Example usage for javax.xml.transform OutputKeys ENCODING

List of usage examples for javax.xml.transform OutputKeys ENCODING

Introduction

In this page you can find the example usage for javax.xml.transform OutputKeys ENCODING.

Prototype

String ENCODING

To view the source code for javax.xml.transform OutputKeys ENCODING.

Click Source Link

Document

encoding = string.

Usage

From source file:com.francelabs.datafari.servlets.admin.FieldWeight.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response) Checks if the files still exist Used to modify the weight of
 *      a field//  ww w .  j a  va 2s.  c  om
 */
@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    try {
        if ((config == null) || !new File(env + File.separator + "solrconfig.xml").exists()) {// If
            // the
            // files
            // did
            // not
            // existed
            // when
            // the
            // constructor
            // was
            // runned
            if (!new File(env + File.separator + "solrconfig.xml").exists()) {
                LOGGER.error(
                        "Error while opening the configuration file, solrconfig.xml, in FieldWeight doPost, please make sure this file exists at "
                                + env + "conf/ . Error 69029"); // If
                // not
                // an
                // error
                // is
                // printed
                final PrintWriter out = response.getWriter();
                out.append(
                        "Error while opening the configuration file, please retry, if the problem persists contact your system administrator. Error Code : 69029");
                out.close();
                return;
            } else {
                config = new File(env + File.separator + "solrconfig.xml");
            }
        }

        if (customSearchHandler == null) {
            if (new File(
                    env + File.separator + "customs_solrconfig" + File.separator + "custom_search_handler.incl")
                            .exists()) {
                customSearchHandler = new File(env + File.separator + "customs_solrconfig" + File.separator
                        + "custom_search_handler.incl");
            }
        }

        try {
            final String type = request.getParameter("type");

            if (searchHandler == null) {
                findSearchHandler();
            }

            if (!usingCustom) { // The custom search handler is not used.
                // That means that the current config must
                // be commented in the solrconfig.xml file
                // and the modifications must be saved in
                // the custom search handler file

                // Get the content of solrconfig.xml file as a string
                String configContent = FileUtils.getFileContent(config);

                // Retrieve the searchHandler from the configContent
                final Node originalSearchHandler = XMLUtils.getSearchHandlerNode(config);
                final String strSearchHandler = XMLUtils.nodeToString(originalSearchHandler);

                // Create a commented equivalent of the strSearchHandler
                final String commentedSearchHandler = "<!--" + strSearchHandler + "-->";

                // Replace the searchHandler in the solrconfig.xml file by
                // the commented version
                configContent = configContent.replace(strSearchHandler, commentedSearchHandler);
                FileUtils.saveStringToFile(config, configContent);

                // create the new custom_search_handler document
                doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

                // Import the search handler node from the solrconfig doc to
                // the custom search handler doc
                searchHandler = doc.importNode(searchHandler, true);

                // Make the new node an actual item in the target document
                searchHandler = doc.appendChild(searchHandler);

                final Node n = run(searchHandler.getChildNodes(), type);
                childList = n.getParentNode().getChildNodes();

                // Save the custom_search_handler.incl file
                XMLUtils.docToFile(doc, customSearchHandler);
            }

            if (childList == null) {
                final Node n = run(searchHandler.getChildNodes(), type);
                childList = n.getParentNode().getChildNodes();
            }

            for (int i = 0; i < childList.getLength(); i++) { // Get the str
                // node
                final Node n = childList.item(i);
                if (n.getNodeName().equals("str")) {
                    String name = ""; // Get it's attributes
                    final NamedNodeMap map = n.getAttributes();
                    for (int j = 0; j < map.getLength(); j++) {
                        if (map.item(j).getNodeName().equals("name")) {// Get
                            // the
                            // name
                            name = map.item(j).getNodeValue();
                        }
                    }
                    if (name.equals(type)) { // If it's pf or qf according
                        // to what the user selected
                        // Get the parameters
                        final String field = request.getParameter("field").toString();
                        final String value = request.getParameter("value").toString();
                        final String text = n.getTextContent(); // Get the
                        // value of
                        // the node,
                        // Search for the requested field, if it is there
                        // return the weight, if not return 0
                        final int index = text.indexOf(field + "^");
                        if (index != -1) { // If the field is already
                            // weighted
                            final int pas = field.length() + 1;
                            final String textCut = text.substring(index + pas);
                            if (value.equals("0")) { // If the user entered
                                // 0
                                if (textCut.indexOf(" ") == -1) {
                                    // field is
                                    // the last
                                    // one then
                                    // we just
                                    // cut the
                                    // end of
                                    // the text
                                    // content
                                    n.setTextContent((text.substring(0, index)).trim());
                                } else {
                                    // the field and the part after
                                    n.setTextContent((text.substring(0, index)
                                            + text.substring(index + pas + textCut.indexOf(" "))).trim());
                                }
                            } else { // If the user typed any other values
                                if (textCut.indexOf(" ") == -1) {
                                    n.setTextContent(text.substring(0, index + pas) + value);
                                } else {
                                    n.setTextContent(text.substring(0, index + pas) + value
                                            + text.substring(index + pas + textCut.indexOf(" ")));
                                }
                            }
                        } else { // If it's not weighted
                            if (!value.equals("0")) {
                                // append the field and
                                // it's value
                                n.setTextContent((n.getTextContent() + " " + field + "^" + value).trim());
                            }
                        }
                        break;
                    }
                }
            }
            // Apply the modifications
            final TransformerFactory transformerFactory = TransformerFactory.newInstance();
            final Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            final DOMSource source = new DOMSource(searchHandler);
            final StreamResult result = new StreamResult(customSearchHandler);
            transformer.transform(source, result);

        } catch (final TransformerException e) {
            LOGGER.error(
                    "Error while modifying the solrconfig.xml, in FieldWeight doPost, pls make sure the file is valid. Error 69030",
                    e);
            final PrintWriter out = response.getWriter();
            out.append(
                    "Error while modifying the config file, please retry, if the problem persists contact your system administrator. Error Code : 69030");
            out.close();
            return;
        }

    } catch (final Exception e) {
        final PrintWriter out = response.getWriter();
        out.append(
                "Something bad happened, please retry, if the problem persists contact your system administrator. Error code : 69511");
        out.close();
        LOGGER.error("Unindentified error in FieldWeight doPost. Error 69511", e);
    }
}

From source file:main.java.vasolsim.common.file.ExamBuilder.java

/**
 * writes an editable, unlocked exam to a file
 *
 * @param exam      the exam to be written
 * @param examFile  the target file/*from w  w w . j  av  a  2  s . c o m*/
 * @param overwrite if an existing file can be overwritten
 *
 * @return if the file write was successful
 *
 * @throws VaSolSimException
 */
public static boolean writeRaw(@Nonnull Exam exam, @Nonnull File examFile, boolean overwrite)
        throws VaSolSimException {
    /*
     * check the file creation status and handle it
     */
    //if it exists
    if (examFile.isFile()) {
        //can't overwrite
        if (!overwrite) {
            throw new VaSolSimException(ERROR_MESSAGE_FILE_ALREADY_EXISTS);
        }
        //can overwrite, clear the existing file
        else {
            PrintWriter printWriter;
            try {
                printWriter = new PrintWriter(examFile);
            } catch (FileNotFoundException e) {
                throw new VaSolSimException(ERROR_MESSAGE_FILE_NOT_FOUND_AFTER_INTERNAL_CHECK);
            }

            printWriter.print("");
            printWriter.close();
        }
    }
    //no file, create one
    else {
        if (!examFile.getParentFile().isDirectory() && !examFile.getParentFile().mkdirs()) {
            throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_DIRS);
        }

        try {
            if (!examFile.createNewFile()) {
                throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_FILE);
            }
        } catch (IOException e) {
            throw new VaSolSimException(ERROR_MESSAGE_CREATE_FILE_EXCEPTION);
        }
    }

    /*
     * initialize the document
     */
    Document examDoc;
    Transformer examTransformer;
    try {
        examDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

        examTransformer = TransformerFactory.newInstance().newTransformer();
        examTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
        examTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
        examTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        examTransformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd");
        examTransformer.setOutputProperty(INDENTATION_KEY, "4");
    } catch (ParserConfigurationException e) {
        throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_XML_PARSER_INITIALIZATION_EXCEPTION, e);
    } catch (TransformerConfigurationException e) {
        throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_TRANSFORMER_CONFIGURATION, e);
    }

    /*
     * build exam info
     */
    Element root = examDoc.createElement(XML_ROOT_ELEMENT_NAME);
    examDoc.appendChild(root);

    Element info = examDoc.createElement(XML_INFO_ELEMENT_NAME);
    root.appendChild(info);

    //exam info
    GenericUtils.appendSubNode(XML_TEST_NAME_ELEMENT_NAME, exam.getTestName(), info, examDoc);
    GenericUtils.appendSubNode(XML_AUTHOR_NAME_ELEMENT_NAME, exam.getAuthorName(), info, examDoc);
    GenericUtils.appendSubNode(XML_SCHOOL_NAME_ELEMENT_NAME, exam.getSchoolName(), info, examDoc);
    GenericUtils.appendSubNode(XML_PERIOD_NAME_ELEMENT_NAME, exam.getPeriodName(), info, examDoc);

    //start security xml section
    Element security = examDoc.createElement(XML_SECURITY_ELEMENT_NAME);
    root.appendChild(security);

    GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_ELEMENT_NAME,
            Boolean.toString(exam.isReportingStats()), security, examDoc);
    GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_STANDALONE_ELEMENT_NAME,
            Boolean.toString(exam.isReportingStatsStandalone()), security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_DESTINATION_EMAIL_ADDRESS_ELEMENT_NAME,
            exam.getStatsDestinationEmail(), security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_EMAIL_ADDRESS_ELEMENT_NAME, exam.getStatsSenderEmail(),
            security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_ADDRESS_ELEMENT_NAME,
            exam.getStatsSenderSMTPAddress(), security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_PORT_ELEMENT_NAME,
            Integer.toString(exam.getStatsSenderSMTPPort()), security, examDoc);

    ArrayList<QuestionSet> questionSets = exam.getQuestionSets();
    if (GenericUtils.verifyQuestionSetsIntegrity(questionSets)) {
        for (int setsIndex = 0; setsIndex < questionSets.size(); setsIndex++) {
            QuestionSet qSet = questionSets.get(setsIndex);

            Element qSetElement = examDoc.createElement(XML_QUESTION_SET_ELEMENT_NAME);
            root.appendChild(qSetElement);

            GenericUtils.appendSubNode(XML_QUESTION_SET_ID_ELEMENT_NAME, Integer.toString(setsIndex + 1),
                    qSetElement, examDoc);
            GenericUtils.appendSubNode(XML_QUESTION_SET_NAME_ELEMENT_NAME,
                    (qSet.getName() == null || qSet.getName().equals("")) ? "Question Set " + (setsIndex + 1)
                            : qSet.getName(),
                    qSetElement, examDoc);
            GenericUtils.appendSubNode(XML_QUESTION_SET_RESOURCE_TYPE_ELEMENT_NAME,
                    qSet.getResourceType().toString(), qSetElement, examDoc);

            if (qSet.getResources() != null) {
                for (BufferedImage img : qSet.getResources()) {
                    try {
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        ImageIO.write(img, "png", out);
                        out.flush();
                        GenericUtils.appendSubNode(XML_QUESTION_SET_RESOURCE_DATA_ELEMENT_NAME,
                                convertBytesToHexString(out.toByteArray()), qSetElement, examDoc);
                    } catch (IOException e) {
                        throw new VaSolSimException("Error: cannot write images to byte array for transport");
                    }
                }
            }

            for (int setIndex = 0; setIndex < qSet.getQuestions().size(); setIndex++) {
                Question question = qSet.getQuestions().get(setIndex);

                Element qElement = examDoc.createElement(XML_QUESTION_ELEMENT_NAME);
                qSetElement.appendChild(qElement);

                GenericUtils.appendSubNode(XML_QUESTION_ID_ELEMENT_NAME, Integer.toString(setIndex + 1),
                        qElement, examDoc);
                GenericUtils.appendSubNode(XML_QUESTION_NAME_ELEMENT_NAME,
                        (question.getName() == null || question.getName().equals(""))
                                ? "Question " + (setIndex + 1)
                                : question.getName(),
                        qElement, examDoc);
                GenericUtils.appendSubNode(XML_QUESTION_TEXT_ELEMENT_NAME, question.getQuestion(), qElement,
                        examDoc);
                GenericUtils.appendSubNode(XML_QUESTION_SCRAMBLE_ANSWERS_ELEMENT_NAME,
                        Boolean.toString(question.getScrambleAnswers()), qElement, examDoc);
                GenericUtils.appendSubNode(XML_QUESTION_REATIAN_ANSWER_ORDER_ELEMENT_NAME,
                        Boolean.toString(question.getAnswerOrderMatters()), qElement, examDoc);

                for (AnswerChoice answer : question.getCorrectAnswerChoices()) {
                    GenericUtils.appendSubNode(XML_QUESTION_ENCRYPTED_ANSWER_HASH, answer.getAnswerText(),
                            qElement, examDoc);
                }

                for (int questionIndex = 0; questionIndex < question.getAnswerChoices()
                        .size(); questionIndex++) {
                    AnswerChoice ac = question.getAnswerChoices().get(questionIndex);

                    Element acElement = examDoc.createElement(XML_ANSWER_CHOICE_ELEMENT_NAME);
                    qElement.appendChild(acElement);

                    GenericUtils.appendSubNode(XML_ANSWER_CHOICE_ID_ELEMENT_NAME,
                            Integer.toString(questionIndex + 1), acElement, examDoc);
                    GenericUtils.appendSubNode(XML_ANSWER_CHOICE_VISIBLE_ID_ELEMENT_NAME,
                            ac.getVisibleChoiceID(), acElement, examDoc);
                    GenericUtils.appendSubNode(XML_ANSWER_TEXT_ELEMENT_NAME, ac.getAnswerText(), acElement,
                            examDoc);
                }
            }
        }
    }

    return true;
}

From source file:cz.cas.lib.proarc.common.export.mets.MetsUtils.java

/**
 *
 * Transforms the xml document to a string
 *
 * @param doc//www.  j a  va2s.co m
 * @return
 */
public static String documentToString(Document doc) throws MetsExportException {
    try {
        StringWriter sw = new StringWriter();
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        transformer.transform(new DOMSource(doc), new StreamResult(sw));
        return sw.toString();
    } catch (TransformerException ex) {
        throw new MetsExportException("Error converting Document to String", false, ex);
    }
}

From source file:ee.sk.digidoc.DataFile.java

/**
 * Use this method to assign data directly to body.
 * Input data is an XML subtree//from w  w w  .j a  va 2s .  c om
 * @param xml xml subtree containing input data
 * @param codepage input data's original codepage
 * @deprecated embedded xml no longer supported
 */
public void setBody(Node xml) throws DigiDocException {
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        DOMSource source = new DOMSource(xml);
        StreamResult result = new StreamResult(bos);
        transformer.transform(source, result);
        m_body = bos.toByteArray();
        // DOM library always outputs in UTF-8
        m_codepage = "UTF-8";
        m_size = m_body.length;
        // check if data must be stored in file instead
        storeInTempFile();
    } catch (Exception ex) {
        DigiDocException.handleException(ex, DigiDocException.ERR_XML_CONVERT);
    }
}

From source file:eu.europeana.uim.gui.cp.server.RetrievalServiceImpl.java

private String getFormattedXml(Document doc) throws Exception {
    String xml = "";
    TransformerFactory transFactory = TransformerFactory.newInstance();
    Transformer transformer = transFactory.newTransformer();

    transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    DOMSource source = new DOMSource(doc);

    transformer.transform(source, result);

    xml = writer.toString();/*w w  w. j a v a 2 s  .c o  m*/
    return xml;
}

From source file:com.benchmark.TikaCLI.java

/**
 * Returns a transformer handler that serializes incoming SAX events
 * to XHTML or HTML (depending the given method) using the given output
 * encoding./*from ww w. j av a  2 s .  c  om*/
 *
 * @see <a href="https://issues.apache.org/jira/browse/TIKA-277">TIKA-277</a>
 * @param output output stream
 * @param method "xml" or "html"
 * @param encoding output encoding,
 *                 or <code>null</code> for the platform default
 * @return {@link System#out} transformer handler
 * @throws TransformerConfigurationException
 *         if the transformer can not be created
 */
private static TransformerHandler getTransformerHandler(OutputStream output, String method, String encoding,
        boolean prettyPrint) throws TransformerConfigurationException {
    SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler handler = factory.newTransformerHandler();
    handler.getTransformer().setOutputProperty(OutputKeys.METHOD, method);
    handler.getTransformer().setOutputProperty(OutputKeys.INDENT, prettyPrint ? "yes" : "no");
    if (encoding != null) {
        handler.getTransformer().setOutputProperty(OutputKeys.ENCODING, encoding);
    }
    handler.setResult(new StreamResult(output));
    return handler;
}

From source file:com.hp.application.automation.tools.results.RunResultRecorder.java

private void write2XML(Document document, String filename) throws TransformerException, FileNotFoundException {
    document.normalize();//from ww w.j a v a  2 s . c  o  m

    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    DOMSource source = new DOMSource(document);
    PrintWriter pw = new PrintWriter(new FileOutputStream(filename));
    StreamResult result = new StreamResult(pw);
    transformer.transform(source, result);

}

From source file:com.ggvaidya.scinames.model.Project.java

public void saveToFile() throws IOException {
    File saveToFile = projectFile.getValue();

    if (saveToFile == null)
        throw new IOException("Project file not set: nowhere to save to!");

    /*// w  ww. j  a v a  2s  . c  o m
    XMLOutputFactory factory = XMLOutputFactory.newFactory();
            
    try {
       XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter(saveToFile));
               
       writer.writeStartDocument();
               
       serializeToXMLStream(writer);
               
       writer.writeEndDocument();
       writer.flush();
               
       // Success!
       lastModified.saved();
               
    } catch (XMLStreamException ex) {
       throw new IOException("Could not write project to XML file '" + saveToFile + "': " + ex);
    }*/

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    // Create a document representation of this project.
    Document docProject;
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        docProject = db.newDocument();
        serializeToDocument(docProject);

    } catch (ParserConfigurationException ex) {
        Logger.getLogger(Project.class.getName()).log(Level.SEVERE, null, ex);
        return;
    }

    // Write the document representation of this project
    // as XML.
    TransformerFactory tfc = TransformerFactory.newInstance();
    try {
        OutputStream outputStream = new GZIPOutputStream(new FileOutputStream(saveToFile));
        StreamResult res = new StreamResult(outputStream);

        Transformer t = tfc.newTransformer();
        DOMSource ds = new DOMSource(docProject);

        t.setOutputProperty(OutputKeys.METHOD, "xml");
        t.setOutputProperty(OutputKeys.VERSION, "1.0"); // Do NOT change to 1.1 -- this leads to complex problems!
        t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        t.setOutputProperty(OutputKeys.STANDALONE, "yes");
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        t.transform(ds, res);

        // Success!
        lastModified.saved();
        outputStream.close();
    } catch (TransformerConfigurationException ex) {
        throw new IOException("Could not write out XML to '" + saveToFile + "': " + ex);
    } catch (TransformerException ex) {
        throw new IOException("Could not write out XML to '" + saveToFile + "': " + ex);
    }
}

From source file:jef.tools.XMLUtils.java

private static void output(Node node, StreamResult sr, String encoding, int indent, Boolean XmlDeclarion)
        throws IOException {
    if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
        sr.getWriter().write(node.getNodeValue());
        sr.getWriter().flush();/*from   ww w  . jav  a 2s. co m*/
        return;
    }

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = null;
    try {
        if (indent > 0) {
            try {
                tf.setAttribute("indent-number", indent);
                t = tf.newTransformer();
                // ?XML??XML?
                t.setOutputProperty(OutputKeys.INDENT, "yes");
            } catch (Exception e) {
            }
        } else {
            t = tf.newTransformer();
        }

        t.setOutputProperty(OutputKeys.METHOD, "xml");
        if (encoding != null) {
            t.setOutputProperty(OutputKeys.ENCODING, encoding);
        }
        if (XmlDeclarion == null) {
            XmlDeclarion = (node instanceof Document);
        }
        if (node instanceof Document) {
            Document doc = (Document) node;
            if (doc.getDoctype() != null) {
                t.setOutputProperty(javax.xml.transform.OutputKeys.DOCTYPE_PUBLIC,
                        doc.getDoctype().getPublicId());
                t.setOutputProperty(javax.xml.transform.OutputKeys.DOCTYPE_SYSTEM,
                        doc.getDoctype().getSystemId());
            }
        }
        if (XmlDeclarion) {
            t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        } else {
            t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        }
    } catch (Exception tce) {
        throw new IOException(tce);
    }
    DOMSource doms = new DOMSource(node);
    try {
        t.transform(doms, sr);
    } catch (TransformerException te) {
        IOException ioe = new IOException();
        ioe.initCause(te);
        throw ioe;
    }
}

From source file:edu.utah.bmi.ibiomes.lite.IBIOMESLiteManager.java

/**
 * Pull data files (pdb and images) for a given experiment
 * @param fileTreeXmlPath Path to XML file representing the project file tree
 * @param workflowXmlPath Path to XML file representing the experiment workflow
 * @param dataDirPath Path to directory used to store data files
 * @throws SAXException/*from ww  w .  java2  s.c om*/
 * @throws IOException
 * @throws XPathExpressionException 
 * @throws ParserConfigurationException 
 * @throws TransformerException 
 */
private void pullDataFilesForExperiment(String fileTreeXmlPath, String workflowXmlPath, String dataDirPath)
        throws SAXException, IOException, XPathExpressionException, ParserConfigurationException,
        TransformerException {

    if (outputToConsole)
        System.out.println("Copying analysis data files...");

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document fileTreeDoc = docBuilder.parse(fileTreeXmlPath);
    fileTreeDoc = Utils.normalizeXmlDoc(fileTreeDoc);

    Element fileTreeRootElt = (Element) fileTreeDoc.getDocumentElement().getChildNodes().item(0);
    String dirPath = fileTreeRootElt.getAttribute("absolutePath");

    XPathReader xreader = new XPathReader(fileTreeDoc);

    //load XML representation of experiment workflow
    Document docWorkflow = docBuilder.parse(workflowXmlPath);
    docWorkflow = Utils.normalizeXmlDoc(docWorkflow);
    Element workflowRootElt = (Element) docWorkflow.getDocumentElement();

    //find main structure for display in Jmol
    Element jmolElt = pullJmolFile(fileTreeDoc, fileTreeRootElt, xreader, dataDirPath, dirPath);
    if (jmolElt != null)
        workflowRootElt.appendChild(docWorkflow.importNode(jmolElt, true));

    //find analysis data
    NodeList matchingFiles = (NodeList) xreader.read("//file[AVUs/AVU[@id='" + FileMetadata.FILE_CLASS
            + "' and text()='" + FileMetadata.FILE_CLASS_ANALYSIS.toUpperCase() + "']]",
            XPathConstants.NODESET);

    //add publication information
    //Element dirNode = (Element)fileTreeDoc.getDocumentElement().getFirstChild();
    //dirNode.setAttribute("publisher", workflowRootElt.getAttribute("publisher"));
    //dirNode.setAttribute("publicationDate", workflowRootElt.getAttribute("publicationDate"));

    //analysis data
    if (matchingFiles != null && matchingFiles.getLength() > 0) {
        Element dataElt = docWorkflow.createElement("analysis");
        workflowRootElt.appendChild(dataElt);

        Element imgElt = docWorkflow.createElement("images");
        Element pdbElt = docWorkflow.createElement("structures");
        Element csvElts = docWorkflow.createElement("spreadsheets");
        Element otherDataElts = docWorkflow.createElement("unknowns");

        dataElt.appendChild(imgElt);
        dataElt.appendChild(csvElts);
        dataElt.appendChild(pdbElt);
        dataElt.appendChild(otherDataElts);

        PlotGenerator plotTool = new PlotGenerator();

        for (int f = 0; f < matchingFiles.getLength(); f++) {
            Element fileNode = (Element) matchingFiles.item(f);
            String dataFilePath = fileNode.getAttribute("absolutePath");
            //copy file
            String dataFileNewName = dataFilePath.substring(dirPath.length() + 1)
                    .replaceAll(PATH_FOLDER_SEPARATOR_REGEX, "_");
            String dataFileDestPath = dataDirPath + PATH_FOLDER_SEPARATOR + dataFileNewName;
            Files.copy(Paths.get(dataFilePath), Paths.get(dataFileDestPath),
                    StandardCopyOption.REPLACE_EXISTING);
            //set read permissions
            if (!Utils.isWindows()) {
                HashSet<PosixFilePermission> permissions = new HashSet<PosixFilePermission>();
                permissions.add(PosixFilePermission.OWNER_READ);
                permissions.add(PosixFilePermission.OWNER_WRITE);
                permissions.add(PosixFilePermission.OWNER_EXECUTE);
                permissions.add(PosixFilePermission.GROUP_READ);
                permissions.add(PosixFilePermission.OTHERS_READ);
                Files.setPosixFilePermissions(Paths.get(dataFileDestPath), permissions);
            }
            //read file AVUs
            NodeList avuNodes = (NodeList) xreader.read("//file[@absolutePath='" + dataFilePath + "']/AVUs/AVU",
                    XPathConstants.NODESET);
            MetadataAVUList avuList = new MetadataAVUList();
            if (avuNodes != null) {
                for (int a = 0; a < avuNodes.getLength(); a++) {
                    Element avuNode = (Element) avuNodes.item(a);
                    avuList.add(new MetadataAVU(avuNode.getAttribute("id").toUpperCase(),
                            avuNode.getFirstChild().getNodeValue()));
                }
            }

            //add reference in XML doc
            String description = avuList.getValue(FileMetadata.FILE_DESCRIPTION);
            String format = fileNode.getAttribute("format");
            if (IBIOMESFileGroup.isJmolFile(format)) {
                Element jmolFileElt = docWorkflow.createElement("structure");
                jmolFileElt.setAttribute("path", dataFileNewName);
                if (description != null && description.length() > 0)
                    jmolFileElt.setAttribute("description", description);
                pdbElt.appendChild(jmolFileElt);
            } else if (format.equals(LocalFile.FORMAT_CSV)) {
                Element csvElt = docWorkflow.createElement("spreadsheet");
                csvElt.setAttribute("path", dataFileNewName);
                if (description != null && description.length() > 0)
                    csvElt.setAttribute("description", description);
                csvElts.appendChild(csvElt);
                //try to generate plot and save image
                try {
                    String imgPath = dataFileNewName + "_plot.png";
                    String plotType = generatePlotForCSV(plotTool, dataFileDestPath, avuList,
                            dataFileDestPath + "_plot", "png");
                    csvElt.setAttribute("plotPath", imgPath);
                    if (outputToConsole) {
                        if (plotType == null)
                            plotType = "";
                        else
                            plotType += " ";
                        System.out.println("\t" + plotType + "plot generated for " + dataFileNewName);
                    }

                } catch (Exception e) {
                    if (outputToConsole)
                        System.out.println(
                                "Warning: Plot for '" + dataFileDestPath + "' could not be generated.");
                    try {
                        if (IBIOMESConfiguration.getInstance().isOutputErrorStackToConsole())
                            e.printStackTrace();
                    } catch (Exception e1) {
                    }
                }
            } else if (IBIOMESFileGroup.isImageFile(format)) {
                Element imgFileElt = docWorkflow.createElement("image");
                imgFileElt.setAttribute("path", dataFileNewName);
                if (description != null && description.length() > 0)
                    imgFileElt.setAttribute("description", description);
                imgElt.appendChild(imgFileElt);
            } else {
                Element otherFileElt = docWorkflow.createElement("unknown");
                otherFileElt.setAttribute("path", dataFileNewName);
                if (description != null && description.length() > 0)
                    otherFileElt.setAttribute("description", description);
                imgElt.appendChild(otherDataElts);
            }
        }
    }

    //update XML files
    File outputXmlAvusFile = new File(fileTreeXmlPath);
    if (outputXmlAvusFile.exists())
        outputXmlAvusFile.delete();

    File outputXmlWorkflowFile = new File(workflowXmlPath);
    if (outputXmlWorkflowFile.exists())
        outputXmlWorkflowFile.delete();

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

    DOMSource source = new DOMSource(fileTreeDoc);
    StreamResult result = null;
    result = new StreamResult(fileTreeXmlPath);
    transformer.transform(source, result);

    source = new DOMSource(docWorkflow);
    result = null;
    result = new StreamResult(outputXmlWorkflowFile);
    transformer.transform(source, result);
}