javax.xml.transform.sax.SAXSource Java Examples

The following examples show how to use javax.xml.transform.sax.SAXSource. 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: DocumentCache.java    From openjdk-8-source with GNU General Public License v2.0 7 votes vote down vote up
/**
 * Loads the document and updates build-time (latency) statistics
 */
public void loadDocument(String uri) {

    try {
        final long stamp = System.currentTimeMillis();
        _dom = (DOMEnhancedForDTM)_dtmManager.getDTM(
                         new SAXSource(_reader, new InputSource(uri)),
                         false, null, true, false);
        _dom.setDocumentURI(uri);

        // The build time can be used for statistics for a better
        // priority algorithm (currently round robin).
        final long thisTime = System.currentTimeMillis() - stamp;
        if (_buildTime > 0)
            _buildTime = (_buildTime + thisTime) >>> 1;
        else
            _buildTime = thisTime;
    }
    catch (Exception e) {
        _dom = null;
    }
}
 
Example #2
Source File: DTMManagerDefault.java    From jdk8u60 with GNU General Public License v2.0 7 votes vote down vote up
/**
 * This method returns the SAX2 parser to use with the InputSource
 * obtained from this URI.
 * It may return null if any SAX2-conformant XML parser can be used,
 * or if getInputSource() will also return null. The parser must
 * be free for use (i.e., not currently in use for another parse().
 * After use of the parser is completed, the releaseXMLReader(XMLReader)
 * must be called.
 *
 * @param inputSource The value returned from the URIResolver.
 * @return  a SAX2 XMLReader to use to resolve the inputSource argument.
 *
 * @return non-null XMLReader reference ready to parse.
 */
synchronized public XMLReader getXMLReader(Source inputSource)
{

  try
  {
    XMLReader reader = (inputSource instanceof SAXSource)
                       ? ((SAXSource) inputSource).getXMLReader() : null;

    // If user did not supply a reader, ask for one from the reader manager
    if (null == reader) {
      if (m_readerManager == null) {
          m_readerManager = XMLReaderManager.getInstance(super.useServicesMechnism());
      }

      reader = m_readerManager.getXMLReader();
    }

    return reader;

  } catch (SAXException se) {
    throw new DTMException(se.getMessage(), se);
  }
}
 
Example #3
Source File: DocumentCache.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Loads the document and updates build-time (latency) statistics
 */
public void loadDocument(String uri) {

    try {
        final long stamp = System.currentTimeMillis();
        _dom = (DOMEnhancedForDTM)_dtmManager.getDTM(
                         new SAXSource(_reader, new InputSource(uri)),
                         false, null, true, false);
        _dom.setDocumentURI(uri);

        // The build time can be used for statistics for a better
        // priority algorithm (currently round robin).
        final long thisTime = System.currentTimeMillis() - stamp;
        if (_buildTime > 0)
            _buildTime = (_buildTime + thisTime) >>> 1;
        else
            _buildTime = thisTime;
    }
    catch (Exception e) {
        _dom = null;
    }
}
 
Example #4
Source File: AbstractMarshaller.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Template method for handling {@code StreamSource}s.
 * <p>This implementation delegates to {@code unmarshalInputStream} or {@code unmarshalReader}.
 * @param streamSource the {@code StreamSource}
 * @return the object graph
 * @throws IOException if an I/O exception occurs
 * @throws XmlMappingException if the given source cannot be mapped to an object
 */
protected Object unmarshalStreamSource(StreamSource streamSource) throws XmlMappingException, IOException {
	if (streamSource.getInputStream() != null) {
		if (isProcessExternalEntities() && isSupportDtd()) {
			return unmarshalInputStream(streamSource.getInputStream());
		}
		else {
			InputSource inputSource = new InputSource(streamSource.getInputStream());
			inputSource.setEncoding(getDefaultEncoding());
			return unmarshalSaxSource(new SAXSource(inputSource));
		}
	}
	else if (streamSource.getReader() != null) {
		if (isProcessExternalEntities() && isSupportDtd()) {
			return unmarshalReader(streamSource.getReader());
		}
		else {
			return unmarshalSaxSource(new SAXSource(new InputSource(streamSource.getReader())));
		}
	}
	else {
		return unmarshalSaxSource(new SAXSource(new InputSource(streamSource.getSystemId())));
	}
}
 
Example #5
Source File: DocumentCache.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Loads the document and updates build-time (latency) statistics
 */
public void loadDocument(String uri) {

    try {
        final long stamp = System.currentTimeMillis();
        _dom = (DOMEnhancedForDTM)_dtmManager.getDTM(
                         new SAXSource(_reader, new InputSource(uri)),
                         false, null, true, false);
        _dom.setDocumentURI(uri);

        // The build time can be used for statistics for a better
        // priority algorithm (currently round robin).
        final long thisTime = System.currentTimeMillis() - stamp;
        if (_buildTime > 0)
            _buildTime = (_buildTime + thisTime) >>> 1;
        else
            _buildTime = thisTime;
    }
    catch (Exception e) {
        _dom = null;
    }
}
 
Example #6
Source File: UnmarshallerImpl.java    From hottub 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 #7
Source File: SourceHttpMessageConverterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void readSAXSourceExternal() throws Exception {
	MockHttpInputMessage inputMessage = new MockHttpInputMessage(bodyExternal.getBytes("UTF-8"));
	inputMessage.getHeaders().setContentType(new MediaType("application", "xml"));
	converter.setSupportDtd(true);
	SAXSource result = (SAXSource) converter.read(SAXSource.class, inputMessage);
	InputSource inputSource = result.getInputSource();
	XMLReader reader = result.getXMLReader();
	reader.setContentHandler(new DefaultHandler() {
		@Override
		public void characters(char[] ch, int start, int length) {
			String s = new String(ch, start, length);
			assertNotEquals("Invalid result", "Foo Bar", s);
		}
	});
	reader.parse(inputSource);
}
 
Example #8
Source File: CatalogSupport5.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@DataProvider(name = "data_ValidatorC")
public Object[][] getDataValidator() {
    DOMSource ds = getDOMSource(xml_val_test, xml_val_test_id, true, true, xml_catalog);

    SAXSource ss = new SAXSource(new InputSource(xml_val_test));
    ss.setSystemId(xml_val_test_id);

    StAXSource stax = getStaxSource(xml_val_test, xml_val_test_id, false, true, xml_catalog);
    StAXSource stax1 = getStaxSource(xml_val_test, xml_val_test_id, false, true, xml_catalog);

    StreamSource source = new StreamSource(new File(xml_val_test));

    return new Object[][]{
        // use catalog
        {false, false, true, ds, null, null, xml_bogus_catalog, null},
        {false, false, true, ds, null, null, null, xml_bogus_catalog},
        {false, false, true, ss, null, null, xml_bogus_catalog, null},
        {false, false, true, ss, null, null, null, xml_bogus_catalog},
        {false, false, true, stax, null, null, xml_bogus_catalog, null},
        {false, false, true, stax1, null, null, null, xml_bogus_catalog},
        {false, false, true, source, null, null, xml_bogus_catalog, null},
        {false, false, true, source, null, null, null, xml_bogus_catalog},
    };
}
 
Example #9
Source File: UnmarshallerImpl.java    From openjdk-jdk9 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 #10
Source File: MCRXSLTransformer.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
private void checkTemplateUptodate()
    throws TransformerConfigurationException, SAXException, ParserConfigurationException {
    boolean check = System.currentTimeMillis() - modifiedChecked > CHECK_PERIOD;
    boolean useCache = MCRConfiguration2.getBoolean("MCR.UseXSLTemplateCache").orElse(true);

    if (check || !useCache) {
        for (int i = 0; i < templateSources.length; i++) {
            long lastModified = templateSources[i].getLastModified();
            if (templates[i] == null || modified[i] < lastModified || !useCache) {
                SAXSource source = templateSources[i].getSource();
                templates[i] = tFactory.newTemplates(source);
                if (templates[i] == null) {
                    throw new TransformerConfigurationException(
                        "XSLT Stylesheet could not be compiled: " + templateSources[i].getURL());
                }
                modified[i] = lastModified;
            }
        }
        modifiedChecked = System.currentTimeMillis();
    }
}
 
Example #11
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 #12
Source File: TunedDocumentLoader.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public Document loadDocument(InputSource inputSource, EntityResolver entityResolver,
                             ErrorHandler errorHandler, int validationMode, boolean namespaceAware)
    throws Exception {
    if (validationMode == XmlBeanDefinitionReader.VALIDATION_NONE) {
        SAXParserFactory parserFactory =
            namespaceAware ? nsasaxParserFactory : saxParserFactory;
        SAXParser parser = parserFactory.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        reader.setEntityResolver(entityResolver);
        reader.setErrorHandler(errorHandler);
        SAXSource saxSource = new SAXSource(reader, inputSource);
        W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
        StaxUtils.copy(saxSource, writer);
        return writer.getDocument();
    }
    return super.loadDocument(inputSource, entityResolver, errorHandler, validationMode,
                              namespaceAware);
}
 
Example #13
Source File: DTMManagerDefault.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * This method returns the SAX2 parser to use with the InputSource
 * obtained from this URI.
 * It may return null if any SAX2-conformant XML parser can be used,
 * or if getInputSource() will also return null. The parser must
 * be free for use (i.e., not currently in use for another parse().
 * After use of the parser is completed, the releaseXMLReader(XMLReader)
 * must be called.
 *
 * @param inputSource The value returned from the URIResolver.
 * @return  a SAX2 XMLReader to use to resolve the inputSource argument.
 *
 * @return non-null XMLReader reference ready to parse.
 */
synchronized public XMLReader getXMLReader(Source inputSource)
{

  try
  {
    XMLReader reader = (inputSource instanceof SAXSource)
                       ? ((SAXSource) inputSource).getXMLReader() : null;

    // If user did not supply a reader, ask for one from the reader manager
    if (null == reader) {
      if (m_readerManager == null) {
          m_readerManager = XMLReaderManager.getInstance(super.useServicesMechnism());
      }

      reader = m_readerManager.getXMLReader();
    }

    return reader;

  } catch (SAXException se) {
    throw new DTMException(se.getMessage(), se);
  }
}
 
Example #14
Source File: HibersapJaxbXmlParser.java    From hibersap with Apache License 2.0 6 votes vote down vote up
public HibersapConfig parseResource(final InputStream resourceStream, final String resourceName) {
    Object unmarshalledObject;
    try {
        SAXSource saxSource = createSaxSource(resourceStream);
        unmarshalledObject = createUnmarshaller().unmarshal(saxSource);
    } catch (final JAXBException e) {
        throw new HibersapParseException("Cannot parse the resource " + resourceName, e);
    }

    if (unmarshalledObject == null) {
        throw new HibersapParseException("Resource " + resourceName + " is empty.");
    }
    if (!(unmarshalledObject instanceof HibersapConfig)) {
        throw new HibersapParseException("Resource " + resourceName
                + " does not consist of a hibersap specification. I found a "
                + unmarshalledObject.getClass().getSimpleName());
    }
    return (HibersapConfig) unmarshalledObject;
}
 
Example #15
Source File: SourceHttpMessageConverter.java    From java-technology-stack with MIT License 6 votes vote down vote up
@SuppressWarnings("deprecation")  // on JDK 9
private SAXSource readSAXSource(InputStream body, HttpInputMessage inputMessage) throws IOException {
	try {
		XMLReader xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader();
		xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd());
		xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", isProcessExternalEntities());
		if (!isProcessExternalEntities()) {
			xmlReader.setEntityResolver(NO_OP_ENTITY_RESOLVER);
		}
		byte[] bytes = StreamUtils.copyToByteArray(body);
		return new SAXSource(xmlReader, new InputSource(new ByteArrayInputStream(bytes)));
	}
	catch (SAXException ex) {
		throw new HttpMessageNotReadableException(
				"Could not parse document: " + ex.getMessage(), ex, inputMessage);
	}
}
 
Example #16
Source File: Jaxb2RootElementHttpMessageConverter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
protected Source processSource(Source source) {
	if (source instanceof StreamSource) {
		StreamSource streamSource = (StreamSource) source;
		InputSource inputSource = new InputSource(streamSource.getInputStream());
		try {
			XMLReader xmlReader = XMLReaderFactory.createXMLReader();
			xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd());
			String featureName = "http://xml.org/sax/features/external-general-entities";
			xmlReader.setFeature(featureName, isProcessExternalEntities());
			if (!isProcessExternalEntities()) {
				xmlReader.setEntityResolver(NO_OP_ENTITY_RESOLVER);
			}
			return new SAXSource(xmlReader, inputSource);
		}
		catch (SAXException ex) {
			logger.warn("Processing of external entities could not be disabled", ex);
			return source;
		}
	}
	else {
		return source;
	}
}
 
Example #17
Source File: AbstractStaxXMLReaderTestCase.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void whitespace() throws Exception {
	String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><test><node1> </node1><node2> Some text </node2></test>";

	Transformer transformer = TransformerFactory.newInstance().newTransformer();

	AbstractStaxXMLReader staxXmlReader = createStaxXmlReader(
			new ByteArrayInputStream(xml.getBytes("UTF-8")));

	SAXSource source = new SAXSource(staxXmlReader, new InputSource());
	DOMResult result = new DOMResult();

	transformer.transform(source, result);

	Node node1 = result.getNode().getFirstChild().getFirstChild();
	assertEquals(" ", node1.getTextContent());
	assertEquals(" Some text ", node1.getNextSibling().getTextContent());
}
 
Example #18
Source File: TestHierarchicalConfigurationXMLReader.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
@Test
public void testParse() throws Exception
{
    final SAXSource source = new SAXSource(parser, new InputSource());
    final DOMResult result = new DOMResult();
    final Transformer trans = TransformerFactory.newInstance().newTransformer();
    trans.transform(source, result);
    final Node root = ((Document) result.getNode()).getDocumentElement();
    final JXPathContext ctx = JXPathContext.newContext(root);

    assertEquals("Wrong name of root element", "database", root.getNodeName());
    assertEquals("Wrong number of children of root", 1, ctx.selectNodes(
            "/*").size());
    assertEquals("Wrong number of tables", 2, ctx.selectNodes(
            "/tables/table").size());
    assertEquals("Wrong name of first table", "users", ctx
            .getValue("/tables/table[1]/name"));
    assertEquals("Wrong number of fields in first table", 5, ctx
            .selectNodes("/tables/table[1]/fields/field").size());
    assertEquals("Wrong attribute value", "system", ctx
            .getValue("/tables/table[1]/@tableType"));
}
 
Example #19
Source File: AbstractMarshaller.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Template method for handling {@code StreamSource}s.
 * <p>This implementation delegates to {@code unmarshalInputStream} or {@code unmarshalReader}.
 * @param streamSource the {@code StreamSource}
 * @return the object graph
 * @throws IOException if an I/O exception occurs
 * @throws XmlMappingException if the given source cannot be mapped to an object
 */
protected Object unmarshalStreamSource(StreamSource streamSource) throws XmlMappingException, IOException {
	if (streamSource.getInputStream() != null) {
		if (isProcessExternalEntities() && isSupportDtd()) {
			return unmarshalInputStream(streamSource.getInputStream());
		}
		else {
			InputSource inputSource = new InputSource(streamSource.getInputStream());
			inputSource.setEncoding(getDefaultEncoding());
			return unmarshalSaxSource(new SAXSource(inputSource));
		}
	}
	else if (streamSource.getReader() != null) {
		if (isProcessExternalEntities() && isSupportDtd()) {
			return unmarshalReader(streamSource.getReader());
		}
		else {
			return unmarshalSaxSource(new SAXSource(new InputSource(streamSource.getReader())));
		}
	}
	else {
		return unmarshalSaxSource(new SAXSource(new InputSource(streamSource.getSystemId())));
	}
}
 
Example #20
Source File: JaxbPersistenceFactory.java    From tomee with Apache License 2.0 6 votes vote down vote up
public static <T> T getPersistence(final Class<T> clazz, final InputStream persistenceDescriptor) throws Exception {
    final JAXBContext jc = clazz.getClassLoader() == JaxbPersistenceFactory.class.getClassLoader() ?
            JaxbJavaee.getContext(clazz) : JAXBContextFactory.newInstance(clazz);
    final Unmarshaller u = jc.createUnmarshaller();
    final UnmarshallerHandler uh = u.getUnmarshallerHandler();

    // create a new XML parser
    final SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);
    final SAXParser parser = factory.newSAXParser();

    final XMLReader xmlReader = parser.getXMLReader();

    // Create a filter to intercept events
    final PersistenceFilter xmlFilter = new PersistenceFilter(xmlReader);

    // Be sure the filter has the JAXB content handler set (or it wont work)
    xmlFilter.setContentHandler(uh);
    final SAXSource source = new SAXSource(xmlFilter, new InputSource(persistenceDescriptor));

    return (T) u.unmarshal(source);
}
 
Example #21
Source File: Bug6490921.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test02() {
    String xml = "<?xml version='1.0'?><root/>";
    ReaderStub.used = false;
    setSystemProperty("org.xml.sax.driver", ReaderStub.class.getName());
    try {
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer();
        InputSource in = new InputSource(new StringReader(xml));
        SAXSource source = new SAXSource(in);
        StreamResult result = new StreamResult(new StringWriter());
        transformer.transform(source, result);
        Assert.assertTrue(printWasReaderStubCreated());
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
}
 
Example #22
Source File: AbstractUnmarshallerImpl.java    From TencentKona-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 #23
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 #24
Source File: SAXSourceTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This test case tries to get InputSource from DOMSource using
 * sourceToInputSource method. It is not possible and hence null is
 * expected. This is a negative test case,
 *
 * @throws Exception If any errors occur.
 */
@Test
public void source2inputsource02() throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.newDocumentBuilder().parse(new File(TEST_FILE));
    assertNull(SAXSource.sourceToInputSource(new DOMSource(null)));
}
 
Example #25
Source File: XSLTExFuncTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example #26
Source File: SOAPPartImpl.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public Source getContent() throws SOAPException {
    if (source != null) {
        InputStream bis = null;
        if (source instanceof JAXMStreamSource) {
            StreamSource streamSource = (StreamSource)source;
            bis = streamSource.getInputStream();
        } else if (FastInfosetReflection.isFastInfosetSource(source)) {
            // FastInfosetSource inherits from SAXSource
            SAXSource saxSource = (SAXSource)source;
            bis = saxSource.getInputSource().getByteStream();
        }

        if (bis != null) {
            try {
                bis.reset();
            } catch (IOException e) {
                /* This exception will never be thrown.
                 *
                 * The setContent method will modify the source
                 * if StreamSource to JAXMStreamSource, that uses
                 * a ByteInputStream, and for a FastInfosetSource will
                 * replace the InputStream with a ByteInputStream.
                 */
            }
        }
        return source;
    }

    return ((Envelope) getEnvelope()).getContent();
}
 
Example #27
Source File: MCRXSLTransformer.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
public synchronized void setTransformerFactory(String factoryClass) throws TransformerFactoryConfigurationError {
    TransformerFactory transformerFactory = Optional.ofNullable(factoryClass)
        .map(c -> TransformerFactory.newInstance(c, MCRClassTools.getClassLoader()))
        .orElseGet(TransformerFactory::newInstance);
    LOGGER.debug("Transformerfactory: {}", transformerFactory.getClass().getName());
    transformerFactory.setURIResolver(URI_RESOLVER);
    transformerFactory.setErrorListener(MCRErrorListener.getInstance());
    if (transformerFactory.getFeature(SAXSource.FEATURE) && transformerFactory.getFeature(SAXResult.FEATURE)) {
        this.tFactory = (SAXTransformerFactory) transformerFactory;
    } else {
        throw new MCRConfigurationException("Transformer Factory " + transformerFactory.getClass().getName()
            + " does not implement SAXTransformerFactory");
    }
}
 
Example #28
Source File: SourceUtils.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public SourceUtils(Source src) {
    if(src instanceof StreamSource){
        srcType = streamSource;
    }else if(src instanceof DOMSource){
        srcType = domSource;
    }else if(src instanceof SAXSource){
        srcType = saxSource;
    }
}
 
Example #29
Source File: MultipleStreamTest.java    From exificient with MIT License 5 votes vote down vote up
protected void _testDecode(EXIFactory exiFactory, byte[] isBytes,
		int numberOfEXIDocuments, InputStream isEXI) throws EXIException,
		TransformerException, AssertionFailedError, IOException,
		ParserConfigurationException, SAXException {
	// decode EXI
	TransformerFactory tf = TransformerFactory.newInstance();
	Transformer transformer = tf.newTransformer();

	for (int i = 0; i < numberOfEXIDocuments; i++) {
		// InputSource is = new InputSource(isEXI);
		InputSource is = new InputSource(isEXI);
		SAXSource exiSource = new SAXSource(is);
		XMLReader exiReader = new SAXFactory(exiFactory).createEXIReader();
		exiSource.setXMLReader(exiReader);
		ByteArrayOutputStream xmlOutput = new ByteArrayOutputStream();
		Result result = new StreamResult(xmlOutput);
		transformer.transform(exiSource, result);
		byte[] xmlDec = xmlOutput.toByteArray();
		// System.out.println("Decode #" + (i+1) + new String(xmlDec));

		ByteArrayInputStream baisControl = new ByteArrayInputStream(isBytes); // testing
																				// only
		checkXMLEquality(exiFactory, baisControl, new ByteArrayInputStream(
				xmlDec));
		// checkXMLValidity(exiFactory, new ByteArrayInputStream(xmlDec));
	}
}
 
Example #30
Source File: SourceHttpMessageConverterTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void readSAXSourceWithXmlBomb() throws Exception {
	// https://en.wikipedia.org/wiki/Billion_laughs
	// https://msdn.microsoft.com/en-us/magazine/ee335713.aspx
	String content = "<?xml version=\"1.0\"?>\n" +
			"<!DOCTYPE lolz [\n" +
			" <!ENTITY lol \"lol\">\n" +
			" <!ELEMENT lolz (#PCDATA)>\n" +
			" <!ENTITY lol1 \"&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;\">\n" +
			" <!ENTITY lol2 \"&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;\">\n" +
			" <!ENTITY lol3 \"&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;\">\n" +
			" <!ENTITY lol4 \"&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;\">\n" +
			" <!ENTITY lol5 \"&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;\">\n" +
			" <!ENTITY lol6 \"&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;\">\n" +
			" <!ENTITY lol7 \"&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;\">\n" +
			" <!ENTITY lol8 \"&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;\">\n" +
			" <!ENTITY lol9 \"&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;\">\n" +
			"]>\n" +
			"<root>&lol9;</root>";

	MockHttpInputMessage inputMessage = new MockHttpInputMessage(content.getBytes("UTF-8"));
	SAXSource result = (SAXSource) this.converter.read(SAXSource.class, inputMessage);

	this.thrown.expect(SAXException.class);
	this.thrown.expectMessage("DOCTYPE");

	InputSource inputSource = result.getInputSource();
	XMLReader reader = result.getXMLReader();
	reader.parse(inputSource);
}