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:cn.itcast.fredck.FCKeditor.connector.ConnectorServlet.java

/**
 * Manage the Get requests (GetFolders, GetFoldersAndFiles, CreateFolder).<br>
 *
 * The servlet accepts commands sent in the following format:<br>
 * connector?Command=CommandName&Type=ResourceType&CurrentFolder=FolderPath<br><br>
 * It execute the command and then return the results to the client in XML format.
 *
 *///from   www .  j a v  a2  s  .  c o m
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (debug)
        System.out.println("--- BEGIN DOGET ---");

    response.setContentType("text/xml; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    String currentPath = baseDir + typeStr + currentFolderStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);

    File currentDir = new File(currentDirPath);
    if (!currentDir.exists()) {
        currentDir.mkdir();
    }

    Document document = null;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        document = builder.newDocument();
    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    }

    Node root = CreateCommonXml(document, commandStr, typeStr, currentFolderStr,
            request.getContextPath() + currentPath);

    if (debug)
        System.out.println("Command = " + commandStr);

    if (commandStr.equals("GetFolders")) {
        getFolders(currentDir, root, document);
    } else if (commandStr.equals("GetFoldersAndFiles")) {
        getFolders(currentDir, root, document);
        getFiles(currentDir, root, document);
    } else if (commandStr.equals("CreateFolder")) {
        String newFolderStr = request.getParameter("NewFolderName");
        File newFolder = new File(currentDir, newFolderStr);
        String retValue = "110";

        if (newFolder.exists()) {
            retValue = "101";
        } else {
            try {
                boolean dirCreated = newFolder.mkdir();
                if (dirCreated)
                    retValue = "0";
                else
                    retValue = "102";
            } catch (SecurityException sex) {
                retValue = "103";
            }

        }
        setCreateFolderResponse(retValue, root, document);
    }

    document.getDocumentElement().normalize();
    try {
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();

        DOMSource source = new DOMSource(document);

        StreamResult result = new StreamResult(out);
        transformer.transform(source, result);

        if (debug) {
            StreamResult dbgResult = new StreamResult(System.out);
            transformer.transform(source, dbgResult);
            System.out.println("");
            System.out.println("--- END DOGET ---");
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    out.flush();
    out.close();
}

From source file:net.ion.radon.impl.let.webdav.FCKConnectorRestlet.java

protected Document newDocument() {
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {//from  www.jav a 2 s.c o m
        final DocumentBuilder builder = factory.newDocumentBuilder();
        return builder.newDocument();
    } catch (final Exception e) {
        return null;
    }
}

From source file:com.msopentech.odatajclient.engine.performance.BasicPerfTest.java

@Test
public void writeAtomViaLowerlevelLibs() throws ParserConfigurationException, ClassNotFoundException,
        InstantiationException, IllegalAccessException {

    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    final DocumentBuilder builder = factory.newDocumentBuilder();
    final Document doc = builder.newDocument();

    final Element entry = doc.createElement("entry");
    entry.setAttribute("xmlns", "http://www.w3.org/2005/Atom");
    entry.setAttribute("xmlns:m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
    entry.setAttribute("xmlns:d", "http://schemas.microsoft.com/ado/2007/08/dataservices");
    entry.setAttribute("xmlns:gml", "http://www.opengis.net/gml");
    entry.setAttribute("xmlns:georss", "http://www.georss.org/georss");
    doc.appendChild(entry);// ww w  . j ava 2  s  . c om

    final Element category = doc.createElement("category");
    category.setAttribute("term", "Microsoft.Test.OData.Services.AstoriaDefaultService.Customer");
    category.setAttribute("scheme", "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme");
    entry.appendChild(category);

    final Element properties = doc.createElement("m:properties");
    entry.appendChild(properties);

    final Element name = doc.createElement("d:Name");
    name.setAttribute("m:type", "Edm.String");
    name.appendChild(doc.createTextNode("A name"));
    properties.appendChild(name);

    final Element customerId = doc.createElement("d:CustomerId");
    customerId.setAttribute("m:type", "Edm.Int32");
    customerId.appendChild(doc.createTextNode("0"));
    properties.appendChild(customerId);

    final Element bci = doc.createElement("d:BackupContactInfo");
    bci.setAttribute("m:type",
            "Collection(Microsoft.Test.OData.Services.AstoriaDefaultService.ContactDetails)");
    properties.appendChild(bci);

    final Element topelement = doc.createElement("d:element");
    topelement.setAttribute("m:type", "Microsoft.Test.OData.Services.AstoriaDefaultService.ContactDetails");
    bci.appendChild(topelement);

    final Element altNames = doc.createElement("d:AlternativeNames");
    altNames.setAttribute("m:type", "Collection(Edm.String)");
    topelement.appendChild(altNames);

    final Element element1 = doc.createElement("d:element");
    element1.setAttribute("m:type", "Edm.String");
    element1.appendChild(doc.createTextNode("myname"));
    altNames.appendChild(element1);

    final Element emailBag = doc.createElement("d:EmailBag");
    emailBag.setAttribute("m:type", "Collection(Edm.String)");
    topelement.appendChild(emailBag);

    final Element element2 = doc.createElement("d:element");
    element2.setAttribute("m:type", "Edm.String");
    element2.appendChild(doc.createTextNode("myname@mydomain.com"));
    emailBag.appendChild(element2);

    final Element contactAlias = doc.createElement("d:ContactAlias");
    contactAlias.setAttribute("m:type", "Microsoft.Test.OData.Services.AstoriaDefaultService.Aliases");
    topelement.appendChild(contactAlias);

    final Element altNames2 = doc.createElement("d:AlternativeNames");
    altNames2.setAttribute("m:type", "Collection(Edm.String)");
    contactAlias.appendChild(altNames2);

    final Element element3 = doc.createElement("d:element");
    element3.setAttribute("m:type", "Edm.String");
    element3.appendChild(doc.createTextNode("myAlternativeName"));
    altNames2.appendChild(element3);

    final StringWriter writer = new StringWriter();

    final DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance();
    final DOMImplementationLS impl = (DOMImplementationLS) reg.getDOMImplementation("LS");
    final LSSerializer serializer = impl.createLSSerializer();
    final LSOutput lso = impl.createLSOutput();
    lso.setCharacterStream(writer);
    serializer.write(doc, lso);

    assertFalse(writer.toString().isEmpty());
}

From source file:com.fredck.FCKeditor.connector.ConnectorServlet.java

/**
 * Manage the Get requests (GetFolders, GetFoldersAndFiles, CreateFolder).<br>
 * /*from   ww  w .  ja  v  a2  s  . c  o m*/
 * The servlet accepts commands sent in the following format:<br>
 * connector?Command=CommandName&Type=ResourceType&CurrentFolder=FolderPath<br>
 * <br>
 * It execute the command and then return the results to the client in XML
 * format.
 * 
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("ConnectorServlet.doGet");
    if (debug)
        System.out.println("--- BEGIN DOGET ---");

    response.setContentType("text/xml; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    String currentPath = baseDir + typeStr + currentFolderStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);

    File currentDir = new File(currentDirPath);
    if (!currentDir.exists()) {
        currentDir.mkdir();
    }

    Document document = null;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        document = builder.newDocument();
    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    }

    Node root = CreateCommonXml(document, commandStr, typeStr, currentFolderStr,
            request.getContextPath() + currentPath);

    if (debug)
        System.out.println("Command = " + commandStr);

    if (commandStr.equals("GetFolders")) {
        getFolders(currentDir, root, document);
    } else if (commandStr.equals("GetFoldersAndFiles")) {
        getFolders(currentDir, root, document);
        getFiles(currentDir, root, document);
    } else if (commandStr.equals("CreateFolder")) {
        String newFolderStr = request.getParameter("NewFolderName");
        File newFolder = new File(currentDir, newFolderStr);
        String retValue = "110";

        if (newFolder.exists()) {
            retValue = "101";
        } else {
            try {
                boolean dirCreated = newFolder.mkdir();
                if (dirCreated)
                    retValue = "0";
                else
                    retValue = "102";
            } catch (SecurityException sex) {
                retValue = "103";
            }

        }
        setCreateFolderResponse(retValue, root, document);
    }

    document.getDocumentElement().normalize();
    try {
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();

        DOMSource source = new DOMSource(document);

        StreamResult result = new StreamResult(out);
        transformer.transform(source, result);

        if (debug) {
            StreamResult dbgResult = new StreamResult(System.out);
            transformer.transform(source, dbgResult);
            System.out.println("");
            System.out.println("--- END DOGET ---");
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    out.flush();
    out.close();
}

From source file:org.joy.config.Configuration.java

public void save() {
    try {//from  w  w w .j  a  v a2 s . co m
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        Element root = doc.createElement("configuration");
        doc.appendChild(root);

        Element classpathEle = doc.createElement("classpath");
        root.appendChild(classpathEle);
        for (String s : classPathEntries) {
            Element e = doc.createElement("entry");
            e.appendChild(doc.createTextNode(s));
            classpathEle.appendChild(e);
        }

        Element connectionsEle = doc.createElement("connections");
        root.appendChild(connectionsEle);
        for (DatabaseElement d : connectionHistory) {
            writeDatabase(connectionsEle, d);
        }

        Element e = doc.createElement("tagertProject");
        e.appendChild(doc.createTextNode(tagertProject));
        root.appendChild(e);

        e = doc.createElement("basePackage");
        e.appendChild(doc.createTextNode(basePackage));
        root.appendChild(e);

        e = doc.createElement("moduleName");
        e.appendChild(doc.createTextNode(moduleName));
        root.appendChild(e);

        Element templatesEle = doc.createElement("templates");
        root.appendChild(templatesEle);
        for (TemplateElement t : templates) {
            writeTemplate(templatesEle, t);
        }

        // Write the file
        DOMSource ds = new DOMSource(doc);
        StreamResult sr = new StreamResult(new File(configurationFile));
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.METHOD, "xml");
        t.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.setOutputProperty(OutputKeys.STANDALONE, "yes");
        t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        t.transform(ds, sr);
    } catch (Exception e) {
        LOGGER.info(e.getMessage(), e);
    }
}

From source file:com.photon.phresco.plugins.xcode.Instrumentation.java

private void generateXMLReport(String location) {

    try {/* ww w .j  a va 2 s .com*/
        String startTime = "";
        int total, pass, fail;
        total = pass = fail = 0;
        config = new XMLPropertyListConfiguration(location);
        ArrayList list = (ArrayList) config.getRoot().getChild(0).getValue();
        String key;

        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.newDocument();

        Element root = doc.createElement(XMLConstants.TESTSUITES_NAME);
        doc.appendChild(root);
        Element testSuite = doc.createElement(XMLConstants.TESTSUITE_NAME);
        testSuite.setAttribute(XMLConstants.NAME, "FunctionalTestSuite");
        root.appendChild(testSuite);

        for (Object object : list) {

            XMLPropertyListConfiguration config = (XMLPropertyListConfiguration) object;

            startTime = config.getRoot().getChild(2).getValue().toString();

            break;
        }

        for (Object object : list) {

            XMLPropertyListConfiguration config = (XMLPropertyListConfiguration) object;

            ConfigurationNode con = config.getRoot().getChild(0);
            key = con.getName();

            if (key.equals(XMLConstants.LOGTYPE) && con.getValue().equals(XMLConstants.PASS)) {
                pass++;
                total++;
                Element child1 = doc.createElement(XMLConstants.TESTCASE_NAME);
                child1.setAttribute(XMLConstants.NAME, (String) config.getRoot().getChild(1).getValue());
                child1.setAttribute(XMLConstants.RESULT, (String) con.getValue());

                String endTime = config.getRoot().getChild(2).getValue().toString();

                long differ = getTimeDiff(startTime, endTime);
                startTime = endTime;
                child1.setAttribute(XMLConstants.TIME, differ + "");
                testSuite.appendChild(child1);
            } else if (key.equals(XMLConstants.LOGTYPE) && con.getValue().equals(XMLConstants.ERROR)) {
                fail++;
                total++;
                Element child1 = doc.createElement(XMLConstants.TESTCASE_NAME);
                child1.setAttribute(XMLConstants.NAME, (String) config.getRoot().getChild(1).getValue());
                child1.setAttribute(XMLConstants.RESULT, (String) con.getValue());

                String endTime = config.getRoot().getChild(2).getValue().toString();

                long differ = getTimeDiff(startTime, endTime);
                startTime = endTime;
                child1.setAttribute(XMLConstants.TIME, differ + "");
                testSuite.appendChild(child1);
            }

        }

        testSuite.setAttribute(XMLConstants.TESTS, String.valueOf(total));
        testSuite.setAttribute(XMLConstants.SUCCESS, String.valueOf(pass));
        testSuite.setAttribute(XMLConstants.FAILURES, String.valueOf(fail));

        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.INDENT, "yes");

        File file = new File(project.getBasedir().getAbsolutePath() + File.separator + xmlResult);
        Writer bw = new BufferedWriter(new FileWriter(file));
        StreamResult result = new StreamResult(bw);
        DOMSource source = new DOMSource(doc);
        trans.transform(source, result);

    } catch (Exception e) {
        getLog().error("Interrupted while generating XML file");
    }
}

From source file:eu.eidas.auth.engine.SAMLEngineUtils.java

/**
*
* @param xmlObj// w ww.  ja va  2 s  .co m
* @return a string containing the xml representation of the entityDescriptor
*/
public static String serializeObject(XMLObject xmlObj) {
    StringWriter stringWriter = new StringWriter();
    String stringRepresentation = "";
    try {
        DocumentBuilder builder;
        DocumentBuilderFactory factory = DocumentBuilderFactoryUtil.getSecureDocumentBuilderFactory();

        builder = factory.newDocumentBuilder();
        Document document = builder.newDocument();
        Marshaller out = Configuration.getMarshallerFactory().getMarshaller(xmlObj);
        out.marshall(xmlObj, document);

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        StreamResult streamResult = new StreamResult(stringWriter);
        DOMSource source = new DOMSource(document);
        transformer.transform(source, streamResult);
    } catch (ParserConfigurationException pce) {
        LOG.info("ERROR : parser error", pce.getMessage());
        LOG.debug("ERROR : parser error", pce);
    } catch (TransformerConfigurationException tce) {
        LOG.info("ERROR : transformer configuration error", tce.getMessage());
        LOG.debug("ERROR : transformer configuration error", tce);
    } catch (TransformerException te) {
        LOG.info("ERROR : transformer error", te.getMessage());
        LOG.debug("ERROR : transformer error", te);
    } catch (MarshallingException me) {
        LOG.info("ERROR : marshalling error", me.getMessage());
        LOG.debug("ERROR : marshalling error", me);
    } finally {
        try {
            stringWriter.close();
            stringRepresentation = stringWriter.toString();
        } catch (IOException ioe) {
            LOG.warn("ERROR when closing the marshalling stream {}", ioe);
        }
    }
    return stringRepresentation;
}

From source file:com.zacwolf.commons.wbxcon._WBXCONfactory.java

/**
 * Synchronizes the WBXCON User profile data with the <code>WBXCONuser</code> object
 * @param account      a <code>WBXaccount</code> object
 * @throws WBXCONexception//w w  w .jav  a  2s .c  o m
 * @throws ParserConfigurationException
 * @throws TransformerException
 * @throws NullPointerException
 */
public WBXCONuser accountSyncProfile(final WBXCONuser account, final boolean clearFirst)
        throws WBXCONexception, NullPointerException, TransformerException, ParserConfigurationException {
    if (clearFirst)
        this.org.restapiAccountRemoveEXTchildNode(account.getWBXUID(), "WBX/profile");

    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    final DocumentBuilder parser = factory.newDocumentBuilder();
    final Document doc = parser.newDocument();
    this.org.restapiAccountModify(account.id, "<ext><WBX>"
            + WBXCONorg.documentToXMLstring(account.getWBX().getPROFILE().marshallXML(doc)) + "</WBX></ext>");
    return accountGet(account.userName);
}

From source file:com.baobao121.baby.common.ConnectorServlet.java

/**
 * Manage the Get requests (GetFolders, GetFoldersAndFiles, CreateFolder).<br>
 * //from w  w w . j ava 2 s .c  om
 * The servlet accepts commands sent in the following format:<br>
 * connector?Command=CommandName&Type=ResourceType&CurrentFolder=FolderPath<br>
 * <br>
 * It execute the command and then return the results to the client in XML
 * format.
 * 
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (debug)
        System.out.println("--- BEGIN DOGET ---");

    response.setContentType("text/xml; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    String currentPath = baseDir + typeStr + currentFolderStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);

    File currentDir = new File(currentDirPath);
    if (!currentDir.exists()) {
        currentDir.mkdir();
    }

    Document document = null;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        document = builder.newDocument();
    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    }

    Node root = CreateCommonXml(document, commandStr, typeStr, currentFolderStr,
            request.getContextPath() + currentPath);

    if (debug)
        System.out.println("Command = " + commandStr);

    if (commandStr.equals("GetFolders")) {
        getFolders(currentDir, root, document);
    } else if (commandStr.equals("GetFoldersAndFiles")) {
        getFolders(currentDir, root, document);
        getFiles(currentDir, root, document);
    } else if (commandStr.equals("CreateFolder")) {
        String newFolderStr = request.getParameter("NewFolderName");
        File newFolder = new File(currentDir, newFolderStr);
        String retValue = "110";

        if (newFolder.exists()) {
            retValue = "101";
        } else {
            try {
                boolean dirCreated = newFolder.mkdir();
                if (dirCreated)
                    retValue = "0";
                else
                    retValue = "102";
            } catch (SecurityException sex) {
                retValue = "103";
            }

        }
        setCreateFolderResponse(retValue, root, document);
    }

    document.getDocumentElement().normalize();
    try {
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();

        DOMSource source = new DOMSource(document);

        StreamResult result = new StreamResult(out);
        transformer.transform(source, result);

        if (debug) {
            StreamResult dbgResult = new StreamResult(System.out);
            transformer.transform(source, dbgResult);
            System.out.println("");
            System.out.println("--- END DOGET ---");
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    out.flush();
    out.close();
}