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:ConfigFiles.java

public static void saveXML(boolean blank, String filename) {
    boolean saved = true;
    try {// w  ww . j a v a 2  s.  c  o  m
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        DOMSource source = new DOMSource(document);
        Comment simpleComment = document.createComment(
                "\n Master config file for TSC.\n \n Logs" + " Path: Where CE and PE write their getLogs()."
                        + " Reports Path: Where all reports are saved.\n "
                        + "Test Suite Config: All info about the current " + "Test Suite (Test Plan).\n");
        document.appendChild(simpleComment);
        Element root = document.createElement("Root");
        document.appendChild(root);
        Element rootElement = document.createElement("FileType");
        root.appendChild(rootElement);
        rootElement.appendChild(document.createTextNode("config"));
        try {
            addTag("CentralEnginePort", tceport.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("CentralEnginePort", "", root, blank, document);
        }
        //             try{addTag("ResourceAllocatorPort",traPort.getText(),root,blank,document);}
        //             catch(Exception e){addTag("ResourceAllocatorPort","",root,blank,document);}
        //             try{addTag("HttpServerPort",thttpPort.getText(),root,blank,document);}
        //             catch(Exception e){addTag("HttpServerPort","",root,blank,document);}
        try {
            addTag("TestCaseSourcePath", ttcpath.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("TestCaseSourcePath", "", root, blank, document);
        }
        try {
            addTag("LibsPath", libpath.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("LibsPath", "", root, blank, document);
        }
        try {
            addTag("UsersPath", tUsers.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("UsersPath", "", root, blank, document);
        }
        try {
            addTag("PredefinedSuitesPath", tSuites.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("PredefinedSuitesPath", "", root, blank, document);
        }

        try {
            addTag("ArchiveLogsPath", tsecondarylog.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("ArchiveLogsPath", "", root, blank, document);
        }
        try {
            addTag("ArchiveLogsPathActive", logsenabled.isSelected() + "", root, blank, document);
        } catch (Exception e) {
            addTag("ArchiveLogsPath", "", root, blank, document);
        }

        try {
            addTag("LogsPath", tlog.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("LogsPath", "", root, blank, document);
        }
        rootElement = document.createElement("LogFiles");
        root.appendChild(rootElement);
        try {
            addTag("logRunning", trunning.getText(), rootElement, blank, document);
        } catch (Exception e) {
            addTag("logRunning", "", rootElement, blank, document);
        }
        try {
            addTag("logDebug", tdebug.getText(), rootElement, blank, document);
        } catch (Exception e) {
            addTag("logDebug", "", rootElement, blank, document);
        }
        try {
            addTag("logSummary", tsummary.getText(), rootElement, blank, document);
        } catch (Exception e) {
            addTag("logSummary", "", rootElement, blank, document);
        }
        try {
            addTag("logTest", tinfo.getText(), rootElement, blank, document);
        } catch (Exception e) {
            addTag("logTest", "", rootElement, blank, document);
        }
        try {
            addTag("logCli", tcli.getText(), rootElement, blank, document);
        } catch (Exception e) {
            addTag("logCli", "", rootElement, blank, document);
        }
        try {
            addTag("DbConfigFile", tdbfile.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("DbConfigFile", "", root, blank, document);
        }
        try {
            addTag("EpNames", tepid.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("EpNames", "", root, blank, document);
        }
        try {
            addTag("EmailConfigFile", temailfile.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("EmailConfigFile", "", root, blank, document);
        }
        try {
            addTag("GlobalParams", tglobalsfile.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("GlobalParams", "", root, blank, document);
        }
        try {
            addTag("TestConfigPath", testconfigpath.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("TestConfigPath", "", root, blank, document);
        }
        String temp;
        if (blank)
            temp = "fwmconfig";
        else
            temp = filename;
        File file = new File(RunnerRepository.temp + RunnerRepository.getBar() + "Twister"
                + RunnerRepository.getBar() + temp + ".xml");
        Result result = new StreamResult(file);
        transformer.transform(source, result);
        System.out.println("Saving to: " + RunnerRepository.USERHOME + "/twister/config/");
        FileInputStream in = new FileInputStream(file);
        RunnerRepository.uploadRemoteFile(RunnerRepository.USERHOME + "/twister/config/", in, file.getName());
    } catch (ParserConfigurationException e) {
        System.out
                .println("DocumentBuilder cannot be created which" + " satisfies the configuration requested");
        saved = false;
    } catch (TransformerConfigurationException e) {
        System.out.println("Could not create transformer");
        saved = false;
    } catch (Exception e) {
        e.printStackTrace();
        saved = false;
    }
    if (saved) {
        CustomDialog.showInfo(JOptionPane.INFORMATION_MESSAGE, RunnerRepository.window, "Successful",
                "File successfully saved");
    } else {
        CustomDialog.showInfo(JOptionPane.WARNING_MESSAGE, RunnerRepository.window.mainpanel.p4.getConfig(),
                "Warning", "File could not be saved ");
    }
}

From source file:com.occamlab.te.parsers.ImageParser.java

private static Document parse(InputStream source, Element instruction, PrintWriter logger) throws Exception {
    ImageReader reader;//from  w  w w.  jav a 2s .c  om
    try {
        ImageInputStream iis = ImageIO.createImageInputStream(source);
        reader = ImageIO.getImageReaders(iis).next();
        reader.setInput(iis);
    } catch (Exception e) {
        logger.println("No image handlers available for the data stream. " + e.getMessage());
        throw e;
    }

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    t.transform(new DOMSource(instruction), new DOMResult(doc));

    Element new_instruction = doc.getDocumentElement();

    int framesRead = 0;
    boolean containsFrames = false;
    Element framesElement = null;
    Element metadataElement = null;

    NodeList nodes = new_instruction.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // System.out.println(node.getLocalName());
            if (node.getLocalName().equals("type")) {
                node.setTextContent(reader.getFormatName().toLowerCase());
            } else if (node.getLocalName().equals("frames")) {
                framesElement = (Element) node;
                containsFrames = true;
            } else if (node.getLocalName().equals("metadata")) {
                metadataElement = (Element) node;
            } else if (node.getLocalName().equals("frame")) {
                int frame;
                String frameStr = ((Element) node).getAttribute("num");
                if (frameStr.length() == 0) {
                    frame = framesRead;
                    framesRead++;
                    ((Element) node).setAttribute("num", Integer.toString(frame));
                } else {
                    frame = Integer.parseInt(frameStr);
                    framesRead = frame + 1;
                }
                processFrame(reader, frame, node.getChildNodes(), logger);
                containsFrames = true;
            }
        }
    }

    if (containsFrames) {
        if (metadataElement != null) {
            IIOMetadata metadata = reader.getStreamMetadata();
            if (metadata != null) {
                String format = metadataElement.getAttribute("format");
                if (format.length() == 0) {
                    format = metadata.getNativeMetadataFormatName();
                }
                Node tree = metadata.getAsTree(format);
                t.transform(new DOMSource(tree), new DOMResult(metadataElement));
            }
        }
        if (framesElement != null) {
            boolean allowSearch = !reader.isSeekForwardOnly();
            int frames = reader.getNumImages(allowSearch);
            if (frames == -1) {
                try {
                    while (true) {
                        reader.read(framesRead);
                        framesRead++;
                    }
                } catch (Exception e) {
                    jlogger.log(Level.SEVERE, "", e);

                    frames = framesRead + 1;
                }
            }
            framesElement.setTextContent(Integer.toString(frames));
        }
    } else {
        processFrame(reader, 0, nodes, logger);
        framesRead = 1;
    }

    // t.transform(new DOMSource(doc), new StreamResult(System.out));
    return doc;
}

From source file:com.occamlab.te.parsers.ImageParser.java

private static Node processFrame(ImageReader reader, int frame, NodeList nodes, PrintWriter logger)
        throws Exception {
    if (nodes.getLength() == 0) {
        return null;
    }/* www  .  j ava2s  . co  m*/
    String formatName = reader.getFormatName().toLowerCase(); // 2011-09-08
                                                              // PwD
    BufferedImage image = reader.read(frame);

    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // System.out.println(node.getLocalName());
            if (node.getLocalName().equals("type")) {
                node.setTextContent(formatName); // 2011-09-08 PwD was
                                                 // reader.getFormatName().toLowerCase()
            } else if (node.getLocalName().equals("height")) {
                node.setTextContent(Integer.toString(image.getHeight()));
            } else if (node.getLocalName().equals("width")) {
                node.setTextContent(Integer.toString(image.getWidth()));
            } else if (node.getLocalName().equals("metadata")) {
                try { // 2011--08-23 PwD
                    IIOMetadata metadata = reader.getImageMetadata(frame);
                    if (metadata != null) {
                        String format = ((Element) node).getAttribute("format");
                        if (format.length() == 0) {
                            format = metadata.getNativeMetadataFormatName();
                        }
                        Node tree = metadata.getAsTree(format);
                        TransformerFactory tf = TransformerFactory.newInstance();
                        Transformer t = tf.newTransformer();
                        t.transform(new DOMSource(tree), new DOMResult(node));
                    }
                } catch (javax.imageio.IIOException e) { // 2011--08-23 PwD
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    Document doc = db.newDocument();
                    String format = reader.getFormatName().toLowerCase();
                    String formatEltName = "javax_imageio_" + format + "_1.0";
                    Element formatElt = doc.createElement(formatEltName);
                    TransformerFactory tf = TransformerFactory.newInstance();
                    Transformer t = tf.newTransformer();
                    t.transform(new DOMSource(formatElt), new DOMResult(node));
                }
            } else if (node.getLocalName().equals("model")) {
                int imagetype = -1;
                String model = ((Element) node).getAttribute("value");
                if (model.equals("MONOCHROME")) {
                    imagetype = BufferedImage.TYPE_BYTE_BINARY;
                } else if (model.equals("GRAY")) {
                    imagetype = BufferedImage.TYPE_BYTE_GRAY;
                } else if (model.equals("RGB")) {
                    imagetype = BufferedImage.TYPE_3BYTE_BGR;
                } else if (model.equals("ARGB")) {
                    imagetype = BufferedImage.TYPE_4BYTE_ABGR;
                } else {
                    model = "CUSTOM";
                }
                ((Element) node).setAttribute("value", model);
                BufferedImage buffImage = image;
                if (image.getType() != imagetype && imagetype != -1) {
                    buffImage = new BufferedImage(image.getWidth(), image.getHeight(), imagetype);
                    Graphics2D g2 = buffImage.createGraphics();
                    ImageTracker tracker = new ImageTracker();
                    boolean done = g2.drawImage(image, 0, 0, tracker);
                    if (!done) {
                        while (!tracker.done) {
                            sleep(50);
                        }
                    }
                }
                processBufferedImage(buffImage, formatName, node.getChildNodes());
            } else if (node.getLocalName().equals("transparency")) { // 2011-08-24
                                                                     // PwD
                int transparency = image.getTransparency();
                String transparencyName = null;
                switch (transparency) {
                case Transparency.OPAQUE: {
                    transparencyName = "Opaque";
                    break;
                }
                case Transparency.BITMASK: {
                    transparencyName = "Bitmask";
                    break;
                }
                case Transparency.TRANSLUCENT: {
                    transparencyName = "Translucent";
                    break;
                }
                default: {
                    transparencyName = "Unknown";
                }
                }
                node.setTextContent(transparencyName);

            } else if (node.getLocalName().equals("base64Data")) { // 2011-09-08
                                                                   // PwD
                String base64Data = getBase64Data(image, formatName, node);
                node.setTextContent(base64Data);
            } else {
                logger.println("ImageParser Error: Invalid tag " + node.getNodeName());
            }
        }
    }
    return null;
}

From source file:ie.nuim.cs.dri.metadata.WebSearch.java

/**
 *
 * @param doi/* www  .  ja v  a 2  s  . c  o m*/
 * @param ti
 * @param au
 * @param pubYear
 * @param xmlFile
 */
public static void createROS(String doi, String ti, String au, String pubYear, String xmlFile) {
    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = null;
        try {
            docBuilder = docFactory.newDocumentBuilder();

        } catch (ParserConfigurationException ex) {
            Logger.getLogger(MetadataExtractor.class.getName()).log(Level.SEVERE, null, ex);
        }
        org.w3c.dom.Document rosDoc = docBuilder.newDocument();
        org.w3c.dom.Element rootElement = rosDoc.createElement("ROS");
        rosDoc.appendChild((rootElement));
        org.w3c.dom.Element DOI = rosDoc.createElement("DOI");
        org.w3c.dom.Element title = rosDoc.createElement("Title");
        org.w3c.dom.Element authors = rosDoc.createElement("Authors");
        org.w3c.dom.Element institution = rosDoc.createElement("Institution");
        org.w3c.dom.Element year = rosDoc.createElement("Year");
        org.w3c.dom.Element publication = rosDoc.createElement("Publication");
        org.w3c.dom.Element conference = rosDoc.createElement("Conference");

        rootElement.appendChild(DOI);
        rootElement.appendChild(title);
        rootElement.appendChild(authors);
        rootElement.appendChild(institution);
        rootElement.appendChild(year);
        rootElement.appendChild(publication);
        rootElement.appendChild(conference);

        DOI.appendChild(rosDoc.createTextNode(doi));
        title.appendChild(rosDoc.createTextNode(ti));
        authors.appendChild(rosDoc.createTextNode(au));
        year.appendChild(rosDoc.createTextNode(pubYear));

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(rosDoc);
        xmlFile = xmlFile.replace(".xml", "MD.xml");
        System.out.println("Writing to:\n" + xmlFile);
        StreamResult result = new StreamResult(new File(xmlFile));
        transformer.transform(source, result);
        //result = new StreamResult(System.out);

    } catch (TransformerException ex) {
        Logger.getLogger(MetadataExtractor.class.getName()).log(Level.SEVERE, null, ex);
    }

}

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 a v a  2s .co m*/
        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

/**
 * Queries the CoNE service and transforms the result into a DOM node.
 * /*from   w  ww. j a va2s .  c  om*/
 * @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 {
        System.out.println("queryConeExact: " + model);

        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/rdf:value=\"" + URLEncoder.encode(identifier, "UTF-8")
                + "\"&escidoc:position/eprints:affiliatedInstitution=" + URLEncoder.encode(ou, "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);
        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")));
            Set<String> oldIds = new HashSet<String>();
            for (String result : results) {
                if (!"".equals(result.trim())) {
                    String id = result.split("\\|")[1];
                    if (!oldIds.contains(id)) {
                        GetMethod detailMethod = new GetMethod(id + "?format=rdf&eSciDocUserHandle=" + "TODO");

                        ProxyHelper.setProxy(client, detailsUrl.replace("$1", id));
                        client.executeMethod(detailMethod);
                        logger.info("CoNE query: " + id + "?format=rdf&eSciDocUserHandle=" + "TODO"
                                + " 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.");
        return null;
        //throw new RuntimeException(e);
    }
}

From source file:com.twentyn.patentExtractor.PatentDocumentFeatures.java

/**
 * Extracts sentence nodes from a POS-tagger XML document.  These sentences are intended to provide some notion of
 * locality for identified chemical entities.
 *
 * @param docBuilder A document builder to use when producing single-sentence XML documents.
 * @param doc        The POS-tagger XML document from which to extract sentences.
 * @return A list of single-sentence documents.
 * @throws ParserConfigurationException// w  ww .  j av  a 2  s. com
 * @throws XPathExpressionException
 */
private static List<Document> findSentences(DocumentBuilder docBuilder, Document doc)
        throws ParserConfigurationException, XPathExpressionException {
    if (doc != null) {
        // TODO: is there a more efficient yet still safe way to do this?
        XPath xpath = Util.getXPathFactory().newXPath();
        // TODO: get rid of this inline xpath compilation, run during setup.
        NodeList nodes = (NodeList) xpath.evaluate(SENTENCE_PATH, doc, XPathConstants.NODESET);

        List<Document> docList = new ArrayList<>(nodes.getLength());
        for (int i = 0; i < nodes.getLength(); i++) {
            Node n = nodes.item(i);

            /* With help from:
             * http://examples.javacodegeeks.com/core-java/xml/dom/copy-nodes-subtree-from-one-dom-document-to-another/ */
            org.w3c.dom.Document newDoc = docBuilder.newDocument();
            Element rootElement = newDoc.createElement(SENTENCE_DOC_HEADER);
            Node newNode = newDoc.importNode(n, true);
            rootElement.appendChild(newNode);
            newDoc.appendChild(rootElement);
            docList.add(newDoc);
        }
        return docList;
    } else {
        // TODO: log here.
        return new ArrayList<>(0);
    }
}

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

/**
 * Queries the CoNE service and transforms the result into a DOM node.
 * //from   w  w w . j  a  va2s . co  m
 * @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 {
        System.out.println("queryConeExact: " + model);

        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:title=\"" + URLEncoder.encode(name, "UTF-8")
                + "\"&escidoc:position/eprints:affiliatedInstitution=" + URLEncoder.encode(ou, "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);
        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&dcterms:alternative=\"" + URLEncoder.encode(name, "UTF-8")
                    + "\"&escidoc:position/eprints:affiliatedInstitution=" + 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)) {
                            GetMethod detailMethod = new GetMethod(
                                    id + "?format=rdf&eSciDocUserHandle=" + "TODO");

                            ProxyHelper.setProxy(client, detailsUrl.replace("$1", id));
                            client.executeMethod(detailMethod);
                            logger.info("CoNE query: " + id + "?format=rdf&eSciDocUserHandle=" + "TODO"
                                    + " 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.");
        return null;
        //throw new RuntimeException(e);
    }
}

From source file:com.syrup.storage.xml.XmlFactory.java

/**
 * Returns a <code>Document</code> object representing a ???
 * /*from ww w . jav  a2  s . c  o  m*/
 * @param mockServices List of services to convert into an xml document
  * @return <code>Document</code> object representing a cXML order request
 */
public Document getAsDocument(IStorage store) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);

        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        Document document = docBuilder.newDocument();

        XmlFileConfigurationGenerator xmlGeneratorSupport = new XmlFileConfigurationGenerator();

        Element xmlRootElement = xmlGeneratorSupport.getElement(document, store);
        document.appendChild(xmlRootElement);

        return document;
    } catch (ParserConfigurationException pce) {
        System.out.println(":" + pce.getMessage());

        return null;
    }
}

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>/*from  ww w  .  ja va2  s .  c om*/
 *   <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);
    }
}