powered by Jive Software

Example of passing parameter to an AdHocCommand

We’re using the new AdHocCommands in Smack 3.1.1. I needed to pass a parameter to a RemoteCommand. From the spec (http://xmpp.org/extensions/xep-0050.html) I could see the XML that I needed, but it wasn’t that obvious to me how to use the new Smack API to accomplish this. Here’s psuedo-code for what I got to work.

The basic idea is that the server creates a form with one field in it, and the client code makes two requests - one to get the form, and one to send the completed form.

Here’s the client code:

XMPPConnection con = ...;
        AdHocCommandManager manager = AdHocCommandManager.getAddHocCommandsManager(con);         RemoteCommand command = manager.getRemoteCommand("agent@" + con.getServiceName() + "/siddev", "gatherlogs");
        if ( command.getForm() == null) {
            throw new Exception("Didn't get form back!");
        System.out.println("First response from server: " + command.getRaw());         Form secondForm = command.getForm().createAnswerForm();
        secondForm.setAnswer("myParam", "parameter I want to send");
        System.out.println("Sending form back to Server: " + secondForm.getDataFormToSend().toXML());         command.next(secondForm);         System.out.println("Second response from server: " + command.getRaw());
        System.out.println("Results - [" + command.getNotes().get(0).getValue() + "]");

Here’s a rough idea of the server-side code -

public class GatherLogsCommand extends LocalCommand {    public void execute() throws XMPPException {         Form result = new Form(Form.TYPE_FORM);
        setExecuteAction(Action.next);         FormField resultField = new FormField("myParam");
        resultField.setLabel("Parameter I need to run command");
        result.addField(resultField);         this.addActionAvailable(Action.next);
     }      public void next(Form form) throws XMPPException {
        String myParam = form.getField("myParam").getValues().next();
        // do what you need to
        this.addNote(new AdHocCommandNote(AdHocCommandNote.Type.info, "SUCCESS"));
     }      public boolean isLastStage() {
        return getCurrentStage() == 1;
     }      // rest of methods are stubbed out