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

The following examples show how to use javax.xml.stream.XMLInputFactory#createXMLStreamReader() . 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: DefaultProcessValidatorTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Test
public void testWarningError() throws UnsupportedEncodingException, XMLStreamException {
    String flowWithoutConditionNoDefaultFlow = "<?xml version='1.0' encoding='UTF-8'?>"
            + "<definitions id='definitions' xmlns='http://www.omg.org/spec/BPMN/20100524/MODEL' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:activiti='http://activiti.org/bpmn' targetNamespace='Examples'>"
            + "  <process id='exclusiveGwDefaultSequenceFlow'> " + "    <startEvent id='theStart' /> "
            + "    <sequenceFlow id='flow1' sourceRef='theStart' targetRef='exclusiveGw' /> "
            + "    <exclusiveGateway id='exclusiveGw' name='Exclusive Gateway' /> "
            // no default = "flow3" !!
            + "    <sequenceFlow id='flow2' sourceRef='exclusiveGw' targetRef='theTask1'> "
            + "      <conditionExpression xsi:type='tFormalExpression'>${input == 1}</conditionExpression> "
            + "    </sequenceFlow> " + "    <sequenceFlow id='flow3' sourceRef='exclusiveGw' targetRef='theTask2'/> "
            // one would be OK
            + "    <sequenceFlow id='flow4' sourceRef='exclusiveGw' targetRef='theTask2'/> "
            // but two unconditional not!
            + "    <userTask id='theTask1' name='Input is one' /> " + "    <userTask id='theTask2' name='Default input' /> " + "  </process>"
            + "</definitions>";

    XMLInputFactory xif = XMLInputFactory.newInstance();
    InputStreamReader in = new InputStreamReader(new ByteArrayInputStream(flowWithoutConditionNoDefaultFlow.getBytes()), StandardCharsets.UTF_8);
    XMLStreamReader xtr = xif.createXMLStreamReader(in);
    BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr);
    assertThat(bpmnModel).isNotNull();
    List<ValidationError> allErrors = processValidator.validate(bpmnModel);
    assertThat(allErrors).hasSize(1);
    assertThat(allErrors.get(0).isWarning()).isTrue();
}
 
Example 2
Source File: NamespaceTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testRootElementNamespace() {
    try {
        XMLInputFactory xif = XMLInputFactory.newInstance();
        xif.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        InputStream is = new java.io.ByteArrayInputStream(getXML().getBytes());
        XMLStreamReader sr = xif.createXMLStreamReader(is);
        while (sr.hasNext()) {
            int eventType = sr.next();
            if (eventType == XMLStreamConstants.START_ELEMENT) {
                if (sr.getLocalName().equals(rootElement)) {
                    Assert.assertTrue(sr.getNamespacePrefix(0).equals(prefix) && sr.getNamespaceURI(0).equals(namespaceURI));
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
Example 3
Source File: StaxBasedConfigParser.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private XMLStreamReader getXMLStreamReader(InputStream is) 
{
   XMLInputFactory xmlInputFactory = null;
   XMLStreamReader xmlStreamReader = null;
   try 
   {
     xmlInputFactory = XMLInputFactory.newInstance();
     xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
     xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
     xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
     xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
 
     xmlStreamReader = xmlInputFactory.createXMLStreamReader(is);
   } 
   catch (Exception ex) 
   {
     throw new RuntimeException(ex);
   }
   return xmlStreamReader;
 }
 
Example 4
Source File: NamespaceTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testNamespaceCount() {
    try {
        XMLInputFactory xif = XMLInputFactory.newInstance();
        xif.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        InputStream is = new java.io.ByteArrayInputStream(getXML().getBytes());
        XMLStreamReader sr = xif.createXMLStreamReader(is);
        while (sr.hasNext()) {
            int eventType = sr.next();
            if (eventType == XMLStreamConstants.START_ELEMENT) {
                if (sr.getLocalName().equals(rootElement)) {
                    int count = sr.getNamespaceCount();
                    Assert.assertTrue(count == 1);
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
Example 5
Source File: StaxUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static XMLStreamReader createXMLStreamReader(String systemId, InputStream in) {
    XMLInputFactory factory = getXMLInputFactory();
    try {
        return factory.createXMLStreamReader(systemId, in);
    } catch (XMLStreamException e) {
        throw new RuntimeException("Couldn't parse stream.", e);
    } finally {
        returnXMLInputFactory(factory);
    }
}
 
Example 6
Source File: CFLintAnalysisResultImporter.java    From sonar-coldfusion with Apache License 2.0 5 votes vote down vote up
private void parse(FileReader reader) throws XMLStreamException {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
    factory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
    stream = factory.createXMLStreamReader(reader);

    parse();
}
 
Example 7
Source File: SurrogatesTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private void readXML(byte[] xmlData, String expectedContent)
        throws Exception {
    InputStream stream = new ByteArrayInputStream(xmlData);
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader xmlReader
            = factory.createXMLStreamReader(stream);
    boolean inTestElement = false;
    StringBuilder sb = new StringBuilder();
    while (xmlReader.hasNext()) {
        String ename;
        switch (xmlReader.getEventType()) {
            case XMLStreamConstants.START_ELEMENT:
                ename = xmlReader.getLocalName();
                if (ename.equals("writeCharactersWithString")
                        || ename.equals("writeCharactersWithArray")) {
                    inTestElement = true;
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                ename = xmlReader.getLocalName();
                if (ename.equals("writeCharactersWithString")
                        || ename.equals("writeCharactersWithArray")) {
                    inTestElement = false;
                    String content = sb.toString();
                    System.out.println(ename + " text:'" + content + "' expected:'" + expectedContent+"'");
                    Assert.assertEquals(content, expectedContent);
                    sb.setLength(0);
                }
                break;
            case XMLStreamConstants.CHARACTERS:
                if (inTestElement) {
                    sb.append(xmlReader.getText());
                }
                break;
        }
        xmlReader.next();
    }
}
 
Example 8
Source File: StaxPoiSheet.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private void resetSheetReader() throws IOException, XMLStreamException, InvalidFormatException {
  sheetReader.close();
  sheetStream.close();
  sheetStream = xssfReader.getSheet( sheetId );
  XMLInputFactory factory = XMLParserFactoryProducer.createSecureXMLInputFactory();
  sheetReader = factory.createXMLStreamReader( sheetStream );
}
 
Example 9
Source File: SubProcessMultiDiagramConverterTest.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@Override
protected BpmnModel readXMLFile() throws Exception {
  InputStream xmlStream = this.getClass().getClassLoader().getResourceAsStream(getResource());
  XMLInputFactory xif = XMLInputFactory.newInstance();
  InputStreamReader in = new InputStreamReader(xmlStream, "UTF-8");
  XMLStreamReader xtr = xif.createXMLStreamReader(in);
  return new SubprocessXMLConverter().convertToBpmnModel(xtr);
}
 
Example 10
Source File: DefaultProcessValidatorTest.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testWarningError() throws UnsupportedEncodingException, XMLStreamException {
  String flowWithoutConditionNoDefaultFlow = "<?xml version='1.0' encoding='UTF-8'?>"
      + "<definitions id='definitions' xmlns='http://www.omg.org/spec/BPMN/20100524/MODEL' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:activiti='http://activiti.org/bpmn' targetNamespace='Examples'>"
      + "  <process id='exclusiveGwDefaultSequenceFlow'> " + "    <startEvent id='theStart' /> " + "    <sequenceFlow id='flow1' sourceRef='theStart' targetRef='exclusiveGw' /> " +

      "    <exclusiveGateway id='exclusiveGw' name='Exclusive Gateway' /> "
      + // no default = "flow3" !!
      "    <sequenceFlow id='flow2' sourceRef='exclusiveGw' targetRef='theTask1'> " + "      <conditionExpression xsi:type='tFormalExpression'>${input == 1}</conditionExpression> "
      + "    </sequenceFlow> " + "    <sequenceFlow id='flow3' sourceRef='exclusiveGw' targetRef='theTask2'/> " + // one
                                                                                                                  // would
                                                                                                                  // be
                                                                                                                  // OK
      "    <sequenceFlow id='flow4' sourceRef='exclusiveGw' targetRef='theTask2'/> " + // but
                                                                                       // two
                                                                                       // unconditional
                                                                                       // not!

      "    <userTask id='theTask1' name='Input is one' /> " + "    <userTask id='theTask2' name='Default input' /> " + "  </process>" + "</definitions>";

  XMLInputFactory xif = XMLInputFactory.newInstance();
  InputStreamReader in = new InputStreamReader(new ByteArrayInputStream(flowWithoutConditionNoDefaultFlow.getBytes()), "UTF-8");
  XMLStreamReader xtr = xif.createXMLStreamReader(in);
  BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr);
  Assert.assertNotNull(bpmnModel);
  List<ValidationError> allErrors = processValidator.validate(bpmnModel);
  Assert.assertEquals(1, allErrors.size());
  Assert.assertTrue(allErrors.get(0).isWarning());
}
 
Example 11
Source File: AbstractUnmarshallerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void unmarshalPartialStaxSourceXmlStreamReader() throws Exception {
	XMLInputFactory inputFactory = XMLInputFactory.newInstance();
	XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(INPUT_STRING));
	streamReader.nextTag(); // skip to flights
	assertEquals("Invalid element", new QName("http://samples.springframework.org/flight", "flights"),
			streamReader.getName());
	streamReader.nextTag(); // skip to flight
	assertEquals("Invalid element", new QName("http://samples.springframework.org/flight", "flight"),
			streamReader.getName());
	Source source = StaxUtils.createStaxSource(streamReader);
	Object flight = unmarshaller.unmarshal(source);
	testFlight(flight);
}
 
Example 12
Source File: RemoteAdmin.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Convert the REST server's response to an XML reader.
 *
 * @param response The REST server's response.
 * @return A reader over the parsed XML document.
 * @throws IOException If the document fails to parse
 */
private XMLStreamReader getInputStream(Response response) throws IOException {
  try {
    // Prevent the parser from reading XMl with external entities defined
    XMLInputFactory xif = XMLInputFactory.newFactory();
    xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
    xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
    return xif.createXMLStreamReader(new ByteArrayInputStream(response.getBody()));
  } catch (XMLStreamException e) {
    throw new IOException("Failed to parse XML", e);
  }
}
 
Example 13
Source File: TestCharacterLimits.java    From woodstox with Apache License 2.0 5 votes vote down vote up
public void testLongCommentNextTag() throws Exception {
    try {
        Reader reader = createLongReader("<!--", "-->", true);
        XMLInputFactory factory = getNewInputFactory();
        factory.setProperty(WstxInputProperties.P_MAX_TEXT_LENGTH, Integer.valueOf(1000));
        XMLStreamReader xmlreader = factory.createXMLStreamReader(reader);
        while (xmlreader.next() != XMLStreamReader.COMMENT) {
        }
        xmlreader.nextTag();
        fail("Should have failed");
    } catch (XMLStreamException ex) {
        _verifyTextLimitException(ex);
    }
}
 
Example 14
Source File: XmlMetadataConsumerTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
private XMLStreamReader createStreamReader(final String xml) throws XMLStreamException {
  XMLInputFactory factory = XMLInputFactory.newInstance();
  factory.setProperty(XMLInputFactory.IS_VALIDATING, false);
  factory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
  XMLStreamReader streamReader = factory.createXMLStreamReader(new StringReader(xml));

  return streamReader;
}
 
Example 15
Source File: ConversionService.java    From validator with Apache License 2.0 5 votes vote down vote up
public <T> T readXml(final URI xml, final Class<T> type, final Schema schema, final ValidationEventHandler handler) {
    checkInputEmpty(xml);
    checkTypeEmpty(type);
    CollectingErrorEventHandler defaultHandler = null;
    ValidationEventHandler handler2Use = handler;
    if (schema != null && handler == null) {
        defaultHandler = new CollectingErrorEventHandler();
        handler2Use = defaultHandler;
    }
    try {
        final XMLInputFactory inputFactory = XMLInputFactory.newFactory();
        inputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
        inputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
        inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        final XMLStreamReader xsr = inputFactory.createXMLStreamReader(new StreamSource(xml.toASCIIString()));
        final Unmarshaller u = getJaxbContext().createUnmarshaller();
        u.setSchema(schema);

        u.setEventHandler(handler2Use);
        final T value = u.unmarshal(xsr, type).getValue();
        if (defaultHandler != null && defaultHandler.hasErrors()) {
            throw new ConversionExeption(
                    String.format("Schema errors while reading content from %s: %s", xml, defaultHandler.getErrorDescription()));
        }

        return value;
    } catch (final JAXBException | XMLStreamException e) {
        throw new ConversionExeption(String.format("Can not unmarshal to type %s from %s", type.getSimpleName(), xml.toString()), e);
    }
}
 
Example 16
Source File: SurrogatesTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private void readXML(byte[] xmlData, String expectedContent)
        throws Exception {
    InputStream stream = new ByteArrayInputStream(xmlData);
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader xmlReader
            = factory.createXMLStreamReader(stream);
    boolean inTestElement = false;
    StringBuilder sb = new StringBuilder();
    while (xmlReader.hasNext()) {
        String ename;
        switch (xmlReader.getEventType()) {
            case XMLStreamConstants.START_ELEMENT:
                ename = xmlReader.getLocalName();
                if (ename.equals("writeCharactersWithString")
                        || ename.equals("writeCharactersWithArray")) {
                    inTestElement = true;
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                ename = xmlReader.getLocalName();
                if (ename.equals("writeCharactersWithString")
                        || ename.equals("writeCharactersWithArray")) {
                    inTestElement = false;
                    String content = sb.toString();
                    System.out.println(ename + " text:'" + content + "' expected:'" + expectedContent+"'");
                    Assert.assertEquals(content, expectedContent);
                    sb.setLength(0);
                }
                break;
            case XMLStreamConstants.CHARACTERS:
                if (inTestElement) {
                    sb.append(xmlReader.getText());
                }
                break;
        }
        xmlReader.next();
    }
}
 
Example 17
Source File: ExternalMetadataReader.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
static String documentRootNamespace(Source src, boolean disableXmlSecurity) throws XMLStreamException {
    XMLInputFactory factory;
    factory = XmlUtil.newXMLInputFactory(!disableXmlSecurity);
    XMLStreamReader streamReader = factory.createXMLStreamReader(src);
    XMLStreamReaderUtil.nextElementContent(streamReader);
    String namespaceURI = streamReader.getName().getNamespaceURI();
    XMLStreamReaderUtil.close(streamReader);
    return namespaceURI;
}
 
Example 18
Source File: BpmnImageTest.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected BpmnModel getBpmnModel(String file) throws Exception {
	BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
    InputStream xmlStream = this.getClass().getClassLoader().getResourceAsStream(file);
    XMLInputFactory xif = XMLInputFactory.newInstance();
    InputStreamReader in = new InputStreamReader(xmlStream);
    XMLStreamReader xtr = xif.createXMLStreamReader(in);
    BpmnModel bpmnModel = xmlConverter.convertToBpmnModel(xtr);
    return bpmnModel;
}
 
Example 19
Source File: RuleToXmlConverter.java    From yare with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Rule unmarshal(String value) throws RuleConversionException {
    validateAgainstSchema(value);
    try {
        Unmarshaller unmarshaller = createUnmarshaller();
        XMLInputFactory xmlInputFactory = getXmlInputFactory();
        XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(new StringReader(value));
        RuleSer ruleSer = ((JAXBElement<RuleSer>) unmarshaller.unmarshal(xmlStreamReader)).getValue();
        return toRuleConverter.map(ruleSer);
    } catch (Exception e) {
        throw new RuleConversionException(String.format("Rule cannot be converted to Object:\n%s", value), e);
    }
}
 
Example 20
Source File: XElement.java    From open-ig with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Parse an XML document from the given input stream.
 * Does not close the stream.
 * @param in the input stream
 * @return az XElement object
 * @throws XMLStreamException on error
 */
public static XElement parseXML(InputStream in) throws XMLStreamException {
	XMLInputFactory inf = XMLInputFactory.newInstance();
	XMLStreamReader ir = inf.createXMLStreamReader(in);
	return parseXML(ir);
}