Java Code Examples for javax.xml.stream.XMLStreamReader#close()

The following examples show how to use javax.xml.stream.XMLStreamReader#close() . 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: SourceHttpMessageConverterTests.java    From spring-analysis-note with MIT License 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 2
Source File: EndpointArgumentsBuilder.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
protected void readWrappedRequest(Message msg, Object[] args) throws JAXBException, XMLStreamException {
    if (!msg.hasPayload()) {
        throw new WebServiceException("No payload. Expecting payload with "+wrapperName+" element");
    }
    XMLStreamReader reader = msg.readPayload();
    XMLStreamReaderUtil.verifyTag(reader,wrapperName);
    reader.nextTag();
    while(reader.getEventType()==XMLStreamReader.START_ELEMENT) {
        // TODO: QName has a performance issue
        QName name = reader.getName();
        WrappedPartBuilder part = wrappedParts.get(name);
        if(part==null) {
            // no corresponding part found. ignore
            XMLStreamReaderUtil.skipElement(reader);
            reader.nextTag();
        } else {
            part.readRequest(args,reader, msg.getAttachments());
        }
        XMLStreamReaderUtil.toNextTag(reader, name);
    }

    // we are done with the body
    reader.close();
    XMLStreamReaderFactory.recycle(reader);
}
 
Example 3
Source File: TsoGeneratorVoltageAutomatonTest.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void testXml() throws IOException, XMLStreamException {
    String xml = "<?xml version=\"1.0\" ?><index name=\"tso-generator-voltage-automaton\"><onUnderVoltageDisconnectedGenerators><gen>a</gen><gen>b</gen></onUnderVoltageDisconnectedGenerators><onOverVoltageDisconnectedGenerators><gen>c</gen></onOverVoltageDisconnectedGenerators></index>";
    XMLInputFactory xmlif = XMLInputFactory.newInstance();
    TsoGeneratorVoltageAutomaton index;
    try (Reader reader = new StringReader(xml)) {
        XMLStreamReader xmlReader = xmlif.createXMLStreamReader(reader);
        try {
            index = TsoGeneratorVoltageAutomaton.fromXml("c1", xmlReader);
        } finally {
            xmlReader.close();
        }
    }
    assertTrue(index.getOnUnderVoltageDiconnectedGenerators().equals(Arrays.asList("a", "b")));
    assertTrue(index.getOnOverVoltageDiconnectedGenerators().equals(Arrays.asList("c")));
    assertEquals(xml, index.toXml());
}
 
Example 4
Source File: TsoSynchroLossSecurityIndexTest.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void testXml() throws IOException, XMLStreamException {
    String xml = "<?xml version=\"1.0\" ?><index name=\"tso-synchro-loss\"><synchro-loss-count>1</synchro-loss-count></index>";
    XMLInputFactory xmlif = XMLInputFactory.newInstance();
    TsoSynchroLossSecurityIndex index;
    try (Reader reader = new StringReader(xml)) {
        XMLStreamReader xmlReader = xmlif.createXMLStreamReader(reader);
        try {
            index = TsoSynchroLossSecurityIndex.fromXml("c1", xmlReader);
        } finally {
            xmlReader.close();
        }
    }
    assertTrue(index.getSynchroLossCount() == 1);
    assertEquals(xml, index.toXml());
}
 
Example 5
Source File: Jsr173MR1Req5Test.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testAttributeCountNoNS() {
    XMLInputFactory ifac = XMLInputFactory.newInstance();

    try {
        // Turn off NS awareness to count xmlns as attributes
        ifac.setProperty("javax.xml.stream.isNamespaceAware", Boolean.FALSE);

        XMLStreamReader re = ifac.createXMLStreamReader(getClass().getResource(INPUT_FILE1).toExternalForm(),
                this.getClass().getResourceAsStream(INPUT_FILE1));
        while (re.hasNext()) {
            int event = re.next();
            if (event == XMLStreamConstants.START_ELEMENT) {
                // System.out.println("#attrs = " + re.getAttributeCount());
                Assert.assertTrue(re.getAttributeCount() == 3);
            }
        }
        re.close();
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("Exception occured: " + e.getMessage());
    }
}
 
Example 6
Source File: Jsr173MR1Req5Test.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testAttributeCountNS() {
    XMLInputFactory ifac = XMLInputFactory.newInstance();

    try {
        // Turn on NS awareness to not count xmlns as attributes
        ifac.setProperty("javax.xml.stream.isNamespaceAware", Boolean.TRUE);

        XMLStreamReader re = ifac.createXMLStreamReader(getClass().getResource(INPUT_FILE1).toExternalForm(),
                this.getClass().getResourceAsStream(INPUT_FILE1));
        while (re.hasNext()) {
            int event = re.next();
            if (event == XMLStreamConstants.START_ELEMENT) {
                // System.out.println("#attrs = " + re.getAttributeCount());
                Assert.assertTrue(re.getAttributeCount() == 1);
            }
        }
        re.close();
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("Exception occured: " + e.getMessage());
    }
}
 
Example 7
Source File: DocumentationReader.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
/**
 * Reads XMI from an {@link InputStream}.
 *
 * @param stream The {@link InputStream}.
 * @return The parsed {@link Model}.
 */
public static final Documentation<Type> readDocumentation(final InputStream stream, final ModelIndex mapper) {
    if (stream == null) {
        throw new IllegalArgumentException("stream");
    }
    final XMLInputFactory factory = XMLInputFactory.newInstance();
    try {
        final XMLStreamReader reader = factory.createXMLStreamReader(stream);
        try {
            final Documentation<Type> model = readDocument(mapper, reader);
            return model;
        } finally {
            reader.close();
        }
    } catch (final XMLStreamException e) {
        throw new DocumentGeneratorRuntimeException(e);
    }
}
 
Example 8
Source File: XmiReader.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 Model readModel(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 XmiRuntimeException(e);
    }
}
 
Example 9
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 10
Source File: SourceHttpMessageConverterTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void readStAXSource() throws Exception {
	MockHttpInputMessage inputMessage = new MockHttpInputMessage(BODY.getBytes("UTF-8"));
	inputMessage.getHeaders().setContentType(new MediaType("application", "xml"));
	StAXSource result = (StAXSource) converter.read(StAXSource.class, inputMessage);
	XMLStreamReader streamReader = result.getXMLStreamReader();
	assertTrue(streamReader.hasNext());
	streamReader.nextTag();
	String s = streamReader.getLocalName();
	assertEquals("root", s);
	s = streamReader.getElementText();
	assertEquals("Hello World", s);
	streamReader.close();
}
 
Example 11
Source File: RMCaptureInInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected void handle(Message message) throws SequenceFault, RMException {

    // all messages are initially captured as they cannot be distinguished at this phase
    // Non application messages temp files are released (cos.releaseTempFileHold()) in RMInInterceptor
    if (!isGET(message) && !MessageUtils.getContextualBoolean(message, Message.ROBUST_ONEWAY, false)
        && (getManager().getStore() != null || (getManager().getDestinationPolicy() != null && getManager()
            .getDestinationPolicy().getRetryPolicy() != null))) {

        message.getInterceptorChain().add(new RMCaptureInEnd());
        XMLStreamReader reader = message.getContent(XMLStreamReader.class);

        if (null != reader) {
            CachedOutputStream saved = new CachedOutputStream();
            // REVISIT check factory for READER
            try {
                StaxUtils.copy(reader, saved);
                saved.flush();
                saved.holdTempFile();
                reader.close();
                LOG.fine("Create new XMLStreamReader");
                InputStream is = saved.getInputStream();
                // keep References to clean-up tmp files in RMDeliveryInterceptor
                setCloseable(message, saved, is);
                XMLStreamReader newReader = StaxUtils.createXMLStreamReader(is);
                StaxUtils.configureReader(reader, message);
                message.setContent(XMLStreamReader.class, newReader);
                LOG.fine("Capturing the original RM message");
                message.put(RMMessageConstants.SAVED_CONTENT, saved);
            } catch (XMLStreamException | IOException e) {
                throw new Fault(e);
            }
        } else {
            org.apache.cxf.common.i18n.Message msg = new org.apache.cxf.common.i18n.Message(
                              "No message found for redeliver", LOG, Collections.<String> emptyList());
            RMException ex = new RMException(msg);
            throw new Fault(ex);
        }
    }
}
 
Example 12
Source File: SaxonCommand.java    From kite with Apache License 2.0 5 votes vote down vote up
protected XdmNode parseXmlDocument(InputStream stream) throws XMLStreamException, SaxonApiException {
  XMLStreamReader reader = inputFactory.createXMLStreamReader(null, stream);
  BuildingStreamWriterImpl writer = documentBuilder.newBuildingStreamWriter();      
  new XMLStreamCopier(reader, writer).copy(false); // push XML into Saxon and build TinyTree
  reader.close();
  writer.close();
  XdmNode document = writer.getDocumentNode();
  return document;
}
 
Example 13
Source File: TransformationGraphXMLReaderWriter.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
private String readIdStax(InputStream in) throws XMLStreamException {
	
	XMLStreamReader reader = XMLInputFactory.newFactory().createXMLStreamReader(in);
	try {
		while (reader.hasNext()) {
			int event = reader.next();
			if (event == XMLEvent.START_ELEMENT && GRAPH_ELEMENT.equals(reader.getLocalName())) {
				final int count = reader.getAttributeCount();
				for (int i = 0; i < count; ++i) {
					if (ID_ATTRIBUTE.equals(reader.getAttributeLocalName(i))) {
						String id = reader.getAttributeValue(i);
						if (!StringUtils.isEmpty(id)) {
							return id;
						}
					}
				}
				for (int i = 0; i < count; ++i) {
					if (NAME_ATTRIBUTE.equals(reader.getAttributeLocalName(i))) {
						return reader.getAttributeValue(i);
					}
				}
			}
		}
		return null;
	} finally {
		reader.close();
	}
}
 
Example 14
Source File: JmsSubscription.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void onMessage(Message jmsMessage) {
    try {
        TextMessage text = (TextMessage) jmsMessage;
        XMLStreamReader reader = StaxUtils.createXMLStreamReader(new StringReader(text.getText()));
        Notify notify = (Notify) jaxbContext.createUnmarshaller()
                .unmarshal(reader);
        reader.close();
        for (Iterator<NotificationMessageHolderType> ith = notify.getNotificationMessage().iterator();
            ith.hasNext();) {
            NotificationMessageHolderType h = ith.next();
            Object content = h.getMessage().getAny();
            if (!(content instanceof Element)) {
                DocumentFragment doc = DOMUtils.getEmptyDocument().createDocumentFragment();
                jaxbContext.createMarshaller().marshal(content, doc);
                content = DOMUtils.getFirstElement(doc);
            }
            if (!doFilter((Element) content)) {
                ith.remove();
            } else {
                h.setTopic(topic);
                h.setSubscriptionReference(getEpr());
            }
        }
        if (!notify.getNotificationMessage().isEmpty()) {
            doNotify(notify);
        }
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, "Error notifying consumer", e);
    }
}
 
Example 15
Source File: XmlStackingSemanticTranslator.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private void silentlyCloseReader(final XMLStreamReader reader) {
    try {
        if (reader != null) {
            reader.close();
        }
    } catch (Exception e) {
        LOG.error("Issue closing the streaming XML reader", e);
    }
}
 
Example 16
Source File: StaxUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static Document read(Source s) throws XMLStreamException {
    XMLStreamReader reader = createXMLStreamReader(s);
    try {
        return read(reader);
    } finally {
        try {
            reader.close();
        } catch (Exception ex) {
            //ignore
        }
    }
}
 
Example 17
Source File: XlsxNumberFormatParser.java    From rapidminer-studio with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Parses the XLSX styles XML file (with UTF-8 encoding) and returns the parsed number formats.
 *
 * @return the number formats stored within a {@link XlsxNumberFormats} object
 * @throws IOException
 *             in case the Shared Strings Zip entry cannot be opened
 * @throws XMLStreamException
 *             in case the {@link XMLInputFactory} cannot create a {@link XMLStreamReader}
 * @throws XlsxException
 *             in case the shared string XML content is invalid
 */
public XlsxNumberFormats parseNumberFormats() throws XMLStreamException, IOException {

	boolean isCellFormats = false;
	int cellFormatIndex = 0;
	XlsxNumberFormats xlsxNumberFormats = new XlsxNumberFormats();
	XMLStreamReader reader = null;
	try (ZipFile zipFile = new ZipFile(xlsxFile)) {
		ZipEntry zipEntry = zipFile.getEntry(XlsxUtilities.XLSX_PATH_PREFIX + stylesPath);
		if (zipEntry == null) {
			// no styles defined
			return null;
		}

		InputStream inputStream = zipFile.getInputStream(zipEntry);
		reader = xmlFactory.createXMLStreamReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
		while (reader.hasNext()) {
			switch (reader.next()) {
				case XMLStreamReader.START_ELEMENT:
					if (TAG_NUMBER_FORMAT.equals(reader.getLocalName())) {
						Attributes attributes = XlsxUtilities.getAttributes(reader);
						xlsxNumberFormats.addNumberFormat(Integer.parseInt(attributes.getValue(ATT_NUM_FORM_ID)),
								attributes.getValue(ATT_FORMAT_CODE));
					} else if (TAG_CELL_FORMATS.equals(reader.getLocalName())) {
						isCellFormats = true;

						// create an array of the size of all defined cell formats
						xlsxNumberFormats.initializeCellNumberFormatIds(Integer.parseInt(XlsxUtilities.getAttributes(
								reader).getValue(ATT_COUNT)));
					} else if (isCellFormats && TAG_FORMAT.equals(reader.getLocalName())) {
						xlsxNumberFormats.setCellNumberFormatId(cellFormatIndex,
								Integer.parseInt(XlsxUtilities.getAttributes(reader).getValue(ATT_NUMBER_FORMAT_ID)));
						++cellFormatIndex;
					}
					break;
				case XMLStreamReader.END_ELEMENT:
					if (TAG_CELL_FORMATS.equals(reader.getLocalName())) {
						isCellFormats = false;
					}
					break;
				default:
					// ignore other cases
					break;
			}
		}
	} finally {
		if (reader != null) {
			reader.close();
		}
	}
	return xlsxNumberFormats;
}
 
Example 18
Source File: Library.java    From MusicPlayer with MIT License 4 votes vote down vote up
public static ArrayList<Song> loadPlayingList() {

        ArrayList<Song> nowPlayingList = new ArrayList<>();

        try {

            XMLInputFactory factory = XMLInputFactory.newInstance();
            FileInputStream is = new FileInputStream(new File(Resources.JAR + "library.xml"));
            XMLStreamReader reader = factory.createXMLStreamReader(is, "UTF-8");

            String element = "";
            boolean isNowPlayingList = false;

            while(reader.hasNext()) {
                reader.next();
                if (reader.isWhiteSpace()) {
                    continue;
                } else if (reader.isCharacters() && isNowPlayingList) {
                    String value = reader.getText();
                    if (element.equals(ID)) {
                        nowPlayingList.add(getSong(Integer.parseInt(value)));
                    }
                } else if (reader.isStartElement()) {
                    element = reader.getName().getLocalPart();
                    if (element.equals("nowPlayingList")) {
                        isNowPlayingList = true;
                    }
                } else if (reader.isEndElement() && reader.getName().getLocalPart().equals("nowPlayingList")) {
                    reader.close();
                    break;
                }
            }

            reader.close();

        } catch (Exception ex) {

            ex.printStackTrace();
        }

        return nowPlayingList;
    }
 
Example 19
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 20
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());

    }

}