Example usage for org.w3c.dom Element appendChild

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

Introduction

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

Prototype

public Node appendChild(Node newChild) throws DOMException;

Source Link

Document

Adds the node newChild to the end of the list of children of this node.

Usage

From source file:com.microsoft.tfs.util.xml.DOMUtils.java

/**
 * Adds a new {@link Text} node to a {@link Document} tree as a child of the
 * specified parent {@link Element}.//from  w w w  .ja  v  a 2s  . com
 *
 * @param parent
 *        the parent {@link Element} (must not be <code>null</code>)
 * @param data
 *        the contents to give the new {@link Text} node
 * @return the new {@link Text} node (never <code>null</code>)
 */
public static Text appendText(final Element parent, final String data) {
    Check.notNull(parent, "parent"); //$NON-NLS-1$

    final Text newChild = parent.getOwnerDocument().createTextNode(data);
    parent.appendChild(newChild);
    return newChild;
}

From source file:com.osafe.services.SiteMapServices.java

private static void createSiteMapNode(String URL) {
    StringBuilder urlBuilder = new StringBuilder();

    try {/*from ww w.  j  a v  a 2 s  . c  o  m*/
        List<String> pathElements = StringUtil.split(URL, "/");
        String sUrlTarget = pathElements.get(pathElements.size() - 1);
        String friendlyKey = StringUtil.replaceString(sUrlTarget, "&", "~");
        friendlyKey = StringUtil.replaceString(friendlyKey, "=", "^^");
        String friendlyUrl = null;

        if (OSAFE_FRIENDLY_URL.containsKey(friendlyKey)) {
            friendlyUrl = (String) OSAFE_FRIENDLY_URL.get(friendlyKey);

        }
        if (UtilValidate.isNotEmpty(friendlyUrl)) {
            int idxControl = URL.indexOf("control/");
            if (idxControl > -1) {
                urlBuilder.append(URL.substring(0, idxControl));
                urlBuilder.append(CATALOG_URL_MOUNT_POINT + "/");
            }
            urlBuilder.append(friendlyUrl.toLowerCase());
        } else {
            urlBuilder.append(URL);

        }

        Element newElement = document.createElement("url");
        Element newChildElement = document.createElement("loc");
        newChildElement.appendChild(document.createTextNode(urlBuilder.toString()));
        newElement.appendChild(newChildElement);
        rootElement.appendChild(newElement);

    } catch (Exception e) {

    }

}

From source file:com.icesoft.faces.renderkit.dom_html_basic.FormRenderer.java

/**
 * @param uiComponent//from w w w  . j a va2 s. c o  m
 * @param facesContext
 * @param map
 */
private static void renderRequiredCommandLinkHiddenFields(UIComponent uiComponent, FacesContext facesContext,
        Map map) {
    DOMContext domContext = DOMContext.getDOMContext(facesContext, uiComponent);
    Element root = (Element) domContext.getRootNode();
    Element hiddenFieldsDiv = domContext.createElement(HTML.DIV_ELEM);
    hiddenFieldsDiv.setAttribute(HTML.ID_ATTR, uiComponent.getClientId(facesContext) + "hdnFldsDiv");
    hiddenFieldsDiv.setAttribute(HTML.STYLE_ATTR, "display:none;");
    root.appendChild(hiddenFieldsDiv);

    Iterator commandLinkFields = map.entrySet().iterator();
    while (commandLinkFields.hasNext()) {
        Map.Entry nextField = (Map.Entry) commandLinkFields.next();
        if (COMMAND_LINK_HIDDEN_FIELD.equals(nextField.getValue())) {
            Element next = domContext.createElement("input");
            next.setAttribute("type", "hidden");
            next.setAttribute("name", nextField.getKey().toString());
            hiddenFieldsDiv.appendChild(next);
        }
    }
}

From source file:com.microsoft.tfs.util.xml.DOMUtils.java

/**
 * Adds a new {@link Element} node to a {@link Document} tree as a child of
 * the specified parent {@link Element}.
 *
 * @param parent//  www .j av a 2 s.com
 *        the parent {@link Element} (must not be <code>null</code>)
 * @param tagName
 *        the name to give the new child {@link Element} (must not be
 *        <code>null</code>)
 * @return the new child {@link Element} (never <code>null</code>)
 */
public static Element appendChild(final Element parent, final String tagName) {
    Check.notNull(parent, "parent"); //$NON-NLS-1$

    final Element newChild = parent.getOwnerDocument().createElement(tagName);
    parent.appendChild(newChild);
    return newChild;
}

From source file:com.microsoft.tfs.util.xml.DOMUtils.java

/**
 * Adds a new {@link CDATASection} node to a {@link Document} tree as a
 * child of the specified parent {@link Element}.
 *
 * @param parent//w  w  w  .  jav a 2 s  .  c  om
 *        the parent {@link Element} (must not be <code>null</code>)
 * @param data
 *        the contents to give the new {@link CDATASection} node
 * @return the new {@link CDATASection} node (never <code>null</code>)
 */
public static CDATASection appendCDATA(final Element parent, final String data) {
    Check.notNull(parent, "parent"); //$NON-NLS-1$

    final CDATASection newChild = parent.getOwnerDocument().createCDATASection(data);
    parent.appendChild(newChild);
    return newChild;
}

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

/**
 * Generates download manifest based on bundle manifest and puts in into
 * system owned bucket//www.  j av  a2s  .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:edu.cudenver.bios.matrixsvc.representation.CholeskyDecompositionXmlRepresentation.java

static Element createXml(CholeskyDecompositionImpl _cdImpl, Document _doc) {
    NamedRealMatrix L = new NamedRealMatrix(_cdImpl.getL());
    NamedRealMatrix LT = new NamedRealMatrix(_cdImpl.getLT());
    L.setName(MatrixConstants.SQ_ROOT_MATRIX_RETURN_NAME);
    LT.setName(MatrixConstants.TRANSPOSE_MATRIX_RETURN_NAME);
    Element rootElem = _doc.createElement(MatrixConstants.TAG_CHOLESKY_DECOMP);

    //Get XML for first matrix
    logger.debug("Calling MatrixXmlRepresentation.createMatrixNodeFromRealMatrix() " + "for L matrix.");
    Node matrixL = MatrixXmlRepresentation.createMatrixNodeFromRealMatrix(L, _doc);

    //Get XML for second matrix
    logger.debug("Calling MatrixXmlRepresentation.createMatrixNodeFromRealMatrix() " + "for LT matrix.");
    Node matrixLT = MatrixXmlRepresentation.createMatrixNodeFromRealMatrix(LT, _doc);

    //Add our matrices to our root element
    rootElem.appendChild(matrixL);
    rootElem.appendChild(matrixLT);/*ww w.j a  v a2s  . co m*/

    return rootElem;
}

From source file:com.msopentech.odatajclient.engine.data.json.GeospatialJSONHandler.java

private static void appendPoses(final Element parent, final Document document, final Iterator<JsonNode> itor) {
    while (itor.hasNext()) {
        final Iterator<JsonNode> lineItor = itor.next().elements();
        final Element pos = document.createElementNS(ODataConstants.NS_GML, ODataConstants.ELEM_POS);
        parent.appendChild(pos);
        pos.appendChild(document.createTextNode(lineItor.next().asText() + " " + lineItor.next().asText()));
    }//from ww  w .j  ava 2 s . co m
}

From source file:com.msopentech.odatajclient.engine.data.json.GeospatialJSONHandler.java

public static void serialize(final JsonGenerator jgen, final Element node, final String type)
        throws IOException {
    final EdmSimpleType edmSimpleType = EdmSimpleType.fromValue(type);

    if (edmSimpleType.equals(EdmSimpleType.GeographyCollection)
            || edmSimpleType.equals(EdmSimpleType.GeometryCollection)) {

        jgen.writeStringField(ODataConstants.ATTR_TYPE, EdmSimpleType.GeometryCollection.name());
    } else {//from w  ww.  j ava2 s . c om
        final int yIdx = edmSimpleType.name().indexOf('y');
        final String itemType = edmSimpleType.name().substring(yIdx + 1);
        jgen.writeStringField(ODataConstants.ATTR_TYPE, itemType);
    }

    Element root = null;
    switch (edmSimpleType) {
    case GeographyPoint:
    case GeometryPoint:
        root = XMLUtils.getChildElements(node, ODataConstants.ELEM_POINT).get(0);

        jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES);
        serializePoint(jgen, XMLUtils.getChildElements(root, ODataConstants.ELEM_POS).get(0));
        jgen.writeEndArray();
        break;

    case GeographyMultiPoint:
    case GeometryMultiPoint:
        root = XMLUtils.getChildElements(node, ODataConstants.ELEM_MULTIPOINT).get(0);

        jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES);

        final List<Element> pMembs = XMLUtils.getChildElements(root, ODataConstants.ELEM_POINTMEMBERS);
        if (pMembs != null && !pMembs.isEmpty()) {
            for (Element point : XMLUtils.getChildElements(pMembs.get(0), ODataConstants.ELEM_POINT)) {
                jgen.writeStartArray();
                serializePoint(jgen, XMLUtils.getChildElements(point, ODataConstants.ELEM_POS).get(0));
                jgen.writeEndArray();
            }
        }

        jgen.writeEndArray();
        break;

    case GeographyLineString:
    case GeometryLineString:
        root = XMLUtils.getChildElements(node, ODataConstants.ELEM_LINESTRING).get(0);

        jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES);
        serializeLineString(jgen, root);
        jgen.writeEndArray();
        break;

    case GeographyMultiLineString:
    case GeometryMultiLineString:
        root = XMLUtils.getChildElements(node, ODataConstants.ELEM_MULTILINESTRING).get(0);

        jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES);

        final List<Element> lMembs = XMLUtils.getChildElements(root, ODataConstants.ELEM_LINESTRINGMEMBERS);
        if (lMembs != null && !lMembs.isEmpty()) {
            for (Element lineStr : XMLUtils.getChildElements(lMembs.get(0), ODataConstants.ELEM_LINESTRING)) {
                jgen.writeStartArray();
                serializeLineString(jgen, lineStr);
                jgen.writeEndArray();
            }
        }

        jgen.writeEndArray();
        break;

    case GeographyPolygon:
    case GeometryPolygon:
        root = XMLUtils.getChildElements(node, ODataConstants.ELEM_POLYGON).get(0);

        jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES);
        serializePolygon(jgen, root);
        jgen.writeEndArray();
        break;

    case GeographyMultiPolygon:
    case GeometryMultiPolygon:
        root = XMLUtils.getChildElements(node, ODataConstants.ELEM_MULTIPOLYGON).get(0);

        jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES);

        final List<Element> mpMembs = XMLUtils.getChildElements(root, ODataConstants.ELEM_SURFACEMEMBERS);
        if (mpMembs != null & !mpMembs.isEmpty()) {
            for (Element pol : XMLUtils.getChildElements(mpMembs.get(0), ODataConstants.ELEM_POLYGON)) {
                jgen.writeStartArray();
                serializePolygon(jgen, pol);
                jgen.writeEndArray();
            }
        }

        jgen.writeEndArray();
        break;

    case GeographyCollection:
    case GeometryCollection:
        root = XMLUtils.getChildElements(node, ODataConstants.ELEM_GEOCOLLECTION).get(0);

        final List<Element> cMembs = XMLUtils.getChildElements(root, ODataConstants.ELEM_GEOMEMBERS);
        if (cMembs != null && !cMembs.isEmpty()) {
            jgen.writeArrayFieldStart(ODataConstants.JSON_GEOMETRIES);

            for (Node geom : XMLUtils.getChildNodes(cMembs.get(0), Node.ELEMENT_NODE)) {
                try {
                    final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder();
                    final Document doc = builder.newDocument();

                    final Element fakeParent = doc.createElementNS(ODataConstants.NS_DATASERVICES,
                            ODataConstants.PREFIX_DATASERVICES + "fake");
                    fakeParent.appendChild(doc.importNode(geom, true));

                    final EdmSimpleType callAsType = XMLUtils.simpleTypeForNode(
                            edmSimpleType == EdmSimpleType.GeographyCollection ? Geospatial.Dimension.GEOGRAPHY
                                    : Geospatial.Dimension.GEOMETRY,
                            geom);

                    jgen.writeStartObject();
                    serialize(jgen, fakeParent, callAsType.toString());
                    jgen.writeEndObject();
                } catch (Exception e) {
                    LOG.warn("While serializing {}", XMLUtils.getSimpleName(geom), e);
                }
            }

            jgen.writeEndArray();
        }
        break;

    default:
    }

    if (root != null) {
        serializeCrs(jgen, root);
    }
}

From source file:Main.java

public static Element fromObject(Document doc, String name, Object o) {
    if (o instanceof Map) {
        Map<String, Object> map = (Map) o;
        Object value = map.get("_");
        if (value != null) {
            Element element = fromObject(doc, name, value);
            Map<String, Object> attribs = (Map) map.get("@");
            addAttributes(element, attribs);
            return element;
        } else {/*from   www. j  a v  a 2 s.c o m*/
            Element element = createElement(doc, name, null, null);
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String childName = entry.getKey();
                Object childValue = entry.getValue();
                Element childNode = fromObject(doc, childName, childValue);
                element.appendChild(childNode);
            }
            return element;
        }
    } else if (o instanceof List) {
        Element element = createElement(doc, name, null, null);
        List list = (List) o;
        for (Object child : list) {
            Element childNode = fromObject(doc, name, child);
            element.appendChild(childNode);
        }
        return element;
    } else {
        String value = o == null ? null : o.toString();
        return createElement(doc, name, value, null);
    }
}