/* (non-Javadoc)
@see nz.co.senanque.workflow.WorkflowManager#processMessage(nz.co.senanque.workflow.instances.ProcessInstance, org.springframework.integration.Message, nz.co.senanque.messaging.MessageMapper)
328318
@Transactional
	public void processMessage(ProcessInstance processInstance,
			Message<?> message, MessageMapper messageMapper) {
		Object context = getContextDAO().getContext(processInstance.getObjectInstance());
		processInstance.setStatus(TaskStatus.GO);
		try {
			messageMapper.unpackMessage(message, context);
		} catch (Exception e) {
			processInstance.setStatus(TaskStatus.ABORTING);
			processInstance.setComment(e.getMessage());
		}
		log.debug("set status to processInstance {} to {} {}",processInstance.getId(),processInstance.getStatus(),context);
		getContextDAO().mergeContext(context);
		getWorkflowDAO().mergeProcessInstance(processInstance);
		getWorkflowDAO().flush();
		if (log.isDebugEnabled()) {
			getWorkflowDAO().getActiveProcesses();
		}
	}
28401
@Override
    public void handleMessage(final Message message) throws Fault {
        final InputStream is = message.getContent(InputStream.class);
        if (WireTapHelper.isMessageContentToBeLogged(message, logMessageContent, logMessageContentOverride)) {
            if (null == is) {
                Reader reader = message.getContent(Reader.class);
                if (null != reader) {
                    String encoding = (String) message.get(Message.ENCODING);
                    if (encoding == null) {
                        encoding = "UTF-8";
                    }
                    try {
                        final CachedOutputStream cos = new CachedOutputStream();
                        final Writer writer = new OutputStreamWriter(cos, encoding);
                        IOUtils.copy(reader, writer, 1024);
                        reader.reset();
                        writer.flush();
                        message.setContent(InputStream.class, cos.getInputStream());
                        message.setContent(Reader.class, null);
                        message.setContent(CachedOutputStream.class, cos);
                        closeCachedOutputStream(message, cos);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    } finally {
                        try {
                            reader.reset();
                        } catch (IOException e) {
                        }
                    }
                }
            } else {
                try {
                    final CachedOutputStream cos = new CachedOutputStream();
                    // TODO: We should try to make this streaming
                    //WireTapInputStream wtis = new WireTapInputStream(is, cos);
                    //message.setContent(InputStream.class, wtis);
                    IOUtils.copyAndCloseInput(is, cos);
                    message.setContent(InputStream.class, cos.getInputStream());
                    message.setContent(CachedOutputStream.class, cos);
                    closeCachedOutputStream(message, cos);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }else {
            try {
                final CachedOutputStream cos = new CachedOutputStream();
                cos.write(WireTapHelper.CONTENT_LOGGING_IS_DISABLED.getBytes(Charset.forName("UTF-8")));
                message.setContent(CachedOutputStream.class, cos);
                message.setContent(InputStream.class, is);
                closeCachedOutputStream(message, cos);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
440906
public BaseMessage processMessage(BaseMessage internalMessage)
    {
        if (internalMessage.getMessageDataDesc(null) == null)
            internalMessage.addMessageDataDesc(new RunRemoteProcessMessageData(null, null));
        
        RunRemoteProcessMessageData runRemoteProcessMessageData = (RunRemoteProcessMessageData)internalMessage.getMessageDataDesc(null);
        String processClassName = (String)runRemoteProcessMessageData.get(RunRemoteProcessMessageData.PROCESS_CLASS_NAME);
        if (processClassName == null)
        	return null;
        
        BaseProcess process = null;
        Task task = this.getTask();
        Map<String,Object> properties = new HashMap<String,Object>();
        MapMessage.convertDOMtoMap(internalMessage.getDOM(), properties, true);
        process = (BaseProcess)ClassServiceUtility.getClassService().makeObjectFromClassName(processClassName);
        if (process == null)
        	return null;
        process.init(task, null, properties);
        
        BaseMessage messageReply = null;
        if (process instanceof BaseMessageProcess)
        	messageReply = ((BaseMessageProcess)process).processMessage(internalMessage);
        else
        	process.run();
      
        return messageReply;
    }
749204
public MessageProcessInfoModel getMessageProcessInfo(String strMessageInfoType, String strContactType, String strRequestType, String strMessageProcessType, String strProcessType)
    {
        return null;    // No thin impl
    }
829418
@Override
    public Message newMessage(final String message, final Object... params) {
        if (params == null) {
            return new SimpleMessage(message);
        }
        final ParameterizedMessage msg = new ParameterizedMessage(message, params);
        return new StatusMessage(msg.getFormattedMessage(), msg.getThrowable());
    }
272627
@Override
    public void handleMessage(final Message message) throws Fault {
        OutputStream os = message.getContent(OutputStream.class);

        if (null == os) {
            String encoding = (String) message.get(Message.ENCODING);
            if (encoding == null) {
                encoding = "UTF-8";
            }

            final Writer writer = message.getContent(Writer.class);
            if (null != writer) {
                os = new WriterOutputStream(writer, encoding);
                message.setContent(Writer.class,null);
            }
        }

        if (null != os) {
            final CacheAndWriteTapOutputStream newOut = new CacheAndWriteTapOutputStream(os);

            message.setContent(OutputStream.class, newOut);

            if (WireTapHelper
                    .isMessageContentToBeLogged(message, logMessageContent, logMessageContentOverride)) {
                message.setContent(CachedOutputStream.class, newOut);
            }else {
                try {
                    final CachedOutputStream cos = new CachedOutputStream();
                    cos.write(WireTapHelper.CONTENT_LOGGING_IS_DISABLED.getBytes(Charset.forName("UTF-8")));
                    message.setContent(CachedOutputStream.class, cos);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if (wireTap != null) {
                newOut.registerCallback(new CallBack(message));
            }
        }
    }
1371138
public void processMail(Folder folder)
    {
        try {
            int iCount = folder.getMessageCount();
            if (iCount == 0)
                return;

            String pattern = REPLY_STRING;
            Message[] messages = null;
            if (this.getProperty(PATTERN) == null)
            {
                messages = folder.getMessages();
            }
            else
            {
                pattern = this.getProperty(PATTERN);
                SubjectTerm st = new SubjectTerm(pattern);
                // Get some message references
                messages = folder.search(st);
            }
            
            for (int iMsgnum = 0; iMsgnum < messages.length; iMsgnum++)
            {
                Message message = messages[iMsgnum];
                String strSubject = message.getSubject();
                if (strSubject != null)
                    if ((pattern == null) || (strSubject.indexOf(pattern) != -1))
                        this.processThisMessage(message);
                message.setFlag(Flags.Flag.SEEN, true);  // Archives the message (so I don't process it again)
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
283136
@Override
	public void processEvent(SystemEvent event) throws AbortProcessingException {
		if (!FacesContext.getCurrentInstance().isPostback()) {
			// if (!(getParent() instanceof Column)) {
			insertLabelBeforeThisInputField();
			insertMessageBehindThisInputField();
		}
		// }
	}
1368091
@Override
    public void onMessage(Message message, Session session) throws JMSException {

        StandardLogger logger = LoggerUtil.getStandardLogger();
        try {
            String txt = ((TextMessage) message).getText();
            if (logger.isDebugEnabled()) {
                logger.debug("JMS Spring ExternalEvent Listener receives request: " + txt);
            }
            String resp;
            ListenerHelper helper = new ListenerHelper();
            Map<String, String> metaInfo = new HashMap<String, String>();
            metaInfo.put(Listener.METAINFO_PROTOCOL, Listener.METAINFO_PROTOCOL_JMS);
            metaInfo.put(Listener.METAINFO_REQUEST_PATH, ((Queue)message.getJMSDestination()).getQueueName());
            metaInfo.put(Listener.METAINFO_SERVICE_CLASS, this.getClass().getName());
            metaInfo.put(Listener.METAINFO_REQUEST_ID, message.getJMSMessageID());
            metaInfo.put(Listener.METAINFO_CORRELATION_ID, message.getJMSCorrelationID());
            if (message.getJMSReplyTo() != null)
                metaInfo.put("ReplyTo", message.getJMSReplyTo().toString());

            resp = helper.processEvent(txt, metaInfo);
            String correlId = message.getJMSCorrelationID();

            Queue respQueue = (Queue) message.getJMSReplyTo();
            if (resp != null && respQueue != null) {
                mdwMessageProducer.sendMessage(resp, respQueue, correlId);
                if (logger.isDebugEnabled()) {
                    logger.debug("JMS Listener sends response (corr id='" + correlId + "'): "
                            + resp);
                }

            }

        }
        catch (Throwable ex) {
            logger.severeException(ex.getMessage(), ex);
        }

    }
417888
@Operation(name = JpaConstants.OPERATION_PROCESS_MESSAGE, idempotent = false)
	public IBaseBundle processMessage(
		HttpServletRequest theServletRequest,
		RequestDetails theRequestDetails,

		@OperationParam(name = "content", min = 1, max = 1)
		@Description(formalDefinition = "The message to process (or, if using asynchronous messaging, it may be a response message to accept)")
			Bundle theMessageToProcess
	) {

		startRequest(theServletRequest);
		try {
			return getDao().processMessage(theRequestDetails, theMessageToProcess);
		} finally {
			endRequest(theServletRequest);
		}

	}
824076
public void sendMessage(String message)
    throws ProcessException {
        try {
            HttpHelper httpHelper = new HttpHelper(getURL(destination));
            httpHelper.post(message);
        } catch (Exception e) {
            throw new ProcessException(-1, e.getMessage(), e);
        }
    }
377704
@Override
    public void doMessageReceivedListeners(final long sessionId, final long sessionReadBytes, final Object message) {
        runManagementTask(new Runnable() {
            @Override
            public void run() {
                try {
                    // The particular management listeners change on strategy, so get them here.
                    for (final GatewayManagementListener listener : getManagementListeners()) {
                        listener.doMessageReceived(GatewayManagementBeanImpl.this, sessionId);
                    }

                    markChanged();  // mark ourselves as changed, possibly tell listeners
                } catch (Exception ex) {
                    logger.warn("Error during messageReceived gateway listener notifications:", ex);
                }
            }
        });
    }
323582
@Override
  public void onReceivePassThroughMessage(Context context, com.xiaomi.mipush.sdk.MiPushMessage miPushMessage) {
    processMiPushMessage(miPushMessage);
  }
276591
protected void handleMessage(@NonNull VoidMessage message) {
        if (message == null) {
            //            log.info("sI_{} got null message", getShardIndex());
            return;
        }

        if (message.getTargetId() >= 0 && message.getTargetId() != shardIndex) {
            log.warn("sI_{}: Skipping message: [{}]; TargetIdx: [{}]", shardIndex, message.getClass().getSimpleName(),
                            message.getTargetId());
            return;
        }

        //      log.info("sI_{}: Processing message: [{}]", shardIndex, message.getClass().getSimpleName());

        message.attachContext(voidConfiguration, trainer, clipboard, transport, storage, nodeRole, shardIndex);
        message.processMessage();
    }
687871
public void sendMessage(Message message)
    {
        ((DualMessageQueue)this.getMessageQueue()).getMessageStack().sendMessage(message);
        
        ((BaseMessage)message).setProcessedByClient(true);     // Make sure any server doesn't send this back up.

        super.sendMessage(message);
    }
1326872
public BaseMessage processMessage(BaseMessage message)
    {
        if (message == null)
            return null;
        this.updateLogFiles(message, true);  // Need to change log status to SENTOK (also associate return message log trx ID) (todo)
        String strReturnQueueName = null;
        if (message.getMessageHeader() instanceof TrxMessageHeader)
            strReturnQueueName = (String)((TrxMessageHeader)message.getMessageHeader()).getMessageHeaderMap().get(MessageConstants.RETURN_QUEUE_NAME);
        if (strReturnQueueName == null)
            strReturnQueueName = MessageConstants.TRX_RETURN_QUEUE;
        TrxMessageHeader privateMessageHeader = new TrxMessageHeader(strReturnQueueName, MessageConstants.INTERNET_QUEUE, null);
        if (message.getMessageHeader().getRegistryIDMatch() == null)
        {   // The registry is probably in the message header
            Integer intRegistryID = this.getRegistryID(message);
            if (intRegistryID != null)
                message.getMessageHeader().setRegistryIDMatch(intRegistryID);
        }
        privateMessageHeader.setRegistryIDMatch(message.getMessageHeader().getRegistryIDMatch());
        message.setMessageHeader(privateMessageHeader);

        Environment env = null;
        if ((this.getTask() != null)
            && (this.getTask().getApplication() != null))
                env = ((BaseApplication)this.getTask().getApplication()).getEnvironment();
        if (env == null)
            env = Environment.getEnvironment(null);
        App app = null;
        if (this.getTask() != null)
        	app = this.getTask().getApplication();
        MessageManager msgManager = env.getMessageManager(app, true);
        msgManager.sendMessage(message);
        return null;
    }
159270
@Override
    public void handleMessage(Message message) throws Fault {
        String method = (String) message.get(Message.HTTP_REQUEST_METHOD);
        String query = (String) message.get(Message.QUERY_STRING);
        if (!"GET".equals(method) || StringUtils.isEmpty(query)) {
            return;
        }
        String baseUri = (String) message.get(Message.REQUEST_URL);
        String ctx = (String) message.get(Message.PATH_INFO);

        //cannot have two wsdl's being written for the same endpoint at the same
        //time as the addresses may get mixed up
        synchronized (message.getExchange().getEndpoint()) {
            Map<String, String> map = UrlUtils.parseQueryString(query);
            if (isRecognizedQuery(map, baseUri, ctx,
                                  message.getExchange().getEndpoint().getEndpointInfo())) {

                try {
                    Conduit c = message.getExchange().getDestination().getBackChannel(message, null, null);
                    Message mout = new MessageImpl();
                    mout.setExchange(message.getExchange());
                    message.getExchange().setOutMessage(mout);
                    //Customize the response to 404
                    mout.put(Message.RESPONSE_CODE, HttpURLConnection.HTTP_NOT_FOUND);
                    mout.put(Message.CONTENT_TYPE, "text/xml");
                    c.prepare(mout);
                    OutputStream os = mout.getContent(OutputStream.class);

                    Document doc = getDocument(message,
                                               baseUri,
                                               map,
                                               ctx,
                                               message.getExchange().getEndpoint().getEndpointInfo());

                    String enc = null;
                    try {
                        enc = doc.getXmlEncoding();
                    } catch (Exception ex) {
                        //ignore - not dom level 3
                    }
                    if (enc == null) {
                        enc = "utf-8";
                    }

                    XMLStreamWriter writer = null;
                    try {
                        writer = StaxUtils.createXMLStreamWriter(os, enc);
                        StaxUtils.writeNode(doc, writer, true);
                        message.getInterceptorChain().abort();
                        writer.flush();
                        os.flush();
                    } catch (IOException ex) {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isInfoEnabled()) {
                            Tr.info(tc, "error.write.wsdl.stream", ex);
                        }
                        //LOG.log(Level.FINE, "Failure writing full wsdl to the stream", ex);
                        //we can ignore this.   Likely, whatever has requested the WSDL
                        //has closed the connection before reading the entire wsdl.  
                        //WSDL4J has a tendency to not read the closing tags and such
                        //and thus can sometimes hit this.   In anycase, it's 
                        //pretty much ignorable and nothing we can do about it (cannot
                        //send a fault or anything anyway
                    } finally {
                        if (writer != null) {
                            try {
                                writer.close();
                            } catch (Exception e) {
                            }
                        }
                        try {
                            os.close();
                        } catch (Exception e) {
                        }
                    }
                } catch (IOException e) {
                    throw new Fault(e);
                } catch (XMLStreamException e) {
                    throw new Fault(e);
                } finally {
                    message.getExchange().setOutMessage(null);
                }
            }
        }
    }