use of org.jivesoftware.smackx.packet.AdHocCommandData in project ecf by eclipse.
the class AdHocCommandDataProvider method parseIQ.
public IQ parseIQ(XmlPullParser parser) throws Exception {
boolean done = false;
AdHocCommandData adHocCommandData = new AdHocCommandData();
DataFormProvider dataFormProvider = new DataFormProvider();
int eventType;
String elementName;
String namespace;
adHocCommandData.setSessionID(parser.getAttributeValue("", "sessionid"));
adHocCommandData.setNode(parser.getAttributeValue("", "node"));
// Status
String status = parser.getAttributeValue("", "status");
if (AdHocCommand.Status.executing.toString().equalsIgnoreCase(status)) {
adHocCommandData.setStatus(AdHocCommand.Status.executing);
} else if (AdHocCommand.Status.completed.toString().equalsIgnoreCase(status)) {
adHocCommandData.setStatus(AdHocCommand.Status.completed);
} else if (AdHocCommand.Status.canceled.toString().equalsIgnoreCase(status)) {
adHocCommandData.setStatus(AdHocCommand.Status.canceled);
}
// Action
String action = parser.getAttributeValue("", "action");
if (action != null) {
Action realAction = AdHocCommand.Action.valueOf(action);
if (realAction == null || realAction.equals(Action.unknown)) {
adHocCommandData.setAction(Action.unknown);
} else {
adHocCommandData.setAction(realAction);
}
}
while (!done) {
eventType = parser.next();
elementName = parser.getName();
namespace = parser.getNamespace();
if (eventType == XmlPullParser.START_TAG) {
if (parser.getName().equals("actions")) {
String execute = parser.getAttributeValue("", "execute");
if (execute != null) {
adHocCommandData.setExecuteAction(AdHocCommand.Action.valueOf(execute));
}
} else if (parser.getName().equals("next")) {
adHocCommandData.addAction(AdHocCommand.Action.next);
} else if (parser.getName().equals("complete")) {
adHocCommandData.addAction(AdHocCommand.Action.complete);
} else if (parser.getName().equals("prev")) {
adHocCommandData.addAction(AdHocCommand.Action.prev);
} else if (elementName.equals("x") && namespace.equals("jabber:x:data")) {
adHocCommandData.setForm((DataForm) dataFormProvider.parseExtension(parser));
} else if (parser.getName().equals("note")) {
AdHocCommandNote.Type type = AdHocCommandNote.Type.valueOf(parser.getAttributeValue("", "type"));
String value = parser.nextText();
adHocCommandData.addNote(new AdHocCommandNote(type, value));
} else if (parser.getName().equals("error")) {
XMPPError error = PacketParserUtils.parseError(parser);
adHocCommandData.setError(error);
}
} else if (eventType == XmlPullParser.END_TAG) {
if (parser.getName().equals("command")) {
done = true;
}
}
}
return adHocCommandData;
}
use of org.jivesoftware.smackx.packet.AdHocCommandData in project ecf by eclipse.
the class RemoteCommand method executeAction.
/**
* Executes the <code>action</codo> with the <code>form</code>.
* The action could be any of the available actions. The form must
* be the anwser of the previous stage. It can be <tt>null</tt> if it is the first stage.
*
* @param action the action to execute.
* @param form the form with the information.
* @param timeout the amount of time to wait for a reply.
* @throws XMPPException if there is a problem executing the command.
*/
private void executeAction(Action action, Form form, long timeout) throws XMPPException {
// TODO: Check that all the required fields of the form were filled, if
// TODO: not throw the corresponding exeption. This will make a faster response,
// TODO: since the request is stoped 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);
if (form != null) {
data.setForm(form.getDataFormToSend());
}
PacketCollector collector = connection.createPacketCollector(new PacketIDFilter(data.getPacketID()));
connection.sendPacket(data);
Packet response = collector.nextResult(timeout);
// Cancel the collector.
collector.cancel();
if (response == null) {
throw new XMPPException("No response from server on status set.");
}
if (response.getError() != null) {
throw new XMPPException(response.getError());
}
AdHocCommandData responseData = (AdHocCommandData) response;
this.sessionID = responseData.getSessionID();
super.setData(responseData);
}
use of org.jivesoftware.smackx.packet.AdHocCommandData in project ecf by eclipse.
the class AdHocCommandManager method respondError.
/**
* Responds an error with an specific condition.
*
* @param response the response to send.
* @param condition the condition of the error.
* @param specificCondition the adhoc command error condition.
*/
private void respondError(AdHocCommandData response, XMPPError.Condition condition, AdHocCommand.SpecificErrorCondition specificCondition) {
XMPPError error = new XMPPError(condition);
error.addExtension(new AdHocCommandData.SpecificError(specificCondition));
respondError(response, error);
}
use of org.jivesoftware.smackx.packet.AdHocCommandData in project ecf by eclipse.
the class AdHocCommandManager method init.
/**
* <ul>
* <li>Adds listeners to the connection</li>
* <li>Registers the ad-hoc command feature to the ServiceDiscoveryManager</li>
* <li>Registers the items of the feature</li>
* <li>Adds packet listeners to handle execution requests</li>
* <li>Creates and start the session sweeper</li>
* </ul>
*/
private void init() {
// Register the new instance and associate it with the connection
instances.put(connection, this);
// Add a listener to the connection that removes the registered instance
// when the connection is closed
connection.addConnectionListener(new ConnectionListener() {
public void connectionClosed() {
// Unregister this instance since the connection has been closed
instances.remove(connection);
}
public void connectionClosedOnError(Exception e) {
// Unregister this instance since the connection has been closed
instances.remove(connection);
}
public void reconnectionSuccessful() {
// Register this instance since the connection has been
// reestablished
instances.put(connection, AdHocCommandManager.this);
}
public void reconnectingIn(int seconds) {
// Nothing to do
}
public void reconnectionFailed(Exception e) {
// Nothing to do
}
});
// Add the feature to the service discovery manage to show that this
// connection supports the AdHoc-Commands protocol.
// This information will be used when another client tries to
// discover whether this client supports AdHoc-Commands or not.
ServiceDiscoveryManager.getInstanceFor(connection).addFeature(DISCO_NAMESPACE);
// Set the NodeInformationProvider that will provide information about
// which AdHoc-Commands are registered, whenever a disco request is
// received
ServiceDiscoveryManager.getInstanceFor(connection).setNodeInformationProvider(discoNode, new NodeInformationProvider() {
public List<DiscoverItems.Item> getNodeItems() {
List<DiscoverItems.Item> answer = new ArrayList<DiscoverItems.Item>();
Collection<AdHocCommandInfo> commandsList = getRegisteredCommands();
for (AdHocCommandInfo info : commandsList) {
DiscoverItems.Item item = new DiscoverItems.Item(info.getOwnerJID());
item.setName(info.getName());
item.setNode(info.getNode());
answer.add(item);
}
return answer;
}
public List<String> getNodeFeatures() {
return null;
}
public List<Identity> getNodeIdentities() {
return null;
}
public List<PacketExtension> getNodePacketExtensions() {
return null;
}
});
// The packet listener and the filter for processing some AdHoc Commands
// Packets
PacketListener listener = new PacketListener() {
public void processPacket(Packet packet) {
AdHocCommandData requestData = (AdHocCommandData) packet;
processAdHocCommand(requestData);
}
};
PacketFilter filter = new PacketTypeFilter(AdHocCommandData.class);
connection.addPacketListener(listener, filter);
sessionsSweeper = null;
}
use of org.jivesoftware.smackx.packet.AdHocCommandData in project ecf by eclipse.
the class AdHocCommandManager method processAdHocCommand.
/**
* Process the AdHoc-Command packet that request the execution of some
* action of a command. If this is the first request, this method checks,
* before executing the command, if:
* <ul>
* <li>The requested command exists</li>
* <li>The requester has permissions to execute it</li>
* <li>The command has more than one stage, if so, it saves the command and
* session ID for further use</li>
* </ul>
*
* <br>
* <br>
* If this is not the first request, this method checks, before executing
* the command, if:
* <ul>
* <li>The session ID of the request was stored</li>
* <li>The session life do not exceed the time out</li>
* <li>The action to execute is one of the available actions</li>
* </ul>
*
* @param requestData
* the packet to process.
*/
private void processAdHocCommand(AdHocCommandData requestData) {
// Only process requests of type SET
if (requestData.getType() != IQ.Type.SET) {
return;
}
// Creates the response with the corresponding data
AdHocCommandData response = new AdHocCommandData();
response.setTo(requestData.getFrom());
response.setPacketID(requestData.getPacketID());
response.setNode(requestData.getNode());
response.setId(requestData.getTo());
String sessionId = requestData.getSessionID();
String commandNode = requestData.getNode();
if (sessionId == null) {
// command exists
if (!commands.containsKey(commandNode)) {
// Requested command does not exist so return
// item_not_found error.
respondError(response, XMPPError.Condition.item_not_found);
return;
}
// Create new session ID
sessionId = StringUtils.randomString(15);
try {
// Create a new instance of the command with the
// corresponding sessioid
LocalCommand command = newInstanceOfCmd(commandNode, sessionId);
response.setType(IQ.Type.RESULT);
command.setData(response);
// enough to execute the requested command
if (!command.hasPermission(requestData.getFrom())) {
respondError(response, XMPPError.Condition.forbidden);
return;
}
Action action = requestData.getAction();
// If the action is unknown then respond an error.
if (action != null && action.equals(Action.unknown)) {
respondError(response, XMPPError.Condition.bad_request, AdHocCommand.SpecificErrorCondition.malformedAction);
return;
}
// If the action is not execute, then it is an invalid action.
if (action != null && !action.equals(Action.execute)) {
respondError(response, XMPPError.Condition.bad_request, AdHocCommand.SpecificErrorCondition.badAction);
return;
}
// Increase the state number, so the command knows in witch
// stage it is
command.incrementStage();
// Executes the command
command.execute();
if (command.isLastStage()) {
// If there is only one stage then the command is completed
response.setStatus(Status.completed);
} else {
// Else it is still executing, and is registered to be
// available for the next call
response.setStatus(Status.executing);
executingCommands.put(sessionId, command);
// See if the session reaping thread is started. If not, start it.
if (sessionsSweeper == null) {
sessionsSweeper = new Thread(new Runnable() {
public void run() {
while (true) {
for (String sessionId : executingCommands.keySet()) {
LocalCommand command = executingCommands.get(sessionId);
// map.
if (command != null) {
long creationStamp = command.getCreationDate();
// invalid session error and not a time out error.
if (System.currentTimeMillis() - creationStamp > SESSION_TIMEOUT * 1000 * 2) {
// Remove the expired session
executingCommands.remove(sessionId);
}
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
// Ignore.
}
}
}
});
sessionsSweeper.setDaemon(true);
sessionsSweeper.start();
}
}
// Sends the response packet
connection.sendPacket(response);
} catch (XMPPException e) {
// If there is an exception caused by the next, complete,
// prev or cancel method, then that error is returned to the
// requester.
XMPPError error = e.getXMPPError();
// command be removed from the executing list.
if (XMPPError.Type.CANCEL.equals(error.getType())) {
response.setStatus(Status.canceled);
executingCommands.remove(sessionId);
}
respondError(response, error);
e.printStackTrace();
}
} else {
LocalCommand command = executingCommands.get(sessionId);
// of getting the key and the value of the map.
if (command == null) {
respondError(response, XMPPError.Condition.bad_request, AdHocCommand.SpecificErrorCondition.badSessionid);
return;
}
// Check if the Session data has expired (default is 10 minutes)
long creationStamp = command.getCreationDate();
if (System.currentTimeMillis() - creationStamp > SESSION_TIMEOUT * 1000) {
// Remove the expired session
executingCommands.remove(sessionId);
// Answer a not_allowed error (session-expired)
respondError(response, XMPPError.Condition.not_allowed, AdHocCommand.SpecificErrorCondition.sessionExpired);
return;
}
/*
* Since the requester could send two requests for the same
* executing command i.e. the same session id, all the execution of
* the action must be synchronized to avoid inconsistencies.
*/
synchronized (command) {
Action action = requestData.getAction();
// If the action is unknown the respond an error
if (action != null && action.equals(Action.unknown)) {
respondError(response, XMPPError.Condition.bad_request, AdHocCommand.SpecificErrorCondition.malformedAction);
return;
}
// action then follow the actual default execute action
if (action == null || Action.execute.equals(action)) {
action = command.getExecuteAction();
}
// offered
if (!command.isValidAction(action)) {
respondError(response, XMPPError.Condition.bad_request, AdHocCommand.SpecificErrorCondition.badAction);
return;
}
try {
// TODO: Check that all the requierd fields of the form are
// TODO: filled, if not throw an exception. This will simplify the
// TODO: construction of new commands
// Since all errors were passed, the response is now a
// result
response.setType(IQ.Type.RESULT);
// Set the new data to the command.
command.setData(response);
if (Action.next.equals(action)) {
command.incrementStage();
command.next(new Form(requestData.getForm()));
if (command.isLastStage()) {
// If it is the last stage then the command is
// completed
response.setStatus(Status.completed);
} else {
// Otherwise it is still executing
response.setStatus(Status.executing);
}
} else if (Action.complete.equals(action)) {
command.incrementStage();
command.complete(new Form(requestData.getForm()));
response.setStatus(Status.completed);
// Remove the completed session
executingCommands.remove(sessionId);
} else if (Action.prev.equals(action)) {
command.decrementStage();
command.prev();
} else if (Action.cancel.equals(action)) {
command.cancel();
response.setStatus(Status.canceled);
// Remove the canceled session
executingCommands.remove(sessionId);
}
connection.sendPacket(response);
} catch (XMPPException e) {
// If there is an exception caused by the next, complete,
// prev or cancel method, then that error is returned to the
// requester.
XMPPError error = e.getXMPPError();
// command be removed from the executing list.
if (XMPPError.Type.CANCEL.equals(error.getType())) {
response.setStatus(Status.canceled);
executingCommands.remove(sessionId);
}
respondError(response, error);
e.printStackTrace();
}
}
}
}
Aggregations