Store the important parts of the request data for later use.

@param message
The JsonSimple message to store
@param oid
The Object to store the message in
@throws TransactionException
If an error occurred
775668
private void storeRequestData(JsonSimple message, String oid)
			throws TransactionException {

		// Get our incoming data to look at
		JsonObject toRespond = message.getObject("respond");
		JSONArray newRelations = message.getArray("relationships");
		if (toRespond == null && newRelations == null) {
			log.warn("This request requires no responses and specifies"
					+ " no relationships.");
			return;
		}

		// Get from storage
		DigitalObject object = null;
		Payload payload = null;
		InputStream inStream = null;
		try {
			object = storage.getObject(oid);
			payload = getDataPayload(object);
			inStream = payload.open();
		} catch (StorageException ex) {
			log.error("Error accessing object '{}' in storage: ", oid, ex);
			throw new TransactionException(ex);
		}

		// Parse existing data
		JsonSimple metadata = null;
		try {
			metadata = new JsonSimple(inStream);
			inStream.close();
		} catch (IOException ex) {
			log.error("Error parsing/reading JSON '{}'", oid, ex);
			throw new TransactionException(ex);
		}

		// Store our new response
		if (toRespond != null) {
			JSONArray responses = metadata.writeArray("responses");
			boolean duplicate = false;
			String newOid = (String) toRespond.get("oid");
			for (Object response : responses) {
				String oldOid = (String) ((JsonObject) response).get("oid");
				if (newOid.equals(oldOid)) {
					log.debug("Ignoring duplicate response request by '{}'"
							+ " on object '{}'", newOid, oid);
					duplicate = true;
				}
			}
			if (!duplicate) {
				log.debug("New response requested by '{}' on object '{}'",
						newOid, oid);
				responses.add(toRespond);
			}
		}

		// Store relationship(s), with some basic de-duping
		if (newRelations != null) {
			JSONArray relations = metadata.writeArray("relationships");
			for (JsonSimple newRelation : JsonSimple.toJavaList(newRelations)) {
				boolean duplicate = false;
				String identifier = newRelation.getString(null, "identifier");
				// Compare to each existing relationship
				for (JsonSimple relation : JsonSimple.toJavaList(relations)) {
					String storedId = relation.getString(null, "identifier");
					if (identifier.equals(storedId)) {
						log.debug("Ignoring duplicate relationship '{}'",
								identifier);
						duplicate = true;
					}
				}

				// Store new entries
				if (!duplicate) {
					log.debug("New relationship added to '{}'", oid);
					relations.add(newRelation.getJsonObject());
				}
			}
		}

		// Store modifications
		if (toRespond != null || newRelations != null) {
			log.info("Updating object in storage '{}'", oid);
			String jsonString = metadata.toString(true);
			try {
				updateDataPayload(object, jsonString);
			} catch (Exception ex) {
				log.error("Unable to store data '{}': ", oid, ex);
				throw new TransactionException(ex);
			}
		}
	}
1046535
public void cache(Identity oid, Object obj)
    {
        if (oid != null && obj != null)
        {
            ObjectCache cache = getCache(oid, obj, METHOD_CACHE);
            if (cache != null)
            {
                cache.cache(oid, obj);
            }
        }
    }
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);
    }
367885
@Override
  public void write(final T message) {
    this.link.write(new NSMessage<T>(this.srcId, this.destId, message));
  }
322785
public static void serializeTo( AbstractMessage message , RawDataBuffer out )
    {
        // Do we have a cached version of the raw message ?
    	RawDataBuffer rawMsg = message.getRawMessage();
        if (rawMsg != null)
        {
        	out.writeInt(rawMsg.size());
        	rawMsg.writeTo(out);
        }
        else
        {
            // Serialize the message
        	out.writeInt(0); // Write a dummy size
        	int startPos = out.size();
            out.writeByte(message.getType());
            message.serializeTo(out);
            int endPos = out.size();
            out.writeInt(endPos-startPos,startPos-4); // Update the actual size
        }
    }
141592
@Override
    public void serialize(Message message, OutputStream out) throws IOException {
        String name = names.get(message.getClass());
        if (name == null) {
            throw new Error("BitcoinSerializer doesn't currently know how to serialize " + message.getClass());
        }
        serialize(name, message.bitcoinSerialize(), out);
    }
1258669
@Override
    public void handleMessage(Message message) {

        handlersList = getHanderList(busType, flow);

        if (handlersList == null || handlersList.size() == 0) {

            return;
        }

        ArrayList<Handler> excutedHandlers = new ArrayList<Handler>();
        JAXRS20MessageContextImpl jaxrsMessageContext = new JAXRS20MessageContextImpl(message);
        jaxrsMessageContext.isServerSide = busType.equals(Type.SERVER);
        jaxrsMessageContext.isClientSide = busType.equals(Type.CLIENT);
        jaxrsMessageContext.setProperty(HandlerConstants.FLOW_TYPE, flow.toUpperCase());
        try {
            Iterator<Handler> it = handlersList.iterator();
            while (it.hasNext()) {
                Handler handler = it.next();
                handler.handleMessage(jaxrsMessageContext);
                excutedHandlers.add(handler);
            }
        } catch (Exception e) {
            for (int i = excutedHandlers.size() - 1; i >= 0; i--) {
                excutedHandlers.get(i).handleFault(jaxrsMessageContext);
            }
        }
    }
349604
private void audit(JsonSimple response, String oid, String message) {
		JsonObject order = newSubscription(response, oid);
		JsonObject messageObject = (JsonObject) order.get("message");
		messageObject.put("eventType", message);
	}
1097752
public void send(final long identifier, final SpecificRecord message) {
    if (sender != null) {
      sender.onNext(serializer.write(message, identifier));
    } else {
      final String msgClassName = message.getClass().getCanonicalName();
      LOG.log(Level.SEVERE, "Attempt to send message [{0}] before network is initialized", msgClassName);
      throw new RuntimeException("NetworkTransport not initialized: failed to send " + msgClassName);
    }
  }
267107
public void send(String apiKey, String queue, final Object message) {
        checkNotNull(queue, "queue");
        try {
            URI uri = _queueService.clone()
                    .segment(queue, "send")
                    .build();
            _client.resource(uri)
                    .type(MediaType.APPLICATION_JSON_TYPE)
                    .header(ApiKeyRequest.AUTHENTICATION_HEADER, apiKey)
                    // Wrap the message in a JSONWrappedObject that forces Jersey to use Jackson to serialize it
                    // no matter what the type.  Otherwise null and String objects don't get serialized correctly.
                    .post(new JSONWrappedObject("", "", message));
        } catch (EmoClientException e) {
            throw convertException(e);
        }
    }
166575
@Override
    @SuppressWarnings("unchecked")
    public void onMessage(StreamMessage message)
    {
        String endopointUri = getEndpointUri();

        Map<String, Object> resultMap;

        try
        {
            resultMap = this.converter.toMap(message);
        }
        catch (ConvertFailException ex)
        {
            String logFormat = "Fail convert to jdbc record. Dispose received message. : Message={0}";
            logger.warn(MessageFormat.format(logFormat, message), ex);
            ack();
            return;
        }

        List<Object> valueList = Lists.newArrayList();

        valueList.add(resultMap.get("messageId"));
        valueList.add(resultMap.get("timestamp"));
        valueList.add(resultMap.get("source"));

        List<String> bodyList = (List<String>) resultMap.get("body");

        valueList.addAll(bodyList);

        insert(endopointUri, valueList);
        ack();
    }
725011
void addNewMessage(JsMessageWrapper message, boolean isStored, boolean isRecoverable)
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc,
                  "addNewMessage",
                  new Object[] { new Integer(hashCode()),
                                 message,
                                 new Boolean(isStored)});

    JsMessage jsMsg = message.getMessage();

    long id = jsMsg.getSystemMessageValue();
    SIBUuid8 uuid = jsMsg.getSystemMessageSourceUuid();

    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
      SibTr.debug(tc,
                  "addNewMessage",
                  new Object[] { new Integer(hashCode()),
                                 new Long(jsMsg.getSystemMessageValue()),
                                 jsMsg.getSystemMessageSourceUuid(),
                                 message,
                                 new Boolean(isStored)});

    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
      SibTr.debug(localConsumerPoint, tc, "verboseMsg OUT : " + message.getMessage().toVerboseString());

    synchronized(this)
    {
      LMEMessage newElement = null;
      long messageReferenceExpiry = messageProcessor.getCustomProperties().get_message_reference_expiry_value();

      // We have to create an object if the pool is empty
      if(pooledMsg == null)
      {
        newElement = new LMEMessage(id, uuid, message, isStored, isRecoverable, messageLockExpiry, messageReferenceExpiry);
      }
      // Otherwise pop the first pooled object and use that
      else
      {
        newElement = pooledMsg;
        pooledMsg = pooledMsg.next;
        newElement.next = null;
        pooledCount--;

        newElement.reuseMessage(id, uuid, message, isStored, isRecoverable, messageLockExpiry, messageReferenceExpiry);
      }

      // Add the message to the end of the list
      newElement.previous = lastMsg;
      if(lastMsg != null)
        lastMsg.next = newElement;
      else
        firstMsg = newElement;
      lastMsg = newElement;

      // If the locks are set to expire and this is the first message we need to
      // register an alarm
      if(messageLockExpiry != 0)
      {
        // If there are no other messages expiring, this will be the first one
        if(nextMsgToExpire == null)
          nextMsgToExpire = newElement;

        // If we don't have an alarm registered, register one now
        if(!alarmRegistered)
        {
          if(TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            SibTr.debug(tc, "addNewMessage", "Registering MessageLock Expiry alarm for: " + nextMsgToExpire);

          alarmManager.create(messageLockExpiry, this);
          alarmRegistered = true;
        }
      }

      if (messageReferenceExpiry != 0)
      {
        if (messageLockExpiry != 0 && messageReferenceExpiry > messageLockExpiry)
        {
          // The messageReferenceExpiry is greater than the messageLockExpiry. There is no
          // point in creating the alarm for messageReferenceExpiry as the message lock expiry
          // will always go first.
          if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
          {
            SibTr.debug(tc, "MessageReferenceExpiry: "+messageReferenceExpiry+" is greater than messageLockExpiry: "+messageLockExpiry);
            SibTr.debug(tc, "MessageReferneceExpiry Alarm not registered");
          }
        }
        else
        {
          try
          {
            if (message.getReportCOD() == null)
            {
              // Now register the message reference expiry alarm
              // If there are no other message references expiring, this will be the first one
              if(nextMsgReferenceToExpire == null)
                nextMsgReferenceToExpire = newElement;

              // If we don't have an alarm registered, register one now
              if(!msgReferenceAlarmRegistered)
              {
                if(TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                  SibTr.debug(tc, "addNewMessage", "Registering MessageReference Expiry alarm for: " + nextMsgReferenceToExpire);

                alarmManager.create(messageReferenceExpiry, new MessageReferenceExpiryAlarm());
                msgReferenceAlarmRegistered = true;
              }
            }
          }
          catch(SIResourceException e)
          {
            // No FFDC code needed

            // There was a problem getting hold of the ReportCOD of the message
            // assume it is set and don't create the expiry alarm.
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
              SibTr.debug(tc, "Thrown exception when trying to create msg ref expiry alarm: " + e);
          }
        }
     }

      // By adding a message we must be about to call consumeMessages and therefore
      // we're in a valid state for calls
      validState = true;
    } // synchronized

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "addNewMessage", this);
  }
838995
private void doListGet(final Message<JsonObject> message) {
    final String name = message.body().getString("name");
    if (name == null) {
      message.reply(new JsonObject().putString("status", "error").putString("message", "No name specified."));
      return;
    }

    final Integer index = message.body().getInteger("index");
    if (index == null) {
      message.reply(new JsonObject().putString("status", "error").putString("message", "No index specified."));
      return;
    }

    context.execute(new Action<Object>() {
      @Override
      public Object perform() {
        return data.getList(formatKey(name)).get(index);
      }
    }, new Handler<AsyncResult<Object>>() {
      @Override
      public void handle(AsyncResult<Object> result) {
        if (result.failed()) {
          message.reply(new JsonObject().putString("status", "error").putString("message", result.cause().getMessage()));
        } else {
          message.reply(new JsonObject().putString("status", "ok").putValue("result", result.result()));
        }
      }
    });
  }
241258
private void updateDeletedObjectsThroughEntityManager(List<String> oids, Long timestamp) {
        for (String id : oids) {
            EDBObject o = new EDBObject(id);
            o.updateTimestamp(timestamp);
            o.setDeleted(true);
            JPAObject j = EDBUtils.convertEDBObjectToJPAObject(o);
            entityManager.persist(j);
        }
    }
668758
private void sendToIndex(String message) {
		try {
			getMessaging().queueMessage(SolrWrapperQueueConsumer.QUEUE_ID, message);
		} catch (MessagingException ex) {
			log.error("Unable to send message: ", ex);
		}
	}
653147
@Override
	public void receiveRequest(Tree message) {

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

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

		// Verify protocol version
		if (checkVersion) {
			String ver = message.get("ver", "unknown");
			if (!PROTOCOL_VERSION.equals(ver)) {
				logger.warn("Invalid protocol version (" + ver + ")!");
				transporter.publish(PACKET_RESPONSE, sender,
						throwableToTree(id, nodeID, new ProtocolVersionMismatchError(nodeID, PROTOCOL_VERSION, ver)));
				return;
			}
		}

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

				// Send error
				try {
					transporter.publish(PACKET_RESPONSE, sender, throwableToTree(id, nodeID, error));
				} catch (Throwable ignored) {
					logger.debug("Unable to send response!", ignored);
				}

				// Write error to log file
				if (writeErrorsToLog) {
					logger.error("Unexpected error occurred while streaming!", error);
				}

			}
			if (remove) {
				requestStreamWriteLock.lock();
				try {
					requestStreams.remove(id);
				} finally {
					requestStreamWriteLock.unlock();
				}
			}
		} else if (message.get("stream", false)) {
			requestStreamWriteLock.lock();
			try {
				requestStream = requestStreams.get(id);
				if (requestStream == null) {
					requestStream = new IncomingStream(nodeID, scheduler, streamTimeout);
					requestStreams.put(id, requestStream);
				}
			} finally {
				requestStreamWriteLock.unlock();
			}
			if (requestStream.receive(message)) {
				requestStreamWriteLock.lock();
				try {
					requestStreams.remove(id);
				} finally {
					requestStreamWriteLock.unlock();
				}
			}
		}

		// Get action property
		String action = message.get("action", (String) null);
		if (action == null || action.isEmpty()) {
			if (requestStream == null) {
				logger.warn("Missing \"action\" property!");
				transporter.publish(PACKET_RESPONSE, sender,
						throwableToTree(id, nodeID, new InvalidPacketDataError(nodeID)));
			}
			return;
		}
		if (requestStream != null && requestStream.inited()) {

			// Action method invoked (do not invoke twice)
			return;
		}

		// Get strategy (action endpoint array) by action name
		Strategy<ActionEndpoint> strategy = null;
		long stamp = lock.tryOptimisticRead();
		if (stamp != 0) {
			try {
				strategy = strategies.get(action);
			} catch (Exception modified) {
				stamp = 0;
			}
		}
		if (!lock.validate(stamp) || stamp == 0) {
			stamp = lock.readLock();
			try {
				strategy = strategies.get(action);
			} finally {
				lock.unlockRead(stamp);
			}
		}
		if (strategy == null) {
			logger.warn("Invalid action name (" + action + ")!");
			transporter.publish(PACKET_RESPONSE, sender,
					throwableToTree(id, nodeID, new ServiceNotFoundError(nodeID, action)));
			return;
		}

		// Get local action endpoint (with cache handling)
		ActionEndpoint endpoint = strategy.getEndpoint(nodeID);
		if (endpoint == null) {
			logger.warn("Not a local action (" + action + ")!");
			transporter.publish(PACKET_RESPONSE, sender,
					throwableToTree(id, nodeID, new ServiceNotAvailableError(nodeID, action)));
			return;
		}

		// Process params and meta
		Tree params = message.get("params");
		Tree meta = message.get("meta");
		if (meta != null && !meta.isEmpty()) {
			if (params == null) {
				params = new Tree();
			}
			params.getMeta().setObject(params);
		}

		// Get timeout
		int timeout = message.get("timeout", 0);
		CallOptions.Options opts;
		if (timeout > 0) {
			opts = CallOptions.timeout(timeout);
		} else {
			opts = null;
		}

		// Get other properties
		int level = message.get("level", 1);
		String parentID = message.get("parentID", (String) null);
		String requestID = message.get("requestID", id);

		// Create context
		Context ctx = contextFactory.create(action, params, opts,
				requestStream == null ? null : requestStream.getPacketStream(), id, level, requestID, parentID);

		// Invoke action
		try {
			new Promise(endpoint.handler(ctx)).then(data -> {

				// Send response
				FastBuildTree msg = new FastBuildTree(7);
				msg.putUnsafe("sender", nodeID);
				msg.putUnsafe("id", id);
				msg.putUnsafe("ver", PROTOCOL_VERSION);
				msg.putUnsafe("success", true);

				PacketStream responseStream = null;
				if (data != null) {
					Object d = data.asObject();
					if (d != null && d instanceof PacketStream) {
						msg.putUnsafe("stream", true);
						msg.putUnsafe("seq", 0);
						responseStream = (PacketStream) d;
					} else {
						msg.putUnsafe("data", d);
					}
					Tree m = data.getMeta(false);
					if (m != null && !m.isEmpty()) {
						msg.putUnsafe("meta", m);
					}
				}
				transporter.publish(PACKET_RESPONSE, sender, msg);

				// Define sender for response stream
				if (responseStream != null) {
					responseStream.onPacket(new PacketListener() {

						// Create sequence counter
						private final AtomicLong sequence = new AtomicLong();

						@Override
						public final void onPacket(byte[] bytes, Throwable cause, boolean close) {
							if (bytes != null) {
								transporter.sendDataPacket(PACKET_RESPONSE, sender, ctx, bytes,
										sequence.incrementAndGet());
							} else if (cause != null) {
								if (writeErrorsToLog) {
									logger.error("Unexpected error occured while streaming!", cause);
								}
								transporter.sendErrorPacket(PACKET_RESPONSE, sender, ctx, cause,
										sequence.incrementAndGet());
							}
							if (close) {
								transporter.sendClosePacket(PACKET_RESPONSE, sender, ctx, sequence.incrementAndGet());
							}
						}

					});
				}

			}).catchError(error -> {

				// Send error
				transporter.publish(PACKET_RESPONSE, sender, throwableToTree(id, nodeID, error));

				// Write error to log file
				if (writeErrorsToLog) {
					logger.error("Unexpected error occurred while invoking \"" + action + "\" action!", error);
				}

			});
		} catch (Throwable error) {

			// Send error
			transporter.publish(PACKET_RESPONSE, sender, throwableToTree(id, nodeID, error));

			// Write error to log file
			if (writeErrorsToLog) {
				logger.error("Unexpected error occurred while invoking \"" + action + "\" action!", error);
			}

		}

	}
626728
final void add(Message message)
        throws NullPointerException {

        if (message == null) {
            throw new NullPointerException("Message can't be null");
        }

        this.messages.get(message.getLevel()).add(message);
    }