diff --git a/smack-experimental/src/main/java/org/jivesoftware/smackx/mam/MamManager.java b/smack-experimental/src/main/java/org/jivesoftware/smackx/mam/MamManager.java index 94dfc2f07c..985ca8b48a 100644 --- a/smack-experimental/src/main/java/org/jivesoftware/smackx/mam/MamManager.java +++ b/smack-experimental/src/main/java/org/jivesoftware/smackx/mam/MamManager.java @@ -1,6 +1,6 @@ /** * - * Copyright © 2017-2020 Florian Schmaus, 2016-2017 Fernando Ramirez + * Copyright © 2017-2023 Florian Schmaus, 2016-2017 Fernando Ramirez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,8 +44,8 @@ import org.jivesoftware.smack.util.Objects; import org.jivesoftware.smack.util.StringUtils; +import org.jivesoftware.smackx.commands.AdHocCommand; import org.jivesoftware.smackx.commands.AdHocCommandManager; -import org.jivesoftware.smackx.commands.RemoteCommand; import org.jivesoftware.smackx.disco.ServiceDiscoveryManager; import org.jivesoftware.smackx.disco.packet.DiscoverInfo; import org.jivesoftware.smackx.disco.packet.DiscoverItems; @@ -233,7 +233,7 @@ private MamManager(XMPPConnection connection, Jid archiveAddress) { super(connection); this.archiveAddress = archiveAddress; serviceDiscoveryManager = ServiceDiscoveryManager.getInstanceFor(connection); - adHocCommandManager = AdHocCommandManager.getAddHocCommandsManager(connection); + adHocCommandManager = AdHocCommandManager.getInstance(connection); } /** @@ -759,7 +759,7 @@ public boolean isAdvancedConfigurationSupported() throws InterruptedException, X return false; } - public RemoteCommand getAdvancedConfigurationCommand() throws InterruptedException, XMPPException, SmackException { + public AdHocCommand getAdvancedConfigurationCommand() throws InterruptedException, XMPPException, SmackException { DiscoverItems discoverItems = adHocCommandManager.discoverCommands(archiveAddress); for (DiscoverItems.Item item : discoverItems.getItems()) { if (item.getNode().equals(ADVANCED_CONFIG_NODE)) diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/admin/ServiceAdministrationManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/admin/ServiceAdministrationManager.java index 78ce687a6a..9956533f74 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/admin/ServiceAdministrationManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/admin/ServiceAdministrationManager.java @@ -1,6 +1,6 @@ /** * - * Copyright 2016-2020 Florian Schmaus + * Copyright 2016-2023 Florian Schmaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,8 +27,9 @@ import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException.XMPPErrorException; +import org.jivesoftware.smackx.commands.AdHocCommand; import org.jivesoftware.smackx.commands.AdHocCommandManager; -import org.jivesoftware.smackx.commands.RemoteCommand; +import org.jivesoftware.smackx.commands.AdHocCommandResult; import org.jivesoftware.smackx.xdata.form.FillableForm; import org.jxmpp.jid.EntityBareJid; @@ -56,37 +57,38 @@ public static synchronized ServiceAdministrationManager getInstanceFor(XMPPConne public ServiceAdministrationManager(XMPPConnection connection) { super(connection); - adHocCommandManager = AdHocCommandManager.getAddHocCommandsManager(connection); + adHocCommandManager = AdHocCommandManager.getInstance(connection); } - public RemoteCommand addUser() { + public AdHocCommand addUser() { return addUser(connection().getXMPPServiceDomain()); } - public RemoteCommand addUser(Jid service) { + public AdHocCommand addUser(Jid service) { return adHocCommandManager.getRemoteCommand(service, COMMAND_NODE_HASHSIGN + "add-user"); } public void addUser(final EntityBareJid userJid, final String password) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { - RemoteCommand command = addUser(); - command.execute(); + AdHocCommand command = addUser(); - FillableForm answerForm = new FillableForm(command.getForm()); + AdHocCommandResult.StatusExecuting commandExecutingResult = command.execute().asExecutingOrThrow(); + + FillableForm answerForm = commandExecutingResult.getFillableForm(); answerForm.setAnswer("accountjid", userJid); answerForm.setAnswer("password", password); answerForm.setAnswer("password-verify", password); - command.execute(answerForm); - assert command.isCompleted(); + AdHocCommandResult result = command.execute(answerForm); + assert result.isCompleted(); } - public RemoteCommand deleteUser() { + public AdHocCommand deleteUser() { return deleteUser(connection().getXMPPServiceDomain()); } - public RemoteCommand deleteUser(Jid service) { + public AdHocCommand deleteUser(Jid service) { return adHocCommandManager.getRemoteCommand(service, COMMAND_NODE_HASHSIGN + "delete-user"); } @@ -98,14 +100,14 @@ public void deleteUser(EntityBareJid userJidToDelete) public void deleteUser(Set jidsToDelete) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { - RemoteCommand command = deleteUser(); - command.execute(); + AdHocCommand command = deleteUser(); + AdHocCommandResult.StatusExecuting commandExecutingResult = command.execute().asExecutingOrThrow(); - FillableForm answerForm = new FillableForm(command.getForm()); + FillableForm answerForm = commandExecutingResult.getFillableForm(); answerForm.setAnswer("accountjids", jidsToDelete); - command.execute(answerForm); - assert command.isCompleted(); + AdHocCommandResult result = command.execute(answerForm); + assert result.isCompleted(); } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AbstractAdHocCommand.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AbstractAdHocCommand.java new file mode 100755 index 0000000000..f67498430e --- /dev/null +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AbstractAdHocCommand.java @@ -0,0 +1,277 @@ +/** + * + * Copyright 2005-2007 Jive Software. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smackx.commands; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import org.jivesoftware.smack.SmackException.NoResponseException; +import org.jivesoftware.smack.SmackException.NotConnectedException; +import org.jivesoftware.smack.XMPPException.XMPPErrorException; +import org.jivesoftware.smack.packet.StanzaError; +import org.jivesoftware.smack.util.StringUtils; +import org.jivesoftware.smackx.commands.packet.AdHocCommandData; +import org.jivesoftware.smackx.commands.packet.AdHocCommandData.Action; +import org.jivesoftware.smackx.commands.packet.AdHocCommandData.AllowedAction; +import org.jivesoftware.smackx.commands.packet.AdHocCommandData.Status; + +/** + * An ad-hoc command is responsible for executing the provided service and + * storing the result of the execution. Each new request will create a new + * instance of the command, allowing information related to executions to be + * stored in it. For example suppose that a command that retrieves the list of + * users on a server is implemented. When the command is executed it gets that + * list and the result is stored as a form in the command instance, i.e. the + * getForm method retrieves a form with all the users. + *

+ * Each command has a node that should be unique within a given JID. + *

+ *

+ * Commands may have zero or more stages. Each stage is usually used for + * gathering information required for the command execution. Users are able to + * move forward or backward across the different stages. Commands may not be + * cancelled while they are being executed. However, users may request the + * "cancel" action when submitting a stage response indicating that the command + * execution should be aborted. Thus, releasing any collected information. + * Commands that require user interaction (i.e. have more than one stage) will + * have to provide the data forms the user must complete in each stage and the + * allowed actions the user might perform during each stage (e.g. go to the + * previous stage or go to the next stage). + *

+ * All the actions may throw an XMPPException if there is a problem executing + * them. The XMPPError of that exception may have some specific + * information about the problem. The possible extensions are: + * + *

+ * See the SpecificErrorCondition class for detailed description + * of each one. + *

+ * Use the getSpecificErrorConditionFrom to obtain the specific + * information from an XMPPError. + * + * @author Gabriel Guardincerri + * @author Florian Schmaus + * + */ +public abstract class AbstractAdHocCommand { + private final List requests = new ArrayList<>(); + private final List results = new ArrayList<>(); + + private final String node; + + private String name; + + /** + * The session ID of this execution. + */ + private String sessionId; + + protected AbstractAdHocCommand(String node, String name) { + this.node = StringUtils.requireNotNullNorEmpty(node, "Ad-Hoc command node must be given"); + this.name = name; + } + + protected AbstractAdHocCommand(String node) { + this(node, null); + } + + void addRequest(AdHocCommandData request) { + requests.add(request); + } + + void addResult(AdHocCommandResult result) { + results.add(result); + } + + /** + * Returns the specific condition of the error or null if the + * error doesn't have any. + * + * @param error the error the get the specific condition from. + * @return the specific condition of this error, or null if it doesn't have + * any. + */ + public static SpecificErrorCondition getSpecificErrorCondition(StanzaError error) { + // This method is implemented to provide an easy way of getting a packet + // extension of the XMPPError. + for (SpecificErrorCondition condition : SpecificErrorCondition.values()) { + if (error.getExtension(condition.toString(), + AdHocCommandData.SpecificError.namespace) != null) { + return condition; + } + } + return null; + } + + /** + * Returns the human readable name of the command. + * + * @return the human readable name of the command + */ + public String getName() { + return name; + } + + /** + * Returns the unique identifier of the command. It is unique for the + * OwnerJID. + * + * @return the unique identifier of the command. + */ + public String getNode() { + return node; + } + + public String getSessionId() { + return sessionId; + } + + protected void setSessionId(String sessionId) { + assert this.sessionId == null || this.sessionId.equals(sessionId); + this.sessionId = StringUtils.requireNotNullNorEmpty(sessionId, "Must provide a session ID"); + } + + public AdHocCommandData getLastRequest() { + if (requests.isEmpty()) return null; + return requests.get(requests.size() - 1); + } + + public AdHocCommandResult getLastResult() { + if (results.isEmpty()) return null; + return results.get(results.size() - 1); + } + + /** + * Returns the notes that the command has at the current stage. + * + * @return a list of notes. + */ + public List getNotes() { + AdHocCommandResult result = getLastResult(); + if (result == null) return null; + + return result.getResponse().getNotes(); + } + + /** + * Cancels the execution of the command. This can be invoked on any stage of + * the execution. If there is a problem executing the command it throws an + * XMPPException. + * + * @throws NoResponseException if there was no response from the remote entity. + * @throws XMPPErrorException if there is a problem executing the command. + * @throws NotConnectedException if the XMPP connection is not connected. + * @throws InterruptedException if the calling thread was interrupted. + */ + public abstract void cancel() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException; + + /** + * Returns a collection with the allowed actions based on the current stage. + * Possible actions are: {@link AllowedAction#prev prev}, {@link AllowedAction#next next} and + * {@link AllowedAction#complete complete}. This method will be only invoked for commands that + * have one or more stages. + * + * @return a collection with the allowed actions based on the current stage + * as defined in the SessionData. + */ + public final Set getActions() { + AdHocCommandResult result = getLastResult(); + if (result == null) return null; + + return result.getResponse().getActions(); + } + + /** + * Returns the action available for the current stage which is + * considered the equivalent to "execute". When the requester sends his + * reply, if no action was defined in the command then the action will be + * assumed "execute" thus assuming the action returned by this method. This + * method will never be invoked for commands that have no stages. + * + * @return the action available for the current stage which is considered + * the equivalent to "execute". + */ + protected AllowedAction getExecuteAction() { + AdHocCommandResult result = getLastResult(); + if (result == null) return null; + + return result.getResponse().getExecuteAction(); + } + + /** + * Returns the status of the current stage. + * + * @return the current status. + */ + public Status getStatus() { + AdHocCommandResult result = getLastResult(); + if (result == null) return null; + + return result.getResponse().getStatus(); + } + + /** + * Check if this command has been completed successfully. + * + * @return true if this command is completed. + * @since 4.2 + */ + public boolean isCompleted() { + return getStatus() == AdHocCommandData.Status.completed; + } + + /** + * Returns true if the action is available in the current stage. + * The {@link Action#cancel cancel} action is always allowed. To define the + * available actions use the addActionAvailable method. + * + * @param action The action to check if it is available. + * @return True if the action is available for the current stage. + */ + public final boolean isValidAction(Action action) { + if (action == Action.cancel) { + return true; + } + + final AllowedAction executeAction; + if (action == Action.execute) { + AdHocCommandResult result = getLastResult(); + executeAction = result.getResponse().getExecuteAction(); + + // This is basically the case that was clarified with + // https://github.com/xsf/xeps/commit/fdaee2da8ffd34b5b5151e90ef1df8b396a06531 and + // https://github.com/xsf/xeps/pull/591. + if (executeAction == null) { + return false; + } + } else { + executeAction = action.allowedAction; + assert executeAction != null; + } + + Set actions = getActions(); + return actions != null && actions.contains(executeAction); + } +} diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommand.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommand.java index 347c08f694..0e7fabaaa6 100755 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommand.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommand.java @@ -16,193 +16,68 @@ */ package org.jivesoftware.smackx.commands; -import java.util.List; - import org.jivesoftware.smack.SmackException.NoResponseException; import org.jivesoftware.smack.SmackException.NotConnectedException; +import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException.XMPPErrorException; -import org.jivesoftware.smack.packet.StanzaError; - +import org.jivesoftware.smack.packet.IQ; +import org.jivesoftware.smack.util.Objects; import org.jivesoftware.smackx.commands.packet.AdHocCommandData; import org.jivesoftware.smackx.xdata.form.FillableForm; +import org.jivesoftware.smackx.xdata.form.SubmitForm; import org.jivesoftware.smackx.xdata.packet.DataForm; import org.jxmpp.jid.Jid; /** - * An ad-hoc command is responsible for executing the provided service and - * storing the result of the execution. Each new request will create a new - * instance of the command, allowing information related to executions to be - * stored in it. For example suppose that a command that retrieves the list of - * users on a server is implemented. When the command is executed it gets that - * list and the result is stored as a form in the command instance, i.e. the - * getForm method retrieves a form with all the users. - *

- * Each command has a node that should be unique within a given JID. - *

- *

- * Commands may have zero or more stages. Each stage is usually used for - * gathering information required for the command execution. Users are able to - * move forward or backward across the different stages. Commands may not be - * cancelled while they are being executed. However, users may request the - * "cancel" action when submitting a stage response indicating that the command - * execution should be aborted. Thus, releasing any collected information. - * Commands that require user interaction (i.e. have more than one stage) will - * have to provide the data forms the user must complete in each stage and the - * allowed actions the user might perform during each stage (e.g. go to the - * previous stage or go to the next stage). - *

- * All the actions may throw an XMPPException if there is a problem executing - * them. The XMPPError of that exception may have some specific - * information about the problem. The possible extensions are: - *
    - *
  • malformed-action. Extension of a bad-request error.
  • - *
  • bad-action. Extension of a bad-request error.
  • - *
  • bad-locale. Extension of a bad-request error.
  • - *
  • bad-payload. Extension of a bad-request error.
  • - *
  • bad-sessionid. Extension of a bad-request error.
  • - *
  • session-expired. Extension of a not-allowed error.
  • - *
- *

- * See the SpecificErrorCondition class for detailed description - * of each one. - *

- * Use the getSpecificErrorConditionFrom to obtain the specific - * information from an XMPPError. + * Represents a ad-hoc command invoked on a remote entity. Invoking one of the + * {@link #execute()}, {@link #next(SubmitForm)}, + * {@link #prev()}, {@link #cancel()} or + * {@link #complete(SubmitForm)} actions results in executing that + * action on the remote entity. In response to that action the internal state + * of the this command instance will change. For example, if the command is a + * single stage command, then invoking the execute action will execute this + * action in the remote location. After that the local instance will have a + * state of "completed" and a form or notes that applies. * * @author Gabriel Guardincerri + * @author Florian Schmaus * */ -public abstract class AdHocCommand { - // TODO: Analyze the redesign of command by having an ExecutionResponse as a - // TODO: result to the execution of every action. That result should have all the - // TODO: information related to the execution, e.g. the form to fill. Maybe this - // TODO: design is more intuitive and simpler than the current one that has all in - // TODO: one class. - - private AdHocCommandData data; - - public AdHocCommand() { - super(); - data = new AdHocCommandData(); - } +public class AdHocCommand extends AbstractAdHocCommand { /** - * Returns the specific condition of the error or null if the - * error doesn't have any. - * - * @param error the error the get the specific condition from. - * @return the specific condition of this error, or null if it doesn't have - * any. + * The connection that is used to execute this command */ - public static SpecificErrorCondition getSpecificErrorCondition(StanzaError error) { - // This method is implemented to provide an easy way of getting a packet - // extension of the XMPPError. - for (SpecificErrorCondition condition : SpecificErrorCondition.values()) { - if (error.getExtension(condition.toString(), - AdHocCommandData.SpecificError.namespace) != null) { - return condition; - } - } - return null; - } + private final XMPPConnection connection; /** - * Set the human readable name of the command, usually used for - * displaying in a UI. - * - * @param name the name. + * The full JID of the command host */ - public void setName(String name) { - data.setName(name); - } + private final Jid jid; /** - * Returns the human readable name of the command. + * Creates a new RemoteCommand that uses an specific connection to execute a + * command identified by node in the host identified by + * jid * - * @return the human readable name of the command + * @param connection the connection to use for the execution. + * @param node the identifier of the command. + * @param jid the JID of the host. */ - public String getName() { - return data.getName(); + protected AdHocCommand(XMPPConnection connection, String node, Jid jid) { + super(node); + this.connection = Objects.requireNonNull(connection); + this.jid = Objects.requireNonNull(jid); } - /** - * Sets the unique identifier of the command. This value must be unique for - * the OwnerJID. - * - * @param node the unique identifier of the command. - */ - public void setNode(String node) { - data.setNode(node); + public Jid getOwnerJID() { + return jid; } - /** - * Returns the unique identifier of the command. It is unique for the - * OwnerJID. - * - * @return the unique identifier of the command. - */ - public String getNode() { - return data.getNode(); - } - - /** - * Returns the full JID of the owner of this command. This JID is the "to" of a - * execution request. - * - * @return the owner JID. - */ - public abstract Jid getOwnerJID(); - - /** - * Returns the notes that the command has at the current stage. - * - * @return a list of notes. - */ - public List getNotes() { - return data.getNotes(); - } - - /** - * Adds a note to the current stage. This should be used when setting a - * response to the execution of an action. All the notes added here are - * returned by the {@link #getNotes} method during the current stage. - * Once the stage changes all the notes are discarded. - * - * @param note the note. - */ - protected void addNote(AdHocCommandNote note) { - data.addNote(note); - } - - public String getRaw() { - return data.getChildElementXML().toString(); - } - - /** - * Returns the form of the current stage. Usually it is the form that must - * be answered to execute the next action. If that is the case it should be - * used by the requester to fill all the information that the executor needs - * to continue to the next stage. It can also be the result of the - * execution. - * - * @return the form of the current stage to fill out or the result of the - * execution. - */ - public DataForm getForm() { - return data.getForm(); - } - - /** - * Sets the form of the current stage. This should be used when setting a - * response. It could be a form to fill out the information needed to go to - * the next stage or the result of an execution. - * - * @param form the form of the current stage to fill out or the result of the - * execution. - */ - protected void setForm(DataForm form) { - data.setForm(form); + @Override + public final void cancel() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + executeAction(AdHocCommandData.Action.cancel); } /** @@ -210,12 +85,15 @@ protected void setForm(DataForm form) { * command. It is invoked on every command. If there is a problem executing * the command it throws an XMPPException. * + * @return an ad-hoc command result. * @throws NoResponseException if there was no response from the remote entity. * @throws XMPPErrorException if there is an error executing the command. * @throws NotConnectedException if the XMPP connection is not connected. * @throws InterruptedException if the calling thread was interrupted. */ - public abstract void execute() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException; + public final AdHocCommandResult execute() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + return executeAction(AdHocCommandData.Action.execute); + } /** * Executes the next action of the command with the information provided in @@ -224,13 +102,16 @@ protected void setForm(DataForm form) { * or more stages. If there is a problem executing the command it throws an * XMPPException. * - * @param response the form answer of the previous stage. + * @param filledForm the form answer of the previous stage. + * @return an ad-hoc command result. * @throws NoResponseException if there was no response from the remote entity. * @throws XMPPErrorException if there is a problem executing the command. * @throws NotConnectedException if the XMPP connection is not connected. * @throws InterruptedException if the calling thread was interrupted. */ - public abstract void next(FillableForm response) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException; + public final AdHocCommandResult next(SubmitForm filledForm) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + return executeAction(AdHocCommandData.Action.next, filledForm.getDataForm()); + } /** * Completes the command execution with the information provided in the @@ -239,14 +120,16 @@ protected void setForm(DataForm form) { * or more stages. If there is a problem executing the command it throws an * XMPPException. * - * @param response the form answer of the previous stage. - * + * @param filledForm the form answer of the previous stage. + * @return an ad-hoc command result. * @throws NoResponseException if there was no response from the remote entity. * @throws XMPPErrorException if there is a problem executing the command. * @throws NotConnectedException if the XMPP connection is not connected. * @throws InterruptedException if the calling thread was interrupted. */ - public abstract void complete(FillableForm response) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException; + public AdHocCommandResult complete(SubmitForm filledForm) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + return executeAction(AdHocCommandData.Action.complete, filledForm.getDataForm()); + } /** * Goes to the previous stage. The requester is asking to re-send the @@ -254,224 +137,70 @@ protected void setForm(DataForm form) { * the previous one. If there is a problem executing the command it throws * an XMPPException. * + * @return an ad-hoc command result. * @throws NoResponseException if there was no response from the remote entity. * @throws XMPPErrorException if there is a problem executing the command. * @throws NotConnectedException if the XMPP connection is not connected. * @throws InterruptedException if the calling thread was interrupted. */ - public abstract void prev() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException; + public final AdHocCommandResult prev() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + return executeAction(AdHocCommandData.Action.prev); + } /** - * Cancels the execution of the command. This can be invoked on any stage of - * the execution. If there is a problem executing the command it throws an - * XMPPException. + * Executes the default action of the command with the information provided + * in the Form. This form must be the answer form of the previous stage. If + * there is a problem executing the command it throws an XMPPException. * - * @throws NoResponseException if there was no response from the remote entity. - * @throws XMPPErrorException if there is a problem executing the command. + * @param form the form answer of the previous stage. + * @return an ad-hoc command result. + * @throws XMPPErrorException if an error occurs. + * @throws NoResponseException if there was no response from the server. * @throws NotConnectedException if the XMPP connection is not connected. * @throws InterruptedException if the calling thread was interrupted. */ - public abstract void cancel() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException; - - /** - * Returns a collection with the allowed actions based on the current stage. - * Possible actions are: {@link Action#prev prev}, {@link Action#next next} and - * {@link Action#complete complete}. This method will be only invoked for commands that - * have one or more stages. - * - * @return a collection with the allowed actions based on the current stage - * as defined in the SessionData. - */ - protected List getActions() { - return data.getActions(); - } - - /** - * Add an action to the current stage available actions. This should be used - * when creating a response. - * - * @param action the action. - */ - protected void addActionAvailable(Action action) { - data.addAction(action); - } - - /** - * Returns the action available for the current stage which is - * considered the equivalent to "execute". When the requester sends his - * reply, if no action was defined in the command then the action will be - * assumed "execute" thus assuming the action returned by this method. This - * method will never be invoked for commands that have no stages. - * - * @return the action available for the current stage which is considered - * the equivalent to "execute". - */ - protected Action getExecuteAction() { - return data.getExecuteAction(); + public final AdHocCommandResult execute(FillableForm form) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + return executeAction(AdHocCommandData.Action.execute, form.getDataFormToSubmit()); } - /** - * Sets which of the actions available for the current stage is - * considered the equivalent to "execute". This should be used when setting - * a response. When the requester sends his reply, if no action was defined - * in the command then the action will be assumed "execute" thus assuming - * the action returned by this method. - * - * @param action the action. - */ - protected void setExecuteAction(Action action) { - data.setExecuteAction(action); - } - - /** - * Returns the status of the current stage. - * - * @return the current status. - */ - public Status getStatus() { - return data.getStatus(); + private AdHocCommandResult executeAction(AdHocCommandData.Action action) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + return executeAction(action, null); } /** - * Check if this command has been completed successfully. + * Executes the action with the form. + * The action could be any of the available actions. The form must + * be the answer of the previous stage. It can be null if it is the first stage. * - * @return true if this command is completed. - * @since 4.2 - */ - public boolean isCompleted() { - return getStatus() == Status.completed; - } - - /** - * Sets the data of the current stage. This should not used. - * - * @param data the data. - */ - void setData(AdHocCommandData data) { - this.data = data; - } - - /** - * Gets the data of the current stage. This should not used. - * - * @return the data. - */ - AdHocCommandData getData() { - return data; - } - - /** - * Returns true if the action is available in the current stage. - * The {@link Action#cancel cancel} action is always allowed. To define the - * available actions use the addActionAvailable method. - * - * @param action TODO javadoc me please - * The action to check if it is available. - * @return True if the action is available for the current stage. - */ - protected boolean isValidAction(Action action) { - return getActions().contains(action) || Action.cancel.equals(action); - } - - /** - * The status of the stage in the adhoc command. + * @param action the action to execute. + * @param form the form with the information. + * @throws XMPPErrorException if there is a problem executing the command. + * @throws NoResponseException if there was no response from the server. + * @throws NotConnectedException if the XMPP connection is not connected. + * @throws InterruptedException if the calling thread was interrupted. */ - public enum Status { - - /** - * The command is being executed. - */ - executing, - - /** - * The command has completed. The command session has ended. - */ - completed, - - /** - * The command has been canceled. The command session has ended. - */ - canceled - } - - public enum Action { - - /** - * The command should be executed or continue to be executed. This is - * the default value. - */ - execute, + private synchronized AdHocCommandResult executeAction(AdHocCommandData.Action action, DataForm form) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + AdHocCommandData request = AdHocCommandData.builder(getNode(), connection) + .ofType(IQ.Type.set) + .to(getOwnerJID()) + .setSessionId(getSessionId()) + .setAction(action) + .setForm(form) + .build(); - /** - * The command should be canceled. - */ - cancel, + addRequest(request); - /** - * The command should be digress to the previous stage of execution. - */ - prev, + AdHocCommandData response = connection.sendIqRequestAndWaitForResponse(request); - /** - * The command should progress to the next stage of execution. - */ - next, - - /** - * The command should be completed (if possible). - */ - complete, - - /** - * The action is unknown. This is used when a received message has an - * unknown action. It must not be used to send an execution request. - */ - unknown - } - - public enum SpecificErrorCondition { - - /** - * The responding JID cannot accept the specified action. - */ - badAction("bad-action"), - - /** - * The responding JID does not understand the specified action. - */ - malformedAction("malformed-action"), - - /** - * The responding JID cannot accept the specified language/locale. - */ - badLocale("bad-locale"), - - /** - * The responding JID cannot accept the specified payload (e.g. the data - * form did not provide one or more required fields). - */ - badPayload("bad-payload"), - - /** - * The responding JID cannot accept the specified sessionid. - */ - badSessionid("bad-sessionid"), - - /** - * The requesting JID specified a sessionid that is no longer active - * (either because it was completed, canceled, or timed out). - */ - sessionExpired("session-expired"); - - private final String value; - - SpecificErrorCondition(String value) { - this.value = value; + // The Ad-Hoc service ("server") may have generated a session id for us. + String sessionId = response.getSessionId(); + if (sessionId != null) { + setSessionId(sessionId); } - @Override - public String toString() { - return value; - } + AdHocCommandResult result = AdHocCommandResult.from(response); + addResult(result); + return result; } + } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandHandler.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandHandler.java new file mode 100755 index 0000000000..d4f3704dd4 --- /dev/null +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandHandler.java @@ -0,0 +1,175 @@ +/** + * + * Copyright 2005-2007 Jive Software. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smackx.commands; + +import org.jivesoftware.smack.SmackException.NoResponseException; +import org.jivesoftware.smack.SmackException.NotConnectedException; +import org.jivesoftware.smack.XMPPException.XMPPErrorException; +import org.jivesoftware.smack.packet.StanzaError; +import org.jivesoftware.smackx.commands.packet.AdHocCommandData; +import org.jivesoftware.smackx.commands.packet.AdHocCommandDataBuilder; +import org.jivesoftware.smackx.xdata.form.SubmitForm; + +import org.jxmpp.jid.Jid; + +/** + * Represents a command that can be executed locally from a remote location. This + * class must be extended to implement an specific ad-hoc command. This class + * provides some useful tools:
    + *
  • Node
  • + *
  • Name
  • + *
  • Session ID
  • + *
  • Current Stage
  • + *
  • Available actions
  • + *
  • Default action
  • + *
+ * To implement a new command extend this class and implement all the abstract + * methods. When implementing the actions remember that they could be invoked + * several times, and that you must use the current stage number to know what to + * do. + * + * @author Gabriel Guardincerri + * @author Florian Schmaus + */ +public abstract class AdHocCommandHandler extends AbstractAdHocCommand { + + /** + * The time stamp of first invocation of the command. Used to implement the session timeout. + */ + private final long creationDate; + + /** + * The number of the current stage. + */ + private int currentStage; + + public AdHocCommandHandler(String node, String name, String sessionId) { + super(node, name); + setSessionId(sessionId); + this.creationDate = System.currentTimeMillis(); + } + + protected abstract AdHocCommandData execute(AdHocCommandDataBuilder response) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException; + + protected abstract AdHocCommandData next(AdHocCommandDataBuilder response, SubmitForm submittedForm) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException; + + protected abstract AdHocCommandData complete(AdHocCommandDataBuilder response, SubmitForm submittedForm) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException; + + protected abstract AdHocCommandData prev(AdHocCommandDataBuilder response) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException; + + /** + * Returns the date the command was created. + * + * @return the date the command was created. + */ + public long getCreationDate() { + return creationDate; + } + + /** + * Returns true if the specified requester has permission to execute all the + * stages of this action. This is checked when the first request is received, + * if the permission is grant then the requester will be able to execute + * all the stages of the command. It is not checked again during the + * execution. + * + * @param jid the JID to check permissions on. + * @return true if the user has permission to execute this action. + */ + public boolean hasPermission(Jid jid) { + return true; + }; + + /** + * Returns the currently executing stage number. The first stage number is + * 1. During the execution of the first action this method will answer 1. + * + * @return the current stage number. + */ + public final int getCurrentStage() { + return currentStage; + } + + /** + * Increase the current stage number. + */ + final void incrementStage() { + currentStage++; + } + + /** + * Decrease the current stage number. + */ + final void decrementStage() { + currentStage--; + } + + protected static XMPPErrorException newXmppErrorException(StanzaError.Condition condition) { + return newXmppErrorException(condition, null); + } + + protected static XMPPErrorException newXmppErrorException(StanzaError.Condition condition, String descriptiveText) { + StanzaError stanzaError = StanzaError.from(condition, descriptiveText).build(); + return new XMPPErrorException(null, stanzaError); + } + + protected static XMPPErrorException newBadRequestException(String descriptiveTest) { + return newXmppErrorException(StanzaError.Condition.bad_request, descriptiveTest); + } + + public abstract static class SingleStage extends AdHocCommandHandler { + + public SingleStage(String node, String name, String sessionId) { + super(node, name, sessionId); + } + + protected abstract AdHocCommandData executeSingleStage(AdHocCommandDataBuilder response) + throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException; + + @Override + protected final AdHocCommandData execute(AdHocCommandDataBuilder response) + throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + response.setStatusCompleted(); + return executeSingleStage(response); + } + + @Override + public final AdHocCommandData next(AdHocCommandDataBuilder response, SubmitForm submittedForm) + throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + throw newXmppErrorException(StanzaError.Condition.bad_request); + } + + @Override + public final AdHocCommandData complete(AdHocCommandDataBuilder response, SubmitForm submittedForm) + throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + throw newXmppErrorException(StanzaError.Condition.bad_request); + } + + @Override + public final AdHocCommandData prev(AdHocCommandDataBuilder response) + throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + throw newXmppErrorException(StanzaError.Condition.bad_request); + } + + @Override + public final void cancel() + throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + throw newXmppErrorException(StanzaError.Condition.bad_request); + } + + } +} diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/LocalCommandFactory.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandHandlerFactory.java similarity index 64% rename from smack-extensions/src/main/java/org/jivesoftware/smackx/commands/LocalCommandFactory.java rename to smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandHandlerFactory.java index bc635d72af..1ea08477b1 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/LocalCommandFactory.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandHandlerFactory.java @@ -19,28 +19,31 @@ import java.lang.reflect.InvocationTargetException; /** - * A factory for creating local commands. It's useful in cases where instantiation + * A factory for creating ad-hoc command handlers. It's useful in cases where instantiation * of a command is more complicated than just using the default constructor. For example, * when arguments must be passed into the constructor or when using a dependency injection - * framework. When a LocalCommandFactory isn't used, you can provide the AdHocCommandManager + * framework. When a factory isn't used, you can provide the AdHocCommandManager * a Class object instead. For more details, see - * {@link AdHocCommandManager#registerCommand(String, String, LocalCommandFactory)}. + * {@link AdHocCommandManager#registerCommand(String, String, AdHocCommandHandlerFactory)}. * * @author Matt Tucker */ -public interface LocalCommandFactory { +public interface AdHocCommandHandlerFactory { /** - * Returns an instance of a LocalCommand. + * Returns a new instance of an ad-hoc command handler. * + * @param node the node of the ad-hoc command. + * @param name the name of the ad-hoc command. + * @param sessionId the session ID of the ad-hoc command. * @return a LocalCommand instance. * @throws InstantiationException if creating an instance failed. * @throws IllegalAccessException if creating an instance is not allowed. - * @throws SecurityException if there was a security violation. - * @throws NoSuchMethodException if no such method is declared * @throws InvocationTargetException if a reflection-based method or constructor invocation threw. * @throws IllegalArgumentException if an illegal argument was given. */ - LocalCommand getInstance() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException; + AdHocCommandHandler create(String node, String name, String sessionId) + throws InstantiationException, IllegalAccessException, IllegalArgumentException, + InvocationTargetException; } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandManager.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandManager.java index aaad5c0eec..49bf9c0cdd 100755 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandManager.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandManager.java @@ -17,6 +17,7 @@ package org.jivesoftware.smackx.commands; +import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; @@ -44,16 +45,17 @@ import org.jivesoftware.smack.packet.StanzaError; import org.jivesoftware.smack.util.StringUtils; -import org.jivesoftware.smackx.commands.AdHocCommand.Action; -import org.jivesoftware.smackx.commands.AdHocCommand.Status; import org.jivesoftware.smackx.commands.packet.AdHocCommandData; +import org.jivesoftware.smackx.commands.packet.AdHocCommandData.AllowedAction; +import org.jivesoftware.smackx.commands.packet.AdHocCommandDataBuilder; import org.jivesoftware.smackx.disco.AbstractNodeInformationProvider; import org.jivesoftware.smackx.disco.ServiceDiscoveryManager; import org.jivesoftware.smackx.disco.packet.DiscoverInfo; import org.jivesoftware.smackx.disco.packet.DiscoverItems; -import org.jivesoftware.smackx.xdata.form.FillableForm; +import org.jivesoftware.smackx.xdata.form.SubmitForm; import org.jivesoftware.smackx.xdata.packet.DataForm; +import org.jxmpp.jid.EntityFullJid; import org.jxmpp.jid.Jid; /** @@ -65,6 +67,7 @@ * get an instance of this class. * * @author Gabriel Guardincerri + * @author Florian Schmaus */ public final class AdHocCommandManager extends Manager { public static final String NAMESPACE = "http://jabber.org/protocol/commands"; @@ -74,7 +77,7 @@ public final class AdHocCommandManager extends Manager { /** * The session time out in seconds. */ - private static final int SESSION_TIMEOUT = 2 * 60; + private static int DEFAULT_SESSION_TIMEOUT_SECS = 7 * 60; /** * Map an XMPPConnection with it AdHocCommandManager. This map have a key-value @@ -91,7 +94,7 @@ public final class AdHocCommandManager extends Manager { XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { @Override public void connectionCreated(XMPPConnection connection) { - getAddHocCommandsManager(connection); + getInstance(connection); } }); } @@ -102,8 +105,21 @@ public void connectionCreated(XMPPConnection connection) { * * @param connection the XMPP connection. * @return the AdHocCommandManager associated with the connection. + * @deprecated use {@link #getInstance(XMPPConnection)} instead. */ - public static synchronized AdHocCommandManager getAddHocCommandsManager(XMPPConnection connection) { + @Deprecated + public static AdHocCommandManager getAddHocCommandsManager(XMPPConnection connection) { + return getInstance(connection); + } + + /** + * Returns the AdHocCommandManager related to the + * connection. + * + * @param connection the XMPP connection. + * @return the AdHocCommandManager associated with the connection. + */ + public static synchronized AdHocCommandManager getInstance(XMPPConnection connection) { AdHocCommandManager ahcm = instances.get(connection); if (ahcm == null) { ahcm = new AdHocCommandManager(connection); @@ -117,7 +133,8 @@ public static synchronized AdHocCommandManager getAddHocCommandsManager(XMPPConn * Value=command. Command node matches the node attribute sent by command * requesters. */ - private final Map commands = new ConcurrentHashMap<>(); + // TODO: Change to Map once Smack's minimum Android API level is 24 or higher. + private final ConcurrentHashMap commands = new ConcurrentHashMap<>(); /** * Map a command session ID with the instance LocalCommand. The LocalCommand @@ -125,10 +142,12 @@ public static synchronized AdHocCommandManager getAddHocCommandsManager(XMPPConn * the command execution. Note: Key=session ID, Value=LocalCommand. Session * ID matches the sessionid attribute sent by command responders. */ - private final Map executingCommands = new ConcurrentHashMap<>(); + private final Map executingCommands = new ConcurrentHashMap<>(); private final ServiceDiscoveryManager serviceDiscoveryManager; + private int sessionTimeoutSecs = DEFAULT_SESSION_TIMEOUT_SECS; + private AdHocCommandManager(XMPPConnection connection) { super(connection); this.serviceDiscoveryManager = ServiceDiscoveryManager.getInstanceFor(connection); @@ -148,13 +167,17 @@ private AdHocCommandManager(XMPPConnection connection) { new AbstractNodeInformationProvider() { @Override public List getNodeItems() { - List answer = new ArrayList<>(); - Collection commandsList = getRegisteredCommands(); + Collection commandsList = commands.values(); + + EntityFullJid ourJid = connection().getUser(); + if (ourJid == null) { + LOGGER.warning("Local connection JID not available, can not respond to " + NAMESPACE + " node information"); + return null; + } for (AdHocCommandInfo info : commandsList) { - DiscoverItems.Item item = new DiscoverItems.Item( - info.getOwnerJID()); + DiscoverItems.Item item = new DiscoverItems.Item(ourJid); item.setName(info.getName()); item.setNode(info.getNode()); answer.add(item); @@ -166,18 +189,17 @@ public List getNodeItems() { // The packet listener and the filter for processing some AdHoc Commands // Packets + // TODO: This handler being async means that requests for the same command could be handled out of order. Nobody + // complained so far, and I could imagine that it does not really matter in practice. But it is certainly + // something to keep in mind. connection.registerIQRequestHandler(new AbstractIqRequestHandler(AdHocCommandData.ELEMENT, AdHocCommandData.NAMESPACE, IQ.Type.set, Mode.async) { @Override public IQ handleIQRequest(IQ iqRequest) { AdHocCommandData requestData = (AdHocCommandData) iqRequest; - try { - return processAdHocCommand(requestData); - } - catch (InterruptedException | NoResponseException | NotConnectedException e) { - LOGGER.log(Level.INFO, "processAdHocCommand threw exception", e); - return null; - } + AdHocCommandData response = processAdHocCommand(requestData); + assert response.getStatus() != null || response.getType() == IQ.Type.error; + return response; } }); } @@ -187,18 +209,21 @@ public IQ handleIQRequest(IQ iqRequest) { * connection. The node is an unique identifier of that command for * the connection related to this command manager. The name is the * human readable name of the command. The class is the class of - * the command, which must extend {@link LocalCommand} and have a default + * the command, which must extend {@link AdHocCommandHandler} and have a default * constructor. * * @param node the unique identifier of the command. * @param name the human readable name of the command. - * @param clazz the class of the command, which must extend {@link LocalCommand}. + * @param clazz the class of the command, which must extend {@link AdHocCommandHandler}. + * @throws SecurityException if there was a security violation. + * @throws NoSuchMethodException if no such method is declared. */ - public void registerCommand(String node, String name, final Class clazz) { - registerCommand(node, name, new LocalCommandFactory() { + public void registerCommand(String node, String name, final Class clazz) throws NoSuchMethodException, SecurityException { + Constructor constructor = clazz.getConstructor(String.class, String.class, String.class); + registerCommand(node, name, new AdHocCommandHandlerFactory() { @Override - public LocalCommand getInstance() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - return clazz.getConstructor().newInstance(); + public AdHocCommandHandler create(String node, String name, String sessionId) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + return constructor.newInstance(node, name, sessionId); } }); } @@ -214,10 +239,12 @@ public LocalCommand getInstance() throws InstantiationException, IllegalAccessEx * @param name the human readable name of the command. * @param factory a factory to create new instances of the command. */ - public void registerCommand(String node, final String name, LocalCommandFactory factory) { - AdHocCommandInfo commandInfo = new AdHocCommandInfo(node, name, connection().getUser(), factory); + public synchronized void registerCommand(String node, final String name, AdHocCommandHandlerFactory factory) { + AdHocCommandInfo commandInfo = new AdHocCommandInfo(node, name, factory); + + AdHocCommandInfo existing = commands.putIfAbsent(node, commandInfo); + if (existing != null) throw new IllegalArgumentException("There is already an ad-hoc command registered for " + node); - commands.put(node, commandInfo); // Set the NodeInformationProvider that will provide information about // the added command serviceDiscoveryManager.setNodeInformationProvider(node, @@ -242,6 +269,14 @@ public List getNodeIdentities() { }); } + public synchronized boolean unregisterCommand(String node) { + AdHocCommandInfo commandInfo = commands.remove(node); + if (commandInfo == null) return false; + + serviceDiscoveryManager.removeNodeInformationProvider(node); + return true; + } + /** * Discover the commands of an specific JID. The jid is a * full JID. @@ -266,8 +301,8 @@ public DiscoverItems discoverCommands(Jid jid) throws XMPPException, SmackExcept * @param node the identifier of the command * @return a local instance equivalent to the remote command. */ - public RemoteCommand getRemoteCommand(Jid jid, String node) { - return new RemoteCommand(connection(), node, jid); + public AdHocCommand getRemoteCommand(Jid jid, String node) { + return new AdHocCommand(connection(), node, jid); } /** @@ -291,240 +326,226 @@ public RemoteCommand getRemoteCommand(Jid jid, String node) { *
  • The action to execute is one of the available actions
  • * * - * @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. + * @param request the incoming AdHoc command request. */ - 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(); + private AdHocCommandData processAdHocCommand(AdHocCommandData request) { + String sessionId = request.getSessionId(); + final AdHocCommandHandler command; if (sessionId == null) { + String commandNode = request.getNode(); + // A new execution request has been received. Check that the // command exists - if (!commands.containsKey(commandNode)) { + AdHocCommandInfo commandInfo = commands.get(commandNode); + if (commandInfo == null) { // Requested command does not exist so return // item_not_found error. - return respondError(response, StanzaError.Condition.item_not_found); + return respondError(request, null, StanzaError.Condition.item_not_found); } - // Create new session ID - sessionId = StringUtils.randomString(15); + assert commandInfo.getNode().equals(commandNode); + // Create a new instance of the command with the + // corresponding session ID. 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); - } + command = commandInfo.getCommandInstance(); + } + catch (InstantiationException | IllegalAccessException | IllegalArgumentException + | InvocationTargetException e) { + LOGGER.log(Level.WARNING, "Could not instanciate ad-hoc command server", e); + StanzaError xmppError = StanzaError.getBuilder() + .setCondition(StanzaError.Condition.internal_server_error) + .setDescriptiveEnText(e.getMessage()) + .build(); + return respondError(request, null, xmppError); + } + } else { + command = executingCommands.get(sessionId); + // Check that a command exists for the specified sessionID + // This also handles if the command was removed in the meanwhile + // of getting the key and the value of the map. + if (command == null) { + return respondError(request, null, StanzaError.Condition.bad_request, + SpecificErrorCondition.badSessionid); + } + } - response.setType(IQ.Type.result); - command.setData(response); - // Check that the requester has enough permission. - // Answer forbidden error if requester permissions are not - // enough to execute the requested command - if (!command.hasPermission(requestData.getFrom())) { - return respondError(response, StanzaError.Condition.forbidden); - } + final AdHocCommandDataBuilder responseBuilder = AdHocCommandDataBuilder.buildResponseFor(request) + .setSessionId(command.getSessionId()); - Action action = requestData.getAction(); + final AdHocCommandData response; + /* + * 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) { + command.addRequest(request); - // 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 (sessionId == null) { + response = processAdHocCommandOfNewSession(request, command, responseBuilder); + } else { + response = processAdHocCommandOfExistingSession(request, command, responseBuilder); + } - // 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(); + AdHocCommandResult commandResult = AdHocCommandResult.from(response); + command.addResult(commandResult); + } - 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(); - } + return response; + } - // Sends the response packet - return response; + private AdHocCommandData createResponseFrom(AdHocCommandData request, AdHocCommandDataBuilder response, XMPPErrorException exception, String sessionId) { + StanzaError error = exception.getStanzaError(); - } - 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(); - - // If the error type is cancel, then the execution is - // canceled therefore the status must show that, and the - // 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); - } + // If the error type is cancel, then the execution is + // canceled therefore the status must show that, and the + // command be removed from the executing list. + if (error.getType() == StanzaError.Type.CANCEL) { + response.setStatus(AdHocCommandData.Status.canceled); + + executingCommands.remove(sessionId); + + return response.build(); } - else { - LocalCommand command = executingCommands.get(sessionId); - // Check that a command exists for the specified sessionID - // This also handles if the command was removed in the meanwhile - // of getting the key and the value of the map. - if (command == null) { - return respondError(response, StanzaError.Condition.bad_request, - AdHocCommand.SpecificErrorCondition.badSessionid); - } + return respondError(request, response, error); + } - // 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); + private static AdHocCommandData createResponseFrom(AdHocCommandData request, AdHocCommandDataBuilder response, Exception exception) { + StanzaError error = StanzaError.from(StanzaError.Condition.internal_server_error, exception.getMessage()) + .build(); + return respondError(request, response, error); + } - // Answer a not_allowed error (session-expired) - return respondError(response, StanzaError.Condition.not_allowed, - AdHocCommand.SpecificErrorCondition.sessionExpired); - } + private AdHocCommandData processAdHocCommandOfNewSession(AdHocCommandData request, AdHocCommandHandler command, AdHocCommandDataBuilder responseBuilder) { + // Check that the requester has enough permission. + // Answer forbidden error if requester permissions are not + // enough to execute the requested command + if (!command.hasPermission(request.getFrom())) { + return respondError(request, responseBuilder, StanzaError.Condition.forbidden); + } - /* - * 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); - } + AdHocCommandData.Action action = request.getAction(); - // If the user didn't specify an action or specify the execute - // action then follow the actual default execute action - if (action == null || Action.execute.equals(action)) { - action = command.getExecuteAction(); - } + // If the action is not execute, then it is an invalid action. + if (action != null && !action.equals(AdHocCommandData.Action.execute)) { + return respondError(request, responseBuilder, StanzaError.Condition.bad_request, + SpecificErrorCondition.badAction); + } - // Check that the specified action was previously - // offered - if (!command.isValidAction(action)) { - 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(); + + final AdHocCommandData response; + try { + // Executes the command + response = command.execute(responseBuilder); + } catch (XMPPErrorException e) { + return createResponseFrom(request, responseBuilder, e, command.getSessionId()); + } catch (NoResponseException | NotConnectedException | InterruptedException | IllegalStateException e) { + return createResponseFrom(request, responseBuilder, e); + } - 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); - } + if (response.isExecuting()) { + executingCommands.put(command.getSessionId(), command); + // See if the session sweeper thread is scheduled. If not, start it. + maybeWindUpSessionSweeper(); + } - 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(); - - // If the error type is cancel, then the execution is - // canceled therefore the status must show that, and the - // 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); - } + return response; + } + + private AdHocCommandData processAdHocCommandOfExistingSession(AdHocCommandData request, AdHocCommandHandler command, AdHocCommandDataBuilder responseBuilder) { + // Check if the Session data has expired (default is 10 minutes) + long creationStamp = command.getCreationDate(); + if (System.currentTimeMillis() - creationStamp > sessionTimeoutSecs * 1000) { + // Remove the expired session + executingCommands.remove(command.getSessionId()); + + // Answer a not_allowed error (session-expired) + return respondError(request, responseBuilder, StanzaError.Condition.not_allowed, + SpecificErrorCondition.sessionExpired); + } + + AdHocCommandData.Action action = request.getAction(); + + // If the user didn't specify an action or specify the execute + // action then follow the actual default execute action + if (action == null || AdHocCommandData.Action.execute.equals(action)) { + AllowedAction executeAction = command.getExecuteAction(); + if (executeAction != null) { + action = executeAction.action; } } + + // Check that the specified action was previously + // offered + if (!command.isValidAction(action)) { + return respondError(request, responseBuilder, StanzaError.Condition.bad_request, + SpecificErrorCondition.badAction); + } + + AdHocCommandData response; + try { + DataForm dataForm; + switch (action) { + case next: + command.incrementStage(); + dataForm = request.getForm(); + response = command.next(responseBuilder, new SubmitForm(dataForm)); + break; + case complete: + command.incrementStage(); + dataForm = request.getForm(); + responseBuilder.setStatus(AdHocCommandData.Status.completed); + response = command.complete(responseBuilder, new SubmitForm(dataForm)); + // Remove the completed session + executingCommands.remove(command.getSessionId()); + break; + case prev: + command.decrementStage(); + response = command.prev(responseBuilder); + break; + case cancel: + command.cancel(); + responseBuilder.setStatus(AdHocCommandData.Status.canceled); + response = responseBuilder.build(); + // Remove the canceled session + executingCommands.remove(command.getSessionId()); + break; + default: + return respondError(request, responseBuilder, StanzaError.Condition.bad_request, + SpecificErrorCondition.badAction); + } + } catch (XMPPErrorException e) { + return createResponseFrom(request, responseBuilder, e, command.getSessionId()); + } catch (NoResponseException | NotConnectedException | InterruptedException | IllegalStateException e) { + return createResponseFrom(request, responseBuilder, e); + } + + return response; } private boolean sessionSweeperScheduled; + private int getSessionRemovalTimeoutSecs() { + return sessionTimeoutSecs * 2; + } + private void sessionSweeper() { final long currentTime = System.currentTimeMillis(); synchronized (this) { - for (Iterator> it = executingCommands.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = it.next(); - LocalCommand command = entry.getValue(); + for (Iterator> it = executingCommands.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = it.next(); + AdHocCommandHandler command = entry.getValue(); long creationStamp = command.getCreationDate(); - // Check if the Session data has expired (default is 10 minutes) + // Check if the Session data has expired. // To remove it from the session list it waits for the double of // the of time out time. This is to let // the requester know why his execution request is @@ -532,7 +553,7 @@ private void sessionSweeper() { // after the time out, then once the user requests to // continue the execution he will received an // invalid session error and not a time out error. - if (currentTime - creationStamp > SESSION_TIMEOUT * 1000 * 2) { + if (currentTime - creationStamp > getSessionRemovalTimeoutSecs() * 1000) { // Remove the expired session it.remove(); } @@ -552,104 +573,100 @@ private synchronized void maybeWindUpSessionSweeper() { } sessionSweeperScheduled = true; - schedule(this::sessionSweeper, 10, TimeUnit.SECONDS); + schedule(this::sessionSweeper, getSessionRemovalTimeoutSecs() + 1, TimeUnit.SECONDS); } /** * Responds an error with an specific condition. * - * @param response the response to send. + * @param request the request that caused the error response. * @param condition the condition of the error. */ - private static IQ respondError(AdHocCommandData response, + private static AdHocCommandData respondError(AdHocCommandData request, AdHocCommandDataBuilder response, StanzaError.Condition condition) { - return respondError(response, StanzaError.getBuilder(condition).build()); + return respondError(request, response, StanzaError.getBuilder(condition).build()); } /** * Responds an error with an specific condition. * - * @param response the response to send. + * @param request the request that caused the error response. * @param condition the condition of the error. * @param specificCondition the adhoc command error condition. */ - private static IQ respondError(AdHocCommandData response, StanzaError.Condition condition, - AdHocCommand.SpecificErrorCondition specificCondition) { + private static AdHocCommandData respondError(AdHocCommandData request, AdHocCommandDataBuilder response, StanzaError.Condition condition, + SpecificErrorCondition specificCondition) { StanzaError error = StanzaError.getBuilder(condition) .addExtension(new AdHocCommandData.SpecificError(specificCondition)) .build(); - return respondError(response, error); + return respondError(request, response, error); } /** * Responds an error with an specific error. * - * @param response the response to send. + * @param request the request that caused the error response. * @param error the error to send. */ - private static IQ respondError(AdHocCommandData response, StanzaError error) { - response.setType(IQ.Type.error); - response.setError(error); - return response; + private static AdHocCommandData respondError(AdHocCommandData request, AdHocCommandDataBuilder response, StanzaError error) { + if (response == null) { + return AdHocCommandDataBuilder.buildResponseFor(request, IQ.ResponseType.error).setError(error).build(); + } + + // Response may be not of IQ type error here, so switch that. + return response.ofType(IQ.Type.error) + .setError(error) + .build(); } - /** - * Creates a new instance of a command to be used by a new execution request - * - * @param commandNode the command node that identifies it. - * @param sessionID the session id of this execution. - * @return the command instance to execute. - * @throws XMPPErrorException if there is problem creating the new instance. - * @throws SecurityException if there was a security violation. - * @throws NoSuchMethodException if no such method is declared - * @throws InvocationTargetException if a reflection-based method or constructor invocation threw. - * @throws IllegalArgumentException if an illegal argument was given. - * @throws IllegalAccessException in case of an illegal access. - * @throws InstantiationException in case of an instantiation error. - */ - private LocalCommand newInstanceOfCmd(String commandNode, String sessionID) - throws XMPPErrorException, InstantiationException, IllegalAccessException, IllegalArgumentException, - InvocationTargetException, NoSuchMethodException, SecurityException { - AdHocCommandInfo commandInfo = commands.get(commandNode); - LocalCommand command = commandInfo.getCommandInstance(); - command.setSessionID(sessionID); - command.setName(commandInfo.getName()); - command.setNode(commandInfo.getNode()); - - return command; + public static void setDefaultSessionTimeoutSecs(int seconds) { + if (seconds < 10) { + throw new IllegalArgumentException(); + } + DEFAULT_SESSION_TIMEOUT_SECS = seconds; } - /** - * Returns the registered commands of this command manager, which is related - * to a connection. - * - * @return the registered commands. - */ - private Collection getRegisteredCommands() { - return commands.values(); + public void setSessionTimeoutSecs(int seconds) { + if (seconds < 10) { + throw new IllegalArgumentException(); + } + + sessionTimeoutSecs = seconds; } /** * Stores ad-hoc command information. */ - private static final class AdHocCommandInfo { + private final class AdHocCommandInfo { + + private final String node; + private final String name; + private final AdHocCommandHandlerFactory factory; - private String node; - private String name; - private final Jid ownerJID; - private LocalCommandFactory factory; + private static final int MAX_SESSION_GEN_ATTEMPTS = 3; - private AdHocCommandInfo(String node, String name, Jid ownerJID, - LocalCommandFactory factory) { + private AdHocCommandInfo(String node, String name, AdHocCommandHandlerFactory factory) { this.node = node; this.name = name; - this.ownerJID = ownerJID; this.factory = factory; } - public LocalCommand getCommandInstance() throws InstantiationException, - IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - return factory.getInstance(); + public AdHocCommandHandler getCommandInstance() throws InstantiationException, + IllegalAccessException, IllegalArgumentException, InvocationTargetException { + String sessionId; + // TODO: The code below contains a race condition. Use CopncurrentHashMap.computeIfAbsent() to remove the + // race condition once Smack's minimum Android API level 24 or higher. + int attempt = 0; + do { + attempt++; + if (attempt > MAX_SESSION_GEN_ATTEMPTS) { + throw new RuntimeException("Failed to compute unique session ID"); + } + // Create new session ID + sessionId = StringUtils.randomString(15); + } while (executingCommands.containsKey(sessionId)); + + return factory.create(node, name, sessionId); } public String getName() { @@ -660,8 +677,5 @@ public String getNode() { return node; } - public Jid getOwnerJID() { - return ownerJID; - } } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandResult.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandResult.java new file mode 100644 index 0000000000..e0927e2770 --- /dev/null +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandResult.java @@ -0,0 +1,102 @@ +/** + * + * Copyright 2023 Florian Schmaus + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smackx.commands; + +import org.jivesoftware.smack.packet.IQ; +import org.jivesoftware.smackx.commands.packet.AdHocCommandData; +import org.jivesoftware.smackx.xdata.form.FillableForm; +import org.jivesoftware.smackx.xdata.packet.DataForm; + +// TODO: Make this a sealed class once Smack is Java 17 or higher. +public abstract class AdHocCommandResult { + + private final AdHocCommandData response; + private final boolean completed; + + private AdHocCommandResult(AdHocCommandData response, boolean completed) { + this.response = response; + this.completed = completed; + } + + public final AdHocCommandData getResponse() { + return response; + } + + public final boolean isCompleted() { + return completed; + } + + public StatusExecuting asExecutingOrThrow() { + if (this instanceof StatusExecuting) + return (StatusExecuting) this; + + throw new IllegalStateException(); + } + + public StatusCompleted asCompletedOrThrow() { + if (this instanceof StatusCompleted) + return (StatusCompleted) this; + + throw new IllegalStateException(); + } + + public static final class StatusExecuting extends AdHocCommandResult { + private StatusExecuting(AdHocCommandData response) { + super(response, false); + assert response.getStatus() == AdHocCommandData.Status.executing; + } + + public FillableForm getFillableForm() { + DataForm form = getResponse().getForm(); + return new FillableForm(form); + } + } + + public static final class StatusCompleted extends AdHocCommandResult { + private StatusCompleted(AdHocCommandData response) { + super(response, true); + assert response.getStatus() == AdHocCommandData.Status.completed; + } + } + + /** + * This subclass is only used internally by Smack. + */ + @SuppressWarnings("JavaLangClash") + static final class Error extends AdHocCommandResult { + private Error(AdHocCommandData response) { + super(response, false); + } + } + + public static AdHocCommandResult from(AdHocCommandData response) { + IQ.Type iqType = response.getType(); + if (iqType == IQ.Type.error) + return new Error(response); + + assert iqType == IQ.Type.result; + + switch (response.getStatus()) { + case executing: + return new StatusExecuting(response); + case completed: + return new StatusCompleted(response); + default: + throw new IllegalArgumentException(); + } + } +} diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/LocalCommand.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/LocalCommand.java deleted file mode 100755 index 1dd01d3abe..0000000000 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/LocalCommand.java +++ /dev/null @@ -1,168 +0,0 @@ -/** - * - * Copyright 2005-2007 Jive Software. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jivesoftware.smackx.commands; - -import org.jivesoftware.smackx.commands.packet.AdHocCommandData; - -import org.jxmpp.jid.Jid; - -/** - * Represents a command that can be executed locally from a remote location. This - * class must be extended to implement an specific ad-hoc command. This class - * provides some useful tools:
      - *
    • Node
    • - *
    • Name
    • - *
    • Session ID
    • - *
    • Current Stage
    • - *
    • Available actions
    • - *
    • Default action
    • - *
    - * To implement a new command extend this class and implement all the abstract - * methods. When implementing the actions remember that they could be invoked - * several times, and that you must use the current stage number to know what to - * do. - * - * @author Gabriel Guardincerri - */ -public abstract class LocalCommand extends AdHocCommand { - - /** - * The time stamp of first invocation of the command. Used to implement the session timeout. - */ - private final long creationDate; - - /** - * The unique ID of the execution of the command. - */ - private String sessionID; - - /** - * The full JID of the host of the command. - */ - private Jid ownerJID; - - /** - * The number of the current stage. - */ - private int currentStage; - - public LocalCommand() { - super(); - this.creationDate = System.currentTimeMillis(); - currentStage = -1; - } - - /** - * The sessionID is an unique identifier of an execution request. This is - * automatically handled and should not be called. - * - * @param sessionID the unique session id of this execution - */ - public void setSessionID(String sessionID) { - this.sessionID = sessionID; - getData().setSessionID(sessionID); - } - - /** - * Returns the session ID of this execution. - * - * @return the unique session id of this execution - */ - public String getSessionID() { - return sessionID; - } - - /** - * Sets the JID of the command host. This is automatically handled and should - * not be called. - * - * @param ownerJID the JID of the owner. - */ - public void setOwnerJID(Jid ownerJID) { - this.ownerJID = ownerJID; - } - - @Override - public Jid getOwnerJID() { - return ownerJID; - } - - /** - * Returns the date the command was created. - * - * @return the date the command was created. - */ - public long getCreationDate() { - return creationDate; - } - - /** - * Returns true if the current stage is the last one. If it is then the - * execution of some action will complete the execution of the command. - * Commands that don't have multiple stages can always return true. - * - * @return true if the command is in the last stage. - */ - public abstract boolean isLastStage(); - - /** - * Returns true if the specified requester has permission to execute all the - * stages of this action. This is checked when the first request is received, - * if the permission is grant then the requester will be able to execute - * all the stages of the command. It is not checked again during the - * execution. - * - * @param jid the JID to check permissions on. - * @return true if the user has permission to execute this action. - */ - public abstract boolean hasPermission(Jid jid); - - /** - * Returns the currently executing stage number. The first stage number is - * 0. During the execution of the first action this method will answer 0. - * - * @return the current stage number. - */ - public int getCurrentStage() { - return currentStage; - } - - @Override - void setData(AdHocCommandData data) { - data.setSessionID(sessionID); - super.setData(data); - } - - /** - * Increase the current stage number. This is automatically handled and should - * not be called. - * - */ - void incrementStage() { - currentStage++; - } - - /** - * Decrease the current stage number. This is automatically handled and should - * not be called. - * - */ - void decrementStage() { - currentStage--; - } -} diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/RemoteCommand.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/RemoteCommand.java deleted file mode 100755 index e79919eb68..0000000000 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/RemoteCommand.java +++ /dev/null @@ -1,164 +0,0 @@ -/** - * - * Copyright 2005-2007 Jive Software. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jivesoftware.smackx.commands; - -import org.jivesoftware.smack.SmackException.NoResponseException; -import org.jivesoftware.smack.SmackException.NotConnectedException; -import org.jivesoftware.smack.XMPPConnection; -import org.jivesoftware.smack.XMPPException.XMPPErrorException; -import org.jivesoftware.smack.packet.IQ; - -import org.jivesoftware.smackx.commands.packet.AdHocCommandData; -import org.jivesoftware.smackx.xdata.form.FillableForm; -import org.jivesoftware.smackx.xdata.packet.DataForm; - -import org.jxmpp.jid.Jid; - -/** - * Represents a command that is in a remote location. Invoking one of the - * {@link AdHocCommand.Action#execute execute}, {@link AdHocCommand.Action#next next}, - * {@link AdHocCommand.Action#prev prev}, {@link AdHocCommand.Action#cancel cancel} or - * {@link AdHocCommand.Action#complete complete} actions results in executing that - * action in the remote location. In response to that action the internal state - * of the this command instance will change. For example, if the command is a - * single stage command, then invoking the execute action will execute this - * action in the remote location. After that the local instance will have a - * state of "completed" and a form or notes that applies. - * - * @author Gabriel Guardincerri - * - */ -public class RemoteCommand extends AdHocCommand { - - /** - * The connection that is used to execute this command - */ - private final XMPPConnection connection; - - /** - * The full JID of the command host - */ - private final Jid jid; - - /** - * The session ID of this execution. - */ - private String sessionID; - - /** - * Creates a new RemoteCommand that uses an specific connection to execute a - * command identified by node in the host identified by - * jid - * - * @param connection the connection to use for the execution. - * @param node the identifier of the command. - * @param jid the JID of the host. - */ - protected RemoteCommand(XMPPConnection connection, String node, Jid jid) { - super(); - this.connection = connection; - this.jid = jid; - this.setNode(node); - } - - @Override - public void cancel() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { - executeAction(Action.cancel); - } - - @Override - public void complete(FillableForm form) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { - executeAction(Action.complete, form.getDataFormToSubmit()); - } - - @Override - public void execute() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { - executeAction(Action.execute); - } - - /** - * Executes the default action of the command with the information provided - * in the Form. This form must be the answer form of the previous stage. If - * there is a problem executing the command it throws an XMPPException. - * - * @param form the form answer of the previous stage. - * @throws XMPPErrorException if an error occurs. - * @throws NoResponseException if there was no response from the server. - * @throws NotConnectedException if the XMPP connection is not connected. - * @throws InterruptedException if the calling thread was interrupted. - */ - public void execute(FillableForm form) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { - executeAction(Action.execute, form.getDataFormToSubmit()); - } - - @Override - public void next(FillableForm form) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { - executeAction(Action.next, form.getDataFormToSubmit()); - } - - @Override - public void prev() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { - executeAction(Action.prev); - } - - private void executeAction(Action action) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { - executeAction(action, null); - } - - /** - * Executes the action with the form. - * The action could be any of the available actions. The form must - * be the answer of the previous stage. It can be null if it is the first stage. - * - * @param action the action to execute. - * @param form the form with the information. - * @throws XMPPErrorException if there is a problem executing the command. - * @throws NoResponseException if there was no response from the server. - * @throws NotConnectedException if the XMPP connection is not connected. - * @throws InterruptedException if the calling thread was interrupted. - */ - private void executeAction(Action action, DataForm form) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { - // TODO: Check that all the required fields of the form were filled, if - // TODO: not throw the corresponding exception. This will make a faster response, - // TODO: since the request is stopped before it's sent. - AdHocCommandData data = new AdHocCommandData(); - data.setType(IQ.Type.set); - data.setTo(getOwnerJID()); - data.setNode(getNode()); - data.setSessionID(sessionID); - data.setAction(action); - data.setForm(form); - - AdHocCommandData responseData = null; - try { - responseData = connection.sendIqRequestAndWaitForResponse(data); - } - finally { - // We set the response data in a 'finally' block, so that it also gets set even if an error IQ was returned. - if (responseData != null) { - this.sessionID = responseData.getSessionID(); - super.setData(responseData); - } - } - - } - - @Override - public Jid getOwnerJID() { - return jid; - } -} diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/SpecificErrorCondition.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/SpecificErrorCondition.java new file mode 100644 index 0000000000..fcf94a9894 --- /dev/null +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/SpecificErrorCondition.java @@ -0,0 +1,63 @@ +/** + * + * Copyright 2005-2007 Jive Software. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smackx.commands; + +public enum SpecificErrorCondition { + + /** + * The responding JID cannot accept the specified action. + */ + badAction("bad-action"), + + /** + * The responding JID does not understand the specified action. + */ + malformedAction("malformed-action"), + + /** + * The responding JID cannot accept the specified language/locale. + */ + badLocale("bad-locale"), + + /** + * The responding JID cannot accept the specified payload (e.g. the data + * form did not provide one or more required fields). + */ + badPayload("bad-payload"), + + /** + * The responding JID cannot accept the specified sessionid. + */ + badSessionid("bad-sessionid"), + + /** + * The requesting JID specified a sessionid that is no longer active + * (either because it was completed, canceled, or timed out). + */ + sessionExpired("session-expired"); + + private final String value; + + SpecificErrorCondition(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } +} diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/packet/AdHocCommandData.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/packet/AdHocCommandData.java index f5681b0fc6..19f29ac9be 100755 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/packet/AdHocCommandData.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/packet/AdHocCommandData.java @@ -18,63 +18,114 @@ package org.jivesoftware.smackx.commands.packet; import java.util.ArrayList; +import java.util.EnumSet; import java.util.List; +import java.util.Set; +import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.packet.IQ; +import org.jivesoftware.smack.packet.IqData; import org.jivesoftware.smack.packet.XmlElement; -import org.jivesoftware.smackx.commands.AdHocCommand; -import org.jivesoftware.smackx.commands.AdHocCommand.Action; -import org.jivesoftware.smackx.commands.AdHocCommand.SpecificErrorCondition; import org.jivesoftware.smackx.commands.AdHocCommandNote; +import org.jivesoftware.smackx.commands.SpecificErrorCondition; import org.jivesoftware.smackx.xdata.packet.DataForm; -import org.jxmpp.jid.Jid; - /** * Represents the state and the request of the execution of an adhoc command. * * @author Gabriel Guardincerri + * @author Florian Schmaus */ -public class AdHocCommandData extends IQ { +public class AdHocCommandData extends IQ implements AdHocCommandDataView { public static final String ELEMENT = "command"; public static final String NAMESPACE = "http://jabber.org/protocol/commands"; - /* JID of the command host */ - private Jid id; - - /* Command name */ - private String name; + private final String node; - /* Command identifier */ - private String node; + private final String name; - /* Unique ID of the execution */ - private String sessionID; + private final String sessionId; private final List notes = new ArrayList<>(); - private DataForm form; + private final DataForm form; + + private final Action action; + + private final Status status; + + private final Set actions = EnumSet.noneOf(AllowedAction.class); + + private final AllowedAction executeAction; + + public AdHocCommandData(AdHocCommandDataBuilder builder) { + super(builder, ELEMENT, NAMESPACE); + node = builder.getNode(); + name = builder.getName(); + sessionId = builder.getSessionId(); + notes.addAll(builder.getNotes()); + form = builder.getForm(); + action = builder.getAction(); + status = builder.getStatus(); + actions.addAll(builder.getActions()); + executeAction = builder.getExecuteAction(); + + if (executeAction != null && !actions.contains(executeAction)) { + throw new IllegalArgumentException("Execute action " + executeAction + " is not part of allowed actions: " + actions); + } + } + + @Override + public String getNode() { + return node; + } - /* Action request to be executed */ - private AdHocCommand.Action action; + @Override + public String getName() { + return name; + } + + @Override + public String getSessionId() { + return sessionId; + } + + @Override + public List getNotes() { + return notes; + } + + @Override + public DataForm getForm() { + return form; + } - /* Current execution status */ - private AdHocCommand.Status status; + @Override + public Action getAction() { + return action; + } - private final ArrayList actions = new ArrayList<>(); + @Override + public Status getStatus() { + return status; + } - private AdHocCommand.Action executeAction; + @Override + public Set getActions() { + return actions; + } - public AdHocCommandData() { - super(ELEMENT, NAMESPACE); + @Override + public AllowedAction getExecuteAction() { + return executeAction; } @Override protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) { xml.attribute("node", node); - xml.optAttribute("sessionid", sessionID); + xml.optAttribute("sessionid", sessionId); xml.optAttribute("status", status); xml.optAttribute("action", action); xml.rightAngleBracket(); @@ -87,19 +138,19 @@ protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElement } else { xml.rightAngleBracket(); - for (AdHocCommand.Action action : actions) { + for (AdHocCommandData.AllowedAction action : actions) { xml.emptyElement(action); } xml.closeElement("actions"); } } - if (form != null) { - xml.append(form.toXML()); - } + xml.optAppend(form); for (AdHocCommandNote note : notes) { - xml.halfOpenElement("note").attribute("type", note.getType().toString()).rightAngleBracket(); + xml.halfOpenElement("note") + .attribute("type", note.getType().toString()) + .rightAngleBracket(); xml.append(note.getValue()); xml.closeElement("note"); } @@ -112,132 +163,16 @@ protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElement return xml; } - /** - * Returns the JID of the command host. - * - * @return the JID of the command host. - */ - public Jid getId() { - return id; + public static AdHocCommandDataBuilder builder(String node, IqData iqCommon) { + return new AdHocCommandDataBuilder(node, iqCommon); } - public void setId(Jid id) { - this.id = id; + public static AdHocCommandDataBuilder builder(String node, String stanzaId) { + return new AdHocCommandDataBuilder(node, stanzaId); } - /** - * Returns the human name of the command. - * - * @return the name of the command. - */ - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - /** - * Returns the identifier of the command. - * - * @return the node. - */ - public String getNode() { - return node; - } - - public void setNode(String node) { - this.node = node; - } - - /** - * Returns the list of notes that the command has. - * - * @return the notes. - */ - public List getNotes() { - return notes; - } - - public void addNote(AdHocCommandNote note) { - this.notes.add(note); - } - - public void removeNote(AdHocCommandNote note) { - this.notes.remove(note); - } - - /** - * Returns the form of the command. - * - * @return the data form associated with the command. - */ - public DataForm getForm() { - return form; - } - - public void setForm(DataForm form) { - this.form = form; - } - - /** - * Returns the action to execute. The action is set only on a request. - * - * @return the action to execute. - */ - public AdHocCommand.Action getAction() { - return action; - } - - public void setAction(AdHocCommand.Action action) { - this.action = action; - } - - /** - * Returns the status of the execution. - * - * @return the status. - */ - public AdHocCommand.Status getStatus() { - return status; - } - - public void setStatus(AdHocCommand.Status status) { - this.status = status; - } - - public List getActions() { - return actions; - } - - public void addAction(Action action) { - actions.add(action); - } - - public void setExecuteAction(Action executeAction) { - this.executeAction = executeAction; - } - - public Action getExecuteAction() { - return executeAction; - } - - /** - * Set the 'sessionid' attribute of the command. - *

    - * This value can be null or empty for the first command, but MUST be set for subsequent commands. See also XEP-0050 § 3.3 Session Lifetime. - *

    - * - * @param sessionID TODO javadoc me please - */ - public void setSessionID(String sessionID) { - this.sessionID = sessionID; - } - - public String getSessionID() { - return sessionID; + public static AdHocCommandDataBuilder builder(String node, XMPPConnection connection) { + return new AdHocCommandDataBuilder(node, connection); } public static class SpecificError implements XmlElement { @@ -271,4 +206,86 @@ public String toXML(org.jivesoftware.smack.packet.XmlEnvironment enclosingNamesp return buf.toString(); } } + + /** + * The status of the stage in the adhoc command. + */ + public enum Status { + + /** + * The command is being executed. + */ + executing, + + /** + * The command has completed. The command session has ended. + */ + completed, + + /** + * The command has been canceled. The command session has ended. + */ + canceled + } + + public enum AllowedAction { + + /** + * The command should be digress to the previous stage of execution. + */ + prev(Action.prev), + + /** + * The command should progress to the next stage of execution. + */ + next(Action.next), + + /** + * The command should be completed (if possible). + */ + complete(Action.complete), + ; + + public final Action action; + + AllowedAction(Action action) { + this.action = action; + } + } + + public enum Action { + /** + * The command should be executed or continue to be executed. This is + * the default value. + */ + execute(null), + + /** + * The command should be canceled. + */ + cancel(null), + + /** + * The command should be digress to the previous stage of execution. + */ + prev(AllowedAction.prev), + + /** + * The command should progress to the next stage of execution. + */ + next(AllowedAction.next), + + /** + * The command should be completed (if possible). + */ + complete(AllowedAction.complete), + ; + + public final AllowedAction allowedAction; + + Action(AllowedAction allowedAction) { + this.allowedAction = allowedAction; + } + + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/packet/AdHocCommandDataBuilder.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/packet/AdHocCommandDataBuilder.java new file mode 100644 index 0000000000..fea5e6259f --- /dev/null +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/packet/AdHocCommandDataBuilder.java @@ -0,0 +1,220 @@ +/** + * + * Copyright 2023 Florian Schmaus + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smackx.commands.packet; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Set; + +import org.jivesoftware.smack.XMPPConnection; +import org.jivesoftware.smack.packet.AbstractIqBuilder; +import org.jivesoftware.smack.packet.IQ; +import org.jivesoftware.smack.packet.IqBuilder; +import org.jivesoftware.smack.packet.IqData; +import org.jivesoftware.smack.util.StringUtils; + +import org.jivesoftware.smackx.commands.AdHocCommandNote; +import org.jivesoftware.smackx.commands.packet.AdHocCommandData.Action; +import org.jivesoftware.smackx.commands.packet.AdHocCommandData.AllowedAction; +import org.jivesoftware.smackx.commands.packet.AdHocCommandData.Status; +import org.jivesoftware.smackx.xdata.packet.DataForm; + +public class AdHocCommandDataBuilder extends IqBuilder implements AdHocCommandDataView { + + private final String node; + + private String name; + + private String sessionId; + + private final List notes = new ArrayList<>(); + + private DataForm form; + + /* Action request to be executed */ + private Action action; + + /* Current execution status */ + private Status status; + + private final Set actions = EnumSet.noneOf(AllowedAction.class); + + private AllowedAction executeAction; + + AdHocCommandDataBuilder(String node, IqData iqCommon) { + super(iqCommon); + this.node = StringUtils.requireNotNullNorEmpty(node, "Ad-Hoc Command node must be set"); + } + + AdHocCommandDataBuilder(String node, String stanzaId) { + super(stanzaId); + this.node = StringUtils.requireNotNullNorEmpty(node, "Ad-Hoc Command node must be set"); + } + + AdHocCommandDataBuilder(String node, XMPPConnection connection) { + super(connection); + this.node = StringUtils.requireNotNullNorEmpty(node, "Ad-Hoc Command node must be set"); + } + + @Override + public String getNode() { + return node; + } + + @Override + public String getName() { + return name; + } + + public AdHocCommandDataBuilder setName(String name) { + this.name = name; + return getThis(); + } + + @Override + public String getSessionId() { + return sessionId; + } + + public AdHocCommandDataBuilder setSessionId(String sessionId) { + this.sessionId = sessionId; + return getThis(); + } + + @Override + public List getNotes() { + return notes; + } + + public AdHocCommandDataBuilder addNote(AdHocCommandNote note) { + notes.add(note); + return getThis(); + } + + @Override + public DataForm getForm() { + return form; + } + + public AdHocCommandDataBuilder setForm(DataForm form) { + this.form = form; + return getThis(); + } + + @Override + public Action getAction() { + return action; + } + + public AdHocCommandDataBuilder setAction(AdHocCommandData.Action action) { + this.action = action; + return getThis(); + } + @Override + + public AdHocCommandData.Status getStatus() { + return status; + } + + public AdHocCommandDataBuilder setStatus(AdHocCommandData.Status status) { + this.status = status; + return getThis(); + } + + public AdHocCommandDataBuilder setStatusCompleted() { + return setStatus(AdHocCommandData.Status.completed); + } + + public enum PreviousStage { + exists, + none, + } + + public enum NextStage { + isFinal, + nonFinal, + } + + @SuppressWarnings("fallthrough") + public AdHocCommandDataBuilder setStatusExecuting(PreviousStage previousStage, NextStage nextStage) { + setStatus(AdHocCommandData.Status.executing); + + switch (previousStage) { + case exists: + addAction(AllowedAction.prev); + break; + case none: + break; + } + + setExecuteAction(AllowedAction.next); + + switch (nextStage) { + case isFinal: + addAction(AllowedAction.complete); + // Override execute action of 'next'. + setExecuteAction(AllowedAction.complete); + // Deliberate fallthrough, we want 'next' to be added. + case nonFinal: + addAction(AllowedAction.next); + break; + } + + return getThis(); + } + + @Override + public Set getActions() { + return actions; + } + + public AdHocCommandDataBuilder addAction(AllowedAction action) { + actions.add(action); + return getThis(); + } + + @Override + public AllowedAction getExecuteAction() { + return executeAction; + } + + public AdHocCommandDataBuilder setExecuteAction(AllowedAction action) { + this.executeAction = action; + return getThis(); + } + + @Override + public AdHocCommandData build() { + return new AdHocCommandData(this); + } + + @Override + public AdHocCommandDataBuilder getThis() { + return this; + } + + public static AdHocCommandDataBuilder buildResponseFor(AdHocCommandData request) { + return buildResponseFor(request, IQ.ResponseType.result); + } + + public static AdHocCommandDataBuilder buildResponseFor(AdHocCommandData request, IQ.ResponseType responseType) { + AdHocCommandDataBuilder builder = new AdHocCommandDataBuilder(request.getNode(), AbstractIqBuilder.createResponse(request, responseType)); + return builder; + } + +} diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/packet/AdHocCommandDataView.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/packet/AdHocCommandDataView.java new file mode 100644 index 0000000000..f1cc4b0caa --- /dev/null +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/packet/AdHocCommandDataView.java @@ -0,0 +1,87 @@ +/** + * + * Copyright 2023 Florian Schmaus + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smackx.commands.packet; + +import java.util.List; +import java.util.Set; + +import org.jivesoftware.smack.packet.IqView; + +import org.jivesoftware.smackx.commands.AdHocCommandNote; +import org.jivesoftware.smackx.commands.packet.AdHocCommandData.Action; +import org.jivesoftware.smackx.commands.packet.AdHocCommandData.AllowedAction; +import org.jivesoftware.smackx.commands.packet.AdHocCommandData.Status; +import org.jivesoftware.smackx.xdata.packet.DataForm; + +public interface AdHocCommandDataView extends IqView { + + /** + * Returns the identifier of the command. + * + * @return the node. + */ + String getNode(); + + /** + * Returns the human name of the command. + * + * @return the name of the command. + */ + String getName(); + + String getSessionId(); + + /** + * Returns the list of notes that the command has. + * + * @return the notes. + */ + List getNotes(); + + /** + * Returns the form of the command. + * + * @return the data form associated with the command. + */ + DataForm getForm(); + + /** + * Returns the action to execute. The action is set only on a request. + * + * @return the action to execute. + */ + Action getAction(); + + /** + * Returns the status of the execution. + * + * @return the status. + */ + Status getStatus(); + + Set getActions(); + + AllowedAction getExecuteAction(); + + default boolean isCompleted() { + return getStatus() == Status.completed; + } + + default boolean isExecuting() { + return getStatus() == Status.executing; + } +} diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/provider/AdHocCommandDataProvider.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/provider/AdHocCommandDataProvider.java index 26dfa56a3d..6f9b754776 100755 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/provider/AdHocCommandDataProvider.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/provider/AdHocCommandDataProvider.java @@ -29,10 +29,13 @@ import org.jivesoftware.smack.xml.XmlPullParser; import org.jivesoftware.smack.xml.XmlPullParserException; -import org.jivesoftware.smackx.commands.AdHocCommand; -import org.jivesoftware.smackx.commands.AdHocCommand.Action; import org.jivesoftware.smackx.commands.AdHocCommandNote; +import org.jivesoftware.smackx.commands.SpecificErrorCondition; import org.jivesoftware.smackx.commands.packet.AdHocCommandData; +import org.jivesoftware.smackx.commands.packet.AdHocCommandData.Action; +import org.jivesoftware.smackx.commands.packet.AdHocCommandData.AllowedAction; +import org.jivesoftware.smackx.commands.packet.AdHocCommandDataBuilder; +import org.jivesoftware.smackx.xdata.packet.DataForm; import org.jivesoftware.smackx.xdata.provider.DataFormProvider; /** @@ -44,64 +47,69 @@ public class AdHocCommandDataProvider extends IqProvider { @Override public AdHocCommandData parse(XmlPullParser parser, int initialDepth, IqData iqData, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException { - boolean done = false; - AdHocCommandData adHocCommandData = new AdHocCommandData(); + String commandNode = parser.getAttributeValue("node"); + AdHocCommandDataBuilder builder = AdHocCommandData.builder(commandNode, iqData); DataFormProvider dataFormProvider = new DataFormProvider(); - XmlPullParser.Event eventType; - String elementName; - String namespace; - adHocCommandData.setSessionID(parser.getAttributeValue("", "sessionid")); - adHocCommandData.setNode(parser.getAttributeValue("", "node")); + String sessionId = parser.getAttributeValue("sessionid"); + builder.setSessionId(sessionId); // Status String status = parser.getAttributeValue("", "status"); - if (AdHocCommand.Status.executing.toString().equalsIgnoreCase(status)) { - adHocCommandData.setStatus(AdHocCommand.Status.executing); + if (AdHocCommandData.Status.executing.toString().equalsIgnoreCase(status)) { + builder.setStatus(AdHocCommandData.Status.executing); } - else if (AdHocCommand.Status.completed.toString().equalsIgnoreCase(status)) { - adHocCommandData.setStatus(AdHocCommand.Status.completed); + else if (AdHocCommandData.Status.completed.toString().equalsIgnoreCase(status)) { + builder.setStatus(AdHocCommandData.Status.completed); } - else if (AdHocCommand.Status.canceled.toString().equalsIgnoreCase(status)) { - adHocCommandData.setStatus(AdHocCommand.Status.canceled); + else if (AdHocCommandData.Status.canceled.toString().equalsIgnoreCase(status)) { + builder.setStatus(AdHocCommandData.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); + Action realAction = Action.valueOf(action); + if (realAction == null) { + throw new SmackParsingException("Invalid value for action attribute: " + action); } + + builder.setAction(realAction); } - while (!done) { - eventType = parser.next(); - namespace = parser.getNamespace(); - if (eventType == XmlPullParser.Event.START_ELEMENT) { + + // TODO: Improve parsing below. Currently, the next actions like are not checked for the correct position. + outerloop: + while (true) { + String elementName; + XmlPullParser.Event event = parser.next(); + String namespace = parser.getNamespace(); + switch (event) { + case START_ELEMENT: elementName = parser.getName(); - if (parser.getName().equals("actions")) { - String execute = parser.getAttributeValue("", "execute"); + switch (elementName) { + case "actions": + String execute = parser.getAttributeValue("execute"); if (execute != null) { - adHocCommandData.setExecuteAction(AdHocCommand.Action.valueOf(execute)); + builder.setExecuteAction(AllowedAction.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"); + break; + case "next": + builder.addAction(AllowedAction.next); + break; + case "complete": + builder.addAction(AllowedAction.complete); + break; + case "prev": + builder.addAction(AllowedAction.prev); + break; + case "x": + if (namespace.equals("jabber:x:data")) { + DataForm form = dataFormProvider.parse(parser); + builder.setForm(form); + } + break; + case "note": + String typeString = parser.getAttributeValue("type"); AdHocCommandNote.Type type; if (typeString != null) { type = AdHocCommandNote.Type.valueOf(typeString); @@ -110,61 +118,67 @@ else if (parser.getName().equals("note")) { type = AdHocCommandNote.Type.info; } String value = parser.nextText(); - adHocCommandData.addNote(new AdHocCommandNote(type, value)); - } - else if (parser.getName().equals("error")) { + builder.addNote(new AdHocCommandNote(type, value)); + break; + case "error": StanzaError error = PacketParserUtils.parseError(parser); - adHocCommandData.setError(error); + builder.setError(error); + break; } - } - else if (eventType == XmlPullParser.Event.END_ELEMENT) { + break; + case END_ELEMENT: if (parser.getName().equals("command")) { - done = true; + break outerloop; } + break; + default: + // Catch all for incomplete switch (MissingCasesInEnumSwitch) statement. + break; } } - return adHocCommandData; + + return builder.build(); } public static class BadActionError extends ExtensionElementProvider { @Override public AdHocCommandData.SpecificError parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) { - return new AdHocCommandData.SpecificError(AdHocCommand.SpecificErrorCondition.badAction); + return new AdHocCommandData.SpecificError(SpecificErrorCondition.badAction); } } public static class MalformedActionError extends ExtensionElementProvider { @Override public AdHocCommandData.SpecificError parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) { - return new AdHocCommandData.SpecificError(AdHocCommand.SpecificErrorCondition.malformedAction); + return new AdHocCommandData.SpecificError(SpecificErrorCondition.malformedAction); } } public static class BadLocaleError extends ExtensionElementProvider { @Override public AdHocCommandData.SpecificError parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) { - return new AdHocCommandData.SpecificError(AdHocCommand.SpecificErrorCondition.badLocale); + return new AdHocCommandData.SpecificError(SpecificErrorCondition.badLocale); } } public static class BadPayloadError extends ExtensionElementProvider { @Override public AdHocCommandData.SpecificError parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) { - return new AdHocCommandData.SpecificError(AdHocCommand.SpecificErrorCondition.badPayload); + return new AdHocCommandData.SpecificError(SpecificErrorCondition.badPayload); } } public static class BadSessionIDError extends ExtensionElementProvider { @Override public AdHocCommandData.SpecificError parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) { - return new AdHocCommandData.SpecificError(AdHocCommand.SpecificErrorCondition.badSessionid); + return new AdHocCommandData.SpecificError(SpecificErrorCondition.badSessionid); } } public static class SessionExpiredError extends ExtensionElementProvider { @Override public AdHocCommandData.SpecificError parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) { - return new AdHocCommandData.SpecificError(AdHocCommand.SpecificErrorCondition.sessionExpired); + return new AdHocCommandData.SpecificError(SpecificErrorCondition.sessionExpired); } } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/form/FillableForm.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/form/FillableForm.java index 159c20544a..c14990a9a1 100644 --- a/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/form/FillableForm.java +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/form/FillableForm.java @@ -270,4 +270,8 @@ public DataForm getDataFormToSubmit() { return builder.build(); } + public SubmitForm getSubmitForm() { + DataForm form = getDataFormToSubmit(); + return new SubmitForm(form); + } } diff --git a/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/form/SubmitForm.java b/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/form/SubmitForm.java new file mode 100644 index 0000000000..f317dda275 --- /dev/null +++ b/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/form/SubmitForm.java @@ -0,0 +1,31 @@ +/** + * + * Copyright 2023 Florian Schmaus + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smackx.xdata.form; + +import org.jivesoftware.smackx.xdata.packet.DataForm; + +public class SubmitForm extends FilledForm { + + public SubmitForm(DataForm dataForm) { + super(dataForm); + + if (dataForm.getType() != DataForm.Type.submit) { + throw new IllegalArgumentException(); + } + } + +} diff --git a/smack-extensions/src/test/java/org/jivesoftware/smackx/commands/provider/CommandsProviderTest.java b/smack-extensions/src/test/java/org/jivesoftware/smackx/commands/provider/CommandsProviderTest.java index 68d2098b70..d8b0e734fd 100644 --- a/smack-extensions/src/test/java/org/jivesoftware/smackx/commands/provider/CommandsProviderTest.java +++ b/smack-extensions/src/test/java/org/jivesoftware/smackx/commands/provider/CommandsProviderTest.java @@ -23,7 +23,6 @@ import org.jivesoftware.smack.packet.StanzaError; import org.jivesoftware.smack.util.PacketParserUtils; -import org.jivesoftware.smackx.commands.AdHocCommand; import org.jivesoftware.smackx.commands.packet.AdHocCommandData; import org.junit.jupiter.api.Test; @@ -41,7 +40,7 @@ public void parseErrorWithRequest() throws Exception { final AdHocCommandData adHocIq = (AdHocCommandData) requestStanza; assertEquals(IQ.Type.error, adHocIq.getType()); - assertEquals(AdHocCommand.Action.execute, adHocIq.getAction()); + assertEquals(AdHocCommandData.Action.execute, adHocIq.getAction()); StanzaError error = adHocIq.getError(); assertEquals(StanzaError.Type.CANCEL, error.getType()); diff --git a/smack-extensions/src/test/java/org/jivesoftware/smackx/xdata/form/FillableFormTest.java b/smack-extensions/src/test/java/org/jivesoftware/smackx/xdata/form/FillableFormTest.java new file mode 100644 index 0000000000..1e495fe60d --- /dev/null +++ b/smack-extensions/src/test/java/org/jivesoftware/smackx/xdata/form/FillableFormTest.java @@ -0,0 +1,44 @@ +/** + * + * Copyright 2024 Florian Schmaus. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smackx.xdata.form; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.jivesoftware.smackx.xdata.FormField; +import org.jivesoftware.smackx.xdata.packet.DataForm; + +import org.junit.jupiter.api.Test; + +public class FillableFormTest { + + @Test + public void testThrowOnIncompleteyFilled() { + FormField fieldA = FormField.textSingleBuilder("a").setRequired().build(); + FormField fieldB = FormField.textSingleBuilder("b").setRequired().build(); + DataForm form = DataForm.builder(DataForm.Type.form) + .addField(fieldA) + .addField(fieldB) + .build(); + + FillableForm fillableForm = new FillableForm(form); + fillableForm.setAnswer("a", 42); + + IllegalStateException ise = assertThrows(IllegalStateException.class, () -> fillableForm.getSubmitForm()); + assertTrue(ise.getMessage().startsWith("Not all required fields filled. ")); + } +} diff --git a/smack-integration-test/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandIntegrationTest.java b/smack-integration-test/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandIntegrationTest.java new file mode 100644 index 0000000000..b4821f48ed --- /dev/null +++ b/smack-integration-test/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandIntegrationTest.java @@ -0,0 +1,353 @@ +/** + * + * Copyright 2023 Florian Schmaus + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jivesoftware.smackx.commands; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.jivesoftware.smack.SmackException.NoResponseException; +import org.jivesoftware.smack.SmackException.NotConnectedException; +import org.jivesoftware.smack.XMPPException.XMPPErrorException; +import org.jivesoftware.smack.packet.StanzaError; +import org.jivesoftware.smackx.commands.packet.AdHocCommandData; +import org.jivesoftware.smackx.commands.packet.AdHocCommandDataBuilder; +import org.jivesoftware.smackx.commands.packet.AdHocCommandDataBuilder.NextStage; +import org.jivesoftware.smackx.commands.packet.AdHocCommandDataBuilder.PreviousStage; +import org.jivesoftware.smackx.xdata.FormField; +import org.jivesoftware.smackx.xdata.form.FillableForm; +import org.jivesoftware.smackx.xdata.form.SubmitForm; +import org.jivesoftware.smackx.xdata.packet.DataForm; + +import org.igniterealtime.smack.inttest.AbstractSmackIntegrationTest; +import org.igniterealtime.smack.inttest.SmackIntegrationTestEnvironment; +import org.igniterealtime.smack.inttest.annotations.SmackIntegrationTest; + +public class AdHocCommandIntegrationTest extends AbstractSmackIntegrationTest { + + public AdHocCommandIntegrationTest(SmackIntegrationTestEnvironment environment) { + super(environment); + } + + @SmackIntegrationTest + public void singleStageAdHocCommandTest() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + AdHocCommandManager manOne = AdHocCommandManager.getInstance(conOne); + AdHocCommandManager manTwo = AdHocCommandManager.getInstance(conTwo); + + String commandNode = "test-list"; + String commandName = "Return a list for testing purposes"; + AdHocCommandHandlerFactory factory = (String node, String name, String sessionId) -> { + return new AdHocCommandHandler.SingleStage(node, name, sessionId) { + @Override + public AdHocCommandData executeSingleStage(AdHocCommandDataBuilder response) { + FormField field = FormField.textPrivateBuilder("my-field").build(); + DataForm form = DataForm.builder(DataForm.Type.result).addField(field).build(); + + response.setForm(form); + + return response.build(); + } + }; + }; + manOne.registerCommand(commandNode, commandName, factory); + try { + AdHocCommand command = manTwo.getRemoteCommand(conOne.getUser(), commandNode); + + AdHocCommandResult result = command.execute(); + AdHocCommandData response = result.getResponse(); + DataForm form = response.getForm(); + FormField field = form.getField("my-field"); + assertNotNull(field); + } finally { + manOne.unregisterCommand(commandNode); + } + } + + private static class MyMultiStageAdHocCommandServer extends AdHocCommandHandler { + + private Integer a; + private Integer b; + + private static DataForm createDataForm(String variableName) { + FormField field = FormField.textSingleBuilder(variableName).setRequired().build(); + return DataForm.builder(DataForm.Type.form) + .setTitle("Variable " + variableName) + .setInstructions("Please provide an integer variable " + variableName) + .addField(field) + .build(); + } + + private static DataForm createDataFormOp() { + FormField field = FormField.listSingleBuilder("op") + .setLabel("Arthimetic Operation") + .setRequired() + .addOption("+") + .addOption("-") + .build(); + return DataForm.builder(DataForm.Type.form) + .setTitle("Operation") + .setInstructions("Please select the arithmetic operation to be performed with a and b") + .addField(field) + .build(); + } + private static final DataForm dataFormAskingForA = createDataForm("a"); + private static final DataForm dataFormAskingForB = createDataForm("b"); + private static final DataForm dataFormAskingForOp = createDataFormOp(); + + MyMultiStageAdHocCommandServer(String node, String name, String sessionId) { + super(node, name, sessionId); + } + + @Override + protected AdHocCommandData execute(AdHocCommandDataBuilder response) throws XMPPErrorException { + return response.setForm(dataFormAskingForA).setStatusExecuting(PreviousStage.none, + NextStage.nonFinal).build(); + } + + // TODO: Add API for every case where we return null or throw below. + private static Integer extractIntegerField(SubmitForm form, String fieldName) throws XMPPErrorException { + FormField field = form.getField(fieldName); + if (field == null) + throw newBadRequestException("Submitted form does not contain a field of name " + fieldName); + + String fieldValue = field.getFirstValue(); + if (fieldValue == null) + throw newBadRequestException("Submitted form contains field of name " + fieldName + " without value"); + + try { + return Integer.parseInt(fieldValue); + } catch (NumberFormatException e) { + throw newBadRequestException("Submitted form contains field of name " + fieldName + " with value " + fieldValue + " that is not an integer"); + } + } + + @Override + protected AdHocCommandData next(AdHocCommandDataBuilder response, SubmitForm submittedForm) + throws XMPPErrorException { + DataForm form; + switch (getCurrentStage()) { + case 2: + a = extractIntegerField(submittedForm, "a"); + form = dataFormAskingForB; + response.setStatusExecuting(PreviousStage.exists, NextStage.nonFinal); + break; + case 3: + b = extractIntegerField(submittedForm, "b"); + form = dataFormAskingForOp; + response.setStatusExecuting(PreviousStage.exists, NextStage.isFinal); + break; + case 4: + // Ad-Hoc Commands particularity: Can get to 'complete' via 'next'. + return complete(response, submittedForm); + default: + throw new IllegalStateException(); + } + + return response.setForm(form).build(); + } + + @Override + protected AdHocCommandData complete(AdHocCommandDataBuilder response, SubmitForm submittedForm) + throws XMPPErrorException { + if (getCurrentStage() != 4) { + throw new IllegalStateException(); + } + + if (a == null || b == null) { + throw new IllegalStateException(); + } + + String op = submittedForm.getField("op").getFirstValue(); + + int result; + switch (op) { + case "+": + result = a + b; + break; + case "-": + result = a - b; + break; + default: + throw newBadRequestException("Submitted operation " + op + " is neither + nor -"); + } + + response.setStatusCompleted(); + + FormField field = FormField.textSingleBuilder("result").setValue(result).build(); + DataForm form = DataForm.builder(DataForm.Type.result).setTitle("Result").addField(field).build(); + + return response.setForm(form).build(); + } + + @Override + protected AdHocCommandData prev(AdHocCommandDataBuilder response) throws XMPPErrorException { + switch (getCurrentStage()) { + case 1: + return execute(response); + case 2: + return response.setForm(dataFormAskingForA) + .setStatusExecuting(PreviousStage.exists, NextStage.nonFinal) + .build(); + case 3: + return response.setForm(dataFormAskingForB) + .setStatusExecuting(PreviousStage.exists, NextStage.isFinal) + .build(); + default: + throw new IllegalStateException(); + } + } + + @Override + public void cancel() { + } + + } + + @SmackIntegrationTest + public void multiStageAdHocCommandTest() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + AdHocCommandManager manOne = AdHocCommandManager.getInstance(conOne); + AdHocCommandManager manTwo = AdHocCommandManager.getInstance(conTwo); + + String commandNode = "my-multi-stage-command"; + String commandName = "An example multi-sage ad-hoc command"; + AdHocCommandHandlerFactory factory = (String node, String name, String sessionId) -> { + return new MyMultiStageAdHocCommandServer(node, name, sessionId); + }; + manOne.registerCommand(commandNode, commandName, factory); + + try { + AdHocCommand command = manTwo.getRemoteCommand(conOne.getUser(), commandNode); + + AdHocCommandResult.StatusExecuting result = command.execute().asExecutingOrThrow(); + + FillableForm form = result.getFillableForm(); + form.setAnswer("a", 42); + + SubmitForm submitForm = form.getSubmitForm(); + + + result = command.next(submitForm).asExecutingOrThrow(); + + form = result.getFillableForm(); + form.setAnswer("b", 23); + + submitForm = form.getSubmitForm(); + + + result = command.next(submitForm).asExecutingOrThrow(); + + form = result.getFillableForm(); + form.setAnswer("op", "+"); + + submitForm = form.getSubmitForm(); + + AdHocCommandResult.StatusCompleted completed = command.complete(submitForm).asCompletedOrThrow(); + + String operationResult = completed.getResponse().getForm().getField("result").getFirstValue(); + assertEquals("65", operationResult); + } finally { + manTwo.unregisterCommand(commandNode); + } + } + + @SmackIntegrationTest + public void multiStageWithPrevAdHocCommandTest() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + AdHocCommandManager manOne = AdHocCommandManager.getInstance(conOne); + AdHocCommandManager manTwo = AdHocCommandManager.getInstance(conTwo); + + String commandNode = "my-multi-stage-with-prev-command"; + String commandName = "An example multi-sage ad-hoc command"; + AdHocCommandHandlerFactory factory = (String node, String name, String sessionId) -> { + return new MyMultiStageAdHocCommandServer(node, name, sessionId); + }; + manOne.registerCommand(commandNode, commandName, factory); + + try { + AdHocCommand command = manTwo.getRemoteCommand(conOne.getUser(), commandNode); + + AdHocCommandResult.StatusExecuting result = command.execute().asExecutingOrThrow(); + + FillableForm form = result.getFillableForm(); + form.setAnswer("a", 42); + + SubmitForm submitForm = form.getSubmitForm(); + + command.next(submitForm).asExecutingOrThrow(); + + + // Ups, I wanted a different value for 'a', lets execute 'prev' to get back to the previous stage. + result = command.prev().asExecutingOrThrow(); + + form = result.getFillableForm(); + form.setAnswer("a", 77); + + submitForm = form.getSubmitForm(); + + + result = command.next(submitForm).asExecutingOrThrow(); + + form = result.getFillableForm(); + form.setAnswer("b", 23); + + submitForm = form.getSubmitForm(); + + + result = command.next(submitForm).asExecutingOrThrow(); + + form = result.getFillableForm(); + form.setAnswer("op", "+"); + + submitForm = form.getSubmitForm(); + + AdHocCommandResult.StatusCompleted completed = command.complete(submitForm).asCompletedOrThrow(); + + String operationResult = completed.getResponse().getForm().getField("result").getFirstValue(); + assertEquals("100", operationResult); + } finally { + manTwo.unregisterCommand(commandNode); + } + } + + @SmackIntegrationTest + public void multiStageInvalidArgAdHocCommandTest() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { + AdHocCommandManager manOne = AdHocCommandManager.getInstance(conOne); + AdHocCommandManager manTwo = AdHocCommandManager.getInstance(conTwo); + + String commandNode = "my-multi-stage-invalid-arg-command"; + String commandName = "An example multi-sage ad-hoc command"; + AdHocCommandHandlerFactory factory = (String node, String name, String sessionId) -> { + return new MyMultiStageAdHocCommandServer(node, name, sessionId); + }; + manOne.registerCommand(commandNode, commandName, factory); + + try { + AdHocCommand command = manTwo.getRemoteCommand(conOne.getUser(), commandNode); + + AdHocCommandResult.StatusExecuting result = command.execute().asExecutingOrThrow(); + + FillableForm form = result.getFillableForm(); + form.setAnswer("a", "forty-two"); + + SubmitForm submitForm = form.getSubmitForm(); + + XMPPErrorException exception = assertThrows(XMPPErrorException.class, () -> command.next(submitForm)); + assertEquals(exception.getStanzaError().getCondition(), StanzaError.Condition.bad_request); + } finally { + manTwo.unregisterCommand(commandNode); + } + } +} diff --git a/smack-integration-test/src/main/java/org/jivesoftware/smackx/commands/package-info.java b/smack-integration-test/src/main/java/org/jivesoftware/smackx/commands/package-info.java new file mode 100644 index 0000000000..22bfe9d75d --- /dev/null +++ b/smack-integration-test/src/main/java/org/jivesoftware/smackx/commands/package-info.java @@ -0,0 +1,22 @@ +/** + * + * Copyright 2023 Florian Schmaus + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** + * Smacks implementation of XEP-0050: Ad-Hoc Commands. + */ +package org.jivesoftware.smackx.commands;