javax.servlet.http.HttpUtils#javax.xml.transform.stream.StreamResult源码实例Demo

下面列出了javax.servlet.http.HttpUtils#javax.xml.transform.stream.StreamResult 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: XPagesExtensionLibrary   文件: ToolsUtil.java
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;
}
 
源代码2 项目: score   文件: DependencyServiceImpl.java
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);
    }
}
 
源代码3 项目: sarl   文件: StandardSREInstallTest.java
@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);
	}
}
 
源代码4 项目: Pydev   文件: PythonNatureStore.java
/**
 * 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();
    }
}
 
@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));
}
 
源代码6 项目: java-ocr-api   文件: XmlSupport.java
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);
    }
}
 
源代码7 项目: spring-analysis-note   文件: AbstractMarshaller.java
/**
 * 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());
	}
}
 
源代码8 项目: tinkerpop   文件: IoTest.java
@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);
}
 
源代码9 项目: spoon-maven-plugin   文件: ReportDaoImpl.java
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);
}
 
@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"));
}
 
源代码11 项目: openjdk-jdk9   文件: AuctionItemRepository.java
/**
 * 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));
}
 
源代码12 项目: java-scanner-access-twain   文件: XmlSupport.java
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);
    }
}
 
源代码13 项目: ant-ivy   文件: BundleRepoTest.java
@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);
}
 
源代码14 项目: openjdk-jdk9   文件: SAXTFactoryTest.java
/**
 * 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));
}
 
源代码15 项目: camel-spring-boot   文件: DependencyResolver.java
/**
 * 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;
}
 
源代码16 项目: freehealth-connector   文件: ValidatorHelper.java
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);
   }
}
 
源代码17 项目: freehealth-connector   文件: ValidatorHelper.java
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);
   }
}
 
源代码18 项目: BuildmLearn-Toolkit-Android   文件: FileUtils.java
/**
 * @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;
}
 
源代码19 项目: wandora   文件: AbstractBingExtractor.java
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;
    }
}
 
源代码20 项目: TableDisentangler   文件: Utilities.java
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;
}
 
源代码21 项目: openjdk-jdk9   文件: Bug6388460.java
@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());
    }
}
 
@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"));
}
 
/**
 * Writes a XML representation of the JAR specification to to the underlying stream.
 * 
 * @param jarPackage the JAR package data
 * @exception IOException if writing to the underlying stream fails
 */
public void writeXML(JarPackageData jarPackage) throws IOException {
	Assert.isNotNull(jarPackage);
	DocumentBuilder docBuilder= null;
	DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
	factory.setValidating(false);
	try {
    	docBuilder= factory.newDocumentBuilder();
	} catch (ParserConfigurationException ex) {
		throw new IOException(JarPackagerMessages.JarWriter_error_couldNotGetXmlBuilder);
	}
	Document document= docBuilder.newDocument();

	// Create the document
	Element xmlJarDesc= document.createElement(JarPackagerUtil.DESCRIPTION_EXTENSION);
	document.appendChild(xmlJarDesc);
	xmlWriteJarLocation(jarPackage, document, xmlJarDesc);
	xmlWriteOptions(jarPackage, document, xmlJarDesc);
	xmlWriteRefactoring(jarPackage, document, xmlJarDesc);
	xmlWriteSelectedProjects(jarPackage, document, xmlJarDesc);
	if (jarPackage.areGeneratedFilesExported())
		xmlWriteManifest(jarPackage, document, xmlJarDesc);
	xmlWriteSelectedElements(jarPackage, document, xmlJarDesc);

	try {
		// Write the document to the stream
		Transformer transformer=TransformerFactory.newInstance().newTransformer();
		transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
		transformer.setOutputProperty(OutputKeys.ENCODING, fEncoding);
		transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4"); //$NON-NLS-1$ //$NON-NLS-2$
		DOMSource source = new DOMSource(document);
		StreamResult result = new StreamResult(fOutputStream);
		transformer.transform(source, result);
	} catch (TransformerException e) {
		throw new IOException(JarPackagerMessages.JarWriter_error_couldNotTransformToXML);
	}
}
 
源代码24 项目: ingestion   文件: XmlXpathDeserializer.java
public String documentToString(Document document) throws TransformerException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(document), new StreamResult(writer));
    return writer.getBuffer().toString().replaceAll("\n|\r|\t", "");
}
 
源代码25 项目: tuxguitar   文件: KeyBindingWriter.java
public static void saveDocument(Document document,File file) {
	try {
		FileOutputStream fs = new FileOutputStream(file);
		
		// Write it out again
		TransformerFactory xformFactory = TransformerFactory.newInstance();
		Transformer idTransform = xformFactory.newTransformer();
		Source input = new DOMSource(document);
		Result output = new StreamResult(fs);
		idTransform.setOutputProperty(OutputKeys.INDENT, "yes");
		idTransform.transform(input, output);
	}catch(Throwable throwable){
		throwable.printStackTrace();
	}
}
 
源代码26 项目: JVoiceXML   文件: ReportXsltTest.java
private void transfer(OutputStream out, InputStream dataStream,
        InputStream styleStream) throws IOException, TransformerException {

    Source data = new StreamSource(dataStream);
    Source style = new StreamSource(styleStream);
    Result output = new StreamResult(out);

    Transformer xslt = TransformerFactory.newInstance().newTransformer(
            style);
    xslt.transform(data, output);
}
 
源代码27 项目: jdk8u-dev-jdk   文件: XSLTExFuncTest.java
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);
}
 
源代码28 项目: micro-integrator   文件: CarbonUtils.java
public static InputStream toInputStream(Document doc) throws CarbonException {
    try {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        Source xmlSource = new DOMSource(doc);
        Result result = new StreamResult(outputStream);
        TransformerFactory factory = getSecuredTransformerFactory();
        factory.newTransformer().transform(xmlSource, result);
        InputStream in = new ByteArrayInputStream(outputStream.toByteArray());
        return in;
    } catch (TransformerException var5) {
        throw new CarbonException("Error in transforming DOM to InputStream", var5);
    }
}
 
源代码29 项目: iaf   文件: MessageOutputStreamTest.java
@Test
@Ignore("No contract to call endDocument() in case of an Exception")
public void testX32ContentHandlerAsWriterError() throws Exception {
	
	CloseObservableWriter cow = new CloseObservableWriter() {

		@Override
		public void write(char[] arg0, int arg1, int arg2) {
			throw new RuntimeException("fakeFailure");
		}
		
	};
	Result result = new StreamResult(cow);
	SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
	TransformerHandler transformerHandler = tf.newTransformerHandler();
	transformerHandler.setResult(result);

	try (MessageOutputStream stream = new MessageOutputStream(null, transformerHandler, (IForwardTarget)null, null, null)) {
	
		try {
			try (Writer writer = stream.asWriter()) {
				writer.write(testString);
			}
			fail("exception should be thrown");
		} catch (Exception e) {
			assertThat(e.getMessage(),StringContains.containsString("fakeFailure"));
		}
		
	}
	assertTrue(cow.isCloseCalled());
}
 
源代码30 项目: jdk8u_jdk   文件: TransformationWarningsTest.java
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);
}