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.atom.AtomSerializer.java

private static Element feed(final AtomFeed feed) throws ParserConfigurationException {
    final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder();
    final Document doc = builder.newDocument();

    final Element feedElem = doc.createElement(ODataConstants.ATOM_ELEM_FEED);
    feedElem.setAttribute(XMLConstants.XMLNS_ATTRIBUTE, ODataConstants.NS_ATOM);
    feedElem.setAttribute(ODataConstants.XMLNS_METADATA, ODataConstants.NS_METADATA);
    feedElem.setAttribute(ODataConstants.XMLNS_DATASERVICES, ODataConstants.NS_DATASERVICES);
    feedElem.setAttribute(ODataConstants.XMLNS_GML, ODataConstants.NS_GML);
    feedElem.setAttribute(ODataConstants.XMLNS_GEORSS, ODataConstants.NS_GEORSS);
    if (feed.getBaseURI() != null) {
        feedElem.setAttribute(ODataConstants.ATTR_XMLBASE, feed.getBaseURI().toASCIIString());
    }/*from   www . j a v a  2s  .c o m*/
    doc.appendChild(feedElem);

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

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

    for (AtomEntry entry : feed.getEntries()) {
        feedElem.appendChild(doc.importNode(entry(entry), true));
    }

    return feedElem;
}

From source file:de.betterform.connector.file.FileURIResolver.java

/**
 * Returns a plain file listing as a document.
 *
 * @param directory the directory to list.
 * @return a plain file listing as a document.
 *//*from  w ww.j a  v  a  2s  .  co m*/
public static Document buildDirectoryListing(File directory) {
    Document dirList = DOMUtil.newDocument(false, false);
    Element root = dirList.createElement("dir");
    root.setAttribute("path", directory.toURI().toString());
    root.setAttribute("parentDir", directory.getParentFile().toURI().toString());

    File[] fileList = directory.listFiles();
    File file;
    Element element;
    for (int i = 0; i < fileList.length; i++) {
        file = fileList[i];

        if (file.isDirectory()) {
            element = dirList.createElement("dir");
        } else {
            element = dirList.createElement("file");
        }

        element.setAttribute("name", file.getName());
        element.setAttribute("path", file.toURI().toString());
        root.appendChild(element);
    }

    dirList.appendChild(root);
    return dirList;
}

From source file:com.msopentech.odatajclient.engine.data.atom.AtomSerializer.java

private static Element entry(final AtomEntry entry) throws ParserConfigurationException {
    final DocumentBuilder builder = ODataConstants.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, ODataConstants.NS_METADATA);
    entryElem.setAttribute(ODataConstants.XMLNS_DATASERVICES, ODataConstants.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 ww  w.  j  ava 2 s  . co m
    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, ODataConstants.ATOM_CATEGORY_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:de.mpg.escidoc.services.common.util.Util.java

public static Node querySSRNId(String conePersonUrl) {
    DocumentBuilder documentBuilder;
    HttpClient client = new HttpClient();
    try {/*  w  w w  .j  av  a2 s. c om*/
        documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder();

        Document document = documentBuilder.newDocument();
        Element element = document.createElement("cone");
        document.appendChild(element);
        GetMethod detailMethod = new GetMethod(conePersonUrl + "?format=rdf");
        ProxyHelper.setProxy(client, conePersonUrl);
        client.executeMethod(detailMethod);
        if (detailMethod.getStatusCode() == 200) {
            Document details = documentBuilder.parse(detailMethod.getResponseBodyAsStream());
            element.appendChild(document.importNode(details.getFirstChild(), true));
            return document;
        } else {
            logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n"
                    + detailMethod.getResponseBodyAsString());
            return null;
        }

    } catch (Exception e) {
        logger.error("Error querying CoNE service. This is normal during unit tests. "
                + "Otherwise it should be clarified if any measures have to be taken.");
        return null;
    }

}

From source file:de.mpg.escidoc.services.common.util.Util.java

public static Node getSize(String url) {
    DocumentBuilder documentBuilder;

    HttpClient httpClient = new HttpClient();
    HeadMethod headMethod = new HeadMethod(url);

    try {/* w  w w .  j a  v a2s  . c  o  m*/
        logger.info("Getting size of " + url);
        ProxyHelper.executeMethod(httpClient, headMethod);

        if (headMethod.getStatusCode() != 200) {
            logger.warn("Wrong status code " + headMethod.getStatusCode() + " at " + url);
        }

        documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder();
        Document document = documentBuilder.newDocument();
        Element element = document.createElement("size");
        document.appendChild(element);
        Header header = headMethod.getResponseHeader("Content-Length");
        if (header != null) {
            element.setTextContent(header.getValue());
            return document;
        } else {
            element.setTextContent("0");
            return document;
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:de.mpg.escidoc.services.common.util.Util.java

/**
 * Queries CoNE service and returns the result as DOM node.
 * The returned XML has the following structure:
 * <cone>//w w  w .  j a  v  a  2 s .c o  m
 *   <author>
 *     <familyname>Buxtehude-Mlln</familyname>
 *     <givenname>Heribert</givenname>
 *     <prefix>von und zu</prefix>
 *     <title>Knig</title>
 *   </author>
 *   <author>
 *     <familyname>Mller</familyname>
 *     <givenname>Peter</givenname>
 *   </author>
 * </authors>
 * 
 * @param Single instituteId for an institute without departments or list of Ids. Every department has his own Id.
 * @return 
 */
public static Node queryReportPersonCone(String model, String query) {
    DocumentBuilder documentBuilder;
    String queryUrl;
    List<String> childIds = new ArrayList<String>();
    // get the childOUs if any in the query
    if (query.contains(" ")) {
        String[] result = query.split("\\s+");
        for (String s : result) {
            childIds.add(s);
        }
    }

    try {
        documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder();

        Document document = documentBuilder.newDocument();
        Element element = document.createElement("cone");
        document.appendChild(element);

        queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                + "/query?format=jquery&escidoc:position/dc:identifier=\"" + query + "\"&n=0";

        HttpClient client = new HttpClient();
        if (childIds.size() > 0) {
            // execute a method for every child ou
            for (String childId : childIds) {
                queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                        + "/query?format=jquery&escidoc:position/dc:identifier=\"" + childId + "\"&n=0";
                executeGetMethod(client, queryUrl, documentBuilder, document, element);
            }
        } else {
            // there are no child ous, methid is called once
            executeGetMethod(client, queryUrl, documentBuilder, document, element);
        }

        return document;
    } catch (Exception e) {
        logger.error("Error querying CoNE service. This is normal during unit tests. "
                + "Otherwise it should be clarified if any measures have to be taken.");
        return null;
    }
}

From source file:com.sonar.maven.it.ItUtils.java

/**
 * Creates a settings xml with a sonar profile, containing all the given properties
 * Also adds repox to continue to use QAed artifacts 
 */// w w w .  jav  a 2 s .  c om
public static String createSettingsXml(Map<String, String> props) throws Exception {
    DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = docBuilder.newDocument();

    Element settings = doc.createElement("settings");
    Element profiles = doc.createElement("profiles");
    Element profile = doc.createElement("profile");

    Element id = doc.createElement("id");
    id.setTextContent("sonar");

    Element properties = doc.createElement("properties");

    for (Map.Entry<String, String> e : props.entrySet()) {
        Element el = doc.createElement(e.getKey());
        el.setTextContent(e.getValue());
        properties.appendChild(el);
    }

    profile.appendChild(id);
    profile.appendChild(properties);
    profile.appendChild(createRepositories(doc));
    profile.appendChild(createPluginRepositories(doc));

    profiles.appendChild(profile);
    settings.appendChild(profiles);
    doc.appendChild(settings);

    Writer writer = new StringWriter();
    Transformer tf = TransformerFactory.newInstance().newTransformer();
    tf.transform(new DOMSource(doc), new StreamResult(writer));
    return writer.toString();
}

From source file:com.granule.json.utils.XML.java

private static void convertJSONArray(Document doc, Element parent, JSONArray jArray, String tagName) {
    tagName = removeProblemCharacters(tagName);
    for (int i = 0; i < jArray.size(); i++) {
        Element element = doc.createElement(tagName);
        if (parent != null) {
            parent.appendChild(element);
        } else {/*w  ww  . j a  v  a2 s.  co  m*/
            doc.appendChild(element);
        }

        Object obj = jArray.get(i);

        if (obj instanceof Number) {
            Node tNode = doc.createTextNode(obj.toString());
            element.appendChild(tNode);
        } else if (obj instanceof Boolean) {
            Node tNode = doc.createTextNode(obj.toString());
            element.appendChild(tNode);
        } else if (obj instanceof String) {
            Node tNode = doc.createTextNode(escapeEntityCharacters(obj.toString()));
            element.appendChild(tNode);
        } else if (obj instanceof JSONObject) {
            convertJSONObject(doc, element, (JSONObject) obj, "jsonObject");
        } else if (obj instanceof JSONArray) {
            convertJSONArray(doc, element, (JSONArray) obj, "jsonArray");
        }
    }
}

From source file:com.granule.json.utils.XML.java

private static void convertJSONObject(Document doc, Element parent, JSONObject jObject, String tagName) {
    Set attributes = jObject.keySet();
    Iterator attrsItr = attributes.iterator();

    Element element = doc.createElement(removeProblemCharacters(tagName));
    if (parent != null) {
        parent.appendChild(element);//w  w w . jav a  2s.  com
    } else {
        doc.appendChild(element);
    }

    while (attrsItr.hasNext()) {
        String attr = (String) attrsItr.next();
        Object obj = jObject.opt(attr);

        if (obj instanceof Number) {
            element.setAttribute(attr, obj.toString());
        } else if (obj instanceof Boolean) {
            element.setAttribute(attr, obj.toString());
        } else if (obj instanceof String) {
            element.setAttribute(attr, escapeEntityCharacters(obj.toString()));
        } else if (obj == null) {
            element.setAttribute(attr, "");
        } else if (obj instanceof JSONObject) {
            convertJSONObject(doc, element, (JSONObject) obj, attr);
        } else if (obj instanceof JSONArray) {
            convertJSONArray(doc, element, (JSONArray) obj, attr);
        }
    }
}

From source file:de.mpg.escidoc.services.common.util.Util.java

/**
 * Queries CoNE service and returns the result as DOM node.
 * The returned XML has the following structure:
 * <cone>//w  w w. j  av  a2s .co  m
 *   <author>
 *     <familyname>Buxtehude-Mlln</familyname>
 *     <givenname>Heribert</givenname>
 *     <prefix>von und zu</prefix>
 *     <title>Knig</title>
 *   </author>
 *   <author>
 *     <familyname>Mller</familyname>
 *     <givenname>Peter</givenname>
 *   </author>
 * </authors>
 * 
 * @param authors
 * @return 
 */
// IMPORTANT!!! Currently not working due to missing userHnadle info
public static Node queryCone(String model, String query) {
    DocumentBuilder documentBuilder;
    String queryUrl = null;
    try {
        System.out.println("queryCone: " + model);

        documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder();

        Document document = documentBuilder.newDocument();
        Element element = document.createElement("cone");
        document.appendChild(element);

        queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&q="
                + URLEncoder.encode(query, "UTF-8");
        String detailsUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                + "/resource/$1?format=rdf";
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(queryUrl);

        String coneSession = getConeSession();

        if (coneSession != null) {
            method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
        }
        ProxyHelper.executeMethod(client, method);

        if (method.getStatusCode() == 200) {
            String[] results = method.getResponseBodyAsString().split("\n");
            for (String result : results) {
                if (!"".equals(result.trim())) {
                    String id = result.split("\\|")[1];
                    GetMethod detailMethod = new GetMethod(id + "?format=rdf&eSciDocUserHandle=" + "TODO");
                    logger.info(detailMethod.getPath());
                    logger.info(detailMethod.getQueryString());

                    if (coneSession != null) {
                        detailMethod.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
                    }
                    ProxyHelper.executeMethod(client, detailMethod);

                    if (detailMethod.getStatusCode() == 200) {
                        Document details = documentBuilder.parse(detailMethod.getResponseBodyAsStream());
                        element.appendChild(document.importNode(details.getFirstChild(), true));
                    } else {
                        logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n"
                                + detailMethod.getResponseBodyAsString());
                    }
                }
            }
        } else {
            logger.error("Error querying CoNE: Status " + method.getStatusCode() + "\n"
                    + method.getResponseBodyAsString());
        }

        return document;
    } catch (Exception e) {
        logger.error("Error querying CoNE service. This is normal during unit tests. (" + queryUrl
                + ") .Otherwise it should be clarified if any measures have to be taken.");
        logger.debug("Stacktrace", e);
        return null;
        //throw new RuntimeException(e);
    }
}