Search in sources :

Example 1 with IBulkDataListener

use of nl.nn.adapterframework.core.IBulkDataListener in project iaf by ibissource.

the class BrowseExecute method exportMessage.

private void exportMessage(IMessageBrowser mb, String id, ReceiverBase receiver, ZipOutputStream zipOutputStream) {
    IListener listener = null;
    if (receiver != null) {
        listener = receiver.getListener();
    }
    try {
        Object rawmsg = mb.browseMessage(id);
        IMessageBrowsingIteratorItem msgcontext = mb.getContext(id);
        try {
            String msg = null;
            String msgId = msgcontext.getId();
            String msgMid = msgcontext.getOriginalId();
            String msgCid = msgcontext.getCorrelationId();
            HashMap context = new HashMap();
            if (listener != null) {
                msg = listener.getStringFromRawMessage(rawmsg, context);
            } else {
                msg = (String) rawmsg;
            }
            if (StringUtils.isEmpty(msg)) {
                msg = "<no message found>";
            }
            if (msgId == null) {
                msgId = "";
            }
            if (msgMid == null) {
                msgMid = "";
            }
            if (msgCid == null) {
                msgCid = "";
            }
            String filename = "msg_" + id + "_id[" + msgId.replace(':', '-') + "]" + "_mid[" + msgMid.replace(':', '-') + "]" + "_cid[" + msgCid.replace(':', '-') + "]";
            ZipEntry zipEntry = new ZipEntry(filename + ".txt");
            String sentDateString = (String) context.get(IPipeLineSession.tsSentKey);
            if (StringUtils.isNotEmpty(sentDateString)) {
                try {
                    Date sentDate = DateUtils.parseToDate(sentDateString, DateUtils.FORMAT_FULL_GENERIC);
                    zipEntry.setTime(sentDate.getTime());
                } catch (Throwable e) {
                    error(", ", "errors.generic", "Could not set date for message [" + id + "]", e);
                }
            } else {
                Date insertDate = msgcontext.getInsertDate();
                if (insertDate != null) {
                    zipEntry.setTime(insertDate.getTime());
                }
            }
            // String comment=msgcontext.getCommentString();
            // if (StringUtils.isNotEmpty(comment)) {
            // zipEntry.setComment(comment);
            // }
            zipOutputStream.putNextEntry(zipEntry);
            String encoding = Misc.DEFAULT_INPUT_STREAM_ENCODING;
            if (msg.startsWith("<?xml")) {
                int lastpos = msg.indexOf("?>");
                if (lastpos > 0) {
                    String prefix = msg.substring(6, lastpos);
                    int encodingStartPos = prefix.indexOf("encoding=\"");
                    if (encodingStartPos > 0) {
                        int encodingEndPos = prefix.indexOf('"', encodingStartPos + 10);
                        if (encodingEndPos > 0) {
                            encoding = prefix.substring(encodingStartPos + 10, encodingEndPos);
                            log.debug("parsed encoding [" + encoding + "] from prefix [" + prefix + "]");
                        }
                    }
                }
            }
            zipOutputStream.write(msg.getBytes(encoding));
            if (listener != null && listener instanceof IBulkDataListener) {
                IBulkDataListener bdl = (IBulkDataListener) listener;
                String bulkfilename = bdl.retrieveBulkData(rawmsg, msg, context);
                zipOutputStream.closeEntry();
                File bulkfile = new File(bulkfilename);
                zipEntry = new ZipEntry(filename + "_" + bulkfile.getName());
                zipEntry.setTime(bulkfile.lastModified());
                zipOutputStream.putNextEntry(zipEntry);
                StreamUtil.copyStream(new FileInputStream(bulkfile), zipOutputStream, 32000);
                bulkfile.delete();
            }
            zipOutputStream.closeEntry();
        } finally {
            msgcontext.release();
        }
    } catch (Throwable e) {
        error(", ", "errors.generic", "Could not export message with id [" + id + "]", e);
    }
}
Also used : IBulkDataListener(nl.nn.adapterframework.core.IBulkDataListener) HashMap(java.util.HashMap) IMessageBrowsingIteratorItem(nl.nn.adapterframework.core.IMessageBrowsingIteratorItem) IListener(nl.nn.adapterframework.core.IListener) ZipEntry(java.util.zip.ZipEntry) File(java.io.File) Date(java.util.Date) FileInputStream(java.io.FileInputStream)

Example 2 with IBulkDataListener

use of nl.nn.adapterframework.core.IBulkDataListener in project iaf by ibissource.

the class Receiver method processMessageInAdapter.

/*
	 * Assumes message is read, and when transacted, transaction is still open.
	 */
private Message processMessageInAdapter(Object rawMessageOrWrapper, Message message, String messageId, String technicalCorrelationId, Map<String, Object> threadContext, long waitingDuration, boolean manualRetry, boolean duplicatesAlreadyChecked) throws ListenerException {
    long startProcessingTimestamp = System.currentTimeMillis();
    // if (message==null) {
    // requestSizeStatistics.addValue(0);
    // } else {
    // requestSizeStatistics.addValue(message.length());
    // }
    lastMessageDate = startProcessingTimestamp;
    log.debug(getLogPrefix() + "received message with messageId [" + messageId + "] (technical) correlationId [" + technicalCorrelationId + "]");
    if (StringUtils.isEmpty(messageId)) {
        messageId = Misc.createSimpleUUID();
        if (log.isDebugEnabled())
            log.debug(getLogPrefix() + "generated messageId [" + messageId + "]");
    }
    if (getChompCharSize() != null || getElementToMove() != null || getElementToMoveChain() != null) {
        log.debug(getLogPrefix() + "compact received message");
        try {
            CompactSaxHandler handler = new CompactSaxHandler();
            handler.setChompCharSize(getChompCharSize());
            handler.setElementToMove(getElementToMove());
            handler.setElementToMoveChain(getElementToMoveChain());
            handler.setElementToMoveSessionKey(getElementToMoveSessionKey());
            handler.setRemoveCompactMsgNamespaces(isRemoveCompactMsgNamespaces());
            handler.setContext(threadContext);
            try {
                XmlUtils.parseXml(message.asInputSource(), handler);
                message = new Message(handler.getXmlString());
            } catch (Exception e) {
                warn("received message could not be compacted: " + e.getMessage());
            }
            handler = null;
        } catch (Exception e) {
            String msg = "error during compacting received message to more compact format";
            error(msg, e);
            throw new ListenerException(msg, e);
        }
    }
    String businessCorrelationId = null;
    if (correlationIDTp != null) {
        try {
            message.preserve();
            businessCorrelationId = correlationIDTp.transform(message, null);
        } catch (Exception e) {
            // throw new ListenerException(getLogPrefix()+"could not extract businessCorrelationId",e);
            log.warn(getLogPrefix() + "could not extract businessCorrelationId");
        }
        if (StringUtils.isEmpty(businessCorrelationId)) {
            String cidText;
            if (StringUtils.isNotEmpty(getCorrelationIDXPath())) {
                cidText = "xpathExpression [" + getCorrelationIDXPath() + "]";
            } else {
                cidText = "styleSheet [" + getCorrelationIDStyleSheet() + "]";
            }
            if (StringUtils.isNotEmpty(technicalCorrelationId)) {
                log.info(getLogPrefix() + "did not find correlationId using " + cidText + ", reverting to correlationId of transfer [" + technicalCorrelationId + "]");
                businessCorrelationId = technicalCorrelationId;
            }
        }
    } else {
        businessCorrelationId = technicalCorrelationId;
    }
    if (StringUtils.isEmpty(businessCorrelationId) && StringUtils.isNotEmpty(messageId)) {
        log.info(getLogPrefix() + "did not find (technical) correlationId, reverting to messageId [" + messageId + "]");
        businessCorrelationId = messageId;
    }
    log.info(getLogPrefix() + "messageId [" + messageId + "] technicalCorrelationId [" + technicalCorrelationId + "] businessCorrelationId [" + businessCorrelationId + "]");
    threadContext.put(PipeLineSession.businessCorrelationIdKey, businessCorrelationId);
    String label = null;
    if (labelTp != null) {
        try {
            message.preserve();
            label = labelTp.transform(message, null);
        } catch (Exception e) {
            // throw new ListenerException(getLogPrefix()+"could not extract label",e);
            log.warn(getLogPrefix() + "could not extract label: (" + ClassUtils.nameOf(e) + ") " + e.getMessage());
        }
    }
    try {
        final Message messageFinal = message;
        if (!duplicatesAlreadyChecked && hasProblematicHistory(messageId, manualRetry, rawMessageOrWrapper, () -> messageFinal, threadContext, businessCorrelationId)) {
            if (!isTransacted()) {
                log.warn(getLogPrefix() + "received message with messageId [" + messageId + "] which has a problematic history; aborting processing");
            }
            numRejected.increase();
            setExitState(threadContext, ExitState.REJECTED, 500);
            return Message.nullMessage();
        }
        if (isDuplicateAndSkip(getMessageBrowser(ProcessState.DONE), messageId, businessCorrelationId)) {
            setExitState(threadContext, ExitState.SUCCESS, 304);
            return Message.nullMessage();
        }
        if (getCachedProcessResult(messageId) != null) {
            numRetried.increase();
        }
    } catch (Exception e) {
        String msg = "exception while checking history";
        error(msg, e);
        throw wrapExceptionAsListenerException(e);
    }
    IbisTransaction itx = new IbisTransaction(txManager, getTxDef(), "receiver [" + getName() + "]");
    // update processing statistics
    // count in processing statistics includes messages that are rolled back to input
    startProcessingMessage(waitingDuration);
    PipeLineSession pipelineSession = null;
    String errorMessage = "";
    boolean messageInError = false;
    Message result = null;
    PipeLineResult pipeLineResult = null;
    try {
        Message pipelineMessage;
        if (getListener() instanceof IBulkDataListener) {
            try {
                IBulkDataListener<M> bdl = (IBulkDataListener<M>) getListener();
                pipelineMessage = new Message(bdl.retrieveBulkData(rawMessageOrWrapper, message, threadContext));
            } catch (Throwable t) {
                errorMessage = t.getMessage();
                messageInError = true;
                error("exception retrieving bulk data", t);
                ListenerException l = wrapExceptionAsListenerException(t);
                throw l;
            }
        } else {
            pipelineMessage = message;
        }
        numReceived.increase();
        // Note: errorMessage is used to pass value from catch-clause to finally-clause!
        pipelineSession = createProcessingContext(businessCorrelationId, threadContext, messageId);
        // threadContext=pipelineSession; // this is to enable Listeners to use session variables, for instance in afterProcessMessage()
        try {
            if (getMessageLog() != null) {
                getMessageLog().storeMessage(messageId, businessCorrelationId, new Date(), RCV_MESSAGE_LOG_COMMENTS, label, pipelineMessage);
            }
            log.debug(getLogPrefix() + "preparing TimeoutGuard");
            TimeoutGuard tg = new TimeoutGuard("Receiver " + getName());
            try {
                if (log.isDebugEnabled())
                    log.debug(getLogPrefix() + "activating TimeoutGuard with transactionTimeout [" + getTransactionTimeout() + "]s");
                tg.activateGuard(getTransactionTimeout());
                pipeLineResult = adapter.processMessageWithExceptions(businessCorrelationId, pipelineMessage, pipelineSession);
                setExitState(threadContext, pipeLineResult.getState(), pipeLineResult.getExitCode());
                pipelineSession.put("exitcode", "" + pipeLineResult.getExitCode());
                result = pipeLineResult.getResult();
                errorMessage = "exitState [" + pipeLineResult.getState() + "], result [";
                if (!Message.isEmpty(result) && result.size() > ITransactionalStorage.MAXCOMMENTLEN) {
                    // Since we can determine the size, assume the message is preserved
                    errorMessage += result.asString().substring(0, ITransactionalStorage.MAXCOMMENTLEN);
                } else {
                    errorMessage += result;
                }
                errorMessage += "]";
                int status = pipeLineResult.getExitCode();
                if (status > 0) {
                    errorMessage += ", exitcode [" + status + "]";
                }
                if (log.isDebugEnabled()) {
                    log.debug(getLogPrefix() + "received result: " + errorMessage);
                }
                messageInError = itx.isRollbackOnly();
            } finally {
                log.debug(getLogPrefix() + "canceling TimeoutGuard, isInterrupted [" + Thread.currentThread().isInterrupted() + "]");
                if (tg.cancel()) {
                    errorMessage = "timeout exceeded";
                    if (Message.isEmpty(result)) {
                        result = new Message("<timeout/>");
                    }
                    messageInError = true;
                }
            }
            if (!messageInError && !isTransacted()) {
                messageInError = !pipeLineResult.isSuccessful();
            }
        } catch (Throwable t) {
            if (TransactionSynchronizationManager.isActualTransactionActive()) {
                log.debug("<*>" + getLogPrefix() + "TX Update: Received failure, transaction " + (itx.isRollbackOnly() ? "already" : "not yet") + " marked for rollback-only");
            }
            error("Exception in message processing", t);
            errorMessage = t.getMessage();
            messageInError = true;
            if (pipeLineResult == null) {
                pipeLineResult = new PipeLineResult();
            }
            if (Message.isEmpty(pipeLineResult.getResult())) {
                pipeLineResult.setResult(adapter.formatErrorMessage("exception caught", t, message, messageId, this, startProcessingTimestamp));
            }
            throw wrapExceptionAsListenerException(t);
        } finally {
            putSessionKeysIntoThreadContext(threadContext, pipelineSession);
        }
        // }
        if (getSender() != null) {
            String sendMsg = sendResultToSender(result);
            if (sendMsg != null) {
                errorMessage = sendMsg;
            }
        }
    } finally {
        try {
            cacheProcessResult(messageId, errorMessage, new Date(startProcessingTimestamp));
            if (!isTransacted() && messageInError && !manualRetry) {
                final Message messageFinal = message;
                moveInProcessToError(messageId, businessCorrelationId, () -> messageFinal, new Date(startProcessingTimestamp), errorMessage, rawMessageOrWrapper, TXNEW_CTRL);
            }
            try {
                Map<String, Object> afterMessageProcessedMap = threadContext;
                if (pipelineSession != null) {
                    threadContext.putAll(pipelineSession);
                }
                try {
                    if (getListener() instanceof IHasProcessState && !itx.isRollbackOnly()) {
                        ProcessState targetState = messageInError && knownProcessStates.contains(ProcessState.ERROR) ? ProcessState.ERROR : ProcessState.DONE;
                        changeProcessState(rawMessageOrWrapper, targetState, errorMessage);
                    }
                    getListener().afterMessageProcessed(pipeLineResult, rawMessageOrWrapper, afterMessageProcessedMap);
                } catch (Exception e) {
                    if (manualRetry) {
                        // Somehow messages wrapped in MessageWrapper are in the ITransactionalStorage.
                        // This might cause class cast exceptions.
                        // There are, however, also Listeners that might use MessageWrapper as their raw message type,
                        // like JdbcListener
                        error("Exception post processing after retry of message messageId [" + messageId + "] cid [" + technicalCorrelationId + "]", e);
                    } else {
                        error("Exception post processing message messageId [" + messageId + "] cid [" + technicalCorrelationId + "]", e);
                    }
                    throw wrapExceptionAsListenerException(e);
                }
            } finally {
                long finishProcessingTimestamp = System.currentTimeMillis();
                finishProcessingMessage(finishProcessingTimestamp - startProcessingTimestamp);
                if (!itx.isCompleted()) {
                    // NB: Spring will take care of executing a commit or a rollback;
                    // Spring will also ONLY commit the transaction if it was newly created
                    // by the above call to txManager.getTransaction().
                    // txManager.commit(txStatus);
                    itx.commit();
                } else {
                    String msg = "Transaction already completed; we didn't expect this";
                    warn(msg);
                    throw new ListenerException(getLogPrefix() + msg);
                }
            }
        } finally {
            if (pipelineSession != null) {
                if (!Message.isEmpty(result) && result.isScheduledForCloseOnExitOf(pipelineSession)) {
                    // Don't close Message in case it's passed to a 'parent' adapter or ServiceDispatcher.
                    log.debug("unscheduling result message from close on exit");
                    result.unscheduleFromCloseOnExitOf(pipelineSession);
                }
                pipelineSession.close();
            }
        }
    }
    if (log.isDebugEnabled())
        log.debug(getLogPrefix() + "messageId [" + messageId + "] correlationId [" + businessCorrelationId + "] returning result [" + result + "]");
    return result;
}
Also used : Message(nl.nn.adapterframework.stream.Message) PipeLineSession(nl.nn.adapterframework.core.PipeLineSession) TimeoutGuard(nl.nn.adapterframework.task.TimeoutGuard) TimeoutException(nl.nn.adapterframework.core.TimeoutException) SenderException(nl.nn.adapterframework.core.SenderException) ListenerException(nl.nn.adapterframework.core.ListenerException) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) Date(java.util.Date) IHasProcessState(nl.nn.adapterframework.core.IHasProcessState) ProcessState(nl.nn.adapterframework.core.ProcessState) ListenerException(nl.nn.adapterframework.core.ListenerException) IBulkDataListener(nl.nn.adapterframework.core.IBulkDataListener) CompactSaxHandler(nl.nn.adapterframework.util.CompactSaxHandler) IHasProcessState(nl.nn.adapterframework.core.IHasProcessState) IbisTransaction(nl.nn.adapterframework.core.IbisTransaction) PipeLineResult(nl.nn.adapterframework.core.PipeLineResult) INamedObject(nl.nn.adapterframework.core.INamedObject)

Example 3 with IBulkDataListener

use of nl.nn.adapterframework.core.IBulkDataListener in project iaf by ibissource.

the class ReceiverBase method processMessageInAdapter.

/*
	 * Assumes message is read, and when transacted, transaction is still open.
	 */
private String processMessageInAdapter(IListener origin, Object rawMessage, String message, String messageId, String technicalCorrelationId, Map threadContext, long waitingDuration, boolean manualRetry) throws ListenerException {
    String result = null;
    PipeLineResult pipeLineResult = null;
    long startProcessingTimestamp = System.currentTimeMillis();
    // if (message==null) {
    // requestSizeStatistics.addValue(0);
    // } else {
    // requestSizeStatistics.addValue(message.length());
    // }
    lastMessageDate = startProcessingTimestamp;
    log.debug(getLogPrefix() + "received message with messageId [" + messageId + "] (technical) correlationId [" + technicalCorrelationId + "]");
    if (StringUtils.isEmpty(messageId)) {
        messageId = Misc.createSimpleUUID();
        if (log.isDebugEnabled())
            log.debug(getLogPrefix() + "generated messageId [" + messageId + "]");
    }
    if (getChompCharSize() != null || getElementToMove() != null || getElementToMoveChain() != null) {
        log.debug(getLogPrefix() + "compact received message");
        try {
            InputStream xmlInput = IOUtils.toInputStream(message, "UTF-8");
            CompactSaxHandler handler = new CompactSaxHandler();
            handler.setChompCharSize(getChompCharSize());
            handler.setElementToMove(getElementToMove());
            handler.setElementToMoveChain(getElementToMoveChain());
            handler.setElementToMoveSessionKey(getElementToMoveSessionKey());
            handler.setRemoveCompactMsgNamespaces(isRemoveCompactMsgNamespaces());
            if (threadContext != null) {
                handler.setContext(threadContext);
            }
            SAXParserFactory parserFactory = XmlUtils.getSAXParserFactory();
            parserFactory.setNamespaceAware(true);
            SAXParser saxParser = parserFactory.newSAXParser();
            try {
                saxParser.parse(xmlInput, handler);
                message = handler.getXmlString();
            } catch (Exception e) {
                warn("received message could not be compacted: " + e.getMessage());
            }
            handler = null;
        } catch (Exception e) {
            throw new ListenerException("error during compacting received message to more compact format: " + e.getMessage());
        }
    }
    String businessCorrelationId = null;
    if (correlationIDTp != null) {
        try {
            businessCorrelationId = correlationIDTp.transform(message, null);
        } catch (Exception e) {
            // throw new ListenerException(getLogPrefix()+"could not extract businessCorrelationId",e);
            log.warn(getLogPrefix() + "could not extract businessCorrelationId");
        }
        if (StringUtils.isEmpty(businessCorrelationId)) {
            String cidText;
            if (StringUtils.isNotEmpty(getCorrelationIDXPath())) {
                cidText = "xpathExpression [" + getCorrelationIDXPath() + "]";
            } else {
                cidText = "styleSheet [" + getCorrelationIDStyleSheet() + "]";
            }
            if (StringUtils.isNotEmpty(technicalCorrelationId)) {
                log.info(getLogPrefix() + "did not find correlationId using " + cidText + ", reverting to correlationId of transfer [" + technicalCorrelationId + "]");
                businessCorrelationId = technicalCorrelationId;
            }
        }
    } else {
        businessCorrelationId = technicalCorrelationId;
    }
    if (StringUtils.isEmpty(businessCorrelationId)) {
        if (StringUtils.isNotEmpty(messageId)) {
            log.info(getLogPrefix() + "did not find (technical) correlationId, reverting to messageId [" + messageId + "]");
            businessCorrelationId = messageId;
        }
    }
    log.info(getLogPrefix() + "messageId [" + messageId + "] technicalCorrelationId [" + technicalCorrelationId + "] businessCorrelationId [" + businessCorrelationId + "]");
    threadContext.put(IPipeLineSession.businessCorrelationIdKey, businessCorrelationId);
    String label = null;
    if (labelTp != null) {
        try {
            label = labelTp.transform(message, null);
        } catch (Exception e) {
            // throw new ListenerException(getLogPrefix()+"could not extract label",e);
            log.warn(getLogPrefix() + "could not extract label: (" + ClassUtils.nameOf(e) + ") " + e.getMessage());
        }
    }
    if (hasProblematicHistory(messageId, manualRetry, rawMessage, message, threadContext, businessCorrelationId)) {
        if (!isTransacted()) {
            log.warn(getLogPrefix() + "received message with messageId [" + messageId + "] which has a problematic history; aborting processing");
        }
        numRejected.increase();
        return result;
    }
    if (isDuplicateAndSkip(getMessageLog(), messageId, businessCorrelationId)) {
        numRejected.increase();
        return result;
    }
    if (getCachedProcessResult(messageId) != null) {
        numRetried.increase();
    }
    int txOption = this.getTransactionAttributeNum();
    TransactionDefinition txDef = SpringTxManagerProxy.getTransactionDefinition(txOption, getTransactionTimeout());
    // TransactionStatus txStatus = txManager.getTransaction(txDef);
    IbisTransaction itx = new IbisTransaction(txManager, txDef, "receiver [" + getName() + "]");
    TransactionStatus txStatus = itx.getStatus();
    // update processing statistics
    // count in processing statistics includes messages that are rolled back to input
    startProcessingMessage(waitingDuration);
    IPipeLineSession pipelineSession = null;
    String errorMessage = "";
    boolean messageInError = false;
    try {
        String pipelineMessage;
        if (origin instanceof IBulkDataListener) {
            try {
                IBulkDataListener bdl = (IBulkDataListener) origin;
                pipelineMessage = bdl.retrieveBulkData(rawMessage, message, threadContext);
            } catch (Throwable t) {
                errorMessage = t.getMessage();
                messageInError = true;
                ListenerException l = wrapExceptionAsListenerException(t);
                throw l;
            }
        } else {
            pipelineMessage = message;
        }
        numReceived.increase();
        // Note: errorMessage is used to pass value from catch-clause to finally-clause!
        pipelineSession = createProcessingContext(businessCorrelationId, threadContext, messageId);
        // threadContext=pipelineSession; // this is to enable Listeners to use session variables, for instance in afterProcessMessage()
        try {
            if (getMessageLog() != null) {
                getMessageLog().storeMessage(messageId, businessCorrelationId, new Date(), RCV_MESSAGE_LOG_COMMENTS, label, pipelineMessage);
            }
            log.debug(getLogPrefix() + "preparing TimeoutGuard");
            TimeoutGuard tg = new TimeoutGuard("Receiver " + getName());
            try {
                if (log.isDebugEnabled())
                    log.debug(getLogPrefix() + "activating TimeoutGuard with transactionTimeout [" + transactionTimeout + "]s");
                tg.activateGuard(getTransactionTimeout());
                pipeLineResult = adapter.processMessageWithExceptions(businessCorrelationId, pipelineMessage, pipelineSession);
                pipelineSession.put("exitcode", "" + pipeLineResult.getExitCode());
                result = pipeLineResult.getResult();
                errorMessage = "exitState [" + pipeLineResult.getState() + "], result [" + result + "]";
                if (pipelineSession.containsKey("exitcode")) {
                    int status = Integer.parseInt("" + pipelineSession.get("exitcode"));
                    if (status > 0)
                        errorMessage += ", exitcode [" + status + "]";
                }
                if (log.isDebugEnabled()) {
                    log.debug(getLogPrefix() + "received result: " + errorMessage);
                }
                messageInError = txStatus.isRollbackOnly();
            } finally {
                log.debug(getLogPrefix() + "canceling TimeoutGuard, isInterrupted [" + Thread.currentThread().isInterrupted() + "]");
                if (tg.cancel()) {
                    errorMessage = "timeout exceeded";
                    if (StringUtils.isEmpty(result)) {
                        result = "<timeout/>";
                    }
                    messageInError = true;
                }
            }
            if (!messageInError && !isTransacted()) {
                String commitOnState = ((Adapter) adapter).getPipeLine().getCommitOnState();
                if (StringUtils.isNotEmpty(commitOnState) && !commitOnState.equalsIgnoreCase(pipeLineResult.getState())) {
                    messageInError = true;
                }
            }
        } catch (Throwable t) {
            if (TransactionSynchronizationManager.isActualTransactionActive()) {
                log.debug("<*>" + getLogPrefix() + "TX Update: Received failure, transaction " + (txStatus.isRollbackOnly() ? "already" : "not yet") + " marked for rollback-only");
            }
            errorMessage = t.getMessage();
            messageInError = true;
            if (pipeLineResult == null) {
                pipeLineResult = new PipeLineResult();
            }
            if (StringUtils.isEmpty(pipeLineResult.getResult())) {
                String formattedErrorMessage = adapter.formatErrorMessage("exception caught", t, message, messageId, this, startProcessingTimestamp);
                pipeLineResult.setResult(formattedErrorMessage);
            }
            ListenerException l = wrapExceptionAsListenerException(t);
            throw l;
        } finally {
            putSessionKeysIntoThreadContext(threadContext, pipelineSession);
        }
        // }
        if (getSender() != null) {
            String sendMsg = sendResultToSender(technicalCorrelationId, result);
            if (sendMsg != null) {
                errorMessage = sendMsg;
            }
        }
    } finally {
        cacheProcessResult(messageId, businessCorrelationId, errorMessage, new Date(startProcessingTimestamp));
        if (!isTransacted() && messageInError) {
            if (!manualRetry) {
                moveInProcessToError(messageId, businessCorrelationId, message, new Date(startProcessingTimestamp), errorMessage, rawMessage, TXNEW_CTRL);
            }
        }
        try {
            Map afterMessageProcessedMap;
            if (threadContext != null) {
                afterMessageProcessedMap = threadContext;
                if (pipelineSession != null) {
                    threadContext.putAll(pipelineSession);
                }
            } else {
                afterMessageProcessedMap = pipelineSession;
            }
            origin.afterMessageProcessed(pipeLineResult, rawMessage, afterMessageProcessedMap);
        } finally {
            long finishProcessingTimestamp = System.currentTimeMillis();
            finishProcessingMessage(finishProcessingTimestamp - startProcessingTimestamp);
            if (!txStatus.isCompleted()) {
                // NB: Spring will take care of executing a commit or a rollback;
                // Spring will also ONLY commit the transaction if it was newly created
                // by the above call to txManager.getTransaction().
                // txManager.commit(txStatus);
                itx.commit();
            } else {
                throw new ListenerException(getLogPrefix() + "Transaction already completed; we didn't expect this");
            }
        }
    }
    if (log.isDebugEnabled())
        log.debug(getLogPrefix() + "messageId [" + messageId + "] correlationId [" + businessCorrelationId + "] returning result [" + result + "]");
    return result;
}
Also used : DefaultTransactionDefinition(org.springframework.transaction.support.DefaultTransactionDefinition) TransactionDefinition(org.springframework.transaction.TransactionDefinition) InputStream(java.io.InputStream) TransactionStatus(org.springframework.transaction.TransactionStatus) TimeoutGuard(nl.nn.adapterframework.task.TimeoutGuard) SenderException(nl.nn.adapterframework.core.SenderException) ListenerException(nl.nn.adapterframework.core.ListenerException) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) Date(java.util.Date) ListenerException(nl.nn.adapterframework.core.ListenerException) IBulkDataListener(nl.nn.adapterframework.core.IBulkDataListener) CompactSaxHandler(nl.nn.adapterframework.util.CompactSaxHandler) IbisTransaction(nl.nn.adapterframework.core.IbisTransaction) PipeLineResult(nl.nn.adapterframework.core.PipeLineResult) SAXParser(javax.xml.parsers.SAXParser) IPipeLineSession(nl.nn.adapterframework.core.IPipeLineSession) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) SAXParserFactory(javax.xml.parsers.SAXParserFactory)

Aggregations

Date (java.util.Date)3 IBulkDataListener (nl.nn.adapterframework.core.IBulkDataListener)3 HashMap (java.util.HashMap)2 ConfigurationException (nl.nn.adapterframework.configuration.ConfigurationException)2 IbisTransaction (nl.nn.adapterframework.core.IbisTransaction)2 ListenerException (nl.nn.adapterframework.core.ListenerException)2 PipeLineResult (nl.nn.adapterframework.core.PipeLineResult)2 SenderException (nl.nn.adapterframework.core.SenderException)2 TimeoutGuard (nl.nn.adapterframework.task.TimeoutGuard)2 CompactSaxHandler (nl.nn.adapterframework.util.CompactSaxHandler)2 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 InputStream (java.io.InputStream)1 LinkedHashMap (java.util.LinkedHashMap)1 Map (java.util.Map)1 ZipEntry (java.util.zip.ZipEntry)1 SAXParser (javax.xml.parsers.SAXParser)1 SAXParserFactory (javax.xml.parsers.SAXParserFactory)1 IHasProcessState (nl.nn.adapterframework.core.IHasProcessState)1 IListener (nl.nn.adapterframework.core.IListener)1