List of usage examples for javax.xml.stream XMLStreamConstants END_ELEMENT
int END_ELEMENT
To view the source code for javax.xml.stream XMLStreamConstants END_ELEMENT.
Click Source Link
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 ww w .j a v a 2 s . c o 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); }
From source file:com.microsoft.windowsazure.services.table.client.AtomPubParser.java
/** * Reserved for internal use. Parses the operation response as an entity. Parses the result returned in the * specified stream in AtomPub format into a {@link TableResult} containing an entity of the specified class type * projected using the specified resolver. * /*from www . jav a 2 s . c o m*/ * @param xmlr * An <code>XMLStreamReader</code> on the input stream. * @param clazzType * The class type <code>T</code> implementing {@link TableEntity} for the entity returned. Set to * <code>null</code> to ignore the returned entity and copy only response properties into the * {@link TableResult} object. * @param resolver * An {@link EntityResolver} instance to project the entity into an instance of type <code>R</code>. Set * to <code>null</code> to return the entity as an instance of the class type <code>T</code>. * @param opContext * An {@link OperationContext} object used to track the execution of the operation. * @return * A {@link TableResult} containing the parsed entity result of the operation. * * @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. */ protected static <T extends TableEntity, R> TableResult parseEntity(final XMLStreamReader xmlr, final Class<T> clazzType, final EntityResolver<R> resolver, final OperationContext opContext) throws XMLStreamException, ParseException, InstantiationException, IllegalAccessException, StorageException { int eventType = xmlr.getEventType(); final TableResult res = new TableResult(); xmlr.require(XMLStreamConstants.START_ELEMENT, null, ODataConstants.ENTRY); res.setEtag(StringEscapeUtils.unescapeHtml4( xmlr.getAttributeValue(ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.ETAG))); 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.ID)) { res.setId(Utility.readElementFromXMLReader(xmlr, ODataConstants.ID)); } else if (name .equals(ODataConstants.BRACKETED_DATA_SERVICES_METADATA_NS + ODataConstants.PROPERTIES)) { // Do read properties if (resolver == null && clazzType == null) { return res; } else { res.setProperties(readProperties(xmlr, opContext)); break; } } } } // Move to end Content eventType = xmlr.next(); if (eventType == XMLStreamConstants.CHARACTERS) { eventType = xmlr.next(); } xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.CONTENT); eventType = xmlr.next(); if (eventType == XMLStreamConstants.CHARACTERS) { eventType = xmlr.next(); } xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.ENTRY); String rowKey = null; String partitionKey = null; Date timestamp = null; // Remove core properties from map and set individually EntityProperty tempProp = res.getProperties().get(TableConstants.PARTITION_KEY); if (tempProp != null) { res.getProperties().remove(TableConstants.PARTITION_KEY); partitionKey = tempProp.getValueAsString(); } tempProp = res.getProperties().get(TableConstants.ROW_KEY); if (tempProp != null) { res.getProperties().remove(TableConstants.ROW_KEY); rowKey = tempProp.getValueAsString(); } tempProp = res.getProperties().get(TableConstants.TIMESTAMP); if (tempProp != null) { res.getProperties().remove(TableConstants.TIMESTAMP); timestamp = tempProp.getValueAsDate(); } if (resolver != null) { // Call resolver res.setResult(resolver.resolve(partitionKey, rowKey, timestamp, res.getProperties(), res.getEtag())); } else if (clazzType != null) { // Generate new entity and return final T entity = clazzType.newInstance(); entity.setEtag(res.getEtag()); entity.setPartitionKey(partitionKey); entity.setRowKey(rowKey); entity.setTimestamp(timestamp); entity.readEntity(res.getProperties(), opContext); res.setResult(entity); } return res; }
From source file:com.widowcrawler.exo.parse.Parser.java
public Sitemap parse(InputStream inputStream) throws XMLStreamException, SitemapParseException { final XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(inputStream, "utf-8"); final Sitemap retval = new Sitemap(new HashSet<>()); final Set<SitemapURL> sitemapURLs = new HashSet<>(); SitemapURL.Builder urlBuilder = null; String urlContent;//from ww w .j av a 2 s . c om reader.getEventType(); while (reader.hasNext()) { switch (state) { case START: reader.nextTag(); if (StringUtils.equalsIgnoreCase(reader.getLocalName(), URLSET_TAG_NAME)) { state = State.URLSET; } else if (StringUtils.equalsIgnoreCase(reader.getLocalName(), SITEMAPINDEX_TAG_NAME)) { state = State.SITEMAPINDEX; } else { String message = "Invalid root element. Must be either urlset or sitemapindex"; logger.error(message); throw new SitemapParseException(message); } break; case END: // consume all end tags if (reader.getEventType() != XMLStreamConstants.END_ELEMENT) { String message = decorate("There should be only one root element in each sitemap.xml", reader.getLocation()); logger.error(message); throw new SitemapParseException(message); } reader.next(); break; ///////////////////// // URLSET Hierarchy ///////////////////// case URLSET: // If we're done with the URLs, we're done overall if (reader.nextTag() == XMLStreamConstants.END_ELEMENT) { state = State.END; break; } // Check that we're entering into a <url> element if (!StringUtils.equalsIgnoreCase(reader.getLocalName(), URL_TAG_NAME)) { String message = "A <urlset> element can only contain <url> elements. Found: " + reader.getLocalName(); logger.error(message); throw new SitemapParseException(message); } urlBuilder = new SitemapURL.Builder(); state = State.URL; break; case URL: reader.nextTag(); if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) { //logger.info("reader.getLocalName(): " + reader.getLocalName()); switch (StringUtils.lowerCase(reader.getLocalName())) { case LOC_TAG_NAME: state = State.URL_PROP_LOC; break; case LASTMOD_TAG_NAME: state = State.URL_PROP_LASTMOD; break; case CHANGEFREQ_TAG_NAME: state = State.URL_PROP_CHANGEFREQ; break; case PRIORITY_TAG_NAME: state = State.URL_PROP_PRIORITY; break; case MOBILE_TAG_NAME: state = State.URL_PROP_MOBILE; break; default: String message = "Unexpected tag in url: " + reader.getLocalName(); logger.error(message); throw new SitemapParseException(message); } } else if (reader.getEventType() == XMLStreamConstants.END_ELEMENT) { // we're done collecting the data for this URL assert urlBuilder != null; sitemapURLs.add(urlBuilder.build()); urlBuilder = new SitemapURL.Builder(); state = State.URLSET; } break; case URL_PROP_LOC: urlContent = reader.getElementText(); try { assert urlBuilder != null; urlBuilder.withLocation(new URL(StringUtils.trimToNull(urlContent))); } catch (MalformedURLException ex) { String message = String.format("Malformed URL found: %s", urlContent); logger.error(message); throw new SitemapParseException(message); } state = State.URL; break; case URL_PROP_LASTMOD: assert urlBuilder != null; urlBuilder.withLastModified(DateTime.parse(reader.getElementText())); state = State.URL; break; case URL_PROP_CHANGEFREQ: assert urlBuilder != null; urlBuilder.withChangeFrequency(ChangeFreq.valueOf(StringUtils.upperCase(reader.getElementText()))); state = State.URL; break; case URL_PROP_PRIORITY: assert urlBuilder != null; urlBuilder.withPriority(Double.valueOf(reader.getElementText())); state = State.URL; break; case URL_PROP_MOBILE: assert urlBuilder != null; urlBuilder.withIsMobileContent(true); // consume until "end tag" of self-closing tag // Also works if someone puts content in reader.getElementText(); state = State.URL; break; /////////////////////////// // SITEMAPINDEX Hierarchy /////////////////////////// case SITEMAPINDEX: // If we're done with all the Sitemaps, we're done overall if (reader.nextTag() == XMLStreamConstants.END_ELEMENT) { state = State.END; break; } state = State.SITEMAP; break; case SITEMAP: if (!StringUtils.equalsIgnoreCase(reader.getLocalName(), SITEMAP_TAG_NAME)) { throw new SitemapParseException("A <sitemapindex> element can only contain <sitemap> elements"); } reader.nextTag(); if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) { switch (StringUtils.lowerCase(reader.getLocalName())) { case LOC_TAG_NAME: state = State.URL_PROP_LOC; break; case LASTMOD_TAG_NAME: state = State.URL_PROP_LASTMOD; break; default: throw new SitemapParseException("Unexpected tag in sitemap: " + reader.getLocalName()); } } else if (reader.getEventType() == XMLStreamConstants.END_ELEMENT) { // we're done collecting the data for this URL assert urlBuilder != null; sitemapURLs.add(urlBuilder.build()); urlBuilder = new SitemapURL.Builder(); state = State.URLSET; } case SITEMAP_PROP_LOC: urlContent = reader.getElementText(); try { URL sitemapURL = new URL(StringUtils.trimToNull(urlContent)); Sitemap temp = Retry.retry(() -> { try { return Exo.parse(sitemapURL.toString()); } catch (Exception ex) { throw new RuntimeException(ex); } }); retval.merge(temp); } catch (MalformedURLException ex) { String message = String.format("Malformed URL found: %s", urlContent); logger.error(message); throw new SitemapParseException(message); } catch (InterruptedException e) { logger.warn("Thread interrupted while (re)trying"); Thread.currentThread().interrupt(); } catch (RetryFailedException e) { String message = String.format("Failed to retrieve sitemap of sitemap index at %s", urlContent); logger.error(message); throw new SitemapParseException(message); } state = State.URL; break; case SITEMAP_PROP_LASTMOD: // Do nothing with this data for now reader.getElementText(); break; } //System.out.println(state); } return retval.merge(new Sitemap(sitemapURLs)); }
From source file:com.microsoft.tfs.core.memento.XMLMemento.java
/** * Reads the current element from the given reader and returns the * {@link XMLMemento} read from its data. The {@link XMLStreamReader} must * be positioned at {@link XMLStreamConstants#START_ELEMENT}. * * @param reader//from w ww. j av a 2 s. c o m * the reader (must not be <code>null</code>) * @return the {@link XMLMemento} read from the stream * @throws XMLStreamException * if an error occurred reading from the reader */ private synchronized void readFromElement(final XMLStreamReader reader) throws XMLStreamException { Check.notNull(reader, "reader"); //$NON-NLS-1$ /* * Read all the attributes from the current element. */ final int attributeCount = reader.getAttributeCount(); for (int i = 0; i < attributeCount; i++) { putString(reader.getAttributeLocalName(i), reader.getAttributeValue(i)); } /* * Process child nodes (which may be text or child Mementos). */ String localName; int event; do { event = reader.next(); if (event == XMLStreamConstants.START_ELEMENT) { localName = reader.getLocalName(); final XMLMemento child = (XMLMemento) createChild(localName); child.readFromElement(reader); } else if (event == XMLStreamConstants.CHARACTERS) { putTextData(reader.getText()); } } while (event != XMLStreamConstants.END_ELEMENT); }
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();//from w ww . j av 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:di.uniba.it.tee2.wiki.WikipediaDumpIterator.java
@Override public WikiPage next() { WikiPage page = new WikiPage(); try {/* w w w.j av a2s . co m*/ StringBuilder wikimediaText = new StringBuilder(); StringBuilder title = new StringBuilder(); int wikiID = -1; int revisionID = -1; boolean finishedParsingArticle = false; boolean inrevision = false; char lastElement = 'n'; while (!finishedParsingArticle && xmlStreamReader.hasNext()) { int eventCode = xmlStreamReader.next(); switch (eventCode) { case XMLStreamConstants.START_ELEMENT: switch (xmlStreamReader.getLocalName()) { case "title": lastElement = 't'; break; case "text": lastElement = 'c'; break; case "revision": inrevision = true; break; case "id": lastElement = 'd'; break; } break; case XMLStreamConstants.END_ELEMENT: switch (xmlStreamReader.getLocalName()) { case "page": finishedParsingArticle = true; break; case "title": lastElement = 'n'; break; case "text": lastElement = 'n'; break; case "id": lastElement = 'n'; break; case "revision": inrevision = false; break; } break; case XMLStreamConstants.CHARACTERS: if (lastElement == 't') { title.append(xmlStreamReader.getText()); } else if (lastElement == 'c') { wikimediaText.append(xmlStreamReader.getText()); } else if (lastElement == 'd') { if (inrevision && revisionID == -1) { revisionID = Integer.parseInt(xmlStreamReader.getText()); } else if (wikiID == -1) { wikiID = Integer.parseInt(xmlStreamReader.getText()); } } break; } } page.setWikiID(wikiID); page.setRevisionID(revisionID); page.setTitle(title.toString()); try { ParsedPage parsedPage = parser.parse(wikimediaText.toString()); page.setParsedPage(parsedPage); } catch (Exception ex) { Logger.getLogger(WikipediaDumpIterator.class.getName()).log(Level.WARNING, "Error to parse page: " + page.getTitle(), ex); } } catch (XMLStreamException ex) { Logger.getLogger(WikipediaDumpIterator.class.getName()).log(Level.WARNING, "Error reading XML stream", ex); } return page; }
From source file:babel.content.pages.Page.java
public void unpersist(XMLStreamReader reader) throws XMLStreamException { String elemTag;/*from w w w . j a v a2 s . c o m*/ PageVersion ver; m_pageURL = reader.getAttributeValue(0); m_versions.clear(); while (true) { int event = reader.next(); if (event == XMLStreamConstants.END_ELEMENT && XML_TAG_PAGE.equals(reader.getName().toString())) { break; } if (event == XMLStreamConstants.START_ELEMENT) { elemTag = reader.getName().toString(); if ("MetaData".equals(elemTag)) { m_pageProps.unpersist(reader); } else if ("PageVersion".equals(elemTag)) { ver = new PageVersion(); ver.unpersist(reader); m_versions.add(ver); } } } }
From source file:de.tuebingen.uni.sfs.germanet.api.IliLoader.java
/** * Returns the <code>IliRecord</code> for which the start tag was just encountered. * @param parser the <code>parser</code> being used on the current file * @return a <code>IliRecord</code> representing the data parsed * @throws javax.xml.stream.XMLStreamException *//* w ww. j a va2s . co m*/ private IliRecord processIliRecord(XMLStreamReader parser) throws XMLStreamException { int lexUnitId; String ewnRelation; String pwnWord; String pwn20Id; String pwn30Id; String pwn20paraphrase = ""; String source; IliRecord curIli; List<String> englishSynonyms = new ArrayList<String>(); boolean done = false; int event; String nodeName; lexUnitId = Integer.valueOf(parser.getAttributeValue(namespace, GermaNet.XML_LEX_UNIT_ID).substring(1)); ewnRelation = parser.getAttributeValue(namespace, GermaNet.XML_EWN_RELATION); pwnWord = parser.getAttributeValue(namespace, GermaNet.XML_PWN_WORD); pwn20Id = parser.getAttributeValue(namespace, GermaNet.XML_PWN20_ID); pwn30Id = parser.getAttributeValue(namespace, GermaNet.XML_PWN30_ID); pwn20paraphrase = parser.getAttributeValue(namespace, GermaNet.XML_PWN20_PARAPHRASE); source = parser.getAttributeValue(namespace, GermaNet.XML_SOURCE); // process this lexUnit while (parser.hasNext() && !done) { event = parser.next(); switch (event) { case XMLStreamConstants.START_ELEMENT: nodeName = parser.getLocalName(); if (nodeName.equals(GermaNet.XML_PWN20_SYNONYM)) { englishSynonyms.add(processEnglishSynonyms(parser)); } case XMLStreamConstants.END_ELEMENT: nodeName = parser.getLocalName(); // quit when we reach the end lexUnit tag if (nodeName.equals(GermaNet.XML_ILI_RECORD)) { done = true; } break; } } curIli = new IliRecord(lexUnitId, EwnRel.valueOf(ewnRelation), pwnWord, pwn20Id, pwn30Id, pwn20paraphrase, source); for (String synonym : englishSynonyms) { curIli.addEnglishSynonym(synonym); } return curIli; }
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();/*from w w w.jav a 2s. co m*/ 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:com.flexive.chemistry.webdav.TextDocumentResource.java
/** * Set the value of a property, stream points to the start of the property tag. * * @param parser the XML parser// w w w . j a v a 2s. com * @throws XMLStreamException on parsing errors */ protected void processProperty(XMLStreamReader parser) throws XMLStreamException { int level = 0; String name = null; for (int i = 0; i < parser.getAttributeCount(); i++) { if ("name".equals(parser.getAttributeName(i).getLocalPart())) { name = parser.getAttributeValue(i); break; } } if (name == null) { if (LOG.isTraceEnabled()) { LOG.trace("property without name attribute encountered"); } return; } String value = null; for (int event = parser.nextTag(); event != XMLStreamConstants.END_DOCUMENT && level >= 0; event = parser.nextTag()) { switch (event) { case XMLStreamConstants.START_ELEMENT: if ("value".equals(parser.getLocalName())) { value = parser.getElementText().trim(); } else if ("name".equals(parser.getLocalName())) { name = parser.getElementText(); } else { level++; } break; case XMLStreamConstants.END_ELEMENT: level--; break; } } if (value != null) { if (LOG.isTraceEnabled()) { LOG.trace("Setting field " + name + " to " + value); } try { object.setValue(name, value); } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("Failed to set field " + name + " (ignored): " + e.getMessage()); } } } }