Search in sources :

Example 11 with StanzaError

use of org.jivesoftware.smack.packet.StanzaError in project Smack by igniterealtime.

the class CommandsProviderTest method parseErrorWithRequest.

@Test
public void parseErrorWithRequest() throws Exception {
    final String errorWithRequest = "<iq id='sid' type='error' from='from@example.com' to='to@example.com'>" + "<command xmlns='http://jabber.org/protocol/commands' node='http://example.com' action='execute'>" + "</command>" + "<error type='cancel'>" + "<bad-request xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>" + "</error>" + "</iq>";
    final Stanza requestStanza = PacketParserUtils.parseStanza(errorWithRequest);
    final AdHocCommandData adHocIq = (AdHocCommandData) requestStanza;
    assertEquals(IQ.Type.error, adHocIq.getType());
    assertEquals(AdHocCommand.Action.execute, adHocIq.getAction());
    StanzaError error = adHocIq.getError();
    assertEquals(StanzaError.Type.CANCEL, error.getType());
    assertEquals(StanzaError.Condition.bad_request, error.getCondition());
}
Also used : Stanza(org.jivesoftware.smack.packet.Stanza) AdHocCommandData(org.jivesoftware.smackx.commands.packet.AdHocCommandData) StanzaError(org.jivesoftware.smack.packet.StanzaError) Test(org.junit.jupiter.api.Test)

Example 12 with StanzaError

use of org.jivesoftware.smack.packet.StanzaError in project Smack by igniterealtime.

the class JingleSession method createJingleError.

// Packet and error creation
/**
 * Complete and send an error. Complete all the null fields in an IQ error
 * response, using the session information we have or some info from the
 * incoming packet.
 *
 * @param iq
 *            The Jingle stanza we are responding to
 * @param jingleError
 *            the IQ stanza we want to complete and send
 * @return the jingle error IQ.
 */
public IQ createJingleError(IQ iq, JingleError jingleError) {
    IQ errorPacket = null;
    if (jingleError != null) {
        // TODO This is wrong according to XEP-166 ยง 10, but this jingle implementation is deprecated anyways
        StanzaError builder = StanzaError.getBuilder().setCondition(StanzaError.Condition.undefined_condition).addExtension(jingleError).build();
        errorPacket = IQ.createErrorResponse(iq, builder);
        // errorPacket.addExtension(jingleError);
        // NO! Let the normal state machinery do all of the sending.
        // getConnection().sendStanza(perror);
        LOGGER.severe("Error sent: " + errorPacket.toXML());
    }
    return errorPacket;
}
Also used : IQ(org.jivesoftware.smack.packet.IQ) StanzaError(org.jivesoftware.smack.packet.StanzaError)

Example 13 with StanzaError

use of org.jivesoftware.smack.packet.StanzaError in project Smack by igniterealtime.

the class AdHocCommandManager method processAdHocCommand.

/**
 * Process the AdHoc-Command stanza 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 TODO javadoc me please
 *            the stanza to process.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws NoResponseException if there was no response from the remote entity.
 * @throws InterruptedException if the calling thread was interrupted.
 */
private IQ processAdHocCommand(AdHocCommandData requestData) throws NoResponseException, NotConnectedException, InterruptedException {
    // Creates the response with the corresponding data
    AdHocCommandData response = new AdHocCommandData();
    response.setTo(requestData.getFrom());
    response.setStanzaId(requestData.getStanzaId());
    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)) {
            // item_not_found error.
            return respondError(response, StanzaError.Condition.item_not_found);
        }
        // Create new session ID
        sessionId = StringUtils.randomString(15);
        try {
            // Create a new instance of the command with the
            // corresponding sessionid
            LocalCommand command;
            try {
                command = newInstanceOfCmd(commandNode, sessionId);
            } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
                StanzaError xmppError = StanzaError.getBuilder().setCondition(StanzaError.Condition.internal_server_error).setDescriptiveEnText(e.getMessage()).build();
                return respondError(response, xmppError);
            }
            response.setType(IQ.Type.result);
            command.setData(response);
            // enough to execute the requested command
            if (!command.hasPermission(requestData.getFrom())) {
                return respondError(response, StanzaError.Condition.forbidden);
            }
            Action action = requestData.getAction();
            // If the action is unknown then respond an error.
            if (action != null && action.equals(Action.unknown)) {
                return respondError(response, StanzaError.Condition.bad_request, AdHocCommand.SpecificErrorCondition.malformedAction);
            }
            // If the action is not execute, then it is an invalid action.
            if (action != null && !action.equals(Action.execute)) {
                return respondError(response, StanzaError.Condition.bad_request, AdHocCommand.SpecificErrorCondition.badAction);
            }
            // 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 sweeper thread is scheduled. If not, start it.
                maybeWindUpSessionSweeper();
            }
            // Sends the response packet
            return response;
        } catch (XMPPErrorException e) {
            // If there is an exception caused by the next, complete,
            // prev or cancel method, then that error is returned to the
            // requester.
            StanzaError error = e.getStanzaError();
            // command be removed from the executing list.
            if (StanzaError.Type.CANCEL.equals(error.getType())) {
                response.setStatus(Status.canceled);
                executingCommands.remove(sessionId);
            }
            return respondError(response, error);
        }
    } else {
        LocalCommand command = executingCommands.get(sessionId);
        // of getting the key and the value of the map.
        if (command == null) {
            return respondError(response, StanzaError.Condition.bad_request, AdHocCommand.SpecificErrorCondition.badSessionid);
        }
        // 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)
            return respondError(response, StanzaError.Condition.not_allowed, AdHocCommand.SpecificErrorCondition.sessionExpired);
        }
        /*
             * 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)) {
                return respondError(response, StanzaError.Condition.bad_request, AdHocCommand.SpecificErrorCondition.malformedAction);
            }
            // action then follow the actual default execute action
            if (action == null || Action.execute.equals(action)) {
                action = command.getExecuteAction();
            }
            // offered
            if (!command.isValidAction(action)) {
                return respondError(response, StanzaError.Condition.bad_request, AdHocCommand.SpecificErrorCondition.badAction);
            }
            try {
                // TODO: Check that all the required 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();
                    DataForm dataForm = requestData.getForm();
                    command.next(new FillableForm(dataForm));
                    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();
                    DataForm dataForm = requestData.getForm();
                    command.complete(new FillableForm(dataForm));
                    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);
                }
                return response;
            } catch (XMPPErrorException e) {
                // If there is an exception caused by the next, complete,
                // prev or cancel method, then that error is returned to the
                // requester.
                StanzaError error = e.getStanzaError();
                // command be removed from the executing list.
                if (StanzaError.Type.CANCEL.equals(error.getType())) {
                    response.setStatus(Status.canceled);
                    executingCommands.remove(sessionId);
                }
                return respondError(response, error);
            }
        }
    }
}
Also used : Action(org.jivesoftware.smackx.commands.AdHocCommand.Action) XMPPErrorException(org.jivesoftware.smack.XMPPException.XMPPErrorException) FillableForm(org.jivesoftware.smackx.xdata.form.FillableForm) InvocationTargetException(java.lang.reflect.InvocationTargetException) StanzaError(org.jivesoftware.smack.packet.StanzaError) AdHocCommandData(org.jivesoftware.smackx.commands.packet.AdHocCommandData) DataForm(org.jivesoftware.smackx.xdata.packet.DataForm)

Example 14 with StanzaError

use of org.jivesoftware.smack.packet.StanzaError in project Smack by igniterealtime.

the class AdHocCommandDataProvider method parse.

@Override
public AdHocCommandData parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException {
    boolean done = false;
    AdHocCommandData adHocCommandData = new AdHocCommandData();
    DataFormProvider dataFormProvider = new DataFormProvider();
    XmlPullParser.Event eventType;
    String elementName;
    String namespace;
    adHocCommandData.setSessionID(parser.getAttributeValue("", "sessionid"));
    adHocCommandData.setNode(parser.getAttributeValue("", "node"));
    // Status
    String status = parser.getAttributeValue("", "status");
    if (AdHocCommand.Status.executing.toString().equalsIgnoreCase(status)) {
        adHocCommandData.setStatus(AdHocCommand.Status.executing);
    } else if (AdHocCommand.Status.completed.toString().equalsIgnoreCase(status)) {
        adHocCommandData.setStatus(AdHocCommand.Status.completed);
    } else if (AdHocCommand.Status.canceled.toString().equalsIgnoreCase(status)) {
        adHocCommandData.setStatus(AdHocCommand.Status.canceled);
    }
    // Action
    String action = parser.getAttributeValue("", "action");
    if (action != null) {
        Action realAction = AdHocCommand.Action.valueOf(action);
        if (realAction == null || realAction.equals(Action.unknown)) {
            adHocCommandData.setAction(Action.unknown);
        } else {
            adHocCommandData.setAction(realAction);
        }
    }
    while (!done) {
        eventType = parser.next();
        namespace = parser.getNamespace();
        if (eventType == XmlPullParser.Event.START_ELEMENT) {
            elementName = parser.getName();
            if (parser.getName().equals("actions")) {
                String execute = parser.getAttributeValue("", "execute");
                if (execute != null) {
                    adHocCommandData.setExecuteAction(AdHocCommand.Action.valueOf(execute));
                }
            } else if (parser.getName().equals("next")) {
                adHocCommandData.addAction(AdHocCommand.Action.next);
            } else if (parser.getName().equals("complete")) {
                adHocCommandData.addAction(AdHocCommand.Action.complete);
            } else if (parser.getName().equals("prev")) {
                adHocCommandData.addAction(AdHocCommand.Action.prev);
            } else if (elementName.equals("x") && namespace.equals("jabber:x:data")) {
                adHocCommandData.setForm(dataFormProvider.parse(parser));
            } else if (parser.getName().equals("note")) {
                String typeString = parser.getAttributeValue("", "type");
                AdHocCommandNote.Type type;
                if (typeString != null) {
                    type = AdHocCommandNote.Type.valueOf(typeString);
                } else {
                    // Type is optional and 'info' if not present.
                    type = AdHocCommandNote.Type.info;
                }
                String value = parser.nextText();
                adHocCommandData.addNote(new AdHocCommandNote(type, value));
            } else if (parser.getName().equals("error")) {
                StanzaError error = PacketParserUtils.parseError(parser);
                adHocCommandData.setError(error);
            }
        } else if (eventType == XmlPullParser.Event.END_ELEMENT) {
            if (parser.getName().equals("command")) {
                done = true;
            }
        }
    }
    return adHocCommandData;
}
Also used : Action(org.jivesoftware.smackx.commands.AdHocCommand.Action) AdHocCommandNote(org.jivesoftware.smackx.commands.AdHocCommandNote) DataFormProvider(org.jivesoftware.smackx.xdata.provider.DataFormProvider) AdHocCommandData(org.jivesoftware.smackx.commands.packet.AdHocCommandData) XmlPullParser(org.jivesoftware.smack.xml.XmlPullParser) StanzaError(org.jivesoftware.smack.packet.StanzaError)

Example 15 with StanzaError

use of org.jivesoftware.smack.packet.StanzaError in project Smack by igniterealtime.

the class InitiationListener method handleIQRequest.

@Override
public IQ handleIQRequest(final IQ iqRequest) {
    Open ibbRequest = (Open) iqRequest;
    int blockSize = ibbRequest.getBlockSize();
    int maximumBlockSize = manager.getMaximumBlockSize();
    // validate that block size is within allowed range
    if (blockSize > maximumBlockSize) {
        StanzaError error = StanzaError.getBuilder().setCondition(StanzaError.Condition.resource_constraint).setDescriptiveEnText("Requests block size of " + blockSize + " exceeds maximum block size of " + maximumBlockSize).build();
        return IQ.createErrorResponse(iqRequest, error);
    }
    StreamNegotiator.signal(ibbRequest.getFrom().toString() + '\t' + ibbRequest.getSessionID(), ibbRequest);
    // ignore request if in ignore list
    if (this.manager.getIgnoredBytestreamRequests().remove(ibbRequest.getSessionID())) {
        return null;
    }
    // build bytestream request from packet
    InBandBytestreamRequest request = new InBandBytestreamRequest(this.manager, ibbRequest);
    // notify listeners for bytestream initiation from a specific user
    BytestreamListener userListener = this.manager.getUserListener(ibbRequest.getFrom());
    if (userListener != null) {
        userListener.incomingBytestreamRequest(request);
    } else if (!this.manager.getAllRequestListeners().isEmpty()) {
        /*
             * if there is no user specific listener inform listeners for all initiation requests
             */
        for (BytestreamListener listener : this.manager.getAllRequestListeners()) {
            listener.incomingBytestreamRequest(request);
        }
    } else {
        StanzaError error = StanzaError.getBuilder().setCondition(StanzaError.Condition.not_acceptable).setDescriptiveEnText("No file-transfer listeners registered").build();
        return IQ.createErrorResponse(iqRequest, error);
    }
    return null;
}
Also used : BytestreamListener(org.jivesoftware.smackx.bytestreams.BytestreamListener) Open(org.jivesoftware.smackx.bytestreams.ibb.packet.Open) StanzaError(org.jivesoftware.smack.packet.StanzaError)

Aggregations

StanzaError (org.jivesoftware.smack.packet.StanzaError)21 IQ (org.jivesoftware.smack.packet.IQ)7 Test (org.junit.jupiter.api.Test)5 XMPPErrorException (org.jivesoftware.smack.XMPPException.XMPPErrorException)4 ErrorIQ (org.jivesoftware.smack.packet.ErrorIQ)3 XmlEnvironment (org.jivesoftware.smack.packet.XmlEnvironment)3 XmlPullParser (org.jivesoftware.smack.xml.XmlPullParser)3 AdHocCommandData (org.jivesoftware.smackx.commands.packet.AdHocCommandData)3 Failure (org.jivesoftware.smack.compress.packet.Failure)2 EmptyResultIQ (org.jivesoftware.smack.packet.EmptyResultIQ)2 Action (org.jivesoftware.smackx.commands.AdHocCommand.Action)2 Identity (org.jivesoftware.smackx.disco.packet.DiscoverInfo.Identity)2 DiscoverInfoBuilder (org.jivesoftware.smackx.disco.packet.DiscoverInfoBuilder)2 Test (org.junit.Test)2 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 ThreadedDummyConnection (org.jivesoftware.smack.ThreadedDummyConnection)1 XMPPConnection (org.jivesoftware.smack.XMPPConnection)1