Search in sources :

Example 31 with ParameterResolutionContext

use of nl.nn.adapterframework.parameters.ParameterResolutionContext in project iaf by ibissource.

the class ApiStreamPipe method adjustFirstStringPart.

@Override
protected String adjustFirstStringPart(String firstStringPart, IPipeLineSession session) throws PipeRunException {
    if (firstStringPart == null) {
        return "";
    } else {
        boolean retrieveMessage = false;
        if (XmlUtils.isWellFormed(firstStringPart, "MessageID")) {
            String rootNamespace = XmlUtils.getRootNamespace(firstStringPart);
            if ("http://www.w3.org/2005/08/addressing".equals(rootNamespace)) {
                retrieveMessage = true;
            }
        }
        if (retrieveMessage) {
            String messageId = null;
            try {
                messageId = XmlUtils.evaluateXPathNodeSetFirstElement(firstStringPart, "MessageID");
            } catch (Exception e) {
                throw new PipeRunException(this, "Exception getting MessageID", e);
            }
            if (StringUtils.isEmpty(messageId)) {
                throw new PipeRunException(this, "Could not find messageId in request [" + firstStringPart + "]");
            } else {
                // TODO: create dummyQuerySender should be put in
                // configure(), but gives an error
                IbisContext ibisContext = getAdapter().getConfiguration().getIbisManager().getIbisContext();
                dummyQuerySender = (FixedQuerySender) ibisContext.createBeanAutowireByName(FixedQuerySender.class);
                dummyQuerySender.setJmsRealm(jmsRealm);
                dummyQuerySender.setQuery("SELECT count(*) FROM ALL_TABLES");
                try {
                    dummyQuerySender.configure();
                } catch (ConfigurationException e) {
                    throw new PipeRunException(this, "Exception configuring dummy query sender", e);
                }
                ParameterResolutionContext prc = new ParameterResolutionContext("", session);
                String slotId = AppConstants.getInstance().getResolvedProperty("instance.name") + "/" + session.get("operation");
                String selectMessageKeyResult = null;
                try {
                    selectMessageKeyResult = selectMessageKey(slotId, messageId);
                } catch (Exception e) {
                    throw new PipeRunException(this, "Exception getting messageKey", e);
                }
                if (StringUtils.isEmpty(selectMessageKeyResult)) {
                    throw new PipeRunException(this, "Could not find message in MessageStore for slotId [" + slotId + "] and messageId [" + messageId + "]");
                } else {
                    String selectMessageResult = null;
                    try {
                        selectMessageResult = selectMessage(selectMessageKeyResult);
                    } catch (Exception e) {
                        throw new PipeRunException(this, "Exception getting message", e);
                    }
                    if (StringUtils.isEmpty(selectMessageResult)) {
                        throw new PipeRunException(this, "Could not find message in MessageStore with messageKey [" + selectMessageKeyResult + "]");
                    } else {
                        try {
                            deleteMessage(selectMessageKeyResult);
                        } catch (Exception e) {
                            throw new PipeRunException(this, "Exception deleting message", e);
                        }
                    }
                    return selectMessageResult;
                }
            }
        } else {
            return firstStringPart;
        }
    }
}
Also used : IbisContext(nl.nn.adapterframework.configuration.IbisContext) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) PipeRunException(nl.nn.adapterframework.core.PipeRunException) ParameterResolutionContext(nl.nn.adapterframework.parameters.ParameterResolutionContext) PipeRunException(nl.nn.adapterframework.core.PipeRunException) JdbcException(nl.nn.adapterframework.jdbc.JdbcException) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) SQLException(java.sql.SQLException)

Example 32 with ParameterResolutionContext

use of nl.nn.adapterframework.parameters.ParameterResolutionContext in project iaf by ibissource.

the class HttpSenderBase method sendMessageWithTimeoutGuarded.

@Override
public String sendMessageWithTimeoutGuarded(String correlationID, String message, ParameterResolutionContext prc) throws SenderException, TimeOutException {
    ParameterValueList pvl = null;
    try {
        if (prc != null && paramList != null) {
            pvl = prc.getValues(paramList);
        }
    } catch (ParameterException e) {
        throw new SenderException(getLogPrefix() + "Sender [" + getName() + "] caught exception evaluating parameters", e);
    }
    URIBuilder uri;
    HttpRequestBase httpRequestBase;
    try {
        if (urlParameter != null) {
            String url = (String) pvl.getParameterValue(getUrlParam()).getValue();
            uri = getURI(url);
        } else {
            uri = staticUri;
        }
        httpTarget = new HttpHost(uri.getHost(), getPort(uri), uri.getScheme());
        Map<String, String> headersParamsMap = new HashMap<String, String>();
        if (headersParams != null) {
            StringTokenizer st = new StringTokenizer(headersParams, ",");
            while (st.hasMoreElements()) {
                headersParamsMap.put(st.nextToken(), null);
            }
        }
        if (isEncodeMessages()) {
            message = URLEncoder.encode(message, getCharSet());
        }
        httpRequestBase = getMethod(uri, message, pvl, headersParamsMap, prc.getSession());
        if (httpRequestBase == null)
            throw new MethodNotSupportedException("could not find implementation for method [" + getMethodType() + "]");
        if (!"POST".equals(getMethodType()) && !"PUT".equals(getMethodType()) && !"REPORT".equals(getMethodType())) {
            httpClientBuilder.setRedirectStrategy(new DefaultRedirectStrategy() {

                @Override
                protected boolean isRedirectable(String method) {
                    return true;
                }
            });
        }
        if (StringUtils.isNotEmpty(getContentType())) {
            httpRequestBase.setHeader("Content-Type", getContentType());
        }
        if (credentials != null && !StringUtils.isEmpty(credentials.getUsername())) {
            AuthCache authCache = httpClientContext.getAuthCache();
            if (authCache == null)
                authCache = new BasicAuthCache();
            authCache.put(httpTarget, new BasicScheme());
            httpClientContext.setAuthCache(authCache);
        }
        log.info(getLogPrefix() + "configured httpclient for host [" + uri.getHost() + "]");
    } catch (Exception e) {
        throw new SenderException(e);
    }
    CloseableHttpClient httpClient = httpClientBuilder.build();
    String result = null;
    int statusCode = -1;
    int count = getMaxExecuteRetries();
    String msg = null;
    while (count-- >= 0 && statusCode == -1) {
        try {
            log.debug(getLogPrefix() + "executing method [" + httpRequestBase.getRequestLine() + "]");
            HttpResponse httpResponse = httpClient.execute(httpTarget, httpRequestBase, httpClientContext);
            log.debug(getLogPrefix() + "executed method");
            HttpResponseHandler responseHandler = new HttpResponseHandler(httpResponse);
            StatusLine statusline = httpResponse.getStatusLine();
            statusCode = statusline.getStatusCode();
            if (StringUtils.isNotEmpty(getResultStatusCodeSessionKey()) && prc != null) {
                prc.getSession().put(getResultStatusCodeSessionKey(), Integer.toString(statusCode));
            }
            if (statusCode != HttpServletResponse.SC_OK) {
                log.warn(getLogPrefix() + "status [" + statusline.toString() + "]");
            } else {
                log.debug(getLogPrefix() + "status [" + statusCode + "]");
            }
            result = extractResult(responseHandler, prc);
            log.debug(getLogPrefix() + "retrieved result [" + result + "]");
        } catch (ClientProtocolException e) {
            httpRequestBase.abort();
            Throwable throwable = e.getCause();
            String cause = null;
            if (throwable != null) {
                cause = throwable.toString();
            }
            msg = e.getMessage();
            log.warn(getLogPrefix() + "httpException with message [" + msg + "] and cause [" + cause + "], executeRetries left [" + count + "]");
        } catch (IOException e) {
            httpRequestBase.abort();
            if (e instanceof SocketTimeoutException) {
                throw new TimeOutException(e);
            }
            throw new SenderException(e);
        } finally {
        // By forcing the use of the HttpResponseHandler the resultStream
        // will automatically be closed when it has been read.
        // See HttpResponseHandler and ReleaseConnectionAfterReadInputStream.
        // We cannot close the connection as the response might be kept
        // in a sessionKey for later use in the pipeline.
        // 
        // IMPORTANT: It is possible that poorly written implementations
        // wont read or close the response.
        // This will cause the connection to become stale..
        }
    }
    if (statusCode == -1) {
        if (StringUtils.contains(msg.toUpperCase(), "TIMEOUTEXCEPTION")) {
            // java.net.SocketTimeoutException: Read timed out
            throw new TimeOutException("Failed to recover from timeout exception");
        }
        throw new SenderException("Failed to recover from exception");
    }
    if (isXhtml() && StringUtils.isNotEmpty(result)) {
        result = XmlUtils.skipDocTypeDeclaration(result.trim());
        if (result.startsWith("<html>") || result.startsWith("<html ")) {
            CleanerProperties props = new CleanerProperties();
            HtmlCleaner cleaner = new HtmlCleaner(props);
            TagNode tagNode = cleaner.clean(result);
            result = new SimpleXmlSerializer(props).getXmlAsString(tagNode);
            if (transformerPool != null) {
                log.debug(getLogPrefix() + " transforming result [" + result + "]");
                ParameterResolutionContext prc_xslt = new ParameterResolutionContext(result, null, true, true);
                try {
                    result = transformerPool.transform(prc_xslt.getInputSource(), null);
                } catch (Exception e) {
                    throw new SenderException("Exception on transforming input", e);
                }
            }
        }
    }
    return result;
}
Also used : ParameterValueList(nl.nn.adapterframework.parameters.ParameterValueList) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HashMap(java.util.HashMap) SimpleXmlSerializer(org.htmlcleaner.SimpleXmlSerializer) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) ClientProtocolException(org.apache.http.client.ClientProtocolException) HttpHost(org.apache.http.HttpHost) DefaultRedirectStrategy(org.apache.http.impl.client.DefaultRedirectStrategy) ParameterException(nl.nn.adapterframework.core.ParameterException) CleanerProperties(org.htmlcleaner.CleanerProperties) ParameterResolutionContext(nl.nn.adapterframework.parameters.ParameterResolutionContext) BasicScheme(org.apache.http.impl.auth.BasicScheme) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) SenderException(nl.nn.adapterframework.core.SenderException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ClientProtocolException(org.apache.http.client.ClientProtocolException) SocketTimeoutException(java.net.SocketTimeoutException) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) MethodNotSupportedException(org.apache.http.MethodNotSupportedException) IOException(java.io.IOException) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) TimeOutException(nl.nn.adapterframework.core.TimeOutException) ParameterException(nl.nn.adapterframework.core.ParameterException) HtmlCleaner(org.htmlcleaner.HtmlCleaner) URIBuilder(org.apache.http.client.utils.URIBuilder) StatusLine(org.apache.http.StatusLine) StringTokenizer(java.util.StringTokenizer) TimeOutException(nl.nn.adapterframework.core.TimeOutException) SocketTimeoutException(java.net.SocketTimeoutException) MethodNotSupportedException(org.apache.http.MethodNotSupportedException) SenderException(nl.nn.adapterframework.core.SenderException) TagNode(org.htmlcleaner.TagNode)

Example 33 with ParameterResolutionContext

use of nl.nn.adapterframework.parameters.ParameterResolutionContext in project iaf by ibissource.

the class ZipWriterPipe method doPipe.

public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException {
    if (ACTION_CLOSE.equals(getAction())) {
        closeZipWriterHandle(session, true);
        return new PipeRunResult(getForward(), input);
    }
    String msg = null;
    if (input instanceof String) {
        msg = (String) input;
    }
    ParameterResolutionContext prc = new ParameterResolutionContext(msg, session);
    ParameterValueList pvl;
    try {
        pvl = prc.getValues(getParameterList());
    } catch (ParameterException e1) {
        throw new PipeRunException(this, getLogPrefix(session) + "cannot determine filename", e1);
    }
    ZipWriter sessionData = getZipWriter(session);
    if (ACTION_OPEN.equals(getAction())) {
        if (sessionData != null) {
            throw new PipeRunException(this, getLogPrefix(session) + "zipWriterHandle in session key [" + getZipWriterHandle() + "] is already open");
        }
        sessionData = createZipWriter(session, pvl, input);
        return new PipeRunResult(getForward(), input);
    }
    // from here on action must be 'write' or 'stream'
    if (sessionData == null) {
        throw new PipeRunException(this, getLogPrefix(session) + "zipWriterHandle in session key [" + getZipWriterHandle() + "] is not open");
    }
    String filename = (String) pvl.getParameterValue(PARAMETER_FILENAME).getValue();
    if (StringUtils.isEmpty(filename)) {
        throw new PipeRunException(this, getLogPrefix(session) + "filename cannot be empty");
    }
    try {
        if (ACTION_STREAM.equals(getAction())) {
            sessionData.openEntry(filename);
            PipeRunResult prr = new PipeRunResult(getForward(), sessionData.getZipoutput());
            return prr;
        }
        if (ACTION_WRITE.equals(getAction())) {
            try {
                if (isCompleteFileHeader()) {
                    sessionData.writeEntryWithCompletedHeader(filename, input, isCloseInputstreamOnExit(), getCharset());
                } else {
                    sessionData.writeEntry(filename, input, isCloseInputstreamOnExit(), getCharset());
                }
            } catch (IOException e) {
                throw new PipeRunException(this, getLogPrefix(session) + "cannot add data to zipentry for [" + filename + "]", e);
            }
            return new PipeRunResult(getForward(), input);
        }
        throw new PipeRunException(this, getLogPrefix(session) + "illegal action [" + getAction() + "]");
    } catch (CompressionException e) {
        throw new PipeRunException(this, getLogPrefix(session) + "cannot add zipentry for [" + filename + "]", e);
    }
}
Also used : PipeRunResult(nl.nn.adapterframework.core.PipeRunResult) ParameterValueList(nl.nn.adapterframework.parameters.ParameterValueList) PipeRunException(nl.nn.adapterframework.core.PipeRunException) ParameterException(nl.nn.adapterframework.core.ParameterException) IOException(java.io.IOException) ParameterResolutionContext(nl.nn.adapterframework.parameters.ParameterResolutionContext)

Example 34 with ParameterResolutionContext

use of nl.nn.adapterframework.parameters.ParameterResolutionContext in project iaf by ibissource.

the class MessageSendingPipe method sendTextMessage.

protected String sendTextMessage(Object input, IPipeLineSession session, String correlationID, ISender sender, Map threadContext) throws SenderException, TimeOutException {
    if (input != null && !(input instanceof String)) {
        throw new SenderException("String expected, got a [" + input.getClass().getName() + "]");
    }
    // sendResult has a messageID for async senders, the result for sync senders
    if (sender instanceof ISenderWithParameters) {
        // do not only check own parameters, sender may have them by itself
        ISenderWithParameters psender = (ISenderWithParameters) sender;
        ParameterResolutionContext prc = new ParameterResolutionContext((String) input, session, isNamespaceAware());
        return psender.sendMessage(correlationID, (String) input, prc);
    }
    return sender.sendMessage(correlationID, (String) input);
}
Also used : ISenderWithParameters(nl.nn.adapterframework.core.ISenderWithParameters) SenderException(nl.nn.adapterframework.core.SenderException) ParameterResolutionContext(nl.nn.adapterframework.parameters.ParameterResolutionContext)

Example 35 with ParameterResolutionContext

use of nl.nn.adapterframework.parameters.ParameterResolutionContext in project iaf by ibissource.

the class PutParametersInSession method doPipe.

public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException {
    ParameterValueList pvl = null;
    ParameterList parameterList = getParameterList();
    if (parameterList != null) {
        ParameterResolutionContext prc = new ParameterResolutionContext((String) input, session);
        try {
            pvl = prc.getValues(getParameterList());
            if (pvl != null) {
                for (int i = 0; i < parameterList.size(); i++) {
                    Parameter parameter = parameterList.getParameter(i);
                    String pn = parameter.getName();
                    Object pv = parameter.getValue(pvl, prc);
                    session.put(pn, pv);
                    log.debug(getLogPrefix(session) + "stored [" + pv + "] in pipeLineSession under key [" + pn + "]");
                }
            }
        } catch (ParameterException e) {
            throw new PipeRunException(this, getLogPrefix(session) + "exception extracting parameters", e);
        }
    }
    return new PipeRunResult(getForward(), input);
}
Also used : PipeRunResult(nl.nn.adapterframework.core.PipeRunResult) ParameterValueList(nl.nn.adapterframework.parameters.ParameterValueList) PipeRunException(nl.nn.adapterframework.core.PipeRunException) ParameterList(nl.nn.adapterframework.parameters.ParameterList) Parameter(nl.nn.adapterframework.parameters.Parameter) ParameterException(nl.nn.adapterframework.core.ParameterException) ParameterResolutionContext(nl.nn.adapterframework.parameters.ParameterResolutionContext)

Aggregations

ParameterResolutionContext (nl.nn.adapterframework.parameters.ParameterResolutionContext)47 PipeRunException (nl.nn.adapterframework.core.PipeRunException)32 PipeRunResult (nl.nn.adapterframework.core.PipeRunResult)21 ConfigurationException (nl.nn.adapterframework.configuration.ConfigurationException)20 ParameterException (nl.nn.adapterframework.core.ParameterException)18 IOException (java.io.IOException)17 ParameterValueList (nl.nn.adapterframework.parameters.ParameterValueList)16 Parameter (nl.nn.adapterframework.parameters.Parameter)15 Map (java.util.Map)10 SenderException (nl.nn.adapterframework.core.SenderException)10 ParameterList (nl.nn.adapterframework.parameters.ParameterList)10 FixedQuerySender (nl.nn.adapterframework.jdbc.FixedQuerySender)8 PipeForward (nl.nn.adapterframework.core.PipeForward)7 HashMap (java.util.HashMap)6 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)5 PipeLineSessionBase (nl.nn.adapterframework.core.PipeLineSessionBase)4 DomBuilderException (nl.nn.adapterframework.util.DomBuilderException)4 URL (java.net.URL)3 ISender (nl.nn.adapterframework.core.ISender)3 PipeStartException (nl.nn.adapterframework.core.PipeStartException)3