Search in sources :

Example 41 with SenderException

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

the class ProcessUtil method executeCommand.

/**
 * Execute a command as a process in the operating system.
 *
 * @param timeout timeout in seconds, or 0 to wait indefinetely until the process ends
 * @param command
 * @throws TimeOutException
 * @throws SenderException
 */
public static String executeCommand(List command, int timeout) throws TimeOutException, SenderException {
    String output;
    String errors;
    Process process;
    try {
        process = Runtime.getRuntime().exec((String[]) command.toArray(new String[0]));
    } catch (Throwable t) {
        throw new SenderException("Could not execute command [" + getCommandLine(command) + "]", t);
    }
    TimeoutGuard tg = new TimeoutGuard("ProcessUtil ");
    tg.activateGuard(timeout);
    try {
        // Wait until the process is completely finished, or timeout is expired
        process.waitFor();
    } catch (InterruptedException e) {
        if (tg.threadKilled()) {
            throw new TimeOutException("command [" + getCommandLine(command) + "] timed out", e);
        } else {
            throw new SenderException("command [" + getCommandLine(command) + "] interrupted while waiting for process", e);
        }
    } finally {
        tg.cancel();
    }
    // Read the output of the process
    try {
        output = readStream(process.getInputStream());
    } catch (IOException e) {
        throw new SenderException("Could not read output of command [" + getCommandLine(command) + "]", e);
    }
    // Read the errors of the process
    try {
        errors = readStream(process.getErrorStream());
    } catch (IOException e) {
        throw new SenderException("Could not read errors of command [" + getCommandLine(command) + "]", e);
    }
    // Throw an exception if the command returns an error exit value
    int exitValue = process.exitValue();
    if (exitValue != 0) {
        throw new SenderException("Nonzero exit value [" + exitValue + "] for command  [" + getCommandLine(command) + "], process output was [" + output + "], error output was [" + errors + "]");
    }
    if (StringUtils.isNotEmpty(errors)) {
        log.warn("command [" + getCommandLine(command) + "] had error output [" + errors + "]");
    }
    return output;
}
Also used : TimeOutException(nl.nn.adapterframework.core.TimeOutException) IOException(java.io.IOException) SenderException(nl.nn.adapterframework.core.SenderException) TimeoutGuard(nl.nn.adapterframework.task.TimeoutGuard)

Example 42 with SenderException

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

the class ConfigurationUtils method getConfigFromDatabase.

public static Map<String, Object> getConfigFromDatabase(IbisContext ibisContext, String name, String jmsRealm, String version) throws ConfigurationException {
    if (StringUtils.isEmpty(jmsRealm)) {
        jmsRealm = JmsRealmFactory.getInstance().getFirstDatasourceJmsRealm();
        if (StringUtils.isEmpty(jmsRealm)) {
            return null;
        }
    }
    if (StringUtils.isEmpty(version)) {
        // Make sure this is null when empty!
        version = null;
    }
    Connection conn = null;
    ResultSet rs = null;
    FixedQuerySender qs = (FixedQuerySender) ibisContext.createBeanAutowireByName(FixedQuerySender.class);
    qs.setJmsRealm(jmsRealm);
    qs.setQuery("SELECT COUNT(*) FROM IBISCONFIG");
    qs.configure();
    try {
        qs.open();
        conn = qs.getConnection();
        String query;
        if (version == null) {
            // Return active config
            query = "SELECT CONFIG, VERSION, FILENAME, CRE_TYDST, RUSER FROM IBISCONFIG WHERE NAME=? AND ACTIVECONFIG='" + (qs.getDbmsSupport().getBooleanValue(true)) + "'";
            PreparedStatement stmt = conn.prepareStatement(query);
            stmt.setString(1, name);
            rs = stmt.executeQuery();
        } else {
            query = "SELECT CONFIG, VERSION, FILENAME, CRE_TYDST, RUSER FROM IBISCONFIG WHERE NAME=? AND VERSION=?";
            PreparedStatement stmt = conn.prepareStatement(query);
            stmt.setString(1, name);
            stmt.setString(2, version);
            rs = stmt.executeQuery();
        }
        if (rs.next()) {
            Map<String, Object> configuration = new HashMap<String, Object>(5);
            byte[] jarBytes = rs.getBytes(1);
            if (jarBytes == null)
                return null;
            configuration.put("CONFIG", jarBytes);
            configuration.put("VERSION", rs.getString(2));
            configuration.put("FILENAME", rs.getString(3));
            configuration.put("CREATED", rs.getString(4));
            configuration.put("USER", rs.getString(5));
            return configuration;
        }
    } catch (SenderException e) {
        throw new ConfigurationException(e);
    } catch (JdbcException e) {
        throw new ConfigurationException(e);
    } catch (SQLException e) {
        throw new ConfigurationException(e);
    } finally {
        qs.close();
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                log.warn("Could not close resultset", e);
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                log.warn("Could not close connection", e);
            }
        }
    }
    return null;
}
Also used : HashMap(java.util.HashMap) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) JdbcException(nl.nn.adapterframework.jdbc.JdbcException) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) ResultSet(java.sql.ResultSet) SenderException(nl.nn.adapterframework.core.SenderException) FixedQuerySender(nl.nn.adapterframework.jdbc.FixedQuerySender)

Example 43 with SenderException

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

the class ZipIteratorPipe method getZipInputStream.

protected ZipInputStream getZipInputStream(Object input, IPipeLineSession session, String correlationID, Map threadContext) throws SenderException {
    if (input == null) {
        throw new SenderException("input is null. Must supply String (Filename), File or InputStream as input");
    }
    InputStream source = null;
    if (input instanceof InputStream) {
        source = (InputStream) input;
    } else if (input instanceof File) {
        try {
            source = new FileInputStream((File) input);
        } catch (FileNotFoundException e) {
            throw new SenderException("Cannot find file [" + ((File) input).getName() + "]", e);
        }
    } else if (input instanceof String) {
        String filename = (String) input;
        try {
            source = new FileInputStream(filename);
        } catch (FileNotFoundException e) {
            throw new SenderException("Cannot find file [" + filename + "]", e);
        }
    } else {
        throw new SenderException("input is of type [" + ClassUtils.nameOf(input) + "]. Must supply String (Filename), File or InputStream as input");
    }
    if (!(source instanceof BufferedInputStream)) {
        source = new BufferedInputStream(source);
    }
    ZipInputStream zipstream = new ZipInputStream(source);
    return zipstream;
}
Also used : ZipInputStream(java.util.zip.ZipInputStream) BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) ZipInputStream(java.util.zip.ZipInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) SenderException(nl.nn.adapterframework.core.SenderException) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 44 with SenderException

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

the class SoapWrapper method signMessage.

public String signMessage(String soapMessage, String user, String password) throws SenderException {
    try {
        WSSecurityEngine secEngine = WSSecurityEngine.getInstance();
        WSSConfig config = secEngine.getWssConfig();
        config.setPrecisionInMilliSeconds(false);
        // create context
        AxisClient tmpEngine = new AxisClient(new NullProvider());
        MessageContext msgContext = new MessageContext(tmpEngine);
        InputStream in = new ByteArrayInputStream(soapMessage.getBytes());
        Message msg = new Message(in);
        msg.setMessageContext(msgContext);
        // create unsigned envelope
        SOAPEnvelope unsignedEnvelope = msg.getSOAPEnvelope();
        Document doc = unsignedEnvelope.getAsDocument();
        // create security header and insert it into unsigned envelope
        WSSecHeader secHeader = new WSSecHeader();
        secHeader.insertSecurityHeader(doc);
        // add a UsernameToken
        WSSecUsernameToken tokenBuilder = new WSSecUsernameToken();
        tokenBuilder.setPasswordType(WSConstants.PASSWORD_DIGEST);
        tokenBuilder.setUserInfo(user, password);
        tokenBuilder.addNonce();
        tokenBuilder.addCreated();
        tokenBuilder.prepare(doc);
        WSSecSignature sign = new WSSecSignature();
        sign.setUsernameToken(tokenBuilder);
        sign.setKeyIdentifierType(WSConstants.UT_SIGNING);
        sign.setSignatureAlgorithm(XMLSignature.ALGO_ID_MAC_HMAC_SHA1);
        sign.build(doc, null, secHeader);
        tokenBuilder.prependToHeader(secHeader);
        // add a Timestamp
        WSSecTimestamp timestampBuilder = new WSSecTimestamp();
        timestampBuilder.setTimeToLive(300);
        timestampBuilder.prepare(doc);
        timestampBuilder.prependToHeader(secHeader);
        Document signedDoc = doc;
        return DOM2Writer.nodeToString(signedDoc);
    } catch (Exception e) {
        throw new SenderException(e);
    }
}
Also used : Message(org.apache.axis.Message) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) NullProvider(org.apache.axis.configuration.NullProvider) WSSecSignature(org.apache.ws.security.message.WSSecSignature) SOAPEnvelope(org.apache.axis.message.SOAPEnvelope) Document(org.w3c.dom.Document) WSSecTimestamp(org.apache.ws.security.message.WSSecTimestamp) TransformerException(javax.xml.transform.TransformerException) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) DomBuilderException(nl.nn.adapterframework.util.DomBuilderException) IOException(java.io.IOException) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) SenderException(nl.nn.adapterframework.core.SenderException) WSSecHeader(org.apache.ws.security.message.WSSecHeader) WSSConfig(org.apache.ws.security.WSSConfig) AxisClient(org.apache.axis.client.AxisClient) ByteArrayInputStream(java.io.ByteArrayInputStream) WSSecurityEngine(org.apache.ws.security.WSSecurityEngine) MessageContext(org.apache.axis.MessageContext) SenderException(nl.nn.adapterframework.core.SenderException) WSSecUsernameToken(org.apache.ws.security.message.WSSecUsernameToken)

Example 45 with SenderException

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

the class ShadowSender method doSendMessage.

/**
 * We override this from the parallel sender as we should only execute the original and shadowsenders here!
 */
@Override
public String doSendMessage(String correlationID, String message, ParameterResolutionContext prc) throws SenderException, TimeOutException {
    Guard guard = new Guard();
    Map<ISender, ParallelSenderExecutor> executorMap = new HashMap<ISender, ParallelSenderExecutor>();
    TaskExecutor executor = createTaskExecutor();
    for (Iterator<ISender> it = getExecutableSenders(); it.hasNext(); ) {
        ISender sender = it.next();
        // Create a new ParameterResolutionContext to be thread safe, see
        // documentation on constructor of ParameterResolutionContext
        // (parameter cacheXmlSource).
        // Testing also showed that disabling caching is better for
        // performance. At least when testing with a lot of large messages
        // in parallel. This might be due to the fact that objects can be
        // garbage collected earlier. OutOfMemoryErrors occur much
        // faster when caching is enabled. Testing was done by sending 10
        // messages of 1 MB concurrently to a pipeline which will process
        // the message in parallel with 10 SenderWrappers (containing a
        // XsltSender and IbisLocalSender).
        ParameterResolutionContext newPrc = new ParameterResolutionContext(prc.getInput(), prc.getSession(), prc.isNamespaceAware(), prc.isXslt2(), false);
        guard.addResource();
        ParallelSenderExecutor pse = new ParallelSenderExecutor(sender, correlationID, message, newPrc, guard, getStatisticsKeeper(sender));
        executorMap.put(sender, pse);
        executor.execute(pse);
    }
    try {
        guard.waitForAllResources();
    } catch (InterruptedException e) {
        throw new SenderException(getLogPrefix() + "was interupted", e);
    }
    ParallelSenderExecutor originalSender = null;
    XmlBuilder resultsXml = new XmlBuilder("results");
    resultsXml.addAttribute("correlationID", correlationID);
    resultsXml.addAttribute("adapter", getPipe().getAdapter().getName());
    XmlBuilder originalMessageXml = new XmlBuilder("originalMessage");
    originalMessageXml.setValue(XmlUtils.skipXmlDeclaration(message), false);
    resultsXml.addSubElement(originalMessageXml);
    // First loop through all (Shadow)Senders and handle their results
    for (Iterator<ISender> it = getExecutableSenders(); it.hasNext(); ) {
        ISender sender = it.next();
        ParallelSenderExecutor pse = (ParallelSenderExecutor) executorMap.get(sender);
        XmlBuilder resultXml;
        if (sender.getName() != null && sender.getName().equalsIgnoreCase(getOriginalSender())) {
            originalSender = pse;
            resultXml = new XmlBuilder("originalResult");
        } else {
            resultXml = new XmlBuilder("shadowResult");
        }
        StatisticsKeeper sk = getStatisticsKeeper(sender);
        resultXml.addAttribute("duration", sk.getLast() + sk.getUnits());
        resultXml.addAttribute("count", sk.getCount());
        resultXml.addAttribute("senderClass", ClassUtils.nameOf(sender));
        resultXml.addAttribute("senderName", sender.getName());
        Throwable throwable = pse.getThrowable();
        if (throwable == null) {
            Object result = pse.getReply();
            if (result == null) {
                resultXml.addAttribute("type", "null");
            } else {
                resultXml.addAttribute("type", ClassUtils.nameOf(result));
                resultXml.setValue(XmlUtils.skipXmlDeclaration(result.toString()), false);
            }
        } else {
            resultXml.addAttribute("type", ClassUtils.nameOf(throwable));
            resultXml.setValue(throwable.getMessage());
        }
        resultsXml.addSubElement(resultXml);
    }
    // cause an SenderException regardless of the results of the ShadowSenders.
    if (originalSender == null) {
        // In theory this should never happen!
        throw new SenderException("no originalSender found");
    }
    // The messages have been processed, now the results need to be stored somewhere.
    try {
        if (resultISender instanceof ISenderWithParameters) {
            ParameterResolutionContext newPrc = new ParameterResolutionContext(resultsXml.toXML(), prc.getSession());
            ((ISenderWithParameters) resultISender).sendMessage(correlationID, resultsXml.toXML(), newPrc);
        } else {
            resultISender.sendMessage(correlationID, resultsXml.toXML());
        }
    } catch (SenderException se) {
        log.warn("failed to send ShadowSender result to [" + resultISender.getName() + "]");
    }
    if (originalSender.getThrowable() != null) {
        throw new SenderException(originalSender.getThrowable());
    } else {
        return originalSender.getReply().toString();
    }
}
Also used : HashMap(java.util.HashMap) ISenderWithParameters(nl.nn.adapterframework.core.ISenderWithParameters) TaskExecutor(org.springframework.core.task.TaskExecutor) ISender(nl.nn.adapterframework.core.ISender) XmlBuilder(nl.nn.adapterframework.util.XmlBuilder) StatisticsKeeper(nl.nn.adapterframework.statistics.StatisticsKeeper) Guard(nl.nn.adapterframework.util.Guard) SenderException(nl.nn.adapterframework.core.SenderException) ParameterResolutionContext(nl.nn.adapterframework.parameters.ParameterResolutionContext)

Aggregations

SenderException (nl.nn.adapterframework.core.SenderException)130 TimeOutException (nl.nn.adapterframework.core.TimeOutException)41 ConfigurationException (nl.nn.adapterframework.configuration.ConfigurationException)37 IOException (java.io.IOException)36 SQLException (java.sql.SQLException)25 HashMap (java.util.HashMap)21 ParameterException (nl.nn.adapterframework.core.ParameterException)21 PreparedStatement (java.sql.PreparedStatement)20 Map (java.util.Map)20 DomBuilderException (nl.nn.adapterframework.util.DomBuilderException)18 Iterator (java.util.Iterator)17 ParameterValueList (nl.nn.adapterframework.parameters.ParameterValueList)16 InputStream (java.io.InputStream)15 ResultSet (java.sql.ResultSet)13 Element (org.w3c.dom.Element)13 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)12 Date (java.util.Date)10 ParameterResolutionContext (nl.nn.adapterframework.parameters.ParameterResolutionContext)10 XmlBuilder (nl.nn.adapterframework.util.XmlBuilder)10 UnsupportedEncodingException (java.io.UnsupportedEncodingException)9