Java Code Examples for javax.xml.stream.XMLInputFactory#createXMLEventReader()

The following examples show how to use javax.xml.stream.XMLInputFactory#createXMLEventReader() . 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: XmlRecordSource.java    From nifi with Apache License 2.0 6 votes vote down vote up
public XmlRecordSource(final InputStream in, final boolean ignoreWrapper) throws IOException {
    try {
        final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();

        // Avoid XXE Vulnerabilities
        xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        xmlInputFactory.setProperty("javax.xml.stream.isSupportingExternalEntities", false);

        xmlEventReader = xmlInputFactory.createXMLEventReader(in);

        if (ignoreWrapper) {
            readStartElement();
        }
    } catch (XMLStreamException e) {
        throw new IOException("Could not parse XML", e);
    }
}
 
Example 2
Source File: XmlTransformer.java    From recheck with GNU Affero General Public License v3.0 6 votes vote down vote up
private void convertAndWriteToFile( final InputStream inputStream, final File tmpFile ) throws IOException {
	try ( final LZ4BlockOutputStream out = new LZ4BlockOutputStream( new FileOutputStream( tmpFile ) ) ) {
		reset();

		final XMLInputFactory inputFactory = XMLInputFactory.newInstance();
		inputFactory.setProperty( XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE );
		final XMLEventReader eventReader =
				inputFactory.createXMLEventReader( inputStream, StandardCharsets.UTF_8.name() );
		final XMLEventWriter eventWriter =
				XMLOutputFactory.newInstance().createXMLEventWriter( out, StandardCharsets.UTF_8.name() );

		while ( eventReader.hasNext() ) {
			final XMLEvent nextEvent = eventReader.nextEvent();
			convert( nextEvent, eventWriter );
		}
		eventReader.close();
		eventWriter.flush();
		eventWriter.close();

	} catch ( final XMLStreamException | FactoryConfigurationError e ) {
		throw new RuntimeException( e );
	}
}
 
Example 3
Source File: JAXBEncoderDecoderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testMarshallIntoStaxStreamWriter() throws Exception {
    GreetMe obj = new GreetMe();
    obj.setRequestType("Hello");
    QName elName = new QName(wrapperAnnotation.targetNamespace(),
                             wrapperAnnotation.localName());
    MessagePartInfo part = new MessagePartInfo(elName, null);
    part.setElement(true);
    part.setElementQName(elName);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLOutputFactory opFactory = XMLOutputFactory.newInstance();
    opFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
    FixNamespacesXMLStreamWriter writer = new FixNamespacesXMLStreamWriter(opFactory.createXMLStreamWriter(baos));

    assertNull(writer.getMarshaller());

    Marshaller m = context.createMarshaller();
    JAXBEncoderDecoder.marshall(m, obj, part, writer);
    assertEquals(m, writer.getMarshaller());
    writer.flush();
    writer.close();

    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    XMLInputFactory ipFactory = XMLInputFactory.newInstance();
    XMLEventReader reader = ipFactory.createXMLEventReader(bais);

    Unmarshaller um = context.createUnmarshaller();
    Object val = um.unmarshal(reader, GreetMe.class);
    assertTrue(val instanceof JAXBElement);
    val = ((JAXBElement<?>)val).getValue();
    assertTrue(val instanceof GreetMe);
    assertEquals(obj.getRequestType(),
                 ((GreetMe)val).getRequestType());
}
 
Example 4
Source File: Bug6489890.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test1() {
    try {
        XMLInputFactory xif = XMLInputFactory.newInstance();

        XMLStreamReader xsr = xif.createXMLStreamReader(getClass().getResource("sgml.xml").toString(), getClass().getResourceAsStream("sgml.xml"));

        XMLEventReader xer = xif.createXMLEventReader(xsr);

        Assert.assertTrue(xer.nextEvent().getEventType() == XMLEvent.START_DOCUMENT);
        xsr.close();
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }
}
 
Example 5
Source File: SkipDTDTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void runReader(XMLInputFactory factory, int offset) throws XMLStreamException {
    StringReader stringReader = new StringReader(createXMLDocument(offset));
    XMLEventReader reader = factory.createXMLEventReader(stringReader);

    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();
        System.out.println("Event Type: " + event.getEventType());
    }
}
 
Example 6
Source File: SkipDTDTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void runReader(XMLInputFactory factory, int offset) throws XMLStreamException {
    StringReader stringReader = new StringReader(createXMLDocument(offset));
    XMLEventReader reader = factory.createXMLEventReader(stringReader);

    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();
        System.out.println("Event Type: " + event.getEventType());
    }
}
 
Example 7
Source File: MetadataParser.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
protected SchemaBasedEdmProvider buildEdmProvider(InputStream csdl, ReferenceResolver resolver,
                                                  boolean loadCore, boolean useLocal,
                                                  boolean loadReferenceSchemas, String namespace)
        throws XMLStreamException {
  XMLInputFactory xmlInputFactory = createXmlInputFactory();
  XMLEventReader reader = xmlInputFactory.createXMLEventReader(csdl);
  return buildEdmProvider(reader, resolver, loadCore, useLocal, loadReferenceSchemas, namespace);
}
 
Example 8
Source File: XML11Test.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test() {
    try {
        XMLInputFactory xif = XMLInputFactory.newInstance();
        XMLEventReader reader = xif.createXMLEventReader(this.getClass().getResourceAsStream("xml11.xml.data"));
        while (reader.hasNext())
            reader.next();

    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail(e.toString());
    }
}
 
Example 9
Source File: StaxCompare.java    From tomee with Apache License 2.0 5 votes vote down vote up
public static void compare(final String a, final String b) throws Exception {
    final StringBuilder message = new StringBuilder();
    final XMLInputFactory factory = XMLInputFactory.newInstance();
    factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
    final XMLEventReader rA = factory.createXMLEventReader(new StringReader(a));
    final XMLEventReader rB = factory.createXMLEventReader(new StringReader(b));
    if (!compare(rA, rB, message)) {
        throw new Exception(message.toString());
    }
}
 
Example 10
Source File: Xml.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
private static XMLEventReader xmlEventReader(Reader reader) {
    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        factory.setProperty(XMLInputFactory.IS_COALESCING, true);
        factory.setProperty(XMLInputFactory.IS_VALIDATING, false);
        factory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true); // so we can ignore them!
        factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
        factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
        factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        return factory.createXMLEventReader(reader);
    } catch (XMLStreamException e) {
        throw lazyException(e);
    }
}
 
Example 11
Source File: StaxEventXMLReaderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void partial() throws Exception {
	XMLInputFactory inputFactory = XMLInputFactory.newInstance();
	XMLEventReader eventReader = inputFactory.createXMLEventReader(new StringReader(CONTENT));
	eventReader.nextTag();  // skip to root
	StaxEventXMLReader xmlReader = new StaxEventXMLReader(eventReader);
	ContentHandler contentHandler = mock(ContentHandler.class);
	xmlReader.setContentHandler(contentHandler);
	xmlReader.parse(new InputSource());
	verify(contentHandler).startDocument();
	verify(contentHandler).startElement(eq("http://springframework.org/spring-ws"), eq("child"), eq("child"), any(Attributes.class));
	verify(contentHandler).endElement("http://springframework.org/spring-ws", "child", "child");
	verify(contentHandler).endDocument();
}
 
Example 12
Source File: JAXBEncoderDecoderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testMarshallIntoStaxEventWriter() throws Exception {
    GreetMe obj = new GreetMe();
    obj.setRequestType("Hello");
    QName elName = new QName(wrapperAnnotation.targetNamespace(),
                             wrapperAnnotation.localName());
    MessagePartInfo part = new MessagePartInfo(elName, null);
    part.setElement(true);
    part.setElementQName(elName);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLOutputFactory opFactory = XMLOutputFactory.newInstance();
    opFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
    FixNamespacesXMLEventWriter writer = new FixNamespacesXMLEventWriter(opFactory.createXMLEventWriter(baos));
    assertNull(writer.getMarshaller());

    //STARTDOCUMENT/ENDDOCUMENT is not required
    //writer.add(eFactory.createStartDocument("utf-8", "1.0"));
    Marshaller m = context.createMarshaller();
    JAXBEncoderDecoder.marshall(m, obj, part, writer);
    assertEquals(m, writer.getMarshaller());
    //writer.add(eFactory.createEndDocument());
    writer.flush();
    writer.close();

    //System.out.println(baos.toString());

    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    XMLInputFactory ipFactory = XMLInputFactory.newInstance();
    XMLEventReader reader = ipFactory.createXMLEventReader(bais);

    Unmarshaller um = context.createUnmarshaller();
    Object val = um.unmarshal(reader, GreetMe.class);
    assertTrue(val instanceof JAXBElement);
    val = ((JAXBElement<?>)val).getValue();
    assertTrue(val instanceof GreetMe);
    assertEquals(obj.getRequestType(),
                 ((GreetMe)val).getRequestType());
}
 
Example 13
Source File: XmlHandler.java    From appengine-gcs-client with Apache License 2.0 5 votes vote down vote up
XmlHandler(byte[] content, Set<? extends Iterable<String>> paths)
    throws XMLStreamException {
  prefixTrie = new PathTrie(paths);
  Reader reader = new InputStreamReader(new ByteArrayInputStream(content), UTF_8);
  XMLInputFactory f = XMLInputFactory.newInstance();
  xmlr = f.createXMLEventReader(reader);
}
 
Example 14
Source File: PubchemParserTest.java    From act with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testParserProcessesTheCorrectChemicals() throws Exception {
  File testFile = new File(this.getClass().getResource("CompoundTest.xml.gz").getFile());

  String expectedInchi1 = "InChI=1S/C18H27FN2/c1-2-14-11-17(20-16-5-3-4-6-16)13-21(12-14)18-9-7-15(19)8-10-18/h7-10,14,16-17,20H,2-6,11-13H2,1H3";
  String expectedSmiles1 = "CCC1CC(CN(C1)C2=CC=C(C=C2)F)NC3CCCC3";
  String expectedCanonicalName1 = "N-cyclopentyl-5-ethyl-1-(4-fluorophenyl)piperidin-3-amine";
  Long expectedPubchemId1 = 84000001L;

  Chemical testChemical1 = new Chemical(1L, expectedPubchemId1, expectedCanonicalName1, expectedSmiles1);
  testChemical1.setInchi(expectedInchi1);

  String expectedInchi2 = "InChI=1S/C16H23FN2/c17-13-5-3-9-16(11-13)19-10-4-8-15(12-19)18-14-6-1-2-7-14/h3,5,9,11,14-15,18H,1-2,4,6-8,10,12H2";
  String expectedSmiles2 = "C1CCC(C1)NC2CCCN(C2)C3=CC(=CC=C3)F";
  String expectedCanonicalName2 = "N-cyclopentyl-1-(3-fluorophenyl)piperidin-3-amine";
  Long expectedPubchemId2 = 84000002L;

  Chemical testChemical2 = new Chemical(2L, expectedPubchemId2, expectedCanonicalName2, expectedSmiles2);
  testChemical2.setInchi(expectedInchi2);

  List<Chemical> expectedChemicals = new ArrayList<>();
  expectedChemicals.add(testChemical1);
  expectedChemicals.add(testChemical2);

  XMLInputFactory factory = XMLInputFactory.newInstance();
  XMLEventReader eventReader = factory.createXMLEventReader(new GZIPInputStream(new FileInputStream(testFile)));

  int counter = 0;
  Chemical actualChemical;
  while ((actualChemical = pubchemParser.extractNextChemicalFromXMLStream(eventReader)) != null) {
    Chemical expectedChemical = expectedChemicals.get(counter);
    assertEquals("Inchis parsed from the xml file should be the same as expected", expectedChemical.getInChI(), actualChemical.getInChI());
    assertEquals("Canonical name parsed from the xml file should be the same as expected", expectedChemical.getCanon(), actualChemical.getCanon());
    assertEquals("Smiles parsed from the xml file should be the same as expected", expectedChemical.getSmiles(), actualChemical.getSmiles());
    assertEquals("Pubchem id parsed from the xml file should be the same as expected", expectedChemical.getPubchemID(), actualChemical.getPubchemID());
    counter++;
  }

  assertEquals("Two chemicals should be parsed from the xml file", 2, counter);
}
 
Example 15
Source File: StaxParser.java    From tutorials with MIT License 4 votes vote down vote up
public List<Tutorial> getAllTutorial() {
    boolean bTitle = false;
    boolean bDescription = false;
    boolean bDate = false;
    boolean bAuthor = false;
    List<Tutorial> tutorials = new ArrayList<Tutorial>();
    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLEventReader eventReader = factory.createXMLEventReader(new FileReader(this.getFile()));
        Tutorial current = null;
        while (eventReader.hasNext()) {
            XMLEvent event = eventReader.nextEvent();
            switch (event.getEventType()) {
            case XMLStreamConstants.START_ELEMENT:
                StartElement startElement = event.asStartElement();
                String qName = startElement.getName().getLocalPart();
                if (qName.equalsIgnoreCase("tutorial")) {
                    current = new Tutorial();
                    Iterator<Attribute> attributes = startElement.getAttributes();
                    while (attributes.hasNext()) {
                        Attribute currentAt = attributes.next();
                        if (currentAt.getName().toString().equalsIgnoreCase("tutId")) {
                            current.setTutId(currentAt.getValue());
                        } else if (currentAt.getName().toString().equalsIgnoreCase("type")) {
                            current.setType(currentAt.getValue());
                        }
                    }
                } else if (qName.equalsIgnoreCase("title")) {
                    bTitle = true;
                } else if (qName.equalsIgnoreCase("description")) {
                    bDescription = true;
                } else if (qName.equalsIgnoreCase("date")) {
                    bDate = true;
                } else if (qName.equalsIgnoreCase("author")) {
                    bAuthor = true;
                }
                break;
            case XMLStreamConstants.CHARACTERS:
                Characters characters = event.asCharacters();
                if (bTitle) {
                    if (current != null) {
                        current.setTitle(characters.getData());
                    }
                    bTitle = false;
                }
                if (bDescription) {
                    if (current != null) {
                        current.setDescription(characters.getData());
                    }
                    bDescription = false;
                }
                if (bDate) {
                    if (current != null) {
                        current.setDate(characters.getData());
                    }
                    bDate = false;
                }
                if (bAuthor) {
                    if (current != null) {
                        current.setAuthor(characters.getData());
                    }
                    bAuthor = false;
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                EndElement endElement = event.asEndElement();
                if (endElement.getName().getLocalPart().equalsIgnoreCase("tutorial")) {
                    if (current != null) {
                        tutorials.add(current);
                    }
                }
                break;
            }
        }

    } catch (FileNotFoundException | XMLStreamException e) {
        e.printStackTrace();
    }

    return tutorials;
}
 
Example 16
Source File: SpeedTestUtils.java    From drftpd with GNU General Public License v2.0 4 votes vote down vote up
private static HashSet<SpeedTestServer> parseXML(String xmlString) throws UnsupportedEncodingException, XMLStreamException {
    HashSet<SpeedTestServer> serverList = new HashSet<>();
    XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(new ByteArrayInputStream(xmlString.getBytes(StandardCharsets.UTF_8)));
    while (xmlEventReader.hasNext()) {
        //Get next event.
        XMLEvent xmlEvent = xmlEventReader.nextEvent();
        //Check if event is the start element.
        if (xmlEvent.isStartElement()) {
            //Get event as start element.
            StartElement startElement = xmlEvent.asStartElement();
            if (startElement.getName().getLocalPart().equals("server")) {
                SpeedTestServer server = new SpeedTestServer();
                //Iterate and process attributes.
                Iterator iterator = startElement.getAttributes();
                while (iterator.hasNext()) {
                    Attribute attribute = (Attribute) iterator.next();
                    String name = attribute.getName().getLocalPart();
                    String value = attribute.getValue();
                    switch (name) {
                        case "url":
                            server.setUrl(value);
                            break;
                        case "url2":
                            server.setUrl2(value);
                            break;
                        case "lat":
                            server.setLatitude(Double.parseDouble(value));
                            break;
                        case "lon":
                            server.setLongitude(Double.parseDouble(value));
                            break;
                        case "name":
                            server.setName(value);
                            break;
                        case "country":
                            server.setCountry(value);
                            break;
                        case "cc":
                            server.setCc(value);
                            break;
                        case "sponsor":
                            server.setSponsor(value);
                            break;
                        case "id":
                            server.setId(Integer.parseInt(value));
                            break;
                        case "host":
                            server.setHost(value);
                            break;
                    }
                }
                serverList.add(server);
            }
        }
    }
    return serverList;
}
 
Example 17
Source File: Parser.java    From Raccoon with Apache License 2.0 4 votes vote down vote up
public Feed readFeed() {
  Feed feed = null;
  try {
    boolean isFeedHeader = true;
    // Set header values intial to the empty string
    String description = "";
    String title = "";
    String link = "";
    String language = "";
    String copyright = "";
    String author = "";
    String pubdate = "";
    String guid = "";

    // First create a new XMLInputFactory
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    // Setup a new eventReader
    InputStream in = read();
    XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
    // read the XML document
    while (eventReader.hasNext()) {
      XMLEvent event = eventReader.nextEvent();
      if (event.isStartElement()) {
        String localPart = event.asStartElement().getName()
            .getLocalPart();
        if (localPart.equals(ITEM)) {
          if (isFeedHeader) {
            isFeedHeader = false;
            feed = new Feed(title, link, description, language,
                copyright, pubdate);
          }
          event = eventReader.nextEvent();
        }
        if (localPart.equals(TITLE)) {
          title = getCharacterData(event, eventReader);
        }
        if (localPart.equals(DESCRIPTION)) {
          description = getCharacterData(event, eventReader);
        }
        if (localPart.equals(LINK)) {
          link = getCharacterData(event, eventReader);
        }
        if (localPart.equals(GUID)) {
          guid = getCharacterData(event, eventReader);
        }
        if (localPart.equals(LANGUAGE)) {
          language = getCharacterData(event, eventReader);
        }
        if (localPart.equals(AUTHOR)) {
          author = getCharacterData(event, eventReader);
        }
        if (localPart.equals(PUB_DATE)) {
          pubdate = getCharacterData(event, eventReader);
        }
        if (localPart.equals(COPYRIGHT)) {
          copyright = getCharacterData(event, eventReader);
        }
      } else if (event.isEndElement()) {
        if (event.asEndElement().getName().getLocalPart() == (ITEM)) {
          Message message = new Message();
          message.setAuthor(author);
          message.setDescription(description);
          message.setGuid(guid);
          message.setLink(link);
          message.setTitle(title);
          feed.getMessages().add(message);
          event = eventReader.nextEvent();
          continue;
        }
      }
    }
  } catch (XMLStreamException e) {
    throw new RuntimeException(e);
  }
  return feed;
}
 
Example 18
Source File: IssueTracker38.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private void createEventReaderFromSource(Source source) throws Exception {
    XMLInputFactory xIF = XMLInputFactory.newInstance();
    xIF.createXMLEventReader(source);
}
 
Example 19
Source File: Metadata.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
public Metadata(final InputStream is) {
  DEF_NS = Constants.get(ConstantKey.EDM_NS);
  schemas = new HashMap<String, Schema>();

  try {
    final XMLInputFactory ifactory = XMLInputFactory.newInstance();
    ifactory.setProperty(SUPPORT_DTD, false);
    ifactory.setProperty(IS_SUPPORTING_EXTERNAL_ENTITIES, false);
    final XMLEventReader reader = ifactory.createXMLEventReader(is, org.apache.olingo.commons.api.Constants.UTF8);

    try {
      while (reader.hasNext()) {
        final XMLEvent event = reader.nextEvent();

        if (event.isStartElement() && event.asStartElement().getName().equals(new QName(DEF_NS, "Schema"))) {
          final Schema schema = getSchema(event.asStartElement(), reader);
          schemas.put(schema.getNamespace(), schema);
        }
      }

    } catch (Exception ignore) {
      // ignore
    } finally {
      reader.close();
      IOUtils.closeQuietly(is);
    }
  } catch (Exception e) {
    LOG.error("Error parsing metadata", e);
  }

  for (Map.Entry<String, Schema> schemaEntry : schemas.entrySet()) {
    for (EntityType entityType : schemaEntry.getValue().getEntityTypes()) {
      for (NavigationProperty property : entityType.getNavigationProperties()) {
        property.setFeed(property.getType().startsWith("Collection("));

        final Collection<EntitySet> entitySets = schemaEntry.getValue().getContainers().iterator().next().
            getEntitySets(schemaEntry.getKey(), entityType.getName());

        final Iterator<EntitySet> iter = entitySets.iterator();
        boolean found = false;

        while (!found && iter.hasNext()) {
          final EntitySet entitySet = iter.next();
          final String target = entitySet.getTarget(property.getName());
          if (StringUtils.isNotBlank(target)) {
            property.setTarget(entitySet.getTarget(property.getName()));
            found = true;
          }
        }
      }
    }
  }
}
 
Example 20
Source File: EwsXmlReader.java    From ews-java-api with MIT License 3 votes vote down vote up
/**
 * Initializes the XML reader.
 *
 * @param stream the stream
 * @return An XML reader to use.
 * @throws Exception on error
 */
protected XMLEventReader initializeXmlReader(InputStream stream) throws Exception {
  XMLInputFactory inputFactory = XMLInputFactory.newInstance();
  inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);

  return inputFactory.createXMLEventReader(stream);
}