Example usage for org.w3c.dom Element getParentNode

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

Introduction

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

Prototype

public Node getParentNode();

Source Link

Document

The parent of this node.

Usage

From source file:org.wso2.carbon.pc.core.ProcessStore.java

public String deletePredecessor(String deletePredecessor) {
    try {/*from ww  w  .  java 2  s.  c  om*/
        RegistryService registryService = ProcessCenterServerHolder.getInstance().getRegistryService();

        if (registryService != null) {
            UserRegistry reg = registryService.getGovernanceSystemRegistry();

            JSONObject processInfo = new JSONObject(deletePredecessor);
            String processName = processInfo.getString("processName");
            String processVersion = processInfo.getString("processVersion");
            JSONObject predecessor = processInfo.getJSONObject("deletePredecessor");

            String processAssetPath = "processes/" + processName + "/" + processVersion;
            Resource resource = reg.get(processAssetPath);
            String processContent = new String((byte[]) resource.getContent());
            Document doc = stringToXML(processContent);

            if (predecessor != null) {
                NodeList predecessorElements = ((Element) doc.getFirstChild())
                        .getElementsByTagName("predecessor");
                for (int i = 0; i < predecessorElements.getLength(); i++) {
                    Element predecessorElement = (Element) predecessorElements.item(i);
                    String predecessorName = predecessorElement.getElementsByTagName("name").item(0)
                            .getTextContent();
                    String predecessorPath = predecessorElement.getElementsByTagName("path").item(0)
                            .getTextContent();
                    String predecessorId = predecessorElement.getElementsByTagName("id").item(0)
                            .getTextContent();

                    if (predecessorName.equals(predecessor.getString("name"))
                            && predecessorPath.equals(predecessor.getString("path"))
                            && predecessorId.equals(predecessor.getString("id"))) {
                        predecessorElement.getParentNode().removeChild(predecessorElement);
                        break;
                    }
                }
                String newProcessContent = xmlToString(doc);
                resource.setContent(newProcessContent);
                reg.put(processAssetPath, resource);
            }
        }
    } catch (Exception e) {
        log.error(e);
    }
    return "OK";
}

From source file:org.xwiki.officeimporter.internal.filter.ImageFilter.java

/**
 * {@inheritDoc}/*w w w  . j a v  a  2s  .com*/
 */
public void filter(Document htmlDocument, Map<String, String> cleaningParams) {
    String targetDocument = cleaningParams.get("targetDocument");
    DocumentReference targetDocumentReference = null;

    List<Element> images = filterDescendants(htmlDocument.getDocumentElement(), new String[] { TAG_IMG });
    for (Element image : images) {
        if (targetDocumentReference == null && !StringUtils.isBlank(targetDocument)) {
            targetDocumentReference = documentStringReferenceResolver.resolve(targetDocument);
        }
        String src = image.getAttribute(ATTRIBUTE_SRC);
        if (!StringUtils.isBlank(src) && targetDocumentReference != null) {
            // OpenOffice 3.2 server generates relative image paths, extract image name.
            int separator = src.lastIndexOf("/");
            if (-1 != separator) {
                src = src.substring(separator + 1);
            }
            try {
                // We have to decode the image file name in case it contains URL special characters.
                src = URLDecoder.decode(src, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // This should never happen.
            }

            // Set image source attribute relative to the reference document.
            AttachmentReference attachmentReference = new AttachmentReference(src, targetDocumentReference);
            image.setAttribute(ATTRIBUTE_SRC,
                    documentAccessBridge.getAttachmentURL(attachmentReference, false));

            // The 'align' attribute of images creates a lot of problems. First, OO server has a problem with
            // center aligning images (it aligns them to left). Next, OO server uses <br clear"xxx"> for
            // avoiding content wrapping around images which is not valid xhtml. There for, to be consistent and
            // simple we will remove the 'align' attribute of all the images so that they are all left aligned.
            image.removeAttribute(ATTRIBUTE_ALIGN);
        } else if (src.startsWith("file://")) {
            src = "Missing.png";
            image.setAttribute(ATTRIBUTE_SRC, src);
            image.setAttribute(ATTRIBUTE_ALT, src);
        }
        ResourceReference imageReference = new ResourceReference(src, ResourceType.ATTACHMENT);
        imageReference.setTyped(false);
        Comment beforeComment = htmlDocument
                .createComment("startimage:" + this.xhtmlMarkerSerializer.serialize(imageReference));
        Comment afterComment = htmlDocument.createComment("stopimage");
        image.getParentNode().insertBefore(beforeComment, image);
        image.getParentNode().insertBefore(afterComment, image.getNextSibling());
    }
}

From source file:ru.codeinside.gws.crypto.cryptopro.CryptoProvider.java

private static ValidateResult validate(final Element securityToken) throws Exception {
    final X509Security x509 = new X509Security(securityToken);
    final X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509")
            .generateCertificate(new ByteArrayInputStream(x509.getToken()));
    if (cert == null) {
        return new ValidateResult("?  c ?", null);
    }//from w  w  w .j  a v  a2s  .  c  om
    try {
        cert.checkValidity();
    } catch (CertificateException e) {
        return new ValidateResult(" ?  ?", cert);
    }
    final Element signature = first(securityToken.getParentNode(), Constants.SignatureSpecNS, "Signature");
    if (signature == null) {
        return new ValidateResult("?  ? ?", cert);
    }
    final DOMValidateContext ctx = new DOMValidateContext(cert.getPublicKey(), signature);
    fixWsuId(securityToken.getOwnerDocument(), ctx, new HashSet<String>());
    final boolean valid = SIGNATURE_FACTORY.unmarshalXMLSignature(ctx).validate(ctx);
    return new ValidateResult(valid ? null : "?   !", cert);
}

From source file:ru.codeinside.gws.crypto.cryptopro.CryptoProvider.java

@Override
public String signElement(String sourceXML, String elementName, String namespace, boolean removeIdAttribute,
        boolean signatureAfterElement, boolean inclusive) throws Exception {
    loadCertificate();/*from w  w w  .  j  a  v  a2 s.  co m*/
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setCoalescing(true);
    dbf.setNamespaceAware(true);
    DocumentBuilder documentBuilder = dbf.newDocumentBuilder();

    InputSource is = new InputSource(new StringReader(sourceXML));
    Document doc = documentBuilder.parse(is);
    Element elementForSign = (Element) doc.getElementsByTagNameNS(namespace, elementName).item(0);

    Node parentNode = null;
    Element detachedElementForSign;
    Document detachedDocument;
    if (!elementForSign.isSameNode(doc.getDocumentElement())) {
        parentNode = elementForSign.getParentNode();
        parentNode.removeChild(elementForSign);

        detachedDocument = documentBuilder.newDocument();
        Node importedElementForSign = detachedDocument.importNode(elementForSign, true);
        detachedDocument.appendChild(importedElementForSign);
        detachedElementForSign = detachedDocument.getDocumentElement();
    } else {
        detachedElementForSign = elementForSign;
        detachedDocument = doc;
    }

    String signatureMethodUri = inclusive ? "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr34102001-gostr3411"
            : "http://www.w3.org/2001/04/xmldsig-more#gostr34102001-gostr3411";
    String canonicalizationMethodUri = inclusive ? "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
            : "http://www.w3.org/2001/10/xml-exc-c14n#";
    XMLSignature sig = new XMLSignature(detachedDocument, "", signatureMethodUri, canonicalizationMethodUri);
    if (!removeIdAttribute) {
        detachedElementForSign.setAttribute("Id", detachedElementForSign.getTagName());
    }
    if (signatureAfterElement)
        detachedElementForSign.insertBefore(sig.getElement(),
                detachedElementForSign.getLastChild().getNextSibling());
    else {
        detachedElementForSign.insertBefore(sig.getElement(), detachedElementForSign.getFirstChild());
    }
    Transforms transforms = new Transforms(detachedDocument);
    transforms.addTransform("http://www.w3.org/2000/09/xmldsig#enveloped-signature");
    transforms.addTransform(inclusive ? "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"
            : "http://www.w3.org/2001/10/xml-exc-c14n#");

    String digestURI = inclusive ? "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr3411"
            : "http://www.w3.org/2001/04/xmldsig-more#gostr3411";
    sig.addDocument(removeIdAttribute ? "" : "#" + detachedElementForSign.getTagName(), transforms, digestURI);
    sig.addKeyInfo(cert);
    sig.sign(privateKey);

    if ((!elementForSign.isSameNode(doc.getDocumentElement())) && (parentNode != null)) {
        Node signedNode = doc.importNode(detachedElementForSign, true);
        parentNode.appendChild(signedNode);
    }

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer trans = tf.newTransformer();
    trans.setOutputProperty("omit-xml-declaration", "yes");
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    trans.transform(new DOMSource(doc), streamResult);
    return stringWriter.toString();
}

From source file:ru.codeinside.gws3572c.GMPClientSignTest.java

@Test
public void testSignForEntity() throws Exception {
    ClientRequest request = client.createClientRequest(createContext());
    InputSource is = new InputSource(new StringReader(request.appData));
    Document doc = documentBuilder.parse(is);

    Element elementForSign = (Element) doc.getElementsByTagNameNS(null, "Charge").item(0);

    Node parentNode;/*from  ww  w .  ja  va  2 s  .com*/
    Document detachedDocument;
    if (!elementForSign.isSameNode(doc.getDocumentElement())) {
        parentNode = elementForSign.getParentNode();
        parentNode.removeChild(elementForSign);

        detachedDocument = documentBuilder.newDocument();
        Node importedElementForSign = detachedDocument.importNode(elementForSign, true);
        detachedDocument.appendChild(importedElementForSign);
    } else {
        detachedDocument = doc;
    }

    Element nscontext = detachedDocument.createElementNS(null, "namespaceContext");
    nscontext.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + "ds".trim(),
            "http://www.w3.org/2000/09/xmldsig#");

    Element certificateElement = (Element) XPathAPI.selectSingleNode(detachedDocument,
            "//ds:X509Certificate[1]", nscontext);
    Element sigElement = (Element) certificateElement.getParentNode().getParentNode().getParentNode();

    XMLSignature signature = new XMLSignature(sigElement, "");

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate certKey = (X509Certificate) cf.generateCertificate(
            new ByteArrayInputStream(Base64.decode(certificateElement.getTextContent().trim().getBytes())));

    Assert.assertNotNull("There are no information about public key. Verification couldn't be implemented",
            certKey);
    Assert.assertTrue("Signature is not valid", signature.checkSignatureValue(certKey));
}

From source file:ru.runa.wf.web.FormPresentationUtils.java

public static String adjustForm(PageContext pageContext, Long definitionId, String formHtml,
        VariableProvider variableProvider, List<String> requiredVarNames) {
    try {//from   w  ww.  j a v a  2  s.c  o m
        Map<String, String> userErrors = FormSubmissionUtils.getUserInputErrors(pageContext.getRequest());
        Document document = HTMLUtils.readHtml(formHtml.getBytes(Charsets.UTF_8));
        adjustUrls(pageContext, document, definitionId, "form.ftl");
        NodeList htmlTagElements = document.getElementsByTagName("input");
        for (int i = 0; i < htmlTagElements.getLength(); i++) {
            Element node = (Element) htmlTagElements.item(i);
            String typeName = node.getAttribute(TYPE_ATTR);
            String inputName = node.getAttribute(NAME_ATTR);
            if (WebResources.isHighlightRequiredFields() && requiredVarNames.contains(inputName)) {
                Element requiredNode = node;
                if ("file".equalsIgnoreCase(typeName) && WebResources.isAjaxFileInputEnabled()) {
                    requiredNode = (Element) node.getParentNode();
                }
                addRequiredClassAttribute(requiredNode);
            }
            handleErrors(userErrors, inputName, pageContext, document, node);
        }
        NodeList textareaElements = document.getElementsByTagName("textarea");
        for (int i = 0; i < textareaElements.getLength(); i++) {
            Element node = (Element) textareaElements.item(i);
            String inputName = node.getAttribute(NAME_ATTR);
            if (WebResources.isHighlightRequiredFields() && requiredVarNames.contains(inputName)) {
                addRequiredClassAttribute(node);
            }
            handleErrors(userErrors, inputName, pageContext, document, node);
        }
        NodeList selectElements = document.getElementsByTagName("select");
        for (int i = 0; i < selectElements.getLength(); i++) {
            Element node = (Element) selectElements.item(i);
            String inputName = node.getAttribute(NAME_ATTR);
            if (WebResources.isHighlightRequiredFields() && requiredVarNames.contains(inputName)) {
                wrapSelectToErrorContainer(document, node, inputName, true);
            }
            handleErrors(userErrors, inputName, pageContext, document, node);
        }
        if (!userErrors.isEmpty()) {
            Set<String> messages = Sets.newHashSet();
            for (String variableName : userErrors.keySet()) {
                messages.add(variableName + ": " + getErrorText(pageContext, userErrors, variableName));
            }
            log.debug("Not for all errors inputs found, appending errors to the end of the form: " + messages);
            document.getLastChild().appendChild(document.createElement("hr"));
            Element font = document.createElement("font");
            for (String message : messages) {
                font.appendChild(document.createElement("br"));
                font.setAttribute(CSS_CLASS_ATTR, "error");
                Element b = document.createElement("b");
                b.appendChild(document.createTextNode(message));
                font.appendChild(b);
            }
            document.getLastChild().appendChild(font);
        }
        return HTMLUtils.writeHtml(document);
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:ru.runa.wf.web.FormPresentationUtils.java

private static void handleErrors(Map<String, String> errors, String inputName, PageContext pageContext,
        Document document, Element node) {
    if (errors.containsKey(inputName)) {
        String errorText = getErrorText(pageContext, errors, inputName);
        if ("file".equalsIgnoreCase(node.getAttribute(TYPE_ATTR)) && WebResources.isAjaxFileInputEnabled()) {
            try {
                node = (Element) ((Element) ((Element) node.getParentNode()).getParentNode()).getParentNode();
            } catch (Exception e) {
                log.error("Unexpected file input format", e);
            }/*from w w  w . j  a  va  2 s.c o m*/
        }
        if (WebResources.useImagesForValidationErrors()) {
            Element errorImg = document.createElement("img");
            errorImg.setAttribute("title", errorText);
            errorImg.setAttribute("src",
                    Commons.getUrl("/images/error.gif", pageContext, PortletUrlType.Resource));
            Node parent = node.getParentNode();
            parent.insertBefore(errorImg, node.getNextSibling());
        } else {
            node.setAttribute("title", errorText);
            if ("select".equalsIgnoreCase(node.getTagName())) {
                node = wrapSelectToErrorContainer(document, node, inputName, false);
            }
            addClassAttribute(node, Resources.CLASS_INVALID);
        }
        // avoiding multiple error labels
        errors.remove(inputName);
    }
}

From source file:ucar.unidata.idv.ui.ImageGenerator.java

/**
 * process the given node//  w  ww .  j a  v a  2 s .c  o  m
 *
 * @param node Node to process
 *
 * @return keep going
 *
 * @throws Throwable On badness
 */
protected boolean processTagImport(Element node) throws Throwable {
    Element parent = (Element) node.getParentNode();
    String file = applyMacros(node, ATTR_FILE);
    Element root = XmlUtil.findRoot(node);
    Element newRoot = XmlUtil.getRoot(file, getClass());
    newRoot = (Element) root.getOwnerDocument().importNode(newRoot, true);
    parent.insertBefore(newRoot, node);
    parent.removeChild(node);
    if (!processNode(newRoot)) {
        return false;
    }
    return true;
}

From source file:xsul.dsig.globus.security.authentication.SOAPBodyIdResolver.java

public XMLSignatureInput engineResolve(Attr uri, String BaseURI) throws ResourceResolverException {
    String uriNodeValue = uri.getNodeValue();
    NodeList resultNodes = null;/*from   w  w w.  j a va 2s.  c  om*/
    Document doc = uri.getOwnerDocument();

    // this must be done so that Xalan can catch ALL namespaces
    XMLUtils.circumventBug2650(doc);

    CachedXPathAPI cXPathAPI = new CachedXPathAPI();

    /*
     * URI="#chapter1"
     * Identifies a node-set containing the element with ID attribute
     * value 'chapter1' of the XML resource containing the signature.
     * XML Signature (and its applications) modify this node-set to
     * include the element plus all descendents including namespaces and
     * attributes -- but not comments.
     */
    String id = uriNodeValue.substring(1);

    Element selectedElem = WSSecurityUtil.findFirstBodyElement(doc);

    if (selectedElem == null) {
        throw new ResourceResolverException("generic.EmptyMessage", new Object[] { "Body element not found" },
                uri, BaseURI);
    }

    String cId = selectedElem.getAttributeNS(WSConstants.WSU_NS, "Id");

    if ((cId == null) || (cId.length() == 0)) {
        cId = selectedElem.getAttributeNS(WSConstants.SOAP_SEC_NS, "id");
    }

    if (!id.equals(cId)) {
        selectedElem = (Element) selectedElem.getParentNode();
        cId = selectedElem.getAttributeNS(WSConstants.WSU_NS, "Id");

        if ((cId == null) || (cId.length() == 0)) {
            cId = selectedElem.getAttributeNS(WSConstants.SOAP_SEC_NS, "id");
        }

        if (!id.equals(cId)) {
            throw new ResourceResolverException("generic.EmptyMessage", new Object[] { "Id not found" }, uri,
                    BaseURI);
        }
    }

    try {
        resultNodes = cXPathAPI.selectNodeList(selectedElem, Canonicalizer.XPATH_C14N_WITH_COMMENTS_SINGLE_NODE//.XPATH_C14N_OMIT_COMMENTS_SINGLE_NODE
        );
    } catch (javax.xml.transform.TransformerException ex) {
        throw new ResourceResolverException("generic.EmptyMessage", ex, uri, BaseURI);
    }

    Set resultSet = XMLUtils.convertNodelistToSet(resultNodes);
    XMLSignatureInput result = new XMLSignatureInput(resultSet);//, cXPathAPI);

    result.setMIMEType("text/xml");

    try {
        URI uriNew = new URI(new URI(BaseURI), uri.getNodeValue());
        result.setSourceURI(uriNew.toString());
    } catch (URI.MalformedURIException ex) {
        result.setSourceURI(BaseURI);
    }

    return result;
}