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:de.mpg.escidoc.services.transformation.Util.java

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

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

    try {/*  w ww .j av  a  2  s  .co 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");
        logger.info("HEAD Request to " + url + " returned Content-Length: "
                + (header != null ? header.getValue() : null));
        if (header != null) {
            element.setTextContent(header.getValue());
            return document;
        } else {
            //did not get length via HEAD request, try to do a GET request 
            //workaround for biomed central, where HEAD requests sometimes return Content-Length, sometimes not

            logger.info("GET request to " + url + " did not return any Content-Length. Trying GET request.");
            httpClient = new HttpClient();
            GetMethod getMethod = new GetMethod(url);
            ProxyHelper.executeMethod(httpClient, getMethod);

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

            InputStream is = getMethod.getResponseBodyAsStream();
            long size = 0;

            while (is.read() != -1) {
                size++;
            }
            is.close();

            logger.info("GET request to " + url + " returned a file with length: " + size);
            element.setTextContent(String.valueOf(size));
            return document;
        }

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

From source file:Main.java

private static Element copyNode(Document destDocument, Element dest, Element src) {

    NamedNodeMap namedNodeMap = src.getAttributes();
    for (int i = 0; i < namedNodeMap.getLength(); i++) {
        Attr attr = (Attr) namedNodeMap.item(i);
        dest.setAttribute(attr.getName(), attr.getValue());
    }//from  w ww .j  ava  2  s . c om
    NodeList childNodeList = src.getChildNodes();
    for (int i = 0; i < childNodeList.getLength(); i++) {
        Node child = childNodeList.item(i);
        if (child.getNodeType() == Node.TEXT_NODE) {
            Text text = destDocument.createTextNode(child.getTextContent());
            dest.appendChild(text);
        } else if (child.getNodeType() == Node.ELEMENT_NODE) {
            Element element = destDocument.createElement(((Element) child).getTagName());
            element = copyNode(destDocument, element, (Element) child);
            dest.appendChild(element);
        }
    }

    return dest;
}

From source file:cz.mzk.editor.server.fedora.utils.FedoraUtils.java

/**
 * @param foxmlDocument/*from ww  w. j a  v a2s  . c om*/
 * @param streamToModify
 * @param newContent
 */
private static void modifyStream(Document foxmlDocument, String streamToModify, String newContent) {

    if (newContent != null) {
        try {
            Element versionElement = foxmlDocument.createElement("foxml:datastreamVersion");

            if (streamToModify.equals(RELS_EXT.getValue())) {
                versionElement.setAttribute("LABEL", "RDF Statements about this object");
                versionElement.setAttribute("FORMAT_URI", RELS_EXT_NAMESPACE_URI);
                versionElement.setAttribute("MIMETYPE", "application/rdf+xml");

            } else {
                versionElement.setAttribute("MIMETYPE", "text/xml");

                if (streamToModify.equals(DC.getValue())) {
                    versionElement.setAttribute("LABEL", "Dublin Core Record for this object");
                    versionElement.setAttribute("FORMAT_URI", OAI_DC_NAMESPACE_URI);

                } else if (streamToModify.equals(BIBLIO_MODS.getValue())) {
                    versionElement.setAttribute("LABEL", "BIBLIO_MODS description of current object");
                    versionElement.setAttribute("FORMAT_URI", BIBILO_MODS_URI);

                } else if (streamToModify.equals(TEXT_OCR.getValue())) {
                    versionElement.setAttribute("LABEL", "");
                    Element contLocElement = foxmlDocument.createElement("foxml:contentLocation");
                    contLocElement.setAttribute("TYPE", "INTERNAL_ID");
                    contLocElement.setAttribute("REF", "LOCAL");
                    Element localContElement = foxmlDocument.createElement("foxml:content");
                    localContElement.setTextContent(newContent);
                    contLocElement.appendChild(localContElement);
                    versionElement.appendChild(contLocElement);
                }
            }

            String lastStreamXPath = "//foxml:datastream[@ID=\'" + streamToModify
                    + "\']/foxml:datastreamVersion[last()]";
            Element element = FoxmlUtils.getElement(foxmlDocument, lastStreamXPath);

            int versionNumber = 0;
            if (element != null) {
                versionNumber = getVersionNumber(element.getAttribute("ID"));
            }

            versionElement.setAttribute("ID", streamToModify + "." + (versionNumber + 1));
            versionElement.setAttribute("CREATED", "NOT YET");
            versionElement.setAttribute("SIZE", "0");

            Element contentElement = foxmlDocument.createElement("foxml:xmlContent");

            try {
                InputStream is = new ByteArrayInputStream(newContent.getBytes("UTF-8"));
                Document newStreamDocument = FoxmlUtils.getFoxmlDocument(is);
                NodeList streamNodeList = newStreamDocument.getChildNodes();
                for (int i = 0; i < streamNodeList.getLength(); i++) {
                    Node myNewNode = foxmlDocument.importNode(streamNodeList.item(i), true);
                    contentElement.appendChild(myNewNode);
                }
            } catch (IOException e) {
                System.err.println("IO fauilure" + e);
            }

            versionElement.appendChild(contentElement);

            String streamXPath = "//foxml:datastream[@ID=\'" + streamToModify + "\']";
            Element parentOfStream = FoxmlUtils.getElement(foxmlDocument, streamXPath);

            if (parentOfStream == null) {
                String digObjXPath = "//foxml:digitalObject";
                Element digObjElement = FoxmlUtils.getElement(foxmlDocument, digObjXPath);

                parentOfStream = foxmlDocument.createElement("datastream");
                parentOfStream.setAttribute("ID", streamToModify);
                parentOfStream.setAttribute("STATE", "A");
                //TODO for other streams if necessary
                if (streamToModify.equals(TEXT_OCR.getValue()))
                    parentOfStream.setAttribute("CONTROL_GROUP", "M");
                parentOfStream.setAttribute("VERSIONABLE", "false");
                digObjElement.appendChild(parentOfStream);
            }

            parentOfStream.appendChild(versionElement);

        } catch (XPathExpressionException e) {
            LOGGER.warn("XPath failure", e);
        }
    }
}

From source file:com.zimbra.cs.service.AutoDiscoverServlet.java

private static String createResponseDoc(String displayName, String email, String serviceUrl) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*from w  w w. ja  v  a  2 s . c  o  m*/
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document xmlDoc = builder.newDocument();

    Element root = xmlDoc.createElementNS(NS, "Autodiscover");
    root.setAttribute("xmlns", NS);
    root.setAttribute("xmlns:xsi", XSI_NS);
    root.setAttribute("xmlns:xsd", XSD_NS);
    xmlDoc.appendChild(root);

    //Add the response element.
    Element response = xmlDoc.createElementNS(NS_MOBILE, "Response");
    root.appendChild(response);

    //Add culture to to response
    Element culture = xmlDoc.createElement("Culture");
    culture.appendChild(xmlDoc.createTextNode("en:en"));
    response.appendChild(culture);

    //User
    Element user = xmlDoc.createElement("User");
    Element displayNameElm = xmlDoc.createElement("DisplayName");
    displayNameElm.appendChild(xmlDoc.createTextNode(displayName));
    user.appendChild(displayNameElm);
    Element emailAddr = xmlDoc.createElement("EMailAddress");
    emailAddr.appendChild(xmlDoc.createTextNode(email));
    user.appendChild(emailAddr);
    response.appendChild(user);

    //Action
    Element action = xmlDoc.createElement("Action");
    Element settings = xmlDoc.createElement("Settings");
    Element server = xmlDoc.createElement("Server");

    Element type = xmlDoc.createElement("Type");
    type.appendChild(xmlDoc.createTextNode("MobileSync"));
    server.appendChild(type);

    Element url = xmlDoc.createElement("Url");
    url.appendChild(xmlDoc.createTextNode(serviceUrl));
    server.appendChild(url);

    Element name = xmlDoc.createElement("Name");
    name.appendChild(xmlDoc.createTextNode(serviceUrl));
    server.appendChild(name);

    settings.appendChild(server);
    action.appendChild(settings);
    response.appendChild(action);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    DOMSource source = new DOMSource(xmlDoc);
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    transformer.transform(source, result);
    writer.flush();
    String xml = writer.toString();
    writer.close();

    //manually generate xmlns for Autodiscover and Response element, this works
    //for testexchangeconnectivity.com, but iOS and Android don't like Response's xmlns
    //        StringBuilder str = new StringBuilder();
    //        str.append("<?xml version=\"1.0\"?>\n");
    //        str.append("<Autodiscover xmlns:xsd=\"").append(XSD_NS).append("\"");
    //        str.append(" xmlns:xsi=\"").append(XSI_NS).append("\"");
    //        str.append(" xmlns=\"").append(NS).append("\">\n");
    //        int respIndex = xml.indexOf("<Response>");
    //        str.append("<Response xmlns=\"").append(NS_MOBILE).append("\">");
    //        str.append(xml.substring(respIndex + "<Response>".length(), xml.length()));
    //        return str.toString();
    return "<?xml version=\"1.0\"?>\n" + xml;
}

From source file:de.mpg.escidoc.services.transformation.Util.java

/**
 * Queries CoNE service and returns the result as DOM node.
 * The returned XML has the following structure:
 * <cone>/*from   w ww  .j  a va  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 authors
 * @return 
 */
public static Node queryCone(String model, String query) {
    DocumentBuilder documentBuilder;
    String queryUrl = null;
    try {
        logger.info("queryCone: " + model + " query: " + query);

        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();
        client.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        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];
                    // TODO "&redirect=true" must be reinserted again
                    GetMethod detailMethod = new GetMethod(id + "?format=rdf&eSciDocUserHandle="
                            + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8")));
                    detailMethod.setFollowRedirects(true);

                    if (coneSession != null) {
                        detailMethod.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
                    }
                    ProxyHelper.executeMethod(client, detailMethod);
                    if (logger.isDebugEnabled()) {
                        logger.debug("CoNE query: " + id + "?format=rdf&eSciDocUserHandle="
                                + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8"))
                                + " returned " + detailMethod.getResponseBodyAsString());
                    }

                    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.", e);
        logger.debug("Stacktrace", e);
        return null;
        //throw new RuntimeException(e);
    }
}

From source file:com.nebhale.gpxconverter.StandardRouteBuilder.java

private Element ele(Document document, Point point) {
    Element ele = document.createElement("ele");
    ele.setTextContent(String.valueOf(point.getElevation()));

    return ele;/*  ww  w.  j  a va2s .  c  om*/
}

From source file:de.mpg.escidoc.services.transformation.Util.java

/**
 * Queries the CoNE service and transforms the result into a DOM node.
 * /*from   www  .  j  a va  2 s.com*/
 * @param model The type of object (e.g. "persons")
 * @param name The query string.
 * @param ou Specialty for persons
 * @param coneSession A JSESSIONID to not produce a new session with each call.
 * @return A DOM node containing the results.
 */
public static Node queryConeExactWithIdentifier(String model, String identifier, String ou) {
    DocumentBuilder documentBuilder;

    try {
        logger.info("queryConeExactWithIdentifier: " + model + " identifier: " + identifier + " ou: " + ou);

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

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

        String queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                + "/query?format=jquery&dc:identifier/" + URLEncoder.encode("rdf:value", "UTF-8") + "="
                + URLEncoder.encode("\"" + identifier + "\"", "UTF-8") + "&"
                + URLEncoder.encode("escidoc:position/eprints:affiliatedInstitution", "UTF-8") + "="
                + URLEncoder.encode("\"*" + ou + "*\"", "UTF-8");
        String detailsUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                + "/resource/$1?format=rdf";
        HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        GetMethod method = new GetMethod(queryUrl);

        String coneSession = getConeSession();

        if (coneSession != null) {
            method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
        }
        ProxyHelper.executeMethod(client, method);
        if (logger.isDebugEnabled()) {
            logger.debug("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString());
        }
        if (method.getStatusCode() == 200) {
            ArrayList<String> results = new ArrayList<String>();
            results.addAll(Arrays.asList(method.getResponseBodyAsString().split("\n")));
            Set<String> oldIds = new HashSet<String>();
            for (String result : results) {
                if (!"".equals(result.trim())) {
                    String id = result.split("\\|")[1];
                    if (!oldIds.contains(id)) {
                        // TODO "&redirect=true" must be reinserted again
                        GetMethod detailMethod = new GetMethod(id + "?format=rdf&eSciDocUserHandle="
                                + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8")));
                        detailMethod.setFollowRedirects(true);

                        ProxyHelper.setProxy(client, detailsUrl.replace("$1", id));
                        client.executeMethod(detailMethod);
                        // TODO "&redirect=true" must be reinserted again
                        if (logger.isDebugEnabled()) {
                            logger.debug("CoNE query: " + id + "?format=rdf&eSciDocUserHandle="
                                    + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8"))
                                    + " returned " + detailMethod.getResponseBodyAsString());
                        }
                        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());
                        }
                        oldIds.add(id);
                    }
                }
            }
        } 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. "
                + "Otherwise it should be clarified if any measures have to be taken.", e);
        return null;
        //throw new RuntimeException(e);
    }
}

From source file:com.nebhale.gpxconverter.StandardRouteBuilder.java

private Element name(Document document, String name) {
    Element element = document.createElement("name");
    element.setTextContent(name);/*from  w  w w.  ja  va2 s.co  m*/

    return element;
}

From source file:com.nebhale.gpxconverter.StandardRouteBuilder.java

private Element trkpt(Document document, Point point) {
    Element trkpt = document.createElement("trkpt");
    trkpt.setAttribute("lat", String.valueOf(point.getLatitude()));
    trkpt.setAttribute("lon", String.valueOf(point.getLongitude()));
    trkpt.appendChild(ele(document, point));

    return trkpt;
}