List of usage examples for javax.xml.stream XMLStreamReader getEventType
public int getEventType();
From source file:jodtemplate.io.xml.ContentTypesReader.java
@Override public ContentTypes read(final String path, final Resources resources, final XMLInputFactory xmlInputFactory, final ContentTypes contentTypes) throws XMLStreamException, IOException { final Resource contentTypesRes = resources.getResource(Utils.removePrefixSeparator(path)); try (final InputStream is = contentTypesRes.getInputStream()) { final XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(is); int event = xmlStreamReader.next(); while (event != XMLStreamConstants.END_DOCUMENT) { if (xmlStreamReader.getEventType() == XMLStreamConstants.START_ELEMENT) { final String elementNS = xmlStreamReader.getName().getNamespaceURI(); final String elementName = xmlStreamReader.getName().getLocalPart(); if (OOXMLDocument.DEFAULT_ELEMENT.equals(elementName) && OOXMLDocument.CONTENT_TYPES_NAMESPACE.equals(elementNS)) { contentTypes.addDefaultElement(createDefaultElement(xmlStreamReader)); }/*w w w. j a va2s. c o m*/ if (OOXMLDocument.OVERRIDE_ELEMENT.equals(elementName) && OOXMLDocument.CONTENT_TYPES_NAMESPACE.equals(elementNS)) { contentTypes.addOverrideElement(createOverrideElement(xmlStreamReader)); } } event = xmlStreamReader.next(); } } return contentTypes; }
From source file:wiki.link.LinkImporter.java
public boolean readXML(String filename) { //System.exit(1); //MAKE BLOODY SURE YOU HAVE SOME HOURS. DbConnector dbc = new DbConnector("localhost"); dbc.jdbcTemplate.update("TRUNCATE links;"); try {/* w ww.j a v a2 s. c o m*/ XMLInputFactory xif = XMLInputFactory.newInstance(); XMLStreamReader xsr = xif.createXMLStreamReader(new FileInputStream(filename)); long n = 0; List<Doc> toSave = new ArrayList<>(); while (xsr.hasNext()) { xsr.next(); if (xsr.getEventType() == XMLStreamReader.START_ELEMENT) { if (xsr.getLocalName().equals("page")) { long id = -1; String title = null; String text = null; while (xsr.hasNext()) { xsr.next(); if (xsr.getEventType() == XMLStreamReader.START_ELEMENT) { if (xsr.getLocalName().equals("id") && id == -1) { id = Long.parseLong(xsr.getElementText()); } if (xsr.getLocalName().equals("title")) { title = xsr.getElementText(); } if (xsr.getLocalName().equals("text")) { text = xsr.getElementText(); } } else if (xsr.getEventType() == XMLStreamReader.END_ELEMENT && xsr.getLocalName().equals("page")) { break; } } if (id != -1 && title != null && text != null) { Doc wd = new Doc(id, title, text); toSave.add(wd); n++; if (n % 1000 == 0) { insertLinks(toSave, dbc); // WikiDoc.insertAll(toSave, dbc); System.out.println(n); toSave.clear(); } } } } } } catch (IOException | XMLStreamException e) { e.printStackTrace(); } return true; }
From source file:de.huxhorn.sulky.plist.impl.PropertyListReader.java
private List<?> readArray(XMLStreamReader reader) throws XMLStreamException { reader.require(XMLStreamConstants.START_ELEMENT, null, ARRAY_NODE); reader.nextTag();//w w w. j a v a2s .com List<Object> array = new ArrayList<Object>(); for (;;) { int type = reader.getEventType(); if (XMLStreamConstants.END_ELEMENT == type && ARRAY_NODE.equals(reader.getLocalName())) { reader.nextTag(); break; } array.add(readValue(reader)); } return array; }
From source file:de.huxhorn.sulky.plist.impl.PropertyListReader.java
private Map<String, ?> readDict(XMLStreamReader reader) throws XMLStreamException { reader.require(XMLStreamConstants.START_ELEMENT, null, DICT_NODE); reader.nextTag();//w w w . ja v a 2 s .co m Map<String, Object> map = new HashMap<String, Object>(); for (;;) { int type = reader.getEventType(); if (XMLStreamConstants.END_ELEMENT == type && DICT_NODE.equals(reader.getLocalName())) { reader.nextTag(); break; } String key = StaxUtilities.readSimpleTextNodeIfAvailable(reader, null, KEY_NODE); if (key != null) { map.put(key, readValue(reader)); } } return map; }
From source file:com.microsoft.windowsazure.storage.table.TableParser.java
/** * Reserved for internal use. Parses the operation response as a collection of entities. Reads entity data from the * specified input stream using the specified class type and optionally projects each entity result with the * specified resolver into an {@link ODataPayload} containing a collection of {@link TableResult} objects. * // w w w . j av a 2 s.co m * @param inStream * The <code>InputStream</code> to read the data to parse from. * @param clazzType * The class type <code>T</code> implementing {@link TableEntity} for the entities returned. Set to * <code>null</code> to ignore the returned entities and copy only response properties into the * {@link TableResult} objects. * @param resolver * An {@link EntityResolver} instance to project the entities into instances of type <code>R</code>. Set * to <code>null</code> to return the entities as instances of the class type <code>T</code>. * @param opContext * An {@link OperationContext} object used to track the execution of the operation. * @return * An {@link ODataPayload} containing a collection of {@link TableResult} objects with the parsed operation * response. * * @throws XMLStreamException * if an error occurs while accessing the stream. * @throws ParseException * if an error occurs while parsing the stream. * @throws InstantiationException * if an error occurs while constructing the result. * @throws IllegalAccessException * if an error occurs in reflection while parsing the result. * @throws StorageException * if a storage service error occurs. */ @SuppressWarnings("unchecked") private static <T extends TableEntity, R> ODataPayload<?> parseAtomQueryResponse(final InputStream inStream, final Class<T> clazzType, final EntityResolver<R> resolver, final OperationContext opContext) throws XMLStreamException, ParseException, InstantiationException, IllegalAccessException, StorageException { ODataPayload<T> corePayload = null; ODataPayload<R> resolvedPayload = null; ODataPayload<?> commonPayload = null; if (resolver != null) { resolvedPayload = new ODataPayload<R>(); commonPayload = resolvedPayload; } else { corePayload = new ODataPayload<T>(); commonPayload = corePayload; } final XMLStreamReader xmlr = Utility.createXMLStreamReaderFromStream(inStream); int eventType = xmlr.getEventType(); xmlr.require(XMLStreamConstants.START_DOCUMENT, null, null); eventType = xmlr.next(); xmlr.require(XMLStreamConstants.START_ELEMENT, null, ODataConstants.FEED); // skip feed chars eventType = xmlr.next(); while (xmlr.hasNext()) { eventType = xmlr.next(); if (eventType == XMLStreamConstants.CHARACTERS) { xmlr.getText(); continue; } final String name = xmlr.getName().toString(); if (eventType == XMLStreamConstants.START_ELEMENT) { if (name.equals(ODataConstants.BRACKETED_ATOM_NS + ODataConstants.ENTRY)) { final TableResult res = parseAtomEntity(xmlr, clazzType, resolver, opContext); if (corePayload != null) { corePayload.tableResults.add(res); } if (resolver != null) { resolvedPayload.results.add((R) res.getResult()); } else { corePayload.results.add((T) res.getResult()); } } } else if (eventType == XMLStreamConstants.END_ELEMENT && name.equals(ODataConstants.BRACKETED_ATOM_NS + ODataConstants.FEED)) { break; } } xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.FEED); return commonPayload; }
From source file:davmail.exchange.dav.ExchangeDavMethod.java
protected String getTagContent(XMLStreamReader reader) throws XMLStreamException { String value = null;/*from ww w. j ava 2 s . co m*/ String tagLocalName = reader.getLocalName(); while (reader.hasNext() && !((reader.getEventType() == XMLStreamConstants.END_ELEMENT) && tagLocalName.equals(reader.getLocalName()))) { reader.next(); if (reader.getEventType() == XMLStreamConstants.CHARACTERS) { value = reader.getText(); } } // empty tag if (!reader.hasNext()) { throw new XMLStreamException("End element for " + tagLocalName + " not found"); } return value; }
From source file:com.sazneo.export.file.FileProcessor.java
/** * Process the XML file//from w ww .j av a 2 s . c om */ public void process() { try { Reader reader = new FileReader(exportFile); XMLInputFactory xmlFactory = XMLInputFactory.newInstance(); XMLStreamReader xmlStreamReader = xmlFactory.createXMLStreamReader(reader); boolean fileTag = false; String fileName = null; Integer fileSize = null; while (xmlStreamReader.hasNext()) { xmlStreamReader.next(); if (xmlStreamReader.getEventType() == XMLStreamReader.START_ELEMENT) { if ("file".equals(xmlStreamReader.getLocalName())) { fileTag = true; fileName = MessageFormat.format("{0}_{1}", xmlStreamReader.getAttributeValue(null, "id"), xmlStreamReader.getAttributeValue(null, "filename")); fileSize = Integer.parseInt(xmlStreamReader.getAttributeValue(null, "size")); logger.debug(MessageFormat.format("XML contains file with name: {0} and size {1} bytes", fileName, fileSize)); } } if (fileTag) { if (xmlStreamReader.getEventType() == XMLStreamReader.CHARACTERS) { exportFile(xmlStreamReader.getText(), fileName, fileSize); } if (xmlStreamReader.getEventType() == XMLStreamReader.END_ELEMENT) { fileSize = null; fileName = null; fileTag = false; } } } } catch (FileNotFoundException e) { logger.error(MessageFormat.format("Could not find export file:-\n{0}", e)); } catch (XMLStreamException e) { logger.error(MessageFormat.format("Could not parse xml export file:-\n{0}", e)); } }
From source file:com.microsoft.windowsazure.storage.table.TableParser.java
/** * Reserved for internal use. Reads the properties of an entity from the stream into a map of property names to * typed values. Reads the entity data as an AtomPub Entry Resource from the specified {@link XMLStreamReader} into * a map of <code>String</code> property names to {@link EntityProperty} data typed values. * /* w ww.j av a2s . c o m*/ * @param xmlr * The <code>XMLStreamReader</code> to read the data from. * @param opContext * An {@link OperationContext} object used to track the execution of the operation. * * @return * A <code>java.util.HashMap</code> containing a map of <code>String</code> property names to * {@link EntityProperty} data typed values found in the entity data. * @throws XMLStreamException * if an error occurs accessing the stream. * @throws ParseException * if an error occurs converting the input to a particular data type. */ private static HashMap<String, EntityProperty> readAtomProperties(final XMLStreamReader xmlr, final OperationContext opContext) throws XMLStreamException, ParseException { int eventType = xmlr.getEventType(); xmlr.require(XMLStreamConstants.START_ELEMENT, null, ODataConstants.PROPERTIES); final HashMap<String, EntityProperty> properties = new HashMap<String, EntityProperty>(); while (xmlr.hasNext()) { eventType = xmlr.next(); if (eventType == XMLStreamConstants.CHARACTERS) { xmlr.getText(); continue; } if (eventType == XMLStreamConstants.START_ELEMENT && xmlr.getNamespaceURI().equals(ODataConstants.DATA_SERVICES_NS)) { final String key = xmlr.getLocalName(); String val = Constants.EMPTY_STRING; String edmType = null; if (xmlr.getAttributeCount() > 0) { edmType = xmlr.getAttributeValue(ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.TYPE); } // move to chars eventType = xmlr.next(); if (eventType == XMLStreamConstants.CHARACTERS) { val = xmlr.getText(); // end element eventType = xmlr.next(); } xmlr.require(XMLStreamConstants.END_ELEMENT, null, key); final EntityProperty newProp = new EntityProperty(val, EdmType.parse(edmType)); properties.put(key, newProp); } else if (eventType == XMLStreamConstants.END_ELEMENT && xmlr.getName().toString() .equals(ODataConstants.BRACKETED_DATA_SERVICES_METADATA_NS + ODataConstants.PROPERTIES)) { // End read properties break; } } xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.PROPERTIES); return properties; }
From source file:com.pocketsoap.salesforce.soap.ChatterClient.java
private RuntimeException handleSoapFault(XMLStreamReader rdr) throws XMLStreamException { String fc = null, fs = null;/*from ww w . ja va 2 s. c o m*/ while (rdr.next() != XMLStreamReader.END_DOCUMENT) { if (rdr.getEventType() == XMLStreamReader.START_ELEMENT) { String ln = rdr.getLocalName(); if (ln.equals("faultcode")) fc = rdr.getElementText(); else if (ln.equals("faultstring")) fs = rdr.getElementText(); } } return new SoapFaultException(fc, fs); }
From source file:net.sf.jabref.importer.fileformat.FreeCiteImporter.java
public ParserResult importEntries(String text) { // URLencode the string for transmission String urlencodedCitation = null; try {/*from w w w . ja v a 2s . co m*/ urlencodedCitation = URLEncoder.encode(text, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { LOGGER.warn("Unsupported encoding", e); } // Send the request URL url; URLConnection conn; try { url = new URL("http://freecite.library.brown.edu/citations/create"); conn = url.openConnection(); } catch (MalformedURLException e) { LOGGER.warn("Bad URL", e); return new ParserResult(); } catch (IOException e) { LOGGER.warn("Could not download", e); return new ParserResult(); } try { conn.setRequestProperty("accept", "text/xml"); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); String data = "citation=" + urlencodedCitation; // write parameters writer.write(data); writer.flush(); } catch (IllegalStateException e) { LOGGER.warn("Already connected.", e); } catch (IOException e) { LOGGER.warn("Unable to connect to FreeCite online service.", e); return ParserResult .fromErrorMessage(Localization.lang("Unable to connect to FreeCite online service.")); } // output is in conn.getInputStream(); // new InputStreamReader(conn.getInputStream()) List<BibEntry> res = new ArrayList<>(); XMLInputFactory factory = XMLInputFactory.newInstance(); try { XMLStreamReader parser = factory.createXMLStreamReader(conn.getInputStream()); while (parser.hasNext()) { if ((parser.getEventType() == XMLStreamConstants.START_ELEMENT) && "citation".equals(parser.getLocalName())) { parser.nextTag(); StringBuilder noteSB = new StringBuilder(); BibEntry e = new BibEntry(); // fallback type EntryType type = BibtexEntryTypes.INPROCEEDINGS; while (!((parser.getEventType() == XMLStreamConstants.END_ELEMENT) && "citation".equals(parser.getLocalName()))) { if (parser.getEventType() == XMLStreamConstants.START_ELEMENT) { String ln = parser.getLocalName(); if ("authors".equals(ln)) { StringBuilder sb = new StringBuilder(); parser.nextTag(); while (parser.getEventType() == XMLStreamConstants.START_ELEMENT) { // author is directly nested below authors assert "author".equals(parser.getLocalName()); String author = parser.getElementText(); if (sb.length() == 0) { // first author sb.append(author); } else { sb.append(" and "); sb.append(author); } assert parser.getEventType() == XMLStreamConstants.END_ELEMENT; assert "author".equals(parser.getLocalName()); parser.nextTag(); // current tag is either begin:author or // end:authors } e.setField(FieldName.AUTHOR, sb.toString()); } else if (FieldName.JOURNAL.equals(ln)) { // we guess that the entry is a journal // the alternative way is to parse // ctx:context-objects / ctx:context-object / ctx:referent / ctx:metadata-by-val / ctx:metadata / journal / rft:genre // the drawback is that ctx:context-objects is NOT nested in citation, but a separate element // we would have to change the whole parser to parse that format. type = BibtexEntryTypes.ARTICLE; e.setField(ln, parser.getElementText()); } else if ("tech".equals(ln)) { type = BibtexEntryTypes.TECHREPORT; // the content of the "tech" field seems to contain the number of the technical report e.setField(FieldName.NUMBER, parser.getElementText()); } else if (FieldName.DOI.equals(ln) || "institution".equals(ln) || "location".equals(ln) || FieldName.NUMBER.equals(ln) || "note".equals(ln) || FieldName.TITLE.equals(ln) || FieldName.PAGES.equals(ln) || FieldName.PUBLISHER.equals(ln) || FieldName.VOLUME.equals(ln) || FieldName.YEAR.equals(ln)) { e.setField(ln, parser.getElementText()); } else if ("booktitle".equals(ln)) { String booktitle = parser.getElementText(); if (booktitle.startsWith("In ")) { // special treatment for parsing of // "In proceedings of..." references booktitle = booktitle.substring(3); } e.setField("booktitle", booktitle); } else if ("raw_string".equals(ln)) { // raw input string is ignored } else { // all other tags are stored as note noteSB.append(ln); noteSB.append(':'); noteSB.append(parser.getElementText()); noteSB.append(Globals.NEWLINE); } } parser.next(); } if (noteSB.length() > 0) { String note; if (e.hasField("note")) { // "note" could have been set during the parsing as FreeCite also returns "note" note = e.getFieldOptional("note").get().concat(Globals.NEWLINE) .concat(noteSB.toString()); } else { note = noteSB.toString(); } e.setField("note", note); } // type has been derived from "genre" // has to be done before label generation as label generation is dependent on entry type e.setType(type); // autogenerate label (BibTeX key) LabelPatternUtil.makeLabel( JabRefGUI.getMainFrame().getCurrentBasePanel().getBibDatabaseContext().getMetaData(), JabRefGUI.getMainFrame().getCurrentBasePanel().getDatabase(), e, Globals.prefs); res.add(e); } parser.next(); } parser.close(); } catch (IOException | XMLStreamException ex) { LOGGER.warn("Could not parse", ex); return new ParserResult(); } return new ParserResult(res); }