In openfire, I am trying to create a bot which will be deployed in openfire as a plugin. So, the bot will login using smack connection with a username botA. I wanted to listen the messages from 1 to 1 and muc for the logged in user(botA) but if I use stanza listener I am not getting any messages. How can I able to listen all messages for the user(botA).
Below is the code which I am using:
//XmppChatManager .class
public class XmppChatManager extends AbstractXMPPConnection implements InvitationListener{
private static final ConcurrentHashMap<String, XmppChatManager> connections = new ConcurrentHashMap<>();
private static final List<Subscription> subscriptions = new ConcurrentGroupList<>();
private static final ConcurrentHashMap<String, XmppChatManager> users = new ConcurrentHashMap<>();
private static final String domain = XMPPServer.getInstance().getServerInfo().getXMPPDomain();
private static final String hostname = XMPPServer.getInstance().getServerInfo().getHostname();
public boolean anonymous = false;
public ConcurrentHashMap<String, Chat> chats;
private LocalClientSession session;
private SmackConnection smackConnection;
public OpenfireConfiguration config;
public MultiUserChatManager mucManager;
public ConcurrentHashMap<String, MultiUserChat> groupchats;
public XmppChatManager(OpenfireConfiguration configuration) {
super(configuration);
config = configuration;
user = getUserJid();
}
public static XmppChatManager createConnection(String username, String password, boolean anonymous)
{
OpenfireConfiguration config = OpenfireConfiguration.builder()
.setUsernameAndPassword(username, password)
.setXmppDomain(domain)
.setResource(username + (new Random(new Date().getTime()).nextInt()))
.setHost(hostname)
.setPort(0)
.enableDefaultDebugger()
.setSendPresence(true)
.build();
connection = new XmppChatManager(config);
connection.anonymous = false;
connection.connect();
connection.login();
Presence presence = new Presence(Presence.Type.available);
connection.sendStanza(presence);
final XmppChatManager conn=connection;
connection.stanzaListener = new StanzaListener()
{
public void processStanza(Stanza packet) {
conn.processMessageStanza(packet);//
}
};
connection.addAsyncStanzaListener(connection.stanzaListener, new PacketTypeFilter(Message.class));
connections.put(connection.getStreamId(), connection);
return connection;
}
@Override
protected void connectInternal() throws SmackException, IOException, XMPPException, InterruptedException {
Log.debug("connectInternal " + config.getUsername());
streamId = "botuser" + new Random(new Date().getTime()).nextInt();
smackConnection = new SmackConnection(streamId, this);
connected = true;
saslFeatureReceived.reportSuccess();
tlsHandled.reportSuccess();
}
private EntityFullJid getUserJid()
{
try {
return JidCreate.entityFullFrom(config.getUsername() + "@" + config.getXMPPServiceDomain() + "/" + config.getResource());
}
catch (XmppStringprepException e) {
throw new IllegalStateException(e);
}
}
@Override
protected void loginInternal(String username, String password, Resourcepart resource) throws XMPPException
{
Log.info("loginInternal "+user);
try {
AuthToken authToken = null;
if (username == null || password == null || "".equals(username) || "".equals(password))
{
String user = resource.toString();
if (username != null && !"".equals(username)) user = username;
authToken = new AuthToken(user, anonymous);
} else {
username = username.toLowerCase().trim();
user = getUserJid();
JID userJid = XMPPServer.getInstance().createJID(username, null);
session = (LocalClientSession) SessionManager.getInstance().getSession(userJid);
if (session != null)
{
session.close();
SessionManager.getInstance().removeSession(session);
}
try {
authToken = AuthFactory.authenticate( username, password );
} catch ( UnauthorizedException e ) {
authToken = new AuthToken(resource.toString(), true);
}
}
session = SessionManager.getInstance().createClientSession( smackConnection, (Locale) null );
smackConnection.setRouter( new SessionPacketRouter( session ) );
session.setAuthToken(authToken, resource.toString());
authenticated = true;
afterSuccessfulLogin(false);
} catch (Exception e) {
Log.error("loginInternal", e);
}
}
public static XmppChatManager removeConnection(String streamId) throws SmackException
{
XmppChatManager connection = connections.remove(streamId);
if (connection != null)
{
users.remove(connection.getUsername());
connection.disconnect(new Presence(Presence.Type.unavailable));
}
return connection;
}
@Override
protected void shutdown() {
Log.debug("shutdown " + config.getUsername());
user = null;
authenticated = false;
try {
JID userJid = XMPPServer.getInstance().createJID(getUsername(), config.getResource().toString());
session = (LocalClientSession) SessionManager.getInstance().getSession(userJid);
if (session != null)
{
session.close();
SessionManager.getInstance().removeSession(session);
}
} catch (Exception e) {
Log.error("shutdown", e);
}
}
public String getUsername()
{
return config.getUsername().toString();
}
// -------------------------------------------------------
//
// SmackConnection
//
// -------------------------------------------------------
public class SmackConnection extends VirtualConnection
{
private SessionPacketRouter router;
private String remoteAddr;
private String hostName;
private LocalClientSession session;
private boolean isSecure = false;
private XmppChatManager connection;
public SmackConnection(String hostName, XmppChatManager connection)
{
this.remoteAddr = hostName;
this.hostName = hostName;
this.connection = connection;
}
public void setConnection(XmppChatManager connection) {
this.connection = connection;
}
public boolean isSecure() {
return isSecure;
}
public void setSecure(boolean isSecure) {
this.isSecure = isSecure;
}
public SessionPacketRouter getRouter()
{
return router;
}
public void setRouter(SessionPacketRouter router)
{
this.router = router;
}
public void closeVirtualConnection()
{
Log.debug("SmackConnection - close ");
if (this.connection!= null) this.connection.shutdown();
}
public byte[] getAddress() {
return remoteAddr.getBytes();
}
public String getHostAddress() {
return remoteAddr;
}
public String getHostName() {
return ( hostName != null ) ? hostName : "0.0.0.0";
}
public void systemShutdown() {
}
public void deliver(org.xmpp.packet.Packet packet) throws UnauthorizedException
{
deliverRawText(packet.toXML());
}
public void deliverRawText(String text)
{
int pos = text.indexOf("<message ");
if (pos > -1)
{
text = text.substring(0, pos + 9) + "xmlns=\"jabber:client\"" + text.substring(pos + 8);
}
Log.debug("SmackConnection - deliverRawText\n" + text);
// if (clientServlet != null)
// {
// clientServlet.broadcast("chatapi.xmpp", "{\"xmpp\": \"" + DatatypeConverter.printBase64Binary(text.getBytes()) + "\"}");
// }
Stanza stanza = connection.handleParser(text);
if (stanza != null)
{
processMessageStanza(stanza);
}
}
@Override
public org.jivesoftware.openfire.spi.ConnectionConfiguration getConfiguration()
{
return null;
}
public Certificate[] getPeerCertificates() {
return null;
}
}
}
public class ExamplePlugin implements Plugin , PropertyEventListener
{
//private static final Logger Log = LoggerFactory.getLogger( ExamplePlugin.class );
@Override
public void initializePlugin( PluginManager manager, File pluginDirectory )
{
String username="botA";
String password="123456";
try {
XmppChatManager conn=XmppChatManager.createConnection(username, password, false);
if (conn== null)
{
Log.info("COnnection is NULLL::::::::::");
}
} catch (Exception e) {
Log.error("Exception occuered::",e);
}
}
@Override
public void destroyPlugin()
{
Log.info("Destroying Example Plugin");
}
}