Java Code Examples for javax.xml.transform.stream.StreamResult

The following are top voted examples for showing how to use javax.xml.transform.stream.StreamResult. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: openjdk-jdk10   File: Bug7037352Test.java   Source Code and License 7 votes vote down vote up
@Test
public void test() {
    try {
        XMLOutputFactory xof = XMLOutputFactory.newInstance();
        StreamResult sr = new StreamResult();
        XMLStreamWriter xsw = xof.createXMLStreamWriter(sr);
        NamespaceContext nc = xsw.getNamespaceContext();
        System.out.println(nc.getPrefix(XMLConstants.XML_NS_URI));
        System.out.println("  expected result: " + XMLConstants.XML_NS_PREFIX);
        System.out.println(nc.getPrefix(XMLConstants.XMLNS_ATTRIBUTE_NS_URI));
        System.out.println("  expected result: " + XMLConstants.XMLNS_ATTRIBUTE);

        Assert.assertTrue(nc.getPrefix(XMLConstants.XML_NS_URI) == XMLConstants.XML_NS_PREFIX);
        Assert.assertTrue(nc.getPrefix(XMLConstants.XMLNS_ATTRIBUTE_NS_URI) == XMLConstants.XMLNS_ATTRIBUTE);

    } catch (Throwable ex) {
        Assert.fail(ex.toString());
    }
}
 
Example 2
Project: bdf2   File: GraphicalEditorPage.java   Source Code and License 6 votes vote down vote up
public void synchroGraphicalToXml(){
	Document doc=this.buildDocument();
	if(doc==null)return;
	TransformerFactory factory=TransformerFactory.newInstance();
	try{
		Transformer transformer=factory.newTransformer();
		transformer.setOutputProperty("encoding","utf-8");
		transformer.setOutputProperty(OutputKeys.INDENT,"yes");				
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		transformer.transform(new DOMSource(doc),new StreamResult(out));
		xmlEditor.getDocumentProvider().getDocument(xmlEditor.getEditorInput()).set(out.toString("utf-8"));
		out.close();
	}catch(Exception ex){
		ex.printStackTrace();
	}
}
 
Example 3
Project: openjdk-jdk10   File: SAXTFactoryTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test newTransformerHandler with a Template Handler along with a relative
 * URI in the style-sheet file.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase09() throws Exception {
    String outputFile = USER_DIR + "saxtf009.out";
    String goldFile = GOLDEN_DIR + "saxtf009GF.out";

    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory)TransformerFactory.newInstance();

        TemplatesHandler thandler = saxTFactory.newTemplatesHandler();
        thandler.setSystemId("file:///" + XML_DIR);
        reader.setContentHandler(thandler);
        reader.parse(XSLT_INCL_FILE);
        TransformerHandler tfhandler=
            saxTFactory.newTransformerHandler(thandler.getTemplates());
        Result result = new StreamResult(fos);
        tfhandler.setResult(result);
        reader.setContentHandler(tfhandler);
        reader.parse(XML_FILE);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 4
Project: MFM   File: PersistUtils.java   Source Code and License 6 votes vote down vote up
public static void saveXMLDoctoFile(Document doc, DocumentType documentType, String path)
        throws TransformerException {
    // Save DOM XML doc to File
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();

    doc.setXmlVersion("1.0");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, documentType.getPublicId());
    transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, documentType.getSystemId());

    transformer.transform(new DOMSource(doc), new StreamResult(new File(path)));
}
 
Example 5
Project: openjdk-jdk10   File: Bug6540545.java   Source Code and License 6 votes vote down vote up
@Test
public void test() {
    try {
        String xmlFile = "numbering63.xml";
        String xslFile = "numbering63.xsl";

        TransformerFactory tFactory = TransformerFactory.newInstance();
        // tFactory.setAttribute("generate-translet", Boolean.TRUE);
        Transformer t = tFactory.newTransformer(new StreamSource(getClass().getResourceAsStream(xslFile), getClass().getResource(xslFile).toString()));
        StringWriter sw = new StringWriter();
        t.transform(new StreamSource(getClass().getResourceAsStream(xmlFile)), new StreamResult(sw));
        String s = sw.getBuffer().toString();
        Assert.assertFalse(s.contains("1: Level A"));
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }
}
 
Example 6
Project: coteafs-services   File: XmlPayloadLogger.java   Source Code and License 6 votes vote down vote up
@Override
public String [] getPayload (final PayloadType type, final String body) {
	final Source input = new StreamSource (new StringReader (body));
	final StringWriter writer = new StringWriter ();
	final StreamResult output = new StreamResult (writer);
	final TransformerFactory transformerFactory = TransformerFactory.newInstance ();
	transformerFactory.setAttribute ("indent-number", 4);
	try {
		final Transformer transformer = transformerFactory.newTransformer ();
		transformer.setOutputProperty (OutputKeys.INDENT, "yes");
		transformer.transform (input, output);
		return output.getWriter ()
			.toString ()
			.split ("\n");
	}
	catch (final TransformerException e) {
		fail (XmlFormatTransformerError.class, "Error while Xml Transformation.", e);
	}
	return new String [] {};
}
 
Example 7
Project: litiengine   File: XmlUtilities.java   Source Code and License 6 votes vote down vote up
/**
 * Saves the xml, contained by the specified input with the custom indentation.
 * If the input is the result of jaxb marshalling, make sure to set
 * Marshaller.JAXB_FORMATTED_OUTPUT to false in order for this method to work
 * properly.
 * 
 * @param input
 * @param fos
 * @param indentation
 */
public static void saveWithCustomIndetation(ByteArrayInputStream input, FileOutputStream fos, int indentation) {
  try {
    Transformer transformer = SAXTransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indentation));
    Source xmlSource = new SAXSource(new org.xml.sax.InputSource(input));
    StreamResult res = new StreamResult(fos);
    transformer.transform(xmlSource, res);
    fos.flush();
    fos.close();
  } catch (TransformerFactoryConfigurationError | TransformerException | IOException e) {
    log.log(Level.SEVERE, e.getMessage(), e);
  }
}
 
Example 8
Project: OpenVertretung   File: JDBC4MysqlSQLXML.java   Source Code and License 6 votes vote down vote up
protected String domSourceToString() throws SQLException {
    try {
        DOMSource source = new DOMSource(this.asDOMResult.getNode());
        Transformer identity = TransformerFactory.newInstance().newTransformer();
        StringWriter stringOut = new StringWriter();
        Result result = new StreamResult(stringOut);
        identity.transform(source, result);

        return stringOut.toString();
    } catch (Throwable t) {
        SQLException sqlEx = SQLError.createSQLException(t.getMessage(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
        sqlEx.initCause(t);

        throw sqlEx;
    }
}
 
Example 9
Project: openjdk-jdk10   File: AuctionItemRepository.java   Source Code and License 6 votes vote down vote up
/**
 * Test the simple case of including a document using xi:include within a
 * xi:fallback using a DocumentBuilder.
 *
 * @throws Exception If any errors occur.
 */
@Test(groups = {"readWriteLocalFiles"})
public void testXIncludeFallbackDOMPos() throws Exception {
    String resultFile = USER_DIR + "doc_fallbackDOM.out";
    String goldFile = GOLDEN_DIR + "doc_fallbackGold.xml";
    String xmlFile = XML_DIR + "doc_fallback.xml";
    try (FileOutputStream fos = new FileOutputStream(resultFile)) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setXIncludeAware(true);
        dbf.setNamespaceAware(true);

        Document doc = dbf.newDocumentBuilder().parse(new File(xmlFile));
        doc.setXmlStandalone(true);
        TransformerFactory.newInstance().newTransformer()
                .transform(new DOMSource(doc), new StreamResult(fos));
    }
    assertTrue(compareDocumentWithGold(goldFile, resultFile));
}
 
Example 10
Project: incubator-netbeans   File: XMLUtil.java   Source Code and License 6 votes vote down vote up
public static void write(Document doc, OutputStream out) throws IOException {
    // XXX note that this may fail to write out namespaces correctly if the document
    // is created with namespaces and no explicit prefixes; however no code in
    // this package is likely to be doing so
    try {
        Transformer t = TransformerFactory.newInstance().newTransformer(
                new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT)));
        DocumentType dt = doc.getDoctype();
        if (dt != null) {
            String pub = dt.getPublicId();
            if (pub != null) {
                t.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, pub);
            }
            t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, dt.getSystemId());
        }
        t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // NOI18N
        Source source = new DOMSource(doc);
        Result result = new StreamResult(out);
        t.transform(source, result);
    } catch (Exception | TransformerFactoryConfigurationError e) {
        throw new IOException(e);
    }
}
 
Example 11
Project: EVE   File: Weather.java   Source Code and License 6 votes vote down vote up
private void generateWeather(String c) throws IOException, SAXException, TransformerException, ParserConfigurationException {
    city = c;

    // creating the URL
    String url = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&mode=xml&appid=" + APIKey;

    // printing out XML
    URL urlString = new URL(url);
    URLConnection conn = urlString.openConnection();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(conn.getInputStream());

    TransformerFactory transformer = TransformerFactory.newInstance();
    Transformer xform = transformer.newTransformer();

    xform.transform(new DOMSource(doc), new StreamResult(System.out));
}
 
Example 12
Project: tablasco   File: ExceptionHtml.java   Source Code and License 6 votes vote down vote up
private static void writeDocument(Document document, File resultsFile) throws TransformerException, IOException
{
    File parentDir = resultsFile.getParentFile();
    if (!parentDir.exists() && !parentDir.mkdirs())
    {
        throw new IllegalStateException("Unable to create results directory:" + parentDir);
    }
    Transformer trans = TransformerFactory.newInstance().newTransformer();
    trans.setOutputProperty(OutputKeys.METHOD, "xml");
    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    trans.setOutputProperty(OutputKeys.INDENT, "yes");
    try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(resultsFile), "UTF-8")))
    {
        trans.transform(new DOMSource(document), new StreamResult(writer));
    }
}
 
Example 13
Project: openjdk-jdk10   File: SAXTFactoryTest.java   Source Code and License 6 votes vote down vote up
/**
 * SAXTFactory.newTransformerhandler() method which takes SAXSource as
 * argument can be set to XMLReader. SAXSource has input XML file as its
 * input source. XMLReader has a content handler which write out the result
 * to output file. Test verifies output file is same as golden file.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase02() throws Exception {
    String outputFile = USER_DIR + "saxtf002.out";
    String goldFile = GOLDEN_DIR + "saxtf002GF.out";

    try (FileOutputStream fos = new FileOutputStream(outputFile);
            FileInputStream fis = new FileInputStream(XSLT_FILE)) {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory) TransformerFactory.newInstance();
        SAXSource ss = new SAXSource();
        ss.setInputSource(new InputSource(fis));

        TransformerHandler handler = saxTFactory.newTransformerHandler(ss);
        Result result = new StreamResult(fos);
        handler.setResult(result);
        reader.setContentHandler(handler);
        reader.parse(XML_FILE);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 14
Project: iot-plat   File: ConfigManager.java   Source Code and License 6 votes vote down vote up
public static boolean saveFile(Document document, File file) {
	boolean flag = true;
	try {
		/** 将document中的内容写入文件中 */
		TransformerFactory tFactory = TransformerFactory.newInstance();
		Transformer transformer = tFactory.newTransformer();
		/** 编码 */
		transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
		DOMSource source = new DOMSource(document);
		StreamResult result = new StreamResult(file);
		transformer.transform(source, result);
	} catch (Exception ex) {
		flag = false;
		ex.printStackTrace();
	}
	return flag;
}
 
Example 15
Project: sierra   File: XmlOutput.java   Source Code and License 6 votes vote down vote up
@Override
public String toString() {
	try {
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");

		DOMSource source = new DOMSource(document);
		StreamResult result = new StreamResult(new StringWriter());
		transformer.transform(source, result);
		return result.getWriter().toString();
	} catch (TransformerException e) {
		throw new RuntimeException(e);
	}
}
 
Example 16
Project: bohemia   File: XmlUtils.java   Source Code and License 6 votes vote down vote up
/** 
 * Transforms the XML content to XHTML/HTML format string with the XSL. 
 * 
 * @param payload the XML payload to convert 
 * @param xsltFile the XML stylesheet file 
 * @return the transformed XHTML/HTML format string 
 * @throws XmlException problem converting XML to HTML 
 */  
public static String xmlToHtml(String payload, File xsltFile)  
        throws XmlException {  
    String result = null;  
  
    try {  
        Source template = new StreamSource(xsltFile);  
        Transformer transformer = TransformerFactory.newInstance()  
                .newTransformer(template);  
  
        Properties props = transformer.getOutputProperties();  
        props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES);  
        transformer.setOutputProperties(props);  
  
        StreamSource source = new StreamSource(new StringReader(payload));  
        StreamResult sr = new StreamResult(new StringWriter());  
        transformer.transform(source, sr);  
  
        result = sr.getWriter().toString();  
    } catch (TransformerException e) {  
        throw new XmlException(XmlException.XML_TRANSFORM_ERROR, e);  
    }  
  
    return result;  
}
 
Example 17
Project: openjdk-jdk10   File: Bug6565260.java   Source Code and License 6 votes vote down vote up
@Test
public void test() {
    try {
        String xmlFile = "attribset27.xml";
        String xslFile = "attribset27.xsl";

        TransformerFactory tFactory = TransformerFactory.newInstance();
        // tFactory.setAttribute("generate-translet", Boolean.TRUE);
        Transformer t = tFactory.newTransformer(new StreamSource(getClass().getResourceAsStream(xslFile)));
        StringWriter sw = new StringWriter();
        t.transform(new StreamSource(getClass().getResourceAsStream(xmlFile)), new StreamResult(sw));
        String s = sw.getBuffer().toString();
        Assert.assertFalse(s.contains("color") || s.contains("font-size"));
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }
}
 
Example 18
Project: Aurora   File: CharacterHandler.java   Source Code and License 6 votes vote down vote up
/**
 * xml 格式化
 *
 * @param xml
 * @return
 */
public static String xmlFormat(String xml) {
    if (TextUtils.isEmpty(xml)) {
        return "Empty/Null xml content";
    }
    String message;
    try {
        Source xmlInput = new StreamSource(new StringReader(xml));
        StreamResult xmlOutput = new StreamResult(new StringWriter());
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(xmlInput, xmlOutput);
        message = xmlOutput.getWriter().toString().replaceFirst(">", ">\n");
    } catch (TransformerException e) {
        message = xml;
    }
    return message;
}
 
Example 19
Project: TextHIN   File: SparqlExecutor.java   Source Code and License 6 votes vote down vote up
public static void printDocument(Node node, OutputStream out) {
  try {
    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.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    transformer.transform(
        new DOMSource(node),
        new StreamResult(new OutputStreamWriter(out, "UTF-8")));
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 20
Project: javaide   File: MergerXmlUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Outputs the given XML {@link Document} to the file {@code outFile}.
 *
 * TODO right now reformats the document. Needs to output as-is, respecting white-space.
 *
 * @param doc The document to output. Must not be null.
 * @param outFile The {@link File} where to write the document.
 * @param log A log in case of error.
 * @return True if the file was written, false in case of error.
 */
static boolean printXmlFile(
        @NonNull Document doc,
        @NonNull File outFile,
        @NonNull IMergerLog log) {
    // Quick thing based on comments from http://stackoverflow.com/questions/139076
    try {
        Transformer tf = TransformerFactory.newInstance().newTransformer();
        tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");         //$NON-NLS-1$
        tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");                   //$NON-NLS-1$
        tf.setOutputProperty(OutputKeys.INDENT, "yes");                       //$NON-NLS-1$
        tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",     //$NON-NLS-1$
                             "4");                                            //$NON-NLS-1$
        tf.transform(new DOMSource(doc), new StreamResult(outFile));
        return true;
    } catch (TransformerException e) {
        log.error(Severity.ERROR,
                new FileAndLine(outFile.getName(), 0),
                "Failed to write XML file: %1$s",
                e.toString());
        return false;
    }
}
 
Example 21
Project: karate   File: XmlUtils.java   Source Code and License 6 votes vote down vote up
public static String toString(Node node, boolean pretty) {
    if (pretty) {
        trimWhiteSpace(node);
    }
    DOMSource domSource = new DOMSource(node);
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    TransformerFactory tf = TransformerFactory.newInstance();
    try {
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        if (pretty) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        }
        transformer.transform(domSource, result);
        return writer.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 22
Project: tablasco   File: HtmlFormatter.java   Source Code and License 6 votes vote down vote up
public void appendResults(String testName, Map<String, ? extends FormattableTable> results, Metadata metadata, int verifyCount, Document dom, OutputStream outputStream) throws TransformerException, UnsupportedEncodingException
{
    if (dom == null)
    {
        dom = createNewDocument(metadata);
    }
    Node body = dom.getElementsByTagName("body").item(0);
    if (verifyCount == 1)
    {
        body.appendChild(ResultCell.createNodeWithText(dom, "h1", testName));
    }

    if (this.htmlOptions.isDisplayAssertionSummary())
    {
        appendAssertionSummary(testName, results, body);
    }
    for (Map.Entry<String, ? extends FormattableTable> namedTable : results.entrySet())
    {
        appendResults(testName, namedTable.getKey(), namedTable.getValue(), body, true);
    }
    TRANSFORMER.value().transform(new DOMSource(dom), new StreamResult(new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"))));
}
 
Example 23
Project: lams   File: UpdateWarTask.java   Source Code and License 6 votes vote down vote up
/**
    * Writes the modified web.xml back out to war file
    * 
    * @param doc
    *            The application.xml DOM Document
    * @throws org.apache.tools.ant.DeployException
    *             in case of any problems
    */
   protected void writeWebXml(final Document doc, final OutputStream outputStream) throws DeployException {
try {
    doc.normalize();

    // Prepare the DOM document for writing
    DOMSource source = new DOMSource(doc);

    // Prepare the output file
    StreamResult result = new StreamResult(outputStream);

    // Write the DOM document to the file
    // Get Transformer
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    // Write to a file
    xformer.transform(source, result);
} catch (TransformerException tex) {
    throw new DeployException("Error writing out modified web xml ", tex);
}
   }
 
Example 24
Project: lams   File: JDBC4MysqlSQLXML.java   Source Code and License 6 votes vote down vote up
protected String domSourceToString() throws SQLException {
    try {
        DOMSource source = new DOMSource(this.asDOMResult.getNode());
        Transformer identity = TransformerFactory.newInstance().newTransformer();
        StringWriter stringOut = new StringWriter();
        Result result = new StreamResult(stringOut);
        identity.transform(source, result);

        return stringOut.toString();
    } catch (Throwable t) {
        SQLException sqlEx = SQLError.createSQLException(t.getMessage(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
        sqlEx.initCause(t);

        throw sqlEx;
    }
}
 
Example 25
Project: openjdk-jdk10   File: SAXTFactoryTest.java   Source Code and License 6 votes vote down vote up
/**
 * SAXTFactory.newTransformerhandler() method which takes SAXSource as
 * argument can be set to XMLReader. SAXSource has input XML file as its
 * input source. XMLReader has a transformer handler which write out the
 * result to output file. Test verifies output file is same as golden file.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase01() throws Exception {
    String outputFile = USER_DIR + "saxtf001.out";
    String goldFile = GOLDEN_DIR + "saxtf001GF.out";

    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory) TransformerFactory.newInstance();
        TransformerHandler handler = saxTFactory.newTransformerHandler(new StreamSource(XSLT_FILE));
        Result result = new StreamResult(fos);
        handler.setResult(result);
        reader.setContentHandler(handler);
        reader.parse(XML_FILE);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 26
Project: parabuild-ci   File: AbstractXSLRendererComponent.java   Source Code and License 6 votes vote down vote up
/**
 * Oveloaded CustomComponent's render
 */
public final void render(final RenderContext ctx) {
  StreamSource xslSource = null;
  StreamSource xmlSource = null;
  try {
    xslSource = xslSource();
    xmlSource = xmlSource();
    final Transformer transformer = TransformerFactory.newInstance().newTransformer(xslSource);
    final PrintWriter pw = ctx.getWriter();
    transformer.transform(xmlSource, new StreamResult(pw));
  } catch (Exception e) {
    showUnexpectedErrorMsg(ctx, e);
  } finally {
    closeHard(xslSource);
    closeHard(xmlSource);
  }
}
 
Example 27
Project: KeYExperienceReport   File: SPLOpltionGenerator.java   Source Code and License 6 votes vote down vote up
private static void writeOut(Document doc) throws TransformerException {
	TransformerFactory transformerFactory = TransformerFactory
			.newInstance();
	Transformer transformer = transformerFactory.newTransformer();
	transformer.setOutputProperty(OutputKeys.INDENT, "yes");
	transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
	transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
	DOMSource source = new DOMSource(doc);
	File f = new File("splFile.xml");
	f.delete();
	StreamResult result = new StreamResult(f);

	// Output to console for testing
	// StreamResult result = new StreamResult(System.out);

	transformer.transform(source, result);

	System.out.println("File saved!");

}
 
Example 28
Project: ats-framework   File: XmlUtilities.java   Source Code and License 6 votes vote down vote up
/**
 * Pretty print XML Node
 * @param node
 * @return
 * @throws XmlUtilitiesException
 */
public String xmlNodeToString( Node node ) throws XmlUtilitiesException {

    StringWriter sw = new StringWriter();
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "4");
        transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_LINE_SEPARATOR, "\n");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(new DOMSource(node), new StreamResult(sw));
    } catch (TransformerException te) {
        throw new XmlUtilitiesException("Error transforming XML node to String", te);
    }
    return sw.toString().trim();
}
 
Example 29
Project: MoligyMvpArms   File: CharacterHandler.java   Source Code and License 6 votes vote down vote up
/**
 * xml 格式化
 *
 * @param xml
 * @return
 */
public static String xmlFormat(String xml) {
    if (TextUtils.isEmpty(xml)) {
        return "Empty/Null xml content";
    }
    String message;
    try {
        Source xmlInput = new StreamSource(new StringReader(xml));
        StreamResult xmlOutput = new StreamResult(new StringWriter());
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(xmlInput, xmlOutput);
        message = xmlOutput.getWriter().toString().replaceFirst(">", ">\n");
    } catch (TransformerException e) {
        message = xml;
    }
    return message;
}
 
Example 30
Project: DeskChan   File: CharacterPreset.java   Source Code and License 6 votes vote down vote up
public void saveInFile(Path path) throws IOException {
	try {
		Document doc = DocumentBuilderFactory.newInstance()
				                             .newDocumentBuilder()
				                             .parse(new InputSource(new StringReader(XML.toString(toJSON()))));

		Transformer t = TransformerFactory.newInstance().newTransformer();
		t.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes");
		t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
		t.setOutputProperty(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes");
		OutputStreamWriter stream = new OutputStreamWriter(new FileOutputStream(path.resolve("saved.preset").toFile()), "UTF-8");
		t.transform(new DOMSource(doc), new StreamResult(stream));
	} catch(Exception ex){
		Main.log(ex);
		Main.log("Error while writing preset file");
	}
}
 
Example 31
Project: openjdk-jdk10   File: OpenJDK100017Test.java   Source Code and License 6 votes vote down vote up
@Test
public final void testXMLStackOverflowBug() throws TransformerConfigurationException, IOException, SAXException {
    try {
        SAXTransformerFactory stf = (SAXTransformerFactory) TransformerFactory.newInstance();
        TransformerHandler ser = stf.newTransformerHandler();
        ser.setResult(new StreamResult(System.out));

        StringBuilder sb = new StringBuilder(4096);
        for (int x = 4096; x > 0; x--) {
            sb.append((char) x);
        }
        ser.characters(sb.toString().toCharArray(), 0, sb.toString().toCharArray().length);
        ser.endDocument();
    } catch (StackOverflowError se) {
        se.printStackTrace();
        Assert.fail("StackOverflow");
    }
}
 
Example 32
Project: openjdk-jdk10   File: TransformerFactoryTest.java   Source Code and License 6 votes vote down vote up
/**
 * This test case checks for the getAssociatedStylesheet method
 * of TransformerFactory.
 * The style sheet returned is then copied to an tfactory01.out
 * It will then be verified to see if it matches the golden files.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void tfactory01() throws Exception {
    String outputFile = USER_DIR + "tfactory01.out";
    String goldFile = GOLDEN_DIR + "tfactory01GF.out";
    String xmlFile = XML_DIR + "TransformerFactoryTest.xml";
    String xmlURI = "file:///" + XML_DIR;

    try (FileInputStream fis = new FileInputStream(xmlFile);
            FileOutputStream fos = new FileOutputStream(outputFile);) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(fis, xmlURI);
        DOMSource domSource = new DOMSource(doc);
        domSource.setSystemId(xmlURI);
        StreamResult streamResult = new StreamResult(fos);
        TransformerFactory tFactory = TransformerFactory.newInstance();

        Source s = tFactory.getAssociatedStylesheet(domSource, "screen",
                                       "Modern", null);
        Transformer t = tFactory.newTransformer();
        t.transform(s, streamResult);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 33
Project: AndroidApktool   File: ResXmlPatcher.java   Source Code and License 5 votes vote down vote up
/**
 *
 * @param file File to save Document to (ie AndroidManifest.xml)
 * @param doc Document being saved
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws TransformerException
 */
private static void saveDocument(File file, Document doc)
        throws IOException, SAXException, ParserConfigurationException, TransformerException {

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.STANDALONE,"yes");
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(file);
    transformer.transform(source, result);
}
 
Example 34
Project: trashjam2017   File: ParticleIO.java   Source Code and License 5 votes vote down vote up
/**
 * Save a single emitter to the XML file
 * 
 * @param out
 *            The location to which we should save
 * @param emitter
 *            The emitter to store to the XML file
 * @throws IOException
 *             Indicates a failure to write or encode the XML
 */
public static void saveEmitter(OutputStream out, ConfigurableEmitter emitter)
		throws IOException {
	try {
		DocumentBuilder builder = DocumentBuilderFactory.newInstance()
				.newDocumentBuilder();
		Document document = builder.newDocument();

		document.appendChild(emitterToElement(document, emitter));
		Result result = new StreamResult(new OutputStreamWriter(out,
				"utf-8"));
		DOMSource source = new DOMSource(document);

		TransformerFactory factory = TransformerFactory.newInstance();
		Transformer xformer = factory.newTransformer();
		xformer.setOutputProperty(OutputKeys.INDENT, "yes");

		xformer.transform(source, result);
	} catch (Exception e) {
		Log.error(e);
		throw new IOException("Failed to save emitter");
	}
}
 
Example 35
Project: openjdk-jdk10   File: Bug4892774.java   Source Code and License 5 votes vote down vote up
@Test
public void testStream2Stream() {
    try {
        Source input = streamUtil.prepareSource(this.getClass().getResourceAsStream(XML_FILE));
        StreamResult strResult = (StreamResult) streamUtil.prepareResult();
        idTransform.transform(input, strResult);
        streamUtil.checkResult(strResult, EXPECTED_VERSION, "UTF-8");
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("Exception occured: " + e.getMessage());
    }
}
 
Example 36
Project: nfse   File: AssinaturaDigital.java   Source Code and License 5 votes vote down vote up
private String converteDocParaXml(Document doc) throws TransformerException {
  ByteArrayOutputStream os = new ByteArrayOutputStream();
  Transformer trans = TransformerFactory.newInstance().newTransformer();
  trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
  trans.transform(new DOMSource(doc), new StreamResult(os));
  return os.toString();
}
 
Example 37
Project: jdk8u-jdk   File: XSLT.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        ByteArrayOutputStream resStream = new ByteArrayOutputStream();
        TransformerFactory trf = TransformerFactory.newInstance();
        Transformer tr = trf.newTransformer(new StreamSource(System.getProperty("test.src", ".")+"/"+args[1]));
        String res, expectedRes;
        tr.transform( new StreamSource(System.getProperty("test.src", ".")+"/"+args[0]), new StreamResult(resStream));
        res = resStream.toString();
        System.out.println("Transformation completed. Result:"+res);

        if (!res.replaceAll("\\s","").equals(args[2]))
            throw new RuntimeException("Incorrect transformation result. Expected:"+args[2]+" Observed:"+res);
    }
 
Example 38
Project: alvisnlp   File: AbstractAlvisNLP.java   Source Code and License 5 votes vote down vote up
@CLIOption(value="-supportedModulesXML", stop=true)
public final void supportedModulesXML() throws TransformerException {
	Document doc = XMLUtils.docBuilder.newDocument();
	Element root = XMLUtils.createRootElement(doc, "alvisnlp-supported-modules");
       for (Class<? extends Module<A>> mod : moduleFactory.supportedServices()) {
       	Element item = XMLUtils.createElement(doc, root, 1, "module-item");
       	item.setAttribute("target", mod.getCanonicalName());
       	item.setAttribute("short-target", mod.getSimpleName());
       }
	Source source = new DOMSource(doc);
	Result result = new StreamResult(System.out);
	xmlDocTransformer.transform(source, result);
}
 
Example 39
Project: LibraSock   File: XmlUtils.java   Source Code and License 5 votes vote down vote up
public static String Doc2String(Document paramDocument) {
	try {
		DOMSource localDOMSource = new DOMSource(paramDocument);
		StringWriter localStringWriter = new StringWriter();
		StreamResult localStreamResult = new StreamResult(localStringWriter);
		TransformerFactory localTransformerFactory = TransformerFactory.newInstance();
		Transformer localTransformer = localTransformerFactory.newTransformer();
		localTransformer.transform(localDOMSource, localStreamResult);
		return localStringWriter.toString();
	} catch (Exception localException) {
		localException.printStackTrace();
	}
	return null;
}
 
Example 40
Project: joai-project   File: XSLTransformer.java   Source Code and License 5 votes vote down vote up
/**
 *  Transforms an XML String using a pre-compiled {@link javax.xml.transform.Transformer}. Use {@link
 *  #getTransformer(String xslFilePath)} to produce a reusable {@link javax.xml.transform.Transformer} for a
 *  given XSL stylesheet. To convert the resulting StringWriter to a String, call StringWriter.toString().
 *
 * @param  xmlString    The XML String to transform.
 * @param  transformer  A pre-compiled {@link javax.xml.transform.Transformer} used to produce transformed
 *      output.
 * @return              A StringWriter containing the transformed content.
 */
public final static StringWriter transformStringToWriter(String xmlString, Transformer transformer) {
	try {
		StringWriter writer = new StringWriter();
		StreamSource source = new StreamSource(new StringReader(xmlString));
		transformer.transform(source, new StreamResult(writer));
		return writer;
	} catch (Throwable e) {
		prtlnErr(e);
		return new StringWriter();
	}
}
 
Example 41
Project: rapidminer   File: Operator.java   Source Code and License 5 votes vote down vote up
/**
 * This will report this operator with all its parameter settings to the given writer as XML.
 */
public void writeXML(Writer out, boolean hideDefault) throws IOException {
	try {
		XMLTools.stream(new XMLExporter().exportProcess(this, hideDefault), new StreamResult(out),
				XMLImporter.PROCESS_FILE_CHARSET);
	} catch (XMLException e) {
		throw new IOException("Cannot create process XML: " + e, e);
	}
}
 
Example 42
Project: jaffa-framework   File: TransformationHelper.java   Source Code and License 5 votes vote down vote up
private static String nodeToString(Node node, StringWriter xmlString) throws Exception, RuntimeException {
    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    t.setOutputProperty(OutputKeys.INDENT, "no");
    t.transform(new DOMSource(node), new StreamResult(xmlString));
    return xmlString.toString();
}
 
Example 43
Project: rapidminer   File: OperatorDocLoader.java   Source Code and License 5 votes vote down vote up
/**
 * This loads the documentation of the operator referenced by the operator description from the
 * Wiki in the internet.
 */
private static String loadSelectedOperatorDocuFromWiki(OperatorDescription opDesc) throws IOException,
ParserConfigurationException, OperatorCreationException, TransformerException, URISyntaxException {
	String operatorWikiName = StringUtils.EMPTY;
	if (!opDesc.isDeprecated()) {
		operatorWikiName = opDesc.getName().replace(" ", "_");
		if (opDesc.getProvider() != null) {
			String prefix = opDesc.getProvider().getPrefix();
			prefix = Character.toUpperCase(prefix.charAt(0)) + prefix.substring(1);
			operatorWikiName = prefix + ":" + operatorWikiName;
		}

		Document documentOperator = parseDocumentForOperator(operatorWikiName, opDesc);

		if (documentOperator != null) {
			// writing html back to string
			Transformer transformer = TransformerFactory.newInstance().newTransformer();
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");

			// initialize StreamResult with File object to save to file
			StreamResult result = new StreamResult(new StringWriter());
			DOMSource source = new DOMSource(documentOperator);
			transformer.transform(source, result);

			String HTMLString = result.getWriter().toString();
			HTMLString = customizeHTMLStringDirty(HTMLString, opDesc);

			return HTMLString;
		}
	}
	return loadSelectedOperatorDocuLocally(opDesc);
}
 
Example 44
Project: hashsdn-controller   File: SnapshotHandler.java   Source Code and License 5 votes vote down vote up
@Override
public String getElement(final StreamResult rt) {
    String xml = rt.getWriter().toString();
    int beginIndex = xml.indexOf(START_TAG) + START_TAG.length();
    int endIndex = xml.indexOf(END_TAG);
    Preconditions.checkArgument(beginIndex != -1 && endIndex != -1,
            "Unknown element present in config snapshot(expected only configuration): %s", xml);
    return xml.substring(beginIndex, endIndex);
}
 
Example 45
Project: emr-nlp-server   File: XMLUtil.java   Source Code and License 5 votes vote down vote up
/**
 * Save list of record IDs as an XML file.
 * 
 * @param dbName
 * @param itemList
 * @param nodeName
 * @param fn_xml
 * @throws Exception
 */
public static void createXMLDatasetFileFromList(String dbName, String[] itemList,
        String nodeName, String fn_xml) throws Exception {                
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    // root elements
    Document doc = docBuilder.newDocument();        
    
    Element rootElement = doc.createElement("Dataset");
    doc.appendChild(rootElement);        
    // attributes for root node
    rootElement.setAttribute("type", DATASET_TYPE_COLON);
    rootElement.setAttribute("name", dbName);
    rootElement.setAttribute("databaseroot", "./");
    
    Element ele;
    for(String item : itemList) {
        ele = doc.createElement(nodeName);
        ele.appendChild(doc.createTextNode(item));
        
        rootElement.appendChild(ele);
    }
    
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    File outputFile = new File(fn_xml);
    StreamResult result = new StreamResult(outputFile);
    // replace %20 by whitespace
    result.setSystemId(result.getSystemId().replaceAll("%20", " "));
    
    transformer.transform(source, result);
}
 
Example 46
Project: Cognizant-Intelligent-Test-Scripter   File: XMLOperation.java   Source Code and License 5 votes vote down vote up
public static void finishTreeOp(Document doc, String xmlPath) {
    createFile(xmlPath);
    try (FileOutputStream fout = new FileOutputStream(xmlPath)) {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(fout);
        transformer.transform(source, result);
    } catch (TransformerException | IOException ex) {
        Logger.getLogger(XMLOperation.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 47
Project: ChronoBike   File: CGlobalEntityCounter.java   Source Code and License 5 votes vote down vote up
public void Export(String path)
{
	try
	{
		DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Document doc = builder.newDocument();
		MakeXML(doc) ;
		Source source = new DOMSource(doc);
		FileOutputStream file = new FileOutputStream(path+".xml");
		StreamResult res = new StreamResult(file) ;
		Transformer xformer = TransformerFactory.newInstance().newTransformer();
		xformer.setOutputProperty(OutputKeys.ENCODING, "ISO8859-1");
		xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
		xformer.setOutputProperty(OutputKeys.INDENT, "yes");
		xformer.transform(source, res);
		
		File fSS = new File(path+".xsl");
		if(!fSS.exists())
			return;
		Source stylesheet = new StreamSource(fSS) ; 
		Templates templ = TransformerFactory.newInstance().newTemplates(stylesheet) ;
		Transformer xformer2 = templ.newTransformer() ;			

		FileOutputStream file2 = new FileOutputStream(path+".html");
		StreamResult result = new StreamResult(file2) ;
		xformer2.transform(source, result);
		
	}
	catch (Exception e)
	{
		e.printStackTrace() ;
	}
}
 
Example 48
Project: jmt   File: PNMLWriter.java   Source Code and License 5 votes vote down vote up
/**
 * Appends the specific graphics of a node to a string writer
 * @param writer writer that the graphics are appended to
 * @param model data structure of the model
 * @param node search key for the node
 */
private static void appendSpecificNodeGraphfics(StringWriter writer, JSimGraphModel model, Object node)
		throws TransformerException {
	Element graphics = elemCreator.createElement(PNML_JSIM_E_NODE_GRAPHICS);
	Element rotate = elemCreator.createElement(PNML_JSIM_E_NODE_GRAPHICS_ROTATE);
	String text = String.valueOf(model.getStationPosition(node).isRotate());
	rotate.setTextContent(text);
	graphics.appendChild(rotate);
	transformer.transform(new DOMSource(graphics), new StreamResult(writer));
}
 
Example 49
Project: openjdk-jdk10   File: PrettyPrintTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testDisableOutputEscaping() throws Exception {
    final String xsl ="generate-catalog.xsl";
    final String xml ="simple-entity-resolver-config.xml";
    final String expectedOutput ="simple-entity-resolver-config-transformed.xml";
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTemplates(new StreamSource(new StringReader(read(xsl)))).newTransformer();

    String key = "schemaBase";
    String value = "schemas";
    transformer.setParameter(key, value);
    StringWriter writer = new StringWriter();
    transformer.transform(new StreamSource(new StringReader(read(xml))), new StreamResult(writer));
    assertEquals(writer.toString().replaceAll("\r\n", "\n"), read(expectedOutput));
}
 
Example 50
Project: Android_Code_Arbiter   File: StdXmlTransform.java   Source Code and License 5 votes vote down vote up
public void xslt2UnsafeResource(String input) throws TransformerException {
    TransformerFactory factory = TransformerFactory.newInstance();
    Source xslt = new StreamSource(getClass().getResourceAsStream(input));
    Transformer transformer = factory.newTransformer(xslt);

    Source text = new StreamSource(getClass().getResourceAsStream(FORLDER+"input.xml"));
    transformer.transform(text, new StreamResult(System.out));
}
 
Example 51
Project: openjdk-jdk10   File: TransformationWarningsTest.java   Source Code and License 5 votes vote down vote up
void doOneTestIteration() throws Exception {
    // Prepare output stream
    StringWriter xmlResultString = new StringWriter();
    StreamResult xmlResultStream = new StreamResult(xmlResultString);
    // Prepare xml source stream
    Source src = new StreamSource(new StringReader(xml));
    Transformer t = createTransformer();
    //Transform the xml
    t.transform(src, xmlResultStream);
}
 
Example 52
Project: Coder   File: Logger.java   Source Code and License 5 votes vote down vote up
private static String formatXml(String xml) {
    try {
        Source xmlInput = new StreamSource(new StringReader(xml));
        StreamResult xmlOutput = new StreamResult(new StringWriter());
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transformer.transform(xmlInput, xmlOutput);
        xml = xmlOutput.getWriter().toString().replaceFirst(">", ">" + LINE_SEP);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return xml;
}
 
Example 53
Project: OpenJSharp   File: SmartTransformerFactoryImpl.java   Source Code and License 5 votes vote down vote up
/**
 * javax.xml.transform.sax.TransformerFactory implementation.
 * Look up the value of a feature (to see if it is supported).
 * This method must be updated as the various methods and features of this
 * class are implemented.
 *
 * @param name The feature name
 * @return 'true' if feature is supported, 'false' if not
 */
public boolean getFeature(String name) {
    // All supported features should be listed here
    String[] features = {
        DOMSource.FEATURE,
        DOMResult.FEATURE,
        SAXSource.FEATURE,
        SAXResult.FEATURE,
        StreamSource.FEATURE,
        StreamResult.FEATURE
    };

    // feature name cannot be null
    if (name == null) {
        ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_GET_FEATURE_NULL_NAME);
        throw new NullPointerException(err.toString());
    }

    // Inefficient, but it really does not matter in a function like this
    for (int i = 0; i < features.length; i++) {
        if (name.equals(features[i]))
            return true;
    }

    // secure processing?
    if (name.equals(XMLConstants.FEATURE_SECURE_PROCESSING)) {
        return featureSecureProcessing;
    }

    // unknown feature
    return false;
}
 
Example 54
Project: sstore-soft   File: JDBCSQLXML.java   Source Code and License 5 votes vote down vote up
/**
 * Retrieves a new Result for setting the XML value designated by this
 * SQLXML instance.
 *
 * @param resultClass The class of the result, or null.
 * @throws java.sql.SQLException if there is an error processing the XML
 *         value or the state is not writable
 * @return for setting the XML value designated by this SQLXML instance.
 */
protected <T extends Result>T createResult(
        Class<T> resultClass) throws SQLException {

    checkWritable();
    setWritable(false);
    setReadable(true);

    if (JAXBResult.class.isAssignableFrom(resultClass)) {

        // Must go first presently, since JAXBResult extends SAXResult
        // (purely as an implmentation detail) and it's not possible
        // to instantiate a valid JAXBResult with a Zero-Args
        // constructor(or any subclass thereof, due to the finality of
        // its private UnmarshallerHandler)
        // FALL THROUGH... will throw an exception
    } else if ((resultClass == null)
               || StreamResult.class.isAssignableFrom(resultClass)) {
        return createStreamResult(resultClass);
    } else if (DOMResult.class.isAssignableFrom(resultClass)) {
        return createDOMResult(resultClass);
    } else if (SAXResult.class.isAssignableFrom(resultClass)) {
        return createSAXResult(resultClass);
    } else if (StAXResult.class.isAssignableFrom(resultClass)) {
        return createStAXResult(resultClass);
    }

    throw Util.invalidArgument("resultClass: " + resultClass);
}
 
Example 55
Project: joai-project   File: XSLTransformer.java   Source Code and License 5 votes vote down vote up
/**
 *  Transforms an XML String using a pre-compiled {@link javax.xml.transform.Transformer}. Use {@link
 *  #getTransformer(String xslFilePath)} to produce a reusable {@link javax.xml.transform.Transformer} for a
 *  given XSL stylesheet.
 *
 * @param  xmlString    The XML String to transform.
 * @param  transformer  A pre-compiled {@link javax.xml.transform.Transformer} used to produce transformed
 *      output.
 * @return              A String containing the transformed content.
 */
public final static String transformString(String xmlString, Transformer transformer) {
	try {
		StringWriter writer = new StringWriter();
		StreamSource source = new StreamSource(new StringReader(xmlString));
		transformer.transform(source, new StreamResult(writer));
		return writer.toString();
	} catch (Throwable e) {
		prtlnErr(e);
		return "";
	}
}
 
Example 56
Project: dss-demonstrations   File: XSLTService.java   Source Code and License 5 votes vote down vote up
public String generateSimpleReport(String simpleReport) {
	Writer writer = new StringWriter();
	try {
		Transformer transformer = templateSimpleReport.newTransformer();
		transformer.setErrorListener(new DSSXmlErrorListener());
		transformer.transform(new StreamSource(new StringReader(simpleReport)), new StreamResult(writer));
	} catch (Exception e) {
		logger.error("Error while generating simple report : " + e.getMessage(), e);
	}
	return writer.toString();
}
 
Example 57
Project: oryx2   File: PMMLUtils.java   Source Code and License 5 votes vote down vote up
/**
 * @param pmml model
 * @return model serialized as an XML document as a string
 */
public static String toString(PMML pmml) {
  try (StringWriter out = new StringWriter()) {
    // v JAXBUtil.marshalPMML but need to set compact, non-pretty output
    Marshaller marshaller = JAXBUtil.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
    marshaller.marshal(pmml, new StreamResult(out));
    return out.toString();
  } catch (JAXBException | IOException e) {
    // IOException should not be possible; JAXBException would only happen with XML
    // config problems.
    throw new IllegalStateException(e);
  }
}
 
Example 58
Project: openjdk-jdk10   File: XSLTExFuncTest.java   Source Code and License 5 votes vote down vote up
void transform(TransformerFactory factory) throws TransformerConfigurationException, TransformerException {
    SAXSource xslSource = new SAXSource(new InputSource(xslFile));
    xslSource.setSystemId(xslFileId);
    Transformer transformer = factory.newTransformer(xslSource);
    StringWriter stringResult = new StringWriter();
    Result result = new StreamResult(stringResult);
    transformer.transform(new SAXSource(new InputSource(xmlFile)), result);
}
 
Example 59
Project: jdk8u-jdk   File: TransformerTest.java   Source Code and License 5 votes vote down vote up
/**
 * @bug 8169112
 * @summary Test compilation of large xsl file with outlining.
 *
 * This test merely compiles a large xsl file and tests if its bytecode
 * passes verification by invoking the transform() method for
 * dummy content. The test succeeds if no Exception is thrown
 */
@Test
public final void testBug8169112() throws FileNotFoundException,
    TransformerException
{
    TransformerFactory tf = TransformerFactory.newInstance();
    String xslFile = getClass().getResource("Bug8169112.xsl").toString();
    Transformer t = tf.newTransformer(new StreamSource(xslFile));
    String xmlIn = "<?xml version=\"1.0\"?><DOCROOT/>";
    ByteArrayInputStream bis = new ByteArrayInputStream(xmlIn.getBytes());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    t.transform(new StreamSource(bis), new StreamResult(bos));
}
 
Example 60
Project: joai-project   File: XSLTransformer.java   Source Code and License 5 votes vote down vote up
/**
 *  Transforms an XML file using a pre-compiled {@link javax.xml.transform.Transformer}. Use {@link
 *  #getTransformer(String xslFilePath)} to produce a reusable {@link javax.xml.transform.Transformer} for a
 *  given XSL stylesheet.
 *
 * @param  inputFile    The XML file to transform.
 * @param  transformer  A pre-compiled {@link javax.xml.transform.Transformer} used to produce transformed
 *      output.
 * @return              A String containing the transformed content.
 */
public final static String transformFile(File inputFile, Transformer transformer) {
	try {
		StringWriter writer = new StringWriter();
		StreamSource ss = new StreamSource(new FileInputStream(inputFile));
		ss.setSystemId(inputFile);
		transformer.transform(ss, new StreamResult(writer));
		return writer.toString();
	} catch (Throwable e) {
		prtlnErr(e);
		return "";
	}
}