Example usage for javax.xml.transform.stream StreamResult getWriter

List of usage examples for javax.xml.transform.stream StreamResult getWriter

Introduction

In this page you can find the example usage for javax.xml.transform.stream StreamResult getWriter.

Prototype

public Writer getWriter() 

Source Link

Document

Get the character stream that was set with setWriter.

Usage

From source file:de.huberlin.wbi.hiway.am.galaxy.GalaxyApplicationMaster.java

/**
 * A helper function for parsing a Galaxy tool's XML file
 * //  ww  w . j av  a2s .  co  m
 * @param file
 *            the XML file to be parsed
 * @return the Galaxy tools described in the XML file
 */
private GalaxyTool parseToolFile(File file) {
    System.out.println("Parsing Galaxy tool file " + file);
    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        String path = file.getCanonicalPath();
        String dir = path.substring(0, path.lastIndexOf("/"));
        Document doc = builder.parse(file);
        Element rootEl = doc.getDocumentElement();
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(rootEl);
        transformer.transform(source, result);
        String toolDescription = result.getWriter().toString();

        // (1) parse macros, if any
        NodeList macrosNds = rootEl.getElementsByTagName("macros");
        Map<String, String> macrosByName = new HashMap<>();
        for (int i = 0; i < macrosNds.getLength(); i++) {
            Node macrosNd = macrosNds.item(i);
            macrosByName.putAll(processMacros(macrosNd, dir));
        }

        // (2) insert macros into the XML and parse the document
        Pattern p = Pattern.compile("<expand macro=\"([^\"]*)\"(>.*?</expand>|/>)", Pattern.DOTALL);
        Matcher m = p.matcher(toolDescription);
        while (m.find()) {
            String name = m.group(1);
            String replace = m.group(0);
            String with = macrosByName.get(name);
            if (m.group(2).startsWith(">")) {
                String yield = m.group(2).substring(1, m.group(2).indexOf("</expand>"));
                with = with.replaceAll("<yield/>", yield.trim());
            }
            if (with != null)
                toolDescription = toolDescription.replace(replace, with);
        }

        doc = builder.parse(new InputSource(new StringReader(toolDescription)));
        rootEl = doc.getDocumentElement();
        String version = rootEl.hasAttribute("version") ? rootEl.getAttribute("version") : "1.0.0";
        String id = rootEl.getAttribute("id");
        GalaxyTool tool = new GalaxyTool(id, version, dir, galaxyPath);

        // (3) determine requirements (libraries and executables) of this tool; requirements have to be parsed such that the environment of the task can be
        // set to include them
        NodeList requirementNds = rootEl.getElementsByTagName("requirement");
        for (int i = 0; i < requirementNds.getLength(); i++) {
            Element requirementEl = (Element) requirementNds.item(i);
            String requirementName = requirementEl.getChildNodes().item(0).getNodeValue().trim();
            String requirementVersion = requirementEl.getAttribute("version");
            tool.addRequirement(requirementName, requirementVersion);
        }

        // (4) determine and set the template for the command of the task; this template will be compiled at runtime by Cheetah
        Element commandEl = (Element) rootEl.getElementsByTagName("command").item(0);
        if (commandEl != null) {
            String command = commandEl.getChildNodes().item(0).getNodeValue().trim();
            String script = command.split(" ")[0];
            String interpreter = commandEl.getAttribute("interpreter");
            if (interpreter.length() > 0) {
                command = command.replace(script, dir + "/" + script);
                command = interpreter + " " + command;
            }
            command = command.replaceAll("\\.value", "");
            command = command.replaceAll("\\.dataset", "");
            tool.setTemplate(command);
        }

        // (5) determine the parameters (atomic, conditional and repeat) of this tool
        Element inputsEl = (Element) rootEl.getElementsByTagName("inputs").item(0);
        if (inputsEl != null)
            tool.setParams(getParams(inputsEl, tool));

        // (6) determine the output files produced by this tool
        Element outputsEl = (Element) rootEl.getElementsByTagName("outputs").item(0);
        if (outputsEl != null) {
            NodeList dataNds = outputsEl.getElementsByTagName("data");
            for (int i = 0; i < dataNds.getLength(); i++) {
                Element dataEl = (Element) dataNds.item(i);
                String name = dataEl.getAttribute("name");
                GalaxyParamValue param = new GalaxyParamValue(name);
                tool.setPath(name);
                tool.addParam(param);

                String format = dataEl.getAttribute("format");
                String metadata_source = dataEl.getAttribute("metadata_source");
                if (format.equals("input") && metadata_source != null && metadata_source.length() > 0) {
                    param.setDataType(metadata_source);
                } else {
                    param.setDataType(format);
                }

                String from_work_dir = dataEl.getAttribute("from_work_dir");
                param.setFrom_work_dir(from_work_dir);
            }
        }

        // (7) register the tool in the Galaxy tool data structure
        if (tool.getTemplate() != null) {
            Map<String, GalaxyTool> toolMap = addAndGetToolMap(id);
            toolMap.put(version, tool);
        }

        return tool;
    } catch (SAXException | IOException | TransformerException | XPathExpressionException
            | ParserConfigurationException e) {
        e.printStackTrace();
        System.exit(-1);
        return null;
    }
}

From source file:it.ciroppina.idol.generic.tunnel.IdolOEMTunnel.java

/**
 * @param response//from w  w  w. ja va 2s .com
 * @return the ACI aurtnresponse in XML compact format
 */
private String xmlResponse(Document response) {
    String result = "";
    StreamResult xmlOutput = new StreamResult(new StringWriter());
    Transformer transformer;
    try {
        transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(new DOMSource(response.getDocumentElement()), xmlOutput);
        result = xmlOutput.getWriter().toString();
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
        return "Error occurred parsing XML-formatted autnresponse - Badly formatted request";
    } catch (TransformerFactoryConfigurationError e) {
        e.printStackTrace();
        return "Error occurred parsing XML-formatted autnresponse - Badly formatted request";
    } catch (TransformerException e) {
        e.printStackTrace();
        return "Error occurred parsing XML-formatted autnresponse - Badly formatted request";
    }
    return result;
}

From source file:org.activiti.kickstart.service.alfresco.AlfrescoKickstartServiceImpl.java

protected void prettyLogXml(String xml) {
    try {//from   w w w .  ja va  2s .c o  m
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        Source xmlInput = new StreamSource(new StringReader(xml));

        StreamResult xmlOutput = new StreamResult(new StringWriter());
        transformer.transform(xmlInput, xmlOutput);
        LOGGER.info(xmlOutput.getWriter().toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:cz.incad.vdkcommon.solr.Indexer.java

public void processXML(Document doc) throws Exception {
    LOGGER.log(Level.FINE, "Sending to index ...");
    StreamResult destStream = new StreamResult(new StringWriter());
    transformer.transform(new DOMSource(doc), destStream);
    StringWriter sw = (StringWriter) destStream.getWriter();
    SolrIndexerCommiter.postData(sw.toString());
}

From source file:cz.incad.vdkcommon.solr.Indexer.java

public void processXML(File file) throws Exception {
    LOGGER.log(Level.FINE, "Sending {0} to index ...", file.getAbsolutePath());
    StreamResult destStream = new StreamResult(new StringWriter());
    transformer.transform(new StreamSource(file), destStream);
    StringWriter sw = (StringWriter) destStream.getWriter();
    SolrIndexerCommiter.postData(sw.toString());
}

From source file:com.CodeSeance.JSeance.CodeGenXML.ContextManager.java

public XMLObject createXMLObject(Document document) {
    //Transform to String
    Transformer transformer;/*from   w w w.java 2s.  c  o m*/
    StreamResult result;
    try {
        if (ExecutionError.simulate_CONTEXTMANAGER_CREATEXMLOBJECT_ERROR) {
            ExecutionError.simulate_CONTEXTMANAGER_CREATEXMLOBJECT_ERROR = false;
            throw new TransformerException("Simulated exception for log testing");
        }
        transformer = TransformerFactory.newInstance().newTransformer();
        // The next section is required in order for the JS engine to parse the XML
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(document);
        transformer.transform(source, result);
    } catch (TransformerException ex) {
        // Wrap Exception with RuntimeException since caller won't be able to handle it
        throw new RuntimeException(
                ExecutionError.CONTEXTMANAGER_CREATEXMLOBJECT_ERROR.getMessage(ex.getMessage()));
    }

    String xmlString = result.getWriter().toString();

    // Create the JS Objects
    Object[] args = { xmlString };
    Object jsXMLObj = callJSFunction(XML_CREATE_FN, args);
    assert jsXMLObj instanceof XMLObject;
    return (XMLObject) jsXMLObj;
}

From source file:io.kahu.hawaii.util.logger.DefaultLogManager.java

@Override
public String prettyPrintXml(final String s) {
    try {// w  w  w  .  j a  v  a 2s . co  m
        if (s == null) {
            return null;
        }
        if (!looksLikeXml(s)) {
            return s;
        }
        Source xmlInput = new StreamSource(new StringReader(s));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", 2);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (Throwable t) {
        return s;
    }
}

From source file:cz.incad.vdkcommon.solr.Indexer.java

public void processXML(String xml, String uniqueCode, String codeType, String identifier, boolean bohemika,
        String zdrojConf) throws Exception {
    LOGGER.log(Level.FINE, "Transforming {0} ...", identifier);
    StreamResult destStream = new StreamResult(new StringWriter());
    transformer.setParameter("uniqueCode", uniqueCode);
    transformer.setParameter("bohemika", Boolean.toString(bohemika));
    transformer.setParameter("zdrojConf", zdrojConf);
    transformer.transform(new StreamSource(new StringReader(xml)), destStream);
    LOGGER.log(Level.FINE, "Sending to index ...");
    StringWriter sw = (StringWriter) destStream.getWriter();
    SolrIndexerCommiter.postData(sw.toString());
}

From source file:com.maxl.java.aips2sqlite.AllDown.java

private String prettyFormat(String input) {
    try {//from   w  ww .ja v  a2 s.co m
        Source xmlInput = new StreamSource(new StringReader(input));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (Exception e) {
        throw new RuntimeException(e); // simple exception handling, please review it
    }
}

From source file:cz.incad.vdkcommon.solr.Indexer.java

private String doSorlXML(String xml, String uniqueCode, String codeType, String identifier, boolean bohemika,
        String zdrojConf) throws Exception {
    LOGGER.log(Level.FINE, "Transforming {0} ...", identifier);
    StreamResult destStream = new StreamResult(new StringWriter());
    trId.setParameter("uniqueCode", uniqueCode);
    trId.setParameter("codeType", codeType);
    trId.setParameter("bohemika", Boolean.toString(bohemika));
    trId.setParameter("zdrojConf", zdrojConf);
    trId.setParameter("sourceXml", xml);
    trId.transform(new StreamSource(new StringReader(xml)), destStream);
    StringWriter sw = (StringWriter) destStream.getWriter();
    return sw.toString();
}