Example usage for javax.xml.parsers DocumentBuilder newDocument

List of usage examples for javax.xml.parsers DocumentBuilder newDocument

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilder newDocument.

Prototype


public abstract Document newDocument();

Source Link

Document

Obtain a new instance of a DOM Document object to build a DOM tree with.

Usage

From source file:channellistmaker.channelfilemaker.ChannelDocumentMaker.java

/**
 * @return ????X???ML????????//from  w ww .j av a 2s  .  c  o m
 */
public String getChannelList() {
    try {
        final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        final DocumentBuilder db = dbf.newDocumentBuilder();
        final Document document = db.newDocument();
        // >>>>> DOM??
        Element channels_e = document.createElement("channels");//<-root
        document.appendChild(channels_e);

        final Set<MultiKey<Integer>> keys = this.channels.keySet();
        for (MultiKey<Integer> key : keys) {
            Channel ch = channels.get(key);
            this.addChannelElement(document, channels_e, ch);
        }

        TransformerFactory tf = TransformerFactory.newInstance();

        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        StringWriter writer = new StringWriter();// <-??????????
        StreamResult result = new StreamResult(writer);

        DOMSource source = new DOMSource(document);
        transformer.transform(source, result);

        return writer.toString();
    } catch (ParserConfigurationException | TransformerConfigurationException ex) {
        LOG.fatal(ex);
        return "";
    } catch (TransformerException ex) {
        LOG.fatal(ex);
        return "";
    }
}

From source file:no.dusken.barweb.view.InvoiceView.java

private Document generateXml(Map<BarPerson, Integer> persons, Gjeng gjeng, Invoice invoice) {
    Document dom = null;/*from   w w  w . ja v a 2  s. c  o  m*/
    //get an instance of factory
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
        //get an instance of builder
        DocumentBuilder db = dbf.newDocumentBuilder();

        //create an instance of DOM
        dom = db.newDocument();

    } catch (ParserConfigurationException pce) {
        log.error("Error when generating invoice");
    }
    Element root = createInvoiceElement(invoice, gjeng, dom);
    SimpleDateFormat dateformat = new SimpleDateFormat("dd. MMMMMMMMM yyyy - HH:mm", new Locale("no"));
    root.setAttribute("generated", dateformat.format((new GregorianCalendar()).getTime()));
    root.setAttribute("magicNumber", String.valueOf(((new Random()).nextDouble() * 1000)));
    dom.appendChild(root);
    Element personsEle = dom.createElement("persons");

    for (Map.Entry<BarPerson, Integer> p : persons.entrySet()) {
        Element personEle = createPersonElement(p.getKey(), p.getValue(), dom);
        personsEle.appendChild(personEle);
    }

    root.appendChild(personsEle);

    return dom;
}

From source file:de.betterform.xml.dom.DOMUtil.java

/**
 * __UNDOCUMENTED__// w  ww  .  j a v a  2s. co  m
 *
 * @param isNamespaceAware __UNDOCUMENTED__
 * @param isValidating     __UNDOCUMENTED__
 * @return __UNDOCUMENTED__
 */
public static Document newDocument(boolean isNamespaceAware, boolean isValidating) {
    // !!! workaround to enable betterForm to run within WebLogic Server
    // Force JAXP to use xerces as the default JAXP parser doesn't work with BetterForm
    //
    //        String oldFactory = System.getProperty("javax.xml.parsers.DocumentBuilderFactory");
    //        System.setProperty("javax.xml.parsers.DocumentBuilderFactory","org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    // restore to original factory
    //
    //        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",oldFactory);
    // !!! end workaround
    factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(isNamespaceAware);
    factory.setValidating(isValidating);

    try {
        // Create builder.
        DocumentBuilder builder = factory.newDocumentBuilder();

        return builder.newDocument();
    } catch (ParserConfigurationException pce) {
        System.err.println(pce.toString());
    }

    return null;
}

From source file:be.fedict.eid.applet.service.util.KmlLightDocument.java

/**
 * Constructor/*from   w  w w . j av  a 2s.c om*/
 *
 * @throws IOException
 */
public KmlLightDocument() throws IOException {
    try {
        DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = fact.newDocumentBuilder();

        docKml = builder.newDocument();
        Element elKml = docKml.createElement("kml");
        elKml.setAttribute("xmlns", KmlLightDocument.KML_NS);

        docKml.appendChild(elKml);
    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:no.dusken.barweb.view.XListView.java

private Document generateXml(List<BarPerson> barPersons, Gjeng gjeng, List<Vare> varer, int lowlimit,
        Boolean panger) {/*w w w  .j  av a 2 s . c o  m*/
    Document dom = null;
    //get an instance of factory
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
        //get an instance of builder
        DocumentBuilder db = dbf.newDocumentBuilder();

        //create an instance of DOM
        dom = db.newDocument();

    } catch (ParserConfigurationException pce) {
        log.error("Error when generating x-list");
    }
    Element root = dom.createElement("xlist");
    root.setAttribute("gjeng", gjeng.getName());
    SimpleDateFormat dateformat = new SimpleDateFormat("d. MMMMMMMMM yyyy - HH:mm", new Locale("no"));
    root.setAttribute("generated", dateformat.format((new GregorianCalendar()).getTime()));
    root.setAttribute("magicNumber", String.valueOf(((new Random()).nextDouble() * 1000)));
    root.setAttribute("panger", panger.toString());
    dom.appendChild(root);
    Element personsEle = dom.createElement("barPersons");

    for (BarPerson p : barPersons) {
        Element personEle = createPersonElement(p, dom, lowlimit);
        personsEle.appendChild(personEle);
    }

    root.appendChild(personsEle);

    Element vareEle = dom.createElement("varer");

    for (Vare v : varer) {
        Element vare = createVareElement(v, dom);
        vareEle.appendChild(vare);
    }
    root.appendChild(vareEle);

    return dom;
}

From source file:de.mpg.mpdl.inge.transformation.Util.java

/**
 * Queries CoNE service and returns the result as DOM node. The returned XML has the following
 * structure: <cone> <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>
 * //from w ww . j  a  va  2s. c  o m
 * @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);
                    logger.info("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:mx.bigdata.cfdi.CFDv3.java

private Comprobante copy(Comprobante comprobante) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);//w w w.ja va  2s  . c o m
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();
    Marshaller m = CONTEXT.createMarshaller();
    m.marshal(comprobante, doc);
    Unmarshaller u = CONTEXT.createUnmarshaller();
    return (Comprobante) u.unmarshal(doc);
}

From source file:com.codebutler.farebot.card.Card.java

public Element toXML() throws Exception {
    try {/*ww w .j  a va 2  s .c o  m*/
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.newDocument();

        Element element = doc.createElement("card");
        element.setAttribute("type", String.valueOf(getCardType().toInteger()));
        element.setAttribute("id", Utils.getHexString(mTagId, null));
        element.setAttribute("scanned_at", Long.toString(mScannedAt.getTime()));
        doc.appendChild(element);

        return doc.getDocumentElement();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
}

From source file:be.e_contract.mycarenet.xkms.ProofOfPossessionSignatureSOAPHandler.java

private Document copyDocument(Element element) throws ParserConfigurationException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.newDocument();
    Node importedNode = document.importNode(element, true);
    document.appendChild(importedNode);//from   w  w w. j a v a 2 s.  c o m
    return document;
}

From source file:de.mpg.mpdl.inge.transformation.Util.java

/**
 * Queries the CoNE service and transforms the result into a DOM node.
 * //w ww. j  a  v a2 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 queryConeExact(String model, String name, String ou) {
    DocumentBuilder documentBuilder;

    try {
        logger.info("queryConeExact: " + model + " name: " + name + " 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&" + URLEncoder.encode("dc:title", "UTF-8") + "="
                + URLEncoder.encode("\"" + name + "\"", "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);
        logger.info("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString());
        if (method.getStatusCode() == 200) {
            ArrayList<String> results = new ArrayList<String>();
            results.addAll(Arrays.asList(method.getResponseBodyAsString().split("\n")));
            queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&"
                    + URLEncoder.encode("dcterms:alternative", "UTF-8") + "="
                    + URLEncoder.encode("\"" + name + "\"", "UTF-8") + "&"
                    + URLEncoder.encode("escidoc:position/eprints:affiliatedInstitution", "UTF-8") + "="
                    + URLEncoder.encode("\"*" + ou + "*\"", "UTF-8");
            client = new HttpClient();
            method = new GetMethod(queryUrl);
            if (coneSession != null) {
                method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
            }
            ProxyHelper.executeMethod(client, method);
            logger.info("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString());
            if (method.getStatusCode() == 200) {
                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
                            logger.info("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);
    }
}