001/** 002 * 003 * Copyright 2005-2008 Jive Software. 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 018package org.jivesoftware.smackx.commands; 019 020import java.lang.reflect.Constructor; 021import java.lang.reflect.InvocationTargetException; 022import java.util.ArrayList; 023import java.util.Collection; 024import java.util.Iterator; 025import java.util.List; 026import java.util.Map; 027import java.util.WeakHashMap; 028import java.util.concurrent.ConcurrentHashMap; 029import java.util.concurrent.TimeUnit; 030import java.util.concurrent.atomic.AtomicBoolean; 031import java.util.concurrent.atomic.AtomicReference; 032import java.util.logging.Level; 033import java.util.logging.Logger; 034 035import org.jivesoftware.smack.ConnectionCreationListener; 036import org.jivesoftware.smack.Manager; 037import org.jivesoftware.smack.SmackException; 038import org.jivesoftware.smack.SmackException.NoResponseException; 039import org.jivesoftware.smack.SmackException.NotConnectedException; 040import org.jivesoftware.smack.XMPPConnection; 041import org.jivesoftware.smack.XMPPConnectionRegistry; 042import org.jivesoftware.smack.XMPPException; 043import org.jivesoftware.smack.XMPPException.XMPPErrorException; 044import org.jivesoftware.smack.iqrequest.AbstractIqRequestHandler; 045import org.jivesoftware.smack.iqrequest.IQRequestHandler.Mode; 046import org.jivesoftware.smack.packet.IQ; 047import org.jivesoftware.smack.packet.StanzaError; 048import org.jivesoftware.smack.util.StringUtils; 049 050import org.jivesoftware.smackx.commands.packet.AdHocCommandData; 051import org.jivesoftware.smackx.commands.packet.AdHocCommandData.AllowedAction; 052import org.jivesoftware.smackx.commands.packet.AdHocCommandDataBuilder; 053import org.jivesoftware.smackx.disco.AbstractNodeInformationProvider; 054import org.jivesoftware.smackx.disco.ServiceDiscoveryManager; 055import org.jivesoftware.smackx.disco.packet.DiscoverInfo; 056import org.jivesoftware.smackx.disco.packet.DiscoverItems; 057import org.jivesoftware.smackx.xdata.form.SubmitForm; 058import org.jivesoftware.smackx.xdata.packet.DataForm; 059 060import org.jxmpp.jid.EntityFullJid; 061import org.jxmpp.jid.Jid; 062 063/** 064 * An AdHocCommandManager is responsible for keeping the list of available 065 * commands offered by a service and for processing commands requests. 066 * 067 * Pass in an XMPPConnection instance to 068 * {@link #getAddHocCommandsManager(XMPPConnection)} in order to 069 * get an instance of this class. 070 * 071 * @author Gabriel Guardincerri 072 * @author Florian Schmaus 073 */ 074public final class AdHocCommandManager extends Manager { 075 public static final String NAMESPACE = "http://jabber.org/protocol/commands"; 076 077 private static final Logger LOGGER = Logger.getLogger(AdHocCommandManager.class.getName()); 078 079 /** 080 * The session time out in seconds. 081 */ 082 private static int DEFAULT_SESSION_TIMEOUT_SECS = 7 * 60; 083 084 /** 085 * Map an XMPPConnection with it AdHocCommandManager. This map have a key-value 086 * pair for every active connection. 087 */ 088 private static final Map<XMPPConnection, AdHocCommandManager> instances = new WeakHashMap<>(); 089 090 /* 091 * Register the listener for all the connection creations. When a new 092 * connection is created a new AdHocCommandManager is also created and 093 * related to that connection. 094 */ 095 static { 096 XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() { 097 @Override 098 public void connectionCreated(XMPPConnection connection) { 099 getInstance(connection); 100 } 101 }); 102 } 103 104 /** 105 * Returns the <code>AdHocCommandManager</code> related to the 106 * <code>connection</code>. 107 * 108 * @param connection the XMPP connection. 109 * @return the AdHocCommandManager associated with the connection. 110 * @deprecated use {@link #getInstance(XMPPConnection)} instead. 111 */ 112 @Deprecated 113 public static AdHocCommandManager getAddHocCommandsManager(XMPPConnection connection) { 114 return getInstance(connection); 115 } 116 117 /** 118 * Returns the <code>AdHocCommandManager</code> related to the 119 * <code>connection</code>. 120 * 121 * @param connection the XMPP connection. 122 * @return the AdHocCommandManager associated with the connection. 123 */ 124 public static synchronized AdHocCommandManager getInstance(XMPPConnection connection) { 125 AdHocCommandManager ahcm = instances.get(connection); 126 if (ahcm == null) { 127 ahcm = new AdHocCommandManager(connection); 128 instances.put(connection, ahcm); 129 } 130 return ahcm; 131 } 132 133 /** 134 * Map a command node with its AdHocCommandInfo. Note: Key=command node, 135 * Value=command. Command node matches the node attribute sent by command 136 * requesters. 137 */ 138 private final Map<String, AdHocCommandInfo> commands = new ConcurrentHashMap<>(); 139 140 /** 141 * Map a command session ID with the instance LocalCommand. The LocalCommand 142 * is the an objects that has all the information of the current state of 143 * the command execution. Note: Key=session ID, Value=LocalCommand. Session 144 * ID matches the sessionid attribute sent by command responders. 145 */ 146 private final Map<String, AdHocCommandHandler> executingCommands = new ConcurrentHashMap<>(); 147 148 private final ServiceDiscoveryManager serviceDiscoveryManager; 149 150 private int sessionTimeoutSecs = DEFAULT_SESSION_TIMEOUT_SECS; 151 152 private AdHocCommandManager(XMPPConnection connection) { 153 super(connection); 154 this.serviceDiscoveryManager = ServiceDiscoveryManager.getInstanceFor(connection); 155 156 // Add the feature to the service discovery manage to show that this 157 // connection supports the AdHoc-Commands protocol. 158 // This information will be used when another client tries to 159 // discover whether this client supports AdHoc-Commands or not. 160 ServiceDiscoveryManager.getInstanceFor(connection).addFeature( 161 NAMESPACE); 162 163 // Set the NodeInformationProvider that will provide information about 164 // which AdHoc-Commands are registered, whenever a disco request is 165 // received 166 ServiceDiscoveryManager.getInstanceFor(connection) 167 .setNodeInformationProvider(NAMESPACE, 168 new AbstractNodeInformationProvider() { 169 @Override 170 public List<DiscoverItems.Item> getNodeItems() { 171 List<DiscoverItems.Item> answer = new ArrayList<>(); 172 Collection<AdHocCommandInfo> commandsList = commands.values(); 173 174 EntityFullJid ourJid = connection().getUser(); 175 if (ourJid == null) { 176 LOGGER.warning("Local connection JID not available, can not respond to " + NAMESPACE + " node information"); 177 return null; 178 } 179 180 for (AdHocCommandInfo info : commandsList) { 181 DiscoverItems.Item item = new DiscoverItems.Item(ourJid); 182 item.setName(info.getName()); 183 item.setNode(info.getNode()); 184 answer.add(item); 185 } 186 187 return answer; 188 } 189 }); 190 191 // The packet listener and the filter for processing some AdHoc Commands 192 // Packets 193 // TODO: This handler being async means that requests for the same command could be handled out of order. Nobody 194 // complained so far, and I could imagine that it does not really matter in practice. But it is certainly 195 // something to keep in mind. 196 connection.registerIQRequestHandler(new AbstractIqRequestHandler(AdHocCommandData.ELEMENT, 197 AdHocCommandData.NAMESPACE, IQ.Type.set, Mode.async) { 198 @Override 199 public IQ handleIQRequest(IQ iqRequest) { 200 AdHocCommandData requestData = (AdHocCommandData) iqRequest; 201 AdHocCommandData response = processAdHocCommand(requestData); 202 assert response.getStatus() != null || response.getType() == IQ.Type.error; 203 return response; 204 } 205 }); 206 } 207 208 /** 209 * Registers a new command with this command manager, which is related to a 210 * connection. The <code>node</code> is an unique identifier of that command for 211 * the connection related to this command manager. The <code>name</code> is the 212 * human readable name of the command. The <code>class</code> is the class of 213 * the command, which must extend {@link AdHocCommandHandler} and have a default 214 * constructor. 215 * 216 * @param node the unique identifier of the command. 217 * @param name the human readable name of the command. 218 * @param clazz the class of the command, which must extend {@link AdHocCommandHandler}. 219 * @throws SecurityException if there was a security violation. 220 * @throws NoSuchMethodException if no such method is declared. 221 */ 222 public void registerCommand(String node, String name, final Class<? extends AdHocCommandHandler> clazz) throws NoSuchMethodException, SecurityException { 223 Constructor<? extends AdHocCommandHandler> constructor = clazz.getConstructor(String.class, String.class, String.class); 224 registerCommand(node, name, new AdHocCommandHandlerFactory() { 225 @Override 226 public AdHocCommandHandler create(String node, String name, String sessionId) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { 227 return constructor.newInstance(node, name, sessionId); 228 } 229 }); 230 } 231 232 /** 233 * Registers a new command with this command manager, which is related to a 234 * connection. The <code>node</code> is an unique identifier of that 235 * command for the connection related to this command manager. The <code>name</code> 236 * is the human readable name of the command. The <code>factory</code> generates 237 * new instances of the command. 238 * 239 * @param node the unique identifier of the command. 240 * @param name the human readable name of the command. 241 * @param factory a factory to create new instances of the command. 242 */ 243 public synchronized void registerCommand(String node, final String name, AdHocCommandHandlerFactory factory) { 244 AdHocCommandInfo commandInfo = new AdHocCommandInfo(node, name, factory); 245 246 AdHocCommandInfo existing = commands.putIfAbsent(node, commandInfo); 247 if (existing != null) throw new IllegalArgumentException("There is already an ad-hoc command registered for " + node); 248 249 // Set the NodeInformationProvider that will provide information about 250 // the added command 251 serviceDiscoveryManager.setNodeInformationProvider(node, 252 new AbstractNodeInformationProvider() { 253 @Override 254 public List<String> getNodeFeatures() { 255 List<String> answer = new ArrayList<>(); 256 answer.add(NAMESPACE); 257 // TODO: check if this service is provided by the 258 // TODO: current connection. 259 answer.add("jabber:x:data"); 260 return answer; 261 } 262 @Override 263 public List<DiscoverInfo.Identity> getNodeIdentities() { 264 List<DiscoverInfo.Identity> answer = new ArrayList<>(); 265 DiscoverInfo.Identity identity = new DiscoverInfo.Identity( 266 "automation", name, "command-node"); 267 answer.add(identity); 268 return answer; 269 } 270 }); 271 } 272 273 public synchronized boolean unregisterCommand(String node) { 274 AdHocCommandInfo commandInfo = commands.remove(node); 275 if (commandInfo == null) return false; 276 277 serviceDiscoveryManager.removeNodeInformationProvider(node); 278 return true; 279 } 280 281 /** 282 * Discover the commands of an specific JID. The <code>jid</code> is a 283 * full JID. 284 * 285 * @param jid the full JID to retrieve the commands for. 286 * @return the discovered items. 287 * @throws XMPPException if the operation failed for some reason. 288 * @throws SmackException if there was no response from the server. 289 * @throws InterruptedException if the calling thread was interrupted. 290 */ 291 public DiscoverItems discoverCommands(Jid jid) throws XMPPException, SmackException, InterruptedException { 292 return serviceDiscoveryManager.discoverItems(jid, NAMESPACE); 293 } 294 295 /** 296 * Returns a command that represents an instance of a command in a remote 297 * host. It is used to execute remote commands. The concept is similar to 298 * RMI. Every invocation on this command is equivalent to an invocation in 299 * the remote command. 300 * 301 * @param jid the full JID of the host of the remote command 302 * @param node the identifier of the command 303 * @return a local instance equivalent to the remote command. 304 */ 305 public AdHocCommand getRemoteCommand(Jid jid, String node) { 306 return new AdHocCommand(connection(), node, jid); 307 } 308 309 /** 310 * Process the AdHoc-Command stanza that request the execution of some 311 * action of a command. If this is the first request, this method checks, 312 * before executing the command, if: 313 * <ul> 314 * <li>The requested command exists</li> 315 * <li>The requester has permissions to execute it</li> 316 * <li>The command has more than one stage, if so, it saves the command and 317 * session ID for further use</li> 318 * </ul> 319 * 320 * <br> 321 * <br> 322 * If this is not the first request, this method checks, before executing 323 * the command, if: 324 * <ul> 325 * <li>The session ID of the request was stored</li> 326 * <li>The session life do not exceed the time out</li> 327 * <li>The action to execute is one of the available actions</li> 328 * </ul> 329 * 330 * @param request the incoming AdHoc command request. 331 */ 332 private AdHocCommandData processAdHocCommand(AdHocCommandData request) { 333 String sessionId = request.getSessionId(); 334 335 final AdHocCommandHandler command; 336 if (sessionId == null) { 337 String commandNode = request.getNode(); 338 339 // A new execution request has been received. Check that the 340 // command exists 341 AdHocCommandInfo commandInfo = commands.get(commandNode); 342 if (commandInfo == null) { 343 // Requested command does not exist so return 344 // item_not_found error. 345 return respondError(request, null, StanzaError.Condition.item_not_found); 346 } 347 348 assert commandInfo.getNode().equals(commandNode); 349 350 // Create a new instance of the command with the 351 // corresponding session ID. 352 try { 353 command = commandInfo.getCommandInstance(); 354 } 355 catch (InstantiationException | IllegalAccessException | IllegalArgumentException 356 | InvocationTargetException e) { 357 LOGGER.log(Level.WARNING, "Could not instanciate ad-hoc command server", e); 358 StanzaError xmppError = StanzaError.getBuilder() 359 .setCondition(StanzaError.Condition.internal_server_error) 360 .setDescriptiveEnText(e.getMessage()) 361 .build(); 362 return respondError(request, null, xmppError); 363 } 364 } else { 365 command = executingCommands.get(sessionId); 366 // Check that a command exists for the specified sessionID 367 // This also handles if the command was removed in the meanwhile 368 // of getting the key and the value of the map. 369 if (command == null) { 370 return respondError(request, null, StanzaError.Condition.bad_request, 371 SpecificErrorCondition.badSessionid); 372 } 373 } 374 375 376 final AdHocCommandDataBuilder responseBuilder = AdHocCommandDataBuilder.buildResponseFor(request) 377 .setSessionId(command.getSessionId()); 378 379 final AdHocCommandData response; 380 /* 381 * Since the requester could send two requests for the same 382 * executing command i.e. the same session id, all the execution of 383 * the action must be synchronized to avoid inconsistencies. 384 */ 385 synchronized (command) { 386 command.addRequest(request); 387 388 if (sessionId == null) { 389 response = processAdHocCommandOfNewSession(request, command, responseBuilder); 390 } else { 391 response = processAdHocCommandOfExistingSession(request, command, responseBuilder); 392 } 393 394 395 AdHocCommandResult commandResult = AdHocCommandResult.from(response); 396 command.addResult(commandResult); 397 } 398 399 return response; 400 } 401 402 private AdHocCommandData createResponseFrom(AdHocCommandData request, AdHocCommandDataBuilder response, XMPPErrorException exception, String sessionId) { 403 StanzaError error = exception.getStanzaError(); 404 405 // If the error type is cancel, then the execution is 406 // canceled therefore the status must show that, and the 407 // command be removed from the executing list. 408 if (error.getType() == StanzaError.Type.CANCEL) { 409 response.setStatus(AdHocCommandData.Status.canceled); 410 411 executingCommands.remove(sessionId); 412 413 return response.build(); 414 } 415 416 return respondError(request, response, error); 417 } 418 419 private static AdHocCommandData createResponseFrom(AdHocCommandData request, AdHocCommandDataBuilder response, Exception exception) { 420 StanzaError error = StanzaError.from(StanzaError.Condition.internal_server_error, exception.getMessage()) 421 .build(); 422 return respondError(request, response, error); 423 } 424 425 private AdHocCommandData processAdHocCommandOfNewSession(AdHocCommandData request, AdHocCommandHandler command, AdHocCommandDataBuilder responseBuilder) { 426 // Check that the requester has enough permission. 427 // Answer forbidden error if requester permissions are not 428 // enough to execute the requested command 429 if (!command.hasPermission(request.getFrom())) { 430 return respondError(request, responseBuilder, StanzaError.Condition.forbidden); 431 } 432 433 AdHocCommandData.Action action = request.getAction(); 434 435 // If the action is not execute, then it is an invalid action. 436 if (action != null && !action.equals(AdHocCommandData.Action.execute)) { 437 return respondError(request, responseBuilder, StanzaError.Condition.bad_request, 438 SpecificErrorCondition.badAction); 439 } 440 441 // Increase the state number, so the command knows in witch 442 // stage it is 443 command.incrementStage(); 444 445 final AdHocCommandData response; 446 try { 447 // Executes the command 448 response = command.execute(responseBuilder); 449 } catch (XMPPErrorException e) { 450 return createResponseFrom(request, responseBuilder, e, command.getSessionId()); 451 } catch (NoResponseException | NotConnectedException | InterruptedException | IllegalStateException e) { 452 return createResponseFrom(request, responseBuilder, e); 453 } 454 455 if (response.isExecuting()) { 456 executingCommands.put(command.getSessionId(), command); 457 // See if the session sweeper thread is scheduled. If not, start it. 458 maybeWindUpSessionSweeper(); 459 } 460 461 return response; 462 } 463 464 private AdHocCommandData processAdHocCommandOfExistingSession(AdHocCommandData request, AdHocCommandHandler command, AdHocCommandDataBuilder responseBuilder) { 465 // Check if the Session data has expired (default is 10 minutes) 466 long creationStamp = command.getCreationDate(); 467 if (System.currentTimeMillis() - creationStamp > sessionTimeoutSecs * 1000L) { 468 // Remove the expired session 469 executingCommands.remove(command.getSessionId()); 470 471 // Answer a not_allowed error (session-expired) 472 return respondError(request, responseBuilder, StanzaError.Condition.not_allowed, 473 SpecificErrorCondition.sessionExpired); 474 } 475 476 AdHocCommandData.Action action = request.getAction(); 477 478 // If the user didn't specify an action or specify the execute 479 // action then follow the actual default execute action 480 if (action == null || AdHocCommandData.Action.execute.equals(action)) { 481 AllowedAction executeAction = command.getExecuteAction(); 482 if (executeAction != null) { 483 action = executeAction.action; 484 } 485 } 486 487 // Check that the specified action was previously 488 // offered 489 if (!command.isValidAction(action)) { 490 return respondError(request, responseBuilder, StanzaError.Condition.bad_request, 491 SpecificErrorCondition.badAction); 492 } 493 494 AdHocCommandData response; 495 try { 496 DataForm dataForm; 497 switch (action) { 498 case next: 499 command.incrementStage(); 500 dataForm = request.getForm(); 501 response = command.next(responseBuilder, new SubmitForm(dataForm)); 502 break; 503 case complete: 504 command.incrementStage(); 505 dataForm = request.getForm(); 506 responseBuilder.setStatus(AdHocCommandData.Status.completed); 507 response = command.complete(responseBuilder, new SubmitForm(dataForm)); 508 // Remove the completed session 509 executingCommands.remove(command.getSessionId()); 510 break; 511 case prev: 512 command.decrementStage(); 513 response = command.prev(responseBuilder); 514 break; 515 case cancel: 516 command.cancel(); 517 responseBuilder.setStatus(AdHocCommandData.Status.canceled); 518 response = responseBuilder.build(); 519 // Remove the canceled session 520 executingCommands.remove(command.getSessionId()); 521 break; 522 default: 523 return respondError(request, responseBuilder, StanzaError.Condition.bad_request, 524 SpecificErrorCondition.badAction); 525 } 526 } catch (XMPPErrorException e) { 527 return createResponseFrom(request, responseBuilder, e, command.getSessionId()); 528 } catch (NoResponseException | NotConnectedException | InterruptedException | IllegalStateException e) { 529 return createResponseFrom(request, responseBuilder, e); 530 } 531 532 return response; 533 } 534 535 private boolean sessionSweeperScheduled; 536 537 private int getSessionRemovalTimeoutSecs() { 538 return sessionTimeoutSecs * 2; 539 } 540 541 private void sessionSweeper() { 542 final long currentTime = System.currentTimeMillis(); 543 synchronized (this) { 544 for (Iterator<Map.Entry<String, AdHocCommandHandler>> it = executingCommands.entrySet().iterator(); it.hasNext();) { 545 Map.Entry<String, AdHocCommandHandler> entry = it.next(); 546 AdHocCommandHandler command = entry.getValue(); 547 548 long creationStamp = command.getCreationDate(); 549 // Check if the Session data has expired. 550 // To remove it from the session list it waits for the double of 551 // the of time out time. This is to let 552 // the requester know why his execution request is 553 // not accepted. If the session is removed just 554 // after the time out, then once the user requests to 555 // continue the execution he will received an 556 // invalid session error and not a time out error. 557 if (currentTime - creationStamp > getSessionRemovalTimeoutSecs() * 1000L) { 558 // Remove the expired session 559 it.remove(); 560 } 561 } 562 563 sessionSweeperScheduled = false; 564 } 565 566 if (!executingCommands.isEmpty()) { 567 maybeWindUpSessionSweeper(); 568 } 569 }; 570 571 private synchronized void maybeWindUpSessionSweeper() { 572 if (sessionSweeperScheduled) { 573 return; 574 } 575 576 sessionSweeperScheduled = true; 577 schedule(this::sessionSweeper, getSessionRemovalTimeoutSecs() + 1, TimeUnit.SECONDS); 578 } 579 580 /** 581 * Responds an error with an specific condition. 582 * 583 * @param request the request that caused the error response. 584 * @param condition the condition of the error. 585 */ 586 private static AdHocCommandData respondError(AdHocCommandData request, AdHocCommandDataBuilder response, 587 StanzaError.Condition condition) { 588 return respondError(request, response, StanzaError.getBuilder(condition).build()); 589 } 590 591 /** 592 * Responds an error with an specific condition. 593 * 594 * @param request the request that caused the error response. 595 * @param condition the condition of the error. 596 * @param specificCondition the adhoc command error condition. 597 */ 598 private static AdHocCommandData respondError(AdHocCommandData request, AdHocCommandDataBuilder response, StanzaError.Condition condition, 599 SpecificErrorCondition specificCondition) { 600 StanzaError error = StanzaError.getBuilder(condition) 601 .addExtension(new AdHocCommandData.SpecificError(specificCondition)) 602 .build(); 603 return respondError(request, response, error); 604 } 605 606 /** 607 * Responds an error with an specific error. 608 * 609 * @param request the request that caused the error response. 610 * @param error the error to send. 611 */ 612 private static AdHocCommandData respondError(AdHocCommandData request, AdHocCommandDataBuilder response, StanzaError error) { 613 if (response == null) { 614 return AdHocCommandDataBuilder.buildResponseFor(request, IQ.ResponseType.error).setError(error).build(); 615 } 616 617 // Response may be not of IQ type error here, so switch that. 618 return response.ofType(IQ.Type.error) 619 .setError(error) 620 .build(); 621 } 622 623 public static void setDefaultSessionTimeoutSecs(int seconds) { 624 if (seconds < 10) { 625 throw new IllegalArgumentException(); 626 } 627 DEFAULT_SESSION_TIMEOUT_SECS = seconds; 628 } 629 630 public void setSessionTimeoutSecs(int seconds) { 631 if (seconds < 10) { 632 throw new IllegalArgumentException(); 633 } 634 635 sessionTimeoutSecs = seconds; 636 } 637 638 /** 639 * Stores ad-hoc command information. 640 */ 641 private final class AdHocCommandInfo { 642 643 private final String node; 644 private final String name; 645 private final AdHocCommandHandlerFactory factory; 646 647 private AdHocCommandInfo(String node, String name, AdHocCommandHandlerFactory factory) { 648 this.node = node; 649 this.name = name; 650 this.factory = factory; 651 } 652 653 public AdHocCommandHandler getCommandInstance() throws InstantiationException, 654 IllegalAccessException, IllegalArgumentException, InvocationTargetException { 655 AdHocCommandHandler handler; 656 AtomicBoolean isNew = new AtomicBoolean(); 657 AtomicReference<Exception> exceptionReference = new AtomicReference<>(); 658 659 // TODO: Use Atomic(Boolean|Reference).getAcquire() once Smacks' minimum Android SDK API level is 33 or higher. 660 do { 661 var sessionId = StringUtils.randomString(15); 662 handler = executingCommands.computeIfAbsent(sessionId, (s) -> { 663 isNew.lazySet(true); 664 try { 665 return factory.create(node, name, s); 666 } catch (InstantiationException | IllegalAccessException | IllegalArgumentException 667 | InvocationTargetException e) { 668 exceptionReference.lazySet(e); 669 return null; 670 } 671 }); 672 } while (isNew.get() == false); 673 674 Exception exception = exceptionReference.get(); 675 if (exception != null) { 676 if (exception instanceof InstantiationException) 677 throw (InstantiationException) exception; 678 if (exception instanceof IllegalAccessException) 679 throw (IllegalAccessException) exception; 680 if (exception instanceof IllegalArgumentException) 681 throw (IllegalArgumentException) exception; 682 if (exception instanceof InvocationTargetException) 683 throw (InvocationTargetException) exception; 684 685 throw new AssertionError("Unexpected exception type: " + exception, exception); 686 } 687 688 return handler; 689 } 690 691 public String getName() { 692 return name; 693 } 694 695 public String getNode() { 696 return node; 697 } 698 699 } 700}