Assess a workflow event to see how it effects curation

@param response
The response object
@param message
The incoming message
183728
private void workflowCuration(JsonSimple response, JsonSimple message) {
		String oid = message.getString(null, "oid");
		if (!workflowCompleted(oid)) {
			return;
		}

		// Resolve relationships before we continue
		try {
			JSONArray relations = mapRelations(oid);
			// Unless there was an error, we should be good to go
			if (relations != null) {
				JsonObject request = createTask(response, oid,
						"curation-request");
				if (!relations.isEmpty()) {
					request.put("relationships", relations);
				}
			}
		} catch (Exception ex) {
			log.error("Error processing relations: ", ex);
			return;
		}

	}
100740
private void doInstalled(final Message<JsonObject> message) {
    String moduleName = message.body().getString("module");
    if (moduleName == null) {
      message.reply(new JsonObject().putString("status", "error").putString("message", "No module specified."));
      return;
    }

    platform.getModuleInfo(moduleName, new Handler<AsyncResult<ModuleInfo>>() {
      @Override
      public void handle(AsyncResult<ModuleInfo> result) {
        if (result.failed() || result.result() == null) {
          message.reply(new JsonObject().putString("status", "ok").putBoolean("result", false));
        } else {
          message.reply(new JsonObject().putString("status", "ok").putBoolean("result", true));
        }
      }
    });
  }
823914
@Override
    public void onReceive(Object message) throws Exception {
        try {
            if (message instanceof RequestWorkerMsgType) {
                switch ((RequestWorkerMsgType) message) {
                case PROCESS_REQUEST:
                    tryCount++;

                    if (tryCount == 1) {
                        sender = getSender();
                        timeoutDuration = Duration.create(
                                actorMaxOperationTimeoutSec, TimeUnit.SECONDS);
                        timeoutMessageCancellable = getContext()
                                .system()
                                .scheduler()
                                .scheduleOnce(
                                        timeoutDuration,
                                        getSelf(),
                                        RequestWorkerMsgType.PROCESS_ON_TIMEOUT,
                                        getContext().system().dispatcher(),
                                        getSelf());

                        SshTask sshTask = new SshTask(sshMeta, targetHost);
                        setResponseFuture(TcpUdpSshPingResourceStore.getInstance()
                                .getThreadPoolForSshPing().submit(sshTask));

                        getContext()
                                .system()
                                .scheduler()
                                .scheduleOnce(
                                        (FiniteDuration) Duration.create(0.5,
                                                TimeUnit.SECONDS),
                                        new Runnable() {
                                            @Override
                                            public void run() {
                                                getSelf()
                                                        .tell(RequestWorkerMsgType.CHECK_FUTURE_STATE,
                                                                getSelf());
                                            }
                                        }, getContext().system().dispatcher());

                    } else {
                        getLogger().error(
                                "duplicated PROCESS_REQUEST msg. ignore...");
                    }

                    break;

                case CHECK_FUTURE_STATE:
                    getLogger().debug(
                            "checking if SSH callable future completed... for "
                                    + targetHost);
                    if (getResponseFuture().isDone()) {
                        getLogger().debug(
                                "SSH Provider callable returned. for "
                                        + targetHost);
                        ResponseOnSingeRequest sshResponse = getResponseFuture()
                                .get();
                        onComplete(sshResponse);
                        break;
                    } else {
                        // schedule again
                        getContext()
                                .system()
                                .scheduler()
                                .scheduleOnce(
                                        (FiniteDuration) Duration.create(
                                                ParallecGlobalConfig.sshFutureCheckIntervalSec,
                                                TimeUnit.SECONDS),
                                        new Runnable() {
                                            @Override
                                            public void run() {
                                                getSelf()
                                                        .tell(RequestWorkerMsgType.CHECK_FUTURE_STATE,
                                                                getSelf());
                                            }
                                        }, getContext().system().dispatcher());

                    }
                    break;
                case CANCEL:
                    getLogger()
                            .info("Request was CANCELLED.................on SSH host {}",
                                    targetHost);
                    cancelCancellable();
                    if (sender == null)
                        sender = getSender();
                    reply(null, true, PcConstants.REQUEST_CANCELED,
                            PcConstants.REQUEST_CANCELED, PcConstants.NA,
                            PcConstants.NA_INT);
                    break;

                case PROCESS_ON_EXCEPTION:

                    String displayError = PcErrorMsgUtils.replaceErrorMsg(cause
                            .toString());

                    String stackTrace = PcStringUtils.printStackTrace(cause);

                    cancelCancellable();
                    reply(null, true, displayError, stackTrace, PcConstants.NA,
                            PcConstants.NA_INT);

                    break;

                case PROCESS_ON_TIMEOUT:
                    getLogger().error(
                            "Inside PROCESS_ON_TIMEOUT.................target: "
                                    + this.targetHost + "......... at "
                                    + PcDateUtils.getNowDateTimeStrStandard());
                    cancelCancellable();

                    String errorMsg = String
                            .format("SshWorker Timedout after %d SEC (no response but no exception catched). Details more info",
                                    actorMaxOperationTimeoutSec);
                    reply(null, true, errorMsg, errorMsg, PcConstants.NA,
                            PcConstants.NA_INT);
                    break;

                default:
                    break;
                }
            } else {
                unhandled(message);
                this.cause = new ActorMessageTypeInvalidException(
                        "ActorMessageTypeInvalidException error for host "
                                + this.targetHost);
                getSelf().tell(RequestWorkerMsgType.PROCESS_ON_EXCEPTION,
                        getSelf());
            }
        } catch (Exception e) {
            this.cause = e;
            getSelf()
                    .tell(RequestWorkerMsgType.PROCESS_ON_EXCEPTION, getSelf());
        }
    }
1213684
protected void processReceivedMessage(String channel, byte[] message) {

		// Parse message
		Tree data;
		try {
			data = serializer.read(message);
		} catch (Exception cause) {
			logger.warn("Unable to parse incoming message!", cause);
			return;
		}

		// Debug
		if (debug && (debugHeartbeats || !channel.endsWith(heartbeatChannel))) {
			logger.info("Message received from channel \"" + channel + "\":\r\n" + data);
		}

		// Send message to proper component
		try {

			// Get "sender" property
			String sender = data.get("sender", "");
			if (sender == null || sender.isEmpty()) {
				logger.warn("Missing \"sender\" property:\r\n" + data);
				return;
			}
			if (sender.equals(nodeID)) {

				// It's our message
				return;
			}

			// Incoming response
			if (channel.equals(responseChannel)) {
				registry.receiveResponse(data);
				return;
			}

			// Incoming event
			if (channel.equals(eventChannel)) {
				eventbus.receiveEvent(data);
				return;
			}

			// Incoming request
			if (channel.equals(requestChannel)) {
				registry.receiveRequest(data);
				return;
			}

			// HeartBeat packet
			if (channel.endsWith(heartbeatChannel)) {

				// Get node container
				NodeDescriptor node = nodes.get(sender);
				if (node == null) {

					// Unknown node -> send discover packet
					sendDiscoverPacket(channel(PACKET_DISCOVER, sender));
					return;
				}
				int cpu = data.get("cpu", 0);

				// Update CPU info
				boolean offline;
				node.writeLock.lock();
				try {
					node.updateCpu(cpu);
					offline = node.offlineSince > 0;
				} finally {
					node.writeLock.unlock();
				}
				if (offline) {

					// Offline node -> send discover packet
					sendDiscoverPacket(channel(PACKET_DISCOVER, sender));
				}
				return;
			}

			// Info packet
			if (channel.equals(infoChannel) || channel.equals(infoBroadcastChannel)) {

				// Register services and listeners
				data.put("seq", System.currentTimeMillis());
				data.put("port", 1);
				updateNodeInfo(sender, data);
				return;
			}

			// Discover packet
			if (channel.equals(discoverChannel) || channel.equals(discoverBroadcastChannel)) {

				// Send node desriptor to the sender
				sendInfoPacket(channel(PACKET_INFO, sender));
				return;
			}

			// Ping packet
			if (channel.equals(pingChannel)) {
				sendPongPacket(channel(PACKET_PONG, sender), data);
				return;
			}

			// Pong packet
			if (channel.equals(pongChannel)) {
				registry.receivePong(data);
				return;
			}

			// Disconnect packet
			if (channel.equals(disconnectChannel)) {

				// Switch to offline
				NodeDescriptor node = nodes.get(sender);
				if (node == null) {
					return;
				}
				boolean disconnected = false;
				node.writeLock.lock();
				try {
					if (node.markAsOffline()) {

						// Remove remote actions and listeners
						registry.removeActions(sender);
						eventbus.removeListeners(sender);
						disconnected = true;

					}
				} finally {
					node.writeLock.unlock();
				}
				if (node != null && disconnected) {

					// Notify listeners (not unexpected disconnection)
					logger.info("Node \"" + sender + "\" disconnected.");
					broadcastNodeDisconnected(node.info, false);
				}
				return;
			}

		} catch (Exception cause) {
			logger.warn("Unable to process incoming message!", cause);
		}
	}
321312
protected void handleRequestOut(T message) throws Fault {
        String flowId = FlowIdHelper.getFlowId(message);
        if (flowId == null
                && message.containsKey(PhaseInterceptorChain.PREVIOUS_MESSAGE)) {
            // Web Service consumer is acting as an intermediary
            @SuppressWarnings("unchecked")
            WeakReference<Message> wrPreviousMessage = (WeakReference<Message>) message
                    .get(PhaseInterceptorChain.PREVIOUS_MESSAGE);
            Message previousMessage = (Message) wrPreviousMessage.get();
            flowId = FlowIdHelper.getFlowId(previousMessage);
            if (flowId != null && LOG.isLoggable(Level.FINE)) {
                LOG.fine("flowId '" + flowId + "' found in previous message");
            }
        }

        if (flowId == null) {
            // No flowId found. Generate one.
            flowId = ContextUtils.generateUUID();
            if (LOG.isLoggable(Level.FINE)) {
                LOG.fine("Generate new flowId '" + flowId + "'");
            }
        }

        FlowIdHelper.setFlowId(message, flowId);
    }
246028
@Override
    protected void doRecv ( Response response ) throws IOException {
        CommonServerMessageBlock resp = (CommonServerMessageBlock) response;
        this.negotiated.setupResponse(response);
        try {
            if ( this.smb2 ) {
                doRecvSMB2(resp);
            }
            else {
                doRecvSMB1(resp);
            }
        }
        catch ( Exception e ) {
            log.warn("Failure decoding message, disconnecting transport", e);
            response.exception(e);
            synchronized ( response ) {
                response.notifyAll();
            }
            throw e;
        }

    }
636001
public void displaySuccess(final String message) {
        notificationMessage.showNotification(SPUIStyleDefinitions.SP_NOTIFICATION_SUCCESS_MESSAGE_STYLE, null, message,
                true);
    }
1250482
public void calculate(ServiceMessage message) {
    // client to service
    eval(
        message.header(SERVICE_RECV_TIME),
        message.header(CLIENT_SEND_TIME),
        (v1, v2) -> clientToServiceTimer.update(v1 - v2, TimeUnit.MILLISECONDS));

    // service to client
    eval(
        message.header(CLIENT_RECV_TIME),
        message.header(SERVICE_SEND_TIME),
        (v1, v2) -> serviceToClientTimer.update(v1 - v2, TimeUnit.MILLISECONDS));
  }
279971
@Override
	public void processMessage( Message message ) {

		if( message instanceof MsgNotifMachineDown )
			processMsgNotifMachineDown((MsgNotifMachineDown) message );

		else if( message instanceof MsgNotifInstanceChanged )
			processMsgNotifInstanceChanged((MsgNotifInstanceChanged) message );

		else if( message instanceof MsgNotifInstanceRemoved )
			processMsgNotifInstanceRemoved((MsgNotifInstanceRemoved) message );

		else if( message instanceof MsgNotifHeartbeat )
			processMsgNotifHeartbeat((MsgNotifHeartbeat) message );

		else if(message instanceof MsgNotifAutonomic)
			processMsgMonitoringEvent((MsgNotifAutonomic) message );

		else if( message instanceof MsgEcho )
			this.manager.debugMngr().notifyMsgEchoReceived((MsgEcho) message );

		else if( message instanceof MsgNotifLogs )
			processMsgNotifLogs((MsgNotifLogs) message );

		else
			this.logger.warning( "The DM got an undetermined message to process: " + message.getClass().getName());
	}
1176148
public void handleResponse(String response) {
        if (messageListener != null) {
            log.debug("Sending Http response");
            messageListener.onOutboundMessage(new RawMessage(response), null);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Sending Http response:" + NEWLINE + response);
            }
        }
    }
451849
protected void sendServerResponse(HttpMessage response) {
        designer.http().server(httpServer).send()
                .response(response.getStatusCode())
                .message(response);
    }
1198771
synchronized void dataResponseReceived(ClientWorldModelInterface worldModel,
      DataResponseMessage message) {
    // Check for snapshot request
    WorldState ws = null;
    ws = this.outstandingStates.get(Long.valueOf(message.getTicketNumber()));
    if (ws != null) {
      log.debug("Updating data for ticket {}:\n{}",
          Long.valueOf(message.getTicketNumber()), message);
      List<Attribute> attribList = new ArrayList<Attribute>();
      for (Attribute a : message.getAttributes()) {
        attribList.add(a);
      }
      ws.addState(message.getId(), attribList);
      return;
    }

    StepResponse resp = this.outstandingSteps.get(Long.valueOf(message
        .getTicketNumber()));
    if (resp == null) {
      log.error("Unknown request ticket number {}",
          Long.valueOf(message.getTicketNumber()));
      return;
    }
    log.debug("Updating data for ticket {}:\n{}",
        Long.valueOf(message.getTicketNumber()), message);
    ws = new WorldState();
    List<Attribute> attribList = new ArrayList<Attribute>();
    if (message.getAttributes() != null) {
      for (Attribute a : message.getAttributes()) {
        attribList.add(a);
      }
    }
    ws.addState(message.getId(), attribList);
    resp.addState(ws);
    return;
  }
380391
void closeTask(final byte[] message) {
    synchronized (this.contextLifeCycle) {
      if (!this.task.isPresent()) {
        LOG.log(Level.WARNING, "Received a close task while there was no task running. Ignoring.");
      } else {
        this.task.get().close(message);
      }
    }
  }
739959
@Override
	public void receiveResponse(Tree message) {

		// Verify protocol version
		if (checkVersion) {
			String ver = message.get("ver", "unknown");
			if (!PROTOCOL_VERSION.equals(ver)) {
				logger.warn("Invalid protocol version (" + ver + ")!");
				return;
			}
		}

		// Get response's unique ID
		String id = message.get("id", (String) null);
		if (id == null || id.isEmpty()) {
			logger.warn("Missing \"id\" property!", message);
			return;
		}

		// Incoming (response) stream handling
		IncomingStream responseStream;
		responseStreamReadLock.lock();
		try {
			responseStream = responseStreams.get(id);
		} finally {
			responseStreamReadLock.unlock();
		}
		if (responseStream != null) {
			boolean remove = false;
			try {
				if (responseStream.receive(message)) {
					remove = true;
				}
			} catch (Throwable error) {
				remove = true;

				// Write error to log file
				if (writeErrorsToLog) {
					logger.error("Unexpected error occurred while streaming!", error);
				}
			}
			if (remove) {
				responseStreamWriteLock.lock();
				try {
					responseStreams.remove(id);
				} finally {
					responseStreamWriteLock.unlock();
				}
			}
			return;
		}
		if (message.get("stream", false)) {
			responseStreamWriteLock.lock();
			try {
				responseStream = responseStreams.get(id);
				if (responseStream == null) {
					responseStream = new IncomingStream(nodeID, scheduler, streamTimeout);
					responseStreams.put(id, responseStream);
				}
			} finally {
				responseStreamWriteLock.unlock();
			}
			if (responseStream.receive(message)) {
				responseStreamWriteLock.lock();
				try {
					responseStreams.remove(id);
				} finally {
					responseStreamWriteLock.unlock();
				}
			}
			message.putObject("data", responseStream.getPacketStream());
		}

		// Get stored promise
		PendingPromise pending = promises.remove(id);
		if (pending == null) {
			logger.warn("Unknown (maybe timeouted) response received!", message);
			return;
		}
		try {

			// Get response status (successed or not?)
			boolean success = message.get("success", true);
			if (success) {

				// Ok -> resolve
				pending.promise.complete(message.get("data"));

			} else {

				// Failed -> reject
				Tree error = message.get("error");
				MoleculerError moleculerError;
				if (error == null) {
					moleculerError = new MoleculerError("Remote invocation failed!", null, "MoleculerError",
							pending.nodeID, false, 500, "UNKNOWN_ERROR", message);
				} else {
					moleculerError = MoleculerErrorUtils.create(error);
				}

				pending.promise.complete(moleculerError);
				logger.error(moleculerError.getMessage(), moleculerError);

				return;
			}
		} catch (Throwable cause) {
			logger.error("Unable to pass on incoming response!", cause);
		}
	}
719534
private void doListNode(final Message<JsonObject> message) {
    context.execute(new Action<Collection<String>>() {
      @Override
      public Collection<String> perform() {
        List<String> nodes = new ArrayList<>();
        for (String group : groups.keySet()) {
          nodes.addAll(groups.get(group));
        }
        return nodes;
      }
    }, new Handler<AsyncResult<Collection<String>>>() {
      @Override
      public void handle(AsyncResult<Collection<String>> result) {
        if (result.failed()) {
          message.reply(new JsonObject().putString("status", "error").putString("message", result.cause().getMessage()));
        } else {
          message.reply(new JsonObject().putString("status", "ok").putArray("result", new JsonArray(result.result().toArray(new String[result.result().size()]))));
        }
      }
    });
  }
1142432
function onPushNotificationRegistration(response) {
    if (resolveRegistrationEventResponse) {
        diag.debug.assert(!!rejectRegistrationEventResponse);
        resolveRegistrationEventResponse(response);
        resolveRegistrationEventResponse = undefined;
        rejectRegistrationEventResponse = undefined;
    }
    else {
        promiseRegistrationEventResponse = Q.resolve(response);
    }
    return promiseRegistrationEventResponse.done();
}
736368
private void doUndeployNetwork(final Message<JsonObject> message) {
    Object network = message.body().getValue("network");
    if (network != null) {
      // When undeploying a network from the cluster, we first determine
      // the node to which the network belongs by selecting a node.
      // The node that is selected for the network is always the node
      // that controls the network.
      String key;
      if (network instanceof String) {
        key = (String) network;
      } else if (network instanceof JsonObject) {
        try {
          key = serializer.deserializeObject((JsonObject) network, NetworkConfig.class).getName();
        } catch (SerializationException e) {
          message.reply(new JsonObject().putString("status", "error").putString("message", e.getMessage()));
          return;
        }
      } else {
        message.reply(new JsonObject().putString("status", "error").putString("message", "Invalid network configuration."));
        return;
      }

      selectNode(key, new Handler<AsyncResult<String>>() {
        @Override
        public void handle(AsyncResult<String> result) {
          if (result.failed()) {
            message.reply(new JsonObject().putString("status", "error").putString("message", result.cause().getMessage()));
          } else if (result.result() == null) {
            message.reply(new JsonObject().putString("status", "error").putString("message", "No nodes available."));
          } else {
            vertx.eventBus().sendWithTimeout(result.result(), message.body(), 120000, new Handler<AsyncResult<Message<JsonObject>>>() {
              @Override
              public void handle(AsyncResult<Message<JsonObject>> result) {
                if (result.failed()) {
                  message.reply(new JsonObject().putString("status", "error").putString("message", "Failed to reach node."));
                } else {
                  message.reply(result.result().body());
                }
              }
            });
          }
        }
      });
    } else {
      message.reply(new JsonObject().putString("status", "error").putString("message", "No network specified."));
    }
  }