List of usage examples for javax.xml.stream XMLInputFactory newFactory
public static XMLInputFactory newFactory() throws FactoryConfigurationError
From source file:net.sf.jabref.logic.importer.fileformat.MedlineImporter.java
@Override public ParserResult importDatabase(BufferedReader reader) throws IOException { Objects.requireNonNull(reader); List<BibEntry> bibItems = new ArrayList<>(); try {//from w w w. j a va 2 s. c o m JAXBContext context = JAXBContext.newInstance("net.sf.jabref.logic.importer.fileformat.medline"); XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory(); XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(reader); //go to the root element while (!xmlStreamReader.isStartElement()) { xmlStreamReader.next(); } Unmarshaller unmarshaller = context.createUnmarshaller(); Object unmarshalledObject = unmarshaller.unmarshal(xmlStreamReader); //check whether we have an article set, an article, a book article or a book article set if (unmarshalledObject instanceof PubmedArticleSet) { PubmedArticleSet articleSet = (PubmedArticleSet) unmarshalledObject; for (Object article : articleSet.getPubmedArticleOrPubmedBookArticle()) { if (article instanceof PubmedArticle) { PubmedArticle currentArticle = (PubmedArticle) article; parseArticle(currentArticle, bibItems); } if (article instanceof PubmedBookArticle) { PubmedBookArticle currentArticle = (PubmedBookArticle) article; parseBookArticle(currentArticle, bibItems); } } } else if (unmarshalledObject instanceof PubmedArticle) { PubmedArticle article = (PubmedArticle) unmarshalledObject; parseArticle(article, bibItems); } else if (unmarshalledObject instanceof PubmedBookArticle) { PubmedBookArticle currentArticle = (PubmedBookArticle) unmarshalledObject; parseBookArticle(currentArticle, bibItems); } else { PubmedBookArticleSet bookArticleSet = (PubmedBookArticleSet) unmarshalledObject; for (PubmedBookArticle bookArticle : bookArticleSet.getPubmedBookArticle()) { parseBookArticle(bookArticle, bibItems); } } } catch (JAXBException | XMLStreamException e) { LOGGER.debug("could not parse document", e); return ParserResult.fromErrorMessage(e.getLocalizedMessage()); } return new ParserResult(bibItems); }
From source file:org.javelin.sws.ext.bind.jaxb.JaxbTest.java
@Test public void namespacesOfAttributes() throws Exception { XMLEventReader reader = XMLInputFactory.newFactory().createXMLEventReader( new ClassPathResource("org/javelin/sws/ext/bind/jaxb/context6/1.xml").getInputStream()); reader.nextEvent();//ww w. j av a 2s .c o m StartElement start = reader.nextEvent().asStartElement(); for (Iterator<?> it = start.getAttributes(); it.hasNext();) { System.out.println(((Attribute) it.next()).getName()); } System.out.println("---"); reader = XMLInputFactory.newFactory().createXMLEventReader( new ClassPathResource("org/javelin/sws/ext/bind/jaxb/context6/2.xml").getInputStream()); reader.nextEvent(); start = reader.nextEvent().asStartElement(); for (Iterator<?> it = start.getAttributes(); it.hasNext();) { System.out.println(((Attribute) it.next()).getName()); } System.out.println("---"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document doc1 = dbf.newDocumentBuilder().parse(new InputSource( new ClassPathResource("org/javelin/sws/ext/bind/jaxb/context6/1.xml").getInputStream())); NamedNodeMap attributes1 = doc1.getDocumentElement().getAttributes(); for (int i = 0; i < attributes1.getLength(); i++) System.out.println(((org.w3c.dom.Attr) attributes1.item(i)).getName() + " (" + ((org.w3c.dom.Attr) attributes1.item(i)).getNamespaceURI() + ")"); System.out.println("---"); doc1 = dbf.newDocumentBuilder().parse(new InputSource( new ClassPathResource("org/javelin/sws/ext/bind/jaxb/context6/2.xml").getInputStream())); attributes1 = doc1.getDocumentElement().getAttributes(); for (int i = 0; i < attributes1.getLength(); i++) System.out.println(((org.w3c.dom.Attr) attributes1.item(i)).getName() + " (" + ((org.w3c.dom.Attr) attributes1.item(i)).getNamespaceURI() + ")"); System.out.println("---"); doc1 = dbf.newDocumentBuilder().parse(new InputSource( new ClassPathResource("org/javelin/sws/ext/bind/jaxb/context6/3.xml").getInputStream())); attributes1 = doc1.getDocumentElement().getAttributes(); for (int i = 0; i < attributes1.getLength(); i++) System.out.println(((org.w3c.dom.Attr) attributes1.item(i)).getName() + " (" + ((org.w3c.dom.Attr) attributes1.item(i)).getNamespaceURI() + ")"); }
From source file:com.auditbucket.client.Importer.java
static long processXMLFile(String file, AbRestClient abExporter, XmlMappable mappable, boolean simulateOnly) throws ParserConfigurationException, IOException, SAXException, JDOMException, DatagioException { try {//from w ww . j av a 2s . c o m long rows = 0; StopWatch watch = new StopWatch(); StreamSource source = new StreamSource(file); XMLInputFactory xif = XMLInputFactory.newFactory(); XMLStreamReader xsr = xif.createXMLStreamReader(source); mappable.positionReader(xsr); List<CrossReferenceInputBean> referenceInputBeans = new ArrayList<>(); String docType = mappable.getDataType(); watch.start(); try { long then = new DateTime().getMillis(); while (xsr.getLocalName().equals(docType)) { XmlMappable row = mappable.newInstance(simulateOnly); String json = row.setXMLData(xsr); MetaInputBean header = (MetaInputBean) row; if (!header.getCrossReferences().isEmpty()) { referenceInputBeans.add(new CrossReferenceInputBean(header.getFortress(), header.getCallerRef(), header.getCrossReferences())); rows = rows + header.getCrossReferences().size(); } LogInputBean logInputBean = new LogInputBean("system", new DateTime(header.getWhen()), json); header.setLog(logInputBean); //logger.info(json); xsr.nextTag(); writeAudit(abExporter, header, mappable.getClass().getCanonicalName()); rows++; if (rows % 500 == 0 && !simulateOnly) logger.info("Processed {} elapsed seconds {}", rows, new DateTime().getMillis() - then / 1000d); } } finally { abExporter.flush(mappable.getClass().getCanonicalName(), mappable.getABType()); } if (!referenceInputBeans.isEmpty()) { logger.debug("Wrote [{}] cross references", writeCrossReferences(abExporter, referenceInputBeans, "Cross References")); } return endProcess(watch, rows); } catch (XMLStreamException | JAXBException e1) { throw new IOException(e1); } }
From source file:com.predic8.membrane.core.interceptor.rest.REST2SOAPInterceptor.java
private String getRootElementNamespace(InputStream stream) { try {/*w w w . ja va 2s . c o m*/ XMLEventReader xer = XMLInputFactory.newFactory().createXMLEventReader(stream); while (xer.hasNext()) { XMLEvent event = xer.nextEvent(); if (event.isStartElement()) return event.asStartElement().getName().getNamespaceURI(); } } catch (XMLStreamException e) { log.error("Could not determine root element namespace for check whether namespace is SOAP 1.2.", e); } return null; }
From source file:edu.stanford.cfuller.colocalization3d.correction.Correction.java
/** * Reads a stored correction from disk./*www .j ava 2 s.c o m*/ * * @param filename The name of the file containing the Correction that was previously written to disk. * @return The Correction contained in the file. * @throws java.io.IOException if the Correction cannot be successfully read. * @throws ClassNotFoundException if the file does not contain a Correction. */ public static Correction readFromDisk(String filename) throws java.io.IOException, ClassNotFoundException { File f = new File(filename); FileReader fr = new FileReader(f); XMLStreamReader xsr = null; String encBinData = null; try { xsr = XMLInputFactory.newFactory().createXMLStreamReader(fr); while (xsr.hasNext()) { int event = xsr.next(); if (event != XMLStreamReader.START_ELEMENT) continue; if (xsr.hasName() && xsr.getLocalName() == BINARY_DATA_ELEMENT) { encBinData = xsr.getElementText(); break; } } } catch (XMLStreamException e) { java.util.logging.Logger.getLogger(LOG_NAME) .severe("Exception encountered while reading XML correction: " + e.getMessage()); } byte[] binData = (new HexBinaryAdapter()).unmarshal(encBinData); ObjectInputStream oi = new ObjectInputStream(new ByteArrayInputStream(binData)); Object o = oi.readObject(); return (Correction) o; }
From source file:net.solarnetwork.util.JavaBeanXmlSerializer.java
private XMLStreamReader startParse(InputStream in) { XMLStreamReader reader = null; try {// w w w.ja v a2 s. c o m reader = XMLInputFactory.newFactory().createXMLStreamReader(in); } catch (XMLStreamException e) { throw new RuntimeException(e); } catch (FactoryConfigurationError e) { throw new RuntimeException(e); } return reader; }
From source file:com.ggvaidya.scinames.model.Project.java
public static Project loadFromFile(File loadFromFile) throws IOException { Project project = null;//from w ww .ja va 2 s . c om XMLInputFactory factory = XMLInputFactory.newFactory(); factory.setXMLReporter(new XMLReporter() { @Override public void report(String message, String errorType, Object relatedInformation, Location location) throws XMLStreamException { LOGGER.warning(errorType + " while loading project from XML file '" + loadFromFile + "': " + message + " (related info: " + relatedInformation.toString() + ", location: " + location); } }); try { XMLEventReader reader = factory.createXMLEventReader( new XmlStreamReader(new GZIPInputStream(new FileInputStream(loadFromFile)))); project = ProjectXMLReader.read(reader); project.setFile(loadFromFile); project.lastModifiedProperty().saved(); reader.close(); } catch (XMLStreamException ex) { throw new IOException("Could not read project from XML file '" + loadFromFile + "': " + ex, ex); } return project; /* DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // Configure upcoming document builder. dbf.setIgnoringComments(true); dbf.setIgnoringElementContentWhitespace(true); Document docProject; try { DocumentBuilder db = dbf.newDocumentBuilder(); docProject = db.parse(loadFromFile); } catch (SAXException ex) { throw new IOException("Could not load project XML file: " + ex); } catch (ParserConfigurationException ex) { throw new RuntimeException("Could not load XML parser configuration: " + ex); } // Load project. Project newProject; try { newProject = serializeFromDocument(docProject, loadFromFile); } catch(SAXException e) { throw new IOException("XML file loaded but project could not be read: " + e); } catch(IllegalStateException e) { throw new IOException("XML file contains errors in content: " + e); } return newProject; */ }
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 ww . jav a 2 s . c o 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:net.sourceforge.subsonic.service.ITunesParser.java
public ITunesParser(String iTunesXml) { this.iTunesXml = iTunesXml; inputFactory = XMLInputFactory.newFactory(); inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); }
From source file:org.apache.hadoop.gateway.filter.rewrite.impl.xml.XmlFilterReader.java
protected XmlFilterReader(Reader reader, UrlRewriteFilterContentDescriptor config) throws IOException, XMLStreamException { this.reader = reader; this.config = config; writer = new StringWriter(); buffer = writer.getBuffer();/*from w w w . ja va 2 s . co m*/ offset = 0; document = null; stack = new Stack<Level>(); isEmptyElement = false; factory = XMLInputFactory.newFactory(); //KNOX-620 factory.setProperty( XMLConstants.ACCESS_EXTERNAL_DTD, "false" ); //KNOX-620 factory.setProperty( XMLConstants.ACCESS_EXTERNAL_SCHEMA, "false" ); factory.setProperty("javax.xml.stream.isReplacingEntityReferences", Boolean.FALSE); factory.setProperty("http://java.sun.com/xml/stream/" + "properties/report-cdata-event", Boolean.TRUE); parser = factory.createXMLEventReader(reader); }