Example usage for org.w3c.dom Element getPrefix

List of usage examples for org.w3c.dom Element getPrefix

Introduction

In this page you can find the example usage for org.w3c.dom Element getPrefix.

Prototype

public String getPrefix();

Source Link

Document

The namespace prefix of this node, or null if it is unspecified.

Usage

From source file:com.sitewhere.configuration.ConfigurationMigrationSupport.java

/**
 * Moves event processing elements from previous locations into new element.
 * /* w  ww  .j  a  v  a  2  s  .  c  o m*/
 * @param config
 * @param dcomm
 * @param eproc
 * @param document
 * @throws SiteWhereException
 */
protected static void moveEventProcessingElements(Element config, Element dcomm, Element eproc,
        Document document) throws SiteWhereException {
    Element iproc = DomUtils.getChildElementByTagName(dcomm, "inbound-processing-strategy");
    if (iproc != null) {
        dcomm.removeChild(iproc);
        eproc.appendChild(iproc);
    }
    Element ichain = DomUtils.getChildElementByTagName(config, "inbound-processing-chain");
    if (ichain != null) {
        config.removeChild(ichain);
        eproc.appendChild(ichain);
    }
    Element oproc = DomUtils.getChildElementByTagName(dcomm, "outbound-processing-strategy");
    if (oproc != null) {
        dcomm.removeChild(oproc);
        eproc.appendChild(oproc);
    }
    Element ochain = DomUtils.getChildElementByTagName(config, "outbound-processing-chain");
    if (ochain != null) {
        config.removeChild(ochain);
        eproc.appendChild(ochain);
    }
    Element reg = DomUtils.getChildElementByTagName(dcomm, "registration");
    if (reg != null) {
        String qname = (reg.getPrefix() != null) ? (reg.getPrefix() + ":" + "device-services")
                : "device-services";
        document.renameNode(reg, reg.getNamespaceURI(), qname);
    }
}

From source file:XMLUtils.java

/**
 * Adds an element as a child of a given element. 
 * The child is created with the same namespace as the parent. 
 * @param parent// w  w w.j a v a 2 s .  c o  m
 * @param name
 * @return
 */
public static Element addElement(Element parent, String name) {
    Document doc = parent.getOwnerDocument();
    String qname;
    if (parent.getPrefix() != null) {
        qname = parent.getPrefix() + ":" + name;
    } else {
        qname = name;
    }
    Element child = doc.createElementNS(parent.getNamespaceURI(), qname);
    parent.appendChild(child);
    return child;
}

From source file:microsoft.exchange.webservices.data.core.EwsServiceXmlWriter.java

/**
 * @param element DOM element//from w w w .  j a v  a 2  s. com
 * @param writer XML stream writer
 * @throws XMLStreamException the XML stream exception
 */
public static void addElement(Element element, XMLStreamWriter writer) throws XMLStreamException {
    String nameSpace = element.getNamespaceURI();
    String prefix = element.getPrefix();
    String localName = element.getLocalName();
    if (prefix == null) {
        prefix = "";
    }
    if (localName == null) {
        localName = element.getNodeName();

        if (localName == null) {
            throw new IllegalStateException("Element's local name cannot be null!");
        }
    }

    String decUri = writer.getNamespaceContext().getNamespaceURI(prefix);
    boolean declareNamespace = decUri == null || !decUri.equals(nameSpace);

    if (nameSpace == null || nameSpace.length() == 0) {
        writer.writeStartElement(localName);
    } else {
        writer.writeStartElement(prefix, localName, nameSpace);
    }

    NamedNodeMap attrs = element.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
        Node attr = attrs.item(i);

        String name = attr.getNodeName();
        String attrPrefix = "";
        int prefixIndex = name.indexOf(':');
        if (prefixIndex != -1) {
            attrPrefix = name.substring(0, prefixIndex);
            name = name.substring(prefixIndex + 1);
        }

        if ("xmlns".equals(attrPrefix)) {
            writer.writeNamespace(name, attr.getNodeValue());
            if (name.equals(prefix) && attr.getNodeValue().equals(nameSpace)) {
                declareNamespace = false;
            }
        } else {
            if ("xmlns".equals(name) && "".equals(attrPrefix)) {
                writer.writeNamespace("", attr.getNodeValue());
                if (attr.getNodeValue().equals(nameSpace)) {
                    declareNamespace = false;
                }
            } else {
                writer.writeAttribute(attrPrefix, attr.getNamespaceURI(), name, attr.getNodeValue());
            }
        }
    }

    if (declareNamespace) {
        if (nameSpace == null) {
            writer.writeNamespace(prefix, "");
        } else {
            writer.writeNamespace(prefix, nameSpace);
        }
    }

    NodeList nodes = element.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
        Node n = nodes.item(i);
        writeNode(n, writer);
    }

    writer.writeEndElement();

}

From source file:XMLUtils.java

/**
 * Get the first child element to match a given name. 
 * Look for a child element in the same namespace as the parent.
 * //from  w  w  w. j  a v  a  2 s .  c o m
 * @param parent
 * @param name
 * @return
 */
public static Element getChild(Element parent, String name) {
    Element child = getFirstChild(parent);
    while (child != null) {
        String tagName = child.getTagName();
        if (tagName != null && tagName.equals(name)) {
            return child;
        }
        if (child.getPrefix() != null && child.getPrefix().equals(parent.getPrefix())
                && child.getLocalName() != null && child.getLocalName().equals(name)) {
            return child;
        }
        child = getNext(child);
    }
    return child;
}

From source file:com.msopentech.odatajclient.engine.data.ODataBinder.java

private static ODataPrimitiveValue fromPrimitiveValueElement(final Element prop, final EdmType edmType) {
    final ODataPrimitiveValue value;
    if (edmType != null && edmType.getSimpleType().isGeospatial()) {
        final Element geoProp = ODataConstants.PREFIX_GML.equals(prop.getPrefix()) ? prop
                : (Element) XMLUtils.getChildNodes(prop, Node.ELEMENT_NODE).get(0);
        value = new ODataGeospatialValue.Builder().setType(edmType.getSimpleType()).setTree(geoProp).build();
    } else {//from   w w w. j  ava 2s. c o m
        value = new ODataPrimitiveValue.Builder().setType(edmType == null ? null : edmType.getSimpleType())
                .setText(prop.getTextContent()).build();
    }
    return value;
}

From source file:com.sitewhere.configuration.ConfigurationMigrationSupport.java

/**
 * Perform the migration work.//  w  ww.  ja va2s.  co m
 * 
 * @param document
 * @throws SiteWhereException
 */
protected static void migrateTenantConfiguration(Document document) throws SiteWhereException {
    Element beans = document.getDocumentElement();
    Element config = DomUtils.getChildElementByTagName(beans, "tenant-configuration");
    if (config == null) {
        throw new SiteWhereException("Tenant configuration element not found.");
    }
    Element dcomm = DomUtils.getChildElementByTagName(config, "device-communication");
    if (dcomm == null) {
        throw new SiteWhereException("Device communication element missing.");
    }
    Element asset = DomUtils.getChildElementByTagName(config, "asset-management");
    if (asset == null) {
        throw new SiteWhereException("Asset management element missing.");
    }
    Element eproc = DomUtils.getChildElementByTagName(config, "event-processing");
    if (eproc == null) {
        LOGGER.info("Event processing element missing. Migrating to new configuration format.");
        eproc = document.createElementNS(config.getNamespaceURI(), "event-processing");
        eproc.setPrefix(config.getPrefix());
        config.insertBefore(eproc, asset);

        moveEventProcessingElements(config, dcomm, eproc, document);
    }
    document.normalizeDocument();
}

From source file:be.fedict.eid.applet.service.signer.facets.KeyInfoSignatureFacet.java

public void postSign(Element signatureElement, List<X509Certificate> signingCertificateChain) {
    LOG.debug("postSign");

    String signatureNamespacePrefix = signatureElement.getPrefix();

    /*//from  ww w  .  j av  a2  s  .  c om
     * Make sure we insert right after the ds:SignatureValue element, just
     * before the first ds:Object element.
     */
    Node nextSibling;
    NodeList objectNodeList = signatureElement.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#",
            "Object");
    if (0 == objectNodeList.getLength()) {
        nextSibling = null;
    } else {
        nextSibling = objectNodeList.item(0);
    }

    /*
     * Construct the ds:KeyInfo element using JSR 105.
     */
    KeyInfoFactory keyInfoFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI());
    List<Object> x509DataObjects = new LinkedList<Object>();
    X509Certificate signingCertificate = signingCertificateChain.get(0);

    List<Object> keyInfoContent = new LinkedList<Object>();

    if (this.includeKeyValue) {
        KeyValue keyValue;
        try {
            keyValue = keyInfoFactory.newKeyValue(signingCertificate.getPublicKey());
        } catch (KeyException e) {
            throw new RuntimeException("key exception: " + e.getMessage(), e);
        }
        keyInfoContent.add(keyValue);
    }

    if (this.includeIssuerSerial) {
        x509DataObjects.add(keyInfoFactory.newX509IssuerSerial(
                signingCertificate.getIssuerX500Principal().toString(), signingCertificate.getSerialNumber()));
    }

    if (this.includeEntireCertificateChain) {
        for (X509Certificate certificate : signingCertificateChain) {
            x509DataObjects.add(certificate);
        }
    } else {
        x509DataObjects.add(signingCertificate);
    }

    if (false == x509DataObjects.isEmpty()) {
        X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects);
        keyInfoContent.add(x509Data);
    }
    KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent);
    DOMKeyInfo domKeyInfo = (DOMKeyInfo) keyInfo;

    Key key = new Key() {
        private static final long serialVersionUID = 1L;

        public String getAlgorithm() {
            return null;
        }

        public byte[] getEncoded() {
            return null;
        }

        public String getFormat() {
            return null;
        }
    };

    XMLSignContext xmlSignContext = new DOMSignContext(key, signatureElement);
    DOMCryptoContext domCryptoContext = (DOMCryptoContext) xmlSignContext;
    try {
        domKeyInfo.marshal(signatureElement, nextSibling, signatureNamespacePrefix, domCryptoContext);
    } catch (MarshalException e) {
        throw new RuntimeException("marshall error: " + e.getMessage(), e);
    }
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

public static boolean isPrefixUsed(Element targetElement, String prefix) {
    if (comparePrefix(prefix, targetElement.getPrefix())) {
        return true;
    }//  w  w  w .  ja v a  2s.c  o  m
    NamedNodeMap attributes = targetElement.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Attr attr = (Attr) attributes.item(i);
        if (comparePrefix(prefix, attr.getPrefix())) {
            return true;
        }
    }
    NodeList childNodes = targetElement.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node node = childNodes.item(i);
        if (node instanceof Element) {
            Element element = (Element) node;
            if (isPrefixUsed(element, prefix)) {
                return true;
            }
        }
    }
    return false;
}

From source file:com.netflix.ice.login.saml.Saml.java

public LoginResponse processLogin(HttpServletRequest request) throws LoginMethodException {
    IceSession iceSession = new IceSession(request.getSession());
    iceSession.voidSession(); //a second login request voids anything previous
    logger.info("Saml::processLogin");
    LoginResponse lr = new LoginResponse();
    String assertion = (String) request.getParameter("SAMLResponse");
    if (assertion == null) {
        lr.redirectTo = config.singleSignOnUrl;
        return lr;
    }/*from w w w. ja v a2s .c om*/
    logger.trace("Received SAML Assertion: " + assertion);
    try {
        // 1.1 2.0 schemas
        Schema schema = SAMLSchemaBuilder.getSAML11Schema();

        //get parser pool manager
        BasicParserPool parserPoolManager = new BasicParserPool();
        parserPoolManager.setNamespaceAware(true);
        parserPoolManager.setIgnoreElementContentWhitespace(true);
        parserPoolManager.setSchema(schema);

        String data = new String(Base64.decode(assertion));
        logger.info("Decoded SAML Assertion: " + data);

        StringReader reader = new StringReader(data);
        Document document = parserPoolManager.parse(reader);
        Element documentRoot = document.getDocumentElement();

        QName qName = new QName(documentRoot.getNamespaceURI(), documentRoot.getLocalName(),
                documentRoot.getPrefix());

        //get an unmarshaller
        Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(documentRoot);

        //unmarshall using the document root element
        XMLObject xmlObj = unmarshaller.unmarshall(documentRoot);
        Response response = (Response) xmlObj;
        for (Assertion myAssertion : response.getAssertions()) {
            if (!myAssertion.isSigned()) {
                logger.error("SAML Assertion not signed");
                throw new LoginMethodException("SAML Assertions must be signed by a trusted provider");
            }

            Signature assertionSignature = myAssertion.getSignature();
            SAMLSignatureProfileValidator profVal = new SAMLSignatureProfileValidator();

            logger.info("Validating SAML Assertion");
            // will throw a ValidationException 
            profVal.validate(assertionSignature);

            //Credential signCred = assertionSignature.getSigningCredential();
            boolean goodSignature = false;
            for (Certificate trustedCert : trustedSigningCerts) {
                BasicCredential cred = new BasicCredential();
                cred.setPublicKey(trustedCert.getPublicKey());
                SignatureValidator validator = new SignatureValidator(cred);
                try {
                    validator.validate(assertionSignature);
                } catch (ValidationException ve) {
                    /* Not a good key! */
                    logger.debug("Not signed by " + trustedCert.toString());
                    continue;
                }
                logger.info("Assertion trusted from " + trustedCert.toString());
                processAssertion(iceSession, myAssertion, lr);
                goodSignature = true;
                break;
            }

            if (goodSignature) {
                lr.loginSuccess = true;
            }

        }
    } catch (org.xml.sax.SAXException saxe) {
        logger.error(saxe.toString());
    } catch (org.opensaml.xml.parse.XMLParserException xmlpe) {
        logger.error(xmlpe.toString());
    } catch (org.opensaml.xml.io.UnmarshallingException uee) {
        logger.error(uee.toString());
    } catch (org.opensaml.xml.validation.ValidationException ve) {
        throw new LoginMethodException("SAML Assertion Signature was not usable: " + ve.toString());
    }
    return lr;
}

From source file:com.vmware.demo.SamlService.java

public String validateSAMLResponse(String samlResponse, String samlCert) throws Exception {
    String decodedString = "";
    try {/*w  w w. ja  v  a  2s . co m*/
        decodedString = decodeSAMLResponse(samlResponse);
        InputStream inputStream = new ByteArrayInputStream(decodedString.getBytes("UTF-8"));

        // Parse XML
        BasicParserPool parserPoolManager = new BasicParserPool();
        parserPoolManager.setNamespaceAware(true);
        parserPoolManager.setIgnoreElementContentWhitespace(true);
        Document document = parserPoolManager.parse(inputStream);
        Element metadataRoot = document.getDocumentElement();

        QName qName = new QName(metadataRoot.getNamespaceURI(), metadataRoot.getLocalName(),
                metadataRoot.getPrefix());

        // Unmarshall document
        Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(qName);
        Response response = (Response) unmarshaller.unmarshall(metadataRoot);
        Issuer issuer = response.getIssuer();
        logger.info("Parsed response.  Issued:" + response.getIssueInstant().toString() + ", issuer: "
                + issuer.getValue());

        java.security.cert.X509Certificate jX509Cert = SamlUtils.parsePemCertificate(samlCert);
        if (null == jX509Cert) {
            logger.info("Failed to parse cert. " + samlCert);
            return "";
        }

        PublicKey publicCert = jX509Cert.getPublicKey();
        logger.info("Extracted cert.  Cert:" + publicCert);
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicCert.getEncoded());

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
        logger.debug("Key created by provider: " + keyFactory.getProvider().toString());

        // Setup validation
        BasicX509Credential publicCredential = new BasicX509Credential();
        publicCredential.setPublicKey(publicKey);
        SignatureValidator signatureValidator = new SignatureValidator(publicCredential);
        Signature signature = response.getSignature();

        // Validate
        try {
            signatureValidator.validate(signature);
            logger.info("Assertion signature validated.");
        } catch (ValidationException e) {
            logger.error("Failed to validate signature of assertion", e);
            throw e;
        }

        // Get decryption key
        RSAPrivateKey privateKey = null;
        BasicX509Credential decryptionCredential = new BasicX509Credential();
        decryptionCredential.setPrivateKey(privateKey);
        StaticKeyInfoCredentialResolver skicr = new StaticKeyInfoCredentialResolver(decryptionCredential);

        // Decrypt assertion
        Decrypter decrypter = new Decrypter(null, skicr, new InlineEncryptedKeyResolver());
        if (response.getEncryptedAssertions().isEmpty()) {
            logger.info("Nothing to decrypt in assertion.");
        } else {
            Assertion decryptedAssertion;
            try {
                decryptedAssertion = decrypter.decrypt(response.getEncryptedAssertions().get(0));
                logger.info("Assertion decryption succeeded.");
            } catch (DecryptionException e) {
                logger.error("Failed to decrypt assertion", e);
                throw e;
            }

            // Extract attributes, log in output
            List<AttributeStatement> attributeStatements = decryptedAssertion.getAttributeStatements();
            for (int i = 0; i < attributeStatements.size(); i++) {
                List<Attribute> attributes = attributeStatements.get(i).getAttributes();
                for (int x = 0; x < attributes.size(); x++) {
                    String strAttributeName = attributes.get(x).getDOM().getAttribute("Name");

                    List<XMLObject> attributeValues = attributes.get(x).getAttributeValues();
                    for (int y = 0; y < attributeValues.size(); y++) {
                        String strAttributeValue = attributeValues.get(y).getDOM().getTextContent();
                        logger.info(strAttributeName + " = " + strAttributeValue);
                    }
                }
            }
        }
    } catch (Exception ex) {
        logger.error("Failed to validate assertion", ex);
        throw ex;
    }
    return decodedString;
}