javax.xml.transform.stream.StreamSource Java Examples

The following examples show how to use javax.xml.transform.stream.StreamSource. 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: XMLInputFactoryImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
XMLInputSource jaxpSourcetoXMLInputSource(Source source){
     if(source instanceof StreamSource){
         StreamSource stSource = (StreamSource)source;
         String systemId = stSource.getSystemId();
         String publicId = stSource.getPublicId();
         InputStream istream = stSource.getInputStream();
         Reader reader = stSource.getReader();

         if(istream != null){
             return new XMLInputSource(publicId, systemId, null, istream, null);
         }
         else if(reader != null){
             return new XMLInputSource(publicId, systemId,null, reader, null);
         }else{
             return new XMLInputSource(publicId, systemId, null);
         }
     }

     throw new UnsupportedOperationException("Cannot create " +
            "XMLStreamReader or XMLEventReader from a " +
            source.getClass().getName());
}
 
Example #2
Source File: PreviewPanel.java    From jpexs-decompiler with GNU General Public License v3.0 6 votes vote down vote up
public static String formatMetadata(String input, int indent) {
    input = input.replace("> <", "><");
    try {
        Source xmlInput = new StreamSource(new StringReader(input));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        StringWriter sw = new StringWriter();
        xmlOutput.setWriter(sw);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "" + indent);
        transformer.transform(xmlInput, xmlOutput);

        return xmlOutput.getWriter().toString();
    } catch (IllegalArgumentException | TransformerException e) {
        return input;
    }
}
 
Example #3
Source File: CR6689809Test.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public final void testTransform() {

    try {
        StreamSource input = new StreamSource(getClass().getResourceAsStream("PredicateInKeyTest.xml"));
        StreamSource stylesheet = new StreamSource(getClass().getResourceAsStream("PredicateInKeyTest.xsl"));
        CharArrayWriter buffer = new CharArrayWriter();
        StreamResult output = new StreamResult(buffer);

        TransformerFactory.newInstance().newTransformer(stylesheet).transform(input, output);

        Assert.assertEquals(buffer.toString(), "0|1|2|3", "XSLT xsl:key implementation is broken!");
        // expected success
    } catch (Exception e) {
        // unexpected failure
        e.printStackTrace();
        Assert.fail(e.toString());
    }
}
 
Example #4
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 #5
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 #6
Source File: MarshallingHttpMessageConverterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void readWithTypeMismatchException() throws Exception {
	MockHttpInputMessage inputMessage = new MockHttpInputMessage(new byte[0]);

	Marshaller marshaller = mock(Marshaller.class);
	Unmarshaller unmarshaller = mock(Unmarshaller.class);
	given(unmarshaller.unmarshal(isA(StreamSource.class))).willReturn(Integer.valueOf(3));

	MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter(marshaller, unmarshaller);
	try {
		converter.read(String.class, inputMessage);
		fail("Should have thrown HttpMessageNotReadableException");
	}
	catch (HttpMessageNotReadableException ex) {
		assertTrue(ex.getCause() instanceof TypeMismatchException);
	}
}
 
Example #7
Source File: AuthorizerFactoryBean.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private Authorizers loadAuthorizersConfiguration() throws Exception {
    final File authorizersConfigurationFile = properties.getAuthorizerConfigurationFile();

    // load the authorizers from the specified file
    if (authorizersConfigurationFile.exists()) {
        try {
            // find the schema
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            final Schema schema = schemaFactory.newSchema(Authorizers.class.getResource(AUTHORIZERS_XSD));

            // attempt to unmarshal
            final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
            unmarshaller.setSchema(schema);
            final JAXBElement<Authorizers> element = unmarshaller.unmarshal(new StreamSource(authorizersConfigurationFile), Authorizers.class);
            return element.getValue();
        } catch (SAXException | JAXBException e) {
            throw new Exception("Unable to load the authorizer configuration file at: " + authorizersConfigurationFile.getAbsolutePath(), e);
        }
    } else {
        throw new Exception("Unable to find the authorizer configuration file at " + authorizersConfigurationFile.getAbsolutePath());
    }
}
 
Example #8
Source File: TransformersTest.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
private String modsAsFedoraLabel(InputStream xmlIS, String model) throws Exception {
        assertNotNull(xmlIS);
        StreamSource streamSource = new StreamSource(xmlIS);
        Transformers mt = new Transformers();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("MODEL", model);
        try {
            byte[] contents = mt.transformAsBytes(streamSource, Transformers.Format.ModsAsFedoraLabel, params);
            assertNotNull(contents);
            String label = new String(contents, "UTF-8");
//            System.out.println(label);
            return label;
        } finally {
            close(xmlIS);
        }
    }
 
Example #9
Source File: JaxbUtil.java    From KantaCDA-API with Apache License 2.0 6 votes vote down vote up
public POCDMT000040ClinicalDocument unmarshaller(String xml) throws JAXBException {
    long start = 0;
    if ( LOGGER.isDebugEnabled() ) {
        start = System.currentTimeMillis();
    }

    POCDMT000040ClinicalDocument result = null;
    try {
        StringReader reader = new StringReader(xml);
        Unmarshaller u = jaxbContext.createUnmarshaller();
        result = u.unmarshal(new StreamSource(reader), POCDMT000040ClinicalDocument.class).getValue();
    }
    catch (JAXBException e) {
        LOGGER.error("UnMarshallointi epäonnistui.", e.getMessage());
        throw e;
    }

    if ( LOGGER.isDebugEnabled() ) {
        long end = System.currentTimeMillis();
        LOGGER.debug("Unmarshalling took " + (end - start) + " ms.");
    }

    return result;
}
 
Example #10
Source File: XmlUtils.java    From web-data-extractor with Apache License 2.0 6 votes vote down vote up
/**
 * Remove all namespaces from the XML source into the XML output.
 *
 * @param xmlSource the XML source
 * @throws TransformerException the TransformerException
 */
public static String removeNamespace(String xmlSource) throws TransformerException {
    TransformerFactory factory = TransformerFactory.newInstance();
    InputStream xsltRemoveNamespace = XmlUtils.class.getResourceAsStream("/remove-namespace.xslt");
    if (xsltRemoveNamespace == null)
        throw new ExceptionInInitializerError(new FileNotFoundException("No XSLT resource is found!"));
    Templates transformer = factory.newTemplates(new StreamSource(xsltRemoveNamespace));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Result result = new StreamResult(baos);
    Source src = new StreamSource(new StringReader(xmlSource));
    transformer.newTransformer().transform(src, result);
    String newXml = baos.toString();
    try {
        xsltRemoveNamespace.close();
        baos.close();
    } catch (IOException e) {
        //eat it
    }
    return newXml;
}
 
Example #11
Source File: TransformationWarningsTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
Transformer createTransformer() throws Exception {
    // Prepare sources for transormation
    Source xslsrc = new StreamSource(new StringReader(xsl));

    // Create factory and transformer
    TransformerFactory tf;
    // newTransformer() method doc states that different transformer
    // factories can be used concurrently by different Threads.
    synchronized (TransformerFactory.class) {
        tf = TransformerFactory.newInstance();
    }
    Transformer t = tf.newTransformer(xslsrc);

    // Set URI Resolver to return the newly constructed xml
    // stream source object from xml test string
    t.setURIResolver((String href, String base) -> new StreamSource(new StringReader(xml)));
    return t;
}
 
Example #12
Source File: UnmarshallerImpl.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public Object unmarshal0( Source source, JaxBeanInfo expectedType ) throws JAXBException {
    if (source instanceof SAXSource) {
        SAXSource ss = (SAXSource) source;

        XMLReader locReader = ss.getXMLReader();
        if (locReader == null) {
            locReader = getXMLReader();
        }

        return unmarshal0(locReader, ss.getInputSource(), expectedType);
    }
    if (source instanceof StreamSource) {
        return unmarshal0(getXMLReader(), streamSourceToInputSource((StreamSource) source), expectedType);
    }
    if (source instanceof DOMSource) {
        return unmarshal0(((DOMSource) source).getNode(), expectedType);
    }

    // we don't handle other types of Source
    throw new IllegalArgumentException();
}
 
Example #13
Source File: TransformXml.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public ValidationResult validate(final String subject, final String input, final ValidationContext validationContext) {
    final Tuple<String, ValidationResult> lastResult = this.cachedResult;
    if (lastResult != null && lastResult.getKey().equals(input)) {
        return lastResult.getValue();
    } else {
        String error = null;
        final File stylesheet = new File(input);
        final TransformerFactory tFactory = new net.sf.saxon.TransformerFactoryImpl();
        final StreamSource styleSource = new StreamSource(stylesheet);

        try {
            tFactory.newTransformer(styleSource);
        } catch (final Exception e) {
            error = e.toString();
        }

        this.cachedResult = new Tuple<>(input, new ValidationResult.Builder()
                .input(input)
                .subject(subject)
                .valid(error == null)
                .explanation(error)
                .build());
        return this.cachedResult.getValue();
    }
}
 
Example #14
Source File: SAXSource.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Attempt to obtain a SAX InputSource object from a Source
 * object.
 *
 * @param source Must be a non-null Source reference.
 *
 * @return An InputSource, or null if Source can not be converted.
 */
public static InputSource sourceToInputSource(Source source) {

    if (source instanceof SAXSource) {
        return ((SAXSource) source).getInputSource();
    } else if (source instanceof StreamSource) {
        StreamSource ss      = (StreamSource) source;
        InputSource  isource = new InputSource(ss.getSystemId());

        isource.setByteStream(ss.getInputStream());
        isource.setCharacterStream(ss.getReader());
        isource.setPublicId(ss.getPublicId());

        return isource;
    } else {
        return null;
    }
}
 
Example #15
Source File: PropertiesConfig.java    From nordpos with GNU General Public License v3.0 6 votes vote down vote up
public PropertiesConfig(String configXML) {

        if (configXML != null) {
            try {
                if (m_sp == null) {
                SAXParserFactory spf = SAXParserFactory.newInstance();
                spf.setValidating(false);
                spf.setNamespaceAware(true);
                SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
                InputStream = getClass().getResourceAsStream("/com/openbravo/pos/templates/Schema.Ticket.xsd");
                spf.setSchema(schemaFactory.newSchema(new Source[]{new StreamSource(InputStream)}));
                m_sp = spf.newSAXParser();
                m_sr = m_sp.getXMLReader();
                m_sr.setContentHandler(new ConfigurationHandler());
                }
                m_sp.parse(new InputSource(new StringReader(configXML)), new ConfigurationHandler());
                m_sr.parse(new InputSource(new StringReader(configXML)));
            } catch (ParserConfigurationException ePC) {
                logger.log(Level.WARNING, LocalRes.getIntString("exception.parserconfig"), ePC);
            } catch (SAXException eSAX) {
                logger.log(Level.WARNING, LocalRes.getIntString("exception.xmlfile"), eSAX);
            } catch (IOException eIO) {
                logger.log(Level.WARNING, LocalRes.getIntString("exception.iofile"), eIO);
            }
        }
    }
 
Example #16
Source File: HelpManager.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void getHelpItems( OutputStream out, Locale locale )
{
    try
    {
        ClassPathResource classPathResource = resolveHelpFileResource( locale );

        Source source = new StreamSource( classPathResource.getInputStream(), ENCODING_UTF8 );

        Result result = new StreamResult( out );

        getTransformer( "helpitems_stylesheet.xsl" ).transform( source, result );
    }
    catch ( Exception ex )
    {
        throw new RuntimeException( "Failed to get help content", ex );
    }
}
 
Example #17
Source File: AbstractUnmarshallerImpl.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public Object unmarshal( Source source ) throws JAXBException {
    if( source == null ) {
        throw new IllegalArgumentException(
            Messages.format( Messages.MUST_NOT_BE_NULL, "source" ) );
    }

    if(source instanceof SAXSource)
        return unmarshal( (SAXSource)source );
    if(source instanceof StreamSource)
        return unmarshal( streamSourceToInputSource((StreamSource)source));
    if(source instanceof DOMSource)
        return unmarshal( ((DOMSource)source).getNode() );

    // we don't handle other types of Source
    throw new IllegalArgumentException();
}
 
Example #18
Source File: TransformersTest.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
@Test
    public void testOaiMarcAsMarc() throws Exception {
        InputStream goldenIS = TransformersTest.class.getResourceAsStream("alephXServerDetailResponseAsMarcXml.xml");
        assertNotNull(goldenIS);
        InputStream xmlIS = TransformersTest.class.getResourceAsStream("alephXServerDetailResponseAsOaiMarc.xml");
        assertNotNull(xmlIS);
        StreamSource streamSource = new StreamSource(xmlIS);
        Transformers mt = new Transformers();

        try {
            byte[] contents = mt.transformAsBytes(streamSource, Transformers.Format.OaimarcAsMarc21slim);
            assertNotNull(contents);
//            System.out.println(new String(contents, "UTF-8"));
            XMLAssert.assertXMLEqual(new InputSource(goldenIS), new InputSource(new ByteArrayInputStream(contents)));
        } finally {
            close(xmlIS);
            close(goldenIS);
        }
    }
 
Example #19
Source File: UnifiedXmlDataShapeGeneratorShapeValidityTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGenerateValidOutputSchemasets() throws IOException {
    final DataShape output = generator.createShapeFromResponse(json, openApiDoc, operation);

    if (output.getKind() != DataShapeKinds.XML_SCHEMA) {
        return;
    }

    final Validator validator = createValidator();
    try (InputStream in = UnifiedXmlDataShapeGenerator.class.getResourceAsStream("/openapi/v2/atlas-xml-schemaset-model-v2.xsd")) {
        validator.setSchemaSource(new StreamSource(in));
        final String outputSpecification = output.getSpecification();
        final ValidationResult result = validator.validateInstance(source(outputSpecification));
        assertThat(result.isValid())//
            .as("Non valid output XML schemaset was generated for specification: %s, operation: %s, errors: %s", specification,
                operation.operationId,
                StreamSupport.stream(result.getProblems().spliterator(), false).map(ValidationProblem::toString)//
                    .collect(Collectors.joining("\n")))//
            .isTrue();
    }
}
 
Example #20
Source File: UnmarshallerImpl.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@Override
public <T> JAXBElement<T> unmarshal( Source source, Class<T> expectedType ) throws JAXBException {
    if (source instanceof SAXSource) {
        SAXSource ss = (SAXSource) source;

        XMLReader locReader = ss.getXMLReader();
        if (locReader == null) {
            locReader = getXMLReader();
        }

        return unmarshal(locReader, ss.getInputSource(), expectedType);
    }
    if (source instanceof StreamSource) {
        return unmarshal(getXMLReader(), streamSourceToInputSource((StreamSource) source), expectedType);
    }
    if (source instanceof DOMSource) {
        return unmarshal(((DOMSource) source).getNode(), expectedType);
    }

    // we don't handle other types of Source
    throw new IllegalArgumentException();
}
 
Example #21
Source File: XmlUtil.java    From openjdk-jdk8u 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 #22
Source File: ODEEndpointUpdater.java    From container with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a list of QName's which are referenced in the ODE deploy.xml File as invoked service.<br>
 *
 * @param deployXML a file object of a valid deploy.xml File
 * @return a list of QNames which represent the PortTypes used by the BPEL process to invoke operations
 * @throws JAXBException if the JAXB parser couldn't work properly
 */
private List<QName> getInvokedDeployXMLPorts(final File deployXML) throws JAXBException {
    // http://svn.apache.org/viewvc/ode/trunk/bpel-schemas/src/main/xsd/
    // grabbed that and using jaxb
    final List<QName> qnames = new LinkedList<>();
    final JAXBContext context =
        JAXBContext.newInstance("org.apache.ode.schemas.dd._2007._03", this.getClass().getClassLoader());
    final Unmarshaller unmarshaller = context.createUnmarshaller();
    final TDeployment deploy = unmarshaller.unmarshal(new StreamSource(deployXML), TDeployment.class).getValue();
    for (final org.apache.ode.schemas.dd._2007._03.TDeployment.Process process : deploy.getProcess()) {
        for (final TInvoke invoke : process.getInvoke()) {
            final QName serviceName = invoke.getService().getName();
            // add only qnames which aren't from the plan itself
            if (!serviceName.getNamespaceURI().equals(process.getName().getNamespaceURI())) {
                qnames.add(new QName(serviceName.getNamespaceURI(), invoke.getService().getPort()));
            }
        }
    }
    return qnames;
}
 
Example #23
Source File: TransformerImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This class should only be used as a DOMCache for the translet if the
 * URIResolver has been set.
 *
 * The method implements XSLTC's DOMCache interface, which is used to
 * plug in an external document loader into a translet. This method acts
 * as an adapter between TrAX's URIResolver interface and XSLTC's
 * DOMCache interface. This approach is simple, but removes the
 * possibility of using external document caches with XSLTC.
 *
 * @param baseURI The base URI used by the document call.
 * @param href The href argument passed to the document function.
 * @param translet A reference to the translet requesting the document
 */
@Override
public DOM retrieveDocument(String baseURI, String href, Translet translet) {
    try {
        // Argument to document function was: document('');
        if (href.length() == 0) {
            href = baseURI;
        }

        /*
         *  Fix for bug 24188
         *  Incase the _uriResolver.resolve(href,base) is null
         *  try to still  retrieve the document before returning null
         *  and throwing the FileNotFoundException in
         *  com.sun.org.apache.xalan.internal.xsltc.dom.LoadDocument
         *
         */
        Source resolvedSource = _uriResolver.resolve(href, baseURI);
        if (resolvedSource == null)  {
            StreamSource streamSource = new StreamSource(
                 SystemIDResolver.getAbsoluteURI(href, baseURI));
            return getDOM(streamSource) ;
        }

        return getDOM(resolvedSource);
    }
    catch (TransformerException e) {
        if (_errorListener != null)
            postErrorToListener("File not found: " + e.getMessage());
        return(null);
    }
}
 
Example #24
Source File: XeroClient.java    From xero-java-client with Apache License 2.0 5 votes vote down vote up
protected static <T> T unmarshallResponse(String responseBody, Class<T> clazz) {
  try {
    JAXBContext context = JAXBContext.newInstance(clazz);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    Source source = new StreamSource(new ByteArrayInputStream(responseBody.getBytes()));
    return unmarshaller.unmarshal(source, clazz).getValue();
  } catch (JAXBException e) {
    throw new IllegalStateException("Error unmarshalling response: " + responseBody, e);
  }
}
 
Example #25
Source File: ALog.java    From ALog with Apache License 2.0 5 votes vote down vote up
private static String formatXml(String xml) {
    try {
        Source xmlInput = new StreamSource(new StringReader(xml));
        StreamResult xmlOutput = new StreamResult(new StringWriter());
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transformer.transform(xmlInput, xmlOutput);
        xml = xmlOutput.getWriter().toString().replaceFirst(">", ">" + LINE_SEP);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return xml;
}
 
Example #26
Source File: CFDv2.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
byte[] getOriginalBytes(InputStream in) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Source source = new StreamSource(in);
    Result out = new StreamResult(baos);
    TransformerFactory factory = tf;
    if (factory == null) {
        factory = TransformerFactory.newInstance();
        factory.setURIResolver(new URIResolverImpl());
    }
    Transformer transformer = factory.newTransformer(new StreamSource(getClass().getResourceAsStream(XSLT)));
    transformer.transform(source, out);
    in.close();
    return baos.toByteArray();
}
 
Example #27
Source File: ParsingValidatorTest.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
@Test(expected = ConfigurationException.class)
public void shouldMapSAXNotRecognizedException() throws Exception {
    doThrow(new SAXNotRecognizedException())
        .when(parser).setProperty(anyString(), any());
    ParsingValidator v =
        new ParsingValidator(Languages.W3C_XML_SCHEMA_NS_URI);
    v.validateInstance(new StreamSource(new File(TEST_RESOURCE_DIR
                                                 + "BookWithDoctype.xml")),
                       fac);
}
 
Example #28
Source File: Bug4969042.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private ValidatorHandler createValidatorHandler(String xsd) throws SAXException {
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

    StringReader reader = new StringReader(xsd);
    StreamSource xsdSource = new StreamSource(reader);

    Schema schema = schemaFactory.newSchema(xsdSource);
    return schema.newValidatorHandler();
}
 
Example #29
Source File: JavaxXmlDeserializer.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T deserialize( ModuleDescriptor module, ValueType valueType, Reader state )
{
    try
    {
        DOMResult domResult = new DOMResult();
        xmlFactories.normalizationTransformer().transform( new StreamSource( state ), domResult );
        Node node = domResult.getNode();
        return fromXml( module, valueType, node );
    }
    catch( TransformerException ex )
    {
        throw new SerializationException( "Unable to read XML document", ex );
    }
}
 
Example #30
Source File: JPAModelerUtil.java    From jeddict with Apache License 2.0 5 votes vote down vote up
private static void cleanUnMarshaller() {
    try {
        String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><entity-mappings/>";
        MODELER_UNMARSHALLER.unmarshal(new StreamSource(new StringReader(xmlStr)));
    } catch (JAXBException ex) {
        System.err.println(ex);
    }
}