List of usage examples for javax.xml.stream XMLInputFactory createXMLEventReader
public abstract XMLEventReader createXMLEventReader(java.io.InputStream stream) throws XMLStreamException;
From source file:com.github.lindenb.jvarkit.tools.blast.BlastFilterJS.java
@Override protected Collection<Throwable> call(String inputName) throws Exception { final CompiledScript compiledScript; Unmarshaller unmarshaller;/* w w w . j ava 2s . co m*/ Marshaller marshaller; try { compiledScript = super.compileJavascript(); JAXBContext jc = JAXBContext.newInstance("gov.nih.nlm.ncbi.blast"); unmarshaller = jc.createUnmarshaller(); marshaller = jc.createMarshaller(); XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory(); xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE); xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE); xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); PrintWriter pw = openFileOrStdoutAsPrintWriter(); XMLOutputFactory xof = XMLOutputFactory.newFactory(); xof.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE); XMLEventWriter w = xof.createXMLEventWriter(pw); StreamSource src = null; if (inputName == null) { LOG.info("Reading stdin"); src = new StreamSource(stdin()); } else { LOG.info("Reading file " + inputName); src = new StreamSource(new File(inputName)); } XMLEventReader r = xmlInputFactory.createXMLEventReader(src); XMLEventFactory eventFactory = XMLEventFactory.newFactory(); SimpleBindings bindings = new SimpleBindings(); while (r.hasNext()) { XMLEvent evt = r.peek(); switch (evt.getEventType()) { case XMLEvent.START_ELEMENT: { StartElement sE = evt.asStartElement(); Hit hit = null; JAXBElement<Hit> jaxbElement = null; if (sE.getName().getLocalPart().equals("Hit")) { jaxbElement = unmarshaller.unmarshal(r, Hit.class); hit = jaxbElement.getValue(); } else { w.add(r.nextEvent()); break; } if (hit != null) { bindings.put("hit", hit); boolean accept = super.evalJavaScriptBoolean(compiledScript, bindings); if (accept) { marshaller.marshal(jaxbElement, w); w.add(eventFactory.createCharacters("\n")); } } break; } case XMLEvent.SPACE: break; default: { w.add(r.nextEvent()); break; } } r.close(); } w.flush(); w.close(); pw.flush(); pw.close(); return RETURN_OK; } catch (Exception err) { return wrapException(err); } finally { } }
From source file:edu.unc.lib.dl.util.TripleStoreQueryServiceMulgaraImpl.java
/** * @param query/*from www. ja v a2s .com*/ * an ITQL command * @return the message returned by Mulgara * @throws RemoteException * for communication failure */ public String storeCommand(String query) { String result = null; String response = this.sendTQL(query); if (response != null) { XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); try (StringReader sr = new StringReader(response)) { XMLEventReader r = factory.createXMLEventReader(sr); boolean inMessage = false; StringBuffer message = new StringBuffer(); while (r.hasNext()) { XMLEvent e = r.nextEvent(); if (e.isStartElement()) { StartElement s = e.asStartElement(); if ("message".equals(s.getName().getLocalPart())) { inMessage = true; } } else if (e.isEndElement()) { EndElement end = e.asEndElement(); if ("message".equals(end.getName().getLocalPart())) { inMessage = false; } } else if (inMessage && e.isCharacters()) { message.append(e.asCharacters().getData()); } } r.close(); result = message.toString(); } catch (XMLStreamException e) { e.printStackTrace(); } } return result; }
From source file:WpRDFFunctionLibrary.java
public static void mergeGpmltoSingleFile(String gpmlLocation) throws IOException, XMLStreamException, ParserConfigurationException, SAXException, TransformerException { // Based on: http://stackoverflow.com/questions/10759775/how-to-merge-1000-xml-files-into-one-in-java //for (int i = 1; i < 8 ; i++) { Writer outputWriter = new FileWriter("/tmp/WpGPML.xml"); XMLOutputFactory xmlOutFactory = XMLOutputFactory.newFactory(); XMLEventWriter xmlEventWriter = xmlOutFactory.createXMLEventWriter(outputWriter); XMLEventFactory xmlEventFactory = XMLEventFactory.newFactory(); xmlEventWriter.add(xmlEventFactory.createStartDocument("ISO-8859-1", "1.0")); xmlEventWriter.add(xmlEventFactory.createStartElement("", null, "PathwaySet")); xmlEventWriter.add(xmlEventFactory.createAttribute("creationData", basicCalls.now())); XMLInputFactory xmlInFactory = XMLInputFactory.newFactory(); File dir = new File(gpmlLocation); File[] rootFiles = dir.listFiles(); //the section below is only in case of analysis sets for (File rootFile : rootFiles) { String fileName = FilenameUtils.removeExtension(rootFile.getName()); System.out.println(fileName); String[] identifiers = fileName.split("_"); System.out.println(fileName); String wpIdentifier = identifiers[identifiers.length - 2]; String wpRevision = identifiers[identifiers.length - 1]; //Pattern pattern = Pattern.compile("_(WP[0-9]+)_([0-9]+).gpml"); //Matcher matcher = pattern.matcher(fileName); //System.out.println(matcher.find()); //String wpIdentifier = matcher.group(1); File tempFile = new File(constants.localAllGPMLCacheDir() + wpIdentifier + "_" + wpRevision + ".gpml"); //System.out.println(matcher.group(1)); //String wpRevision = matcher.group(2); //System.out.println(matcher.group(2)); if (!(tempFile.exists())) { System.out.println(tempFile.getName()); Document currentGPML = basicCalls.openXmlFile(rootFile.getPath()); basicCalls.saveDOMasXML(WpRDFFunctionLibrary.addWpProvenance(currentGPML, wpIdentifier, wpRevision), constants.localCurrentGPMLCache() + tempFile.getName()); }/*from w w w.j a v a2 s . co m*/ } dir = new File("/tmp/GPML"); rootFiles = dir.listFiles(); for (File rootFile : rootFiles) { System.out.println(rootFile); XMLEventReader xmlEventReader = xmlInFactory.createXMLEventReader(new StreamSource(rootFile)); XMLEvent event = xmlEventReader.nextEvent(); // Skip ahead in the input to the opening document element try { while (event.getEventType() != XMLEvent.START_ELEMENT) { event = xmlEventReader.nextEvent(); } do { xmlEventWriter.add(event); event = xmlEventReader.nextEvent(); } while (event.getEventType() != XMLEvent.END_DOCUMENT); xmlEventReader.close(); } catch (Exception e) { System.out.println("Malformed gpml file"); } } xmlEventWriter.add(xmlEventFactory.createEndElement("", null, "PathwaySet")); xmlEventWriter.add(xmlEventFactory.createEndDocument()); xmlEventWriter.close(); outputWriter.close(); }
From source file:org.alex73.osm.converters.bel.Convert.java
public static void main(String[] args) throws Exception { loadStreetNamesForHouses();// ww w . ja v a 2s. co m InputStream in = new BZip2CompressorInputStream( new BufferedInputStream(new FileInputStream("tmp/belarus-latest.osm.bz2"), BUFFER_SIZE)); // create xml event reader for input stream XMLEventFactory eventFactory = XMLEventFactory.newInstance(); XMLEvent newLine = eventFactory.createCharacters("\n"); XMLInputFactory xif = XMLInputFactory.newInstance(); XMLOutputFactory xof = XMLOutputFactory.newInstance(); XMLEventReader reader = xif.createXMLEventReader(in); XMLEventWriter wrCyr = xof.createXMLEventWriter( new BufferedOutputStream(new FileOutputStream("tmp/belarus-bel.osm"), BUFFER_SIZE)); XMLEventWriter wrInt = xof.createXMLEventWriter( new BufferedOutputStream(new FileOutputStream("tmp/belarus-intl.osm"), BUFFER_SIZE)); // initialize jaxb JAXBContext jaxbCtx = JAXBContext.newInstance(Node.class, Way.class, Relation.class); Unmarshaller um = jaxbCtx.createUnmarshaller(); Marshaller m = jaxbCtx.createMarshaller(); m.setProperty(Marshaller.JAXB_FRAGMENT, true); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); XMLEvent e = null; while ((e = reader.peek()) != null) { boolean processed = false; if (e.isStartElement()) { StartElement se = (StartElement) e; switch (se.getName().getLocalPart()) { case "way": Way way = um.unmarshal(reader, Way.class).getValue(); if (way.getId() == 25439425) { System.out.println(); } fixBel(way.getTag(), "name:be", "name"); String nameBeHouse = houseStreetBe.get(way.getId()); if (nameBeHouse != null) { setTag(way.getTag(), "addr:street", nameBeHouse); } m.marshal(way, wrCyr); fixInt(way.getTag()); m.marshal(way, wrInt); wrCyr.add(newLine); wrInt.add(newLine); processed = true; break; case "node": Node node = um.unmarshal(reader, Node.class).getValue(); fixBel(node.getTag(), "name:be", "name"); // fixBel(node.getTag(),"addr:street:be","addr:street"); m.marshal(node, wrCyr); fixInt(node.getTag()); m.marshal(node, wrInt); wrCyr.add(newLine); wrInt.add(newLine); processed = true; break; case "relation": Relation relation = um.unmarshal(reader, Relation.class).getValue(); fixBel(relation.getTag(), "name:be", "name"); // fixBel(relation.getTag(),"addr:street:be","addr:street"); m.marshal(relation, wrCyr); fixInt(relation.getTag()); m.marshal(relation, wrInt); wrCyr.add(newLine); wrInt.add(newLine); processed = true; break; } } if (!processed) { wrCyr.add(e); wrInt.add(e); } reader.next(); } wrCyr.flush(); wrCyr.close(); wrInt.flush(); wrInt.close(); System.out.println("UniqueTranslatedTags: " + uniqueTranslatedTags); }
From source file:org.apache.hadoop.hdfs.tools.offlineImageViewer.OfflineImageReconstructor.java
private OfflineImageReconstructor(CountingOutputStream out, InputStreamReader reader) throws XMLStreamException { this.out = out; XMLInputFactory factory = XMLInputFactory.newInstance(); this.events = factory.createXMLEventReader(reader); this.sections = new HashMap<>(); this.sections.put(NameSectionProcessor.NAME, new NameSectionProcessor()); this.sections.put(INodeSectionProcessor.NAME, new INodeSectionProcessor()); this.sections.put(SecretManagerSectionProcessor.NAME, new SecretManagerSectionProcessor()); this.sections.put(CacheManagerSectionProcessor.NAME, new CacheManagerSectionProcessor()); this.sections.put(SnapshotDiffSectionProcessor.NAME, new SnapshotDiffSectionProcessor()); this.sections.put(INodeReferenceSectionProcessor.NAME, new INodeReferenceSectionProcessor()); this.sections.put(INodeDirectorySectionProcessor.NAME, new INodeDirectorySectionProcessor()); this.sections.put(FilesUnderConstructionSectionProcessor.NAME, new FilesUnderConstructionSectionProcessor()); this.sections.put(SnapshotSectionProcessor.NAME, new SnapshotSectionProcessor()); this.isoDateFormat = PBImageXmlWriter.createSimpleDateFormat(); }
From source file:org.apache.hadoop.util.ConfTest.java
private static List<NodeInfo> parseConf(InputStream in) throws XMLStreamException { QName configuration = new QName("configuration"); QName property = new QName("property"); List<NodeInfo> nodes = new ArrayList<NodeInfo>(); Stack<NodeInfo> parsed = new Stack<NodeInfo>(); XMLInputFactory factory = XMLInputFactory.newInstance(); XMLEventReader reader = factory.createXMLEventReader(in); while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); if (event.isStartElement()) { StartElement currentElement = event.asStartElement(); NodeInfo currentNode = new NodeInfo(currentElement); if (parsed.isEmpty()) { if (!currentElement.getName().equals(configuration)) { return null; }//w w w. j av a2s . c om } else { NodeInfo parentNode = parsed.peek(); QName parentName = parentNode.getStartElement().getName(); if (parentName.equals(configuration) && currentNode.getStartElement().getName().equals(property)) { @SuppressWarnings("unchecked") Iterator<Attribute> it = currentElement.getAttributes(); while (it.hasNext()) { currentNode.addAttribute(it.next()); } } else if (parentName.equals(property)) { parentNode.addElement(currentElement); } } parsed.push(currentNode); } else if (event.isEndElement()) { NodeInfo node = parsed.pop(); if (parsed.size() == 1) { nodes.add(node); } } else if (event.isCharacters()) { if (2 < parsed.size()) { NodeInfo parentNode = parsed.pop(); StartElement parentElement = parentNode.getStartElement(); NodeInfo grandparentNode = parsed.peek(); if (grandparentNode.getElement(parentElement) == null) { grandparentNode.setElement(parentElement, event.asCharacters()); } parsed.push(parentNode); } } } return nodes; }
From source file:org.apache.olingo.fit.utils.XMLEventReaderWrapper.java
public XMLEventReaderWrapper(final InputStream stream) throws IOException, XMLStreamException { final StringBuilder startBuilder = new StringBuilder(); startBuilder.append("<").append(CONTENT).append(" xmlns:m").append("=\"") .append(Constants.get(ConstantKey.METADATA_NS)).append("\"").append(" xmlns:d").append("=\"") .append(Constants.get(ConstantKey.DATASERVICES_NS)).append("\"").append(" xmlns:georss") .append("=\"").append(Constants.get(ConstantKey.GEORSS_NS)).append("\"").append(" xmlns:gml") .append("=\"").append(Constants.get(ConstantKey.GML_NS)).append("\"").append(">"); CONTENT_STAG = startBuilder.toString(); final XMLInputFactory factory = XMLInputFactory.newInstance(); final InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream( (CONTENT_STAG + IOUtils.toString(stream, ENCODING).replaceAll("^<\\?xml.*\\?>", "") + XMLEventReaderWrapper.CONTENT_ETAG).getBytes(ENCODING)), Constants.DECODER);//w w w. j a v a 2s . c om wrapped = factory.createXMLEventReader(reader); init(); }
From source file:org.apereo.portal.io.xml.IdentityImportExportTestUtilities.java
public static <T> void testIdentityImportExport(TransactionOperations transactionOperations, final IDataImporter<T> dataImporter, final IDataExporter<?> dataExporter, Resource resource, Function<T, String> getName) throws Exception { final String importData = toString(resource); final XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory(); final XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(new StringReader(importData)); //Unmarshall from XML final Unmarshaller unmarshaller = dataImporter.getUnmarshaller(); final StAXSource source = new StAXSource(xmlEventReader); @SuppressWarnings("unchecked") final T dataImport = (T) unmarshaller.unmarshal(source); //Make sure the data was unmarshalled assertNotNull("Unmarshalled import data was null", dataImport); //Import the data dataImporter.importData(dataImport); //Export the data final String name = getName.apply(dataImport); final Object dataExport = transactionOperations.execute(new TransactionCallback<Object>() { /* (non-Javadoc) * @see org.springframework.transaction.support.TransactionCallback#doInTransaction(org.springframework.transaction.TransactionStatus) *///from w w w . j ava 2 s. co m @Override public Object doInTransaction(TransactionStatus status) { return dataExporter.exportData(name); } }); //Make sure the data was exported assertNotNull("Exported data was null", dataExport); //Marshall to XML final Marshaller marshaller = dataExporter.getMarshaller(); final StringWriter result = new StringWriter(); marshaller.marshal(dataExport, new StreamResult(result)); //Compare the exported XML data with the imported XML data, they should match final String resultString = result.toString(); try { XMLUnit.setIgnoreWhitespace(true); Diff d = new Diff(new StringReader(importData), new StringReader(resultString)); assertTrue("Export result differs from import" + d, d.similar()); } catch (Exception e) { throw new XmlTestException("Failed to assert similar between import XML and export XML", resultString, e); } catch (Error e) { throw new XmlTestException("Failed to assert similar between import XML and export XML", resultString, e); } }
From source file:org.apereo.portal.io.xml.JaxbPortalDataHandlerService.java
protected BufferedXMLEventReader createSourceXmlEventReader(final Source source) { //If it is a StAXSource see if we can do better handling of it if (source instanceof StAXSource) { final StAXSource staxSource = (StAXSource) source; XMLEventReader xmlEventReader = staxSource.getXMLEventReader(); if (xmlEventReader != null) { if (xmlEventReader instanceof BufferedXMLEventReader) { final BufferedXMLEventReader bufferedXMLEventReader = (BufferedXMLEventReader) xmlEventReader; bufferedXMLEventReader.reset(); bufferedXMLEventReader.mark(-1); return bufferedXMLEventReader; }/*from w ww .j a v a 2 s .c o m*/ return new BufferedXMLEventReader(xmlEventReader, -1); } } final XMLInputFactory xmlInputFactory = this.xmlUtilities.getXmlInputFactory(); final XMLEventReader xmlEventReader; try { xmlEventReader = xmlInputFactory.createXMLEventReader(source); } catch (XMLStreamException e) { throw new RuntimeException("Failed to create XML Event Reader for data Source", e); } return new BufferedXMLEventReader(xmlEventReader, -1); }
From source file:org.apereo.portal.layout.dlm.DistributedLayoutManager.java
@Override public XMLEventReader getUserLayoutReader() { Document ul = this.getUserLayoutDOM(); if (ul == null) { throw new PortalException( "User layout has not been initialized for " + owner.getAttribute(IPerson.USERNAME)); }/*from w w w . j a v a 2 s. c o m*/ final XMLInputFactory xmlInputFactory = this.xmlUtilities.getXmlInputFactory(); final DOMSource layoutSoure = new DOMSource(ul); try { return xmlInputFactory.createXMLEventReader(layoutSoure); } catch (XMLStreamException e) { throw new RuntimeException( "Failed to create Layout XMLStreamReader for user: " + owner.getAttribute(IPerson.USERNAME), e); } }