Search in sources :

Example 1 with ErrorMessageFormatter

use of nl.nn.adapterframework.errormessageformatters.ErrorMessageFormatter 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 2 with ErrorMessageFormatter

use of nl.nn.adapterframework.errormessageformatters.ErrorMessageFormatter in project iaf by ibissource.

the class CompressPipe method doPipe.

public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException {
    try {
        Object result;
        InputStream in;
        OutputStream out;
        boolean zipMultipleFiles = false;
        if (messageIsContent) {
            if (input instanceof byte[]) {
                in = new ByteArrayInputStream((byte[]) input);
            } else {
                in = new ByteArrayInputStream(input.toString().getBytes());
            }
        } else {
            if (compress && StringUtils.contains((String) input, ";")) {
                zipMultipleFiles = true;
                in = null;
            } else {
                in = new FileInputStream((String) input);
            }
        }
        if (resultIsContent) {
            out = new ByteArrayOutputStream();
            result = out;
        } else {
            String outFilename = null;
            if (messageIsContent) {
                outFilename = FileUtils.getFilename(getParameterList(), session, (File) null, filenamePattern);
            } else {
                outFilename = FileUtils.getFilename(getParameterList(), session, new File((String) input), filenamePattern);
            }
            File outFile = new File(outputDirectory, outFilename);
            result = outFile.getAbsolutePath();
            out = new FileOutputStream(outFile);
        }
        if (zipMultipleFiles) {
            ZipOutputStream zipper = new ZipOutputStream(out);
            StringTokenizer st = new StringTokenizer((String) input, ";");
            while (st.hasMoreElements()) {
                String fn = st.nextToken();
                String zipEntryName = getZipEntryName(fn, session);
                zipper.putNextEntry(new ZipEntry(zipEntryName));
                in = new FileInputStream(fn);
                try {
                    int readLength = 0;
                    byte[] block = new byte[4096];
                    while ((readLength = in.read(block)) > 0) {
                        zipper.write(block, 0, readLength);
                    }
                } finally {
                    in.close();
                    zipper.closeEntry();
                }
            }
            zipper.close();
            out = zipper;
        } else {
            if (compress) {
                if ("gz".equals(fileFormat) || fileFormat == null && resultIsContent) {
                    out = new GZIPOutputStream(out);
                } else {
                    ZipOutputStream zipper = new ZipOutputStream(out);
                    String zipEntryName = getZipEntryName(input, session);
                    zipper.putNextEntry(new ZipEntry(zipEntryName));
                    out = zipper;
                }
            } else {
                if ("gz".equals(fileFormat) || fileFormat == null && messageIsContent) {
                    in = new GZIPInputStream(in);
                } else {
                    ZipInputStream zipper = new ZipInputStream(in);
                    String zipEntryName = getZipEntryName(input, session);
                    if (zipEntryName.equals("")) {
                        // Use first entry found
                        zipper.getNextEntry();
                    } else {
                        // Position the stream at the specified entry
                        ZipEntry zipEntry = zipper.getNextEntry();
                        while (zipEntry != null && !zipEntry.getName().equals(zipEntryName)) {
                            zipEntry = zipper.getNextEntry();
                        }
                    }
                    in = zipper;
                }
            }
            try {
                int readLength = 0;
                byte[] block = new byte[4096];
                while ((readLength = in.read(block)) > 0) {
                    out.write(block, 0, readLength);
                }
            } finally {
                out.close();
                in.close();
            }
        }
        return new PipeRunResult(getForward(), getResultMsg(result));
    } catch (Exception e) {
        PipeForward exceptionForward = findForward(EXCEPTIONFORWARD);
        if (exceptionForward != null) {
            log.warn(getLogPrefix(session) + "exception occured, forwarded to [" + exceptionForward.getPath() + "]", e);
            String originalMessage;
            if (input instanceof String) {
                originalMessage = (String) input;
            } else {
                originalMessage = "Object of type " + input.getClass().getName();
            }
            String resultmsg = new ErrorMessageFormatter().format(getLogPrefix(session), e, this, originalMessage, session.getMessageId(), 0);
            return new PipeRunResult(exceptionForward, resultmsg);
        }
        throw new PipeRunException(this, "Unexpected exception during compression", e);
    }
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) ZipInputStream(java.util.zip.ZipInputStream) FileInputStream(java.io.FileInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) ZipOutputStream(java.util.zip.ZipOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) FileOutputStream(java.io.FileOutputStream) GZIPOutputStream(java.util.zip.GZIPOutputStream) ZipEntry(java.util.zip.ZipEntry) ByteArrayOutputStream(java.io.ByteArrayOutputStream) PipeForward(nl.nn.adapterframework.core.PipeForward) FileInputStream(java.io.FileInputStream) PipeRunException(nl.nn.adapterframework.core.PipeRunException) ParameterException(nl.nn.adapterframework.core.ParameterException) GZIPInputStream(java.util.zip.GZIPInputStream) PipeRunResult(nl.nn.adapterframework.core.PipeRunResult) StringTokenizer(java.util.StringTokenizer) ZipInputStream(java.util.zip.ZipInputStream) ErrorMessageFormatter(nl.nn.adapterframework.errormessageformatters.ErrorMessageFormatter) ByteArrayInputStream(java.io.ByteArrayInputStream) GZIPOutputStream(java.util.zip.GZIPOutputStream) ZipOutputStream(java.util.zip.ZipOutputStream) FileOutputStream(java.io.FileOutputStream) PipeRunException(nl.nn.adapterframework.core.PipeRunException) File(java.io.File)

Example 3 with ErrorMessageFormatter

use of nl.nn.adapterframework.errormessageformatters.ErrorMessageFormatter in project iaf by ibissource.

the class Adapter method formatErrorMessage.

public synchronized String formatErrorMessage(String errorMessage, Throwable t, String originalMessage, String messageID, INamedObject objectInError, long receivedTime) {
    if (errorMessageFormatter == null) {
        errorMessageFormatter = new ErrorMessageFormatter();
    }
    // you never can trust an implementation, so try/catch!
    try {
        String formattedErrorMessage = errorMessageFormatter.format(errorMessage, t, objectInError, originalMessage, messageID, receivedTime);
        String logMsg = "Adapter [" + getName() + "] messageId [" + messageID + "] formatted errormessage, result [" + formattedErrorMessage + "]";
        if (isMsgLogTerseEnabled()) {
            if (isMsgLogHidden()) {
                msgLog.info("Adapter [" + getName() + "] messageId [" + messageID + "] formatted errormessage, result [SIZE=" + getFileSizeAsBytes(formattedErrorMessage) + "]");
            } else {
                msgLog.info(logMsg);
            }
        }
        if (log.isDebugEnabled()) {
            log.debug(logMsg);
        }
        return formattedErrorMessage;
    } catch (Exception e) {
        String msg = "got error while formatting errormessage, original errorMessage [" + errorMessage + "]";
        msg = msg + " from [" + (objectInError == null ? "unknown-null" : objectInError.getName()) + "]";
        error(false, "got error while formatting errormessage", e);
        return errorMessage;
    }
}
Also used : ErrorMessageFormatter(nl.nn.adapterframework.errormessageformatters.ErrorMessageFormatter) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException)

Aggregations

ErrorMessageFormatter (nl.nn.adapterframework.errormessageformatters.ErrorMessageFormatter)3 ParameterException (nl.nn.adapterframework.core.ParameterException)2 PipeForward (nl.nn.adapterframework.core.PipeForward)2 PipeRunException (nl.nn.adapterframework.core.PipeRunException)2 PipeRunResult (nl.nn.adapterframework.core.PipeRunResult)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 StringTokenizer (java.util.StringTokenizer)1 GZIPInputStream (java.util.zip.GZIPInputStream)1 GZIPOutputStream (java.util.zip.GZIPOutputStream)1 ZipEntry (java.util.zip.ZipEntry)1