Java Code Examples for javax.xml.transform.Transformer

The following are top voted examples for showing how to use javax.xml.transform.Transformer. 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: Random-Music-Generator   File: XMLGenerator.java   View source code 8 votes vote down vote up
private void saveDocumentTo() throws XMLException {
	try {
		TransformerFactory tfactory = TransformerFactory.newInstance();
		Transformer transf = tfactory.newTransformer();
		
		transf.setOutputProperty( OutputKeys.INDENT, "yes" );
		transf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
		transf.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "no" );
		transf.setOutputProperty( OutputKeys.METHOD, "xml" );
		
		DOMImplementation impl = doc.getImplementation();
		DocumentType doctype = impl.createDocumentType( "doctype", 
				"-//Recordare//DTD MusicXML 3.0 Partwise//EN", "http://www.musicxml.org/dtds/partwise.dtd" );
		
		transf.setOutputProperty( OutputKeys.DOCTYPE_PUBLIC, doctype.getPublicId() );
		transf.setOutputProperty( OutputKeys.DOCTYPE_SYSTEM, doctype.getSystemId() );
		
		DOMSource src = new DOMSource( doc );
		StreamResult resultS = new StreamResult( file );
		transf.transform( src, resultS );
		
	} catch ( TransformerException e ) {
		throw new XMLException( "Could not save the File" );
	}
}
 
Example 2
Project: Equella   File: XsltServiceImpl.java   View source code 8 votes vote down vote up
/**
 * Performs the XSLT transformation.
 */
private String doTransform(final Transformer transformer, final Source input, final URIResolver resolver)
{
	final StringWriter writer = new StringWriter();
	final StreamResult output = new StreamResult(writer);

	if( resolver != null )
	{
		transformer.setURIResolver(resolver);
	}

	try
	{
		transformer.transform(input, output);
	}
	catch( final TransformerException ex )
	{
		throw new RuntimeException("Error transforming XSLT", ex);
	}

	return writer.toString();
}
 
Example 3
Project: cuttlefish   File: GraphMLExporter.java   View source code 6 votes vote down vote up
public void export(File file) {
	try {
		// Create the GraphML Document
		docFactory = DocumentBuilderFactory.newInstance();
		docBuilder = docFactory.newDocumentBuilder();
		doc = docBuilder.newDocument();

		// Export the data
		exportData();

		// Save data as GraphML file
		Transformer transformer = TransformerFactory.newInstance()
				.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(file);
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
		transformer.transform(source, result);

	} catch (TransformerException te) {
		te.printStackTrace();
	} catch (ParserConfigurationException pce) {
		pce.printStackTrace();
	}
}
 
Example 4
Project: javaide   File: MergerXmlUtils.java   View source code 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 5
Project: openjdk-jdk10   File: URIResolverTest.java   View source code 6 votes vote down vote up
/**
 * This is to test the URIResolver.resolve() method when there is an error
 * in the file.
 *
 * @throws Exception If any errors occur.
 */
@Test
public static void docResolver01() throws Exception {
    try (FileInputStream fis = new FileInputStream(XML_DIR + "doctest.xsl")) {
        URIResolverTest resolver = new URIResolverTest("temp/colors.xml", SYSTEM_ID);
        StreamSource streamSource = new StreamSource(fis);
        streamSource.setSystemId(SYSTEM_ID);

        Transformer transformer = TransformerFactory.newInstance().newTransformer(streamSource);
        transformer.setURIResolver(resolver);

        File f = new File(XML_DIR + "myFake.xml");
        Document document = DocumentBuilderFactory.newInstance().
                newDocumentBuilder().parse(f);

        // Use a Transformer for output
        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(System.err);
        // No exception is expected because resolver resolve wrong URI.
        transformer.transform(source, result);
    }
}
 
Example 6
Project: openjdk-jdk10   File: MexEntityResolver.java   View source code 6 votes vote down vote up
public MexEntityResolver(List<? extends Source> wsdls) throws IOException {
    Transformer transformer = XmlUtil.newTransformer();
    for (Source source : wsdls) {
        XMLStreamBufferResult xsbr = new XMLStreamBufferResult();
        try {
            transformer.transform(source, xsbr);
        } catch (TransformerException e) {
            throw new WebServiceException(e);
        }
        String systemId = source.getSystemId();

        //TODO: can we do anything if the given mex Source has no systemId?
        if(systemId != null){
            SDDocumentSource doc = SDDocumentSource.create(JAXWSUtils.getFileOrURL(systemId), xsbr.getXMLStreamBuffer());
            this.wsdls.put(systemId, doc);
        }
    }
}
 
Example 7
Project: oscm   File: XMLConverter.java   View source code 6 votes vote down vote up
public static String convertToString(Source source,
        boolean includeXmlDeclaration) throws TransformerException {

    Transformer transformer = Transformers.newFormatingTransformer();
    if (!includeXmlDeclaration) {
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
                "yes");
    }

    StringWriter stringWriter = new StringWriter();
    try {
        transformer.transform(source, new StreamResult(stringWriter));
        return stringWriter.toString();
    } finally {
        try {
            stringWriter.close();
        } catch (IOException e) {
            // ignore
        }
    }
}
 
Example 8
Project: pgcodekeeper   File: XmlStringList.java   View source code 6 votes vote down vote up
public <T> void serializeList(List<T> listToConvert, boolean noFormatting,
        Writer writer) throws TransformerException, IOException {
    Document xml;
    try {
        xml = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException ex) {
        throw new IOException(ex);
    }
    
    Element root = xml.createElement(rootTagName);
    xml.appendChild(root);
    
    for (T listElement : listToConvert) {
        Element newElement = xml.createElement(elementTagName);
        newElement.setTextContent(listElement.toString());
        root.appendChild(newElement);
    }
    
    Transformer tf =  TransformerFactory.newInstance().newTransformer();
    if (!noFormatting) {
        tf.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
        tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$
    }
    tf.transform(new DOMSource(xml), new StreamResult(writer));
}
 
Example 9
Project: featurea   File: XMLOutputVisitor.java   View source code 6 votes vote down vote up
private void doTransform(String sXSL, OutputStream os) throws javax.xml.transform.TransformerConfigurationException, javax.xml.transform.TransformerException {
    // create the transformerfactory & transformer instance
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();

    if (null == sXSL) {
        t.transform(new DOMSource(doc), new StreamResult(os));
        return;
    }

    try {
        Transformer finalTransformer = tf.newTransformer(new StreamSource(sXSL));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(baos);
        t.transform(new DOMSource(doc), new StreamResult(bos));
        bos.flush();
        StreamSource xmlSource = new StreamSource(new BufferedInputStream(new ByteArrayInputStream(baos.toByteArray())));
        finalTransformer.transform(xmlSource, new StreamResult(os));
    } catch (IOException ioe) {
        throw new javax.xml.transform.TransformerException(ioe);
    }
}
 
Example 10
Project: OSWf-OSWorkflow-fork   File: WfDefinitionServiceImpl.java   View source code 6 votes vote down vote up
String colorizeXML(String xml, String xsltFilename) throws TransformerConfigurationException, TransformerException {

       // Get the XSLT file as a resource
       InputStream xslt = getClass().getResourceAsStream(xsltFilename);
       
       // Create and configure XSLT Transformer 
       TransformerFactory factory = TransformerFactory.newInstance();
       Transformer transformer = factory.newTransformer(new StreamSource(xslt));
       transformer.setParameter("indent-elements", "yes");
       
       OutputStream outputStream = new ByteArrayOutputStream();
       InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
       
       // Convert the XML into HTML per the XSLT file
       transformer.transform(new StreamSource(inputStream), new StreamResult(outputStream));
       
       return new String(((ByteArrayOutputStream)outputStream).toByteArray());
   }
 
Example 11
Project: openjdk-jdk10   File: SAX2DOMTest.java   View source code 6 votes vote down vote up
@Test
public void test() throws Exception {
    SAXParserFactory fac = SAXParserFactory.newInstance();
    fac.setNamespaceAware(true);
    SAXParser saxParser = fac.newSAXParser();

    StreamSource sr = new StreamSource(this.getClass().getResourceAsStream("SAX2DOMTest.xml"));
    InputSource is = SAXSource.sourceToInputSource(sr);
    RejectDoctypeSaxFilter rf = new RejectDoctypeSaxFilter(saxParser);
    SAXSource src = new SAXSource(rf, is);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    DOMResult result = new DOMResult();
    transformer.transform(src, result);

    Document doc = (Document) result.getNode();
    System.out.println("Name" + doc.getDocumentElement().getLocalName());

    String id = "XWSSGID-11605791027261938254268";
    Element selement = doc.getElementById(id);
    if (selement == null) {
        System.out.println("getElementById returned null");
    }

}
 
Example 12
Project: bohemia   File: XmlUtils.java   View source code 6 votes vote down vote up
/** 
 * Converts the Node/Document/Element instance to XML payload. 
 * 
 * @param node the node/document/element instance to convert 
 * @return the XML payload representing the node/document/element 
 * @throws XmlException problem converting XML to string 
 */  
public static String nodeToString(Node node) throws XmlException {  
    String payload = null;  
  
    try {  
        Transformer tf = TransformerFactory.newInstance().newTransformer();  
  
        Properties props = tf.getOutputProperties();  
        props.setProperty(OutputKeys.INDENT, LOGIC_YES);  
        props.setProperty(OutputKeys.ENCODING, DEFAULT_ENCODE);  
        tf.setOutputProperties(props);  
  
        StringWriter writer = new StringWriter();  
        tf.transform(new DOMSource(node), new StreamResult(writer));  
        payload = writer.toString();  
        payload = payload.replaceAll(REG_INVALID_CHARS, " ");  
    } catch (TransformerException e) {  
        throw new XmlException(XmlException.XML_TRANSFORM_ERROR, e);  
    }  
  
    return payload;  
}
 
Example 13
Project: joai-project   File: CollectionAdopter.java   View source code 6 votes vote down vote up
/**
 *  Gets the ncsItemStream attribute of the CollectionAdopter object
 *
 * @param  nsdl_dc_stream  NOT YET DOCUMENTED
 * @return                 The ncsItemStream value
 * @exception  Exception   NOT YET DOCUMENTED
 */
public Element getNcsItemStream(Element nsdl_dc_stream) throws Exception {
	// return XSLTransformer.transformString (nsdl_dc, this.xslPath);
	String className = "net.sf.saxon.TransformerFactoryImpl";
	if (nsdl_dc_stream == null)
		return null;
	String nsdl_dc = nsdl_dc_stream.asXML();
	try {
		Transformer transformer =
			XSLTransformer.getTransformer(this.xslPath, className);
		String xml = XSLTransformer.transformString(nsdl_dc, transformer);
		if (xml != null && xml.trim().length() > 0)
			return DocumentHelper.parseText(xml).getRootElement();
	} catch (Throwable t) {
		prtln("transform problem: " + t.getMessage());
	}
	return null;
}
 
Example 14
Project: openjdk-jdk10   File: Bug6794483Test.java   View source code 6 votes vote down vote up
public String printXmlDoc(Document doc) throws Exception {
    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);

    TransformerFactory transformerFact = TransformerFactory.newInstance();
    transformerFact.setAttribute("indent-number", new Integer(4));
    Transformer transformer;

    transformer = transformerFact.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml");

    transformer.transform(new DOMSource(doc), result);
    return sw.toString();
}
 
Example 15
Project: KeYExperienceReport   File: SPLOpltionGenerator.java   View source code 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 16
Project: openjdk-jdk10   File: CR6652519Test.java   View source code 6 votes vote down vote up
@Test
public final void test1() {
    try {
        long start = System.currentTimeMillis();
        Transformer t = TransformerFactory.newInstance().newTransformer();
        File file = new File(getClass().getResource("msgAttach.xml").getFile());
        StreamSource source = new StreamSource(file);
        DOMResult result = new DOMResult();
        t.transform(source, result);

        long end = System.currentTimeMillis();
        System.out.println("Test2:Total Time Taken=" + (end - start));
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }
}
 
Example 17
Project: stroom-stats   File: XMLUtil.java   View source code 6 votes vote down vote up
public static TransformerHandler createTransformerHandler(final ErrorListener errorListener,
                                                          final boolean indentOutput) throws TransformerConfigurationException {
    final SAXTransformerFactory stf = (SAXTransformerFactory) TransformerFactoryFactory.newInstance();
    if (errorListener != null) {
        stf.setErrorListener(errorListener);
    }

    final TransformerHandler th = stf.newTransformerHandler();
    final Transformer transformer = th.getTransformer();
    setCommonOutputProperties(transformer, indentOutput);

    if (errorListener != null) {
        transformer.setErrorListener(errorListener);
    }

    return th;
}
 
Example 18
Project: TextHIN   File: SparqlExecutor.java   View source code 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 19
Project: OpenJSharp   File: MexEntityResolver.java   View source code 6 votes vote down vote up
public MexEntityResolver(List<? extends Source> wsdls) throws IOException {
    Transformer transformer = XmlUtil.newTransformer();
    for (Source source : wsdls) {
        XMLStreamBufferResult xsbr = new XMLStreamBufferResult();
        try {
            transformer.transform(source, xsbr);
        } catch (TransformerException e) {
            throw new WebServiceException(e);
        }
        String systemId = source.getSystemId();

        //TODO: can we do anything if the given mex Source has no systemId?
        if(systemId != null){
            SDDocumentSource doc = SDDocumentSource.create(JAXWSUtils.getFileOrURL(systemId), xsbr.getXMLStreamBuffer());
            this.wsdls.put(systemId, doc);
        }
    }
}
 
Example 20
Project: fluentxml4j   File: FluentXmlTransformerIntegrationTest.java   View source code 6 votes vote down vote up
@Test
public void streamToStringWithTransformers() throws Exception
{
	String resultXml = fluentXmlTransformer
			.transform(sourceDocumentRule.asInputStream())
			.withStylesheet(xsltDocumentRule.asDocument())
			.withStylesheet(xsltDocumentRule2.asInputStream())
			.withStylesheet(xsltDocumentRule3.asUrl())
			.withSerializer(new SerializerConfigurerAdapter()
			{
				@Override
				protected void configure(Transformer transformer)
				{
					super.configure(transformer);
					transformer.setOutputProperty(OutputKeys.INDENT, "no");
					transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
				}
			})
			.toString();

	assertThat(resultXml, is("<transformed3/>"));
}
 
Example 21
Project: fluentxml4j   File: FluentXmlTransformerIntegrationTest.java   View source code 6 votes vote down vote up
@Test
public void documentWithPrefixMappingToString() throws Exception
{
	String xml = fluentXmlTransformer
			.transform(sourceDocumentWithNSRule.asDocument())
			.withPrefixMapping("ns1", "ns2")
			.withSerializer(new SerializerConfigurerAdapter()
			{
				@Override
				protected void configure(Transformer transformer)
				{
					super.configure(transformer);
					transformer.setOutputProperty(OutputKeys.INDENT, "no");
					transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
				}
			})
			.toString();

	assertThat(xml, is("<ns2:source xmlns:ns2=\"uri:ns\" xmlns=\"uri:ns\" xmlns:ns1=\"uri:ns\"/>"));
}
 
Example 22
Project: fluentxml4j   File: FluentXmlTransformerIntegrationTest.java   View source code 6 votes vote down vote up
@Test
public void transformWithJAXBAndStylesheetToString() throws Exception
{
	String xml = fluentXmlTransformer.transform(JAXBContext.newInstance(JaxbSource.class), new JaxbSource())
			.withStylesheet(this.xsltDocumentRule.asDocument())
			.withSerializer(new SerializerConfigurerAdapter()
			{
				@Override
				protected void configure(Transformer transformer)
				{
					super.configure(transformer);
					transformer.setOutputProperty(OutputKeys.INDENT, "no");
					transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
				}
			})
			.toString();

	assertThat(xml, is("<transformed1/>"));
}
 
Example 23
Project: massim   File: Conversions.java   View source code 6 votes vote down vote up
/**
 * Transforms a DOM document to string.
 * @param doc the document to transform
 * @return the string representation of the doc or an empty string if sth. went wrong
 */
public static String docToString(Document doc, boolean indent){
    try {
        StringWriter writer = new StringWriter();
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        if (indent) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        }
        transformer.transform(new DOMSource(doc), new StreamResult(writer));
        return writer.getBuffer().toString();
    } catch (TransformerException e) {
        e.printStackTrace();
    }
    return "";
}
 
Example 24
Project: DaUtil   File: DomXmlUtils.java   View source code 6 votes vote down vote up
/**
 * 获取一个Transformer对象,由于使用时都做相同的初始化,所以提取出来作为公共方法。
 *
 * @return a Transformer encoding gb2312
 */

public static Transformer newTransformer() {
	try {
		Transformer transformer = TransformerFactory.newInstance()
				.newTransformer();
		Properties properties = transformer.getOutputProperties();
		properties.setProperty(OutputKeys.ENCODING, "gb2312");
		properties.setProperty(OutputKeys.METHOD, "xml");
		properties.setProperty(OutputKeys.VERSION, "1.0");
		properties.setProperty(OutputKeys.INDENT, "no");
		transformer.setOutputProperties(properties);
		return transformer;
	} catch (TransformerConfigurationException tce) {
		throw new RuntimeException(tce.getMessage());
	}
}
 
Example 25
Project: javaide   File: FormatFactory.java   View source code 6 votes vote down vote up
private static String formatXml(Context context, String src) throws TransformerException,
        ParserConfigurationException, IOException, SAXException {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(src)));

    AppSetting setting = new AppSetting(context);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", setting.getTab().length() + "");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

    //initialize StreamResult with File object to save to file
    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(doc);
    transformer.transform(source, result);
    return result.getWriter().toString();
}
 
Example 26
Project: neoscada   File: XMLBase.java   View source code 6 votes vote down vote up
protected void storeXmlDocument ( final Document doc, final File file ) throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException
{
    // create output directory

    file.getParentFile ().mkdirs ();

    // write out xml

    final TransformerFactory transformerFactory = TransformerFactory.newInstance ();

    final Transformer transformer = transformerFactory.newTransformer ();
    transformer.setOutputProperty ( OutputKeys.INDENT, "yes" ); //$NON-NLS-1$

    final DOMSource source = new DOMSource ( doc );
    final StreamResult result = new StreamResult ( file );
    transformer.transform ( source, result );
}
 
Example 27
Project: openjdk-jdk10   File: Bug6490921.java   View source code 5 votes vote down vote up
@Test
public void test02() {
    String xml = "<?xml version='1.0'?><root/>";
    ReaderStub.used = false;
    setSystemProperty("org.xml.sax.driver", ReaderStub.class.getName());
    try {
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer();
        InputSource in = new InputSource(new StringReader(xml));
        SAXSource source = new SAXSource(in);
        StreamResult result = new StreamResult(new StringWriter());
        transformer.transform(source, result);
        Assert.assertTrue(printWasReaderStubCreated());
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
}
 
Example 28
Project: openjdk-jdk10   File: SourceTest.java   View source code 5 votes vote down vote up
@Test
public final void testSAXSource() {
    String xml = getClass().getResource("SourceTest.xml").getFile();
    File xsl = new File(getClass().getResource("SourceTest.xsl").getFile());
    try {
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();
        StreamSource source = new StreamSource(xsl);
        transformer = tFactory.newTransformer(source);
        // the xml result
        StringWriter xmlResultString = new StringWriter();
        StreamResult xmlResultStream = new StreamResult(xmlResultString);

        Source xmlSource = new SAXSource();
        xmlSource.setSystemId(xml);

        transformer.transform(xmlSource, xmlResultStream);
        System.out.println(xmlResultString.toString());
        String temp = xmlResultString.toString();
        int pos = temp.lastIndexOf("count");
        if (temp.substring(pos + 8, pos + 9).equals("1")) {
            Assert.fail("count=1");
        } else if (temp.substring(pos + 8, pos + 9).equals("2")) {
            // expected success
            System.out.println("count=2");
        }
    } catch (Exception e) {
        // unexpected failure
        e.printStackTrace();
        Assert.fail(e.toString());
    }
}
 
Example 29
Project: openjdk-jdk10   File: StylesheetTest.java   View source code 5 votes vote down vote up
/**
 * @bug 8058152
 * Verifies that an error is reported if the xsl:import element
 * is not at the top of the stylesheet.
 * @throws TransformerConfigurationException
 */
@Test(dataProvider = "invalidImport", expectedExceptions = TransformerConfigurationException.class)
public void testInvalidImport(String xsl) throws TransformerConfigurationException {
    StringReader xsl1 = new StringReader(xsl);
    TransformerFactory factory = TransformerFactory.newInstance();
    SAXSource xslSource = new SAXSource(new InputSource(xsl1));
    Transformer transformer = factory.newTransformer(xslSource);
}
 
Example 30
Project: RLibrary   File: L.java   View source code 5 votes vote down vote up
private static void printXml(String tag, String xml, String headString) {
    if (TextUtils.isEmpty(tag)) {
        tag = TAG;
    }
    if (xml != null) {
        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);
            xml = xmlOutput.getWriter().toString().replaceFirst(">", ">\n");
        } catch (Exception e) {
            e.printStackTrace();
        }
        xml = headString + "\n" + xml;
    } else {
        xml = headString + "Log with null object";
    }

    printLine(tag, true);
    String[] lines = xml.split(LINE_SEPARATOR);
    for (String line : lines) {
        if (!TextUtils.isEmpty(line)) {
            Log.d(tag, "|" + line);
        }
    }
    printLine(tag, false);
}
 
Example 31
Project: octoBubbles   File: PersistenceManager.java   View source code 5 votes vote down vote up
public static void exportXMI(Graph pGraph, String path){
    try{
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();

        DOMSource source = new DOMSource(createXmi(pGraph));

        StreamResult result = new StreamResult(new File(path));
        transformer.transform(source, result);
    } catch (TransformerException tfe) {
        tfe.printStackTrace();
    }
}
 
Example 32
Project: jdk8u-jdk   File: Test.java   View source code 5 votes vote down vote up
private static String toString(Source response) throws TransformerException, IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(response, new StreamResult(bos));
    bos.close();
    return new String(bos.toByteArray());
}
 
Example 33
Project: joai-project   File: XSLTransformer.java   View source code 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. To convert the resulting StringWriter to a String, call StringWriter.toString().
 *
 * @param  inputFilePath  The XML file 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 transformFileToWriter(String inputFilePath, Transformer transformer) {
	try {
		StringWriter writer = new StringWriter();
		transformer.transform(new StreamSource(new FileInputStream(inputFilePath)), new StreamResult(writer));
		return writer;
	} catch (Throwable e) {
		prtlnErr(e);
		return new StringWriter();
	}
}
 
Example 34
Project: nfse   File: AssinaturaDigital.java   View source code 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 35
Project: openjdk-jdk10   File: Test.java   View source code 5 votes vote down vote up
private static String toString(Source response) throws TransformerException, IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(response, new StreamResult(bos));
    bos.close();
    return new String(bos.toByteArray());
}
 
Example 36
Project: openjdk-jdk10   File: TransformerTest.java   View source code 5 votes vote down vote up
@Test(dataProvider = "testdata8150704")
public void run(String xsl, String xml, String ref) throws IOException, TransformerException {
    System.out.println("Testing transformation of " + xml + "...");
    setXsl(fromInputStream(getClass().getResourceAsStream(xsl)));
    setSourceXml(fromInputStream(getClass().getResourceAsStream(xml)));
    Transformer t = getTransformer();
    StringWriter resultWriter = new StringWriter();
    t.transform(getStreamSource(), new StreamResult(resultWriter));
    String resultString = resultWriter.toString().replaceAll("\\r\\n", "\n").replaceAll("\\r", "\n").trim();
    String reference = fromInputStream(getClass().getResourceAsStream(ref)).trim();
    Assert.assertEquals(resultString, reference, "Output of transformation of " + xml + " does not match reference");
    System.out.println("Passed.");
}
 
Example 37
Project: incubator-netbeans   File: XMLUtil.java   View source code 5 votes vote down vote up
public static void write(Element el, OutputStream out) throws IOException {
    try {
        Transformer t = TransformerFactory.newInstance().newTransformer(
                new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT)));
        t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // NOI18N
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        Source source = new DOMSource(el);
        Result result = new StreamResult(out);
        t.transform(source, result);
    } catch (Exception | TransformerFactoryConfigurationError e) {
        throw new IOException(e);
    }
}
 
Example 38
Project: incubator-netbeans   File: Arch.java   View source code 5 votes vote down vote up
private static String elementToString(Element e) throws IOException {
    try {
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.INDENT, "no"); // NOI18N
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // NOI18N
        Source source = new DOMSource(e);
        StringWriter w = new StringWriter();
        Result result = new StreamResult(w);
        t.transform(source, result);
        return w.toString();
    } catch (Exception x) {
        throw (IOException)new IOException(x.toString()).initCause(x);
    }
}
 
Example 39
Project: openjdk-jdk10   File: AbstractFilterFactory.java   View source code 5 votes vote down vote up
@Override
public TransformerHandler newDECFilter(double min, double max) throws TransformerConfigurationException, SAXException, ParserConfigurationException,
        IOException {
    TransformerHandler retval = getTransformerHandler(getDECXsl());
    Transformer xformer = retval.getTransformer();
    xformer.setParameter("dec_min_deg", String.valueOf(min));
    xformer.setParameter("dec_max_deg", String.valueOf(max));
    return retval;
}
 
Example 40
Project: OpenJSharp   File: BGMBuilder.java   View source code 5 votes vote down vote up
/**
 * Gets the shared instance of the identity transformer.
 */
public Transformer getIdentityTransformer() {
    try {
        if(identityTransformer==null) {
            TransformerFactory tf = XmlFactory.createTransformerFactory(model.options.disableXmlSecurity);
            identityTransformer = tf.newTransformer();
        }
        return identityTransformer;
    } catch (TransformerConfigurationException e) {
        throw new Error(e); // impossible
    }
}