Example usage for org.w3c.dom Document createElement

List of usage examples for org.w3c.dom Document createElement

Introduction

In this page you can find the example usage for org.w3c.dom Document createElement.

Prototype

public Element createElement(String tagName) throws DOMException;

Source Link

Document

Creates an element of the type specified.

Usage

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

public static Element createNamespaceElement(Node documentNode) {
    Document document = documentNode.getOwnerDocument();
    Element nsElement = document.createElement("nsElement");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS);
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:xades", XADES_NAMESPACE);
    return nsElement;
}

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

private static Element newEntryContent() {
    Element properties = null;/*from  www  .  j a va2 s  . c om*/
    try {
        final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder();
        final Document doc = builder.newDocument();
        properties = doc.createElement(ODataConstants.ELEM_PROPERTIES);
        properties.setAttribute(ODataConstants.XMLNS_METADATA, ODataConstants.NS_METADATA);
        properties.setAttribute(ODataConstants.XMLNS_DATASERVICES, ODataConstants.NS_DATASERVICES);
        properties.setAttribute(ODataConstants.XMLNS_GML, ODataConstants.NS_GML);
        properties.setAttribute(ODataConstants.XMLNS_GEORSS, ODataConstants.NS_GEORSS);
    } catch (ParserConfigurationException e) {
        LOG.error("Failure building entry content", e);
    }

    return properties;
}

From source file:it.intecs.pisa.toolbox.util.URLReader.java

public static void getContent(String url, Document urlTree, Element fatherNode) throws Exception {
    Element directoryNode = urlTree.createElement("directory");
    directoryNode.setAttribute("name", url);
    fatherNode.appendChild(directoryNode);
    try {// w  ww.  j a va  2 s .  c o m
        String[] filesToDw = URLReader.getFileToDW("/" + SCHEMA + url);
        int index = 0;
        while (index < filesToDw.length) {
            Element fileNode = urlTree.createElement("file");
            fileNode.setAttribute("name", filesToDw[index]);
            directoryNode.appendChild(fileNode);
            index++;
        }

        String[] directoryToDw = URLReader.getDirectoryToDW("/" + SCHEMA + url);
        index = 0;
        while (index < directoryToDw.length) {
            getContent(directoryToDw[index], urlTree, directoryNode);
            index++;
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
    }
}

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

private static Element toComplexPropertyElement(final String name, final ODataComplexValue value,
        final Document doc, final boolean setType) {

    final Element element = doc.createElement(ODataConstants.PREFIX_DATASERVICES + name);
    if (value.getTypeName() != null && setType) {
        element.setAttribute(ODataConstants.ATTR_M_TYPE, value.getTypeName());
    }//from   ww  w . j  a  va2  s  .  c om

    for (ODataProperty field : value) {
        element.appendChild(toDOMElement(field, doc, true));
    }
    return element;
}

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

private static Element toPrimitivePropertyElement(final String name, final ODataPrimitiveValue value,
        final Document doc, final boolean setType) {

    final Element element = doc.createElement(ODataConstants.PREFIX_DATASERVICES + name);
    if (setType) {
        element.setAttribute(ODataConstants.ATTR_M_TYPE, value.getTypeName());
    }//from   ww w  .  j  a v a2 s.c  om

    if (value instanceof ODataGeospatialValue) {
        element.appendChild(doc.importNode(((ODataGeospatialValue) value).toTree(), true));
    } else {
        element.setTextContent(value.toString());
    }

    return element;
}

From source file:com.eucalyptus.imaging.manifest.DownloadManifestFactory.java

/**
 * Generates download manifest based on bundle manifest and puts in into
 * system owned bucket/*from  w  ww.j a  v a  2 s .c o m*/
 * 
 * @param baseManifest
 *          the base manifest
 * @param keyToUse
 *          public key that used for encryption
 * @param manifestName
 *          name for generated manifest file
 * @param expirationHours
 *          expiration policy in hours for pre-signed URLs
 * @param urlForNc
 *          indicates if urs are constructed for NC use
 * @return pre-signed URL that can be used to download generated manifest
 * @throws DownloadManifestException
 */
public static String generateDownloadManifest(final ImageManifestFile baseManifest, final PublicKey keyToUse,
        final String manifestName, int expirationHours, boolean urlForNc) throws DownloadManifestException {
    EucaS3Client s3Client = null;
    try {
        try {
            s3Client = s3ClientsPool.borrowObject();
        } catch (Exception ex) {
            throw new DownloadManifestException("Can't borrow s3Client from the pool");
        }
        // prepare to do pre-signed urls
        if (!urlForNc)
            s3Client.refreshEndpoint(true);
        else
            s3Client.refreshEndpoint();

        Date expiration = new Date();
        long msec = expiration.getTime() + 1000 * 60 * 60 * expirationHours;
        expiration.setTime(msec);

        // check if download-manifest already exists
        if (objectExist(s3Client, DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName)) {
            LOG.debug("Manifest '" + (DOWNLOAD_MANIFEST_PREFIX + manifestName)
                    + "' is already created and has not expired. Skipping creation");
            URL s = s3Client.generatePresignedUrl(DOWNLOAD_MANIFEST_BUCKET_NAME,
                    DOWNLOAD_MANIFEST_PREFIX + manifestName, expiration, HttpMethod.GET);
            return String.format("%s://imaging@%s%s?%s", s.getProtocol(), s.getAuthority(), s.getPath(),
                    s.getQuery());
        } else {
            LOG.debug("Manifest '" + (DOWNLOAD_MANIFEST_PREFIX + manifestName) + "' does not exist");
        }

        UrlValidator urlValidator = new UrlValidator();

        final String manifest = baseManifest.getManifest();
        if (manifest == null) {
            throw new DownloadManifestException("Can't generate download manifest from null base manifest");
        }
        final Document inputSource;
        final XPath xpath;
        Function<String, String> xpathHelper;
        DocumentBuilder builder = XMLParser.getDocBuilder();
        inputSource = builder.parse(new ByteArrayInputStream(manifest.getBytes()));
        if (!"manifest".equals(inputSource.getDocumentElement().getNodeName())) {
            LOG.error("Expected image manifest. Got " + nodeToString(inputSource, false));
            throw new InvalidBaseManifestException("Base manifest does not have manifest element");
        }

        StringBuilder signatureSrc = new StringBuilder();
        Document manifestDoc = builder.newDocument();
        Element root = (Element) manifestDoc.createElement("manifest");
        manifestDoc.appendChild(root);
        Element el = manifestDoc.createElement("version");
        el.appendChild(manifestDoc.createTextNode("2014-01-14"));
        signatureSrc.append(nodeToString(el, false));
        root.appendChild(el);
        el = manifestDoc.createElement("file-format");
        el.appendChild(manifestDoc.createTextNode(baseManifest.getManifestType().getFileType().toString()));
        root.appendChild(el);
        signatureSrc.append(nodeToString(el, false));

        xpath = XPathFactory.newInstance().newXPath();
        xpathHelper = new Function<String, String>() {
            @Override
            public String apply(String input) {
                try {
                    return (String) xpath.evaluate(input, inputSource, XPathConstants.STRING);
                } catch (XPathExpressionException ex) {
                    return null;
                }
            }
        };

        // extract keys
        // TODO: move this?
        if (baseManifest.getManifestType().getFileType() == FileType.BUNDLE) {
            String encryptedKey = xpathHelper.apply("/manifest/image/ec2_encrypted_key");
            String encryptedIV = xpathHelper.apply("/manifest/image/ec2_encrypted_iv");
            String size = xpathHelper.apply("/manifest/image/size");
            EncryptedKey encryptKey = reEncryptKey(new EncryptedKey(encryptedKey, encryptedIV), keyToUse);
            el = manifestDoc.createElement("bundle");
            Element key = manifestDoc.createElement("encrypted-key");
            key.appendChild(manifestDoc.createTextNode(encryptKey.getKey()));
            Element iv = manifestDoc.createElement("encrypted-iv");
            iv.appendChild(manifestDoc.createTextNode(encryptKey.getIV()));
            el.appendChild(key);
            el.appendChild(iv);
            Element sizeEl = manifestDoc.createElement("unbundled-size");
            sizeEl.appendChild(manifestDoc.createTextNode(size));
            el.appendChild(sizeEl);
            root.appendChild(el);
            signatureSrc.append(nodeToString(el, false));
        }

        el = manifestDoc.createElement("image");
        String bundleSize = xpathHelper.apply(baseManifest.getManifestType().getSizePath());
        if (bundleSize == null) {
            throw new InvalidBaseManifestException("Base manifest does not have size element");
        }
        Element size = manifestDoc.createElement("size");
        size.appendChild(manifestDoc.createTextNode(bundleSize));
        el.appendChild(size);

        Element partsEl = manifestDoc.createElement("parts");
        el.appendChild(partsEl);
        // parts
        NodeList parts = (NodeList) xpath.evaluate(baseManifest.getManifestType().getPartsPath(), inputSource,
                XPathConstants.NODESET);
        if (parts == null) {
            throw new InvalidBaseManifestException("Base manifest does not have parts");
        }

        for (int i = 0; i < parts.getLength(); i++) {
            Node part = parts.item(i);
            String partIndex = part.getAttributes().getNamedItem("index").getNodeValue();
            String partKey = ((Node) xpath.evaluate(baseManifest.getManifestType().getPartUrlElement(), part,
                    XPathConstants.NODE)).getTextContent();
            String partDownloadUrl = partKey;
            if (baseManifest.getManifestType().signPartUrl()) {
                GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(
                        baseManifest.getBaseBucket(), partKey, HttpMethod.GET);
                generatePresignedUrlRequest.setExpiration(expiration);
                URL s = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
                partDownloadUrl = s.toString();
            } else {
                // validate url per EUCA-9144
                if (!urlValidator.isEucalyptusUrl(partDownloadUrl))
                    throw new DownloadManifestException(
                            "Some parts in the manifest are not stored in the OS. Its location is outside Eucalyptus:"
                                    + partDownloadUrl);
            }
            Node digestNode = null;
            if (baseManifest.getManifestType().getDigestElement() != null)
                digestNode = ((Node) xpath.evaluate(baseManifest.getManifestType().getDigestElement(), part,
                        XPathConstants.NODE));
            Element aPart = manifestDoc.createElement("part");
            Element getUrl = manifestDoc.createElement("get-url");
            getUrl.appendChild(manifestDoc.createTextNode(partDownloadUrl));
            aPart.setAttribute("index", partIndex);
            aPart.appendChild(getUrl);
            if (digestNode != null) {
                NamedNodeMap nm = digestNode.getAttributes();
                if (nm == null)
                    throw new DownloadManifestException(
                            "Some parts in manifest don't have digest's verification algorithm");
                Element digest = manifestDoc.createElement("digest");
                digest.setAttribute("algorithm", nm.getNamedItem("algorithm").getTextContent());
                digest.appendChild(manifestDoc.createTextNode(digestNode.getTextContent()));
                aPart.appendChild(digest);
            }
            partsEl.appendChild(aPart);
        }
        root.appendChild(el);
        signatureSrc.append(nodeToString(el, false));
        String signatureData = signatureSrc.toString();
        Element signature = manifestDoc.createElement("signature");
        signature.setAttribute("algorithm", "RSA-SHA256");
        signature.appendChild(manifestDoc
                .createTextNode(Signatures.SHA256withRSA.trySign(Eucalyptus.class, signatureData.getBytes())));
        root.appendChild(signature);
        String downloadManifest = nodeToString(manifestDoc, true);
        // TODO: move this ?
        createManifestsBucketIfNeeded(s3Client);
        putManifestData(s3Client, DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName,
                downloadManifest, expiration);
        // generate pre-sign url for download manifest
        URL s = s3Client.generatePresignedUrl(DOWNLOAD_MANIFEST_BUCKET_NAME,
                DOWNLOAD_MANIFEST_PREFIX + manifestName, expiration, HttpMethod.GET);
        return String.format("%s://imaging@%s%s?%s", s.getProtocol(), s.getAuthority(), s.getPath(),
                s.getQuery());
    } catch (Exception ex) {
        LOG.error("Got an error", ex);
        throw new DownloadManifestException("Can't generate download manifest");
    } finally {
        if (s3Client != null)
            try {
                s3ClientsPool.returnObject(s3Client);
            } catch (Exception e) {
                // sad, but let's not break instances run
                LOG.warn("Could not return s3Client to the pool");
            }
    }
}

From source file:ConfigFiles.java

public static void addTag(String tagname, String tagcontent, Element root, boolean blank, Document document) {
    Element rootElement = document.createElement(tagname);
    root.appendChild(rootElement);//from  w  w  w.  ja  v  a 2  s .com
    String temp;
    if (blank)
        temp = "";
    else
        temp = tagcontent;
    rootElement.appendChild(document.createTextNode(temp));
}

From source file:DOMEdit.java

private static void makeNamelist(Document doc) {
        String names = null;//from  w  w w.ja v  a  2s . c om
        Element root = doc.getDocumentElement();
        NodeList nameElements = root.getElementsByTagName("name");
        for (int i = 0; i < nameElements.getLength(); i++) {
            Element name = (Element) nameElements.item(i);
            Text nametext = (Text) name.getFirstChild();
            if (names == null) {
                names = nametext.getData();
            } else {
                names += ", " + nametext.getData();
            }
        }
        Element namelist = doc.createElement("names");
        Text namelisttext = doc.createTextNode(names);
        namelist.appendChild(namelisttext);
        root.insertBefore(namelist, root.getFirstChild());
    }

From source file:Main.java

private static Node copyNodeExceptNamespace(Document document, Node srcNode, Set<String> namespace,
        List<String> exceptNamespaces) {

    if (srcNode.getNodeType() == Node.ELEMENT_NODE) {

        String nodeName = srcNode.getNodeName();
        nodeName = nodeName.substring(nodeName.indexOf(":") + 1);
        Element element = document.createElement(nodeName);

        for (int i = 0; i < srcNode.getAttributes().getLength(); i++) {
            Attr attr = (Attr) srcNode.getAttributes().item(i);
            String name = attr.getName();
            if (name.startsWith("xmlns:")) {
                String suffix = name.substring(6);
                if (!exceptNamespaces.contains(suffix)) {
                    namespace.add(suffix);
                }/*w  ww.j av  a  2 s  .  co m*/
                continue;
            }
        }

        for (int i = 0; i < srcNode.getAttributes().getLength(); i++) {
            Attr attr = (Attr) srcNode.getAttributes().item(i);
            String name = attr.getName();
            if (name.startsWith("xmlns:")) {
                continue;
            }
            int semi = name.indexOf(":");
            if (semi > 0) {
                if (namespace.contains(name.substring(0, semi))) {
                    name = name.substring(semi + 1);
                }
            }
            element.setAttribute(name, attr.getValue());
        }

        NodeList nodeList = srcNode.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node childNode = nodeList.item(i);
            if (childNode.getNodeType() == Node.TEXT_NODE) {
                element.appendChild(document.createTextNode(childNode.getTextContent()));
            } else if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                Node node = copyNodeExceptNamespace(document, childNode, namespace, exceptNamespaces);
                element.appendChild(node);
            }
        }

        return element;
    }

    if (srcNode.getNodeType() == Node.TEXT_NODE) {
        Text text = document.createTextNode(srcNode.getTextContent());
        return text;
    }

    return null;
}

From source file:Main.java

public static Element getElement(Document document, String[] path, String value, String translate,
        String module) {//  w ww.j a v a 2s.  com
    Node node = document;
    NodeList list;
    for (int i = 0; i < path.length; ++i) {
        list = node.getChildNodes();
        boolean found = false;
        for (int j = 0; j < list.getLength(); ++j) {
            Node testNode = list.item(j);
            if (testNode.getNodeName().equals(path[i])) {
                found = true;
                node = testNode;
                break;
            }
        }
        if (found == false) {
            Element element = document.createElement(path[i]);
            node.appendChild(element);
            node = element;
        }
    }
    if (value != null) {
        Text text = document.createTextNode(value);
        list = node.getChildNodes();
        boolean found = false;
        for (int j = 0; j < list.getLength(); ++j) {
            Node testNode = list.item(j);
            if (testNode instanceof Text) {
                node.replaceChild(text, testNode);
                found = true;
                break;
            }
        }
        if (!found)
            node.appendChild(text);
    }
    if (node instanceof Element) {
        Element element = (Element) node;
        if (translate != null && element.getAttribute("translate").equals("")) {
            element.setAttribute("translate", translate);
        }
        if (module != null && element.getAttribute("module").equals("")) {
            element.setAttribute("module", module);
        }
    }
    return (Element) node;
}