List of usage examples for javax.xml.stream XMLInputFactory createXMLStreamReader
public abstract XMLStreamReader createXMLStreamReader(String systemId, java.io.Reader reader) throws XMLStreamException;
From source file:CursorApproachEventObject.java
public static void main(String[] args) throws Exception { String filename = "yourXML.xml"; XMLInputFactory xmlif = XMLInputFactory.newInstance(); xmlif.setEventAllocator(new XMLEventAllocatorImpl()); allocator = xmlif.getEventAllocator(); XMLStreamReader xmlr = xmlif.createXMLStreamReader(filename, new FileInputStream(filename)); int eventType = xmlr.getEventType(); while (xmlr.hasNext()) { eventType = xmlr.next();/* www.ja v a 2 s .c o m*/ if ((eventType == XMLStreamConstants.START_ELEMENT) && xmlr.getLocalName().equals("Book")) { StartElement event = getXMLEvent(xmlr).asStartElement(); System.out.println("EVENT: " + event.toString()); } } }
From source file:StaxCursorTest.java
public static void main(String[] args) throws Exception { String filename = "yourXML.xml"; XMLInputFactory xmlif = null; xmlif = XMLInputFactory.newInstance(); xmlif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE); xmlif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE); xmlif.setProperty(XMLInputFactory.IS_COALESCING, Boolean.FALSE); try {// w w w . j a v a2 s . c o m XMLStreamReader xmlr = xmlif.createXMLStreamReader(filename, new FileInputStream(filename)); int eventType = xmlr.getEventType(); printStartDocument(xmlr); while (xmlr.hasNext()) { eventType = xmlr.next(); printStartElement(xmlr); printEndElement(xmlr); printText(xmlr); printPIData(xmlr); printComment(xmlr); } } catch (XMLStreamException ex) { System.out.println(ex.getMessage()); if (ex.getNestedException() != null) { ex.getNestedException().printStackTrace(); } } }
From source file:com.predic8.membrane.integration.ProxyRuleTest.java
@Test public void testReadRuleFromByteBuffer() throws Exception { ProxyRule rule2 = new ProxyRule(); rule2.setRouter(router);//from w w w .ja va 2 s. c om XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader reader = factory.createXMLStreamReader((new ByteArrayInputStream(buffer)), Constants.UTF_8); while (reader.next() != XMLStreamReader.START_ELEMENT) ; rule2.parse(reader); assertEquals(8888, rule2.getKey().getPort()); assertEquals("Rule 1", rule2.getName()); assertNull(rule2.getLocalHost()); assertEquals(true, rule2.isInboundTLS()); assertFalse(rule2.isOutboundTLS()); List<Interceptor> inters = rule2.getInterceptors(); assertFalse(inters.isEmpty()); assertTrue(inters.size() == 2); inters.get(0).getId().equals("roundRobinBalancer"); inters.get(1).getId().equals("accessControlInterceptor"); assertEquals(true, rule2.isBlockResponse()); assertFalse(rule2.isBlockRequest()); }
From source file:com.graphhopper.reader.OSMInputFile.java
private void openXMLStream(InputStream in) throws XMLStreamException { XMLInputFactory factory = XMLInputFactory.newInstance(); parser = factory.createXMLStreamReader(bis, "UTF-8"); int event = parser.next(); if (event != XMLStreamConstants.START_ELEMENT || !parser.getLocalName().equalsIgnoreCase("osm")) { throw new IllegalArgumentException("File is not a valid OSM stream"); }//from w ww .j a va2 s . c om // See https://wiki.openstreetmap.org/wiki/PBF_Format#Definition_of_the_OSMHeader_fileblock String timestamp = parser.getAttributeValue(null, "osmosis_replication_timestamp"); if (timestamp == null) timestamp = parser.getAttributeValue(null, "timestamp"); if (timestamp != null) { try { fileheader = new OSMFileHeader(); fileheader.setTag("timestamp", timestamp); } catch (Exception ex) { } } eof = false; }
From source file:com.graphhopper.reader.osm.OSMInputFile.java
private void openXMLStream(InputStream in) throws XMLStreamException { XMLInputFactory factory = XMLInputFactory.newInstance(); parser = factory.createXMLStreamReader(in, "UTF-8"); int event = parser.next(); if (event != XMLStreamConstants.START_ELEMENT || !parser.getLocalName().equalsIgnoreCase("osm")) { throw new IllegalArgumentException("File is not a valid OSM stream"); }/* ww w. j a va2 s. c o m*/ // See https://wiki.openstreetmap.org/wiki/PBF_Format#Definition_of_the_OSMHeader_fileblock String timestamp = parser.getAttributeValue(null, "osmosis_replication_timestamp"); if (timestamp == null) timestamp = parser.getAttributeValue(null, "timestamp"); if (timestamp != null) { try { fileheader = new OSMFileHeader(); fileheader.setTag("timestamp", timestamp); } catch (Exception ex) { } } eof = false; }
From source file:au.org.ala.bhl.DocumentPaginator.java
public void paginate(String filename, PageHandler handler) { XMLInputFactory factory = XMLInputFactory.newInstance(); try {/*from w w w . j a v a 2 s. com*/ File f = new File(filename); if (f.length() == 0) { // empty file, can't paginate... return; } XMLStreamReader parser = factory.createXMLStreamReader(new FileInputStream(f), "cp1252"); paginateImpl(parser, handler); } catch (Exception ex) { throw new RuntimeException("Failed to paginate " + filename, ex); } }
From source file:di.uniba.it.tee2.wiki.WikipediaDumpIterator.java
public WikipediaDumpIterator(File xmlFile, String encoding) throws XMLStreamException, FileNotFoundException, CompressorException, IOException { MediaWikiParserFactory parserFactory = new MediaWikiParserFactory(WikiConstants.Language.english); parserFactory.setTemplateParserClass(FlushTemplates.class); parserFactory.setShowImageText(false); parserFactory.setShowMathTagContent(false); parser = parserFactory.createParser(); XMLInputFactory inputFactory = XMLInputFactory.newInstance(); if (xmlFile.getName().endsWith(".bz2")) { logger.log(Level.INFO, "Trying to open Wikipedia compress dump (bzip2)..."); BZip2CompressorInputStream compressIS = new BZip2CompressorInputStream( new BufferedInputStream(new FileInputStream(xmlFile))); xmlStreamReader = inputFactory.createXMLStreamReader(compressIS, encoding); } else if (xmlFile.getName().endsWith(".gz")) { logger.log(Level.INFO, "Trying to open Wikipedia compress dump (gzip)..."); GZIPInputStream compressIS = new GZIPInputStream(new BufferedInputStream(new FileInputStream(xmlFile))); xmlStreamReader = inputFactory.createXMLStreamReader(compressIS, encoding); } else {//from ww w. ja v a 2 s.c o m logger.log(Level.INFO, "Trying to open Wikipedia plain text dump..."); xmlStreamReader = inputFactory .createXMLStreamReader(new BufferedInputStream(new FileInputStream(xmlFile)), encoding); } }
From source file:ca.efendi.datafeeds.messaging.FtpSubscriptionMessageListener.java
private void parse(FtpSubscription ftpSubscription, final InputStream is) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, true); factory.setProperty(XMLInputFactory.IS_COALESCING, true); final XMLStreamReader reader = factory.createXMLStreamReader(is, "UTF-8"); CJProduct product = null;//from ww w .jav a 2 s .com String tagContent = null; //final ServiceContext serviceContext = new ServiceContext(); //ServiceContext serviceContext = ServiceContextFactory.getInstance( // BlogsEntry.class.getName(), actionRequest); //serviceContext.setScopeGroupId(20159); while (reader.hasNext()) { final int event = reader.next(); switch (event) { case XMLStreamConstants.START_ELEMENT: //tagContent = ""; if ("product".equals(reader.getLocalName())) { product = _cjProductLocalService.createCJProduct(0); } break; case XMLStreamConstants.CHARACTERS: //tagContent += reader.getText().trim(); tagContent = reader.getText().trim(); break; case XMLStreamConstants.END_ELEMENT: switch (reader.getLocalName()) { case "product": try { _log.warn("refreshing document..."); _cjProductLocalService.refresh(ftpSubscription, product); } catch (final SystemException e) { _log.error(e); } catch (final PortalException e) { _log.error(e); } break; case "programname": product.setProgramName(tagContent); break; case "programurl": product.setProgramUrl(tagContent); break; case "catalogname": product.setCatalogName(tagContent); break; case "lastupdated": product.setLastUpdated(tagContent); break; case "name": product.setName(tagContent); break; case "keywords": product.setKeywords(tagContent); break; case "description": product.setDescription(tagContent); break; case "sku": product.setSku(tagContent); break; case "manufacturer": product.setManufacturer(tagContent); break; case "manufacturerid": product.setManufacturerId(tagContent); break; case "currency": product.setCurrency(tagContent); break; case "price": product.setPrice(tagContent); break; case "buyurl": product.setBuyUrl(tagContent); break; case "impressionurl": product.setImpressionUrl(tagContent); break; case "imageurl": product.setImageUrl(tagContent); break; case "instock": product.setInStock(tagContent); break; } break; case XMLStreamConstants.START_DOCUMENT: break; } } }
From source file:hudson.plugins.report.jck.parsers.JtregReportParser.java
@Override public Suite parsePath(Path path) { List<Test> testsList = new ArrayList<>(); try (ArchiveInputStream in = streamPath(path)) { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); ArchiveEntry entry;/*from w ww .j a v a 2 s . c o m*/ while ((entry = in.getNextEntry()) != null) { String entryName = entry.getName(); if (entryName == null || !entryName.endsWith(".jtr.xml")) { continue; } try { XMLStreamReader reader = inputFactory.createXMLStreamReader(new CloseShieldInputStream(in), "UTF-8"); testsList.addAll(parseTestsuites(reader)); } catch (Exception ex) { ex.printStackTrace(); } } } catch (Exception ex) { ex.printStackTrace(); } if (testsList.isEmpty()) { return null; } List<String> testNames = testsList.stream().sequential().map(t -> t.getName()).sorted() .collect(Collectors.toList()); List<Test> testProblems = testsList.stream().sequential() .filter(t -> t.getStatus() == TestStatus.ERROR || t.getStatus() == TestStatus.FAILED).sorted() .collect(Collectors.toList()); ReportFull fullReport = new ReportFull( (int) testsList.stream().sequential().filter(t -> t.getStatus() == TestStatus.PASSED).count(), (int) testsList.stream().sequential().filter(t -> t.getStatus() == TestStatus.NOT_RUN).count(), (int) testsList.stream().sequential().filter(t -> t.getStatus() == TestStatus.FAILED).count(), (int) testsList.stream().sequential().filter(t -> t.getStatus() == TestStatus.ERROR).count(), testsList.size(), testProblems, testNames); return new Suite(suiteName(path), fullReport); }
From source file:eu.delving.sip.xml.AnalysisParser.java
@Override public void run() { try {/* w ww . j av a 2 s. c o m*/ XMLInputFactory xmlif = XMLToolFactory.xmlInputFactory(); Path path = Path.create(); InputStream inputStream = null; if (dataSetModel.isEmpty()) return; try { switch (dataSetModel.getDataSetState()) { case IMPORTED: inputStream = dataSetModel.getDataSet().openImportedInputStream(); break; case SOURCED: inputStream = dataSetModel.getDataSet().openSourceInputStream(); stats.setRecordRoot(Storage.RECORD_ROOT); stats.sourceFormat = true; break; default: throw new IllegalStateException("Unexpected state: " + dataSetModel.getDataSetState()); } stats.name = dataSetModel.getDataSet().getDataSetFacts().get("name"); XMLStreamReader2 input = (XMLStreamReader2) xmlif.createXMLStreamReader(getClass().getName(), inputStream); StringBuilder text = new StringBuilder(); int count = 0; while (true) { switch (input.getEventType()) { case XMLEvent.START_ELEMENT: if (++count % ELEMENT_STEP == 0) { if (listener != null) progressListener.setProgress(count); } for (int walk = 0; walk < input.getNamespaceCount(); walk++) { stats.recordNamespace(input.getNamespacePrefix(walk), input.getNamespaceURI(walk)); } String chunk = text.toString().trim(); if (!chunk.isEmpty()) { stats.recordValue(path, chunk); } text.setLength(0); path = path.child(Tag.element(input.getName())); if (input.getAttributeCount() > 0) { for (int walk = 0; walk < input.getAttributeCount(); walk++) { QName attributeName = input.getAttributeName(walk); Path withAttr = path.child(Tag.attribute(attributeName)); stats.recordValue(withAttr, input.getAttributeValue(walk)); } } break; case XMLEvent.CHARACTERS: case XMLEvent.CDATA: text.append(input.getText()); break; case XMLEvent.END_ELEMENT: stats.recordValue(path, text.toString().trim()); text.setLength(0); path = path.parent(); break; } if (!input.hasNext()) break; input.next(); } } finally { IOUtils.closeQuietly(inputStream); } stats.finish(); listener.success(stats); } catch (CancelException e) { listener.failure("Cancellation", e); } catch (Exception e) { switch (dataSetModel.getDataSetState()) { case IMPORTED: case DELIMITED: FileUtils.deleteQuietly(dataSetModel.getDataSet().importedOutput()); break; case SOURCED: dataSetModel.getDataSet().deleteSource(); break; default: throw new IllegalStateException("Unexpected state " + dataSetModel.getDataSetState(), e); } listener.failure("The imported file contains errors, the file has been deleted", e); } }