List of usage examples for javax.xml.stream XMLEventReader close
public void close() throws XMLStreamException;
From source file:com.msopentech.odatajclient.testservice.utils.AbstractUtilities.java
private void initialize() throws Exception { if (!initialized.contains(version)) { final MetadataLinkInfo metadataLinkInfo = new MetadataLinkInfo(); Commons.linkInfo.put(version, metadataLinkInfo); final InputStream metadata = fsManager.readFile(Constants.METADATA, Accept.XML); final XMLEventReader reader = XMLUtilities.getEventReader(metadata); int initialDepth = 0; try {/*from w ww .java 2 s .c o m*/ while (true) { Map.Entry<Integer, XmlElement> entityType = XMLUtilities.getAtomElement(reader, null, "EntityType", null, initialDepth, 4, 4, false); initialDepth = entityType.getKey(); final String entitySetName = entityType.getValue().getStart() .getAttributeByName(new QName("Name")).getValue(); final XMLEventReader entityReader = XMLUtilities .getEventReader(entityType.getValue().toStream()); int size = 0; try { while (true) { final XmlElement navProperty = XMLUtilities.getAtomElement(entityReader, null, "NavigationProperty"); final String linkName = navProperty.getStart().getAttributeByName(new QName("Name")) .getValue(); final Map.Entry<String, Boolean> target = getTargetInfo(navProperty.getStart(), linkName); metadataLinkInfo.addLink(entitySetName, linkName, target.getKey(), target.getValue()); size++; } } catch (Exception e) { } finally { entityReader.close(); } if (size == 0) { metadataLinkInfo.addEntitySet(entitySetName); } } } catch (Exception e) { } finally { reader.close(); initialized.add(version); } } }
From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java
public InputStream addAtomContent(final InputStream content, final String title, final String href) throws Exception { final XMLOutputFactory xof = XMLOutputFactory.newInstance(); final ByteArrayOutputStream copy = new ByteArrayOutputStream(); IOUtils.copy(content, copy);/* www . j av a 2s . c o m*/ IOUtils.closeQuietly(content); XMLEventReader reader = getEventReader(new ByteArrayInputStream(copy.toByteArray())); ByteArrayOutputStream bos = new ByteArrayOutputStream(); XMLEventWriter writer = xof.createXMLEventWriter(bos); try { // check edit link existence XmlElement contentElement = getAtomElement(reader, writer, "content"); writer.add(contentElement.getStart()); writer.add(contentElement.getContentReader()); writer.add(contentElement.getEnd()); writer.add(reader); } catch (Exception e) { reader.close(); reader = getEventReader(new ByteArrayInputStream(copy.toByteArray())); bos = new ByteArrayOutputStream(); writer = xof.createXMLEventWriter(bos); if (isMediaContent(title)) { final XmlElement entryElement = getAtomElement(reader, writer, "entry"); writer.add(entryElement.getStart()); writer.add(entryElement.getContentReader()); addAtomElement( IOUtils.toInputStream(String.format("<content type=\"*/*\" src=\"%s/$value\" />", href)), writer); writer.add(entryElement.getEnd()); } else { try { final XmlElement entryElement = getAtomElement(reader, writer, PROPERTIES); addAtomElement(IOUtils.toInputStream("<content type=\"application/xml\">"), writer); writer.add(entryElement.getStart()); writer.add(entryElement.getContentReader()); writer.add(entryElement.getEnd()); addAtomElement(IOUtils.toInputStream("</content>"), writer); } catch (Exception nf) { reader.close(); reader = getEventReader(new ByteArrayInputStream(copy.toByteArray())); bos = new ByteArrayOutputStream(); writer = xof.createXMLEventWriter(bos); final XmlElement entryElement = getAtomElement(reader, writer, "entry"); writer.add(entryElement.getStart()); writer.add(entryElement.getContentReader()); addAtomElement(IOUtils.toInputStream("<content type=\"application/xml\"/>"), writer); writer.add(entryElement.getEnd()); } } writer.add(reader); writer.flush(); writer.close(); } finally { reader.close(); } return new ByteArrayInputStream(bos.toByteArray()); }
From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java
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 {/*from ww w . j a va2 s. co m*/ 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); } }
From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java
private InputStream addAtomEditLink(final InputStream content, final String title, final String href) throws Exception { final XMLOutputFactory xof = XMLOutputFactory.newInstance(); final ByteArrayOutputStream copy = new ByteArrayOutputStream(); IOUtils.copy(content, copy);/*from w ww .j a va 2 s .c o m*/ IOUtils.closeQuietly(content); XMLEventReader reader = getEventReader(new ByteArrayInputStream(copy.toByteArray())); ByteArrayOutputStream bos = new ByteArrayOutputStream(); XMLEventWriter writer = xof.createXMLEventWriter(bos); try { // check edit link existence final XmlElement editLink = getAtomElement(reader, writer, LINK, Collections.<Map.Entry<String, String>>singletonList( new AbstractMap.SimpleEntry<String, String>("rel", "edit"))); writer.add(editLink.getStart()); writer.add(editLink.getContentReader()); writer.add(editLink.getEnd()); writer.add(reader); } catch (Exception e) { reader.close(); reader = getEventReader(new ByteArrayInputStream(copy.toByteArray())); bos = new ByteArrayOutputStream(); writer = xof.createXMLEventWriter(bos); final XmlElement entryElement = getAtomElement(reader, writer, "entry"); writer.add(entryElement.getStart()); addAtomElement(IOUtils.toInputStream( String.format("<link rel=\"edit\" title=\"%s\" href=\"%s\" />", title, href)), writer); writer.add(entryElement.getContentReader()); writer.add(entryElement.getEnd()); writer.add(reader); writer.flush(); writer.close(); } finally { reader.close(); } return new ByteArrayInputStream(bos.toByteArray()); }
From source file:org.fcrepo.serialization.JcrXmlSerializer.java
private void validateJCRXML(final File file) throws InvalidSerializationFormatException, IOException { int depth = 0; try (final FileInputStream fis = new FileInputStream(file)) { final XMLEventReader reader = XMLInputFactory.newFactory().createXMLEventReader(fis); while (reader.hasNext()) { final XMLEvent event = reader.nextEvent(); if (event.isStartElement()) { depth++;/*from www .j a v a 2s .co m*/ final StartElement startElement = event.asStartElement(); final Attribute nameAttribute = startElement .getAttributeByName(new QName("http://www.jcp.org/jcr/sv/1.0", "name")); if (depth == 1 && nameAttribute != null && "jcr:content".equals(nameAttribute.getValue())) { throw new InvalidSerializationFormatException( "Cannot import JCR/XML starting with content node."); } if (depth == 1 && nameAttribute != null && "jcr:frozenNode".equals(nameAttribute.getValue())) { throw new InvalidSerializationFormatException("Cannot import historic versions."); } final QName name = startElement.getName(); if (!(name.getNamespaceURI().equals("http://www.jcp.org/jcr/sv/1.0") && (name.getLocalPart().equals("node") || name.getLocalPart().equals("property") || name.getLocalPart().equals("value")))) { throw new InvalidSerializationFormatException( "Unrecognized element \"" + name.toString() + "\", in import XML."); } } else { if (event.isEndElement()) { depth--; } } } reader.close(); } catch (XMLStreamException e) { throw new InvalidSerializationFormatException( "Unable to parse XML" + (e.getMessage() != null ? " (" + e.getMessage() + ")." : ".")); } }
From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java
public InputStream addAtomInlinecount(final InputStream feed, final int count, final Accept accept) throws Exception { final XMLEventReader reader = getEventReader(feed); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final XMLOutputFactory xof = XMLOutputFactory.newInstance(); final XMLEventWriter writer = xof.createXMLEventWriter(bos); try {/*from w ww .j a v a 2s.c o m*/ final XmlElement feedElement = getAtomElement(reader, writer, "feed"); writer.add(feedElement.getStart()); addAtomElement(IOUtils.toInputStream(String.format("<m:count>%d</m:count>", count)), writer); writer.add(feedElement.getContentReader()); writer.add(feedElement.getEnd()); while (reader.hasNext()) { writer.add(reader.nextEvent()); } } finally { writer.flush(); writer.close(); reader.close(); IOUtils.closeQuietly(feed); } return new ByteArrayInputStream(bos.toByteArray()); }
From source file:com.aionengine.gameserver.dataholders.loadingutils.XmlMerger.java
/** * This method processes the source file, replacing all of * the 'import' tags by the data from the relevant files. * * @throws XMLStreamException on event writing error. * @throws IOException if the destination file exists but is a directory rather than * a regular file, does not exist but cannot be created, * or cannot be opened for any other reason *//* ww w .ja v a 2 s. co m*/ private void doUpdate() throws XMLStreamException, IOException { XMLEventReader reader = null; XMLEventWriter writer = null; Properties metadata = new Properties(); try { writer = outputFactory.createXMLEventWriter(new BufferedWriter(new FileWriter(destFile, false))); reader = inputFactory.createXMLEventReader(new FileReader(sourceFile)); while (reader.hasNext()) { final XMLEvent xmlEvent = reader.nextEvent(); if (xmlEvent.isStartElement() && isImportQName(xmlEvent.asStartElement().getName())) { processImportElement(xmlEvent.asStartElement(), writer, metadata); continue; } if (xmlEvent.isEndElement() && isImportQName(xmlEvent.asEndElement().getName())) continue; if (xmlEvent instanceof Comment)// skip comments. continue; if (xmlEvent.isCharacters())// skip whitespaces. if (xmlEvent.asCharacters().isWhiteSpace() || xmlEvent.asCharacters().isIgnorableWhiteSpace())// skip whitespaces. continue; writer.add(xmlEvent); if (xmlEvent.isStartDocument()) { writer.add(eventFactory.createComment("\nThis file is machine-generated. DO NOT MODIFY IT!\n")); } } storeFileModifications(metadata, metaDataFile); } finally { if (writer != null) try { writer.close(); } catch (Exception ignored) { } if (reader != null) try { reader.close(); } catch (Exception ignored) { } } }
From source file:com.aionengine.gameserver.dataholders.loadingutils.XmlMerger.java
/** * Read all {@link javax.xml.stream.events.XMLEvent}'s from specified file and write them onto the {@link javax.xml.stream.XMLEventWriter} * * @param file File to import/*from w w w .j a v a 2s .c o m*/ * @param skipRoot Skip-root flag * @param writer Destenation writer * @throws XMLStreamException On event reading/writing error. * @throws FileNotFoundException if the reading file does not exist, * is a directory rather than a regular file, * or for some other reason cannot be opened for * reading. */ private void importFile(File file, boolean skipRoot, XMLEventWriter writer, Properties metadata) throws XMLStreamException, IOException { logger.debug("Appending file " + file); metadata.setProperty(file.getPath(), makeHash(file)); XMLEventReader reader = null; try { reader = inputFactory.createXMLEventReader(new FileReader(file)); QName firstTagQName = null; while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); // skip start and end of document. if (event.isStartDocument() || event.isEndDocument()) continue; // skip all comments. if (event instanceof Comment) continue; // skip white-spaces and all ignoreable white-spaces. if (event.isCharacters()) { if (event.asCharacters().isWhiteSpace() || event.asCharacters().isIgnorableWhiteSpace()) continue; } // modify root-tag of imported file. if (firstTagQName == null && event.isStartElement()) { firstTagQName = event.asStartElement().getName(); if (skipRoot) { continue; } else { StartElement old = event.asStartElement(); event = eventFactory.createStartElement(old.getName(), old.getAttributes(), null); } } // if root was skipped - skip root end too. if (event.isEndElement() && skipRoot && event.asEndElement().getName().equals(firstTagQName)) continue; // finally - write tag writer.add(event); } } finally { if (reader != null) try { reader.close(); } catch (Exception ignored) { } } }
From source file:com.aionemu.gameserver.dataholders.loadingutils.XmlMerger.java
/** * Read all {@link javax.xml.stream.events.XMLEvent}'s from specified file * and write them onto the {@link javax.xml.stream.XMLEventWriter} * * @param file File to import/*from w w w . j a v a2 s . c o m*/ * @param skipRoot Skip-root flag * @param writer Destenation writer * @throws XMLStreamException On event reading/writing error. * @throws FileNotFoundException if the reading file does not exist, is a * directory rather than a regular file, or for some other reason cannot be * opened for reading. */ private void importFile(File file, boolean skipRoot, XMLEventWriter writer, Properties metadata) throws XMLStreamException, IOException { logger.debug("Appending file " + file); metadata.setProperty(file.getPath(), makeHash(file)); XMLEventReader reader = null; try { reader = inputFactory.createXMLEventReader(new FileReader(file)); QName firstTagQName = null; while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); // skip start and end of document. if (event.isStartDocument() || event.isEndDocument()) { continue; } // skip all comments. if (event instanceof Comment) { continue; } // skip white-spaces and all ignoreable white-spaces. if (event.isCharacters()) { if (event.asCharacters().isWhiteSpace() || event.asCharacters().isIgnorableWhiteSpace()) { continue; } } // modify root-tag of imported file. if (firstTagQName == null && event.isStartElement()) { firstTagQName = event.asStartElement().getName(); if (skipRoot) { continue; } else { StartElement old = event.asStartElement(); event = eventFactory.createStartElement(old.getName(), old.getAttributes(), null); } } // if root was skipped - skip root end too. if (event.isEndElement() && skipRoot && event.asEndElement().getName().equals(firstTagQName)) { continue; } // finally - write tag writer.add(event); } } finally { if (reader != null) { try { reader.close(); } catch (Exception ignored) { } } } }
From source file:com.amazonaws.http.StaxRxNettyResponseHandler.java
@Override public Observable<AmazonWebServiceResponse<T>> handle(HttpClientResponse<ByteBuf> response) throws Exception { return response.getContent().reduce(new ByteArrayOutputStream(), new Func2<ByteArrayOutputStream, ByteBuf, ByteArrayOutputStream>() { @Override//w w w. j a v a 2s. c o m public ByteArrayOutputStream call(ByteArrayOutputStream out, ByteBuf bb) { try { bb.readBytes(out, bb.readableBytes()); return out; } catch (java.io.IOException e) { throw new RuntimeException(e); } finally { ReferenceCountUtil.safeRelease(bb); } } }).observeOn(RxSchedulers.computation()).flatMap(out -> { byte[] bytes = out.toByteArray(); if (bytes.length == 0) bytes = "<eof/>".getBytes(); ByteArrayInputStream in = new ByteArrayInputStream(bytes); XMLEventReader reader = null; try { reader = xmlInputFactory.createXMLEventReader(in); } catch (XMLStreamException e) { throw new RuntimeException(e); } try { Map<String, String> responseHeaders = new HashMap<String, String>(); for (String k : response.getHeaders().names()) { // TODO: comma seperated? responseHeaders.put(k, response.getHeaders().get(k)); } AmazonWebServiceResponse<T> awsResponse = new AmazonWebServiceResponse<T>(); StaxUnmarshallerContext unmarshallerContext = new StaxUnmarshallerContext(reader, responseHeaders); unmarshallerContext.registerMetadataExpression("ResponseMetadata/RequestId", 2, ResponseMetadata.AWS_REQUEST_ID); unmarshallerContext.registerMetadataExpression("requestId", 2, ResponseMetadata.AWS_REQUEST_ID); registerAdditionalMetadataExpressions(unmarshallerContext); T result = responseUnmarshaller.unmarshall(unmarshallerContext); awsResponse.setResult(result); Map<String, String> metadata = unmarshallerContext.getMetadata(); if (responseHeaders != null) { if (responseHeaders.get("x-amzn-RequestId") != null) { metadata.put(ResponseMetadata.AWS_REQUEST_ID, responseHeaders.get("x-amzn-RequestId")); } } awsResponse.setResponseMetadata(new ResponseMetadata(metadata)); return Observable.just(awsResponse); } catch (Exception e) { throw new RuntimeException(e); } finally { try { reader.close(); } catch (XMLStreamException e) { log.warn("Error closing xml parser", e); } } }); }