Example for creating your own IQHandler for new needs

Example for CustomIQHandler

If you need some new type of IQ request to handle. This may be beficial to you.

I need a IQ request for Importing Roster from my earlier system. So I made a IQ request for that. Client send this request and In response of it Sever imports his RosterItem from other system to Openfire. If some needs such type new request.This example help you

For handling a new IQ request according to ours needs we have to make a class which extends IQHandler. We have to implement ‘IQ handleIQ(IQ packet)’ and ‘IQHandlerInfo getInfo()’ according to ours needs.

import org.jivesoftware.openfire.IQHandlerInfo;

import org.jivesoftware.openfire.auth.UnauthorizedException;

import org.jivesoftware.openfire.handler.IQHandler;

import org.xmpp.packet.IQ;

import org.xmpp.packet.PacketError;

public class MyCustomIQHandler extends IQHandler {

private IQHandlerInfo info;

public MyCustomIQHandler() {

super(“My Custom IQ Handler”);

info= new IQHandlerInfo(“query”,“custom:iq:example”);

}

@Override

public IQHandlerInfo getInfo() {

return info;

}

@Override

public IQ handleIQ(IQ packet) throws UnauthorizedException {

IQ result = IQ.createResultIQ(packet);

IQ.Type type = packet.getType();

if (type.equals(IQ.Type.get)) {

result.setChildElement(“query”, “custom:iq:example”);

//Do stuff you according to get and return the query result by adding to result

}

else if(type.equals(IQ.Type.set))

{

result.setChildElement(“query”, “custom:iq:example”);

//Do stuff you according to set and return the query result by adding to result

}

else{

result.setChildElement(packet.getChildElement().createCopy());

result.setError(PacketError.Condition.not_acceptable);

}

return result;

}

}

After creating this Class we also need to load in XMPPServer class’s loadModules() method. like

loadModule(MyCustomIQHandler.class.getName());

And now you customHandler is ready for handling this type of IQRequests.

1 Like

In order to activate your custom iq handler you can also implement a plugin interface and in initializePlugin() write:

IQHandler accessCodeIQ = new AccessCodeSubmissionHandler();

IQRouter iqRouter = XMPPServer.getInstance().getIQRouter();

iqRouter.addHandler(accessCodeIQ);

where AccessCodeSubmissionHandler() is the constructor for your IQHandler implementation

Hi,does the iqhandler have the order sensitively?