Search in sources :

Example 1 with TransformerPool

use of nl.nn.adapterframework.util.TransformerPool in project iaf by ibissource.

the class Parameter method transform.

private Object transform(Source xmlSource, ParameterResolutionContext prc) throws ParameterException, TransformerException, IOException {
    TransformerPool pool = getTransformerPool();
    if (TYPE_NODE.equals(getType()) || TYPE_DOMDOC.equals(getType())) {
        DOMResult transformResult = new DOMResult();
        pool.transform(xmlSource, transformResult, prc.getValueMap(paramList));
        Node result = transformResult.getNode();
        if (result != null && TYPE_NODE.equals(getType())) {
            result = result.getFirstChild();
        }
        if (log.isDebugEnabled()) {
            if (result != null)
                log.debug("Returning Node result [" + result.getClass().getName() + "][" + result + "]: " + ToStringBuilder.reflectionToString(result));
        }
        return result;
    } else {
        return pool.transform(xmlSource, prc.getValueMap(paramList));
    }
}
Also used : DOMResult(javax.xml.transform.dom.DOMResult) Node(org.w3c.dom.Node) TransformerPool(nl.nn.adapterframework.util.TransformerPool)

Example 2 with TransformerPool

use of nl.nn.adapterframework.util.TransformerPool in project iaf by ibissource.

the class Parameter method getValue.

/**
 * determines the raw value
 * @param alreadyResolvedParameters
 * @return the raw value as object
 * @throws IbisException
 */
public Object getValue(ParameterValueList alreadyResolvedParameters, ParameterResolutionContext prc) throws ParameterException {
    Object result = null;
    log.debug("Calculating value for Parameter [" + getName() + "]");
    if (!configured) {
        throw new ParameterException("Parameter [" + getName() + "] not configured");
    }
    String retrievedSessionKey;
    if (transformerPoolSessionKey != null) {
        try {
            retrievedSessionKey = transformerPoolSessionKey.transform(prc.getInput(), null);
        } catch (Exception e) {
            throw new ParameterException("SessionKey for parameter [" + getName() + "] exception on transformation to get name", e);
        }
    } else {
        retrievedSessionKey = getSessionKey();
    }
    TransformerPool pool = getTransformerPool();
    if (pool != null) {
        try {
            Object transformResult = null;
            Source source = null;
            if (StringUtils.isNotEmpty(getValue())) {
                source = XmlUtils.stringToSourceForSingleUse(getValue(), prc.isNamespaceAware());
            } else if (StringUtils.isNotEmpty(retrievedSessionKey)) {
                String sourceString;
                Object sourceObject = prc.getSession().get(retrievedSessionKey);
                if (TYPE_LIST.equals(getType()) && sourceObject instanceof List) {
                    List<String> items = (List<String>) sourceObject;
                    XmlBuilder itemsXml = new XmlBuilder("items");
                    for (Iterator<String> it = items.iterator(); it.hasNext(); ) {
                        String item = it.next();
                        XmlBuilder itemXml = new XmlBuilder("item");
                        itemXml.setValue(item);
                        itemsXml.addSubElement(itemXml);
                    }
                    sourceString = itemsXml.toXML();
                } else if (TYPE_MAP.equals(getType()) && sourceObject instanceof Map) {
                    Map<String, String> items = (Map<String, String>) sourceObject;
                    XmlBuilder itemsXml = new XmlBuilder("items");
                    for (Iterator<String> it = items.keySet().iterator(); it.hasNext(); ) {
                        String item = it.next();
                        XmlBuilder itemXml = new XmlBuilder("item");
                        itemXml.addAttribute("name", item);
                        itemXml.setValue(items.get(item));
                        itemsXml.addSubElement(itemXml);
                    }
                    sourceString = itemsXml.toXML();
                } else {
                    sourceString = (String) sourceObject;
                }
                if (StringUtils.isNotEmpty(sourceString)) {
                    log.debug("Parameter [" + getName() + "] using sessionvariable [" + retrievedSessionKey + "] as source for transformation");
                    source = XmlUtils.stringToSourceForSingleUse(sourceString, prc.isNamespaceAware());
                } else {
                    log.debug("Parameter [" + getName() + "] sessionvariable [" + retrievedSessionKey + "] empty, no transformation will be performed");
                }
            } else if (StringUtils.isNotEmpty(getPattern())) {
                String sourceString = format(alreadyResolvedParameters, prc);
                if (StringUtils.isNotEmpty(sourceString)) {
                    log.debug("Parameter [" + getName() + "] using pattern [" + getPattern() + "] as source for transformation");
                    source = XmlUtils.stringToSourceForSingleUse(sourceString, prc.isNamespaceAware());
                } else {
                    log.debug("Parameter [" + getName() + "] pattern [" + getPattern() + "] empty, no transformation will be performed");
                }
            } else {
                source = prc.getInputSource();
            }
            if (source != null) {
                if (transformerPoolRemoveNamespaces != null) {
                    String rnResult = transformerPoolRemoveNamespaces.transform(source, null);
                    source = XmlUtils.stringToSource(rnResult);
                }
                transformResult = transform(source, prc);
            }
            if (!(transformResult instanceof String) || StringUtils.isNotEmpty((String) transformResult)) {
                result = transformResult;
            }
        } catch (Exception e) {
            throw new ParameterException("Parameter [" + getName() + "] exception on transformation to get parametervalue", e);
        }
    } else {
        if (StringUtils.isNotEmpty(retrievedSessionKey)) {
            result = prc.getSession().get(retrievedSessionKey);
        } else if (StringUtils.isNotEmpty(getPattern())) {
            result = format(alreadyResolvedParameters, prc);
        } else if (StringUtils.isNotEmpty(getValue())) {
            result = getValue();
        } else {
            result = prc.getInput();
        }
    }
    if (result != null) {
        if (log.isDebugEnabled()) {
            log.debug("Parameter [" + getName() + "] resolved to [" + (isHidden() ? hide(result.toString()) : result) + "]");
        }
    } else {
        // if value is null then return specified default value
        StringTokenizer stringTokenizer = new StringTokenizer(getDefaultValueMethods(), ",");
        while (result == null && stringTokenizer.hasMoreElements()) {
            String token = stringTokenizer.nextToken();
            if ("defaultValue".equals(token)) {
                result = getDefaultValue();
            } else if ("sessionKey".equals(token)) {
                result = prc.getSession().get(retrievedSessionKey);
            } else if ("pattern".equals(token)) {
                result = format(alreadyResolvedParameters, prc);
            } else if ("value".equals(token)) {
                result = getValue();
            } else if ("input".equals(token)) {
                result = prc.getInput();
            }
        }
        log.debug("Parameter [" + getName() + "] resolved to defaultvalue [" + (isHidden() ? hide(result.toString()) : result) + "]");
    }
    if (result != null && result instanceof String) {
        if (getMinLength() >= 0 && !TYPE_NUMBER.equals(getType())) {
            if (result.toString().length() < getMinLength()) {
                log.debug("Padding parameter [" + getName() + "] because length [" + result.toString().length() + "] deceeds minLength [" + getMinLength() + "]");
                result = StringUtils.rightPad(result.toString(), getMinLength());
            }
        }
        if (getMaxLength() >= 0) {
            if (result.toString().length() > getMaxLength()) {
                log.debug("Trimming parameter [" + getName() + "] because length [" + result.toString().length() + "] exceeds maxLength [" + getMaxLength() + "]");
                result = result.toString().substring(0, getMaxLength());
            }
        }
        if (TYPE_NODE.equals(getType())) {
            try {
                result = XmlUtils.buildNode((String) result, prc.isNamespaceAware());
                if (log.isDebugEnabled())
                    log.debug("final result [" + result.getClass().getName() + "][" + result + "]");
            } catch (DomBuilderException e) {
                throw new ParameterException("Parameter [" + getName() + "] could not parse result [" + result + "] to XML nodeset", e);
            }
        }
        if (TYPE_DOMDOC.equals(getType())) {
            try {
                result = XmlUtils.buildDomDocument((String) result, prc.isNamespaceAware(), prc.isXslt2());
                if (log.isDebugEnabled())
                    log.debug("final result [" + result.getClass().getName() + "][" + result + "]");
            } catch (DomBuilderException e) {
                throw new ParameterException("Parameter [" + getName() + "] could not parse result [" + result + "] to XML document", e);
            }
        }
        if (TYPE_DATE.equals(getType()) || TYPE_DATETIME.equals(getType()) || TYPE_TIMESTAMP.equals(getType()) || TYPE_TIME.equals(getType())) {
            log.debug("Parameter [" + getName() + "] converting result [" + result + "] to date using formatString [" + getFormatString() + "]");
            DateFormat df = new SimpleDateFormat(getFormatString());
            try {
                result = df.parseObject((String) result);
            } catch (ParseException e) {
                throw new ParameterException("Parameter [" + getName() + "] could not parse result [" + result + "] to Date using formatString [" + getFormatString() + "]", e);
            }
        }
        if (TYPE_XMLDATETIME.equals(getType())) {
            log.debug("Parameter [" + getName() + "] converting result [" + result + "] from xml dateTime to date");
            result = DateUtils.parseXmlDateTime((String) result);
        }
        if (TYPE_NUMBER.equals(getType())) {
            log.debug("Parameter [" + getName() + "] converting result [" + result + "] to number decimalSeparator [" + decimalFormatSymbols.getDecimalSeparator() + "] groupingSeparator [" + decimalFormatSymbols.getGroupingSeparator() + "]");
            DecimalFormat df = new DecimalFormat();
            df.setDecimalFormatSymbols(decimalFormatSymbols);
            try {
                Number n = df.parse((String) result);
                result = n;
            } catch (ParseException e) {
                throw new ParameterException("Parameter [" + getName() + "] could not parse result [" + result + "] to number decimalSeparator [" + decimalFormatSymbols.getDecimalSeparator() + "] groupingSeparator [" + decimalFormatSymbols.getGroupingSeparator() + "]", e);
            }
            if (getMinLength() >= 0 && result.toString().length() < getMinLength()) {
                log.debug("Adding leading zeros to parameter [" + getName() + "]");
                result = StringUtils.leftPad(result.toString(), getMinLength(), '0');
            }
        }
        if (TYPE_INTEGER.equals(getType())) {
            log.debug("Parameter [" + getName() + "] converting result [" + result + "] to integer");
            try {
                Integer i = Integer.parseInt((String) result);
                result = i;
            } catch (NumberFormatException e) {
                throw new ParameterException("Parameter [" + getName() + "] could not parse result [" + result + "] to integer", e);
            }
        }
    }
    if (result != null) {
        if (getMinInclusive() != null || getMaxInclusive() != null) {
            if (getMinInclusive() != null) {
                if (((Number) result).floatValue() < minInclusive.floatValue()) {
                    log.debug("Replacing parameter [" + getName() + "] because value [" + result + "] exceeds minInclusive [" + getMinInclusive() + "]");
                    result = minInclusive;
                }
            }
            if (getMaxInclusive() != null) {
                if (((Number) result).floatValue() > maxInclusive.floatValue()) {
                    log.debug("Replacing parameter [" + getName() + "] because value [" + result + "] exceeds maxInclusive [" + getMaxInclusive() + "]");
                    result = maxInclusive;
                }
            }
        }
    }
    return result;
}
Also used : DecimalFormat(java.text.DecimalFormat) TransformerException(javax.xml.transform.TransformerException) IbisException(nl.nn.adapterframework.core.IbisException) ParseException(java.text.ParseException) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) DomBuilderException(nl.nn.adapterframework.util.DomBuilderException) IOException(java.io.IOException) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) ParameterException(nl.nn.adapterframework.core.ParameterException) TransformerPool(nl.nn.adapterframework.util.TransformerPool) Source(javax.xml.transform.Source) StringTokenizer(java.util.StringTokenizer) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) Iterator(java.util.Iterator) XmlBuilder(nl.nn.adapterframework.util.XmlBuilder) INamedObject(nl.nn.adapterframework.core.INamedObject) ParameterException(nl.nn.adapterframework.core.ParameterException) ArrayList(java.util.ArrayList) List(java.util.List) DomBuilderException(nl.nn.adapterframework.util.DomBuilderException) ParseException(java.text.ParseException) Map(java.util.Map) SimpleDateFormat(java.text.SimpleDateFormat)

Example 3 with TransformerPool

use of nl.nn.adapterframework.util.TransformerPool in project iaf by ibissource.

the class JmsListenerBase method getResultFromxPath.

protected String getResultFromxPath(String message, String xPathExpression) {
    String found = "";
    if (message != null && message.length() > 0) {
        if (XmlUtils.isWellFormed(message)) {
            try {
                TransformerPool test = TransformerPool.getInstance(XmlUtils.createXPathEvaluatorSource("", xPathExpression, "text", false), true);
                found = test.transform(message, null);
                // xPath not found and message length is 0 but not null nor ""
                if (found.length() == 0)
                    found = "";
            } catch (Exception e) {
            }
        }
    }
    return found;
}
Also used : TransformerPool(nl.nn.adapterframework.util.TransformerPool) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) JMSException(javax.jms.JMSException) SenderException(nl.nn.adapterframework.core.SenderException) ListenerException(nl.nn.adapterframework.core.ListenerException)

Example 4 with TransformerPool

use of nl.nn.adapterframework.util.TransformerPool in project iaf by ibissource.

the class JsonPipe method doPipe.

@Override
public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException {
    if (input == null) {
        throw new PipeRunException(this, getLogPrefix(session) + "got null input");
    }
    if (!(input instanceof String)) {
        throw new PipeRunException(this, getLogPrefix(session) + "got an invalid type as input, expected String, got " + input.getClass().getName());
    }
    try {
        String stringResult = (String) input;
        String actualDirection = getDirection();
        String actualVersion = getVersion();
        if ("json2xml".equalsIgnoreCase(actualDirection)) {
            JSONTokener jsonTokener = new JSONTokener(stringResult);
            if (stringResult.startsWith("{")) {
                JSONObject jsonObject = new JSONObject(jsonTokener);
                stringResult = XML.toString(jsonObject);
            }
            if (stringResult.startsWith("[")) {
                JSONArray jsonArray = new JSONArray(jsonTokener);
                stringResult = XML.toString(jsonArray);
            }
            if (addXmlRootElement()) {
                boolean isWellFormed = XmlUtils.isWellFormed(stringResult);
                if (!isWellFormed) {
                    stringResult = "<root>" + stringResult + "</root>";
                }
            }
        }
        if ("xml2json".equalsIgnoreCase(actualDirection)) {
            if ("2".equals(actualVersion)) {
                stringResult = (String) input;
                ParameterResolutionContext prc = new ParameterResolutionContext(stringResult, session, true, true);
                TransformerPool transformerPool = TransformerPool.configureTransformer0(getLogPrefix(null), classLoader, null, null, "/xml/xsl/xml2json.xsl", null, false, null, true);
                stringResult = transformerPool.transform(prc.getInputSource(), null);
            } else {
                JSONObject jsonObject = XML.toJSONObject(stringResult);
                stringResult = jsonObject.toString();
            }
        }
        return new PipeRunResult(getForward(), stringResult);
    } catch (Exception e) {
        throw new PipeRunException(this, getLogPrefix(session) + " Exception on transforming input", e);
    }
}
Also used : JSONTokener(org.json.JSONTokener) PipeRunResult(nl.nn.adapterframework.core.PipeRunResult) JSONObject(org.json.JSONObject) PipeRunException(nl.nn.adapterframework.core.PipeRunException) JSONArray(org.json.JSONArray) ParameterResolutionContext(nl.nn.adapterframework.parameters.ParameterResolutionContext) TransformerPool(nl.nn.adapterframework.util.TransformerPool) PipeRunException(nl.nn.adapterframework.core.PipeRunException) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException)

Example 5 with TransformerPool

use of nl.nn.adapterframework.util.TransformerPool in project iaf by ibissource.

the class WsdlGeneratorPipe method createValidator.

private EsbSoapValidator createValidator(File xsdFile, String namespace, String root, int rootPosition, int cmhVersion) throws ConfigurationException {
    if (xsdFile != null) {
        EsbSoapValidator esbSoapValidator = new EsbSoapValidator();
        esbSoapValidator.setWarn(false);
        esbSoapValidator.setCmhVersion(cmhVersion);
        if (StringUtils.isEmpty(namespace)) {
            String xsdTargetNamespace = null;
            try {
                TransformerPool tp = TransformerPool.getInstance(XmlUtils.createXPathEvaluatorSource("*/@targetNamespace", "text"));
                xsdTargetNamespace = tp.transform(Misc.fileToString(xsdFile.getPath()), null);
                if (StringUtils.isNotEmpty(xsdTargetNamespace)) {
                    log.debug("found target namespace [" + xsdTargetNamespace + "] in xsd file [" + xsdFile.getName() + "]");
                } else {
                    // default namespace to prevent
                    // "(IllegalArgumentException) The schema attribute isn't supported"
                    xsdTargetNamespace = "urn:wsdlGenerator";
                    log.warn("could not find target namespace in xsd file [" + xsdFile.getName() + "], assuming namespace [" + xsdTargetNamespace + "]");
                }
            } catch (Exception e) {
                throw new ConfigurationException(e);
            }
            if (StringUtils.isEmpty(xsdTargetNamespace)) {
                esbSoapValidator.setSchema(xsdFile.getName());
            } else {
                esbSoapValidator.setSchemaLocation(xsdTargetNamespace + "\t" + xsdFile.getName());
                esbSoapValidator.setAddNamespaceToSchema(true);
            }
        } else {
            esbSoapValidator.setSchemaLocation(namespace + "\t" + xsdFile.getName());
            esbSoapValidator.setAddNamespaceToSchema(true);
        }
        if (StringUtils.isEmpty(root)) {
            String xsdRoot = null;
            try {
                String rootXPath = "*/*[local-name()='element'][" + rootPosition + "]/@name";
                TransformerPool tp = TransformerPool.getInstance(XmlUtils.createXPathEvaluatorSource(rootXPath, "text"));
                xsdRoot = tp.transform(Misc.fileToString(xsdFile.getPath()), null);
                if (StringUtils.isNotEmpty(xsdRoot)) {
                    log.debug("found root element [" + xsdRoot + "] in xsd file [" + xsdFile.getName() + "]");
                    esbSoapValidator.setSoapBody(xsdRoot);
                }
            } catch (Exception e) {
                throw new ConfigurationException(e);
            }
        } else {
            esbSoapValidator.setSoapBody(root);
        }
        esbSoapValidator.setForwardFailureToSuccess(true);
        PipeForward pf = new PipeForward();
        pf.setName("success");
        esbSoapValidator.registerForward(pf);
        esbSoapValidator.configure();
        return esbSoapValidator;
    }
    return null;
}
Also used : ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) PipeForward(nl.nn.adapterframework.core.PipeForward) TransformerPool(nl.nn.adapterframework.util.TransformerPool) PipeRunException(nl.nn.adapterframework.core.PipeRunException) IOException(java.io.IOException) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException)

Aggregations

TransformerPool (nl.nn.adapterframework.util.TransformerPool)9 ConfigurationException (nl.nn.adapterframework.configuration.ConfigurationException)7 PipeRunException (nl.nn.adapterframework.core.PipeRunException)4 IOException (java.io.IOException)3 JMSException (javax.jms.JMSException)2 ParameterException (nl.nn.adapterframework.core.ParameterException)2 ParameterResolutionContext (nl.nn.adapterframework.parameters.ParameterResolutionContext)2 QueueInfo (com.tibco.tibjms.admin.QueueInfo)1 TibjmsAdmin (com.tibco.tibjms.admin.TibjmsAdmin)1 TibjmsAdminException (com.tibco.tibjms.admin.TibjmsAdminException)1 URL (java.net.URL)1 DateFormat (java.text.DateFormat)1 DecimalFormat (java.text.DecimalFormat)1 ParseException (java.text.ParseException)1 SimpleDateFormat (java.text.SimpleDateFormat)1 ArrayList (java.util.ArrayList)1 Iterator (java.util.Iterator)1 List (java.util.List)1 Map (java.util.Map)1 StringTokenizer (java.util.StringTokenizer)1