javax.xml.transform.stream.StreamResult Java Examples

The following examples show how to use javax.xml.transform.stream.StreamResult. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BundleRepoTest.java    From ant-ivy with Apache License 2.0 6 votes vote down vote up
@Test
public void testXMLSerialisation() throws SAXException, IOException {
    FSManifestIterable it = new FSManifestIterable(bundlerepo);
    BundleRepoDescriptor repo = new BundleRepoDescriptor(bundlerepo.toURI(),
            ExecutionEnvironmentProfileProvider.getInstance());
    repo.populate(it.iterator());

    SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler hd;
    try {
        hd = tf.newTransformerHandler();
    } catch (TransformerConfigurationException e) {
        throw new BuildException("Sax configuration error: " + e.getMessage(), e);
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    StreamResult stream = new StreamResult(out);
    hd.setResult(stream);

    OBRXMLWriter.writeManifests(it, hd, false);

    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    BundleRepoDescriptor repo2 = OBRXMLParser.parse(bundlerepo.toURI(), in);

    assertEquals(repo, repo2);
}
 
Example #2
Source File: SAXTFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test newTransformerHandler with a Template Handler.
 *
 * @throws Exception If any errors occur.
 */
public void testcase08() throws Exception {
    String outputFile = USER_DIR + "saxtf008.out";
    String goldFile = GOLDEN_DIR + "saxtf008GF.out";

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

        TemplatesHandler thandler = saxTFactory.newTemplatesHandler();
        reader.setContentHandler(thandler);
        reader.parse(XSLT_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 #3
Source File: PythonNatureStore.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Serializes an Xml document to an array of bytes.
 *
 * @param doc
 * @return the array of bytes representing the Xml document
 * @throws IOException
 * @throws TransformerException
 */
private byte[] serializeDocument(Document doc) throws IOException, TransformerException {
    traceFunc("serializeDocument");
    synchronized (this) {
        ByteArrayOutputStream s = new ByteArrayOutputStream();

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$

        DOMSource source = new DOMSource(doc);
        StreamResult outputTarget = new StreamResult(s);
        transformer.transform(source, outputTarget);

        traceFunc("END serializeDocument");
        return s.toByteArray();
    }
}
 
Example #4
Source File: XmlSupport.java    From java-ocr-api with GNU Affero General Public License v3.0 6 votes vote down vote up
private static final void writeDoc(Document doc, OutputStream out)
    throws IOException
{
    try {
        TransformerFactory tf = TransformerFactory.newInstance();
        try {
            tf.setAttribute("indent-number", new Integer(2));
        } catch (IllegalArgumentException iae) {

        }
        Transformer t = tf.newTransformer();
        t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doc.getDoctype().getSystemId());
        t.setOutputProperty(OutputKeys.INDENT, "yes");

        t.transform(new DOMSource(doc),
                    new StreamResult(new BufferedWriter(new OutputStreamWriter(out, "UTF-8"))));
    } catch(TransformerException e) {
        throw new AssertionError(e);
    }
}
 
Example #5
Source File: MarshallingViewTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void renderNoModelKeyAndBindingResultFirst() throws Exception {
	Object toBeMarshalled = new Object();
	String modelKey = "key";
	Map<String, Object> model = new LinkedHashMap<>();
	model.put(BindingResult.MODEL_KEY_PREFIX + modelKey, new BeanPropertyBindingResult(toBeMarshalled, modelKey));
	model.put(modelKey, toBeMarshalled);

	MockHttpServletRequest request = new MockHttpServletRequest();
	MockHttpServletResponse response = new MockHttpServletResponse();

	given(marshallerMock.supports(BeanPropertyBindingResult.class)).willReturn(true);
	given(marshallerMock.supports(Object.class)).willReturn(true);

	view.render(model, request, response);
	assertEquals("Invalid content type", "application/xml", response.getContentType());
	assertEquals("Invalid content length", 0, response.getContentLength());
	verify(marshallerMock).marshal(eq(toBeMarshalled), isA(StreamResult.class));
}
 
Example #6
Source File: DependencyResolver.java    From camel-spring-boot with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves a list of dependencies of the given scope
 */
public static List<String> getDependencies(String pom, String scope) throws Exception {
    String expression = "/project/dependencies/dependency[scope='" + scope + "']";

    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(pom);
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile(expression);

    List<String> dependencies = new LinkedList<>();
    NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        try (StringWriter writer = new StringWriter()) {
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.transform(new DOMSource(node), new StreamResult(writer));
            String xml = writer.toString();
            dependencies.add(xml);
        }
    }

    return dependencies;
}
 
Example #7
Source File: StandardSREInstallTest.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Test
public void getAsXML() throws Exception {
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	DocumentBuilder builder = factory.newDocumentBuilder();
	Document xmldocument = builder.newDocument();
	Element root = xmldocument.createElement("root"); //$NON-NLS-1$
	this.sre.getAsXML(xmldocument, root);
	xmldocument.appendChild(root);
	TransformerFactory transFactory = TransformerFactory.newInstance();
	Transformer trans = transFactory.newTransformer();
	try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
		DOMSource source = new DOMSource(xmldocument);
		PrintWriter flot = new PrintWriter(baos);
		StreamResult xmlStream = new StreamResult(flot);
		trans.transform(source, xmlStream);
		String content = new String(baos.toByteArray());
		String[] expected = new String[] { "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>",
				"<root libraryPath=\"" + this.path.toPortableString() + "\" standalone=\"false\"/>", };
		StringBuilder b = new StringBuilder();
		for (String s : expected) {
			b.append(s);
			// b.append("\n");
		}
		assertEquals(b.toString(), content);
	}
}
 
Example #8
Source File: ValidatorHelper.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private static InputStream convert(final Source source) {
   try {
      InputStreamFromOutputStream<Void> isOs = new InputStreamFromOutputStream<Void>() {
         protected Void produce(OutputStream sink) throws Exception {
            Result result = new StreamResult(sink);
            Transformer transformer = ValidatorHelper.TRF.newTransformer();
            transformer.setOutputProperty("omit-xml-declaration", "yes");
            transformer.transform(source, result);
            return null;
         }
      };
      return isOs;
   } catch (Exception var2) {
      throw new IllegalArgumentException(var2);
   }
}
 
Example #9
Source File: ValidatorHelper.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private static InputStream convert(final Source source) {
   try {
      InputStreamFromOutputStream<Void> isOs = new InputStreamFromOutputStream<Void>() {
         protected Void produce(OutputStream sink) throws Exception {
            Result result = new StreamResult(sink);
            Transformer transformer = ValidatorHelper.TRF.newTransformer();
            transformer.setOutputProperty("omit-xml-declaration", "yes");
            transformer.transform(source, result);
            return null;
         }
      };
      return isOs;
   } catch (Exception var2) {
      throw new IllegalArgumentException(var2);
   }
}
 
Example #10
Source File: FileUtils.java    From BuildmLearn-Toolkit-Android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * @param destinationFolder Destination folder for saving the file
 * @param fileName          Destination file name
 * @param doc               Document object to be converted to xml formatted file
 * @return Returns true if successfully converted
 * @brief Converts a given Document object to xml format file
 */
public static boolean saveXmlFile(String destinationFolder, String fileName, Document doc) {

    File f = new File(destinationFolder);
    if (!f.isDirectory()) {
        f.mkdirs();
    }
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer;
    try {
        File newTemplateFile=new File(destinationFolder + fileName);
        if(newTemplateFile.exists())
            return false;
        transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(newTemplateFile);
        transformer.transform(source, result);

    } catch (TransformerException e) {
        e.printStackTrace();
    }
    return true;
}
 
Example #11
Source File: DependencyServiceImpl.java    From score with Apache License 2.0 6 votes vote down vote up
private void removeByXpathExpression(String pomFilePath, String expression) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException, TransformerException {
    File xmlFile = new File(pomFilePath);
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nl = (NodeList) xpath.compile(expression).
            evaluate(doc, XPathConstants.NODESET);

    if (nl != null && nl.getLength() > 0) {
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            node.getParentNode().removeChild(node);
        }

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        // need to convert to file and then to path to override a problem with spaces
        Result output = new StreamResult(new File(pomFilePath).getPath());
        Source input = new DOMSource(doc);
        transformer.transform(input, output);
    }
}
 
Example #12
Source File: AbstractMarshaller.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Marshals the object graph with the given root into the provided {@code javax.xml.transform.Result}.
 * <p>This implementation inspects the given result, and calls {@code marshalDomResult},
 * {@code marshalSaxResult}, or {@code marshalStreamResult}.
 * @param graph the root of the object graph to marshal
 * @param result the result to marshal to
 * @throws IOException if an I/O exception occurs
 * @throws XmlMappingException if the given object cannot be marshalled to the result
 * @throws IllegalArgumentException if {@code result} if neither a {@code DOMResult},
 * a {@code SAXResult}, nor a {@code StreamResult}
 * @see #marshalDomResult(Object, javax.xml.transform.dom.DOMResult)
 * @see #marshalSaxResult(Object, javax.xml.transform.sax.SAXResult)
 * @see #marshalStreamResult(Object, javax.xml.transform.stream.StreamResult)
 */
@Override
public final void marshal(Object graph, Result result) throws IOException, XmlMappingException {
	if (result instanceof DOMResult) {
		marshalDomResult(graph, (DOMResult) result);
	}
	else if (StaxUtils.isStaxResult(result)) {
		marshalStaxResult(graph, result);
	}
	else if (result instanceof SAXResult) {
		marshalSaxResult(graph, (SAXResult) result);
	}
	else if (result instanceof StreamResult) {
		marshalStreamResult(graph, (StreamResult) result);
	}
	else {
		throw new IllegalArgumentException("Unknown Result type: " + result.getClass());
	}
}
 
Example #13
Source File: IoTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES)
@FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES)
@FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_INTEGER_VALUES)
@FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_FLOAT_VALUES)
public void shouldTransformGraphMLV2ToV3ViaXSLT() throws Exception {
    final InputStream stylesheet = Thread.currentThread().getContextClassLoader().getResourceAsStream("tp2-to-tp3-graphml.xslt");
    final InputStream datafile = getResourceAsStream(GraphMLResourceAccess.class, "tinkerpop-classic-tp2.xml");
    final ByteArrayOutputStream output = new ByteArrayOutputStream();

    final TransformerFactory tFactory = TransformerFactory.newInstance();
    final StreamSource stylesource = new StreamSource(stylesheet);
    final Transformer transformer = tFactory.newTransformer(stylesource);

    final StreamSource source = new StreamSource(datafile);
    final StreamResult result = new StreamResult(output);
    transformer.transform(source, result);

    final GraphReader reader = GraphMLReader.build().create();
    reader.readGraph(new ByteArrayInputStream(output.toByteArray()), graph);
    assertClassicGraph(graph, false, true);
}
 
Example #14
Source File: XmlSupport.java    From java-scanner-access-twain with GNU Affero General Public License v3.0 6 votes vote down vote up
private static final void writeDoc(Document doc, OutputStream out)
    throws IOException
{
    try {
        TransformerFactory tf = TransformerFactory.newInstance();
        try {
            tf.setAttribute("indent-number", new Integer(2));
        } catch (IllegalArgumentException iae) {

        }
        Transformer t = tf.newTransformer();
        t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doc.getDoctype().getSystemId());
        t.setOutputProperty(OutputKeys.INDENT, "yes");

        t.transform(new DOMSource(doc),
                    new StreamResult(new BufferedWriter(new OutputStreamWriter(out, "UTF-8"))));
    } catch(TransformerException e) {
        throw new AssertionError(e);
    }
}
 
Example #15
Source File: AbstractBingExtractor.java    From wandora with GNU General Public License v3.0 6 votes vote down vote up
protected String getStringFromDocument(Document doc) {
    try {
        DOMSource domSource = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(domSource, result);

        return writer.toString();
    }

    catch(TransformerException ex) {
        ex.printStackTrace();
        return null;
    }
}
 
Example #16
Source File: ToolsUtil.java    From XPagesExtensionLibrary with Apache License 2.0 6 votes vote down vote up
private static String nodeToString(Node node) {
    StringWriter sw = new StringWriter();
    try {
      Transformer t = TransformerFactory.newInstance().newTransformer();
      t.setOutputProperty(OutputKeys.INDENT, "yes");
      t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
      t.transform(new DOMSource(node), new StreamResult(sw));
    } catch (TransformerException te) {
    	throw new RuntimeException(te);
    }
    String asStr = sw.toString();
    String xmlDecl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
    String badStart = xmlDecl+"<";
    if( asStr.startsWith(badStart) ){ // missing newline after xmlDecl
    	asStr = xmlDecl+NEWLINE+asStr.substring(xmlDecl.length());
    }
    // convert the newline character in render-markup elements from
    // &#13; to &#xd; (hex encoding of same character), to be consistent
    // with the previous XML serializer.
    asStr = asStr.replace("&#13;", "&#xd;");
    return asStr+NEWLINE;
}
 
Example #17
Source File: Utilities.java    From TableDisentangler with GNU General Public License v3.0 6 votes vote down vote up
public static String CreateXMLStringFromSubNodeWithoutDeclaration(Element xml) {
	xml = xml.getAllElements().first();
	String result = "";
	try {
		StringWriter sw = new StringWriter();
		Transformer serializer = TransformerFactory.newInstance()
				.newTransformer();
		serializer
				.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
		DocumentBuilderFactory factory = DocumentBuilderFactory
				.newInstance();
		factory.setNamespaceAware(true);
		factory.setValidating(false);
		DocumentBuilder builder = factory.newDocumentBuilder();
		Node fragmentNode = builder.parse(
		        new InputSource(new StringReader(xml.html())))
		        .getDocumentElement();
		serializer.transform(new DOMSource(fragmentNode), new StreamResult(sw));
		result = sw.toString();
	} catch (Exception ex) {
		ex.printStackTrace();
	}
	return result;
}
 
Example #18
Source File: ReportDaoImpl.java    From spoon-maven-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void report(Map<ReportBuilderImpl.ReportKey, Object> data)
		throws ParserConfigurationException, TransformerException {
	DocumentBuilderFactory bFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder docBuilder = bFactory.newDocumentBuilder();

	// Adds all elements.
	final Document doc = docBuilder.newDocument();
	final Element root = addRoot(doc, data);
	addProcessors(doc, root, data);

	addElement(doc, root, data, INPUT, (String) data.get(INPUT));
	addElement(doc, root, data, OUTPUT, (String) data.get(OUTPUT));
	addElement(doc, root, data, SOURCE_CLASSPATH, (String) data.get(SOURCE_CLASSPATH));
	addElement(doc, root, data, PERFORMANCE, Long.toString((Long) data.get(PERFORMANCE)));

	// write the content into xml file
	TransformerFactory transfFactory = TransformerFactory.newInstance();
	Transformer transformer = transfFactory.newTransformer();
	DOMSource source = new DOMSource(doc);
	StreamResult result = new StreamResult(resultFile.getAbsolutePath());
	transformer.transform(source, result);
}
 
Example #19
Source File: Bug6388460.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test() {
    try {

        Source source = new StreamSource(util.BOMInputStream.createStream("UTF-16BE", this.getClass().getResourceAsStream("Hello.wsdl.data")),
                    this.getClass().getResource("Hello.wsdl.data").toExternalForm());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.transform(source, new StreamResult(baos));
        System.out.println(new String(baos.toByteArray()));
        ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
        InputSource inSource = new InputSource(bis);

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        XMLStreamReader reader = xmlInputFactory.createXMLStreamReader(inSource.getSystemId(), inSource.getByteStream());
        while (reader.hasNext()) {
            reader.next();
        }
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
        Assert.fail("Exception occured: " + ex.getMessage());
    }
}
 
Example #20
Source File: DemoSpringWsApplicationTests.java    From spring-boot-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendingHolidayRequest() {
	final String request = "<hr:HolidayRequest xmlns:hr=\"http://joedayz.pe/hr/schemas\">"
			+ "   <hr:Holiday>"
			+ "      <hr:StartDate>2013-10-20</hr:StartDate>"
			+ "      <hr:EndDate>2013-11-22</hr:EndDate>"
			+ "   </hr:Holiday>"
			+ "   <hr:Employee>"
			+ "      <hr:Number>1</hr:Number>"
			+ "      <hr:FirstName>John</hr:FirstName>"
			+ "      <hr:LastName>Doe</hr:LastName>"
			+ "   </hr:Employee>"
			+ "</hr:HolidayRequest>";

	StreamSource source = new StreamSource(new StringReader(request));
	StreamResult result = new StreamResult(System.out);

	this.webServiceTemplate.sendSourceAndReceiveToResult(source, result);
	assertThat(this.output.toString(), 
			containsString("Booking holiday for"));
}
 
Example #21
Source File: AuctionItemRepository.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test for xi:fallback where the fall back text is parsed as text. This
 * test uses a nested xi:include for the fallback test.
 *
 * @throws Exception If any errors occur.
 */
@Test(groups = {"readWriteLocalFiles"})
public void testXIncludeFallbackTextPos() throws Exception {
    String resultFile = USER_DIR + "doc_fallback_text.out";
    String goldFile = GOLDEN_DIR + "doc_fallback_textGold.xml";
    String xmlFile = XML_DIR + "doc_fallback_text.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 #22
Source File: XMLUtil.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public static void writeDomToFile(Document doc, String filename) throws TransformerException {
  TransformerFactory transformerFactory = TransformerFactory.newInstance();
  Transformer transformer = transformerFactory.newTransformer();
  DOMSource source = new DOMSource(doc);
  StreamResult streamResult =  new StreamResult(new File(filename));
  transformer.transform(source, streamResult);    
}
 
Example #23
Source File: BusinessContentEncryptor.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static String toStringOmittingXmlDeclaration(NodeList nodes) throws TransformerException {
   StringBuilder sb = new StringBuilder();
   TransformerFactory tf = TransformerFactory.newInstance();
   Transformer serializer = tf.newTransformer();
   serializer.setOutputProperty("omit-xml-declaration", "yes");

   for(int i = 0; i < nodes.getLength(); ++i) {
      StringWriter sw = new StringWriter();
      serializer.transform(new DOMSource(nodes.item(i)), new StreamResult(sw));
      sb.append(sw.toString());
   }

   return sb.toString();
}
 
Example #24
Source File: XSLT.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws TransformerException {
    ByteArrayOutputStream resStream = new ByteArrayOutputStream();
    TransformerFactory trf = TransformerFactory.newInstance();
    Transformer tr = trf.newTransformer(new StreamSource(System.getProperty("test.src", ".") + XSLTRANSFORMER));
    tr.transform(new StreamSource(System.getProperty("test.src", ".") + XMLTOTRANSFORM), new StreamResult(resStream));
    System.out.println("Transformation completed. Result:" + resStream.toString());
    if (!resStream.toString().equals(EXPECTEDRESULT)) {
        throw new RuntimeException("Incorrect transformation result");
    }
}
 
Example #25
Source File: TestXMLPropertiesConfiguration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
@Test
public void testDOMSave() throws Exception
{
    // load the configuration
    final XMLPropertiesConfiguration conf = load(TEST_PROPERTIES_FILE);

    // update the configuration
    conf.addProperty("key4", "value4");
    conf.clearProperty("key2");
    conf.setHeader("Description of the new property list");

    // save the configuration
    final File saveFile = folder.newFile("test2.properties.xml");

    // save as DOM into saveFile
    final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    final DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    final Document document = dBuilder.newDocument();
    conf.save(document, document);
    final TransformerFactory tFactory = TransformerFactory.newInstance();
    final Transformer transformer = tFactory.newTransformer();
    final DOMSource source = new DOMSource(document);
    final Result result = new StreamResult(saveFile);
    transformer.transform(source, result);

    // reload the configuration
    final XMLPropertiesConfiguration conf2 = load(saveFile.getAbsolutePath());

    // test the configuration
    assertEquals("header", "Description of the new property list", conf2.getHeader());

    assertFalse("The configuration is empty", conf2.isEmpty());
    assertEquals("'key1' property", "value1", conf2.getProperty("key1"));
    assertEquals("'key3' property", "value3", conf2.getProperty("key3"));
    assertEquals("'key4' property", "value4", conf2.getProperty("key4"));
}
 
Example #26
Source File: XStreamMarshallerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void jettisonDriver() throws Exception {
	marshaller.setStreamDriver(new JettisonMappedXmlDriver());
	Writer writer = new StringWriter();
	marshaller.marshal(flight, new StreamResult(writer));
	assertEquals("Invalid result", "{\"flight\":{\"flightNumber\":42}}", writer.toString());
	Object o = marshaller.unmarshal(new StreamSource(new StringReader(writer.toString())));
	assertTrue("Unmarshalled object is not Flights", o instanceof Flight);
	Flight unflight = (Flight) o;
	assertNotNull("Flight is null", unflight);
	assertEquals("Number is invalid", 42L, unflight.getFlightNumber());
}
 
Example #27
Source File: XOMParserTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public final void testTransform() {
    String inFilename = filePath + "/JDK8022548.xml";
    String xslFilename = filePath + "/JDK8022548.xsl";
    String outFilename = "JDK8022548.out";

    try (InputStream xslInput = new FileInputStream(xslFilename);
         InputStream xmlInput = new FileInputStream(inFilename);
         OutputStream out = new FileOutputStream(outFilename);
    ) {


        StringWriter sw = new StringWriter();
        // Create transformer factory
        TransformerFactory factory = TransformerFactory.newInstance();

        // Use the factory to create a template containing the xsl file
        Templates template = factory.newTemplates(new StreamSource(xslInput));
        // Use the template to create a transformer
        Transformer xformer = template.newTransformer();
        // Prepare the input and output files
        Source source = new StreamSource(xmlInput);
        Result result = new StreamResult(outFilename);
        //Result result = new StreamResult(sw);
        // Apply the xsl file to the source file and write the result to the output file
        xformer.transform(source, result);

        /**
         * String out = sw.toString(); if (out.indexOf("<p>") < 0 ) {
         * fail(out); }
         */
        String canonicalizedFileName = outFilename + ".canonicalized";
        canonicalize(outFilename, canonicalizedFileName);
    } catch (Exception e) {
        // unexpected failure
        fail(e.getMessage());
    }
}
 
Example #28
Source File: PermutationsIO.java    From gwt-appcache with Apache License 2.0 5 votes vote down vote up
private static String transformDocumentToString( final Document document )
  throws Exception
{
  final StringWriter xml = new StringWriter();
  final Transformer transformer = TransformerFactory.newInstance().newTransformer();
  transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
  transformer.transform( new DOMSource( document ), new StreamResult( xml ) );
  return xml.toString();
}
 
Example #29
Source File: LibVersionsCheckTask.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private String xmlToString(File ivyXmlFile) {
  StringWriter writer = new StringWriter();
  try {
    StreamSource inputSource = new StreamSource(new FileInputStream(ivyXmlFile.getPath()));
    Transformer serializer = TransformerFactory.newInstance().newTransformer();
    serializer.transform(inputSource, new StreamResult(writer));
  } catch (TransformerException | IOException e) {
    throw new BuildException("Exception reading " + ivyXmlFile.getPath() + ": " + e.toString(), e);
  }
  return writer.toString();
}
 
Example #30
Source File: XML.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
public String saveToString() throws Exception {
    Source domSource = new DOMSource(doc);
    StringWriter writer = new StringWriter();
    Result result = new StreamResult(writer);
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.transform(domSource, result);
    String text=writer.toString();
    int index=text.indexOf(">");
    if (text.substring(index+1,index+2).equals("\n")==false){
        text=text.substring(0,index+1)+"\n"+text.substring(index+1);
    }
    return text;
}