javax.xml.transform.Result Java Examples

The following examples show how to use javax.xml.transform.Result. 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: ValidatorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private void validate(final String xsdFile, final Source src, final Result result) throws Exception {
    try {
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new File(ValidatorTest.class.getResource(xsdFile).toURI()));

        // Get a Validator which can be used to validate instance document
        // against this grammar.
        Validator validator = schema.newValidator();
        ErrorHandler eh = new ErrorHandlerImpl();
        validator.setErrorHandler(eh);

        // Validate this instance document against the
        // Instance document supplied
        validator.validate(src, result);
    } catch (Exception ex) {
        throw ex;
    }
}
 
Example #2
Source File: TransformerHandlerImpl.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
   * Enables the user of the TransformerHandler to set the
   * to set the Result for the transformation.
   *
   * @param result A Result instance, should not be null.
   *
   * @throws IllegalArgumentException if result is invalid for some reason.
   */
  public void setResult(Result result) throws IllegalArgumentException
  {

    if (null == result)
      throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_RESULT_NULL, null)); //"result should not be null");

    try
    {
//      ContentHandler handler =
//        m_transformer.createResultContentHandler(result);
//      m_transformer.setContentHandler(handler);
        SerializationHandler xoh = 
            m_transformer.createSerializationHandler(result);
        m_transformer.setSerializationHandler(xoh);
    }
    catch (javax.xml.transform.TransformerException te)
    {
      throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_RESULT_COULD_NOT_BE_SET, null)); //"result could not be set");
    }

    m_result = result;
  }
 
Example #3
Source File: CatalogExportModuleEBL.java    From olat with Apache License 2.0 6 votes vote down vote up
public void transformCatalogXml(Document document) throws FileNotFoundException {

        try {
            final File systemDir = new File(WebappHelper.getUserDataRoot(), SYSTEM_DIR); // destination is .../olatdata/system/catalog.xml
            final File xmlFile = new File(systemDir, XML_FILE);
            final File oldXmlFile = new File(systemDir, XML_FILE + OLD_FILE_SUFFIX);
            final Result destination = getDestination(xmlFile, oldXmlFile);
            final Source source = new DOMSource(document);
            Transformer transformer = getTransformer();
            transformXml(source, destination, transformer);
            log.debug("                                ...done");
        } catch (final Exception e) {
            log.error("Error writing catalog export file.", e);
        }

    }
 
Example #4
Source File: SAXTFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * SAXTFactory.newTransformerhandler() method which takes SAXSource as
 * argument can be set to XMLReader. SAXSource has input XML file as its
 * input source. XMLReader has a content handler which write out the result
 * to output file. Test verifies output file is same as golden file.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase02() throws Exception {
    String outputFile = USER_DIR + "saxtf002.out";
    String goldFile = GOLDEN_DIR + "saxtf002GF.out";

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

        TransformerHandler handler = saxTFactory.newTransformerHandler(ss);
        Result result = new StreamResult(fos);
        handler.setResult(result);
        reader.setContentHandler(handler);
        reader.parse(XML_FILE);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example #5
Source File: ConfigReader.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Decides where the schema file (of the given namespace URI)
 * will be written, and return it as a {@link Result} object.
 *
 */
public Result createOutput( String namespaceUri, String suggestedFileName ) {

    // the user's preference takes a precedence
    if(schemas.containsKey(namespaceUri)) {
        File loc = schemas.get(namespaceUri);
        if(loc==null)   return null;    // specifically not to generate a schema

        // create directories if necessary. we've already checked that the baseDir
        // exists, so this should be no surprise to users.
        loc.getParentFile().mkdirs();

        return new StreamResult(loc);   // generate into a file the user specified.
    }

    // if the user didn't say anything about this namespace,
    // generate it into the default directory with a default name.

     File schemaFile = new File (baseDir, suggestedFileName);
     // The systemId for the result will be schemaFile
     return new StreamResult(schemaFile);
}
 
Example #6
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 #7
Source File: ConnectorXmlUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static String toString(Source source) throws TechnicalConnectorException {
   ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

   String var5;
   try {
      TransformerFactory tff = TransformerFactory.newInstance();
      Transformer tf = tff.newTransformer();
      tf.setOutputProperty("omit-xml-declaration", "yes");
      Result result = new StreamResult(outputStream);
      tf.transform(source, result);
      var5 = new String(outputStream.toByteArray(), "UTF-8");
   } catch (Exception var9) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var9, new Object[]{var9.getMessage()});
   } finally {
      ConnectorIOUtils.closeQuietly((Object)outputStream);
   }

   return var5;
}
 
Example #8
Source File: MathmlUtils.java    From sun-wordtable-read with Apache License 2.0 6 votes vote down vote up
/**    
 * <p>Description: xsl转换器</p>
 */
public static String xslConvert(String s, String xslpath, URIResolver uriResolver) {
	TransformerFactory tFac = TransformerFactory.newInstance();
	if (uriResolver != null)
		tFac.setURIResolver(uriResolver);
	StreamSource xslSource = new StreamSource(MathmlUtils.class.getResourceAsStream(xslpath));
	StringWriter writer = new StringWriter();
	try {
		Transformer t = tFac.newTransformer(xslSource);
		Source source = new StreamSource(new StringReader(s));
		Result result = new StreamResult(writer);
		t.transform(source, result);
	} catch (TransformerException e) {
		System.out.println(e.getMessage());
	}
	return writer.getBuffer().toString();
}
 
Example #9
Source File: XmlUtil.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Performs identity transformation.
 */
public static <T extends Result>
T identityTransform(Source src, T result) throws TransformerException, SAXException, ParserConfigurationException, IOException {
    if (src instanceof StreamSource) {
        // work around a bug in JAXP in JDK6u4 and earlier where the namespace processing
        // is not turned on by default
        StreamSource ssrc = (StreamSource) src;
        TransformerHandler th = ((SAXTransformerFactory) transformerFactory.get()).newTransformerHandler();
        th.setResult(result);
        XMLReader reader = saxParserFactory.get().newSAXParser().getXMLReader();
        reader.setContentHandler(th);
        reader.setProperty(LEXICAL_HANDLER_PROPERTY, th);
        reader.parse(toInputSource(ssrc));
    } else {
        newTransformer().transform(src, result);
    }
    return result;
}
 
Example #10
Source File: MarshallingHttpMessageConverterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void writeWithMarshallingFailureException() throws Exception {
	String body = "<root>Hello World</root>";
	MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
	MarshallingFailureException ex = new MarshallingFailureException("forced");

	Marshaller marshaller = mock(Marshaller.class);
	willThrow(ex).given(marshaller).marshal(eq(body), isA(Result.class));

	try {
		MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter(marshaller);
		converter.write(body, null, outputMessage);
		fail("HttpMessageNotWritableException should be thrown");
	}
	catch (HttpMessageNotWritableException e) {
		assertTrue("Invalid exception hierarchy", e.getCause() == ex);
	}
}
 
Example #11
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 along with a relative
 * URI in the style-sheet file.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase09() throws Exception {
    String outputFile = USER_DIR + "saxtf009.out";
    String goldFile = GOLDEN_DIR + "saxtf009GF.out";

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

        TemplatesHandler thandler = saxTFactory.newTemplatesHandler();
        thandler.setSystemId("file:///" + XML_DIR);
        reader.setContentHandler(thandler);
        reader.parse(XSLT_INCL_FILE);
        TransformerHandler tfhandler=
            saxTFactory.newTransformerHandler(thandler.getTemplates());
        Result result = new StreamResult(fos);
        tfhandler.setResult(result);
        reader.setContentHandler(tfhandler);
        reader.parse(XML_FILE);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example #12
Source File: FORendererApacheFOP.java    From docx4j-export-FO with Apache License 2.0 6 votes vote down vote up
protected void render(FopFactory fopFactory, FOUserAgent foUserAgent, String outputFormat, Source foDocumentSrc, PlaceholderReplacementHandler.PlaceholderLookup placeholderLookup, OutputStream outputStream) throws Docx4JException {
	Fop fop = null;
	Result result = null;
	try {
		if (foUserAgent==null) {
			fop = fopFactory.newFop(outputFormat, outputStream);
		} else {
			fop = fopFactory.newFop(outputFormat, foUserAgent, outputStream);				
		}
		result = (placeholderLookup == null ?
				//1 Pass
				new SAXResult(fop.getDefaultHandler()) :
				//2 Pass
				new SAXResult(new PlaceholderReplacementHandler(fop.getDefaultHandler(), placeholderLookup)));
	} catch (FOPException e) {
		throw new Docx4JException("Exception setting up result for fo transformation: " + e.getMessage(), e);
	}
	
	XmlSerializerUtil.serialize(foDocumentSrc, result, false, false);
}
 
Example #13
Source File: WSDLGenerator.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
     * Creates the {@link Result} object used by JAXB to generate a schema for the
     * namesapceUri namespace.
     * @param namespaceUri The namespace for the schema being generated
     * @param suggestedFileName the JAXB suggested file name for the schema file
     * @return the {@link Result} for JAXB to generate the schema into
     * @throws java.io.IOException thrown if on IO error occurs
     */
    public Result createOutputFile(String namespaceUri, String suggestedFileName) throws IOException {
        Result result;
        if (namespaceUri == null) {
            return null;
        }

        Holder<String> fileNameHolder = new Holder<String>();
        fileNameHolder.value = schemaPrefix + suggestedFileName;
        result = wsdlResolver.getSchemaOutput(namespaceUri, fileNameHolder);
//        System.out.println("schema file: "+fileNameHolder.value);
//        System.out.println("result: "+result);
        String schemaLoc;
        if (result == null)
            schemaLoc = fileNameHolder.value;
        else
            schemaLoc = relativize(result.getSystemId(), wsdlLocation);
        boolean isEmptyNs = namespaceUri.trim().equals("");
        if (!isEmptyNs) {
            com.sun.xml.internal.ws.wsdl.writer.document.xsd.Import _import = types.schema()._import();
            _import.namespace(namespaceUri);
            _import.schemaLocation(schemaLoc);
        }
        return result;
    }
 
Example #14
Source File: StaxUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the {@link XMLStreamWriter} for the given StAX Result.
 * @param result a JAXP 1.4 {@link StAXResult}
 * @return the {@link XMLStreamReader}
 * @throws IllegalArgumentException if {@code source} isn't a JAXP 1.4 {@link StAXResult}
 * or custom StAX Result
 */
public static XMLStreamWriter getXMLStreamWriter(Result result) {
	if (result instanceof StAXResult) {
		return ((StAXResult) result).getXMLStreamWriter();
	}
	else if (result instanceof StaxResult) {
		return ((StaxResult) result).getXMLStreamWriter();
	}
	else {
		throw new IllegalArgumentException("Result '" + result + "' is neither StaxResult nor StAXResult");
	}
}
 
Example #15
Source File: BonitaToBPMNExporter.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private void generateXSDForConnector(final File connectorToTransform)
        throws URISyntaxException, IOException, TransformerException {
    if (xslTemplate == null) {
        final TransformerFactory transFact = TransformerFactory.newInstance();
        final URL xsltUrl = ConnectorPlugin.getDefault().getBundle().getEntry("transfo/genConnectorsXSD.xsl");
        final File xsltFileoriginal = new File(FileLocator.toFileURL(xsltUrl).getFile());
        final Source xsltSource = new StreamSource(xsltFileoriginal);
        xslTemplate = transFact.newTemplates(xsltSource);
    }

    //FIXME: this is only a workaround because currently we can't serialize the xml file in a way that both EMF and xslt can handle it correctly
    // see http://java.dzone.com/articles/emf-reading-model-xml-%E2%80%93-how
    final File connectorToTransformWC = File.createTempFile(connectorToTransform.getName(), "");
    FileUtil.copy(connectorToTransform, connectorToTransformWC);
    FileUtil.replaceStringInFile(connectorToTransformWC,
            "xmlns:definition=\"http://www.bonitasoft.org/ns/connector/definition/6.0\"",
            "xmlns=\"http://www.bonitasoft.org/ns/connector/definition/6.0\" xmlns:definition=\"http://www.bonitasoft.org/ns/connector/definition/6.0\"");

    final Source xmlSource = new StreamSource(connectorToTransformWC);

    final String generatedXsdName = connectorToTransform.getName() + "connectors.xsd";
    final File connectorsDefFolder = new File(
            destBpmnFile.getParentFile().getAbsolutePath() + File.separator + "connectorDefs");
    if (!connectorsDefFolder.exists()) {
        connectorsDefFolder.mkdirs();
    }
    try (final OutputStream stream = new FileOutputStream(
            new File(connectorsDefFolder.getAbsolutePath(), generatedXsdName))) {
        final Result result = new StreamResult(stream);
        final Transformer transformer = xslTemplate.newTransformer();
        transformer.setParameter("indent", true);
        transformer.transform(xmlSource, result);
    } finally {
        connectorToTransformWC.delete();
    }
}
 
Example #16
Source File: JAXPSAXParserTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public final void testTransform() {
    String data =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<r>\n"
            + "    <e/>\n"
            + "</r>\n";
    String IDENTITY_XSLT_WITH_INDENT = // #5064280 workaround
            "<xsl:stylesheet version='1.0' "
            + "xmlns:xsl='http://www.w3.org/1999/XSL/Transform' "
            + "xmlns:xalan='http://xml.apache.org/xslt' "
            + "exclude-result-prefixes='xalan'>"
            + "<xsl:output method='xml' indent='yes' xalan:indent-amount='4'/>"
            + "<xsl:template match='@*|node()'>"
            + "<xsl:copy>"
            + "<xsl:apply-templates select='@*|node()'/>"
            + "</xsl:copy>"
            + "</xsl:template>"
            + "</xsl:stylesheet>";
    try {
        //Skip the default XMLReader
        System.setProperty("org.xml.sax.driver", "com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser");

        StringWriter sw = new StringWriter();
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer(new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT)));
        Result result = new StreamResult(sw);
        t.transform(new StreamSource(new StringReader(data)), result);
        success("JAXPSAXParserTest passed");
    } catch (Exception e) {
        /**
         * JAXPSAXParser throws NullPointerException since the jaxp 1.5 security
         * manager is not initialized when JAXPSAXParser is instantiated using
         * the default constructor.
        */
        fail(e.toString());
    } finally {
        System.clearProperty("org.xml.sax.driver");
    }
}
 
Example #17
Source File: BarcodeSVGImageProducer.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Renderable createImage(
	JasperReportsContext jasperReportsContext,
	JRComponentElement componentElement,
	BarcodeGenerator barcode, 
	String message
	)
{
	try
	{
		SVGCanvasProvider provider = 
			new SVGCanvasProvider(
				false, 
				((Barcode4jComponent)componentElement.getComponent()).getOrientationValue().getValue()
				);
		barcode.generateBarcode(provider, message);
		Document svgDoc = provider.getDOM();

		Source source = new DOMSource(svgDoc);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		Result output = new StreamResult(baos);
		Transformer transformer = TransformerFactory.newInstance()
				.newTransformer();
		transformer.transform(source, output);

		return SimpleRenderToImageAwareDataRenderer.getInstance(baos.toByteArray());
	}
	catch (Exception e)
	{
		throw new JRRuntimeException(e);
	}
}
 
Example #18
Source File: JibxMarshaller.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void transformAndMarshal(Object graph, Result result) throws IOException {
	try {
		ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
		marshalOutputStream(graph, os);
		ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
		Transformer transformer = this.transformerFactory.newTransformer();
		transformer.transform(new StreamSource(is), result);
	}
	catch (TransformerException ex) {
		throw new MarshallingFailureException(
				"Could not transform to [" + ClassUtils.getShortName(result.getClass()) + "]", ex);
	}

}
 
Example #19
Source File: ResultFactory.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Factory method for producing {@link XmlSerializer) from {@link javax.xml.transform.Result}.
 *
 * This method supports {@link javax.xml.transform.sax.SAXResult},
 * {@link javax.xml.transform.stream.StreamResult}, and {@link javax.xml.transform.dom.DOMResult}.
 *
 * @param result the Result that will receive output from the XmlSerializer
 * @return an implementation of XmlSerializer that will produce output on the supplied Result
 */
public static XmlSerializer createSerializer(Result result) {
    if (result instanceof SAXResult)
        return new SaxSerializer((SAXResult) result);
    if (result instanceof DOMResult)
        return new DomSerializer((DOMResult) result);
    if (result instanceof StreamResult)
        return new StreamSerializer((StreamResult) result);
    if (result instanceof TXWResult)
        return new TXWSerializer(((TXWResult)result).getWriter());

    throw new UnsupportedOperationException("Unsupported Result type: " + result.getClass().getName());
}
 
Example #20
Source File: StaxUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static XMLStreamWriter getXMLStreamWriter(final Result result) throws ProcessingException {
    XMLOutputFactory factory = getXMLOutputFactory();
    try {
        return factory.createXMLStreamWriter(result);
    } catch (XMLStreamException xe) {
        throw logger.processingError(xe);
    }
}
 
Example #21
Source File: MCRXSLTransformer.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
protected LinkedList<TransformerHandler> getTransformHandlerList(MCRParameterCollector parameterCollector)
    throws TransformerConfigurationException, SAXException, ParserConfigurationException {
    checkTemplateUptodate();
    LinkedList<TransformerHandler> xslSteps = new LinkedList<>();
    //every transformhandler shares the same ErrorListener instance
    MCRErrorListener errorListener = MCRErrorListener.getInstance();
    for (Templates template : templates) {
        TransformerHandler handler = tFactory.newTransformerHandler(template);
        parameterCollector.setParametersTo(handler.getTransformer());
        handler.getTransformer().setErrorListener(errorListener);
        if (TRACE_LISTENER_ENABLED) {
            TransformerImpl transformer = (TransformerImpl) handler.getTransformer();
            TraceManager traceManager = transformer.getTraceManager();
            try {
                traceManager.addTraceListener(TRACE_LISTENER);
            } catch (TooManyListenersException e) {
                LOGGER.warn("Could not add MCRTraceListener.", e);
            }
        }
        if (!xslSteps.isEmpty()) {
            Result result = new SAXResult(handler);
            xslSteps.getLast().setResult(result);
        }
        xslSteps.add(handler);
    }
    return xslSteps;
}
 
Example #22
Source File: FlowParser.java    From nifi-minifi with Apache License 2.0 5 votes vote down vote up
/**
 * Writes a given XML Flow out to the specified path.
 *
 * @param flowDocument flowDocument of the associated XML content to write to disk
 * @param flowXmlPath  path on disk to write the flow
 * @throws IOException if there are issues in accessing the target destination for the flow
 * @throws TransformerException if there are issues in the xml transformation process
 */
public void writeFlow(final Document flowDocument, final Path flowXmlPath) throws IOException, TransformerException {
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final Source xmlSource = new DOMSource(flowDocument);
    final Result outputTarget = new StreamResult(outputStream);
    TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget);
    final InputStream is = new ByteArrayInputStream(outputStream.toByteArray());

    try (final OutputStream output = Files.newOutputStream(flowXmlPath, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
         final OutputStream gzipOut = new GZIPOutputStream(output);) {
        FileUtils.copy(is, gzipOut);
    }
}
 
Example #23
Source File: MarshallerBridge.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void marshal(Marshaller m, Object object, Result result) throws JAXBException {
    m.setProperty(Marshaller.JAXB_FRAGMENT,true);
    try {
        m.marshal(object,result);
    } finally {
        m.setProperty(Marshaller.JAXB_FRAGMENT,false);
    }
}
 
Example #24
Source File: XStreamMarshallerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void marshalStaxResultXMLStreamWriter() throws Exception {
	XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
	StringWriter writer = new StringWriter();
	XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(writer);
	Result result = StaxUtils.createStaxResult(streamWriter);
	marshaller.marshal(flight, result);
	assertThat("Marshaller writes invalid StreamResult", writer.toString(), isSimilarTo(EXPECTED_STRING));
}
 
Example #25
Source File: XMLUtils.java    From red5-io with Apache License 2.0 5 votes vote down vote up
/**
 * Convert a DOM tree into a String using transform
 * 
 * @param domDoc
 *            DOM object
 * @throws java.io.IOException
 *             I/O exception
 * @return XML as String
 */
public static String docToString2(Document domDoc) throws IOException {
    try {
        TransformerFactory transFact = TransformerFactory.newInstance();
        Transformer trans = transFact.newTransformer();
        trans.setOutputProperty(OutputKeys.INDENT, "no");
        StringWriter sw = new StringWriter();
        Result result = new StreamResult(sw);
        trans.transform(new DOMSource(domDoc), result);
        return sw.toString();
    } catch (Exception ex) {
        throw new IOException(String.format("Error converting from doc to string %s", ex.getMessage()));
    }
}
 
Example #26
Source File: MemberSubmissionEndpointReference.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void writeTo(Result result) {
    try {
        Marshaller marshaller = MemberSubmissionEndpointReference.msjc.get().createMarshaller();
        //marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.marshal(this, result);
    } catch (JAXBException e) {
        throw new WebServiceException("Error marshalling W3CEndpointReference. ", e);
    }
}
 
Example #27
Source File: Jdbc4SqlXmlHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SqlXmlValue newSqlXmlValue(final Class<? extends Result> resultClass, final XmlResultProvider provider) {
	return new AbstractJdbc4SqlXmlValue() {
		@Override
		protected void provideXml(SQLXML xmlObject) throws SQLException, IOException {
			provider.provideXml(xmlObject.setResult(resultClass));
		}
	};
}
 
Example #28
Source File: JAXPSAXParserTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public final void testTransform() {
    String data =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<r>\n"
            + "    <e/>\n"
            + "</r>\n";
    String IDENTITY_XSLT_WITH_INDENT = // #5064280 workaround
            "<xsl:stylesheet version='1.0' "
            + "xmlns:xsl='http://www.w3.org/1999/XSL/Transform' "
            + "xmlns:xalan='http://xml.apache.org/xslt' "
            + "exclude-result-prefixes='xalan'>"
            + "<xsl:output method='xml' indent='yes' xalan:indent-amount='4'/>"
            + "<xsl:template match='@*|node()'>"
            + "<xsl:copy>"
            + "<xsl:apply-templates select='@*|node()'/>"
            + "</xsl:copy>"
            + "</xsl:template>"
            + "</xsl:stylesheet>";
    try {
        //Skip the default XMLReader
        System.setProperty("org.xml.sax.driver", "com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser");

        StringWriter sw = new StringWriter();
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer(new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT)));
        Result result = new StreamResult(sw);
        t.transform(new StreamSource(new StringReader(data)), result);
        success("JAXPSAXParserTest passed");
    } catch (Exception e) {
        /**
         * JAXPSAXParser throws NullPointerException since the jaxp 1.5 security
         * manager is not initialized when JAXPSAXParser is instantiated using
         * the default constructor.
        */
        fail(e.toString());
    } finally {
        System.clearProperty("org.xml.sax.driver");
    }
}
 
Example #29
Source File: WSDLGenResolver.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Updates filename if the suggested filename need to be changed in
 * wsdl:import. If the metadata already contains abstract wsdl(i.e. a WSDL
 * which has the porttype), then the abstract wsdl shouldn't be generated
 *
 * return null if abstract WSDL need not be generated
 *        Result the abstract WSDL
 */
public Result getAbstractWSDL(Holder<String> filename) {
    if (abstractWsdl != null) {
        filename.value = abstractWsdl.getURL().toString();
        return null;                // Don't generate abstract WSDL
    }
    URL url = createURL(filename.value);
    MutableXMLStreamBuffer xsb = new MutableXMLStreamBuffer();
    xsb.setSystemId(url.toExternalForm());
    SDDocumentSource abstractWsdlSource = SDDocumentSource.create(url,xsb);
    newDocs.add(abstractWsdlSource);
    XMLStreamBufferResult r = new XMLStreamBufferResult(xsb);
    r.setSystemId(filename.value);
    return r;
}
 
Example #30
Source File: TestClasspathExtractor.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Test method for {@link org.jvoicexml.config.ClasspathExtractor#getLoaderRepostory()}.
 * @exception Exception
 *            test failed
 */
@Test
public void testGetLoaderRepository() throws Exception {
    final TransformerFactory factory = TransformerFactory.newInstance();
    final Transformer transformer = factory.newTransformer();
    final Source source =
        new StreamSource("../org.jvoicexml.config/src/test/resources/config/test-implementation.xml");
    final ClasspathExtractor extractor = new ClasspathExtractor();
    final Result result = new SAXResult(extractor);
    transformer.transform(source, result);
    final String repository = extractor.getLoaderRepostory();
    Assert.assertEquals("deschd", repository);
}