Java Code Examples for javax.xml.stream.XMLEventReader#close()
The following examples show how to use
javax.xml.stream.XMLEventReader#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: XMLUtilities.java From olingo-odata4 with Apache License 2.0 | 6 votes |
@Override public InputStream deleteProperty(final InputStream src, final List<String> path) throws Exception { final XMLEventReader reader = getEventReader(src); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final XMLEventWriter writer = getEventWriter(bos); final XMLEventReader changesReader = new XMLEventReaderWrapper(IOUtils.toInputStream( String.format("<%s m:null=\"true\" />", path.get(path.size() - 1)), Constants.ENCODING)); writer.add(changesReader); changesReader.close(); writer.add(reader); reader.close(); IOUtils.closeQuietly(src); writer.flush(); writer.close(); return new ByteArrayInputStream(bos.toByteArray()); }
Example 2
Source File: JaxbCfgProcessor.java From lams with GNU General Public License v2.0 | 6 votes |
public JaxbCfgHibernateConfiguration unmarshal(InputStream stream, Origin origin) { try { XMLEventReader staxReader = staxFactory().createXMLEventReader( stream ); try { return unmarshal( staxReader, origin ); } finally { try { staxReader.close(); } catch ( Exception ignore ) { } } } catch ( XMLStreamException e ) { throw new HibernateException( "Unable to create stax reader", e ); } }
Example 3
Source File: XMLUtilities.java From olingo-odata4 with Apache License 2.0 | 6 votes |
private int countFeedElements(final InputStream is, final String elementName) throws XMLStreamException { final XMLEventReader reader = getEventReader(is); int count = 0; while (reader.hasNext()) { final XMLEvent event = reader.nextEvent(); if (event.getEventType() == XMLStreamConstants.START_ELEMENT && elementName.equals(event.asStartElement().getName().getLocalPart())) { count++; } } reader.close(); return count; }
Example 4
Source File: ReaderToWriterTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * Test: 6419687 NPE in XMLEventWriterImpl. */ @Test public void testCR6419687() { try { InputStream in = getClass().getResourceAsStream("ReaderToWriterTest.wsdl"); OutputStream out = new FileOutputStream(USER_DIR + "ReaderToWriterTest-out.xml"); XMLEventReader reader = XML_INPUT_FACTORY.createXMLEventReader(in); XMLEventWriter writer = XML_OUTPUT_FACTORY.createXMLEventWriter(out, "UTF-8"); while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); writer.add(event); } reader.close(); writer.close(); } catch (XMLStreamException xmlStreamException) { xmlStreamException.printStackTrace(); Assert.fail(xmlStreamException.toString()); } catch (FileNotFoundException fileNotFoundException) { fileNotFoundException.printStackTrace(); Assert.fail(fileNotFoundException.toString()); } }
Example 5
Source File: PooledUnmarshaller.java From sis with Apache License 2.0 | 5 votes |
/** * Unmarshals to the given input with on-the-fly substitution of namespaces. * This method is invoked when we may marshal a different GML or metadata version than the one * supported natively by SIS, i.e. when {@link #getTransformVersion()} returns a non-null value. * * @param input the reader created by SIS (<b>not</b> the reader given by the user). * @param version identify the namespace substitutions to perform. * @return the unmarshalled object. */ private Object unmarshal(XMLEventReader input, final TransformVersion version) throws XMLStreamException, JAXBException { input = new TransformingReader(input, version); final Context context = begin(); final Object object; try { object = unmarshaller.unmarshal(input); } finally { context.finish(); } input.close(); // Despite its name, this method does not close the underlying input stream. return object; }
Example 6
Source File: XMLUtilities.java From olingo-odata4 with Apache License 2.0 | 5 votes |
private void addAtomElement( final InputStream content, final XMLEventWriter writer) throws Exception { final XMLEventReader reader = getEventReader(content); final XMLEventFactory eventFactory = XMLEventFactory.newInstance(); XMLEvent newLine = eventFactory.createSpace("\n"); try { writer.add(newLine); while (reader.hasNext()) { final XMLEvent event = reader.nextEvent(); if (event.getEventType() != XMLStreamConstants.START_DOCUMENT && event.getEventType() != XMLStreamConstants.END_DOCUMENT && event.getEventType() != XMLStreamConstants.COMMENT) { writer.add(event); } } writer.add(newLine); } finally { reader.close(); IOUtils.closeQuietly(content); } }
Example 7
Source File: XMLUtilities.java From olingo-odata4 with Apache License 2.0 | 5 votes |
/** * {@inheritDoc } */ @Override protected Set<String> retrieveAllLinkNames(final InputStream is) throws Exception { final Set<String> links = new HashSet<String>(); final XMLEventReader reader = getEventReader(is); try { int startDepth = 0; while (true) { final Map.Entry<Integer, XMLElement> linkInfo = extractElement(reader, null, Collections.<String> singletonList(Constants.get(ConstantKey.LINK)), startDepth, 2, 2); startDepth = linkInfo.getKey(); links.add(linkInfo.getValue().getStart().getAttributeByName(new QName("title")).getValue()); } } catch (Exception ignore) { // ignore } finally { reader.close(); IOUtils.closeQuietly(is); } return links; }
Example 8
Source File: AbstractBinder.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public Binding bind(InputStream stream, Origin origin) { final XMLEventReader eventReader = createReader( stream, origin ); try { return doBind( eventReader, origin ); } finally { try { eventReader.close(); } catch (XMLStreamException e) { log.debug( "Unable to close StAX reader", e ); } } }
Example 9
Source File: Bug6976938Test.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
public void eventReaderTest(XMLInputFactory xif) { XMLEventReader eventReader = null; try { eventReader = xif.createXMLEventReader(this.getClass().getResourceAsStream(INPUT_FILE)); XMLEventReader filteredEventReader = xif.createFilteredReader(eventReader, new EventFilter() { public boolean accept(XMLEvent event) { if (!event.isStartElement()) { return false; } QName elementQName = event.asStartElement().getName(); if ((elementQName.getLocalPart().equals(ATTACHMENT_NAME.getLocalPart()) || elementQName.getLocalPart().equals("Attachment")) && elementQName.getNamespaceURI().equals(VF_GENERIC_TT_NAMESPACE)) { return true; } return false; } }); if (filteredEventReader.hasNext()) { System.out.println("containsAttachments() returns true"); } } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); } finally { if (eventReader != null) { try { eventReader.close(); } catch (XMLStreamException xse) { // Ignored by intention } } } }
Example 10
Source File: ReaderToWriterTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
private void writeEvents(XMLEventReader reader, XMLEventWriter writer) throws XMLStreamException { while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); writer.add(event); } reader.close(); writer.close(); }
Example 11
Source File: ReaderToWriterTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
private void checkOutput(String output) throws Exception { InputStream in = new FileInputStream(output); XMLEventReader reader = XML_INPUT_FACTORY.createXMLEventReader(in); while (reader.hasNext()) { reader.next(); } reader.close(); }
Example 12
Source File: XmlOutputStreamFilter.java From KeePassJava2 with Apache License 2.0 | 5 votes |
public XmlOutputStreamFilter(final OutputStream outputStream, final XmlEventTransformer eventTransformer) throws IOException { super(); pipedInputStream = new PipedInputStream(this); Callable<Boolean> output = new Callable<Boolean>() { public Boolean call() { try { XMLEventReader eventReader = new com.fasterxml.aalto.stax.InputFactoryImpl() .createXMLEventReader(pipedInputStream); XMLEventWriter eventWriter = new com.fasterxml.aalto.stax.OutputFactoryImpl() .createXMLEventWriter(outputStream); XMLEvent event = null; while (eventReader.hasNext()) { event = eventReader.nextEvent(); event = eventTransformer.transform(event); eventWriter.add(event); eventWriter.flush(); } eventReader.close(); eventWriter.flush(); eventWriter.close(); outputStream.flush(); outputStream.close(); } catch (XMLStreamException | IOException e) { throw new IllegalStateException(e); } return true; } }; future = Executors.newSingleThreadExecutor().submit(output); }
Example 13
Source File: XMLUtilities.java From olingo-odata4 with Apache License 2.0 | 4 votes |
@Override public InputStream addEditLink( final InputStream content, final String title, final String href) throws Exception { final ByteArrayOutputStream copy = new ByteArrayOutputStream(); IOUtils.copy(content, copy); IOUtils.closeQuietly(content); XMLEventReader reader = getEventReader(new ByteArrayInputStream(copy.toByteArray())); ByteArrayOutputStream bos = new ByteArrayOutputStream(); XMLEventWriter writer = getEventWriter(bos); final String editLinkElement = String.format("<link rel=\"edit\" title=\"%s\" href=\"%s\" />", title, href); try { // check edit link existence extractElement(reader, writer, Collections.<String> singletonList(Constants.get(ConstantKey.LINK)), Collections.<Map.Entry<String, String>> singletonList( new AbstractMap.SimpleEntry<String, String>("rel", "edit")), false, 0, -1, -1); addAtomElement(IOUtils.toInputStream(editLinkElement, Constants.ENCODING), writer); writer.add(reader); } catch (Exception e) { reader.close(); reader = getEventReader(new ByteArrayInputStream(copy.toByteArray())); bos = new ByteArrayOutputStream(); writer = getEventWriter(bos); final XMLElement entryElement = extractElement(reader, writer, Collections.<String> singletonList("entry"), 0, 1, 1).getValue(); writer.add(entryElement.getStart()); addAtomElement(IOUtils.toInputStream(editLinkElement, Constants.ENCODING), writer); writer.add(entryElement.getContentReader()); writer.add(entryElement.getEnd()); writer.add(reader); writer.flush(); writer.close(); } finally { reader.close(); } return new ByteArrayInputStream(bos.toByteArray()); }
Example 14
Source File: Metadata.java From olingo-odata4 with Apache License 2.0 | 4 votes |
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 15
Source File: DrawSimpleShape.java From lams with GNU General Public License v2.0 | 4 votes |
protected static CustomGeometry getCustomGeometry(String name, Graphics2D graphics) { @SuppressWarnings("unchecked") Map<String, CustomGeometry> presets = (graphics == null) ? null : (Map<String, CustomGeometry>)graphics.getRenderingHint(Drawable.PRESET_GEOMETRY_CACHE); if (presets == null) { presets = new HashMap<String,CustomGeometry>(); if (graphics != null) { graphics.setRenderingHint(Drawable.PRESET_GEOMETRY_CACHE, presets); } String packageName = "org.apache.poi.sl.draw.binding"; InputStream presetIS = Drawable.class.getResourceAsStream("presetShapeDefinitions.xml"); // StAX: EventFilter startElementFilter = new EventFilter() { @Override public boolean accept(XMLEvent event) { return event.isStartElement(); } }; try { XMLInputFactory staxFactory = StaxHelper.newXMLInputFactory(); XMLEventReader staxReader = staxFactory.createXMLEventReader(presetIS); XMLEventReader staxFiltRd = staxFactory.createFilteredReader(staxReader, startElementFilter); // Ignore StartElement: staxFiltRd.nextEvent(); // JAXB: JAXBContext jaxbContext = JAXBContext.newInstance(packageName); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); while (staxFiltRd.peek() != null) { StartElement evRoot = (StartElement)staxFiltRd.peek(); String cusName = evRoot.getName().getLocalPart(); // XMLEvent ev = staxReader.nextEvent(); JAXBElement<org.apache.poi.sl.draw.binding.CTCustomGeometry2D> el = unmarshaller.unmarshal(staxReader, CTCustomGeometry2D.class); CTCustomGeometry2D cusGeom = el.getValue(); presets.put(cusName, new CustomGeometry(cusGeom)); } staxFiltRd.close(); staxReader.close(); } catch (Exception e) { throw new RuntimeException("Unable to load preset geometries.", e); } finally { IOUtils.closeQuietly(presetIS); } } return presets.get(name); }
Example 16
Source File: XMLUtilities.java From olingo-odata4 with Apache License 2.0 | 4 votes |
@Override protected InputStream replaceLink( final InputStream toBeChanged, final String linkName, final InputStream replacement) throws Exception { final XMLEventReader reader = getEventReader(toBeChanged); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final XMLEventWriter writer = getEventWriter(bos); final XMLEventFactory eventFactory = XMLEventFactory.newInstance(); XMLEvent newLine = eventFactory.createSpace("\n"); try { final XMLElement linkElement = extractElement(reader, writer, Collections.<String> singletonList(Constants.get(ConstantKey.LINK)), Collections.<Map.Entry<String, String>> singletonList( new SimpleEntry<String, String>("title", linkName)), false, 0, -1, -1).getValue(); writer.add(linkElement.getStart()); // ------------------------------------------ // write inline ... // ------------------------------------------ writer.add(newLine); writer.add(eventFactory.createStartElement("m", null, "inline")); addAtomElement(replacement, writer); writer.add(eventFactory.createEndElement("m", null, "inline")); writer.add(newLine); // ------------------------------------------ writer.add(linkElement.getEnd()); writer.add(reader); writer.flush(); writer.close(); } finally { reader.close(); IOUtils.closeQuietly(toBeChanged); } return new ByteArrayInputStream(bos.toByteArray()); }
Example 17
Source File: XmlModifier.java From neoscada with Eclipse Public License 1.0 | 4 votes |
public void set ( final String expression, final int targetElement, final String value ) throws IOException, XMLStreamException { int pos = 0; final Stack<String> ele = new Stack<> (); final Pattern pattern = Pattern.compile ( expression ); final XMLEventReader reader; Modification mod = null; final XMLInputFactory xmlinf = XMLInputFactory.newInstance (); try (final FileInputStream is = new FileInputStream ( this.inputFile )) { reader = xmlinf.createXMLEventReader ( is ); try { while ( reader.hasNext () ) { final XMLEvent event = (XMLEvent)reader.next (); if ( event instanceof StartElement ) { final StartElement startEvent = event.asStartElement (); ele.push ( startEvent.getName ().getLocalPart () ); } else if ( event instanceof EndElement ) { final EndElement endEvent = event.asEndElement (); final String en = ele.pop (); if ( !endEvent.getName ().getLocalPart ().equals ( en ) ) { throw new IllegalStateException ( "Element error: " + en + " / " + endEvent.getName () ); } } boolean inMatch = mod != null; final boolean match = isMatch ( ele, pattern ); if ( inMatch && !match ) { // end if ( pos == targetElement ) { this.mods.add ( mod ); } pos++; mod = null; } else if ( !inMatch && match ) { // starting mod = new Modification (); mod.start = event.getLocation ().getCharacterOffset (); mod.data = value; } else if ( inMatch && match ) { mod.end = event.getLocation ().getCharacterOffset () - 2; } inMatch = match; } } finally { reader.close (); } } }
Example 18
Source File: XmlIndentation.java From butterfly with MIT License | 4 votes |
/** * Returns a String that represents the indentation used in the very first * tag, inside the root tag, in the given XML file. * Returns {@code null} if the root tag has no children, * or if the first tag is at the same line as the root tag. * * @param xmlFile XML file to be evaluated * @return a String that represents the indentation used in the very first tag, * inside the root tag, in the given XML file * @throws FileNotFoundException if the given file does not exist * @throws XMLStreamException if an error occurs when reading the XML file */ public static String getFirst(File xmlFile) throws XMLStreamException, FileNotFoundException { // first occurrences of a set of ignored characters in between elements String firstElementsGap = null; boolean rootElementConsumed = false; boolean firstElementConsumed = false; XMLEvent xmlEvent; XMLEventReader reader = null; try { reader = xmlInputFactory.createXMLEventReader(new FileInputStream(xmlFile)); while (reader.hasNext()) { xmlEvent = reader.nextEvent(); if (xmlEvent.isCharacters() && !xmlEvent.asCharacters().isCData()) { firstElementsGap = xmlEvent.asCharacters().getData(); } else if (xmlEvent.isStartElement()) { if (rootElementConsumed) { firstElementConsumed = true; break; } else { rootElementConsumed = true; } } } reader.close(); } finally { if (reader != null) { reader.close(); } } String indentationSample = null; if (firstElementConsumed && firstElementsGap != null) { int i = firstElementsGap.lastIndexOf('\n') + 1; indentationSample = firstElementsGap.substring(i); } return indentationSample; }
Example 19
Source File: ResourceCompiler.java From bazel with Apache License 2.0 | 4 votes |
private void extractAttributes(String type, String filename, List<Path> results) throws Exception { XMLEventReader xmlEventReader = null; try { // aapt2 compile strips out namespaces and attributes from the resources tag. // Read them here separately and package them with the other flat files. xmlEventReader = XMLInputFactory.newInstance() .createXMLEventReader(new FileInputStream(file.toString())); // Iterate through the XML until we find a start element. // This should mimic xmlEventReader.nextTag() except that it also skips DTD elements. StartElement rootElement = null; while (xmlEventReader.hasNext()) { XMLEvent event = xmlEventReader.nextEvent(); if (event.getEventType() != XMLStreamConstants.COMMENT && event.getEventType() != XMLStreamConstants.DTD && event.getEventType() != XMLStreamConstants.PROCESSING_INSTRUCTION && event.getEventType() != XMLStreamConstants.SPACE && event.getEventType() != XMLStreamConstants.START_DOCUMENT) { // If the event should not be skipped, try parsing it as a start element here. // If the event is not a start element, an appropriate exception will be thrown. rootElement = event.asStartElement(); break; } } if (rootElement == null) { throw new Exception("No start element found in resource XML file: " + file.toString()); } Iterator<Attribute> attributeIterator = XmlResourceValues.iterateAttributesFrom(rootElement); if (attributeIterator.hasNext()) { results.add(createAttributesProto(type, filename, attributeIterator)); } } finally { if (xmlEventReader != null) { xmlEventReader.close(); } } }
Example 20
Source File: ArtifactsXmlAbsoluteUrlRemover.java From nexus-repository-p2 with Eclipse Public License 1.0 | 4 votes |
private TempBlob transformXmlMetadata(final TempBlob artifact, final Repository repository, final String file, final String extension, final XmlStreamTransformer transformer) throws IOException { Path tempFile = createTempFile("", ".xml"); // This is required in the case that the input stream is a jar to allow us to extract a single file Path artifactsTempFile = createTempFile("", ".xml"); try { try (InputStream xmlIn = xmlInputStream(artifact, file + "." + "xml", extension, artifactsTempFile); OutputStream xmlOut = xmlOutputStream(file + "." + "xml", extension, tempFile)) { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); inputFactory.setProperty(SUPPORT_DTD, false); inputFactory.setProperty(IS_SUPPORTING_EXTERNAL_ENTITIES, false); XMLOutputFactory outputFactory = XMLOutputFactory.newFactory(); XMLEventReader reader = null; XMLEventWriter writer = null; //try-with-resources will be better here, but XMLEventReader and XMLEventWriter are not AutoCloseable try { reader = inputFactory.createXMLEventReader(xmlIn); writer = outputFactory.createXMLEventWriter(xmlOut); transformer.transform(reader, writer); writer.flush(); } finally { if (reader != null) { reader.close(); } if (writer != null) { writer.close(); } } } catch (XMLStreamException ex) { log.error("Failed to rewrite metadata for file with extension {} and blob {} with reason: {} ", ex, artifact.getBlob().getId(), ex); return artifact; } return convertFileToTempBlob(tempFile, repository); } finally { delete(tempFile); delete(artifactsTempFile); } }