org.codehaus.stax2.XMLInputFactory2 Java Examples

The following examples show how to use org.codehaus.stax2.XMLInputFactory2. 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: XmlSource.java    From beam with Apache License 2.0 6 votes vote down vote up
private void setUpXMLParser(ReadableByteChannel channel, byte[] lookAhead) throws IOException {
  try {
    // We use Woodstox because the StAX implementation provided by OpenJDK reports
    // character locations incorrectly. Note that Woodstox still currently reports *byte*
    // locations incorrectly when parsing documents that contain multi-byte characters.
    XMLInputFactory2 xmlInputFactory = (XMLInputFactory2) XMLInputFactory.newInstance();
    this.parser =
        xmlInputFactory.createXMLStreamReader(
            new SequenceInputStream(
                new ByteArrayInputStream(lookAhead), Channels.newInputStream(channel)),
            getCurrentSource().configuration.getCharset());

    // Current offset should be the offset before reading the record element.
    while (true) {
      int event = parser.next();
      if (event == XMLStreamConstants.START_ELEMENT) {
        String localName = parser.getLocalName();
        if (localName.equals(getCurrentSource().configuration.getRecordElement())) {
          break;
        }
      }
    }
  } catch (FactoryConfigurationError | XMLStreamException e) {
    throw new IOException(e);
  }
}
 
Example #2
Source File: TestWsdlValidation.java    From woodstox with Apache License 2.0 6 votes vote down vote up
public void testWsdlValidation() throws Exception {
	String runMe = System.getProperty("testWsdlValidation");
	if (runMe == null || "".equals(runMe)) {
		return;
	}
	XMLInputFactory2 factory = getInputFactory();
	XMLStreamReader2 reader = (XMLStreamReader2) factory.createXMLStreamReader(getClass().getResourceAsStream("test-message.xml"), "utf-8");
	QName msgQName = new QName("http://server.hw.demo/", "sayHi");
	while (true) {
		int what = reader.nextTag();
		if (what == XMLStreamConstants.START_ELEMENT) {
			if (reader.getName().equals(msgQName)) {
				reader.validateAgainst(schema);
			}
		} else if (what == XMLStreamConstants.END_ELEMENT) {
			if (reader.getName().equals(msgQName)) {
				reader.stopValidatingAgainst(schema);
			}
		} else if (what == XMLStreamConstants.END_DOCUMENT) {
			break;
		}
	}
}
 
Example #3
Source File: TestXmlId.java    From woodstox with Apache License 2.0 6 votes vote down vote up
private XMLStreamReader2 getReader(String contents,
                                  boolean xmlidEnabled,
                                  boolean nsAware, boolean coal)
    throws XMLStreamException
{
    XMLInputFactory2 f = getInputFactory();
    setSupportDTD(f, true);
    setValidating(f, false);
    setCoalescing(f, coal);
    setNamespaceAware(f, nsAware);
    f.setProperty(XMLInputFactory2.XSP_SUPPORT_XMLID,
                  xmlidEnabled
                  ? XMLInputFactory2.XSP_V_XMLID_TYPING
                  : XMLInputFactory2.XSP_V_XMLID_NONE);
    return constructStreamReader(f, contents);
}
 
Example #4
Source File: TestCopyEventFromReader97.java    From woodstox with Apache License 2.0 6 votes vote down vote up
public void testUTF8MsLinefeedCopyEvent() throws Exception
{
    final XMLInputFactory2 xmlIn = getInputFactory();
    final XMLOutputFactory2 xmlOut = getOutputFactory();
    InputStream in = getClass().getResource("issue97.xml").openStream();

    ByteArrayOutputStream bogus = new ByteArrayOutputStream();
    XMLStreamReader2 reader = (XMLStreamReader2) xmlIn.createXMLStreamReader(in);
    XMLStreamWriter2 writer = (XMLStreamWriter2) xmlOut.createXMLStreamWriter(bogus, "UTF-8");
    while (reader.hasNext()) {
       reader.next();
       writer.copyEventFromReader(reader, false);
    }

    in.close();
}
 
Example #5
Source File: TestStreamResult.java    From woodstox with Apache License 2.0 6 votes vote down vote up
/**
 * This test is related to problem reported as [WSTX-182], inability
 * to use SystemId alone as source.
 */
public void testCreateUsingSystemId()
    throws IOException, XMLStreamException
{
    File tmpF = File.createTempFile("staxtest", ".xml");
    tmpF.deleteOnExit();

    XMLOutputFactory f = getOutputFactory();
    StreamResult dst = new StreamResult();
    dst.setSystemId(tmpF);
    XMLStreamWriter sw = f.createXMLStreamWriter(dst);

    sw.writeStartDocument();
    sw.writeEmptyElement("root");
    sw.writeEndDocument();
    sw.close();

    // plus let's read and check it
    XMLInputFactory2 inf = getInputFactory();
    XMLStreamReader sr = inf.createXMLStreamReader(tmpF);
    assertTokenType(START_ELEMENT, sr.next());
    assertTokenType(END_ELEMENT, sr.next());
    sr.close();
}
 
Example #6
Source File: PomHelperTest.java    From versions-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Tests what happens when changing a long property substitution pattern, e.g.
 * <a href="http://jira.codehaus.org/browse/MVERSIONS-44">MVERSIONS-44</a>
 *
 * @throws Exception if the test fails.
 */
@Test
public void testLongProperties()
    throws Exception
{
    URL url = getClass().getResource( "PomHelperTest.testLongProperties.pom.xml" );
    File file = new File( url.getPath() );
    StringBuilder input = PomHelper.readXmlFile( file );

    XMLInputFactory inputFactory = XMLInputFactory2.newInstance();
    inputFactory.setProperty( XMLInputFactory2.P_PRESERVE_LOCATION, Boolean.TRUE );

    ModifiedPomXMLEventReader pom = new ModifiedPomXMLEventReader( input, inputFactory, file.getAbsolutePath() );

    String oldVersion = PomHelper.getProjectVersion( pom );

    String newVersion = "1";

    assertTrue( "The pom has been modified", PomHelper.setProjectVersion( pom, newVersion ) );

    assertEquals( newVersion, PomHelper.getProjectVersion( pom ) );

    assertNotSame( oldVersion, newVersion );
}
 
Example #7
Source File: PomHelperTest.java    From versions-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Tests if imported POMs are properly read from dependency management section. Such logic is required to resolve
 * <a href="https://github.com/mojohaus/versions-maven-plugin/issues/134">bug #134</a>
 *
 * @throws Exception if the test fails.
 */
@Test
public void testImportedPOMsRetrievedFromDependencyManagement()
    throws Exception
{
    URL url = getClass().getResource( "PomHelperTest.dependencyManagementBOMs.pom.xml" );
    File file = new File( url.getPath() );
    StringBuilder input = PomHelper.readXmlFile( file );

    XMLInputFactory inputFactory = XMLInputFactory2.newInstance();
    inputFactory.setProperty( XMLInputFactory2.P_PRESERVE_LOCATION, Boolean.TRUE );

    ModifiedPomXMLEventReader pom = new ModifiedPomXMLEventReader( input, inputFactory, file.getAbsolutePath() );

    List<Dependency> dependencies = PomHelper.readImportedPOMsFromDependencyManagementSection( pom );

    assertNotNull( dependencies );
    assertEquals( 1, dependencies.size() );

    Dependency dependency = dependencies.get( 0 );
    assertEquals( "org.group1", dependency.getGroupId() );
    assertEquals( "artifact-pom", dependency.getArtifactId() );
    assertEquals( "1.0-SNAPSHOT", dependency.getVersion() );
    assertEquals( "import", dependency.getScope() );
    assertEquals( "pom", dependency.getType() );
}
 
Example #8
Source File: RewriteWithStAXTest.java    From versions-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasic()
    throws Exception
{
    String input = "<?xml version='1.0' encoding='utf-8'?>\n" + "<project>\n\r\n\r\n\r\n\r" + "  <parent>\r\n"
        + "    <groupId xmlns='foo'>org.codehaus.mojo</groupId>\n"
        + "    <artifactId>mojo-&amp;sandbox-parent</artifactId>\n" + "    <version>5-SNAPSHOT</version>\r"
        + "  </parent>\r" + "<build/></project>";

    byte[] rawInput = input.getBytes( "utf-8" );
    ByteArrayInputStream source = new ByteArrayInputStream( rawInput );
    ByteArrayOutputStream dest = new ByteArrayOutputStream();
    XMLInputFactory inputFactory = XMLInputFactory2.newInstance();
    inputFactory.setProperty( XMLInputFactory2.P_PRESERVE_LOCATION, Boolean.TRUE );
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    XMLEventReader eventReader = inputFactory.createXMLEventReader( source );
    XMLEventWriter eventWriter = outputFactory.createXMLEventWriter( dest, "utf-8" );
    while ( eventReader.hasNext() )
    {
        eventWriter.add( eventReader.nextEvent() );
    }

    String output = new String( dest.toByteArray(), "utf-8" );

    assertFalse( "StAX implementation is not good enough", input.equals( output ) );
}
 
Example #9
Source File: XmlDumpParser.java    From wikiforia with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor used by Multistream parser
 * @param header   parsed header
 * @param xmlInput parallel input stream
 */
public XmlDumpParser(Header header, InputStream xmlInput) {
    try {
        this.header = header;

        XMLInputFactory2 factory = (XMLInputFactory2) XMLInputFactory2.newInstance();
        factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
        factory.setProperty(WstxInputProperties.P_INPUT_PARSING_MODE, WstxInputProperties.PARSING_MODE_FRAGMENT);

        xmlReader = (XMLStreamReader2)factory.createXMLStreamReader(xmlInput);

    } catch (XMLStreamException e) {
        throw new IOError(e);
    }
}
 
Example #10
Source File: XmlDumpParser.java    From wikiforia with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Standalone constructor
 * @param xmlInput the stream to read from
 */
public XmlDumpParser(InputStream xmlInput) {
    try {
        XMLInputFactory2 factory = (XMLInputFactory2) XMLInputFactory2.newInstance();
        factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
        factory.setProperty(WstxInputProperties.P_INPUT_PARSING_MODE, WstxInputProperties.PARSING_MODE_FRAGMENT);

        xmlReader = (XMLStreamReader2) factory.createXMLStreamReader(xmlInput);
        this.header = readHeader(xmlReader);
    } catch (XMLStreamException e) {
        throw new IOError(e);
    }
}
 
Example #11
Source File: MultistreamBzip2XmlDumpParser.java    From wikiforia with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Header parsing code
 * @param xml the header xml
 * @return true if match
 * @throws javax.xml.stream.XMLStreamException
 */
public static Header parseHeader(String xml) throws XMLStreamException
{
    XMLInputFactory2 factory = (XMLInputFactory2) XMLInputFactory2.newInstance();
    factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
    BufferedReader buffreader = new BufferedReader(new StringReader(xml));

    XMLStreamReader2 xmlReader = (XMLStreamReader2)factory.createXMLStreamReader(buffreader);
    return XmlDumpParser.readHeader(xmlReader);
}
 
Example #12
Source File: TestAllowXml11EscapedCharsInXml10.java    From woodstox with Apache License 2.0 5 votes vote down vote up
/**
 * Unit test to verify workaround for XML 1.1 escaped chars in XML 1.0 file.
 */
public void testAllowXml11EscapedCharsInXml10() throws Exception {
    XMLInputFactory2 f = getInputFactory();
    setNamespaceAware(f, true);
    setCoalescing(f, true);
    f.setProperty(WstxInputProperties.P_ALLOW_XML11_ESCAPED_CHARS_IN_XML10, true);
    XMLStreamReader sr = constructStreamReader(f, "<?xml version=\"1.0\" encoding=\"utf-8\"?><root>&#x2;</root>");
    assertTokenType(START_ELEMENT, sr.next());
    assertTokenType(CHARACTERS, sr.next());
    assertTokenType(END_ELEMENT, sr.next());
}
 
Example #13
Source File: TestAllowXml11EscapedCharsInXml10.java    From woodstox with Apache License 2.0 5 votes vote down vote up
/**
 * Unit test to verify failure for XML 1.1 escaped chars in XML 1.0 file.
 */
public void testDoNotAllowXml11EscapedCharsInXml10() throws Exception {
    XMLInputFactory2 f = getInputFactory();
    setNamespaceAware(f, true);
    setCoalescing(f, true);
    XMLStreamReader sr = constructStreamReader(f, "<?xml version=\"1.0\" encoding=\"utf-8\"?><root>&#x2;</root>");
    assertTokenType(START_ELEMENT, sr.next());
    try {
        assertTokenType(CHARACTERS, sr.next());
        fail("Should fail");
    } catch (WstxParsingException e) {
        // success
    }
    assertTokenType(END_ELEMENT, sr.next());
}
 
Example #14
Source File: TestReaderWithDTD.java    From woodstox with Apache License 2.0 5 votes vote down vote up
private XMLStreamReader2 getReader(String contents, boolean nsAware)
    throws XMLStreamException
{
    XMLInputFactory2 f = getInputFactory();
    setCoalescing(f, true);
    setSupportDTD(f, true);
    setNamespaceAware(f, nsAware);
    setValidating(f, false);
    return constructStreamReader(f, contents);
}
 
Example #15
Source File: RewriteWithStAXTest.java    From versions-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testReplace()
    throws Exception
{
    String input = "<?xml version='1.0' encoding='utf-8'?>\n" + "<project>\n\r\n\r\n\r\n\r" + "  <parent>\r\n"
        + "    <groupId xmlns='foo'>org.codehaus.mojo</groupId>\n"
        + "    <artifactId>mojo-&amp;sandbox-parent</artifactId>\n" + "    <version>5-SNAPSHOT</version>\r"
        + "  </parent>\r" + "<build/></project>";
    String expected = "<?xml version='1.0' encoding='utf-8'?>\n" + "<project>\n\r\n\r\n\r\n\r" + "  <parent>\r\n"
        + "    <groupId xmlns='foo'>org.codehaus.mojo</groupId>\n" + "    <artifactId>my-artifact</artifactId>\n"
        + "    <version>5-SNAPSHOT</version>\r" + "  </parent>\r" + "<build/></project>";

    StringBuilder output = new StringBuilder( input );

    XMLInputFactory inputFactory = XMLInputFactory2.newInstance();
    inputFactory.setProperty( XMLInputFactory2.P_PRESERVE_LOCATION, Boolean.TRUE );
    ModifiedPomXMLEventReader eventReader = new ModifiedPomXMLEventReader( output, inputFactory, null );
    while ( eventReader.hasNext() )
    {
        XMLEvent event = eventReader.nextEvent();
        if ( event instanceof StartElement
            && event.asStartElement().getName().getLocalPart().equals( "artifactId" ) )
        {
            eventReader.mark( 0 );
        }
        if ( event instanceof EndElement && event.asEndElement().getName().getLocalPart().equals( "artifactId" ) )
        {
            eventReader.mark( 1 );
            if ( eventReader.hasMark( 0 ) )
            {
                eventReader.replaceBetween( 0, 1, "my-artifact" );
            }
        }
    }

    assertEquals( expected, output.toString() );
}
 
Example #16
Source File: TestXmlId.java    From woodstox with Apache License 2.0 5 votes vote down vote up
private XMLStreamReader2 getValidatingReader(String contents,
                                            boolean nsAware, boolean coal)
    throws XMLStreamException
{
    XMLInputFactory2 f = getInputFactory();
    setSupportDTD(f, true);
    setValidating(f, true);
    setCoalescing(f, coal);
    setNamespaceAware(f, nsAware);
    f.setProperty(XMLInputFactory2.XSP_SUPPORT_XMLID,
                  XMLInputFactory2.XSP_V_XMLID_TYPING);
    return constructStreamReader(f, contents);
}
 
Example #17
Source File: TestW3CSchemaComplexTypes.java    From woodstox with Apache License 2.0 4 votes vote down vote up
XMLStreamReader2 getReader(String contents) throws XMLStreamException
{
    XMLInputFactory2 f = getInputFactory();
    setValidating(f, false);
    return constructStreamReader(f, contents);
}
 
Example #18
Source File: POM.java    From pomutils with Apache License 2.0 4 votes vote down vote up
private static XMLInputFactory initializeXmlInputFactory()
        throws FactoryConfigurationError {
	XMLInputFactory inputFactory = new WstxInputFactory();
	inputFactory.setProperty(XMLInputFactory2.P_PRESERVE_LOCATION, Boolean.TRUE);
	return inputFactory;
}
 
Example #19
Source File: InputFactoryProviderImpl.java    From woodstox with Apache License 2.0 4 votes vote down vote up
@Override
public XMLInputFactory2 createInputFactory() {
    return new WstxInputFactory();
}
 
Example #20
Source File: XMLEventReaderFactory.java    From tidy-maven-plugin with Apache License 2.0 4 votes vote down vote up
private static XMLInputFactory createInputFactory()
{
    XMLInputFactory inputFactory = XMLInputFactory2.newInstance();
    inputFactory.setProperty( XMLInputFactory2.P_PRESERVE_LOCATION, true );
    return inputFactory;
}