1
0
Fork 0
mirror of https://github.com/vanitasvitae/Smack.git synced 2024-11-22 12:02:05 +01:00

Re-work ad-hoc command (XEP-0050) implementation

Fixes SMACK-933.
This commit is contained in:
Florian Schmaus 2023-12-05 19:16:32 +01:00
parent dac06b04c3
commit 2337a446a5
21 changed files with 2062 additions and 1232 deletions

View file

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -44,8 +44,8 @@ import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.util.Objects; import org.jivesoftware.smack.util.Objects;
import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.commands.AdHocCommand;
import org.jivesoftware.smackx.commands.AdHocCommandManager; import org.jivesoftware.smackx.commands.AdHocCommandManager;
import org.jivesoftware.smackx.commands.RemoteCommand;
import org.jivesoftware.smackx.disco.ServiceDiscoveryManager; import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
import org.jivesoftware.smackx.disco.packet.DiscoverInfo; import org.jivesoftware.smackx.disco.packet.DiscoverInfo;
import org.jivesoftware.smackx.disco.packet.DiscoverItems; import org.jivesoftware.smackx.disco.packet.DiscoverItems;
@ -233,7 +233,7 @@ public final class MamManager extends Manager {
super(connection); super(connection);
this.archiveAddress = archiveAddress; this.archiveAddress = archiveAddress;
serviceDiscoveryManager = ServiceDiscoveryManager.getInstanceFor(connection); serviceDiscoveryManager = ServiceDiscoveryManager.getInstanceFor(connection);
adHocCommandManager = AdHocCommandManager.getAddHocCommandsManager(connection); adHocCommandManager = AdHocCommandManager.getInstance(connection);
} }
/** /**
@ -759,7 +759,7 @@ public final class MamManager extends Manager {
return false; return false;
} }
public RemoteCommand getAdvancedConfigurationCommand() throws InterruptedException, XMPPException, SmackException { public AdHocCommand getAdvancedConfigurationCommand() throws InterruptedException, XMPPException, SmackException {
DiscoverItems discoverItems = adHocCommandManager.discoverCommands(archiveAddress); DiscoverItems discoverItems = adHocCommandManager.discoverCommands(archiveAddress);
for (DiscoverItems.Item item : discoverItems.getItems()) { for (DiscoverItems.Item item : discoverItems.getItems()) {
if (item.getNode().equals(ADVANCED_CONFIG_NODE)) if (item.getNode().equals(ADVANCED_CONFIG_NODE))

View file

@ -1,6 +1,6 @@
/** /**
* *
* Copyright 2016-2020 Florian Schmaus * Copyright 2016-2023 Florian Schmaus
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -27,8 +27,9 @@ import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException.XMPPErrorException; import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smackx.commands.AdHocCommand;
import org.jivesoftware.smackx.commands.AdHocCommandManager; 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.jivesoftware.smackx.xdata.form.FillableForm;
import org.jxmpp.jid.EntityBareJid; import org.jxmpp.jid.EntityBareJid;
@ -56,37 +57,38 @@ public class ServiceAdministrationManager extends Manager {
public ServiceAdministrationManager(XMPPConnection connection) { public ServiceAdministrationManager(XMPPConnection connection) {
super(connection); super(connection);
adHocCommandManager = AdHocCommandManager.getAddHocCommandsManager(connection); adHocCommandManager = AdHocCommandManager.getInstance(connection);
} }
public RemoteCommand addUser() { public AdHocCommand addUser() {
return addUser(connection().getXMPPServiceDomain()); return addUser(connection().getXMPPServiceDomain());
} }
public RemoteCommand addUser(Jid service) { public AdHocCommand addUser(Jid service) {
return adHocCommandManager.getRemoteCommand(service, COMMAND_NODE_HASHSIGN + "add-user"); return adHocCommandManager.getRemoteCommand(service, COMMAND_NODE_HASHSIGN + "add-user");
} }
public void addUser(final EntityBareJid userJid, final String password) public void addUser(final EntityBareJid userJid, final String password)
throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
RemoteCommand command = addUser(); AdHocCommand command = addUser();
command.execute();
FillableForm answerForm = new FillableForm(command.getForm()); AdHocCommandResult.StatusExecuting commandExecutingResult = command.execute().asExecutingOrThrow();
FillableForm answerForm = commandExecutingResult.getFillableForm();
answerForm.setAnswer("accountjid", userJid); answerForm.setAnswer("accountjid", userJid);
answerForm.setAnswer("password", password); answerForm.setAnswer("password", password);
answerForm.setAnswer("password-verify", password); answerForm.setAnswer("password-verify", password);
command.execute(answerForm); AdHocCommandResult result = command.execute(answerForm);
assert command.isCompleted(); assert result.isCompleted();
} }
public RemoteCommand deleteUser() { public AdHocCommand deleteUser() {
return deleteUser(connection().getXMPPServiceDomain()); return deleteUser(connection().getXMPPServiceDomain());
} }
public RemoteCommand deleteUser(Jid service) { public AdHocCommand deleteUser(Jid service) {
return adHocCommandManager.getRemoteCommand(service, COMMAND_NODE_HASHSIGN + "delete-user"); return adHocCommandManager.getRemoteCommand(service, COMMAND_NODE_HASHSIGN + "delete-user");
} }
@ -98,14 +100,14 @@ public class ServiceAdministrationManager extends Manager {
public void deleteUser(Set<EntityBareJid> jidsToDelete) public void deleteUser(Set<EntityBareJid> jidsToDelete)
throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
RemoteCommand command = deleteUser(); AdHocCommand command = deleteUser();
command.execute(); AdHocCommandResult.StatusExecuting commandExecutingResult = command.execute().asExecutingOrThrow();
FillableForm answerForm = new FillableForm(command.getForm()); FillableForm answerForm = commandExecutingResult.getFillableForm();
answerForm.setAnswer("accountjids", jidsToDelete); answerForm.setAnswer("accountjids", jidsToDelete);
command.execute(answerForm); AdHocCommandResult result = command.execute(answerForm);
assert command.isCompleted(); assert result.isCompleted();
} }
} }

View file

@ -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
* <code>getForm</code> method retrieves a form with all the users.
* <p>
* Each command has a <code>node</code> that should be unique within a given JID.
* </p>
* <p>
* 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).
* </p>
* All the actions may throw an XMPPException if there is a problem executing
* them. The <code>XMPPError</code> of that exception may have some specific
* information about the problem. The possible extensions are:
* <ul>
* <li><i>malformed-action</i>. Extension of a <i>bad-request</i> error.</li>
* <li><i>bad-action</i>. Extension of a <i>bad-request</i> error.</li>
* <li><i>bad-locale</i>. Extension of a <i>bad-request</i> error.</li>
* <li><i>bad-payload</i>. Extension of a <i>bad-request</i> error.</li>
* <li><i>bad-sessionid</i>. Extension of a <i>bad-request</i> error.</li>
* <li><i>session-expired</i>. Extension of a <i>not-allowed</i> error.</li>
* </ul>
* <p>
* See the <code>SpecificErrorCondition</code> class for detailed description
* of each one.
* </p>
* Use the <code>getSpecificErrorConditionFrom</code> to obtain the specific
* information from an <code>XMPPError</code>.
*
* @author Gabriel Guardincerri
* @author Florian Schmaus
*
*/
public abstract class AbstractAdHocCommand {
private final List<AdHocCommandData> requests = new ArrayList<>();
private final List<AdHocCommandResult> results = new ArrayList<>();
private final String node;
private final 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 <code>error</code> or <code>null</code> 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
* <code>OwnerJID</code>.
*
* @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<AdHocCommandNote> 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<AllowedAction> 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 <code>true</code> if this command is completed.
* @since 4.2
*/
public boolean isCompleted() {
return getStatus() == AdHocCommandData.Status.completed;
}
/**
* Returns true if the <code>action</code> is available in the current stage.
* The {@link Action#cancel cancel} action is always allowed. To define the
* available actions use the <code>addActionAvailable</code> 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<AllowedAction> actions = getActions();
return actions != null && actions.contains(executeAction);
}
}

View file

@ -16,193 +16,68 @@
*/ */
package org.jivesoftware.smackx.commands; package org.jivesoftware.smackx.commands;
import java.util.List;
import org.jivesoftware.smack.SmackException.NoResponseException; import org.jivesoftware.smack.SmackException.NoResponseException;
import org.jivesoftware.smack.SmackException.NotConnectedException; import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException.XMPPErrorException; 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.commands.packet.AdHocCommandData;
import org.jivesoftware.smackx.xdata.form.FillableForm; import org.jivesoftware.smackx.xdata.form.FillableForm;
import org.jivesoftware.smackx.xdata.form.SubmitForm;
import org.jivesoftware.smackx.xdata.packet.DataForm; import org.jivesoftware.smackx.xdata.packet.DataForm;
import org.jxmpp.jid.Jid; import org.jxmpp.jid.Jid;
/** /**
* An ad-hoc command is responsible for executing the provided service and * Represents a ad-hoc command invoked on a remote entity. Invoking one of the
* storing the result of the execution. Each new request will create a new * {@link #execute()}, {@link #next(SubmitForm)},
* instance of the command, allowing information related to executions to be * {@link #prev()}, {@link #cancel()} or
* stored in it. For example suppose that a command that retrieves the list of * {@link #complete(SubmitForm)} actions results in executing that
* users on a server is implemented. When the command is executed it gets that * action on the remote entity. In response to that action the internal state
* list and the result is stored as a form in the command instance, i.e. the * of the this command instance will change. For example, if the command is a
* <code>getForm</code> method retrieves a form with all the users. * single stage command, then invoking the execute action will execute this
* <p> * action in the remote location. After that the local instance will have a
* Each command has a <code>node</code> that should be unique within a given JID. * state of "completed" and a form or notes that applies.
* </p>
* <p>
* 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).
* </p>
* All the actions may throw an XMPPException if there is a problem executing
* them. The <code>XMPPError</code> of that exception may have some specific
* information about the problem. The possible extensions are:
* <ul>
* <li><i>malformed-action</i>. Extension of a <i>bad-request</i> error.</li>
* <li><i>bad-action</i>. Extension of a <i>bad-request</i> error.</li>
* <li><i>bad-locale</i>. Extension of a <i>bad-request</i> error.</li>
* <li><i>bad-payload</i>. Extension of a <i>bad-request</i> error.</li>
* <li><i>bad-sessionid</i>. Extension of a <i>bad-request</i> error.</li>
* <li><i>session-expired</i>. Extension of a <i>not-allowed</i> error.</li>
* </ul>
* <p>
* See the <code>SpecificErrorCondition</code> class for detailed description
* of each one.
* </p>
* Use the <code>getSpecificErrorConditionFrom</code> to obtain the specific
* information from an <code>XMPPError</code>.
* *
* @author Gabriel Guardincerri * @author Gabriel Guardincerri
* @author Florian Schmaus
* *
*/ */
public abstract class AdHocCommand { public class AdHocCommand extends AbstractAdHocCommand {
// 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();
}
/** /**
* Returns the specific condition of the <code>error</code> or <code>null</code> if the * The connection that is used to execute this command
* 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) { private final XMPPConnection connection;
// 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;
}
/** /**
* Set the human readable name of the command, usually used for * The full JID of the command host
* displaying in a UI.
*
* @param name the name.
*/ */
public void setName(String name) { private final Jid jid;
data.setName(name);
}
/** /**
* Returns the human readable name of the command. * Creates a new RemoteCommand that uses an specific connection to execute a
* command identified by <code>node</code> in the host identified by
* <code>jid</code>
* *
* @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() { protected AdHocCommand(XMPPConnection connection, String node, Jid jid) {
return data.getName(); super(node);
this.connection = Objects.requireNonNull(connection);
this.jid = Objects.requireNonNull(jid);
} }
/** public Jid getOwnerJID() {
* Sets the unique identifier of the command. This value must be unique for return jid;
* the <code>OwnerJID</code>.
*
* @param node the unique identifier of the command.
*/
public void setNode(String node) {
data.setNode(node);
} }
/** @Override
* Returns the unique identifier of the command. It is unique for the public final void cancel() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
* <code>OwnerJID</code>. executeAction(AdHocCommandData.Action.cancel);
*
* @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<AdHocCommandNote> 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);
} }
/** /**
@ -210,12 +85,15 @@ public abstract class AdHocCommand {
* command. It is invoked on every command. If there is a problem executing * command. It is invoked on every command. If there is a problem executing
* the command it throws an XMPPException. * the command it throws an XMPPException.
* *
* @return an ad-hoc command result.
* @throws NoResponseException if there was no response from the remote entity. * @throws NoResponseException if there was no response from the remote entity.
* @throws XMPPErrorException if there is an error executing the command. * @throws XMPPErrorException if there is an error executing the command.
* @throws NotConnectedException if the XMPP connection is not connected. * @throws NotConnectedException if the XMPP connection is not connected.
* @throws InterruptedException if the calling thread was interrupted. * @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 * Executes the next action of the command with the information provided in
@ -224,13 +102,16 @@ public abstract class AdHocCommand {
* or more stages. If there is a problem executing the command it throws an * or more stages. If there is a problem executing the command it throws an
* XMPPException. * 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 NoResponseException if there was no response from the remote entity.
* @throws XMPPErrorException if there is a problem executing the command. * @throws XMPPErrorException if there is a problem executing the command.
* @throws NotConnectedException if the XMPP connection is not connected. * @throws NotConnectedException if the XMPP connection is not connected.
* @throws InterruptedException if the calling thread was interrupted. * @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 * Completes the command execution with the information provided in the
@ -239,14 +120,16 @@ public abstract class AdHocCommand {
* or more stages. If there is a problem executing the command it throws an * or more stages. If there is a problem executing the command it throws an
* XMPPException. * 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 NoResponseException if there was no response from the remote entity.
* @throws XMPPErrorException if there is a problem executing the command. * @throws XMPPErrorException if there is a problem executing the command.
* @throws NotConnectedException if the XMPP connection is not connected. * @throws NotConnectedException if the XMPP connection is not connected.
* @throws InterruptedException if the calling thread was interrupted. * @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 * Goes to the previous stage. The requester is asking to re-send the
@ -254,224 +137,70 @@ public abstract class AdHocCommand {
* the previous one. If there is a problem executing the command it throws * the previous one. If there is a problem executing the command it throws
* an XMPPException. * an XMPPException.
* *
* @return an ad-hoc command result.
* @throws NoResponseException if there was no response from the remote entity. * @throws NoResponseException if there was no response from the remote entity.
* @throws XMPPErrorException if there is a problem executing the command. * @throws XMPPErrorException if there is a problem executing the command.
* @throws NotConnectedException if the XMPP connection is not connected. * @throws NotConnectedException if the XMPP connection is not connected.
* @throws InterruptedException if the calling thread was interrupted. * @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 * Executes the default action of the command with the information provided
* the execution. If there is a problem executing the command it throws an * in the Form. This form must be the answer form of the previous stage. If
* XMPPException. * there is a problem executing the command it throws an XMPPException.
* *
* @throws NoResponseException if there was no response from the remote entity. * @param form the form answer of the previous stage.
* @throws XMPPErrorException if there is a problem executing the command. * @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 NotConnectedException if the XMPP connection is not connected.
* @throws InterruptedException if the calling thread was interrupted. * @throws InterruptedException if the calling thread was interrupted.
*/ */
public abstract void cancel() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException; public final AdHocCommandResult execute(FillableForm form) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
return executeAction(AdHocCommandData.Action.execute, form.getDataFormToSubmit());
}
private AdHocCommandResult executeAction(AdHocCommandData.Action action) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
return executeAction(action, null);
}
/** /**
* Returns a collection with the allowed actions based on the current stage. * Executes the <code>action</code> with the <code>form</code>.
* Possible actions are: {@link Action#prev prev}, {@link Action#next next} and * The action could be any of the available actions. The form must
* {@link Action#complete complete}. This method will be only invoked for commands that * be the answer of the previous stage. It can be <code>null</code> if it is the first stage.
* have one or more stages.
* *
* @return a collection with the allowed actions based on the current stage * @param action the action to execute.
* as defined in the SessionData. * @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.
*/ */
protected List<Action> getActions() { private synchronized AdHocCommandResult executeAction(AdHocCommandData.Action action, DataForm form) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
return data.getActions(); AdHocCommandData request = AdHocCommandData.builder(getNode(), connection)
.ofType(IQ.Type.set)
.to(getOwnerJID())
.setSessionId(getSessionId())
.setAction(action)
.setForm(form)
.build();
addRequest(request);
AdHocCommandData response = connection.sendIqRequestAndWaitForResponse(request);
// The Ad-Hoc service ("server") may have generated a session id for us.
String sessionId = response.getSessionId();
if (sessionId != null) {
setSessionId(sessionId);
} }
/** AdHocCommandResult result = AdHocCommandResult.from(response);
* Add an action to the current stage available actions. This should be used addResult(result);
* when creating a response. return result;
*
* @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();
}
/**
* 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();
}
/**
* Check if this command has been completed successfully.
*
* @return <code>true</code> 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 <code>action</code> is available in the current stage.
* The {@link Action#cancel cancel} action is always allowed. To define the
* available actions use the <code>addActionAvailable</code> 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.
*/
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,
/**
* The command should be canceled.
*/
cancel,
/**
* The command should be digress to the previous stage of execution.
*/
prev,
/**
* 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;
}
@Override
public String toString() {
return value;
}
}
} }

View file

@ -0,0 +1,181 @@
/**
*
* 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:<ul>
* <li>Node</li>
* <li>Name</li>
* <li>Session ID</li>
* <li>Current Stage</li>
* <li>Available actions</li>
* <li>Default action</li>
* </ul>
* 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, IllegalStateException;
protected abstract AdHocCommandData next(AdHocCommandDataBuilder response, SubmitForm submittedForm)
throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException,
IllegalStateException;
protected abstract AdHocCommandData complete(AdHocCommandDataBuilder response, SubmitForm submittedForm)
throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException,
IllegalStateException;
protected abstract AdHocCommandData prev(AdHocCommandDataBuilder response) throws NoResponseException,
XMPPErrorException, NotConnectedException, InterruptedException, IllegalStateException;
/**
* 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);
}
}
}

View file

@ -19,28 +19,31 @@ package org.jivesoftware.smackx.commands;
import java.lang.reflect.InvocationTargetException; 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, * 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 * 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 * a Class object instead. For more details, see
* {@link AdHocCommandManager#registerCommand(String, String, LocalCommandFactory)}. * {@link AdHocCommandManager#registerCommand(String, String, AdHocCommandHandlerFactory)}.
* *
* @author Matt Tucker * @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. * @return a LocalCommand instance.
* @throws InstantiationException if creating an instance failed. * @throws InstantiationException if creating an instance failed.
* @throws IllegalAccessException if creating an instance is not allowed. * @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 InvocationTargetException if a reflection-based method or constructor invocation threw.
* @throws IllegalArgumentException if an illegal argument was given. * @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;
} }

View file

@ -17,6 +17,7 @@
package org.jivesoftware.smackx.commands; package org.jivesoftware.smackx.commands;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
@ -44,16 +45,17 @@ import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.StanzaError; import org.jivesoftware.smack.packet.StanzaError;
import org.jivesoftware.smack.util.StringUtils; 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;
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.AbstractNodeInformationProvider;
import org.jivesoftware.smackx.disco.ServiceDiscoveryManager; import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
import org.jivesoftware.smackx.disco.packet.DiscoverInfo; import org.jivesoftware.smackx.disco.packet.DiscoverInfo;
import org.jivesoftware.smackx.disco.packet.DiscoverItems; 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.jivesoftware.smackx.xdata.packet.DataForm;
import org.jxmpp.jid.EntityFullJid;
import org.jxmpp.jid.Jid; import org.jxmpp.jid.Jid;
/** /**
@ -65,6 +67,7 @@ import org.jxmpp.jid.Jid;
* get an instance of this class. * get an instance of this class.
* *
* @author Gabriel Guardincerri * @author Gabriel Guardincerri
* @author Florian Schmaus
*/ */
public final class AdHocCommandManager extends Manager { public final class AdHocCommandManager extends Manager {
public static final String NAMESPACE = "http://jabber.org/protocol/commands"; 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. * 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 * 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() { XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() {
@Override @Override
public void connectionCreated(XMPPConnection connection) { public void connectionCreated(XMPPConnection connection) {
getAddHocCommandsManager(connection); getInstance(connection);
} }
}); });
} }
@ -102,8 +105,21 @@ public final class AdHocCommandManager extends Manager {
* *
* @param connection the XMPP connection. * @param connection the XMPP connection.
* @return the AdHocCommandManager associated with the 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 <code>AdHocCommandManager</code> related to the
* <code>connection</code>.
*
* @param connection the XMPP connection.
* @return the AdHocCommandManager associated with the connection.
*/
public static synchronized AdHocCommandManager getInstance(XMPPConnection connection) {
AdHocCommandManager ahcm = instances.get(connection); AdHocCommandManager ahcm = instances.get(connection);
if (ahcm == null) { if (ahcm == null) {
ahcm = new AdHocCommandManager(connection); ahcm = new AdHocCommandManager(connection);
@ -117,7 +133,8 @@ public final class AdHocCommandManager extends Manager {
* Value=command. Command node matches the node attribute sent by command * Value=command. Command node matches the node attribute sent by command
* requesters. * requesters.
*/ */
private final Map<String, AdHocCommandInfo> commands = new ConcurrentHashMap<>(); // TODO: Change to Map once Smack's minimum Android API level is 24 or higher.
private final ConcurrentHashMap<String, AdHocCommandInfo> commands = new ConcurrentHashMap<>();
/** /**
* Map a command session ID with the instance LocalCommand. The LocalCommand * Map a command session ID with the instance LocalCommand. The LocalCommand
@ -125,10 +142,12 @@ public final class AdHocCommandManager extends Manager {
* the command execution. Note: Key=session ID, Value=LocalCommand. Session * the command execution. Note: Key=session ID, Value=LocalCommand. Session
* ID matches the sessionid attribute sent by command responders. * ID matches the sessionid attribute sent by command responders.
*/ */
private final Map<String, LocalCommand> executingCommands = new ConcurrentHashMap<>(); private final Map<String, AdHocCommandHandler> executingCommands = new ConcurrentHashMap<>();
private final ServiceDiscoveryManager serviceDiscoveryManager; private final ServiceDiscoveryManager serviceDiscoveryManager;
private int sessionTimeoutSecs = DEFAULT_SESSION_TIMEOUT_SECS;
private AdHocCommandManager(XMPPConnection connection) { private AdHocCommandManager(XMPPConnection connection) {
super(connection); super(connection);
this.serviceDiscoveryManager = ServiceDiscoveryManager.getInstanceFor(connection); this.serviceDiscoveryManager = ServiceDiscoveryManager.getInstanceFor(connection);
@ -148,13 +167,17 @@ public final class AdHocCommandManager extends Manager {
new AbstractNodeInformationProvider() { new AbstractNodeInformationProvider() {
@Override @Override
public List<DiscoverItems.Item> getNodeItems() { public List<DiscoverItems.Item> getNodeItems() {
List<DiscoverItems.Item> answer = new ArrayList<>(); List<DiscoverItems.Item> answer = new ArrayList<>();
Collection<AdHocCommandInfo> commandsList = getRegisteredCommands(); Collection<AdHocCommandInfo> 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) { for (AdHocCommandInfo info : commandsList) {
DiscoverItems.Item item = new DiscoverItems.Item( DiscoverItems.Item item = new DiscoverItems.Item(ourJid);
info.getOwnerJID());
item.setName(info.getName()); item.setName(info.getName());
item.setNode(info.getNode()); item.setNode(info.getNode());
answer.add(item); answer.add(item);
@ -166,18 +189,17 @@ public final class AdHocCommandManager extends Manager {
// The packet listener and the filter for processing some AdHoc Commands // The packet listener and the filter for processing some AdHoc Commands
// Packets // 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, connection.registerIQRequestHandler(new AbstractIqRequestHandler(AdHocCommandData.ELEMENT,
AdHocCommandData.NAMESPACE, IQ.Type.set, Mode.async) { AdHocCommandData.NAMESPACE, IQ.Type.set, Mode.async) {
@Override @Override
public IQ handleIQRequest(IQ iqRequest) { public IQ handleIQRequest(IQ iqRequest) {
AdHocCommandData requestData = (AdHocCommandData) iqRequest; AdHocCommandData requestData = (AdHocCommandData) iqRequest;
try { AdHocCommandData response = processAdHocCommand(requestData);
return processAdHocCommand(requestData); assert response.getStatus() != null || response.getType() == IQ.Type.error;
} return response;
catch (InterruptedException | NoResponseException | NotConnectedException e) {
LOGGER.log(Level.INFO, "processAdHocCommand threw exception", e);
return null;
}
} }
}); });
} }
@ -187,18 +209,21 @@ public final class AdHocCommandManager extends Manager {
* connection. The <code>node</code> is an unique identifier of that command for * connection. The <code>node</code> is an unique identifier of that command for
* the connection related to this command manager. The <code>name</code> is the * the connection related to this command manager. The <code>name</code> is the
* human readable name of the command. The <code>class</code> is the class of * human readable name of the command. The <code>class</code> 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. * constructor.
* *
* @param node the unique identifier of the command. * @param node the unique identifier of the command.
* @param name the human readable name 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<? extends LocalCommand> clazz) { public void registerCommand(String node, String name, final Class<? extends AdHocCommandHandler> clazz) throws NoSuchMethodException, SecurityException {
registerCommand(node, name, new LocalCommandFactory() { Constructor<? extends AdHocCommandHandler> constructor = clazz.getConstructor(String.class, String.class, String.class);
registerCommand(node, name, new AdHocCommandHandlerFactory() {
@Override @Override
public LocalCommand getInstance() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { public AdHocCommandHandler create(String node, String name, String sessionId) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
return clazz.getConstructor().newInstance(); return constructor.newInstance(node, name, sessionId);
} }
}); });
} }
@ -214,10 +239,12 @@ public final class AdHocCommandManager extends Manager {
* @param name the human readable name of the command. * @param name the human readable name of the command.
* @param factory a factory to create new instances of the command. * @param factory a factory to create new instances of the command.
*/ */
public void registerCommand(String node, final String name, LocalCommandFactory factory) { public synchronized void registerCommand(String node, final String name, AdHocCommandHandlerFactory factory) {
AdHocCommandInfo commandInfo = new AdHocCommandInfo(node, name, connection().getUser(), 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 // Set the NodeInformationProvider that will provide information about
// the added command // the added command
serviceDiscoveryManager.setNodeInformationProvider(node, serviceDiscoveryManager.setNodeInformationProvider(node,
@ -242,6 +269,14 @@ public final class AdHocCommandManager extends Manager {
}); });
} }
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 <code>jid</code> is a * Discover the commands of an specific JID. The <code>jid</code> is a
* full JID. * full JID.
@ -266,8 +301,8 @@ public final class AdHocCommandManager extends Manager {
* @param node the identifier of the command * @param node the identifier of the command
* @return a local instance equivalent to the remote command. * @return a local instance equivalent to the remote command.
*/ */
public RemoteCommand getRemoteCommand(Jid jid, String node) { public AdHocCommand getRemoteCommand(Jid jid, String node) {
return new RemoteCommand(connection(), node, jid); return new AdHocCommand(connection(), node, jid);
} }
/** /**
@ -291,240 +326,226 @@ public final class AdHocCommandManager extends Manager {
* <li>The action to execute is one of the available actions</li> * <li>The action to execute is one of the available actions</li>
* </ul> * </ul>
* *
* @param requestData TODO javadoc me please * @param request the incoming AdHoc command request.
* the stanza to process.
* @throws NotConnectedException if the XMPP connection is not connected.
* @throws NoResponseException if there was no response from the remote entity.
* @throws InterruptedException if the calling thread was interrupted.
*/ */
private IQ processAdHocCommand(AdHocCommandData requestData) throws NoResponseException, NotConnectedException, InterruptedException { private AdHocCommandData processAdHocCommand(AdHocCommandData request) {
// Creates the response with the corresponding data String sessionId = request.getSessionId();
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();
final AdHocCommandHandler command;
if (sessionId == null) { if (sessionId == null) {
String commandNode = request.getNode();
// A new execution request has been received. Check that the // A new execution request has been received. Check that the
// command exists // command exists
if (!commands.containsKey(commandNode)) { AdHocCommandInfo commandInfo = commands.get(commandNode);
if (commandInfo == null) {
// Requested command does not exist so return // Requested command does not exist so return
// item_not_found error. // 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 assert commandInfo.getNode().equals(commandNode);
sessionId = StringUtils.randomString(15);
try {
// Create a new instance of the command with the // Create a new instance of the command with the
// corresponding sessionid // corresponding session ID.
LocalCommand command;
try { try {
command = newInstanceOfCmd(commandNode, sessionId); command = commandInfo.getCommandInstance();
} }
catch (InstantiationException | IllegalAccessException | IllegalArgumentException catch (InstantiationException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException | NoSuchMethodException | SecurityException e) { | InvocationTargetException e) {
LOGGER.log(Level.WARNING, "Could not instanciate ad-hoc command server", e);
StanzaError xmppError = StanzaError.getBuilder() StanzaError xmppError = StanzaError.getBuilder()
.setCondition(StanzaError.Condition.internal_server_error) .setCondition(StanzaError.Condition.internal_server_error)
.setDescriptiveEnText(e.getMessage()) .setDescriptiveEnText(e.getMessage())
.build(); .build();
return respondError(response, xmppError); return respondError(request, null, xmppError);
} }
} else {
response.setType(IQ.Type.result); command = executingCommands.get(sessionId);
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);
}
Action action = requestData.getAction();
// If the action is unknown then respond an error.
if (action != null && action.equals(Action.unknown)) {
return respondError(response, StanzaError.Condition.bad_request,
AdHocCommand.SpecificErrorCondition.malformedAction);
}
// If the action is not execute, then it is an invalid action.
if (action != null && !action.equals(Action.execute)) {
return respondError(response, StanzaError.Condition.bad_request,
AdHocCommand.SpecificErrorCondition.badAction);
}
// Increase the state number, so the command knows in witch
// stage it is
command.incrementStage();
// Executes the command
command.execute();
if (command.isLastStage()) {
// If there is only one stage then the command is completed
response.setStatus(Status.completed);
}
else {
// Else it is still executing, and is registered to be
// available for the next call
response.setStatus(Status.executing);
executingCommands.put(sessionId, command);
// See if the session sweeper thread is scheduled. If not, start it.
maybeWindUpSessionSweeper();
}
// Sends the response packet
return response;
}
catch (XMPPErrorException e) {
// If there is an exception caused by the next, complete,
// prev or cancel method, then that error is returned to the
// requester.
StanzaError error = e.getStanzaError();
// 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);
}
}
else {
LocalCommand command = executingCommands.get(sessionId);
// Check that a command exists for the specified sessionID // Check that a command exists for the specified sessionID
// This also handles if the command was removed in the meanwhile // This also handles if the command was removed in the meanwhile
// of getting the key and the value of the map. // of getting the key and the value of the map.
if (command == null) { if (command == null) {
return respondError(response, StanzaError.Condition.bad_request, return respondError(request, null, StanzaError.Condition.bad_request,
AdHocCommand.SpecificErrorCondition.badSessionid); SpecificErrorCondition.badSessionid);
}
} }
// Check if the Session data has expired (default is 10 minutes)
long creationStamp = command.getCreationDate();
if (System.currentTimeMillis() - creationStamp > SESSION_TIMEOUT * 1000) {
// Remove the expired session
executingCommands.remove(sessionId);
// Answer a not_allowed error (session-expired) final AdHocCommandDataBuilder responseBuilder = AdHocCommandDataBuilder.buildResponseFor(request)
return respondError(response, StanzaError.Condition.not_allowed, .setSessionId(command.getSessionId());
AdHocCommand.SpecificErrorCondition.sessionExpired);
}
final AdHocCommandData response;
/* /*
* Since the requester could send two requests for the same * Since the requester could send two requests for the same
* executing command i.e. the same session id, all the execution of * executing command i.e. the same session id, all the execution of
* the action must be synchronized to avoid inconsistencies. * the action must be synchronized to avoid inconsistencies.
*/ */
synchronized (command) { synchronized (command) {
Action action = requestData.getAction(); command.addRequest(request);
// If the action is unknown the respond an error if (sessionId == null) {
if (action != null && action.equals(Action.unknown)) { response = processAdHocCommandOfNewSession(request, command, responseBuilder);
return respondError(response, StanzaError.Condition.bad_request, } else {
AdHocCommand.SpecificErrorCondition.malformedAction); response = processAdHocCommandOfExistingSession(request, command, responseBuilder);
} }
AdHocCommandResult commandResult = AdHocCommandResult.from(response);
command.addResult(commandResult);
}
return response;
}
private AdHocCommandData createResponseFrom(AdHocCommandData request, AdHocCommandDataBuilder response, XMPPErrorException exception, String sessionId) {
StanzaError error = exception.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 (error.getType() == StanzaError.Type.CANCEL) {
response.setStatus(AdHocCommandData.Status.canceled);
executingCommands.remove(sessionId);
return response.build();
}
return respondError(request, response, error);
}
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);
}
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);
}
AdHocCommandData.Action action = request.getAction();
// 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);
}
// 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);
}
if (response.isExecuting()) {
executingCommands.put(command.getSessionId(), command);
// See if the session sweeper thread is scheduled. If not, start it.
maybeWindUpSessionSweeper();
}
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 // If the user didn't specify an action or specify the execute
// action then follow the actual default execute action // action then follow the actual default execute action
if (action == null || Action.execute.equals(action)) { if (action == null || AdHocCommandData.Action.execute.equals(action)) {
action = command.getExecuteAction(); AllowedAction executeAction = command.getExecuteAction();
if (executeAction != null) {
action = executeAction.action;
}
} }
// Check that the specified action was previously // Check that the specified action was previously
// offered // offered
if (!command.isValidAction(action)) { if (!command.isValidAction(action)) {
return respondError(response, StanzaError.Condition.bad_request, return respondError(request, responseBuilder, StanzaError.Condition.bad_request,
AdHocCommand.SpecificErrorCondition.badAction); SpecificErrorCondition.badAction);
} }
AdHocCommandData response;
try { try {
// TODO: Check that all the required fields of the form are DataForm dataForm;
// TODO: filled, if not throw an exception. This will simplify the switch (action) {
// TODO: construction of new commands case next:
// Since all errors were passed, the response is now a
// result
response.setType(IQ.Type.result);
// Set the new data to the command.
command.setData(response);
if (Action.next.equals(action)) {
command.incrementStage(); command.incrementStage();
DataForm dataForm = requestData.getForm(); dataForm = request.getForm();
command.next(new FillableForm(dataForm)); response = command.next(responseBuilder, new SubmitForm(dataForm));
if (command.isLastStage()) { break;
// If it is the last stage then the command is case complete:
// completed
response.setStatus(Status.completed);
}
else {
// Otherwise it is still executing
response.setStatus(Status.executing);
}
}
else if (Action.complete.equals(action)) {
command.incrementStage(); command.incrementStage();
DataForm dataForm = requestData.getForm(); dataForm = request.getForm();
command.complete(new FillableForm(dataForm)); responseBuilder.setStatus(AdHocCommandData.Status.completed);
response.setStatus(Status.completed); response = command.complete(responseBuilder, new SubmitForm(dataForm));
// Remove the completed session // Remove the completed session
executingCommands.remove(sessionId); executingCommands.remove(command.getSessionId());
} break;
else if (Action.prev.equals(action)) { case prev:
command.decrementStage(); command.decrementStage();
command.prev(); response = command.prev(responseBuilder);
} break;
else if (Action.cancel.equals(action)) { case cancel:
command.cancel(); command.cancel();
response.setStatus(Status.canceled); responseBuilder.setStatus(AdHocCommandData.Status.canceled);
response = responseBuilder.build();
// Remove the canceled session // Remove the canceled session
executingCommands.remove(sessionId); 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; 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);
}
}
}
}
private boolean sessionSweeperScheduled; private boolean sessionSweeperScheduled;
private int getSessionRemovalTimeoutSecs() {
return sessionTimeoutSecs * 2;
}
private void sessionSweeper() { private void sessionSweeper() {
final long currentTime = System.currentTimeMillis(); final long currentTime = System.currentTimeMillis();
synchronized (this) { synchronized (this) {
for (Iterator<Map.Entry<String, LocalCommand>> it = executingCommands.entrySet().iterator(); it.hasNext();) { for (Iterator<Map.Entry<String, AdHocCommandHandler>> it = executingCommands.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, LocalCommand> entry = it.next(); Map.Entry<String, AdHocCommandHandler> entry = it.next();
LocalCommand command = entry.getValue(); AdHocCommandHandler command = entry.getValue();
long creationStamp = command.getCreationDate(); 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 // To remove it from the session list it waits for the double of
// the of time out time. This is to let // the of time out time. This is to let
// the requester know why his execution request is // the requester know why his execution request is
@ -532,7 +553,7 @@ public final class AdHocCommandManager extends Manager {
// after the time out, then once the user requests to // after the time out, then once the user requests to
// continue the execution he will received an // continue the execution he will received an
// invalid session error and not a time out error. // 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 // Remove the expired session
it.remove(); it.remove();
} }
@ -552,104 +573,100 @@ public final class AdHocCommandManager extends Manager {
} }
sessionSweeperScheduled = true; sessionSweeperScheduled = true;
schedule(this::sessionSweeper, 10, TimeUnit.SECONDS); schedule(this::sessionSweeper, getSessionRemovalTimeoutSecs() + 1, TimeUnit.SECONDS);
} }
/** /**
* Responds an error with an specific condition. * 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 condition the condition of the error.
*/ */
private static IQ respondError(AdHocCommandData response, private static AdHocCommandData respondError(AdHocCommandData request, AdHocCommandDataBuilder response,
StanzaError.Condition condition) { 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. * 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 condition the condition of the error.
* @param specificCondition the adhoc command error condition. * @param specificCondition the adhoc command error condition.
*/ */
private static IQ respondError(AdHocCommandData response, StanzaError.Condition condition, private static AdHocCommandData respondError(AdHocCommandData request, AdHocCommandDataBuilder response, StanzaError.Condition condition,
AdHocCommand.SpecificErrorCondition specificCondition) { SpecificErrorCondition specificCondition) {
StanzaError error = StanzaError.getBuilder(condition) StanzaError error = StanzaError.getBuilder(condition)
.addExtension(new AdHocCommandData.SpecificError(specificCondition)) .addExtension(new AdHocCommandData.SpecificError(specificCondition))
.build(); .build();
return respondError(response, error); return respondError(request, response, error);
} }
/** /**
* Responds an error with an specific 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. * @param error the error to send.
*/ */
private static IQ respondError(AdHocCommandData response, StanzaError error) { private static AdHocCommandData respondError(AdHocCommandData request, AdHocCommandDataBuilder response, StanzaError error) {
response.setType(IQ.Type.error); if (response == null) {
response.setError(error); return AdHocCommandDataBuilder.buildResponseFor(request, IQ.ResponseType.error).setError(error).build();
return response;
} }
/** // Response may be not of IQ type error here, so switch that.
* Creates a new instance of a command to be used by a new execution request return response.ofType(IQ.Type.error)
* .setError(error)
* @param commandNode the command node that identifies it. .build();
* @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) {
* Returns the registered commands of this command manager, which is related if (seconds < 10) {
* to a connection. throw new IllegalArgumentException();
* }
* @return the registered commands. DEFAULT_SESSION_TIMEOUT_SECS = seconds;
*/ }
private Collection<AdHocCommandInfo> getRegisteredCommands() {
return commands.values(); public void setSessionTimeoutSecs(int seconds) {
if (seconds < 10) {
throw new IllegalArgumentException();
}
sessionTimeoutSecs = seconds;
} }
/** /**
* Stores ad-hoc command information. * Stores ad-hoc command information.
*/ */
private static final class AdHocCommandInfo { private final class AdHocCommandInfo {
private String node; private final String node;
private String name; private final String name;
private final Jid ownerJID; private final AdHocCommandHandlerFactory factory;
private LocalCommandFactory factory;
private AdHocCommandInfo(String node, String name, Jid ownerJID, private static final int MAX_SESSION_GEN_ATTEMPTS = 3;
LocalCommandFactory factory) {
private AdHocCommandInfo(String node, String name, AdHocCommandHandlerFactory factory) {
this.node = node; this.node = node;
this.name = name; this.name = name;
this.ownerJID = ownerJID;
this.factory = factory; this.factory = factory;
} }
public LocalCommand getCommandInstance() throws InstantiationException, public AdHocCommandHandler getCommandInstance() throws InstantiationException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { IllegalAccessException, IllegalArgumentException, InvocationTargetException {
return factory.getInstance(); 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() { public String getName() {
@ -660,8 +677,5 @@ public final class AdHocCommandManager extends Manager {
return node; return node;
} }
public Jid getOwnerJID() {
return ownerJID;
}
} }
} }

View file

@ -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();
}
}
}

View file

@ -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:<ul>
* <li>Node</li>
* <li>Name</li>
* <li>Session ID</li>
* <li>Current Stage</li>
* <li>Available actions</li>
* <li>Default action</li>
* </ul>
* 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 <code>true</code>.
*
* @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--;
}
}

View file

@ -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 <code>node</code> in the host identified by
* <code>jid</code>
*
* @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 <code>action</code> with the <code>form</code>.
* The action could be any of the available actions. The form must
* be the answer of the previous stage. It can be <code>null</code> 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;
}
}

View file

@ -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;
}
}

View file

@ -18,63 +18,114 @@
package org.jivesoftware.smackx.commands.packet; package org.jivesoftware.smackx.commands.packet;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List; import java.util.List;
import java.util.Set;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.IqData;
import org.jivesoftware.smack.packet.XmlElement; 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.AdHocCommandNote;
import org.jivesoftware.smackx.commands.SpecificErrorCondition;
import org.jivesoftware.smackx.xdata.packet.DataForm; 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. * Represents the state and the request of the execution of an adhoc command.
* *
* @author Gabriel Guardincerri * @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 ELEMENT = "command";
public static final String NAMESPACE = "http://jabber.org/protocol/commands"; public static final String NAMESPACE = "http://jabber.org/protocol/commands";
/* JID of the command host */ private final String node;
private Jid id;
/* Command name */ private final String name;
private String name;
/* Command identifier */ private final String sessionId;
private String node;
/* Unique ID of the execution */
private String sessionID;
private final List<AdHocCommandNote> notes = new ArrayList<>(); private final List<AdHocCommandNote> notes = new ArrayList<>();
private DataForm form; private final DataForm form;
/* Action request to be executed */ private final Action action;
private AdHocCommand.Action action;
/* Current execution status */ private final Status status;
private AdHocCommand.Status status;
private final ArrayList<AdHocCommand.Action> actions = new ArrayList<>(); private final Set<AllowedAction> actions = EnumSet.noneOf(AllowedAction.class);
private AdHocCommand.Action executeAction; private final AllowedAction executeAction;
public AdHocCommandData() { public AdHocCommandData(AdHocCommandDataBuilder builder) {
super(ELEMENT, NAMESPACE); 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;
}
@Override
public String getName() {
return name;
}
@Override
public String getSessionId() {
return sessionId;
}
@Override
public List<AdHocCommandNote> getNotes() {
return notes;
}
@Override
public DataForm getForm() {
return form;
}
@Override
public Action getAction() {
return action;
}
@Override
public Status getStatus() {
return status;
}
@Override
public Set<AllowedAction> getActions() {
return actions;
}
@Override
public AllowedAction getExecuteAction() {
return executeAction;
} }
@Override @Override
protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) { protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) {
xml.attribute("node", node); xml.attribute("node", node);
xml.optAttribute("sessionid", sessionID); xml.optAttribute("sessionid", sessionId);
xml.optAttribute("status", status); xml.optAttribute("status", status);
xml.optAttribute("action", action); xml.optAttribute("action", action);
xml.rightAngleBracket(); xml.rightAngleBracket();
@ -87,19 +138,19 @@ public class AdHocCommandData extends IQ {
} else { } else {
xml.rightAngleBracket(); xml.rightAngleBracket();
for (AdHocCommand.Action action : actions) { for (AdHocCommandData.AllowedAction action : actions) {
xml.emptyElement(action); xml.emptyElement(action);
} }
xml.closeElement("actions"); xml.closeElement("actions");
} }
} }
if (form != null) { xml.optAppend(form);
xml.append(form.toXML());
}
for (AdHocCommandNote note : notes) { 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.append(note.getValue());
xml.closeElement("note"); xml.closeElement("note");
} }
@ -112,132 +163,16 @@ public class AdHocCommandData extends IQ {
return xml; return xml;
} }
/** public static AdHocCommandDataBuilder builder(String node, IqData iqCommon) {
* Returns the JID of the command host. return new AdHocCommandDataBuilder(node, iqCommon);
*
* @return the JID of the command host.
*/
public Jid getId() {
return id;
} }
public void setId(Jid id) { public static AdHocCommandDataBuilder builder(String node, String stanzaId) {
this.id = id; return new AdHocCommandDataBuilder(node, stanzaId);
} }
/** public static AdHocCommandDataBuilder builder(String node, XMPPConnection connection) {
* Returns the human name of the command. return new AdHocCommandDataBuilder(node, connection);
*
* @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<AdHocCommandNote> 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<Action> 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.
* <p>
* This value can be null or empty for the first command, but MUST be set for subsequent commands. See also <a
* href="http://xmpp.org/extensions/xep-0050.html#impl-session">XEP-0050 § 3.3 Session Lifetime</a>.
* </p>
*
* @param sessionID TODO javadoc me please
*/
public void setSessionID(String sessionID) {
this.sessionID = sessionID;
}
public String getSessionID() {
return sessionID;
} }
public static class SpecificError implements XmlElement { public static class SpecificError implements XmlElement {
@ -271,4 +206,86 @@ public class AdHocCommandData extends IQ {
return buf.toString(); 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;
}
}
} }

View file

@ -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<AdHocCommandDataBuilder, AdHocCommandData> implements AdHocCommandDataView {
private final String node;
private String name;
private String sessionId;
private final List<AdHocCommandNote> notes = new ArrayList<>();
private DataForm form;
/* Action request to be executed */
private Action action;
/* Current execution status */
private Status status;
private final Set<AllowedAction> 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<AdHocCommandNote> 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<AllowedAction> 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;
}
}

View file

@ -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<AdHocCommandNote> 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<AllowedAction> getActions();
AllowedAction getExecuteAction();
default boolean isCompleted() {
return getStatus() == Status.completed;
}
default boolean isExecuting() {
return getStatus() == Status.executing;
}
}

View file

@ -29,10 +29,13 @@ import org.jivesoftware.smack.util.PacketParserUtils;
import org.jivesoftware.smack.xml.XmlPullParser; import org.jivesoftware.smack.xml.XmlPullParser;
import org.jivesoftware.smack.xml.XmlPullParserException; 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.AdHocCommandNote;
import org.jivesoftware.smackx.commands.SpecificErrorCondition;
import org.jivesoftware.smackx.commands.packet.AdHocCommandData; 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; import org.jivesoftware.smackx.xdata.provider.DataFormProvider;
/** /**
@ -44,64 +47,69 @@ public class AdHocCommandDataProvider extends IqProvider<AdHocCommandData> {
@Override @Override
public AdHocCommandData parse(XmlPullParser parser, int initialDepth, IqData iqData, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException { public AdHocCommandData parse(XmlPullParser parser, int initialDepth, IqData iqData, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException {
boolean done = false; String commandNode = parser.getAttributeValue("node");
AdHocCommandData adHocCommandData = new AdHocCommandData(); AdHocCommandDataBuilder builder = AdHocCommandData.builder(commandNode, iqData);
DataFormProvider dataFormProvider = new DataFormProvider(); DataFormProvider dataFormProvider = new DataFormProvider();
XmlPullParser.Event eventType; String sessionId = parser.getAttributeValue("sessionid");
String elementName; builder.setSessionId(sessionId);
String namespace;
adHocCommandData.setSessionID(parser.getAttributeValue("", "sessionid"));
adHocCommandData.setNode(parser.getAttributeValue("", "node"));
// Status // Status
String status = parser.getAttributeValue("", "status"); String status = parser.getAttributeValue("", "status");
if (AdHocCommand.Status.executing.toString().equalsIgnoreCase(status)) { if (AdHocCommandData.Status.executing.toString().equalsIgnoreCase(status)) {
adHocCommandData.setStatus(AdHocCommand.Status.executing); builder.setStatus(AdHocCommandData.Status.executing);
} }
else if (AdHocCommand.Status.completed.toString().equalsIgnoreCase(status)) { else if (AdHocCommandData.Status.completed.toString().equalsIgnoreCase(status)) {
adHocCommandData.setStatus(AdHocCommand.Status.completed); builder.setStatus(AdHocCommandData.Status.completed);
} }
else if (AdHocCommand.Status.canceled.toString().equalsIgnoreCase(status)) { else if (AdHocCommandData.Status.canceled.toString().equalsIgnoreCase(status)) {
adHocCommandData.setStatus(AdHocCommand.Status.canceled); builder.setStatus(AdHocCommandData.Status.canceled);
} }
// Action // Action
String action = parser.getAttributeValue("", "action"); String action = parser.getAttributeValue("", "action");
if (action != null) { if (action != null) {
Action realAction = AdHocCommand.Action.valueOf(action); Action realAction = Action.valueOf(action);
if (realAction == null || realAction.equals(Action.unknown)) { if (realAction == null) {
adHocCommandData.setAction(Action.unknown); throw new SmackParsingException("Invalid value for action attribute: " + action);
} }
else {
adHocCommandData.setAction(realAction); builder.setAction(realAction);
} }
}
while (!done) { // TODO: Improve parsing below. Currently, the next actions like <prev/> are not checked for the correct position.
eventType = parser.next(); outerloop:
namespace = parser.getNamespace(); while (true) {
if (eventType == XmlPullParser.Event.START_ELEMENT) { String elementName;
XmlPullParser.Event event = parser.next();
String namespace = parser.getNamespace();
switch (event) {
case START_ELEMENT:
elementName = parser.getName(); elementName = parser.getName();
if (parser.getName().equals("actions")) { switch (elementName) {
String execute = parser.getAttributeValue("", "execute"); case "actions":
String execute = parser.getAttributeValue("execute");
if (execute != null) { if (execute != null) {
adHocCommandData.setExecuteAction(AdHocCommand.Action.valueOf(execute)); builder.setExecuteAction(AllowedAction.valueOf(execute));
} }
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);
} }
else if (parser.getName().equals("next")) { break;
adHocCommandData.addAction(AdHocCommand.Action.next); case "note":
} String typeString = parser.getAttributeValue("type");
else if (parser.getName().equals("complete")) {
adHocCommandData.addAction(AdHocCommand.Action.complete);
}
else if (parser.getName().equals("prev")) {
adHocCommandData.addAction(AdHocCommand.Action.prev);
}
else if (elementName.equals("x") && namespace.equals("jabber:x:data")) {
adHocCommandData.setForm(dataFormProvider.parse(parser));
}
else if (parser.getName().equals("note")) {
String typeString = parser.getAttributeValue("", "type");
AdHocCommandNote.Type type; AdHocCommandNote.Type type;
if (typeString != null) { if (typeString != null) {
type = AdHocCommandNote.Type.valueOf(typeString); type = AdHocCommandNote.Type.valueOf(typeString);
@ -110,61 +118,67 @@ public class AdHocCommandDataProvider extends IqProvider<AdHocCommandData> {
type = AdHocCommandNote.Type.info; type = AdHocCommandNote.Type.info;
} }
String value = parser.nextText(); String value = parser.nextText();
adHocCommandData.addNote(new AdHocCommandNote(type, value)); builder.addNote(new AdHocCommandNote(type, value));
} break;
else if (parser.getName().equals("error")) { case "error":
StanzaError error = PacketParserUtils.parseError(parser); StanzaError error = PacketParserUtils.parseError(parser);
adHocCommandData.setError(error); builder.setError(error);
break;
} }
} break;
else if (eventType == XmlPullParser.Event.END_ELEMENT) { case END_ELEMENT:
if (parser.getName().equals("command")) { 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<AdHocCommandData.SpecificError> { public static class BadActionError extends ExtensionElementProvider<AdHocCommandData.SpecificError> {
@Override @Override
public AdHocCommandData.SpecificError parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) { 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<AdHocCommandData.SpecificError> { public static class MalformedActionError extends ExtensionElementProvider<AdHocCommandData.SpecificError> {
@Override @Override
public AdHocCommandData.SpecificError parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) { 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<AdHocCommandData.SpecificError> { public static class BadLocaleError extends ExtensionElementProvider<AdHocCommandData.SpecificError> {
@Override @Override
public AdHocCommandData.SpecificError parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) { 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<AdHocCommandData.SpecificError> { public static class BadPayloadError extends ExtensionElementProvider<AdHocCommandData.SpecificError> {
@Override @Override
public AdHocCommandData.SpecificError parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) { 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<AdHocCommandData.SpecificError> { public static class BadSessionIDError extends ExtensionElementProvider<AdHocCommandData.SpecificError> {
@Override @Override
public AdHocCommandData.SpecificError parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) { 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<AdHocCommandData.SpecificError> { public static class SessionExpiredError extends ExtensionElementProvider<AdHocCommandData.SpecificError> {
@Override @Override
public AdHocCommandData.SpecificError parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) { public AdHocCommandData.SpecificError parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) {
return new AdHocCommandData.SpecificError(AdHocCommand.SpecificErrorCondition.sessionExpired); return new AdHocCommandData.SpecificError(SpecificErrorCondition.sessionExpired);
} }
} }
} }

View file

@ -270,4 +270,8 @@ public class FillableForm extends FilledForm {
return builder.build(); return builder.build();
} }
public SubmitForm getSubmitForm() {
DataForm form = getDataFormToSubmit();
return new SubmitForm(form);
}
} }

View file

@ -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();
}
}
}

View file

@ -23,7 +23,6 @@ import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.packet.StanzaError; import org.jivesoftware.smack.packet.StanzaError;
import org.jivesoftware.smack.util.PacketParserUtils; import org.jivesoftware.smack.util.PacketParserUtils;
import org.jivesoftware.smackx.commands.AdHocCommand;
import org.jivesoftware.smackx.commands.packet.AdHocCommandData; import org.jivesoftware.smackx.commands.packet.AdHocCommandData;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -41,7 +40,7 @@ public class CommandsProviderTest {
final AdHocCommandData adHocIq = (AdHocCommandData) requestStanza; final AdHocCommandData adHocIq = (AdHocCommandData) requestStanza;
assertEquals(IQ.Type.error, adHocIq.getType()); assertEquals(IQ.Type.error, adHocIq.getType());
assertEquals(AdHocCommand.Action.execute, adHocIq.getAction()); assertEquals(AdHocCommandData.Action.execute, adHocIq.getAction());
StanzaError error = adHocIq.getError(); StanzaError error = adHocIq.getError();
assertEquals(StanzaError.Type.CANCEL, error.getType()); assertEquals(StanzaError.Type.CANCEL, error.getType());

View file

@ -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. "));
}
}

View file

@ -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);
}
}
}

View file

@ -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;