Search in sources :

Example 6 with Form

use of org.jivesoftware.smackx.Form in project Smack by igniterealtime.

the class MultiUserChatTest method testReservedNickname.

public void testReservedNickname() {
    try {
        MultiUserChat muc2 = new MultiUserChat(getConnection(1), room);
        // Check that user2 doesn't have a reserved nickname yet
        String reservedNickname = muc2.getReservedNickname();
        assertNull("Reserved nickname is not null", reservedNickname);
        // User2 registers with the room and reserves a nickname
        Form registrationForm = muc2.getRegistrationForm();
        Form answerForm = registrationForm.createAnswerForm();
        answerForm.setAnswer("muc#register_first", "MyFirstName");
        answerForm.setAnswer("muc#register_last", "MyLastName");
        answerForm.setAnswer("muc#register_roomnick", "MyNick");
        muc2.sendRegistrationForm(answerForm);
        // Check that user2 has a reserved nickname
        reservedNickname = muc2.getReservedNickname();
        assertEquals("Reserved nickname is wrong", "MyNick", reservedNickname);
        // Check that user2 can join the room using his reserved nickname
        muc2.join("MyNick");
        muc2.leave();
        // Check that other users cannot join the room with user2's reserved nickname
        MultiUserChat muc3 = new MultiUserChat(getConnection(2), room);
        try {
            muc3.join("MyNick");
            fail("Other user was able to join with other user's reserved nickname");
        } catch (XMPPException e) {
            XMPPError xmppError = e.getStanzaError();
            assertNotNull("No XMPPError was received when joining with other user's reserved nickname", xmppError);
            assertEquals("Different error code was received while joining with other user's reserved nickname", 409, xmppError.getCode());
        }
        // Check that user3 can join the room using his own nickname (not reserved)
        muc3.join("MyNotReservedNick");
        muc3.leave();
        // Check that another user cannot reserve an already reserved nickname
        registrationForm = muc3.getRegistrationForm();
        answerForm = registrationForm.createAnswerForm();
        answerForm.setAnswer("muc#register_first", "MyFirstName 2");
        answerForm.setAnswer("muc#register_last", "MyLastName 2");
        answerForm.setAnswer("muc#register_roomnick", "MyNick");
        try {
            muc3.sendRegistrationForm(answerForm);
        } catch (XMPPException e) {
            XMPPError xmppError = e.getStanzaError();
            assertNotNull("No XMPPError was received when reserving an already reserved nickname", xmppError);
            assertEquals("Different error code was received while reserving an already reserved nickname", 409, xmppError.getCode());
        }
        // Check that another user can reserve a new nickname
        registrationForm = muc3.getRegistrationForm();
        answerForm = registrationForm.createAnswerForm();
        answerForm.setAnswer("muc#register_first", "MyFirstName 2");
        answerForm.setAnswer("muc#register_last", "MyLastName 2");
        answerForm.setAnswer("muc#register_roomnick", "MyNick 2");
        muc3.sendRegistrationForm(answerForm);
    } catch (XMPPException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
Also used : Form(org.jivesoftware.smackx.Form) XMPPError(org.jivesoftware.smack.packet.XMPPError) XMPPException(org.jivesoftware.smack.XMPPException)

Example 7 with Form

use of org.jivesoftware.smackx.Form in project Smack by igniterealtime.

the class MultiUserChatCreationTest method testCreateInstantRoom.

/**
 * Tests creating a new "Instant Room".
 */
public void testCreateInstantRoom() {
    MultiUserChat muc = new MultiUserChat(getConnection(0), room);
    try {
        // Create the room
        muc.create("testbot");
        // Send an empty room configuration form which indicates that we want
        // an instant room
        muc.sendConfigurationForm(new Form(Form.TYPE_SUBMIT));
        // Destroy the new room
        muc.destroy("The room has almost no activity...", null);
    } catch (XMPPException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
Also used : Form(org.jivesoftware.smackx.Form) XMPPException(org.jivesoftware.smack.XMPPException)

Example 8 with Form

use of org.jivesoftware.smackx.Form in project Smack by igniterealtime.

the class AdHocCommandDiscoTest method testAdHocCommands.

public void testAdHocCommands() {
    try {
        AdHocCommandManager manager1 = AdHocCommandManager.getAddHocCommandsManager(getConnection(0));
        manager1.registerCommand("test", "test node", LocalCommand.class);
        manager1.registerCommand("test2", "test node", new LocalCommandFactory() {

            public LocalCommand getInstance() throws InstantiationException, IllegalAccessException {
                return new LocalCommand() {

                    public boolean isLastStage() {
                        return true;
                    }

                    public boolean hasPermission(String jid) {
                        return true;
                    }

                    public void execute() throws XMPPException {
                        Form result = new Form(Form.TYPE_RESULT);
                        FormField resultField = new FormField("test2");
                        resultField.setLabel("test node");
                        resultField.addValue("it worked");
                        result.addField(resultField);
                        setForm(result);
                    }

                    public void next(Form response) throws XMPPException {
                    // 
                    }

                    public void complete(Form response) throws XMPPException {
                    // 
                    }

                    public void prev() throws XMPPException {
                    // 
                    }

                    public void cancel() throws XMPPException {
                    // 
                    }
                };
            }
        });
        AdHocCommandManager manager2 = AdHocCommandManager.getAddHocCommandsManager(getConnection(1));
        DiscoverItems items = manager2.discoverCommands(getFullJID(0));
        assertTrue("Disco for command test failed", items.getItems().next().getNode().equals("test"));
        RemoteCommand command = manager2.getRemoteCommand(getFullJID(0), "test2");
        command.execute();
        assertEquals("Disco for command test failed", command.getForm().getField("test2").getValues().next(), "it worked");
    } catch (Exception e) {
        fail(e.getMessage());
    }
}
Also used : Form(org.jivesoftware.smackx.Form) DiscoverItems(org.jivesoftware.smackx.packet.DiscoverItems) XMPPException(org.jivesoftware.smack.XMPPException) FormField(org.jivesoftware.smackx.FormField) XMPPException(org.jivesoftware.smack.XMPPException)

Example 9 with Form

use of org.jivesoftware.smackx.Form in project Smack by igniterealtime.

the class MultiUserChatTest method setUp.

protected void setUp() throws Exception {
    // SmackConfiguration.DEBUG = false;
    super.setUp();
    room = "fruta124@" + getMUCDomain();
    try {
        // User1 creates the room
        muc = new MultiUserChat(getConnection(0), room);
        muc.create("testbot");
        // User1 sends an empty room configuration form which indicates that we want
        // an instant room
        Form form = new Form(Form.TYPE_SUBMIT);
        FormField field = new FormField("muc#roomconfig_whois");
        field.setType("list-single");
        form.addField(field);
        form.setAnswer("muc#roomconfig_whois", Arrays.asList("moderators"));
        muc.sendConfigurationForm(form);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
Also used : Form(org.jivesoftware.smackx.Form) FormField(org.jivesoftware.smackx.FormField) XMPPException(org.jivesoftware.smack.XMPPException)

Example 10 with Form

use of org.jivesoftware.smackx.Form in project ecf by eclipse.

the class AdHocCommandManager method processAdHocCommand.

/**
 * Process the AdHoc-Command packet that request the execution of some
 * action of a command. If this is the first request, this method checks,
 * before executing the command, if:
 * <ul>
 *  <li>The requested command exists</li>
 *  <li>The requester has permissions to execute it</li>
 *  <li>The command has more than one stage, if so, it saves the command and
 *      session ID for further use</li>
 * </ul>
 *
 * <br>
 * <br>
 * If this is not the first request, this method checks, before executing
 * the command, if:
 * <ul>
 *  <li>The session ID of the request was stored</li>
 *  <li>The session life do not exceed the time out</li>
 *  <li>The action to execute is one of the available actions</li>
 * </ul>
 *
 * @param requestData
 *            the packet to process.
 */
private void processAdHocCommand(AdHocCommandData requestData) {
    // Only process requests of type SET
    if (requestData.getType() != IQ.Type.SET) {
        return;
    }
    // Creates the response with the corresponding data
    AdHocCommandData response = new AdHocCommandData();
    response.setTo(requestData.getFrom());
    response.setPacketID(requestData.getPacketID());
    response.setNode(requestData.getNode());
    response.setId(requestData.getTo());
    String sessionId = requestData.getSessionID();
    String commandNode = requestData.getNode();
    if (sessionId == null) {
        // command exists
        if (!commands.containsKey(commandNode)) {
            // Requested command does not exist so return
            // item_not_found error.
            respondError(response, XMPPError.Condition.item_not_found);
            return;
        }
        // Create new session ID
        sessionId = StringUtils.randomString(15);
        try {
            // Create a new instance of the command with the
            // corresponding sessioid
            LocalCommand command = newInstanceOfCmd(commandNode, sessionId);
            response.setType(IQ.Type.RESULT);
            command.setData(response);
            // enough to execute the requested command
            if (!command.hasPermission(requestData.getFrom())) {
                respondError(response, XMPPError.Condition.forbidden);
                return;
            }
            Action action = requestData.getAction();
            // If the action is unknown then respond an error.
            if (action != null && action.equals(Action.unknown)) {
                respondError(response, XMPPError.Condition.bad_request, AdHocCommand.SpecificErrorCondition.malformedAction);
                return;
            }
            // If the action is not execute, then it is an invalid action.
            if (action != null && !action.equals(Action.execute)) {
                respondError(response, XMPPError.Condition.bad_request, AdHocCommand.SpecificErrorCondition.badAction);
                return;
            }
            // Increase the state number, so the command knows in witch
            // stage it is
            command.incrementStage();
            // Executes the command
            command.execute();
            if (command.isLastStage()) {
                // If there is only one stage then the command is completed
                response.setStatus(Status.completed);
            } else {
                // Else it is still executing, and is registered to be
                // available for the next call
                response.setStatus(Status.executing);
                executingCommands.put(sessionId, command);
                // See if the session reaping thread is started. If not, start it.
                if (sessionsSweeper == null) {
                    sessionsSweeper = new Thread(new Runnable() {

                        public void run() {
                            while (true) {
                                for (String sessionId : executingCommands.keySet()) {
                                    LocalCommand command = executingCommands.get(sessionId);
                                    // map.
                                    if (command != null) {
                                        long creationStamp = command.getCreationDate();
                                        // invalid session error and not a time out error.
                                        if (System.currentTimeMillis() - creationStamp > SESSION_TIMEOUT * 1000 * 2) {
                                            // Remove the expired session
                                            executingCommands.remove(sessionId);
                                        }
                                    }
                                }
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException ie) {
                                // Ignore.
                                }
                            }
                        }
                    });
                    sessionsSweeper.setDaemon(true);
                    sessionsSweeper.start();
                }
            }
            // Sends the response packet
            connection.sendPacket(response);
        } catch (XMPPException e) {
            // If there is an exception caused by the next, complete,
            // prev or cancel method, then that error is returned to the
            // requester.
            XMPPError error = e.getXMPPError();
            // command be removed from the executing list.
            if (XMPPError.Type.CANCEL.equals(error.getType())) {
                response.setStatus(Status.canceled);
                executingCommands.remove(sessionId);
            }
            respondError(response, error);
            e.printStackTrace();
        }
    } else {
        LocalCommand command = executingCommands.get(sessionId);
        // of getting the key and the value of the map.
        if (command == null) {
            respondError(response, XMPPError.Condition.bad_request, AdHocCommand.SpecificErrorCondition.badSessionid);
            return;
        }
        // Check if the Session data has expired (default is 10 minutes)
        long creationStamp = command.getCreationDate();
        if (System.currentTimeMillis() - creationStamp > SESSION_TIMEOUT * 1000) {
            // Remove the expired session
            executingCommands.remove(sessionId);
            // Answer a not_allowed error (session-expired)
            respondError(response, XMPPError.Condition.not_allowed, AdHocCommand.SpecificErrorCondition.sessionExpired);
            return;
        }
        /*
             * Since the requester could send two requests for the same
             * executing command i.e. the same session id, all the execution of
             * the action must be synchronized to avoid inconsistencies.
             */
        synchronized (command) {
            Action action = requestData.getAction();
            // If the action is unknown the respond an error
            if (action != null && action.equals(Action.unknown)) {
                respondError(response, XMPPError.Condition.bad_request, AdHocCommand.SpecificErrorCondition.malformedAction);
                return;
            }
            // action then follow the actual default execute action
            if (action == null || Action.execute.equals(action)) {
                action = command.getExecuteAction();
            }
            // offered
            if (!command.isValidAction(action)) {
                respondError(response, XMPPError.Condition.bad_request, AdHocCommand.SpecificErrorCondition.badAction);
                return;
            }
            try {
                // TODO: Check that all the requierd fields of the form are
                // TODO: filled, if not throw an exception. This will simplify the
                // TODO: construction of new commands
                // Since all errors were passed, the response is now a
                // result
                response.setType(IQ.Type.RESULT);
                // Set the new data to the command.
                command.setData(response);
                if (Action.next.equals(action)) {
                    command.incrementStage();
                    command.next(new Form(requestData.getForm()));
                    if (command.isLastStage()) {
                        // If it is the last stage then the command is
                        // completed
                        response.setStatus(Status.completed);
                    } else {
                        // Otherwise it is still executing
                        response.setStatus(Status.executing);
                    }
                } else if (Action.complete.equals(action)) {
                    command.incrementStage();
                    command.complete(new Form(requestData.getForm()));
                    response.setStatus(Status.completed);
                    // Remove the completed session
                    executingCommands.remove(sessionId);
                } else if (Action.prev.equals(action)) {
                    command.decrementStage();
                    command.prev();
                } else if (Action.cancel.equals(action)) {
                    command.cancel();
                    response.setStatus(Status.canceled);
                    // Remove the canceled session
                    executingCommands.remove(sessionId);
                }
                connection.sendPacket(response);
            } catch (XMPPException e) {
                // If there is an exception caused by the next, complete,
                // prev or cancel method, then that error is returned to the
                // requester.
                XMPPError error = e.getXMPPError();
                // command be removed from the executing list.
                if (XMPPError.Type.CANCEL.equals(error.getType())) {
                    response.setStatus(Status.canceled);
                    executingCommands.remove(sessionId);
                }
                respondError(response, error);
                e.printStackTrace();
            }
        }
    }
}
Also used : Action(org.jivesoftware.smackx.commands.AdHocCommand.Action) Form(org.jivesoftware.smackx.Form) AdHocCommandData(org.jivesoftware.smackx.packet.AdHocCommandData) XMPPError(org.jivesoftware.smack.packet.XMPPError)

Aggregations

Form (org.jivesoftware.smackx.Form)11 XMPPException (org.jivesoftware.smack.XMPPException)7 FormField (org.jivesoftware.smackx.FormField)4 ArrayList (java.util.ArrayList)2 XMPPError (org.jivesoftware.smack.packet.XMPPError)2 URISyntaxException (java.net.URISyntaxException)1 Iterator (java.util.Iterator)1 List (java.util.List)1 ECFException (org.eclipse.ecf.core.util.ECFException)1 ChatRoomCreateException (org.eclipse.ecf.presence.chatroom.ChatRoomCreateException)1 IChatRoomInfo (org.eclipse.ecf.presence.chatroom.IChatRoomInfo)1 ICriterion (org.eclipse.ecf.presence.search.ICriterion)1 IResultList (org.eclipse.ecf.presence.search.IResultList)1 ResultList (org.eclipse.ecf.presence.search.ResultList)1 UserSearchException (org.eclipse.ecf.presence.search.UserSearchException)1 XMPPRoomID (org.eclipse.ecf.provider.xmpp.identity.XMPPRoomID)1 ReportedData (org.jivesoftware.smackx.ReportedData)1 Action (org.jivesoftware.smackx.commands.AdHocCommand.Action)1 MultiUserChat (org.jivesoftware.smackx.muc.MultiUserChat)1 RoomInfo (org.jivesoftware.smackx.muc.RoomInfo)1