Java Code Examples for javax.xml.transform.stax.StAXSource

The following are top voted examples for showing how to use javax.xml.transform.stax.StAXSource. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: OpenDiabetes   File: JDBCSQLXML.java   View source code 6 votes vote down vote up
/**
 * Returns a Source for reading the XML value designated by this SQLXML
 * instance. <p>
 *
 * @param sourceClass The class of the source, or null.  If null, then a
 *      DOMSource is returned.
 * @return a Source for reading the XML value.
 * @throws SQLException if there is an error processing the XML value
 *   or if the given <tt>sourceClass</tt> is not supported.
 */
protected <T extends Source>T getSourceImpl(
        Class<T> sourceClass) throws SQLException {

    if (JAXBSource.class.isAssignableFrom(sourceClass)) {

        // Must go first presently, since JAXBSource extends SAXSource
        // (purely as an implementation detail) and it's not possible
        // to instantiate a valid JAXBSource with a Zero-Args
        // constructor(or any subclass thereof, due to the finality of
        // its private marshaller and context object attributes)
        // FALL THROUGH... will throw an exception
    } else if (StreamSource.class.isAssignableFrom(sourceClass)) {
        return createStreamSource(sourceClass);
    } else if ((sourceClass == null)
               || DOMSource.class.isAssignableFrom(sourceClass)) {
        return createDOMSource(sourceClass);
    } else if (SAXSource.class.isAssignableFrom(sourceClass)) {
        return createSAXSource(sourceClass);
    } else if (StAXSource.class.isAssignableFrom(sourceClass)) {
        return createStAXSource(sourceClass);
    }

    throw JDBCUtil.invalidArgument("sourceClass: " + sourceClass);
}
 
Example 2
Project: sstore-soft   File: JDBCSQLXML.java   View source code 6 votes vote down vote up
/**
 * Returns a Source for reading the XML value designated by this SQLXML
 * instance. <p>
 *
 * @param sourceClass The class of the source, or null.  If null, then a
 *      DOMSource is returned.
 * @return a Source for reading the XML value.
 * @throws SQLException if there is an error processing the XML value
 *   or if the given <tt>sourceClass</tt> is not supported.
 */
protected <T extends Source>T getSourceImpl(
        Class<T> sourceClass) throws SQLException {

    if (JAXBSource.class.isAssignableFrom(sourceClass)) {

        // Must go first presently, since JAXBSource extends SAXSource
        // (purely as an implmentation detail) and it's not possible
        // to instantiate a valid JAXBSource with a Zero-Args
        // constructor(or any subclass thereof, due to the finality of
        // its private marshaller and context object attrbutes)
        // FALL THROUGH... will throw an exception
    } else if (StreamSource.class.isAssignableFrom(sourceClass)) {
        return createStreamSource(sourceClass);
    } else if ((sourceClass == null)
               || DOMSource.class.isAssignableFrom(sourceClass)) {
        return createDOMSource(sourceClass);
    } else if (SAXSource.class.isAssignableFrom(sourceClass)) {
        return createSAXSource(sourceClass);
    } else if (StAXSource.class.isAssignableFrom(sourceClass)) {
        return createStAXSource(sourceClass);
    }

    throw Util.invalidArgument("sourceClass: " + sourceClass);
}
 
Example 3
Project: s-store   File: JDBCSQLXML.java   View source code 6 votes vote down vote up
/**
 * Returns a Source for reading the XML value designated by this SQLXML
 * instance. <p>
 *
 * @param sourceClass The class of the source, or null.  If null, then a
 *      DOMSource is returned.
 * @return a Source for reading the XML value.
 * @throws SQLException if there is an error processing the XML value
 *   or if the given <tt>sourceClass</tt> is not supported.
 */
protected <T extends Source>T getSourceImpl(
        Class<T> sourceClass) throws SQLException {

    if (JAXBSource.class.isAssignableFrom(sourceClass)) {

        // Must go first presently, since JAXBSource extends SAXSource
        // (purely as an implmentation detail) and it's not possible
        // to instantiate a valid JAXBSource with a Zero-Args
        // constructor(or any subclass thereof, due to the finality of
        // its private marshaller and context object attrbutes)
        // FALL THROUGH... will throw an exception
    } else if (StreamSource.class.isAssignableFrom(sourceClass)) {
        return createStreamSource(sourceClass);
    } else if ((sourceClass == null)
               || DOMSource.class.isAssignableFrom(sourceClass)) {
        return createDOMSource(sourceClass);
    } else if (SAXSource.class.isAssignableFrom(sourceClass)) {
        return createSAXSource(sourceClass);
    } else if (StAXSource.class.isAssignableFrom(sourceClass)) {
        return createStAXSource(sourceClass);
    }

    throw Util.invalidArgument("sourceClass: " + sourceClass);
}
 
Example 4
Project: lams   File: SourceHttpMessageConverter.java   View source code 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected T readInternal(Class<? extends T> clazz, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	InputStream body = inputMessage.getBody();
	if (DOMSource.class.equals(clazz)) {
		return (T) readDOMSource(body);
	}
	else if (SAXSource.class.equals(clazz)) {
		return (T) readSAXSource(body);
	}
	else if (StAXSource.class.equals(clazz)) {
		return (T) readStAXSource(body);
	}
	else if (StreamSource.class.equals(clazz) || Source.class.equals(clazz)) {
		return (T) readStreamSource(body);
	}
	else {
		throw new HttpMessageConversionException("Could not read class [" + clazz +
				"]. Only DOMSource, SAXSource, StAXSource, and StreamSource are supported.");
	}
}
 
Example 5
Project: lams   File: SourceHttpMessageConverter.java   View source code 6 votes vote down vote up
private Source readStAXSource(InputStream body) {
	try {
		XMLInputFactory inputFactory = XMLInputFactory.newFactory();
		inputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, isProcessExternalEntities());
		if (!isProcessExternalEntities()) {
			inputFactory.setXMLResolver(NO_OP_XML_RESOLVER);
		}
		XMLStreamReader streamReader = inputFactory.createXMLStreamReader(body);
		return new StAXSource(streamReader);
	}
	catch (XMLStreamException ex) {
		throw new HttpMessageNotReadableException("Could not parse document: " + ex.getMessage(), ex);
	}
}
 
Example 6
Project: dev-courses   File: JDBCSQLXML.java   View source code 6 votes vote down vote up
/**
 * Returns a Source for reading the XML value designated by this SQLXML
 * instance. <p>
 *
 * @param sourceClass The class of the source, or null.  If null, then a
 *      DOMSource is returned.
 * @return a Source for reading the XML value.
 * @throws SQLException if there is an error processing the XML value
 *   or if the given <tt>sourceClass</tt> is not supported.
 */
protected <T extends Source>T getSourceImpl(
        Class<T> sourceClass) throws SQLException {

    if (JAXBSource.class.isAssignableFrom(sourceClass)) {

        // Must go first presently, since JAXBSource extends SAXSource
        // (purely as an implmentation detail) and it's not possible
        // to instantiate a valid JAXBSource with a Zero-Args
        // constructor(or any subclass thereof, due to the finality of
        // its private marshaller and context object attrbutes)
        // FALL THROUGH... will throw an exception
    } else if (StreamSource.class.isAssignableFrom(sourceClass)) {
        return createStreamSource(sourceClass);
    } else if ((sourceClass == null)
               || DOMSource.class.isAssignableFrom(sourceClass)) {
        return createDOMSource(sourceClass);
    } else if (SAXSource.class.isAssignableFrom(sourceClass)) {
        return createSAXSource(sourceClass);
    } else if (StAXSource.class.isAssignableFrom(sourceClass)) {
        return createStAXSource(sourceClass);
    }

    throw JDBCUtil.invalidArgument("sourceClass: " + sourceClass);
}
 
Example 7
Project: openjdk-jdk10   File: StAXSourceTest.java   View source code 6 votes vote down vote up
/**
 * @bug 8152530
 * Verifies that StAXSource handles empty namespace properly. NPE was thrown
 * before the fix.
 * @throws Exception if the test fails
 */
@Test
public final void testStAXSourceWEmptyNS() throws Exception {
    String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        + "<EntityList>\n"
        + "  <Entity xmlns=\"\">\n"
        + "  </Entity>\n"
        + "  <Entity xmlns=\"\">\n"
        + "  </Entity>\n"
        + "</EntityList> ";

    XMLInputFactory xif = XMLInputFactory.newInstance();
    XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(xml));
    xsr.nextTag();
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    while (xsr.nextTag() == XMLStreamConstants.START_ELEMENT && xsr.getLocalName().equals("Entity")) {
        StringWriter stringResult = new StringWriter();
        t.transform(new StAXSource(xsr), new StreamResult(stringResult));
        System.out.println("result: \n" + stringResult.toString());
    }
}
 
Example 8
Project: openjdk-jdk10   File: StAXSourceTest.java   View source code 6 votes vote down vote up
@Test
public final void testStAXSource2() throws XMLStreamException {
    XMLInputFactory ifactory = XMLInputFactory.newInstance();
    ifactory.setProperty("javax.xml.stream.supportDTD", Boolean.TRUE);

    StAXSource ss = new StAXSource(ifactory.createXMLStreamReader(getClass().getResource("5368141.xml").toString(),
            getClass().getResourceAsStream("5368141.xml")));
    DOMResult dr = new DOMResult();

    TransformerFactory tfactory = TransformerFactory.newInstance();
    try {
        Transformer transformer = tfactory.newTransformer();
        transformer.transform(ss, dr);
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }
}
 
Example 9
Project: openjdk-jdk10   File: CatalogSupport4.java   View source code 6 votes vote down vote up
@DataProvider(name = "data_ValidatorA")
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, true, true, xml_catalog);
    StAXSource stax1 = getStaxSource(xml_val_test, xml_val_test_id, true, true, xml_catalog);

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

    return new Object[][]{
        // use catalog
        {true, false, true, ds, null, null, xml_catalog, null},
        {false, true, true, ds, null, null, null, xml_catalog},
        {true, false, true, ss, null, null, xml_catalog, null},
        {false, true, true, ss, null, null, null, xml_catalog},
        {true, false, true, stax, null, null, xml_catalog, xml_catalog},
        {false, true, true, stax1, null, null, xml_catalog, xml_catalog},
        {true, false, true, source, null, null, xml_catalog, null},
        {false, true, true, source, null, null, null, xml_catalog},
    };
}
 
Example 10
Project: openjdk-jdk10   File: CatalogSupport5.java   View source code 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 11
Project: openjdk-jdk10   File: CatalogSupport2.java   View source code 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_catalog, null},
        {false, false, true, ds, null, null, null, xml_catalog},
        {false, false, true, ss, null, null, xml_catalog, null},
        {false, false, true, ss, null, null, null, xml_catalog},
        {false, false, true, stax, null, null, xml_catalog, null},
        {false, false, true, stax1, null, null, null, xml_catalog},
        {false, false, true, source, null, null, xml_catalog, null},
        {false, false, true, source, null, null, null, xml_catalog},
    };
}
 
Example 12
Project: openjdk9   File: StAXSourceTest.java   View source code 6 votes vote down vote up
@Test
public final void testStAXSource2() throws XMLStreamException {
    XMLInputFactory ifactory = XMLInputFactory.newInstance();
    ifactory.setProperty("javax.xml.stream.supportDTD", Boolean.TRUE);

    StAXSource ss = new StAXSource(ifactory.createXMLStreamReader(getClass().getResource("5368141.xml").toString(),
            getClass().getResourceAsStream("5368141.xml")));
    DOMResult dr = new DOMResult();

    TransformerFactory tfactory = TransformerFactory.newInstance();
    try {
        Transformer transformer = tfactory.newTransformer();
        transformer.transform(ss, dr);
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }
}
 
Example 13
Project: spring4-understanding   File: SourceHttpMessageConverter.java   View source code 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected T readInternal(Class<? extends T> clazz, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	InputStream body = inputMessage.getBody();
	if (DOMSource.class == clazz) {
		return (T) readDOMSource(body);
	}
	else if (SAXSource.class == clazz) {
		return (T) readSAXSource(body);
	}
	else if (StAXSource.class == clazz) {
		return (T) readStAXSource(body);
	}
	else if (StreamSource.class == clazz || Source.class == clazz) {
		return (T) readStreamSource(body);
	}
	else {
		throw new HttpMessageConversionException("Could not read class [" + clazz +
				"]. Only DOMSource, SAXSource, StAXSource, and StreamSource are supported.");
	}
}
 
Example 14
Project: spring4-understanding   File: SourceHttpMessageConverterTests.java   View source code 6 votes vote down vote up
@Test
public void readStAXSourceExternal() throws Exception {
	MockHttpInputMessage inputMessage = new MockHttpInputMessage(bodyExternal.getBytes("UTF-8"));
	inputMessage.getHeaders().setContentType(new MediaType("application", "xml"));
	converter.setSupportDtd(true);
	StAXSource result = (StAXSource) converter.read(StAXSource.class, inputMessage);
	XMLStreamReader streamReader = result.getXMLStreamReader();
	assertTrue(streamReader.hasNext());
	streamReader.next();
	streamReader.next();
	String s = streamReader.getLocalName();
	assertEquals("root", s);
	try {
		s = streamReader.getElementText();
		assertNotEquals("Foo Bar", s);
	}
	catch (XMLStreamException ex) {
		// Some parsers raise a parse exception
	}
	streamReader.close();
}
 
Example 15
Project: Camel   File: XQueryBuilder.java   View source code 6 votes vote down vote up
/**
 * Converts the inbound body to a {@link Source}, if the body is <b>not</b> already a {@link Source}.
 * <p/>
 * This implementation will prefer to source in the following order:
 * <ul>
 *   <li>StAX - Is StAX is allowed</li>
 *   <li>SAX - SAX as 2nd choice</li>
 *   <li>Stream - Stream as 3rd choice</li>
 *   <li>DOM - DOM as 4th choice</li>
 * </ul>
 */
protected Source getSource(Exchange exchange, Object body) {
    // body may already be a source
    if (body instanceof Source) {
        return (Source) body;
    }

    Source source = null;
    if (isAllowStAX()) {
        source = exchange.getContext().getTypeConverter().tryConvertTo(StAXSource.class, exchange, body);
    }
    if (source == null) {
        // then try SAX
        source = exchange.getContext().getTypeConverter().tryConvertTo(SAXSource.class, exchange, body);
    }
    if (source == null) {
        // then try stream
        source = exchange.getContext().getTypeConverter().tryConvertTo(StreamSource.class, exchange, body);
    }
    if (source == null) {
        // and fallback to DOM
        source = exchange.getContext().getTypeConverter().tryConvertTo(DOMSource.class, exchange, body);
    }
    return source;
}
 
Example 16
Project: VoltDB   File: JDBCSQLXML.java   View source code 6 votes vote down vote up
/**
 * Returns a Source for reading the XML value designated by this SQLXML
 * instance. <p>
 *
 * @param sourceClass The class of the source, or null.  If null, then a
 *      DOMSource is returned.
 * @return a Source for reading the XML value.
 * @throws SQLException if there is an error processing the XML value
 *   or if the given <tt>sourceClass</tt> is not supported.
 */
protected <T extends Source>T getSourceImpl(
        Class<T> sourceClass) throws SQLException {

    if (JAXBSource.class.isAssignableFrom(sourceClass)) {

        // Must go first presently, since JAXBSource extends SAXSource
        // (purely as an implmentation detail) and it's not possible
        // to instantiate a valid JAXBSource with a Zero-Args
        // constructor(or any subclass thereof, due to the finality of
        // its private marshaller and context object attrbutes)
        // FALL THROUGH... will throw an exception
    } else if (StreamSource.class.isAssignableFrom(sourceClass)) {
        return createStreamSource(sourceClass);
    } else if ((sourceClass == null)
               || DOMSource.class.isAssignableFrom(sourceClass)) {
        return createDOMSource(sourceClass);
    } else if (SAXSource.class.isAssignableFrom(sourceClass)) {
        return createSAXSource(sourceClass);
    } else if (StAXSource.class.isAssignableFrom(sourceClass)) {
        return createStAXSource(sourceClass);
    }

    throw Util.invalidArgument("sourceClass: " + sourceClass);
}
 
Example 17
Project: eMonocot   File: UnmarshallCharacterStatesTest.java   View source code 6 votes vote down vote up
/**
 * @throws Exception
 *             if there is a problem
 *
 */
@Test
public final void testParseCharacterStatesFragment() throws Exception {

	CategoricalCharacter categoricalCharacter = (CategoricalCharacter) super
			.getUnmarshaller().unmarshal(
					new StAXSource(getXMLEventReader(filename)));
	assertNotNull("categoricalCharacter should not be null",
			categoricalCharacter);
	assertEquals("categoricalCharacter.id should equal c7", "c7",
			categoricalCharacter.getId());
	assertEquals(
			"categoricalCharacter.representation.label should be shape",
			"shape", categoricalCharacter.getRepresentation().getLabel());
	assertEquals("there should be two states",3 , categoricalCharacter
			.getStates().size());

}
 
Example 18
Project: xslweb   File: ParseJSON.java   View source code 6 votes vote down vote up
@Override
public Sequence call(XPathContext context, Sequence[] arguments) throws XPathException {                     
  try {
    String json = ((StringValue) arguments[0].head()).getStringValue();
    if (StringUtils.isBlank(json)) {
      return EmptySequence.getInstance();
    }        
    XMLInputFactory factory = new JsonXMLInputFactory();                
    XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(json));        
    StAXSource source = new StAXSource(reader);        
    Configuration config = context.getConfiguration();        
    PipelineConfiguration pipe = config.makePipelineConfiguration();
    pipe.getParseOptions().getParserFeatures().remove("http://apache.org/xml/features/xinclude");        
    TinyBuilder builder = new TinyBuilder(pipe);        
    SerializerFactory sf = config.getSerializerFactory();
    Receiver receiver = sf.getReceiver(builder, pipe, new Properties());               
    NamespaceReducer reducer = new NamespaceReducer(receiver);
    ParseOptions options = pipe.getParseOptions();
    options.setContinueAfterValidationErrors(true);
    Sender.send(source, reducer, options);                             
    return builder.getCurrentRoot();                
  } catch (Exception e) {
    throw new XPathException("Error parsing JSON string", e);
  }                    
}
 
Example 19
Project: jetstream   File: ConfigurationManagementXMLParser.java   View source code 6 votes vote down vote up
public List<JetStreamBeanConfigurationDo> parse(String source)
        throws FileNotFoundException, XMLStreamException,
        TransformerException {
    List<JetStreamBeanConfigurationDo> list = new ArrayList<JetStreamBeanConfigurationDo>();

    XMLInputFactory xmlInputfactory = XMLInputFactory.newInstance();
    TransformerFactory transformerFactory = TransformerFactory
            .newInstance();
    XMLStreamReader reader = xmlInputfactory
            .createXMLStreamReader(new StringReader(source));
    reader.nextTag();
    Transformer t = transformerFactory.newTransformer();
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    while (reader.nextTag() == XMLStreamConstants.START_ELEMENT) {
        JetStreamBeanConfigurationDo doObj = new JetStreamBeanConfigurationDo();
        doObj.setBeanName(getId(reader));
        t.transform(new StAXSource(reader), new StreamResult(bao));
        doObj.setBeanDefinition(getSource(bao.toString()));
        list.add(doObj);
        bao.reset();
    }

    return list;
}
 
Example 20
Project: teiid   File: XQueryEvaluator.java   View source code 6 votes vote down vote up
private static Source wrapStax(Source value, Configuration config) throws TeiidProcessingException {
	if (value instanceof StAXSource) {
		//saxon doesn't like staxsources
		StaxToEventBridge sb = new StaxToEventBridge();
		sb.setPipelineConfiguration(config.makePipelineConfiguration());
		StAXSource staxSource = (StAXSource)value;
		if (staxSource.getXMLEventReader() != null) {
			try {
				sb.setXMLStreamReader(new XMLEventStreamReader(staxSource.getXMLEventReader()));
			} catch (XMLStreamException e) {
				//should not happen as the StAXSource already peeked
				throw new TeiidProcessingException(e);
			}
		} else {
			sb.setXMLStreamReader(staxSource.getXMLStreamReader());
		}
		value = new PullEventSource(sb);
	}
	return value;
}
 
Example 21
Project: bagri   File: BagriXQDataFactory.java   View source code 6 votes vote down vote up
@Override
public XQItem createItemFromDocument(XMLStreamReader value, XQItemType type) throws XQException {

	checkState(ex_connection_closed);
	if (value == null) {
		throw new XQException("StreamReader is null");
	}

	String content;
	try {
		content = XMLUtils.sourceToString(new StAXSource(value), null);
	} catch (IOException ex) {
		throw new XQException(ex.getMessage());
	}
	return createItemFromDocument(content, null, type);
}
 
Example 22
Project: Pegasus   File: JDBCSQLXML.java   View source code 6 votes vote down vote up
/**
 * Returns a Source for reading the XML value designated by this SQLXML
 * instance. <p>
 *
 * @param sourceClass The class of the source, or null.  If null, then a
 *      DOMSource is returned.
 * @return a Source for reading the XML value.
 * @throws SQLException if there is an error processing the XML value
 *   or if the given <tt>sourceClass</tt> is not supported.
 */
protected <T extends Source>T getSourceImpl(
        Class<T> sourceClass) throws SQLException {

    if (JAXBSource.class.isAssignableFrom(sourceClass)) {

        // Must go first presently, since JAXBSource extends SAXSource
        // (purely as an implmentation detail) and it's not possible
        // to instantiate a valid JAXBSource with a Zero-Args
        // constructor(or any subclass thereof, due to the finality of
        // its private marshaller and context object attrbutes)
        // FALL THROUGH... will throw an exception
    } else if (StreamSource.class.isAssignableFrom(sourceClass)) {
        return createStreamSource(sourceClass);
    } else if ((sourceClass == null)
               || DOMSource.class.isAssignableFrom(sourceClass)) {
        return createDOMSource(sourceClass);
    } else if (SAXSource.class.isAssignableFrom(sourceClass)) {
        return createSAXSource(sourceClass);
    } else if (StAXSource.class.isAssignableFrom(sourceClass)) {
        return createStAXSource(sourceClass);
    }

    throw Util.invalidArgument("sourceClass: " + sourceClass);
}
 
Example 23
Project: StoryBear   File: JDBCSQLXML.java   View source code 6 votes vote down vote up
/**
 * Returns a Source for reading the XML value designated by this SQLXML
 * instance. <p>
 *
 * @param sourceClass The class of the source, or null.  If null, then a
 *      DOMSource is returned.
 * @return a Source for reading the XML value.
 * @throws SQLException if there is an error processing the XML value
 *   or if the given <tt>sourceClass</tt> is not supported.
 */
protected <T extends Source>T getSourceImpl(
        Class<T> sourceClass) throws SQLException {

    if (JAXBSource.class.isAssignableFrom(sourceClass)) {

        // Must go first presently, since JAXBSource extends SAXSource
        // (purely as an implmentation detail) and it's not possible
        // to instantiate a valid JAXBSource with a Zero-Args
        // constructor(or any subclass thereof, due to the finality of
        // its private marshaller and context object attrbutes)
        // FALL THROUGH... will throw an exception
    } else if (StreamSource.class.isAssignableFrom(sourceClass)) {
        return createStreamSource(sourceClass);
    } else if ((sourceClass == null)
               || DOMSource.class.isAssignableFrom(sourceClass)) {
        return createDOMSource(sourceClass);
    } else if (SAXSource.class.isAssignableFrom(sourceClass)) {
        return createSAXSource(sourceClass);
    } else if (StAXSource.class.isAssignableFrom(sourceClass)) {
        return createStAXSource(sourceClass);
    }

    throw JDBCUtil.invalidArgument("sourceClass: " + sourceClass);
}
 
Example 24
Project: cleverbus   File: RemoveStAXConverters.java   View source code 6 votes vote down vote up
/**
 * Remove all converters to {@link StAXSource}.
 *
 * @param event event about finished start of {@link CamelContext}
 * @throws Exception all errors
 */
@Override
public void notify(final EventObject event) throws Exception {
    if (event instanceof CamelContextStartedEvent) {
        CamelContext camelContext = ((CamelContextStartedEvent) event).getContext();

        if (camelContext.getTypeConverterRegistry().removeTypeConverter(StAXSource.class, byte[].class)) {
            Log.debug("Remove converter from '{}' to '{}'.", byte[].class.getSimpleName(),
                    StAXSource.class.getSimpleName());
        }
        if (camelContext.getTypeConverterRegistry().removeTypeConverter(StAXSource.class, File.class)) {
            Log.debug("Remove converter from '{}' to '{}'.", File.class.getSimpleName(),
                    StAXSource.class.getSimpleName());
        }
        if (camelContext.getTypeConverterRegistry().removeTypeConverter(StAXSource.class, InputStream.class)) {
            Log.debug("Remove converter from '{}' to '{}'.", InputStream.class.getSimpleName(),
                    StAXSource.class.getSimpleName());
        }
        if (camelContext.getTypeConverterRegistry().removeTypeConverter(StAXSource.class, String.class)) {
            Log.debug("Remove converter from '{}' to '{}'.", String.class.getSimpleName(),
                    StAXSource.class.getSimpleName());
        }
    }
}
 
Example 25
Project: olca-modules   File: GeoKmzImport.java   View source code 6 votes vote down vote up
private byte[] getKmz(XMLStreamReader reader) {
	try {
		DOMResult dom = new DOMResult();
		transformer.transform(new StAXSource(reader), dom);
		Document doc = (Document) dom.getNode();
		NodeList list = doc.getElementsByTagName("*");
		String ns = "http://earth.google.com/kml/2.1";
		for (int i = 0; i < list.getLength(); i++) {
			Node n = list.item(i);
			doc.renameNode(n, ns, n.getLocalName());
		}
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		transformer.transform(new DOMSource(doc), new StreamResult(bout));
		byte[] bytes = bout.toByteArray();
		return BinUtils.zip(bytes);
	} catch (Exception e) {
		log.error("failed to parse KML", e);
		return null;
	}
}
 
Example 26
Project: fluentxml4j   File: StaxUtils.java   View source code 5 votes vote down vote up
public static StAXSource newStAXSource(XMLEventReader in)
{
	try
	{
		return new StAXSource(in);
	}
	catch (XMLStreamException ex)
	{
		throw new FluentXmlProcessingException(ex);
	}
}
 
Example 27
Project: fluentxml4j   File: StaxUtilsTest.java   View source code 5 votes vote down vote up
@Test
public void newStAXSource() throws Exception
{
	givenXMLEventReaderAtStartOfDocument();

	StAXSource source = StaxUtils.newStAXSource(xmlEventReader);

	assertThat(source, is(not(nullValue())));
}
 
Example 28
Project: openjdk-jdk10   File: EnvelopeFactory.java   View source code 5 votes vote down vote up
private static Envelope parseEnvelopeStax(Source src, SOAPPartImpl soapPart)
            throws SOAPException {
        XMLStreamReader streamReader = null;
        if (src instanceof StAXSource) {
           streamReader = ((StAXSource) src).getXMLStreamReader();
        }
        try {
            if (streamReader == null) {
                if (xmlInputFactory == null) xmlInputFactory = XMLInputFactory.newInstance();
                streamReader = xmlInputFactory.createXMLStreamReader(src);
            }
//            SaajStaxWriter saajWriter = new SaajStaxWriter(soapPart.message, soapPart.document);
//            XMLStreamReaderToXMLStreamWriter readerWriterBridge = new XMLStreamReaderToXMLStreamWriter(
//                    streamReader, saajWriter, soapPart.getSOAPNamespace());

            StaxBridge readerWriterBridge = new StaxReaderBridge(streamReader, soapPart);
            //bridge will stop reading at body element, and parse upon request, so save it
            //on the envelope
            readerWriterBridge.bridgeEnvelopeAndHeaders();

            Envelope env = (Envelope) soapPart.getEnvelope();
            env.setStaxBridge(readerWriterBridge);
            return env;
        } catch (Exception e) {
            throw new SOAPException(e);
        }
    }
 
Example 29
Project: openjdk-jdk10   File: XMLSchemaFactory.java   View source code 5 votes vote down vote up
public boolean getFeature(String name)
    throws SAXNotRecognizedException, SAXNotSupportedException {
    if (name == null) {
        throw new NullPointerException(JAXPValidationMessageFormatter.formatMessage(fXMLSchemaLoader.getLocale(),
                "FeatureNameNull", null));
    }
    if (name.startsWith(JAXP_SOURCE_FEATURE_PREFIX)) {
        // Indicates to the caller that this SchemaFactory supports a specific JAXP Source.
        if (name.equals(StreamSource.FEATURE) ||
            name.equals(SAXSource.FEATURE) ||
            name.equals(DOMSource.FEATURE) ||
            name.equals(StAXSource.FEATURE)) {
            return true;
        }
    }
    if (name.equals(XMLConstants.FEATURE_SECURE_PROCESSING)) {
        return (fSecurityManager != null && fSecurityManager.isSecureProcessing());
    }
    else if (name.equals(USE_GRAMMAR_POOL_ONLY)) {
        return fUseGrammarPoolOnly;
    }
    try {
        return fXMLSchemaLoader.getFeature(name);
    }
    catch (XMLConfigurationException e) {
        String identifier = e.getIdentifier();
        if (e.getType() == Status.NOT_RECOGNIZED) {
            throw new SAXNotRecognizedException(
                    SAXMessageFormatter.formatMessage(fXMLSchemaLoader.getLocale(),
                    "feature-not-recognized", new Object [] {identifier}));
        }
        else {
            throw new SAXNotSupportedException(
                    SAXMessageFormatter.formatMessage(fXMLSchemaLoader.getLocale(),
                    "feature-not-supported", new Object [] {identifier}));
        }
    }
}
 
Example 30
Project: openjdk-jdk10   File: CR6708840Test.java   View source code 5 votes vote down vote up
/**
 * refer to http://forums.java.net/jive/thread.jspa?threadID=41626&tstart=0
 */
@Test
public final void testStAX() {
    try {
        XMLInputFactory xmlif = XMLInputFactory.newInstance();

        // XMLStreamReader staxReader =
        // xmlif.createXMLStreamReader((Source)new
        // StreamSource(getClass().getResource("Forum31576.xml").getFile()));
        XMLStreamReader staxReader = xmlif.createXMLStreamReader(this.getClass().getResourceAsStream("gMonths.xml"));

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schemaGrammar = schemaFactory.newSchema(new File(getClass().getResource("gMonths.xsd").getFile()));

        Validator schemaValidator = schemaGrammar.newValidator();

        Source staxSrc = new StAXSource(staxReader);
        schemaValidator.validate(staxSrc);

        while (staxReader.hasNext()) {
            int eventType = staxReader.next();
            System.out.println("Event of type: " + eventType);
        }
    } catch (NullPointerException ne) {
        Assert.fail("NullPointerException when result is not specified.");
    } catch (Exception e) {
        Assert.fail(e.getMessage());
        e.printStackTrace();
    }
}
 
Example 31
Project: openjdk-jdk10   File: CR6708840Test.java   View source code 5 votes vote down vote up
/**
 * workaround before the fix: provide a result
 */
@Test
public final void testStAXWResult() {
    try {
        XMLInputFactory xmlif = XMLInputFactory.newInstance();

        // XMLStreamReader staxReader =
        // xmlif.createXMLStreamReader((Source)new
        // StreamSource(getClass().getResource("Forum31576.xml").getFile()));
        XMLStreamReader staxReader = xmlif.createXMLStreamReader(this.getClass().getResourceAsStream("gMonths.xml"));

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schemaGrammar = schemaFactory.newSchema(new File(getClass().getResource("gMonths.xsd").getFile()));

        Validator schemaValidator = schemaGrammar.newValidator();

        Source staxSrc = new StAXSource(staxReader);
        File resultFile = new File(USER_DIR + "gMonths.result.xml");
        if (resultFile.exists()) {
            resultFile.delete();
        }

        Result xmlResult = new javax.xml.transform.stax.StAXResult(XMLOutputFactory.newInstance().createXMLStreamWriter(new FileWriter(resultFile)));
        schemaValidator.validate(staxSrc, xmlResult);

        while (staxReader.hasNext()) {
            int eventType = staxReader.next();
            System.out.println("Event of type: " + eventType);
        }
    } catch (Exception e) {
        Assert.fail(e.getMessage());
        e.printStackTrace();
    }
}
 
Example 32
Project: openjdk-jdk10   File: TransformerFactoryTest.java   View source code 5 votes vote down vote up
/**
 * Refer to 6631168 : StAXSource & StAXResult support in JavaSE6
 */
@Test
public final void testFeatures() {
    TransformerFactory tff = TransformerFactory.newInstance();
    Assert.assertTrue(tff.getFeature(StAXSource.FEATURE));
    Assert.assertTrue(tff.getFeature(StAXResult.FEATURE));
}
 
Example 33
Project: openjdk-jdk10   File: TransformerTestTemplate.java   View source code 5 votes vote down vote up
public StAXSource getStAXSource(XMLInputFactory xif)
    throws XMLStreamException
{
    return new StAXSource(
        xif.createXMLStreamReader(new StringReader(sourceXml))
    );
}
 
Example 34
Project: openjdk-jdk10   File: CatalogSupport3.java   View source code 5 votes vote down vote up
@DataProvider(name = "data_ValidatorC")
public Object[][] getDataValidator() {
    DOMSource ds = getDOMSource(xml_val_test, xml_val_test_id, false, 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 disabled through factory
        {true, false, false, ds, null, null, xml_catalog, null},
        {true, false, false, ds, null, null, null, xml_catalog},
        {true, false, false, ss, null, null, xml_catalog, null},
        {true, false, false, ss, null, null, null, xml_catalog},
        {true, false, false, stax, null, null, xml_catalog, null},
        {true, false, false, stax1, null, null, null, xml_catalog},
        {true, false, false, source, null, null, xml_catalog, null},
        {true, false, false, source, null, null, null, xml_catalog},
        // use catalog disabled through validatory
        {false, true, false, ds, null, null, xml_catalog, null},
        {false, true, false, ds, null, null, null, xml_catalog},
        {false, true, false, ss, null, null, xml_catalog, null},
        {false, true, false, ss, null, null, null, xml_catalog},
        {false, true, false, stax, null, null, xml_catalog, null},
        {false, true, false, stax1, null, null, null, xml_catalog},
        {false, true, false, source, null, null, xml_catalog, null},
        {false, true, false, source, null, null, null, xml_catalog},
    };
}
 
Example 35
Project: openjdk-jdk10   File: CatalogSupport.java   View source code 5 votes vote down vote up
@DataProvider(name = "data_ValidatorA")
public Object[][] getDataValidator() {
    DOMSource ds = getDOMSource(xml_val_test, xml_val_test_id, false, 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));

    String[] systemIds = {"system.dtd", "val_test.xsd"};
    XmlInput[] returnValues = {new XmlInput(null, dtd_system, null), new XmlInput(null, xsd_val_test, null)};
    LSResourceResolver resolver = new SourceResolver(null, systemIds, returnValues);

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

    return new Object[][]{
        // use catalog
        {false, false, true, ds, null, null, xml_catalog, null},
        {false, false, true, ds, null, null, null, xml_catalog},
        {false, false, true, ss, null, null, xml_catalog, null},
        {false, false, true, ss, null, null, null, xml_catalog},
        {false, false, true, stax, null, null, xml_catalog, null},
        {false, false, true, stax1, null, null, null, xml_catalog},
        {false, false, true, source, null, null, xml_catalog, null},
        {false, false, true, source, null, null, null, xml_catalog},
        // use resolver
        {false, false, true, ds, resolver, resolver, xml_bogus_catalog, xml_bogus_catalog},
        {false, false, true, ss, resolver, resolver, xml_bogus_catalog, xml_bogus_catalog},
        {false, false, true, stax2, resolver, resolver, xml_bogus_catalog, xml_bogus_catalog},
        {false, false, true, source, resolver, resolver, xml_bogus_catalog, xml_bogus_catalog}
    };
}
 
Example 36
Project: openjdk-jdk10   File: CatalogSupport1.java   View source code 5 votes vote down vote up
@DataProvider(name = "data_ValidatorC")
public Object[][] getDataValidator() {
    DOMSource ds = getDOMSource(xml_val_test, xml_val_test_id, false, true, null);

    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));

    String[] systemIds = {"system.dtd", "val_test.xsd"};
    XmlInput[] returnValues = {new XmlInput(null, dtd_system, null), new XmlInput(null, xsd_val_test, null)};
    LSResourceResolver resolver = new SourceResolver(null, systemIds, returnValues);

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

    return new Object[][]{
        // use catalog
        {false, false, true, ds, null, null, null, null},
        {false, false, true, ds, null, null, null, null},
        {false, false, true, ss, null, null, null, null},
        {false, false, true, ss, null, null, null, null},
        {false, false, true, stax, null, null, null, null},
        {false, false, true, stax1, null, null, null, null},
        {false, false, true, source, null, null, null, null},
        {false, false, true, source, null, null, null, null},
        // use resolver
        {false, false, true, ds, resolver, resolver, xml_bogus_catalog, xml_bogus_catalog},
        {false, false, true, ss, resolver, resolver, xml_bogus_catalog, xml_bogus_catalog},
        {false, false, true, stax2, resolver, resolver, xml_bogus_catalog, xml_bogus_catalog},
        {false, false, true, source, resolver, resolver, xml_bogus_catalog, xml_bogus_catalog}
    };
}
 
Example 37
Project: openjdk-jdk10   File: TransformTest.java   View source code 5 votes vote down vote up
private StAXSource getStAXEventSource() {
    try {
        return new StAXSource(ifac.createXMLEventReader(xmlInputStream()));
    } catch (XMLStreamException e) {
        throw new WrapperException(e);
    }
}
 
Example 38
Project: openjdk9   File: EnvelopeFactory.java   View source code 5 votes vote down vote up
private static Envelope parseEnvelopeStax(Source src, SOAPPartImpl soapPart)
            throws SOAPException {
        XMLStreamReader streamReader = null;
        if (src instanceof StAXSource) {
           streamReader = ((StAXSource) src).getXMLStreamReader();
        }
        try {
            if (streamReader == null) {
                if (xmlInputFactory == null) xmlInputFactory = XMLInputFactory.newInstance();
                streamReader = xmlInputFactory.createXMLStreamReader(src);
            }
//            SaajStaxWriter saajWriter = new SaajStaxWriter(soapPart.message, soapPart.document);
//            XMLStreamReaderToXMLStreamWriter readerWriterBridge = new XMLStreamReaderToXMLStreamWriter(
//                    streamReader, saajWriter, soapPart.getSOAPNamespace());

            StaxBridge readerWriterBridge = new StaxReaderBridge(streamReader, soapPart);
            //bridge will stop reading at body element, and parse upon request, so save it
            //on the envelope
            readerWriterBridge.bridgeEnvelopeAndHeaders();

            Envelope env = (Envelope) soapPart.getEnvelope();
            env.setStaxBridge(readerWriterBridge);
            return env;
        } catch (Exception e) {
            throw new SOAPException(e);
        }
    }
 
Example 39
Project: openjdk9   File: XMLSchemaFactory.java   View source code 5 votes vote down vote up
public boolean getFeature(String name)
    throws SAXNotRecognizedException, SAXNotSupportedException {
    if (name == null) {
        throw new NullPointerException(JAXPValidationMessageFormatter.formatMessage(fXMLSchemaLoader.getLocale(),
                "FeatureNameNull", null));
    }
    if (name.startsWith(JAXP_SOURCE_FEATURE_PREFIX)) {
        // Indicates to the caller that this SchemaFactory supports a specific JAXP Source.
        if (name.equals(StreamSource.FEATURE) ||
            name.equals(SAXSource.FEATURE) ||
            name.equals(DOMSource.FEATURE) ||
            name.equals(StAXSource.FEATURE)) {
            return true;
        }
    }
    if (name.equals(XMLConstants.FEATURE_SECURE_PROCESSING)) {
        return (fSecurityManager != null && fSecurityManager.isSecureProcessing());
    }
    else if (name.equals(USE_GRAMMAR_POOL_ONLY)) {
        return fUseGrammarPoolOnly;
    }
    try {
        return fXMLSchemaLoader.getFeature(name);
    }
    catch (XMLConfigurationException e) {
        String identifier = e.getIdentifier();
        if (e.getType() == Status.NOT_RECOGNIZED) {
            throw new SAXNotRecognizedException(
                    SAXMessageFormatter.formatMessage(fXMLSchemaLoader.getLocale(),
                    "feature-not-recognized", new Object [] {identifier}));
        }
        else {
            throw new SAXNotSupportedException(
                    SAXMessageFormatter.formatMessage(fXMLSchemaLoader.getLocale(),
                    "feature-not-supported", new Object [] {identifier}));
        }
    }
}
 
Example 40
Project: openjdk9   File: CR6708840Test.java   View source code 5 votes vote down vote up
/**
 * refer to http://forums.java.net/jive/thread.jspa?threadID=41626&tstart=0
 */
@Test
public final void testStAX() {
    try {
        XMLInputFactory xmlif = XMLInputFactory.newInstance();

        // XMLStreamReader staxReader =
        // xmlif.createXMLStreamReader((Source)new
        // StreamSource(getClass().getResource("Forum31576.xml").getFile()));
        XMLStreamReader staxReader = xmlif.createXMLStreamReader(this.getClass().getResourceAsStream("gMonths.xml"));

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schemaGrammar = schemaFactory.newSchema(new File(getClass().getResource("gMonths.xsd").getFile()));

        Validator schemaValidator = schemaGrammar.newValidator();

        Source staxSrc = new StAXSource(staxReader);
        schemaValidator.validate(staxSrc);

        while (staxReader.hasNext()) {
            int eventType = staxReader.next();
            System.out.println("Event of type: " + eventType);
        }
    } catch (NullPointerException ne) {
        Assert.fail("NullPointerException when result is not specified.");
    } catch (Exception e) {
        Assert.fail(e.getMessage());
        e.printStackTrace();
    }
}