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

The following examples show how to use javax.xml.stream.XMLInputFactory#newInstance() . 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: AbstractParser.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Get the JAXP {@link XMLInputFactory}
 *
 * @return
 */
private XMLInputFactory getXMLInputFactory() {
    boolean tccl_jaxp = SystemPropertiesUtil.getSystemProperty(GeneralConstants.TCCL_JAXP, "false")
            .equalsIgnoreCase("true");
    ClassLoader prevTCCL = SecurityActions.getTCCL();
    try {
        if (tccl_jaxp) {
            SecurityActions.setTCCL(AbstractParser.class.getClassLoader());
        }
        return XMLInputFactory.newInstance();
    } finally {
        if (tccl_jaxp) {
            SecurityActions.setTCCL(prevTCCL);
        }
    }
}
 
Example 2
Source File: TestPayloadNameRequestWrapper.java    From javamelody with Apache License 2.0 6 votes vote down vote up
private boolean scanForChildTag(String tagName, String xml) throws XMLStreamException {
	final XMLInputFactory factory = XMLInputFactory.newInstance();
	final XMLStreamReader reader = factory
			.createXMLStreamReader(new ByteArrayInputStream(xml.getBytes()));

	//advance to first tag (reader starts at "begin document")
	reader.next();

	final boolean found = PayloadNameRequestWrapper.scanForChildTag(reader, tagName);

	if (found) {
		assertEquals("Found wrong tag", tagName, reader.getLocalName());
	}

	reader.close();

	return found;
}
 
Example 3
Source File: ProcessingInstructionTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testPITargetAndData() {
    try {
        XMLInputFactory xif = XMLInputFactory.newInstance();
        String PITarget = "soffice";
        String PIData = "WebservicesArchitecture";
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<?" + PITarget + " " + PIData + "?>" + "<foo></foo>";
        // System.out.println("XML = " + xml) ;
        InputStream is = new java.io.ByteArrayInputStream(xml.getBytes());
        XMLStreamReader sr = xif.createXMLStreamReader(is);
        while (sr.hasNext()) {
            int eventType = sr.next();
            if (eventType == XMLStreamConstants.PROCESSING_INSTRUCTION) {
                String target = sr.getPITarget();
                String data = sr.getPIData();
                Assert.assertTrue(target.equals(PITarget) && data.equals(PIData));
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
Example 4
Source File: AbstractDOMDocumentSerializer.java    From jettison with Apache License 2.0 6 votes vote down vote up
public void serialize(Element el) throws IOException {
	if (output == null)
		throw new IllegalStateException("OutputStream cannot be null");

	try {
		DOMSource source = new DOMSource(el);
		XMLInputFactory readerFactory = XMLInputFactory.newInstance();
		XMLStreamReader streamReader = readerFactory
				.createXMLStreamReader(source);
		XMLEventReader eventReader = readerFactory
				.createXMLEventReader(streamReader);

		XMLEventWriter eventWriter = writerFactory
				.createXMLEventWriter(output);
		eventWriter.add(eventReader);
		eventWriter.close();
	} catch (XMLStreamException ex) {
		IOException ioex = new IOException("Cannot serialize: " + el);
		ioex.initCause(ex);
		throw ioex;
	}
}
 
Example 5
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 6
Source File: SkipDTDTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test() {
    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        for (int i = 0; i < 3; i++) {
            runReader(factory, i);
        }
    } catch (XMLStreamException xe) {
        xe.printStackTrace();
        Assert.fail(xe.getMessage());
    }
}
 
Example 7
Source File: MusicPlayer.java    From MusicPlayer with MIT License 5 votes vote down vote up
private static int xmlMusicDirFileNumFinder() {
    try {
        // Creates reader for xml file.
        XMLInputFactory factory = XMLInputFactory.newInstance();
        factory.setProperty("javax.xml.stream.isCoalescing", true);
        FileInputStream is = new FileInputStream(new File(Resources.JAR + "library.xml"));
        XMLStreamReader reader = factory.createXMLStreamReader(is, "UTF-8");

        String element = null;
        String fileNum = null;

        // Loops through xml file looking for the music directory file path.
        while(reader.hasNext()) {
            reader.next();
            if (reader.isWhiteSpace()) {
                continue;
            } else if (reader.isStartElement()) {
                element = reader.getName().getLocalPart();
            } else if (reader.isCharacters() && element.equals("fileNum")) {
                fileNum = reader.getText();
                break;
            }
        }
        // Closes xml reader.
        reader.close();

        // Converts the file number to an int and returns the value.
        return Integer.parseInt(fileNum);
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}
 
Example 8
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 9
Source File: XmiMappingReader.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * Reads XMI from an {@link InputStream}.
 * 
 * @param stream
 *            The {@link InputStream}.
 * @return The parsed {@link Model}.
 */
public static final XmiComparison readDocument(final InputStream stream) {
    final XMLInputFactory factory = XMLInputFactory.newInstance();
    try {
        final XMLStreamReader reader = factory.createXMLStreamReader(stream);
        try {
            return readDocument(reader);
        } finally {
            reader.close();
        }
    } catch (final XMLStreamException e) {
        throw new XmiCompRuntimeException(e);
    }
}
 
Example 10
Source File: SkipDTDTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test() {
    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        for (int i = 0; i < 3; i++) {
            runReader(factory, i);
        }
    } catch (XMLStreamException xe) {
        xe.printStackTrace();
        Assert.fail(xe.getMessage());
    }
}
 
Example 11
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 12
Source File: XmlUtil.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static XMLInputFactory newXMLInputFactory(boolean secureXmlProcessingEnabled)  {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    if (isXMLSecurityDisabled(secureXmlProcessingEnabled)) {
        // TODO-Miran: are those apppropriate defaults?
        factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
    }
    return factory;
}
 
Example 13
Source File: DatabaseIO.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new, initialized XML input factory object.
 * 
 * @return The factory object
 */
private XMLInputFactory getXMLInputFactory()
{
    XMLInputFactory factory = XMLInputFactory.newInstance();

    factory.setProperty("javax.xml.stream.isCoalescing",     Boolean.TRUE);
    factory.setProperty("javax.xml.stream.isNamespaceAware", Boolean.TRUE);
    return factory;
}
 
Example 14
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 15
Source File: PsmConfigReader.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * Reads XMI from an {@link InputStream}.
 *
 * @param stream
 *            The {@link InputStream}.
 * @return The parsed {@link Model}.
 */
public static final PsmConfig<Type> readConfig(final InputStream stream, final ModelIndex mapper) {
    final XMLInputFactory factory = XMLInputFactory.newInstance();
    try {
        final XMLStreamReader reader = factory.createXMLStreamReader(stream);
        try {
            final PsmConfig<Type> model = readDocument(mapper, reader);
            return model;
        } finally {
            reader.close();
        }
    } catch (final XMLStreamException e) {
        throw new PsmConfigRuntimeException(e);
    }
}
 
Example 16
Source File: MtasConfiguration.java    From mtas with Apache License 2.0 4 votes vote down vote up
/**
 * Read configuration.
 *
 * @param reader
 *          the reader
 * @return the mtas configuration
 * @throws IOException
 *           Signals that an I/O exception has occurred.
 */
public static MtasConfiguration readConfiguration(InputStream reader)
    throws IOException {
  MtasConfiguration currentConfig = null;
  // parse xml
  XMLInputFactory factory = XMLInputFactory.newInstance();
  try {
    XMLStreamReader streamReader = factory.createXMLStreamReader(reader);
    QName qname;
    try {
      int event = streamReader.getEventType();
      while (true) {
        switch (event) {
        case XMLStreamConstants.START_DOCUMENT:
          if (!streamReader.getCharacterEncodingScheme().equals("UTF-8")) {
            throw new IOException("XML not UTF-8 encoded");
          }
          break;
        case XMLStreamConstants.END_DOCUMENT:
        case XMLStreamConstants.SPACE:
          break;
        case XMLStreamConstants.START_ELEMENT:
          // get data
          qname = streamReader.getName();
          if (currentConfig == null) {
            if (qname.getLocalPart().equals("mtas")) {
              currentConfig = new MtasConfiguration();
            } else {
              throw new IOException("no Mtas Configuration");
            }
          } else {
            MtasConfiguration parentConfig = currentConfig;
            currentConfig = new MtasConfiguration();
            parentConfig.children.add(currentConfig);
            currentConfig.parent = parentConfig;
            currentConfig.name = qname.getLocalPart();
            for (int i = 0; i < streamReader.getAttributeCount(); i++) {
              currentConfig.attributes.put(
                  streamReader.getAttributeLocalName(i),
                  streamReader.getAttributeValue(i));
            }
          }
          break;
        case XMLStreamConstants.END_ELEMENT:
          if (currentConfig.parent == null) {
            return currentConfig;
          } else {
            currentConfig = currentConfig.parent;
          }
          break;
        case XMLStreamConstants.CHARACTERS:
          break;
        }
        if (!streamReader.hasNext()) {
          break;
        }
        event = streamReader.next();
      }
    } finally {
      streamReader.close();
    }
  } catch (XMLStreamException e) {
    log.debug(e);
  }
  return null;
}
 
Example 17
Source File: XmlFileIndexerProvider.java    From jd-gui with GNU General Public License v3.0 4 votes vote down vote up
public XmlFileIndexerProvider() {
    factory = XMLInputFactory.newInstance();
    factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
}
 
Example 18
Source File: SyncService.java    From SQLite-sync.com with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void PushDeletedRecrods(String subscriber, String deletedRecordsXML) {
    Connection cn = Database.getInstance().GetDBConnection();
    try {
        if (deletedRecordsXML.equalsIgnoreCase("<delete></delete>"))
            return;

        CommonTools commonTools = new CommonTools();
        Map<Integer, String> tables = commonTools.GetSynchronizedTables();
        Map<Integer, DatabaseTable> tablesDef = new HashMap<>();

        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        InputStream in = new ByteArrayInputStream(deletedRecordsXML.getBytes(StandardCharsets.UTF_8));
        XMLStreamReader streamReader = inputFactory.createXMLStreamReader(in);

        Statement deleteStatment = cn.createStatement();

        int eventType;

        String tableId = "";
        String recordId = "";
        Boolean isTableId = false;
        Boolean isRecordId = false;
        Boolean hasRecords = false;

        while (streamReader.hasNext()) {
            eventType = streamReader.next();

            switch (eventType) {
                case XMLStreamConstants.START_ELEMENT:
                    if (streamReader.getLocalName().equals("tb")) {
                        isTableId = true;
                        isRecordId = false;
                    }
                    if (streamReader.getLocalName().equals("id")) {
                        isRecordId = true;
                        isTableId = false;
                    }

                    break;
                case XMLStreamConstants.CHARACTERS:
                    if (isTableId) {
                        tableId = streamReader.getText();
                        if (!tablesDef.containsKey(tableId)) {
                            String tableSchema = "";
                            String tableName = tables.get(Integer.parseInt(tableId));
                            if (tableName.contains(".")) {
                                String[] tmp = tableName.split(Pattern.quote("."));
                                tableSchema = tmp[0];
                                tableName = tmp[1];
                            }
                            tablesDef.put(Integer.parseInt(tableId), DatabaseTableGuavaCacheUtil.getTableUsingGuava(tableName, tableSchema));
                        }
                    }
                    if (isRecordId) {
                        recordId = streamReader.getText();
                    }
                    break;
                case XMLStreamConstants.END_ELEMENT:
                    if (streamReader.getLocalName().equals("r")) {
                        isTableId = false;
                        isRecordId = false;
                        String deleteQuery = "";

                        if (tables.containsKey(Integer.parseInt(tableId))) {

                            deleteQuery = "delete from `" + tables.get(Integer.parseInt(tableId)) + "` where RowId='" + recordId.toString() + "'";
                            deleteStatment.addBatch(deleteQuery);
                            if (!hasRecords)
                                hasRecords = true;
                        }
                        tableId = "";
                        recordId = "";
                    }
                    break;
                default:
                    break;
            }
        }

        if (hasRecords)
            deleteStatment.executeBatch();

    } catch (XMLStreamException | SQLException e) {
        Logs.write(Logs.Level.ERROR, "PushDeletedRecrods() " + e.getMessage());
    } finally {
        JDBCCloser.close(cn);
    }
}
 
Example 19
Source File: Bug6509774.java    From openjdk-jdk9 with GNU General Public License v2.0 2 votes vote down vote up
@Test
public void test2() {

    try {

        XMLInputFactory xif = XMLInputFactory.newInstance();

        xif.setProperty("javax.xml.stream.supportDTD", Boolean.FALSE);

        XMLStreamReader xsr = xif.createXMLStreamReader(

        getClass().getResource("sgml-bad-systemId.xml").toString(),

        getClass().getResourceAsStream("sgml-bad-systemId.xml"));

        Assert.assertTrue(xsr.getEventType() == XMLStreamConstants.START_DOCUMENT);

        int event = xsr.next();

        // Should not be a DTD event since they are ignored

        Assert.assertTrue(event == XMLStreamConstants.DTD);

        while (xsr.hasNext()) {

            event = xsr.next();

        }

        Assert.assertTrue(event == XMLStreamConstants.END_DOCUMENT);

        xsr.close();

    }

    catch (Exception e) {

        // Bogus systemId in XML document should not result in exception

        Assert.fail(e.getMessage());

    }

}
 
Example 20
Source File: XMLProvider.java    From jpx with Apache License 2.0 2 votes vote down vote up
/**
 * Returns {@link XMLInputFactory} to be used for reading files.
 *
 * @return the xml input factory
 */
public XMLInputFactory xmlInputFactory() {
	return XMLInputFactory.newInstance();
}