Search in sources :

Example 11 with PipeRunResult

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

the class CorePipeLineProcessor method processPipeLine.

public PipeLineResult processPipeLine(PipeLine pipeLine, String messageId, String message, IPipeLineSession pipeLineSession, String firstPipe) throws PipeRunException {
    // Object is the object that is passed to and returned from Pipes
    Object object = (Object) message;
    PipeRunResult pipeRunResult;
    // the PipeLineResult
    PipeLineResult pipeLineResult = new PipeLineResult();
    if (object == null || (object instanceof String && StringUtils.isEmpty(object.toString()))) {
        if (StringUtils.isNotEmpty(pipeLine.getAdapterToRunBeforeOnEmptyInput())) {
            log.debug("running adapterBeforeOnEmptyInput");
            IAdapter adapter = pipeLine.getAdapter().getConfiguration().getIbisManager().getRegisteredAdapter(pipeLine.getAdapterToRunBeforeOnEmptyInput());
            if (adapter == null) {
                log.warn("adapterToRunBefore with specified name [" + pipeLine.getAdapterToRunBeforeOnEmptyInput() + "] could not be retrieved");
            } else {
                PipeLineResult plr = adapter.processMessage(messageId, message, pipeLineSession);
                if (plr == null || !plr.getState().equals("success")) {
                    throw new PipeRunException(null, "adapterToRunBefore [" + pipeLine.getAdapterToRunBeforeOnEmptyInput() + "] ended with state [" + plr.getState() + "]");
                }
                message = plr.getResult();
                log.debug("input after running adapterBeforeOnEmptyInput [" + message + "]");
                object = (Object) message;
            }
        }
    }
    // ready indicates wether the pipeline processing is complete
    boolean ready = false;
    // get the first pipe to run
    IPipe pipeToRun = pipeLine.getPipe(pipeLine.getFirstPipe());
    boolean inputValidateError = false;
    IPipe inputValidator = pipeLine.getInputValidator();
    if (inputValidator != null) {
        log.debug("validating input");
        PipeRunResult validationResult = pipeProcessor.processPipe(pipeLine, inputValidator, messageId, message, pipeLineSession);
        if (validationResult != null) {
            if (!validationResult.getPipeForward().getName().equals("success")) {
                PipeForward validationForward = validationResult.getPipeForward();
                if (validationForward.getPath() == null) {
                    throw new PipeRunException(pipeToRun, "forward [" + validationForward.getName() + "] of inputValidator has emtpy forward path");
                }
                log.warn("setting first pipe to [" + validationForward.getPath() + "] due to validation fault");
                inputValidateError = true;
                pipeToRun = pipeLine.getPipe(validationForward.getPath());
                if (pipeToRun == null) {
                    throw new PipeRunException(pipeToRun, "forward [" + validationForward.getName() + "], path [" + validationForward.getPath() + "] does not correspond to a pipe");
                }
            }
            Object validatedMessage = validationResult.getResult();
            if (validatedMessage != null) {
                object = validatedMessage;
                message = validatedMessage.toString();
            }
        }
    }
    if (!inputValidateError) {
        IPipe inputWrapper = pipeLine.getInputWrapper();
        if (inputWrapper != null) {
            log.debug("wrapping input");
            PipeRunResult wrapResult = pipeProcessor.processPipe(pipeLine, inputWrapper, messageId, message, pipeLineSession);
            if (wrapResult != null && !wrapResult.getPipeForward().getName().equals("success")) {
                PipeForward wrapForward = wrapResult.getPipeForward();
                if (wrapForward.getPath() == null) {
                    throw new PipeRunException(pipeToRun, "forward [" + wrapForward.getName() + "] of inputWrapper has emtpy forward path");
                }
                log.warn("setting first pipe to [" + wrapForward.getPath() + "] due to wrap fault");
                pipeToRun = pipeLine.getPipe(wrapForward.getPath());
                if (pipeToRun == null) {
                    throw new PipeRunException(pipeToRun, "forward [" + wrapForward.getName() + "], path [" + wrapForward.getPath() + "] does not correspond to a pipe");
                }
            } else {
                message = wrapResult.getResult().toString();
            }
            log.debug("input after wrapping [" + message + "]");
            object = (Object) message;
        }
    }
    pipeLine.getRequestSizeStats().addValue(message.length());
    if (pipeLine.isStoreOriginalMessageWithoutNamespaces()) {
        if (XmlUtils.isWellFormed(message)) {
            String removeNamespaces_xslt = XmlUtils.makeRemoveNamespacesXslt(true, true);
            try {
                String xsltResult = null;
                Transformer transformer = XmlUtils.createTransformer(removeNamespaces_xslt);
                xsltResult = XmlUtils.transformXml(transformer, message);
                pipeLineSession.put("originalMessageWithoutNamespaces", xsltResult);
            } catch (IOException e) {
                throw new PipeRunException(pipeToRun, "cannot retrieve removeNamespaces", e);
            } catch (TransformerConfigurationException te) {
                throw new PipeRunException(pipeToRun, "got error creating transformer from removeNamespaces", te);
            } catch (TransformerException te) {
                throw new PipeRunException(pipeToRun, "got error transforming removeNamespaces", te);
            } catch (DomBuilderException te) {
                throw new PipeRunException(pipeToRun, "caught DomBuilderException", te);
            }
        } else {
            log.warn("original message is not well-formed");
            pipeLineSession.put("originalMessageWithoutNamespaces", message);
        }
    }
    boolean outputValidated = false;
    try {
        while (!ready) {
            pipeRunResult = pipeProcessor.processPipe(pipeLine, pipeToRun, messageId, object, pipeLineSession);
            object = pipeRunResult.getResult();
            if (!(pipeToRun instanceof AbstractPipe)) {
                if (object != null && object instanceof String) {
                    StatisticsKeeper sizeStat = pipeLine.getPipeSizeStatistics(pipeToRun);
                    if (sizeStat != null) {
                        sizeStat.addValue(((String) object).length());
                    }
                }
            }
            PipeForward pipeForward = pipeRunResult.getPipeForward();
            if (pipeForward == null) {
                throw new PipeRunException(pipeToRun, "Pipeline of [" + pipeLine.getOwner().getName() + "] received result from pipe [" + pipeToRun.getName() + "] without a pipeForward");
            }
            // get the next pipe to run
            String nextPath = pipeForward.getPath();
            if ((null == nextPath) || (nextPath.length() == 0)) {
                throw new PipeRunException(pipeToRun, "Pipeline of [" + pipeLine.getOwner().getName() + "] got an path that equals null or has a zero-length value from pipe [" + pipeToRun.getName() + "]. Check the configuration, probably forwards are not defined for this pipe.");
            }
            PipeLineExit plExit = pipeLine.getPipeLineExits().get(nextPath);
            if (null != plExit) {
                boolean outputWrapError = false;
                IPipe outputWrapper = pipeLine.getOutputWrapper();
                if (outputWrapper != null) {
                    log.debug("wrapping PipeLineResult");
                    PipeRunResult wrapResult = pipeProcessor.processPipe(pipeLine, outputWrapper, messageId, object, pipeLineSession);
                    if (wrapResult != null && !wrapResult.getPipeForward().getName().equals("success")) {
                        PipeForward wrapForward = wrapResult.getPipeForward();
                        if (wrapForward.getPath() == null) {
                            throw new PipeRunException(pipeToRun, "forward [" + wrapForward.getName() + "] of outputWrapper has emtpy forward path");
                        }
                        log.warn("setting next pipe to [" + wrapForward.getPath() + "] due to wrap fault");
                        outputWrapError = true;
                        pipeToRun = pipeLine.getPipe(wrapForward.getPath());
                        if (pipeToRun == null) {
                            throw new PipeRunException(pipeToRun, "forward [" + wrapForward.getName() + "], path [" + wrapForward.getPath() + "] does not correspond to a pipe");
                        }
                    } else {
                        log.debug("wrap succeeded");
                        object = wrapResult.getResult();
                    }
                    log.debug("PipeLineResult after wrapping [" + object.toString() + "]");
                }
                if (!outputWrapError) {
                    IPipe outputValidator = pipeLine.getOutputValidator();
                    if ((outputValidator != null) && !outputValidated) {
                        outputValidated = true;
                        log.debug("validating PipeLineResult");
                        PipeRunResult validationResult;
                        validationResult = pipeProcessor.processPipe(pipeLine, outputValidator, messageId, object, pipeLineSession);
                        if (validationResult != null && !validationResult.getPipeForward().getName().equals("success")) {
                            PipeForward validationForward = validationResult.getPipeForward();
                            if (validationForward.getPath() == null) {
                                throw new PipeRunException(pipeToRun, "forward [" + validationForward.getName() + "] of outputValidator has emtpy forward path");
                            }
                            log.warn("setting next pipe to [" + validationForward.getPath() + "] due to validation fault");
                            pipeToRun = pipeLine.getPipe(validationForward.getPath());
                            if (pipeToRun == null) {
                                throw new PipeRunException(pipeToRun, "forward [" + validationForward.getName() + "], path [" + validationForward.getPath() + "] does not correspond to a pipe");
                            }
                        } else {
                            log.debug("validation succeeded");
                            object = validationResult.getResult();
                            ready = true;
                        }
                    } else {
                        ready = true;
                    }
                } else {
                    ready = true;
                }
                if (ready) {
                    String state = plExit.getState();
                    pipeLineResult.setState(state);
                    pipeLineResult.setExitCode(plExit.getExitCode());
                    if (object != null && !plExit.getEmptyResult()) {
                        pipeLineResult.setResult(object.toString());
                    } else {
                        pipeLineResult.setResult(null);
                    }
                    ready = true;
                    if (log.isDebugEnabled()) {
                        // for performance reasons
                        String skString = "";
                        for (Iterator it = pipeLineSession.keySet().iterator(); it.hasNext(); ) {
                            String key = (String) it.next();
                            Object value = pipeLineSession.get(key);
                            skString = skString + "\n " + key + "=[" + value + "]";
                        }
                        log.debug("Available session keys at finishing pipeline of adapter [" + pipeLine.getOwner().getName() + "]:" + skString);
                        log.debug("Pipeline of adapter [" + pipeLine.getOwner().getName() + "] finished processing messageId [" + messageId + "] result: [" + object + "] with exit-state [" + state + "]");
                    }
                }
            } else {
                pipeToRun = pipeLine.getPipe(pipeForward.getPath());
                if (pipeToRun == null) {
                    throw new PipeRunException(null, "Pipeline of adapter [" + pipeLine.getOwner().getName() + "] got an erroneous definition. Pipe to execute [" + pipeForward.getPath() + "] is not defined.");
                }
            }
        }
    } finally {
        for (int i = 0; i < pipeLine.getExitHandlers().size(); i++) {
            IPipeLineExitHandler exitHandler = pipeLine.getExitHandlers().get(i);
            try {
                if (log.isDebugEnabled())
                    log.debug("processing ExitHandler [" + exitHandler.getName() + "]");
                exitHandler.atEndOfPipeLine(messageId, pipeLineResult, pipeLineSession);
            } catch (Throwable t) {
                log.warn("Caught Exception processing ExitHandler [" + exitHandler.getName() + "]", t);
            }
        }
    }
    return pipeLineResult;
}
Also used : Transformer(javax.xml.transform.Transformer) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) IPipeLineExitHandler(nl.nn.adapterframework.core.IPipeLineExitHandler) IOException(java.io.IOException) PipeForward(nl.nn.adapterframework.core.PipeForward) PipeRunResult(nl.nn.adapterframework.core.PipeRunResult) AbstractPipe(nl.nn.adapterframework.pipes.AbstractPipe) PipeLineResult(nl.nn.adapterframework.core.PipeLineResult) PipeRunException(nl.nn.adapterframework.core.PipeRunException) Iterator(java.util.Iterator) StatisticsKeeper(nl.nn.adapterframework.statistics.StatisticsKeeper) DomBuilderException(nl.nn.adapterframework.util.DomBuilderException) IAdapter(nl.nn.adapterframework.core.IAdapter) IPipe(nl.nn.adapterframework.core.IPipe) TransformerException(javax.xml.transform.TransformerException) PipeLineExit(nl.nn.adapterframework.core.PipeLineExit)

Example 12 with PipeRunResult

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

the class MessageSendingPipe method doPipe.

public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException {
    String originalMessage = input.toString();
    String result = null;
    String correlationID = session.getMessageId();
    if (getInputWrapper() != null) {
        log.debug(getLogPrefix(session) + "wrapping input");
        PipeRunResult wrapResult = pipeProcessor.processPipe(getPipeLine(), inputWrapper, correlationID, input, session);
        if (wrapResult != null && !wrapResult.getPipeForward().getName().equals(SUCCESS_FORWARD)) {
            return wrapResult;
        } else {
            input = wrapResult.getResult();
        }
        log.debug(getLogPrefix(session) + "input after wrapping [" + input.toString() + "]");
    }
    if (getInputValidator() != null) {
        log.debug(getLogPrefix(session) + "validating input");
        PipeRunResult validationResult = pipeProcessor.processPipe(getPipeLine(), inputValidator, correlationID, input, session);
        if (validationResult != null && !validationResult.getPipeForward().getName().equals(SUCCESS_FORWARD)) {
            return validationResult;
        }
    }
    if (StringUtils.isNotEmpty(getStubFileName())) {
        ParameterList pl = getParameterList();
        result = returnString;
        if (pl != null) {
            ParameterResolutionContext prc = new ParameterResolutionContext((String) input, session);
            Map params;
            try {
                params = prc.getValueMap(pl);
            } catch (ParameterException e1) {
                throw new PipeRunException(this, getLogPrefix(session) + "got exception evaluating parameters", e1);
            }
            String sfn = null;
            if (params != null && params.size() > 0) {
                sfn = (String) params.get(STUBFILENAME);
            }
            if (sfn != null) {
                try {
                    result = Misc.resourceToString(ClassUtils.getResourceURL(classLoader, sfn), SystemUtils.LINE_SEPARATOR);
                    log.info(getLogPrefix(session) + "returning result from dynamic stub [" + sfn + "]");
                } catch (Throwable e) {
                    throw new PipeRunException(this, getLogPrefix(session) + "got exception loading result from stub [" + sfn + "]", e);
                }
            } else {
                log.info(getLogPrefix(session) + "returning result from static stub [" + getStubFileName() + "]");
            }
        } else {
            log.info(getLogPrefix(session) + "returning result from static stub [" + getStubFileName() + "]");
        }
    } else {
        Map threadContext = new HashMap();
        try {
            String messageID = null;
            // sendResult has a messageID for async senders, the result for sync senders
            int retryInterval = getRetryMinInterval();
            String sendResult = null;
            boolean replyIsValid = false;
            int retriesLeft = 0;
            if (getMaxRetries() > 0) {
                retriesLeft = getMaxRetries() + 1;
            } else {
                retriesLeft = 1;
            }
            while (retriesLeft-- >= 1 && !replyIsValid) {
                try {
                    sendResult = sendMessage(input, session, correlationID, getSender(), threadContext);
                    if (retryTp != null) {
                        String retry = retryTp.transform(sendResult, null);
                        if (retry.equalsIgnoreCase("true")) {
                            if (retriesLeft >= 1) {
                                retryInterval = increaseRetryIntervalAndWait(session, retryInterval, "xpathRetry result [" + retry + "], retries left [" + retriesLeft + "]");
                            }
                        } else {
                            replyIsValid = true;
                        }
                    } else {
                        replyIsValid = true;
                    }
                } catch (TimeOutException toe) {
                    if (retriesLeft >= 1) {
                        retryInterval = increaseRetryIntervalAndWait(session, retryInterval, "timeout occured, retries left [" + retriesLeft + "]");
                    } else {
                        throw toe;
                    }
                } catch (SenderException se) {
                    if (retriesLeft >= 1) {
                        retryInterval = increaseRetryIntervalAndWait(session, retryInterval, "exception [" + (se != null ? se.getMessage() : "") + "] occured, retries left [" + retriesLeft + "]");
                    } else {
                        throw se;
                    }
                }
            }
            if (!replyIsValid) {
                throw new PipeRunException(this, getLogPrefix(session) + "invalid reply message is received");
            }
            if (getSender().isSynchronous()) {
                if (log.isInfoEnabled()) {
                    log.info(getLogPrefix(session) + "sent message to [" + getSender().getName() + "] synchronously");
                }
                result = sendResult;
            } else {
                messageID = sendResult;
                if (log.isInfoEnabled()) {
                    log.info(getLogPrefix(session) + "sent message to [" + getSender().getName() + "] messageID [" + messageID + "] correlationID [" + correlationID + "] linkMethod [" + getLinkMethod() + "]");
                }
                // as this will be used with the listener
                if (getLinkMethod().equalsIgnoreCase("MESSAGEID")) {
                    correlationID = sendResult;
                    if (log.isDebugEnabled())
                        log.debug(getLogPrefix(session) + "setting correlationId to listen for to messageId [" + correlationID + "]");
                }
            }
            ITransactionalStorage messageLog = getMessageLog();
            if (messageLog != null) {
                long messageLogStartTime = System.currentTimeMillis();
                String messageTrail = "no audit trail";
                if (auditTrailTp != null) {
                    if (isUseInputForExtract()) {
                        messageTrail = auditTrailTp.transform(originalMessage, null);
                    } else {
                        messageTrail = auditTrailTp.transform((String) input, null);
                    }
                } else {
                    if (StringUtils.isNotEmpty(getAuditTrailSessionKey())) {
                        messageTrail = (String) (session.get(getAuditTrailSessionKey()));
                    }
                }
                String storedMessageID = messageID;
                if (storedMessageID == null) {
                    storedMessageID = "-";
                }
                if (correlationIDTp != null) {
                    if (StringUtils.isNotEmpty(getCorrelationIDSessionKey())) {
                        String sourceString = (String) (session.get(getCorrelationIDSessionKey()));
                        correlationID = correlationIDTp.transform(sourceString, null);
                    } else {
                        if (isUseInputForExtract()) {
                            correlationID = correlationIDTp.transform(originalMessage, null);
                        } else {
                            correlationID = correlationIDTp.transform((String) input, null);
                        }
                    }
                    if (StringUtils.isEmpty(correlationID)) {
                        correlationID = "-";
                    }
                }
                String label = null;
                if (labelTp != null) {
                    if (isUseInputForExtract()) {
                        label = labelTp.transform(originalMessage, null);
                    } else {
                        label = labelTp.transform((String) input, null);
                    }
                }
                if (sender instanceof MailSender) {
                    String messageInMailSafeForm = (String) session.get("messageInMailSafeForm");
                    if (hideRegex != null) {
                        if (getHideMethod().equalsIgnoreCase("FIRSTHALF")) {
                            messageInMailSafeForm = Misc.hideFirstHalf(messageInMailSafeForm, hideRegex);
                        } else {
                            messageInMailSafeForm = Misc.hideAll(messageInMailSafeForm, hideRegex);
                        }
                    }
                    messageLog.storeMessage(storedMessageID, correlationID, new Date(), messageTrail, label, messageInMailSafeForm);
                } else {
                    String message = (String) input;
                    if (hideRegex != null) {
                        if (getHideMethod().equalsIgnoreCase("FIRSTHALF")) {
                            message = Misc.hideFirstHalf(message, hideRegex);
                        } else {
                            message = Misc.hideAll(message, hideRegex);
                        }
                    }
                    messageLog.storeMessage(storedMessageID, correlationID, new Date(), messageTrail, label, message);
                }
                long messageLogEndTime = System.currentTimeMillis();
                long messageLogDuration = messageLogEndTime - messageLogStartTime;
                StatisticsKeeper sk = getPipeLine().getPipeStatistics(messageLog);
                sk.addValue(messageLogDuration);
            }
            if (sender instanceof MailSender) {
                session.remove("messageInMailSafeForm");
            }
            if (getListener() != null) {
                result = listenerProcessor.getMessage(getListener(), correlationID, session);
            } else {
                result = sendResult;
            }
            if (result == null) {
                result = "";
            }
            if (timeoutPending) {
                timeoutPending = false;
                throwEvent(PIPE_CLEAR_TIMEOUT_MONITOR_EVENT);
            }
        } catch (TimeOutException toe) {
            throwEvent(PIPE_TIMEOUT_MONITOR_EVENT);
            if (!timeoutPending) {
                timeoutPending = true;
            }
            PipeForward timeoutForward = findForward(TIMEOUT_FORWARD);
            log.warn(getLogPrefix(session) + "timeout occured");
            if (timeoutForward == null) {
                if (StringUtils.isEmpty(getResultOnTimeOut())) {
                    timeoutForward = findForward(EXCEPTION_FORWARD);
                } else {
                    timeoutForward = getForward();
                }
            }
            if (timeoutForward != null) {
                String resultmsg;
                if (StringUtils.isNotEmpty(getResultOnTimeOut())) {
                    resultmsg = getResultOnTimeOut();
                } else {
                    if (input instanceof String) {
                        resultmsg = new ErrorMessageFormatter().format(getLogPrefix(session), toe, this, (String) input, session.getMessageId(), 0);
                    } else {
                        if (input == null) {
                            input = "null";
                        }
                        resultmsg = new ErrorMessageFormatter().format(getLogPrefix(session), toe, this, input.toString(), session.getMessageId(), 0);
                    }
                }
                return new PipeRunResult(timeoutForward, resultmsg);
            }
            throw new PipeRunException(this, getLogPrefix(session) + "caught timeout-exception", toe);
        } catch (Throwable t) {
            throwEvent(PIPE_EXCEPTION_MONITOR_EVENT);
            PipeForward exceptionForward = findForward(EXCEPTION_FORWARD);
            if (exceptionForward != null) {
                log.warn(getLogPrefix(session) + "exception occured, forwarding to exception-forward [" + exceptionForward.getPath() + "], exception:\n", t);
                String resultmsg;
                if (input instanceof String) {
                    resultmsg = new ErrorMessageFormatter().format(getLogPrefix(session), t, this, (String) input, session.getMessageId(), 0);
                } else {
                    if (input == null) {
                        input = "null";
                    }
                    resultmsg = new ErrorMessageFormatter().format(getLogPrefix(session), t, this, input.toString(), session.getMessageId(), 0);
                }
                return new PipeRunResult(exceptionForward, resultmsg);
            }
            throw new PipeRunException(this, getLogPrefix(session) + "caught exception", t);
        }
    }
    if (!validResult(result)) {
        PipeForward illegalResultForward = findForward(ILLEGAL_RESULT_FORWARD);
        return new PipeRunResult(illegalResultForward, result);
    }
    IPipe outputValidator = getOutputValidator();
    if (outputValidator != null) {
        log.debug(getLogPrefix(session) + "validating response");
        PipeRunResult validationResult;
        validationResult = pipeProcessor.processPipe(getPipeLine(), outputValidator, correlationID, result, session);
        if (validationResult != null && !validationResult.getPipeForward().getName().equals(SUCCESS_FORWARD)) {
            return validationResult;
        }
    }
    if (getOutputWrapper() != null) {
        log.debug(getLogPrefix(session) + "wrapping response");
        PipeRunResult wrapResult = pipeProcessor.processPipe(getPipeLine(), outputWrapper, correlationID, result, session);
        if (wrapResult != null && !wrapResult.getPipeForward().getName().equals(SUCCESS_FORWARD)) {
            return wrapResult;
        }
        result = wrapResult.getResult().toString();
        log.debug(getLogPrefix(session) + "response after wrapping [" + result + "]");
    }
    if (isStreamResultToServlet()) {
        byte[] bytes = Base64.decodeBase64(new String(result));
        try {
            String contentType = (String) session.get("contentType");
            if (StringUtils.isNotEmpty(contentType)) {
                RestListenerUtils.setResponseContentType(session, contentType);
            }
            RestListenerUtils.writeToResponseOutputStream(session, bytes);
        } catch (IOException e) {
            throw new PipeRunException(this, getLogPrefix(session) + "caught exception", e);
        }
        return new PipeRunResult(getForward(), "");
    } else {
        return new PipeRunResult(getForward(), result);
    }
}
Also used : HashMap(java.util.HashMap) MailSender(nl.nn.adapterframework.senders.MailSender) IOException(java.io.IOException) PipeForward(nl.nn.adapterframework.core.PipeForward) Date(java.util.Date) ITransactionalStorage(nl.nn.adapterframework.core.ITransactionalStorage) PipeRunResult(nl.nn.adapterframework.core.PipeRunResult) TimeOutException(nl.nn.adapterframework.core.TimeOutException) ErrorMessageFormatter(nl.nn.adapterframework.errormessageformatters.ErrorMessageFormatter) PipeRunException(nl.nn.adapterframework.core.PipeRunException) ParameterList(nl.nn.adapterframework.parameters.ParameterList) StatisticsKeeper(nl.nn.adapterframework.statistics.StatisticsKeeper) ParameterException(nl.nn.adapterframework.core.ParameterException) SenderException(nl.nn.adapterframework.core.SenderException) ParameterResolutionContext(nl.nn.adapterframework.parameters.ParameterResolutionContext) Map(java.util.Map) HashMap(java.util.HashMap) IPipe(nl.nn.adapterframework.core.IPipe)

Example 13 with PipeRunResult

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

the class MoveFilePipe method doPipe.

/**
 * @see nl.nn.adapterframework.core.IPipe#doPipe(Object, IPipeLineSession)
 */
public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException {
    File srcFile = null;
    File dstFile = null;
    if (StringUtils.isEmpty(getWildcard()) && StringUtils.isEmpty(getWildcardSessionKey())) {
        if (StringUtils.isEmpty(getDirectory())) {
            if (StringUtils.isEmpty(getFilename())) {
                srcFile = new File(input.toString());
            } else {
                srcFile = new File(getFilename());
            }
        } else {
            if (StringUtils.isEmpty(getFilename())) {
                srcFile = new File(getDirectory(), input.toString());
            } else {
                srcFile = new File(getDirectory(), getFilename());
            }
        }
        if (StringUtils.isEmpty(getMove2file())) {
            if (StringUtils.isEmpty(getMove2fileSessionKey())) {
                dstFile = new File(getMove2dir(), retrieveDestinationChild(srcFile.getName()));
            } else {
                dstFile = new File(getMove2dir(), retrieveDestinationChild((String) session.get(getMove2fileSessionKey())));
            }
        } else {
            dstFile = new File(getMove2dir(), retrieveDestinationChild(getMove2file()));
        }
        moveFile(session, srcFile, dstFile);
    } else {
        if (StringUtils.isEmpty(getDirectory())) {
            if (StringUtils.isEmpty(getFilename())) {
                srcFile = new File(input.toString());
            } else {
                srcFile = new File(getFilename());
            }
        } else {
            srcFile = new File(getDirectory());
        }
        String wc;
        if (StringUtils.isEmpty(getWildcardSessionKey())) {
            wc = getWildcard();
        } else {
            wc = (String) session.get(getWildcardSessionKey());
        }
        // WildCardFilter filter = new WildCardFilter(wc);
        // File[] srcFiles = srcFile.listFiles(filter);
        File[] srcFiles = FileUtils.getFiles(srcFile.getPath(), wc, null, -1);
        int count = (srcFiles == null ? 0 : srcFiles.length);
        if (count == 0) {
            log.info(getLogPrefix(session) + "no files with wildcard [" + wc + "] found in directory [" + srcFile.getAbsolutePath() + "]");
        }
        for (int i = 0; i < count; i++) {
            dstFile = new File(getMove2dir(), retrieveDestinationChild(srcFiles[i].getName()));
            moveFile(session, srcFiles[i], dstFile);
        }
    }
    /* if parent source directory is empty, delete the directory */
    if (isDeleteEmptyDirectory()) {
        File srcDirectory;
        if (StringUtils.isEmpty(getWildcard()) && StringUtils.isEmpty(getWildcardSessionKey())) {
            srcDirectory = srcFile.getParentFile();
        } else {
            srcDirectory = srcFile.getAbsoluteFile();
        }
        log.debug("srcFile [" + srcFile.getPath() + "] srcDirectory [" + srcDirectory.getPath() + "]");
        if (srcDirectory.exists()) {
            if (srcDirectory.list().length == 0) {
                boolean success = srcDirectory.delete();
                if (!success) {
                    log.warn(getLogPrefix(session) + "could not delete directory [" + srcDirectory.getAbsolutePath() + "]");
                } else {
                    log.info(getLogPrefix(session) + "deleted directory [" + srcDirectory.getAbsolutePath() + "]");
                }
            } else {
                log.info(getLogPrefix(session) + "directory [" + srcDirectory.getAbsolutePath() + "] is not empty");
            }
        } else {
            log.info(getLogPrefix(session) + "directory [" + srcDirectory.getAbsolutePath() + "] doesn't exist");
        }
    }
    return new PipeRunResult(getForward(), (dstFile == null ? srcFile.getAbsolutePath() : dstFile.getAbsolutePath()));
}
Also used : PipeRunResult(nl.nn.adapterframework.core.PipeRunResult) File(java.io.File)

Example 14 with PipeRunResult

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

the class PostboxRetrieverPipe method doPipe.

public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException {
    if (!(input instanceof String)) {
        throw new PipeRunException(this, "String expected, got a [" + input.getClass().getName() + "]");
    }
    Map threadContext = null;
    try {
        threadContext = getListener().openThread();
        Object rawMessage = getListener().retrieveRawMessage((String) input, threadContext);
        if (rawMessage == null)
            return new PipeRunResult(findForward("emptyPostbox"), getResultOnEmptyPostbox());
        String result = getListener().getStringFromRawMessage(rawMessage, threadContext);
        return new PipeRunResult(getForward(), result);
    } catch (Exception e) {
        throw new PipeRunException(this, getLogPrefix(session) + "caught exception", e);
    } finally {
        try {
            getListener().closeThread(threadContext);
        } catch (ListenerException le) {
            log.error(getLogPrefix(session) + "got error closing listener");
        }
    }
}
Also used : PipeRunResult(nl.nn.adapterframework.core.PipeRunResult) ListenerException(nl.nn.adapterframework.core.ListenerException) PipeRunException(nl.nn.adapterframework.core.PipeRunException) Map(java.util.Map) PipeRunException(nl.nn.adapterframework.core.PipeRunException) PipeStartException(nl.nn.adapterframework.core.PipeStartException) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) ListenerException(nl.nn.adapterframework.core.ListenerException)

Example 15 with PipeRunResult

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

the class CompareStringPipe method doPipe.

@Override
public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException {
    ParameterValueList pvl = null;
    if (getParameterList() != null) {
        ParameterResolutionContext prc = new ParameterResolutionContext((String) input, session);
        try {
            pvl = prc.getValues(getParameterList());
        } catch (ParameterException e) {
            throw new PipeRunException(this, getLogPrefix(session) + "exception extracting parameters", e);
        }
    }
    String operand1 = getParameterValue(pvl, OPERAND1);
    if (operand1 == null) {
        if (StringUtils.isNotEmpty(getSessionKey1())) {
            operand1 = (String) session.get(getSessionKey1());
        }
        if (operand1 == null) {
            operand1 = (String) input;
        }
    }
    String operand2 = getParameterValue(pvl, OPERAND2);
    if (operand2 == null) {
        if (StringUtils.isNotEmpty(getSessionKey2())) {
            operand2 = (String) session.get(getSessionKey2());
        }
        if (operand2 == null) {
            operand2 = (String) input;
        }
    }
    if (isXml()) {
        try {
            operand1 = XmlUtils.canonicalize(operand1);
            operand2 = XmlUtils.canonicalize(operand2);
        } catch (Exception e) {
            throw new PipeRunException(this, getLogPrefix(session) + " Exception on pretty printing input", e);
        }
    }
    String ip = getParameterValue(pvl, IGNOREPATTERNS);
    if (ip != null) {
        try {
            Node n = XmlUtils.buildNode(ip);
            if (n.getNodeName().equals("ignores")) {
                NodeList nList = n.getChildNodes();
                for (int i = 0; i <= nList.getLength() - 1; i++) {
                    Node cn = nList.item(i);
                    if (cn.getNodeName().equals("ignore")) {
                        NodeList cnList = cn.getChildNodes();
                        String after = null;
                        String before = null;
                        for (int j = 0; j <= cnList.getLength() - 1; j++) {
                            Node ccn = cnList.item(j);
                            if (ccn.getNodeName().equals("after")) {
                                after = ccn.getFirstChild().getNodeValue();
                            } else {
                                if (ccn.getNodeName().equals("before")) {
                                    before = ccn.getFirstChild().getNodeValue();
                                }
                            }
                        }
                        operand1 = ignoreBetween(operand1, after, before);
                        operand2 = ignoreBetween(operand2, after, before);
                    }
                }
            }
        } catch (Exception e) {
            throw new PipeRunException(this, getLogPrefix(session) + " Exception on ignoring parts of input", e);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("operand1 [" + operand1 + "]");
        log.debug("operand2 [" + operand2 + "]");
    }
    int comparison = operand1.compareTo(operand2);
    if (comparison == 0)
        return new PipeRunResult(findForward(EQUALSFORWARD), input);
    else if (comparison < 0)
        return new PipeRunResult(findForward(LESSTHANFORWARD), input);
    else
        return new PipeRunResult(findForward(GREATERTHANFORWARD), input);
}
Also used : PipeRunResult(nl.nn.adapterframework.core.PipeRunResult) ParameterValueList(nl.nn.adapterframework.parameters.ParameterValueList) Node(org.w3c.dom.Node) NodeList(org.w3c.dom.NodeList) PipeRunException(nl.nn.adapterframework.core.PipeRunException) ParameterException(nl.nn.adapterframework.core.ParameterException) ParameterResolutionContext(nl.nn.adapterframework.parameters.ParameterResolutionContext) PipeRunException(nl.nn.adapterframework.core.PipeRunException) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) ParameterException(nl.nn.adapterframework.core.ParameterException)

Aggregations

PipeRunResult (nl.nn.adapterframework.core.PipeRunResult)89 PipeRunException (nl.nn.adapterframework.core.PipeRunException)65 PipeForward (nl.nn.adapterframework.core.PipeForward)23 ConfigurationException (nl.nn.adapterframework.configuration.ConfigurationException)22 ParameterResolutionContext (nl.nn.adapterframework.parameters.ParameterResolutionContext)21 IOException (java.io.IOException)17 ParameterException (nl.nn.adapterframework.core.ParameterException)14 ParameterValueList (nl.nn.adapterframework.parameters.ParameterValueList)11 Test (org.junit.Test)11 File (java.io.File)10 Map (java.util.Map)10 ParameterList (nl.nn.adapterframework.parameters.ParameterList)8 InputStream (java.io.InputStream)7 DomBuilderException (nl.nn.adapterframework.util.DomBuilderException)7 Parameter (nl.nn.adapterframework.parameters.Parameter)6 FileInputStream (java.io.FileInputStream)4 StringReader (java.io.StringReader)4 Iterator (java.util.Iterator)4 StringTokenizer (java.util.StringTokenizer)4 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)4