Example usage for org.w3c.dom Node toString

List of usage examples for org.w3c.dom Node toString

Introduction

In this page you can find the example usage for org.w3c.dom Node toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.apache.ws.security.processor.SignatureProcessor.java

/**
 * Verify the WS-Security signature.//from  w ww.  j  av  a2  s . com
 * 
 * The functions at first checks if then <code>KeyInfo</code> that is
 * contained in the signature contains standard X509 data. If yes then
 * get the certificate data via the standard <code>KeyInfo</code> methods.
 * 
 * Otherwise, if the <code>KeyInfo</code> info does not contain X509 data, check
 * if we can find a <code>wsse:SecurityTokenReference</code> element. If yes, the next
 * step is to check how to get the certificate. Two methods are currently supported
 * here:
 * <ul>
 * <li> A URI reference to a binary security token contained in the <code>wsse:Security
 * </code> header.  If the dereferenced token is
 * of the correct type the contained certificate is extracted.
 * </li>
 * <li> Issuer name an serial number of the certificate. In this case the method
 * looks up the certificate in the keystore via the <code>crypto</code> parameter.
 * </li>
 * </ul>
 * 
 * The methods checks is the certificate is valid and calls the
 * {@link org.apache.xml.security.signature.XMLSignature#checkSignatureValue(X509Certificate) 
 * verification} function.
 *
 * @param elem        the XMLSignature DOM Element.
 * @param crypto      the object that implements the access to the keystore and the
 *                    handling of certificates.
 * @param returnCert  verifyXMLSignature stores the certificate in the first
 *                    entry of this array. The caller may then further validate
 *                    the certificate
 * @param returnElements verifyXMLSignature adds the wsu:ID attribute values for
 *               the signed elements to this Set
 * @param cb CallbackHandler instance to extract key passwords
 * @return the subject principal of the validated X509 certificate (the
 *         authenticated subject). The calling function may use this
 *         principal for further authentication or authorization.
 * @throws WSSecurityException
 */
protected Principal verifyXMLSignature(Element elem, Crypto crypto, X509Certificate[] returnCert,
        Set returnElements, List protectedElements, byte[][] signatureValue, CallbackHandler cb,
        WSDocInfo wsDocInfo) throws WSSecurityException {
    if (log.isDebugEnabled()) {
        log.debug("Verify XML Signature");
    }
    long t0 = 0, t1 = 0, t2 = 0;
    if (tlog.isDebugEnabled()) {
        t0 = System.currentTimeMillis();
    }

    XMLSignature sig = null;
    try {
        sig = new XMLSignature(elem, null);
    } catch (XMLSecurityException e2) {
        throw new WSSecurityException(WSSecurityException.FAILED_CHECK, "noXMLSig", null, e2);
    }

    sig.addResourceResolver(EnvelopeIdResolver.getInstance());

    KeyInfo info = sig.getKeyInfo();
    UsernameToken ut = null;
    DerivedKeyToken dkt = null;
    SAMLKeyInfo samlKi = null;
    SAML2KeyInfo saml2Ki = null;
    String customTokenId = null;
    java.security.PublicKey publicKey = null;
    X509Certificate[] certs = null;
    boolean validateCertificateChain = false;
    boolean kerbThumbPrint = false;
    X509Certificate cert = null;

    try {
        cert = info.getX509Certificate();
    } catch (KeyResolverException ignore) {
        if (log.isDebugEnabled()) {
            log.debug(ignore);
        }
    }

    if (info != null && info.containsKeyValue()) {
        try {
            publicKey = info.getPublicKey();
        } catch (Exception ex) {
            throw new WSSecurityException(ex.getMessage(), ex);
        }
    } else if (info != null && cert != null) {
        certs = new X509Certificate[] { cert };
    } else if (info != null) {
        Node node = WSSecurityUtil.getDirectChild(info.getElement(),
                SecurityTokenReference.SECURITY_TOKEN_REFERENCE, WSConstants.WSSE_NS);
        if (node == null) {
            throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "unsupportedKeyInfo");
        }
        SecurityTokenReference secRef = new SecurityTokenReference((Element) node);
        //
        // Here we get some information about the document that is being
        // processed, in particular the crypto implementation, and already
        // detected BST that may be used later during dereferencing.
        //
        if (secRef.containsReference()) {
            org.apache.ws.security.message.token.Reference ref = secRef.getReference();
            Element krbToken = secRef.getTokenElement(elem.getOwnerDocument(), wsDocInfo, cb);

            if (krbToken.getAttribute("ValueType").equals(
                    "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1#GSS_Kerberosv5_AP_REQ")) {

                KerberosTokenProcessor krbp = new KerberosTokenProcessor(this.returnResults);
                return krbp.verifyXMLSignature(elem, crypto, returnCert, returnElements, protectedElements,
                        signatureValue, cb);
            }

            String uri = ref.getURI();
            if (uri.charAt(0) == '#') {
                uri = uri.substring(1);
            }
            Processor processor = wsDocInfo.getProcessor(uri);
            if (processor == null) {
                Element token = secRef.getTokenElement(elem.getOwnerDocument(), wsDocInfo, cb);
                //
                // at this point check token type: Binary, SAML, EncryptedKey, Custom
                //
                QName el = new QName(token.getNamespaceURI(), token.getLocalName());
                if (el.equals(WSSecurityEngine.binaryToken)) {
                    certs = getCertificatesTokenReference(token, crypto);
                    if (certs != null && certs.length > 1) {
                        validateCertificateChain = true;
                    }
                } else if (el.equals(WSSecurityEngine.SAML_TOKEN)) {
                    samlKi = SAMLUtil.getSAMLKeyInfo(token, crypto, cb);
                    certs = samlKi.getCerts();
                    secretKey = samlKi.getSecret();
                } else if (el.equals(WSSecurityEngine.SAML2_TOKEN)) {
                    saml2Ki = SAML2Util.getSAML2KeyInfo(token, crypto, cb);
                    certs = saml2Ki.getCerts();
                    secretKey = saml2Ki.getSecret();

                } else if (el.equals(WSSecurityEngine.ENCRYPTED_KEY)) {
                    if (crypto == null) {
                        throw new WSSecurityException(WSSecurityException.FAILURE, "noSigCryptoFile");
                    }
                    EncryptedKeyProcessor encryptKeyProcessor = new EncryptedKeyProcessor();
                    encryptKeyProcessor.handleEncryptedKey(token, cb, crypto);
                    secretKey = encryptKeyProcessor.getDecryptedBytes();
                } else {
                    // Try custom token through callback handler
                    // try to find a custom token
                    String id = secRef.getReference().getURI();
                    if (id.charAt(0) == '#') {
                        id = id.substring(1);
                    }
                    WSPasswordCallback pwcb = new WSPasswordCallback(id, WSPasswordCallback.CUSTOM_TOKEN);
                    try {
                        Callback[] callbacks = new Callback[] { pwcb };
                        cb.handle(callbacks);
                    } catch (Exception e) {
                        throw new WSSecurityException(WSSecurityException.FAILURE, "noPassword",
                                new Object[] { id }, e);
                    }

                    secretKey = pwcb.getKey();
                    customTokenId = id;
                    if (secretKey == null) {
                        throw new WSSecurityException(WSSecurityException.INVALID_SECURITY,
                                "unsupportedKeyInfo", new Object[] { el.toString() });
                    }
                }
            } else if (processor instanceof UsernameTokenProcessor) {
                ut = ((UsernameTokenProcessor) processor).getUt();
                if (ut.isDerivedKey()) {
                    secretKey = ut.getDerivedKey();
                } else {
                    secretKey = ut.getSecretKey(secretKeyLength);
                }
            } else if (processor instanceof BinarySecurityTokenProcessor) {
                certs = ((BinarySecurityTokenProcessor) processor).getCertificates();
                if (certs != null && certs.length > 1) {
                    validateCertificateChain = true;
                }
            } else if (processor instanceof EncryptedKeyProcessor) {
                EncryptedKeyProcessor ekProcessor = (EncryptedKeyProcessor) processor;
                secretKey = ekProcessor.getDecryptedBytes();
                customTokenId = ekProcessor.getId();
            } else if (processor instanceof SecurityContextTokenProcessor) {
                SecurityContextTokenProcessor sctProcessor = (SecurityContextTokenProcessor) processor;
                secretKey = sctProcessor.getSecret();
                customTokenId = sctProcessor.getIdentifier();
            } else if (processor instanceof DerivedKeyTokenProcessor) {
                DerivedKeyTokenProcessor dktProcessor = (DerivedKeyTokenProcessor) processor;
                String signatureMethodURI = sig.getSignedInfo().getSignatureMethodURI();
                dkt = dktProcessor.getDerivedKeyToken();
                int keyLength = (dkt.getLength() > 0) ? dkt.getLength()
                        : WSSecurityUtil.getKeyLength(signatureMethodURI);

                secretKey = dktProcessor.getKeyBytes(keyLength);
            } else if (processor instanceof SAMLTokenProcessor) {
                if (crypto == null) {
                    throw new WSSecurityException(WSSecurityException.FAILURE, "noSigCryptoFile");
                }
                SAMLTokenProcessor samlp = (SAMLTokenProcessor) processor;
                samlKi = SAMLUtil.getSAMLKeyInfo(samlp.getSamlTokenElement(), crypto, cb);
                certs = samlKi.getCerts();
                secretKey = samlKi.getSecret();
                publicKey = samlKi.getPublicKey();
            } else if (processor instanceof SAML2TokenProcessor) {
                if (crypto == null)
                    throw new WSSecurityException(0, "noSigCryptoFile");
                SAML2TokenProcessor samlp = (SAML2TokenProcessor) processor;
                saml2Ki = SAML2Util.getSAML2KeyInfo(samlp.getSamlTokenElement(), crypto, cb);
                certs = saml2Ki.getCerts();
                secretKey = saml2Ki.getSecret();
            }
        } else if (secRef.containsX509Data() || secRef.containsX509IssuerSerial()) {
            certs = secRef.getX509IssuerSerial(crypto);
        } else if (secRef.containsKeyIdentifier()) {
            if (secRef.getKeyIdentifierValueType().equals(SecurityTokenReference.ENC_KEY_SHA1_URI)) {
                String id = secRef.getKeyIdentifierValue();
                WSPasswordCallback pwcb = new WSPasswordCallback(id, null,
                        SecurityTokenReference.ENC_KEY_SHA1_URI, WSPasswordCallback.ENCRYPTED_KEY_TOKEN);
                try {
                    Callback[] callbacks = new Callback[] { pwcb };
                    cb.handle(callbacks);
                } catch (Exception e) {
                    throw new WSSecurityException(WSSecurityException.FAILURE, "noPassword",
                            new Object[] { id }, e);
                }
                secretKey = pwcb.getKey();
            } else if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())) {
                Element token = secRef.getKeyIdentifierTokenElement(elem.getOwnerDocument(), wsDocInfo, cb);

                samlKi = SAMLUtil.getSAMLKeyInfo(token, crypto, cb);
                certs = samlKi.getCerts();
                secretKey = samlKi.getSecret();
                publicKey = samlKi.getPublicKey();
            } else if (WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())) {
                Element token = secRef.getKeyIdentifierTokenElement(elem.getOwnerDocument(), wsDocInfo, cb);
                saml2Ki = SAML2Util.getSAML2KeyInfo(token, crypto, cb);
                certs = saml2Ki.getCerts();
                secretKey = saml2Ki.getSecret();
            } else {
                certs = secRef.getKeyIdentifier(crypto);
                if (certs == null && secRef.containsKerberosThumbprint()) {
                    secretKey = secRef.getKerberosSession().getSessionKey().getEncoded();
                    kerbThumbPrint = true;
                }
            }
        } else {
            throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "unsupportedKeyInfo",
                    new Object[] { node.toString() });
        }
    } else {
        if (crypto == null) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "noSigCryptoFile");
        }
        if (crypto.getDefaultX509Alias() != null) {
            certs = crypto.getCertificates(crypto.getDefaultX509Alias());
        } else {
            throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "unsupportedKeyInfo");
        }
    }
    if (tlog.isDebugEnabled()) {
        t1 = System.currentTimeMillis();
    }
    if ((certs == null || certs.length == 0 || certs[0] == null) && secretKey == null && publicKey == null
            && !kerbThumbPrint) {
        throw new WSSecurityException(WSSecurityException.FAILED_CHECK);
    }
    if (certs != null) {
        try {
            for (int i = 0; i < certs.length; i++) {
                certs[i].checkValidity();
            }
        } catch (CertificateExpiredException e) {
            throw new WSSecurityException(WSSecurityException.FAILED_CHECK, "invalidCert", null, e);
        } catch (CertificateNotYetValidException e) {
            throw new WSSecurityException(WSSecurityException.FAILED_CHECK, "invalidCert", null, e);
        }
    }
    //
    // Delegate verification of a public key to a Callback Handler
    //
    if (publicKey != null) {
        PublicKeyCallback pwcb = new PublicKeyCallback(publicKey);
        try {
            Callback[] callbacks = new Callback[] { pwcb };
            cb.handle(callbacks);
            if (!pwcb.isVerified()) {
                throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION, null, null, null);
            }
        } catch (Exception e) {
            throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION, null, null, e);
        }
    }
    try {
        boolean signatureOk = false;
        if (certs != null) {
            signatureOk = sig.checkSignatureValue(certs[0]);
        } else if (publicKey != null) {
            signatureOk = sig.checkSignatureValue(publicKey);
        } else {
            signatureOk = sig.checkSignatureValue(sig.createSecretKey(secretKey));
        }
        if (signatureOk) {
            if (tlog.isDebugEnabled()) {
                t2 = System.currentTimeMillis();
                tlog.debug("Verify: total= " + (t2 - t0) + ", prepare-cert= " + (t1 - t0) + ", verify= "
                        + (t2 - t1));
            }
            signatureValue[0] = sig.getSignatureValue();
            //
            // Now dig into the Signature element to get the elements that
            // this Signature covers. Build the QName of these Elements and
            // return them to caller
            //
            SignedInfo si = sig.getSignedInfo();
            int numReferences = si.getLength();
            for (int i = 0; i < numReferences; i++) {
                Reference siRef;
                try {
                    siRef = si.item(i);
                } catch (XMLSecurityException e3) {
                    throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e3);
                }
                String uri = siRef.getURI();
                if (uri != null && !"".equals(uri)) {

                    Element se = null;
                    try {
                        Transforms transforms = siRef.getTransforms();
                        for (int j = 0; j < transforms.getLength(); j++) {
                            Transform transform = transforms.item(j);
                            // We have some transforming to do before we can 
                            // determine the protected element.
                            if (STRTransform.implementedTransformURI.equals(transform.getURI())) {

                                XMLSignatureInput signatureInput = siRef.getContentsBeforeTransformation();

                                if (signatureInput.isElement()) {
                                    // The signature was already validated,
                                    // meaning that this element was already
                                    // parsed.  We can therefore be pretty
                                    // confident that this constructor will work.
                                    SecurityTokenReference secTokenRef = new SecurityTokenReference(
                                            (Element) signatureInput.getSubNode());

                                    // Use the utility to extract the element (or
                                    // generate a new one in some cases) from the
                                    // message.
                                    se = STRTransformUtil.dereferenceSTR(transform.getDocument(), secTokenRef,
                                            wsDocInfo);
                                } else {
                                    // The internal impl of Reference changed.
                                    // We expect it to return the signature input
                                    // based on a node/element.
                                    throw new WSSecurityException(WSSecurityException.FAILURE);
                                }
                            }
                        }
                    } catch (XMLSecurityException e) {
                        log.warn("Error processing signature coverage elements.", e);
                        throw new WSSecurityException(WSSecurityException.FAILURE);
                    }

                    if (se == null) {
                        se = WSSecurityUtil.getElementByWsuId(elem.getOwnerDocument(), uri);
                    }
                    if (se == null) {
                        se = WSSecurityUtil.getElementByGenId(elem.getOwnerDocument(), uri);
                    }
                    if (se == null) {
                        throw new WSSecurityException(WSSecurityException.FAILED_CHECK);
                    }
                    WSDataRef ref = new WSDataRef(uri);
                    ref.setWsuId(uri);
                    ref.setName(new QName(se.getNamespaceURI(), se.getLocalName()));
                    ref.setProtectedElement(se);
                    ref.setXpath(ReferenceListProcessor.getXPath(se));
                    ref.setAlgorithm(si.getSignatureMethodURI());
                    ref.setDigestAlgorithm(siRef.getMessageDigestAlgorithm().getAlgorithmURI());
                    protectedElements.add(ref);
                    returnElements.add(WSSecurityUtil.getIDFromReference(uri));
                } else {
                    // This is the case where the signed element is identified 
                    // by a transform such as XPath filtering
                    // We add the complete reference element to the return 
                    // elements
                    returnElements.add(siRef);
                }
            }

            // Algorithms used for signature and c14n
            signatureMethod = si.getSignatureMethodURI();
            c14nMethod = si.getCanonicalizationMethodURI();

            if (certs != null) {
                returnCert[0] = certs[0];
                if (validateCertificateChain) {
                    certificates = certs;
                }
                return certs[0].getSubjectX500Principal();
            } else if (publicKey != null) {
                return new PublicKeyPrincipal(publicKey);
            } else if (ut != null) {
                WSUsernameTokenPrincipal principal = new WSUsernameTokenPrincipal(ut.getName(), ut.isHashed());
                principal.setNonce(ut.getNonce());
                principal.setPassword(ut.getPassword());
                principal.setCreatedTime(ut.getCreated());
                return principal;
            } else if (dkt != null) {
                WSDerivedKeyTokenPrincipal principal = new WSDerivedKeyTokenPrincipal(dkt.getID());
                principal.setNonce(dkt.getNonce());
                principal.setLabel(dkt.getLabel());
                principal.setLength(dkt.getLength());
                principal.setOffset(dkt.getOffset());
                String basetokenId = null;
                SecurityTokenReference securityTokenReference = dkt.getSecurityTokenReference();
                if (securityTokenReference.containsReference()) {
                    basetokenId = securityTokenReference.getReference().getURI();
                    if (basetokenId.charAt(0) == '#') {
                        basetokenId = basetokenId.substring(1);
                    }
                } else {
                    // KeyIdentifier
                    basetokenId = securityTokenReference.getKeyIdentifierValue();
                }
                principal.setBasetokenId(basetokenId);
                return principal;
            } else if (samlKi != null) {
                final SAMLAssertion assertion = samlKi.getAssertion();
                CustomTokenPrincipal principal = new CustomTokenPrincipal(assertion.getId());
                principal.setTokenObject(assertion);
                return principal;

            } else if (saml2Ki != null) {
                Assertion assertion = saml2Ki.getAssertion();
                CustomTokenPrincipal principal = new CustomTokenPrincipal(assertion.getID());
                principal.setTokenObject(assertion);
                return principal;
            } else if (secretKey != null) {
                // This is the custom key scenario
                CustomTokenPrincipal principal = new CustomTokenPrincipal(customTokenId);
                return principal;
            } else {
                throw new WSSecurityException("Cannot determine principal");
            }
        } else {
            throw new WSSecurityException(WSSecurityException.FAILED_CHECK);
        }
    } catch (XMLSignatureException e1) {
        throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e1);
    }
}

From source file:org.exist.dom.ElementImpl.java

/**
 * Method toString./*ww  w  .  j  av a  2 s.c  o  m*/
 *
 */
public String toString(boolean top, TreeSet<String> namespaces) {
    final StringBuilder buf = new StringBuilder();
    final StringBuilder attributes = new StringBuilder();
    final StringBuilder children = new StringBuilder();
    buf.append('<');
    buf.append(nodeName);
    //Remove false to have a verbose output
    //if (top && false) {
    //buf.append(" xmlns:exist=\""+ Namespaces.EXIST_NS + "\"");
    //buf.append(" exist:id=\"");
    //buf.append(getNodeId());
    //buf.append("\" exist:document=\"");
    //buf.append(((DocumentImpl)getOwnerDocument()).getFileURI());
    //buf.append("\"");
    //}
    if (declaresNamespacePrefixes()) {
        // declare namespaces used by this element
        Map.Entry<String, String> entry;
        String namespace, prefix;
        for (final Iterator<Map.Entry<String, String>> i = namespaceMappings.entrySet().iterator(); i
                .hasNext();) {
            entry = i.next();
            prefix = entry.getKey();
            namespace = entry.getValue();
            if (prefix.length() == 0) {
                buf.append(" xmlns=\"");
                //buf.append(namespace);
                buf.append("...");
            } else {
                buf.append(" xmlns:");
                buf.append(prefix);
                buf.append("=\"");
                //buf.append(namespace);
                buf.append("...");
            }
            buf.append("\" ");
            namespaces.add(namespace);
        }
    }
    if (nodeName.getNamespaceURI().length() > 0 && (!namespaces.contains(nodeName.getNamespaceURI()))) {
        buf.append(" xmlns:").append(nodeName.getPrefix()).append("=\"");
        buf.append(nodeName.getNamespaceURI());
        buf.append("\" ");
    }
    final NodeList childNodes = getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        final Node child = childNodes.item(i);
        switch (child.getNodeType()) {
        case Node.ATTRIBUTE_NODE:
            attributes.append(' ');
            attributes.append(((Attr) child).getName());
            attributes.append("=\"");
            attributes.append(escapeXml(child));
            attributes.append("\"");
            break;
        case Node.ELEMENT_NODE:
            children.append(((ElementImpl) child).toString(false, namespaces));
            break;
        default:
            children.append(child.toString());
        }
    }
    if (attributes.length() > 0) {
        buf.append(attributes.toString());
    }
    if (childNodes.getLength() > 0) {
        buf.append(">");
        buf.append(children.toString());
        buf.append("</");
        buf.append(nodeName);
        buf.append(">");
    } else {
        buf.append("/>");
    }
    return buf.toString();
}

From source file:org.pentaho.di.trans.steps.xmlinput.XMLInput.java

private Object[] getRowFromXML() throws KettleValueException {
    // finished reading the file, read the next file

    while (data.itemPosition >= data.itemCount || data.file == null) {
        data.file = null;/*ww  w  .ja  v a  2s .  co m*/
        if (!openNextFile()) {
            return null;
        }
    }

    Object[] outputRowData = buildEmptyRow();

    // Get the item in the XML file...

    // First get the appropriate node

    Node itemNode;
    if (meta.getInputPosition().length > 1) {
        itemNode = XMLHandler.getSubNodeByNr(data.section, data.itemElement, data.itemPosition);
    } else {
        itemNode = data.section; // Only the root node, 1 element to read
        // in the whole document.
    }
    data.itemPosition++;

    // Read from the Node...
    for (int i = 0; i < meta.getInputFields().length; i++) {
        Node node = itemNode;

        XMLInputField xmlInputField = meta.getInputFields()[i];

        // This value will contain the value we're looking for...
        //
        String value = null;

        for (int p = 0; (value == null) && node != null && p < xmlInputField.getFieldPosition().length; p++) {
            XMLInputFieldPosition pos = xmlInputField.getFieldPosition()[p];

            switch (pos.getType()) {
            case XMLInputFieldPosition.XML_ELEMENT: {
                if (pos.getElementNr() <= 1) {
                    Node subNode = XMLHandler.getSubNode(node, pos.getName());
                    if (subNode != null) {
                        if (p == xmlInputField.getFieldPosition().length - 1) // last
                        // level
                        {
                            value = XMLHandler.getNodeValue(subNode);
                        }
                    } else {
                        if (log.isDebug())
                            logDebug(BaseMessages.getString(PKG, "XMLInput.Log.UnableToFindPosition",
                                    pos.toString(), node.toString()));
                    }
                    node = subNode;
                } else
                // Multiple possible values: get number
                // pos.getElementNr()!
                {
                    Node subNode = XMLHandler.getSubNodeByNr(node, pos.getName(), pos.getElementNr() - 1,
                            false);
                    if (subNode != null) {
                        if (p == xmlInputField.getFieldPosition().length - 1) // last
                        // level
                        {
                            value = XMLHandler.getNodeValue(subNode);
                        }
                    } else {
                        if (log.isDebug())
                            logDebug(BaseMessages.getString(PKG, "XMLInput.Log.UnableToFindPosition",
                                    pos.toString(), node.toString()));
                    }
                    node = subNode;
                }
            }
                break;

            case XMLInputFieldPosition.XML_ATTRIBUTE: {
                value = XMLHandler.getTagAttribute(node, pos.getName());
            }
                break;
            case XMLInputFieldPosition.XML_ROOT: {
                value = XMLHandler.getNodeValue(node);
            }
                break;
            default:
                break;
            }

        }

        // OK, we have grabbed the string called value
        // Trim it, convert it, ...

        // DO Trimming!
        switch (xmlInputField.getTrimType()) {
        case XMLInputField.TYPE_TRIM_LEFT:
            value = Const.ltrim(value);
            break;
        case XMLInputField.TYPE_TRIM_RIGHT:
            value = Const.rtrim(value);
            break;
        case XMLInputField.TYPE_TRIM_BOTH:
            value = Const.trim(value);
            break;
        default:
            break;
        }

        // System.out.println("after trim, field #"+i+" : "+v);

        // DO CONVERSIONS...
        //
        ValueMetaInterface targetValueMeta = data.outputRowMeta.getValueMeta(i);
        ValueMetaInterface sourceValueMeta = data.convertRowMeta.getValueMeta(i);
        outputRowData[i] = targetValueMeta.convertData(sourceValueMeta, value);

        // Do we need to repeat this field if it is null?
        if (meta.getInputFields()[i].isRepeated()) {
            if (data.previousRow != null && Const.isEmpty(value)) {
                outputRowData[i] = data.previousRow[i];
            }
        }
    } // End of loop over fields...

    int outputIndex = meta.getInputFields().length;

    // See if we need to add the filename to the row...
    if (meta.includeFilename() && !Const.isEmpty(meta.getFilenameField())) {
        outputRowData[outputIndex++] = KettleVFS.getFilename(data.file);
    }

    // See if we need to add the row number to the row...
    if (meta.includeRowNumber() && !Const.isEmpty(meta.getRowNumberField())) {
        outputRowData[outputIndex++] = new Long(data.rownr);
    }

    RowMetaInterface irow = getInputRowMeta();

    data.previousRow = irow == null ? outputRowData : (Object[]) irow.cloneRow(outputRowData); // copy it to make
    // surely the next step doesn't change it in between...
    data.rownr++;

    // Throw away the information in the item?
    NodeList nodeList = itemNode.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        itemNode.removeChild(nodeList.item(i));
    }

    return outputRowData;
}

From source file:org.pentaho.reporting.engine.classic.extensions.datasources.xpath.XPathTableModel.java

public XPathTableModel(final ResourceData xmlResource, final ResourceManager resourceManager,
        final String xPathExpression, final DataRow parameters, final int maxRowsToProcess)
        throws ReportDataFactoryException {
    try {//  ww  w. ja  v  a2s . c o m
        columnTypes = new ArrayList<Class>();

        final XPath xPath = XPathFactory.newInstance().newXPath();
        xPath.setXPathVariableResolver(new InternalXPathVariableResolver(parameters));

        // load metadata (number of rows, row names, row types)

        final String nodeValue = computeColDeclaration(xmlResource, resourceManager, xPath);
        if (nodeValue != null) {
            final StringTokenizer stringTokenizer = new StringTokenizer(nodeValue, ",");
            while (stringTokenizer.hasMoreTokens()) {
                final String className = stringTokenizer.nextToken();
                if (SUPPORTED_TYPES.containsKey(className)) {
                    columnTypes.add(SUPPORTED_TYPES.get(className));
                } else {
                    columnTypes.add(String.class);
                }
            }
        }

        if (maxRowsToProcess == -1) {
            dataLimit = Integer.MAX_VALUE;
        } else {
            this.dataLimit = Math.min(1, maxRowsToProcess);
        }

        backend = new TypedTableModel();
        final LinkedHashMap<String, String> results = new LinkedHashMap<String, String>();
        // try to find all valid column names
        // visit all entries and add the names as we find them
        final NodeList rows = evaluateNodeList(xPath, xPathExpression, xmlResource, resourceManager);
        for (int r = 0; r < rows.getLength(); r++) {
            // Get the next value from the result sequence
            final Node rowValue = rows.item(r);

            final short nodeType = rowValue.getNodeType();
            // Print this value
            if (nodeType == Node.ELEMENT_NODE) {
                // explodes into columns ..
                if (processNode(rowValue, results, backend) == false) {
                    return;
                }
            } else {
                final String columnName = rowValue.getNodeValue();
                results.put(columnName, rowValue.toString());
                if (addRow(results, backend) == false) {
                    return;
                }
                results.clear();
            }
            //     System.out.println("NodeType: " + nodeType + "\n" + value.toString());
        }
    } catch (Exception e) {
        throw new ReportDataFactoryException("Failed to query XPath datasource", e);
    }
}

From source file:org.wso2.carbon.identity.core.util.IdentityUtil.java

/**
 * Serialize the given node to a String.
 *
 * @param node Node to be serialized./*w w  w.  j  av a  2s  .c om*/
 * @return The serialized node as a java.lang.String instance.
 */
public static String nodeToString(Node node) {

    if (importerDoc == null) {
        OMDOMFactory fac = new OMDOMFactory();
        importerDoc = (Document) fac.createOMDocument();
    }
    // Import the node as an AXIOM-DOOM node and use toSting()
    Node axiomNode = importerDoc.importNode(node, true);
    return axiomNode.toString();
}

From source file:org.wso2.carbon.identity.sts.GenericTokenIssuer.java

/**
 * Create the <code>wst:RequstedSecurityTokenRespoonse</code> element.
 * /*from  w w  w.  j  a  va  2  s.c o m*/
 * @param data WS-Trust information in the issue request
 * @param notBefore Created time
 * @param notAfter Expiration time
 * @param env Response SOAP envelope
 * @param doc <code>org.w3.dom.Document</code> instance of the response SOAP envelope
 * @param assertion SAML Assertion to be sent in the response.
 * @param encryptedKey Key used to encrypt the SAML assertion.
 * @return <code>wst:RequstedSecurityTokenRespoonse</code> element.
 * @throws TrustException
 * @throws SAMLException
 */
protected OMElement createRSTR(RahasData data, Date notBefore, Date notAfter, SOAPEnvelope env, Document doc,
        Node assertionElem, String assertionId, WSSecEncryptedKey encryptedKey)
        throws TrustException, SAMLException, IdentityProviderException {
    if (log.isDebugEnabled()) {
        log.debug("Begin RSTR Element creation.");
    }

    int wstVersion;
    MessageContext inMsgCtx = null;
    OMElement rstrElem = null;
    OMElement appliesToEpr = null;

    wstVersion = data.getVersion();
    inMsgCtx = data.getInMessageContext();

    rstrElem = TrustUtil.createRequestSecurityTokenResponseElement(wstVersion, env.getBody());
    TrustUtil.createTokenTypeElement(wstVersion, rstrElem).setText(data.getTokenType());

    createDisplayToken(rstrElem, ipData);

    if (encryptedKey != null) {
        OMElement incomingAppliesToEpr = null;
        OMElement appliesToElem = null;
        int keysize = data.getKeysize();
        if (keysize == -1) {
            keysize = encryptedKey.getEphemeralKey().length * 8;
        }

        TrustUtil.createKeySizeElement(wstVersion, rstrElem, keysize);
        incomingAppliesToEpr = data.getAppliesToEpr();
        try {
            Document eprDoc = null;
            eprDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(new ByteArrayInputStream(incomingAppliesToEpr.toString().getBytes()));
            appliesToEpr = (OMElement) doc.importNode(eprDoc.getDocumentElement(), true);
        } catch (Exception e) {
            throw new TrustException(TrustException.REQUEST_FAILED, e);
        }

        appliesToElem = rstrElem.getOMFactory()
                .createOMElement(new QName(RahasConstants.WSP_NS,
                        RahasConstants.IssuanceBindingLocalNames.APPLIES_TO, RahasConstants.WSP_PREFIX),
                        rstrElem);
        appliesToElem.addChild(appliesToEpr);
    }

    DateFormat zulu = null;
    OMElement reqSecTokenElem = null;
    Node assertionElement = null;
    Token assertionToken = null;

    // Use GMT time in milliseconds
    zulu = new XmlSchemaDateFormat();

    // Add the Lifetime element
    TrustUtil.createLifetimeElement(wstVersion, rstrElem, zulu.format(notBefore), zulu.format(notAfter));

    reqSecTokenElem = TrustUtil.createRequestedSecurityTokenElement(wstVersion, rstrElem);
    assertionElement = doc.importNode(assertionElem, true);
    reqSecTokenElem.addChild((OMNode) assertionElement);

    if (log.isDebugEnabled()) {
        log.debug(assertionElement.toString());
    }

    if (encryptedKey != null) {
        encryptSAMLAssertion(doc, (Element) assertionElement, encryptedKey);
    }

    createAttachedRef(rstrElem, assertionId);
    createUnattachedRef(rstrElem, assertionId);

    // Store the Token
    assertionToken = new Token(assertionId, (OMElement) doc.importNode(assertionElem, true), notBefore,
            notAfter);

    // At this point we definitely have the secret
    // Otherwise it should fail with an exception earlier
    assertionToken.setSecret(data.getEphmeralKey());
    TrustUtil.getTokenStore(inMsgCtx).add(assertionToken);

    // Creating the ReqProoftoken - END
    if (log.isDebugEnabled()) {
        log.debug("RSTR Elem created.");
    }

    return rstrElem;
}