Example usage for org.w3c.dom Document appendChild

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

Introduction

In this page you can find the example usage for org.w3c.dom Document 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.msopentech.odatajclient.engine.data.impl.v3.AtomSerializer.java

private Element entry(final AtomEntry entry) throws ParserConfigurationException {
    final DocumentBuilder builder = XMLUtils.DOC_BUILDER_FACTORY.newDocumentBuilder();
    final Document doc = builder.newDocument();

    final Element entryElem = doc.createElement(ODataConstants.ATOM_ELEM_ENTRY);
    entryElem.setAttribute(XMLConstants.XMLNS_ATTRIBUTE, ODataConstants.NS_ATOM);
    entryElem.setAttribute(ODataConstants.XMLNS_METADATA,
            client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA));
    entryElem.setAttribute(ODataConstants.XMLNS_DATASERVICES,
            client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_DATASERVICES));
    entryElem.setAttribute(ODataConstants.XMLNS_GML, ODataConstants.NS_GML);
    entryElem.setAttribute(ODataConstants.XMLNS_GEORSS, ODataConstants.NS_GEORSS);
    if (entry.getBaseURI() != null) {
        entryElem.setAttribute(ODataConstants.ATTR_XMLBASE, entry.getBaseURI().toASCIIString());
    }//from  w w w.j  av a  2 s. com
    doc.appendChild(entryElem);

    final Element category = doc.createElement(ODataConstants.ATOM_ELEM_CATEGORY);
    category.setAttribute(ODataConstants.ATOM_ATTR_TERM, entry.getType());
    category.setAttribute(ODataConstants.ATOM_ATTR_SCHEME,
            client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_SCHEME));
    entryElem.appendChild(category);

    if (StringUtils.isNotBlank(entry.getTitle())) {
        final Element title = doc.createElement(ODataConstants.ATOM_ELEM_TITLE);
        title.appendChild(doc.createTextNode(entry.getTitle()));
        entryElem.appendChild(title);
    }

    if (StringUtils.isNotBlank(entry.getSummary())) {
        final Element summary = doc.createElement(ODataConstants.ATOM_ELEM_SUMMARY);
        summary.appendChild(doc.createTextNode(entry.getSummary()));
        entryElem.appendChild(summary);
    }

    setLinks(entryElem, entry.getAssociationLinks());
    setLinks(entryElem, entry.getNavigationLinks());
    setLinks(entryElem, entry.getMediaEditLinks());

    final Element content = doc.createElement(ODataConstants.ATOM_ELEM_CONTENT);
    if (entry.isMediaEntry()) {
        if (StringUtils.isNotBlank(entry.getMediaContentType())) {
            content.setAttribute(ODataConstants.ATTR_TYPE, entry.getMediaContentType());
        }
        if (StringUtils.isNotBlank(entry.getMediaContentSource())) {
            content.setAttribute(ODataConstants.ATOM_ATTR_SRC, entry.getMediaContentSource());
        }
        if (content.getAttributes().getLength() > 0) {
            entryElem.appendChild(content);
        }

        if (entry.getMediaEntryProperties() != null) {
            entryElem.appendChild(doc.importNode(entry.getMediaEntryProperties(), true));
        }
    } else {
        content.setAttribute(ODataConstants.ATTR_TYPE, ContentType.APPLICATION_XML.getMimeType());
        if (entry.getContent() != null) {
            content.appendChild(doc.importNode(entry.getContent(), true));
        }
        entryElem.appendChild(content);
    }

    return entryElem;
}

From source file:com.microsoft.windowsazure.management.ManagementCertificateOperationsImpl.java

/**
* The Create Management Certificate operation adds a certificate to the
* list of management certificates. Management certificates, which are also
* known as subscription certificates, authenticate clients attempting to
* connect to resources associated with your Azure subscription.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj154123.aspx for
* more information)//  w w  w  .j av a  2  s  .c  o  m
*
* @param parameters Required. Parameters supplied to the Create Management
* Certificate operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse create(ManagementCertificateCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "createAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/certificates";
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpPost httpRequest = new HttpPost(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/xml");
    httpRequest.setHeader("x-ms-version", "2014-10-01");

    // Serialize Request
    String requestContent = null;
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document requestDoc = documentBuilder.newDocument();

    Element subscriptionCertificateElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/windowsazure", "SubscriptionCertificate");
    requestDoc.appendChild(subscriptionCertificateElement);

    if (parameters.getPublicKey() != null) {
        Element subscriptionCertificatePublicKeyElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificatePublicKey");
        subscriptionCertificatePublicKeyElement
                .appendChild(requestDoc.createTextNode(Base64.encode(parameters.getPublicKey())));
        subscriptionCertificateElement.appendChild(subscriptionCertificatePublicKeyElement);
    }

    if (parameters.getThumbprint() != null) {
        Element subscriptionCertificateThumbprintElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificateThumbprint");
        subscriptionCertificateThumbprintElement
                .appendChild(requestDoc.createTextNode(parameters.getThumbprint()));
        subscriptionCertificateElement.appendChild(subscriptionCertificateThumbprintElement);
    }

    if (parameters.getData() != null) {
        Element subscriptionCertificateDataElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "SubscriptionCertificateData");
        subscriptionCertificateDataElement
                .appendChild(requestDoc.createTextNode(Base64.encode(parameters.getData())));
        subscriptionCertificateElement.appendChild(subscriptionCertificateDataElement);
    }

    DOMSource domSource = new DOMSource(requestDoc);
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(domSource, streamResult);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/xml");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        OperationResponse result = null;
        // Deserialize Response
        result = new OperationResponse();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:ddf.metrics.reporting.internal.rrd4j.RrdMetricsRetriever.java

@Override
public String createXmlData(String metricName, String rrdFilename, long startTime, long endTime)
        throws IOException, MetricsGraphException {
    LOGGER.trace("ENTERING: createXmlData");

    MetricData metricData = getMetricData(rrdFilename, startTime, endTime);

    String displayableMetricName = convertCamelCase(metricName);

    String title = displayableMetricName + " for " + getCalendarTime(startTime) + " to "
            + getCalendarTime(endTime);//www  .  j a  va 2 s.com

    String xmlString = null;

    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement(metricName);
        doc.appendChild(rootElement);

        Element titleElement = doc.createElement("title");
        titleElement.appendChild(doc.createTextNode(title));
        rootElement.appendChild(titleElement);

        Element dataElement = doc.createElement("data");
        rootElement.appendChild(dataElement);

        List<Long> timestamps = metricData.getTimestamps();
        List<Double> values = metricData.getValues();

        for (int i = 0; i < timestamps.size(); i++) {
            Element sampleElement = doc.createElement("sample");
            dataElement.appendChild(sampleElement);

            String timestamp = getCalendarTime(timestamps.get(i));
            Element timestampElement = doc.createElement("timestamp");
            timestampElement.appendChild(doc.createTextNode(timestamp));
            sampleElement.appendChild(timestampElement);

            Element valueElement = doc.createElement("value");
            valueElement.appendChild(doc.createTextNode(String.valueOf(values.get(i))));
            sampleElement.appendChild(valueElement);
        }

        if (metricData.hasTotalCount()) {
            Element totalCountElement = doc.createElement("totalCount");
            totalCountElement.appendChild(doc.createTextNode(Long.toString(metricData.getTotalCount())));
            dataElement.appendChild(totalCountElement);
        }

        // Write the content into xml stringwriter
        xmlString = XMLUtils.prettyFormat(doc);
    } catch (ParserConfigurationException pce) {
        LOGGER.error("Parsing error while creating xml data", pce);
    }

    LOGGER.trace("xml = {}", xmlString);

    LOGGER.trace("EXITING: createXmlData");

    return xmlString;
}

From source file:es.upm.fi.dia.oeg.sitemap4rdf.Generator.java

/**
 * Generates the sitemap_index.xml file//from   w w w.ja  v  a2 s .c  o  m
-    */
protected void generateSiteMapIndex() {
    if (siteroot == null || siteroot.isEmpty()) {
        //Logger.getLogger(Generator.class.getName()).log(Level.SEVERE, null, new java.lang.Exception());
        System.err.print(
                "You should provide the siteroot parameter needed because a sitemapindex is being created");
        System.exit(3);
    }

    try {
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        String indexFileName = indexOutputFile;
        if (outputDir != null && !outputDir.isEmpty())
            indexFileName = outputDir + indexOutputFile;

        Element root = doc.createElement(siteMapIndexTag);
        root.setAttribute(XMLNS, namespace);
        doc.appendChild(root);

        generateSitemapsSection(root, doc);

        OutputFormat format = new OutputFormat(defaultDocumentType, DEFAULT_ENCODING, true);
        format.setIndenting(true);
        format.setIndent(4);
        Writer output = new BufferedWriter(new FileWriter(indexFileName));
        XMLSerializer serializer = new XMLSerializer(output, format);
        serializer.serialize(doc);

    } catch (ParserConfigurationException e) {
        logger.debug("ParserConfigurationException ", e);
        System.err.println(e.getMessage());
        System.exit(3);
    } catch (IOException e) {
        logger.debug("IOException ", e);
        System.err.println(e.getMessage());
        System.exit(3);
    }
}

From source file:com.igeekinc.indelible.indeliblefs.webaccess.IndelibleWebAccessServlet.java

public void rename(HttpServletRequest req, HttpServletResponse resp, String destPathStr, Document buildDoc)
        throws IndelibleWebAccessException, PermissionDeniedException, RemoteException, IOException {
    Element rootElem = buildDoc.createElement("duplicate");
    buildDoc.appendChild(rootElem);
    String path = req.getPathInfo();
    FilePath reqPath = FilePath.getFilePath(path);
    if (reqPath == null || destPathStr == null || reqPath.getNumComponents() < 3)
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);

    // Should be an absolute path
    reqPath = reqPath.removeLeadingComponent();
    String fsIDStr = reqPath.getComponent(0);
    IndelibleFSVolumeIF volume = getVolume(fsIDStr);
    FilePath sourcePath = reqPath.removeLeadingComponent();
    sourcePath = FilePath.getFilePath("/").getChild(sourcePath); // Make sourcePath absolute
    FilePath destinationPath = FilePath.getFilePath(destPathStr);
    IndelibleFileNodeIF sourceFile = null;
    FilePath destPath = FilePath.getFilePath(destPathStr);
    if (destPath == null)
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);
    String createName = null;/*  w  ww  .  j a va  2  s. co m*/
    if (sourcePath != null) {
        createName = sourcePath.getName();
    }
    try {
        volume.moveObject(sourcePath, destinationPath);
    } catch (ObjectNotFoundException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kPathNotFound, e);
    } catch (FileExistsException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kDestinationExists, e);
    } catch (NotDirectoryException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kNotDirectory, e);
    }

}

From source file:com.igeekinc.indelible.indeliblefs.webaccess.IndelibleWebAccessServlet.java

public void rmdir(HttpServletRequest req, HttpServletResponse resp, Document buildDoc)
        throws IndelibleWebAccessException, PermissionDeniedException, RemoteException, IOException {
    Element rootElem = buildDoc.createElement("rmdir");
    buildDoc.appendChild(rootElem);
    String path = req.getPathInfo();
    FilePath reqPath = FilePath.getFilePath(path);
    if (reqPath == null || reqPath.getNumComponents() < 3)
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);

    // Should be an absolute path
    reqPath = reqPath.removeLeadingComponent();
    String fsIDStr = reqPath.getComponent(0);
    IndelibleFSVolumeIF volume = getVolume(fsIDStr);
    FilePath deletePath = reqPath.removeLeadingComponent();
    FilePath parentPath = deletePath.getParent();
    String deleteName = deletePath.getName();

    IndelibleDirectoryNodeIF parentNode = null;

    connection.startTransaction();/*from www  . java2s  .  c  o  m*/
    try {
        IndelibleFileNodeIF parentObject = volume.getObjectByPath(parentPath.makeAbsolute());
        if (!(parentObject instanceof IndelibleDirectoryNodeIF)) {
            connection.rollback();
            throw new IndelibleWebAccessException(IndelibleWebAccessException.kNotDirectory, null);
        }
        parentNode = (IndelibleDirectoryNodeIF) parentObject;
    } catch (ObjectNotFoundException e1) {
        connection.rollback();
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kPathNotFound, e1);
    }

    try {
        parentNode.deleteChildDirectory(deleteName);
    } catch (PermissionDeniedException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kPermissionDenied, e);
    } catch (NotDirectoryException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kNotDirectory, e);
    }

    connection.commit();
}

From source file:com.betfair.testing.utils.cougar.helpers.CougarHelpers.java

private Document handleSoapResponse(SOAPMessage response, HttpResponseBean responseBean)
        throws TransformerException, SOAPException, ParserConfigurationException {

    Node responseNode = null;/*  ww  w .ja  va 2  s  .c  o  m*/

    if (response != null) {
        responseNode = extractResponseNode(response);
        extractHeaderDataSOAP(response, responseBean);
    }

    // build new xml document for assertion
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document newDocument = builder.newDocument();

    Node adoptedBlob = newDocument.importNode(responseNode, true);
    newDocument.appendChild(adoptedBlob);

    // Output as String if required
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    transformer.transform(new DOMSource(newDocument), new StreamResult(out));

    if (logger.isDebugEnabled()) {
        logger.debug("\n Return Doc \n");
        logger.debug(new String(out.toByteArray()));
    }

    return newDocument;
}

From source file:org.kuali.mobility.maps.service.LocationServiceImpl.java

private Document writeMapsGroupToDocument(MapsGroup mapsGroup, String groupCode, boolean isOneStart) {
    DocumentBuilderFactory dbf;//from www .  ja  v a  2  s.  c  o m
    Document xmlDoc = null;
    try {
        dbf = DocumentBuilderFactory.newInstance();
        xmlDoc = createDocument(dbf);
        if (xmlDoc != null) {
            // Create Root
            Element rootElement = xmlDoc.createElement("root");
            xmlDoc.appendChild(rootElement);
            // Handle the maps groups
            Map<Long, Long> map = new HashMap<Long, Long>();
            Element groupElement = mapsGroupToElement(xmlDoc, mapsGroup, map);
            if (groupElement != null) {
                rootElement.appendChild(groupElement);
            }
        }
    } catch (Exception e) {
        //         LOG.error("Failed to create document: ", e);
    }
    return xmlDoc;
}

From source file:org.alfresco.web.config.forms.FormConfigRuntime.java

/**
 * @param element/*from w w  w .  j av  a 2 s  .  c om*/
 * @return
 * @throws ParserConfigurationException
 */
public org.dom4j.Element convert(org.w3c.dom.Element element) throws ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    org.w3c.dom.Document doc1 = builder.newDocument();
    doc1.appendChild(doc1.importNode(element, true));
    // Convert w3c document to dom4j document
    org.dom4j.io.DOMReader reader = new org.dom4j.io.DOMReader();
    org.dom4j.Document doc2 = reader.read(doc1);

    return doc2.getRootElement();
}