List of usage examples for javax.xml.stream XMLStreamReader getLocalName
public String getLocalName();
From source file:com.conx.logistics.kernel.bpm.impl.jbpm.core.mock.BPMGuvnorUtil.java
public List<String> getAllProcessesInPackage(String pkgName) { List<String> processes = new ArrayList<String>(); String assetsURL = getGuvnorProtocol() + "://" + getGuvnorHost() + "/" + getGuvnorSubdomain() + "/rest/packages/" + pkgName + "/assets/"; try {//from w ww .j a v a2s . c o m XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader reader = factory.createXMLStreamReader(getInputStreamForURL(assetsURL, "GET")); String format = ""; String title = ""; while (reader.hasNext()) { int next = reader.next(); if (next == XMLStreamReader.START_ELEMENT) { if ("format".equals(reader.getLocalName())) { format = reader.getElementText(); } if ("title".equals(reader.getLocalName())) { title = reader.getElementText(); } if ("asset".equals(reader.getLocalName())) { if (format.equals(EXT_BPMN) || format.equals(EXT_BPMN2)) { processes.add(title); title = ""; format = ""; } } } } // last one if (format.equals(EXT_BPMN) || format.equals(EXT_BPMN2)) { processes.add(title); } } catch (Exception e) { logger.error("Error finding processes in package: " + e.getMessage()); } return processes; }
From source file:de.codesourcery.eve.skills.util.XMLMapper.java
public <T> Collection<T> read(Class<T> clasz, IFieldConverters converters, InputStream instream) throws XMLStreamException, IOException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException { final Collection<T> result = new ArrayList<T>(); try {/*from w w w. j a va2s . co m*/ final BeanDescription desc = createBeanDescription(clasz); /* * Create inverse mapping attribute name -> field. */ final Map<String, Field> inverseMapping = new HashMap<String, Field>(); if (!this.propertyNameMappings.isEmpty()) { // key = property name / value = attribute name for (Map.Entry<String, String> propToAttribute : this.propertyNameMappings.entrySet()) { inverseMapping.put(propToAttribute.getValue(), desc.getFieldByName(propToAttribute.getKey())); } } else { // create default mappings for (Field f : desc.getFields()) { inverseMapping.put(f.getName(), f); } } final int fieldCount = desc.getFields().size(); final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader parser = factory.createXMLStreamReader(instream); boolean inRow = false; final Constructor<T> constructor = clasz.getConstructor(new Class<?>[0]); for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) { switch (event) { case XMLStreamConstants.START_ELEMENT: if ("row".equals(parser.getLocalName())) { // parse row if (inRow) { throw new XMLStreamException("Found nested <row> tag ?", parser.getLocation()); } inRow = true; final T bean = constructor.newInstance(new Object[0]); for (int i = 0; i < fieldCount; i++) { final String attrName = parser.getAttributeLocalName(i); final String attrValue = parser.getAttributeValue(i); final Field field = inverseMapping.get(attrName); if (!NIL.equals(attrValue)) { final Object fieldValue = converters.getConverter(field) .toObject(fromAttributeValue(attrValue), field.getType()); field.set(bean, fieldValue); } else { field.set(bean, null); } } result.add(bean); } break; case XMLStreamConstants.END_ELEMENT: if ("row".equals(parser.getLocalName())) { // parse row if (!inRow) { throw new XMLStreamException("Found </row> tag without start tag at ", parser.getLocation()); } inRow = false; } break; } } } finally { instream.close(); } return result; }
From source file:at.lame.hellonzb.parser.NzbParser.java
/** * This is the constructor of the class. * It parses the given XML file.//from www. ja v a 2 s .c om * * @param mainApp The main application object * @param file The file name of the nzb file to parse * @throws XMLStreamException * @throws IOException */ public NzbParser(HelloNzbCradle mainApp, String file) throws XMLStreamException, IOException, ParseException { this.mainApp = mainApp; DownloadFile currentFile = null; DownloadFileSegment currentSegment = null; boolean groupFlag = false; boolean segmentFlag = false; this.name = file.trim(); this.name = file.substring(0, file.length() - 4); this.downloadFiles = new Vector<DownloadFile>(); this.origTotalSize = 0; this.downloadedBytes = 0; // create XML parser String string = reformatInputStream(file); InputStream in = new ByteArrayInputStream(string.getBytes()); XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader parser = factory.createXMLStreamReader(in); // parse nzb file with a Java XML parser while (parser.hasNext()) { switch (parser.getEventType()) { // parser has reached the end of the xml file case XMLStreamConstants.END_DOCUMENT: parser.close(); break; // parser has found a new element case XMLStreamConstants.START_ELEMENT: String elemName = parser.getLocalName().toLowerCase(); if (elemName.equals("file")) { currentFile = newDownloadFile(parser); boolean found = false; for (DownloadFile dlf : downloadFiles) if (dlf.getFilename().equals(currentFile.getFilename())) { found = true; break; } if (!found) downloadFiles.add(currentFile); } else if (elemName.equals("group")) groupFlag = true; else if (elemName.equals("segment")) { currentSegment = newDownloadFileSegment(parser, currentFile); currentFile.addSegment(currentSegment); segmentFlag = true; } break; // end of element case XMLStreamConstants.END_ELEMENT: groupFlag = false; segmentFlag = false; break; // get the elements value(s) case XMLStreamConstants.CHARACTERS: if (!parser.isWhiteSpace()) { if (groupFlag && (currentFile != null)) currentFile.addGroup(parser.getText()); else if (segmentFlag && (currentSegment != null)) currentSegment.setArticleId(parser.getText()); } break; // any other parser event? default: break; } parser.next(); } checkFileSegments(); this.origTotalSize = getCurrTotalSize(); }
From source file:net.landora.animeinfo.mylistreader.ListReader.java
public boolean download(InputStream input) throws Throwable { TarInputStream is = null;// www.j a v a 2s . c o m try { is = new TarInputStream(new GZIPInputStream(input)); TarEntry entry; while ((entry = is.getNextEntry()) != null) { if (!entry.getName().equalsIgnoreCase("mylist.xml")) { continue; } XMLStreamReader reader = XMLInputFactory.newFactory().createXMLStreamReader(is); reader.nextTag(); reader.require(XMLStreamReader.START_ELEMENT, null, "my_anime_list"); values = new HashMap<String, String>(); StringBuilder value = new StringBuilder(); while (reader.nextTag() != XMLStreamReader.END_ELEMENT) { reader.require(XMLStreamReader.START_ELEMENT, null, null); String tableName = reader.getLocalName(); values.clear(); while (reader.nextTag() != XMLStreamReader.END_ELEMENT) { String valueName = reader.getLocalName(); value.setLength(0); while (reader.next() != XMLStreamReader.END_ELEMENT) { switch (reader.getEventType()) { case XMLStreamReader.CDATA: case XMLStreamReader.CHARACTERS: case XMLStreamReader.SPACE: value.append(reader.getText()); } } reader.require(XMLStreamReader.END_ELEMENT, null, valueName); values.put(valueName, value.toString()); } reader.require(XMLStreamReader.END_ELEMENT, null, tableName); handleTable(tableName); } reader.require(XMLStreamReader.END_ELEMENT, null, "my_anime_list"); saveLast(); } return true; } finally { if (is != null) { IOUtils.closeQuietly(is); } else if (input != null) { IOUtils.closeQuietly(input); } } }
From source file:hudson.model.ExternalRun.java
/** * Instead of performing a build, accept the log and the return code from a * remote machine.//from ww w. j a v a 2s.com * * <p> The format of the XML is: * * <pre><xmp> * <run> * <log>...console output...</log> * <result>exit code</result> * </run> * </xmp></pre> */ @SuppressWarnings({ "Since15" }) public void acceptRemoteSubmission(final Reader in) throws IOException { final long[] duration = new long[1]; run(new Runner() { private String elementText(XMLStreamReader r) throws XMLStreamException { StringBuilder buf = new StringBuilder(); while (true) { int type = r.next(); if (type == CHARACTERS || type == CDATA) { buf.append(r.getTextCharacters(), r.getTextStart(), r.getTextLength()); } else { return buf.toString(); } } } public Result run(BuildListener listener) throws Exception { PrintStream logger = null; try { logger = new PrintStream(new DecodingStream(listener.getLogger())); XMLInputFactory xif = XMLInputFactory.newInstance(); XMLStreamReader p = xif.createXMLStreamReader(in); p.nextTag(); // get to the <run> p.nextTag(); // get to the <log> charset = p.getAttributeValue(null, "content-encoding"); while (p.next() != END_ELEMENT) { int type = p.getEventType(); if (type == CHARACTERS || type == CDATA) { logger.print(p.getText()); } } p.nextTag(); // get to <result> Result r = Integer.parseInt(elementText(p)) == 0 ? Result.SUCCESS : Result.FAILURE; p.nextTag(); // get to <duration> (optional) if (p.getEventType() == START_ELEMENT && p.getLocalName().equals("duration")) { duration[0] = Long.parseLong(elementText(p)); } return r; } finally { IOUtils.closeQuietly(logger); } } public void post(BuildListener listener) { // do nothing } public void cleanUp(BuildListener listener) { // do nothing } }); if (duration[0] != 0) { super.duration = duration[0]; // save the updated duration save(); } }
From source file:net.landora.anidb.mylist.ListReader.java
public boolean download(InputStream input) throws Throwable { TarInputStream is = null;//from w ww . j av a 2s. co m try { is = new TarInputStream(new GZIPInputStream(input)); TarEntry entry; while ((entry = is.getNextEntry()) != null) { if (!entry.getName().equalsIgnoreCase("mylist.xml")) { continue; } XMLStreamReader reader = XMLInputFactory.newFactory().createXMLStreamReader(is); reader.nextTag(); reader.require(XMLStreamReader.START_ELEMENT, null, "my_anime_list"); values = new HashMap<>(); StringBuilder value = new StringBuilder(); while (reader.nextTag() != XMLStreamReader.END_ELEMENT) { reader.require(XMLStreamReader.START_ELEMENT, null, null); String tableName = reader.getLocalName(); values.clear(); while (reader.nextTag() != XMLStreamReader.END_ELEMENT) { String valueName = reader.getLocalName(); value.setLength(0); while (reader.next() != XMLStreamReader.END_ELEMENT) { switch (reader.getEventType()) { case XMLStreamReader.CDATA: case XMLStreamReader.CHARACTERS: case XMLStreamReader.SPACE: value.append(reader.getText()); } } reader.require(XMLStreamReader.END_ELEMENT, null, valueName); values.put(valueName, value.toString()); } reader.require(XMLStreamReader.END_ELEMENT, null, tableName); handleTable(tableName); } reader.require(XMLStreamReader.END_ELEMENT, null, "my_anime_list"); saveLast(); } return true; } finally { if (is != null) { IOUtils.closeQuietly(is); } else if (input != null) { IOUtils.closeQuietly(input); } } }
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 .j ava2 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
/** * Test status of testcase is determined from its child tags( <skipped>, <failure>, <error> ). * If it doesn't contain any of these tags, test is considered passed. If it contains both failure and error tags, * test status is set to error.// ww w . j a v a 2 s . co m */ private JtregBackwardCompatibileTest parseTestcase(XMLStreamReader in) throws Exception { final String testName = findAttributeValue(in, "name"); final String className = findAttributeValue(in, "classname"); TestStatus status = TestStatus.PASSED; String failureOutput = ""; String stdOutput = ""; String sysErrOutput = ""; String message = ""; StringBuilder errOutput = new StringBuilder(); while (in.hasNext()) { int event = in.next(); if (event == START_ELEMENT && FAILURE.equals(in.getLocalName())) { final String lEmessage = findAttributeValue(in, "message"); if (lEmessage != null) { message = lEmessage; } failureOutput = captureCharacters(in, FAILURE); if (status != TestStatus.ERROR) { status = TestStatus.FAILED; } continue; } if (event == START_ELEMENT && SYSTEMOUT.equals(in.getLocalName())) { stdOutput = captureCharacters(in, SYSTEMOUT); continue; } if (event == START_ELEMENT && SYSTEMERR.equals(in.getLocalName())) { sysErrOutput = captureCharacters(in, SYSTEMERR); continue; } if (event == START_ELEMENT && SKIPPED.equals(in.getLocalName())) { status = TestStatus.NOT_RUN; continue; } if (event == START_ELEMENT && ERROR.equals(in.getLocalName())) { status = TestStatus.ERROR; errOutput.append(captureCharacters(in, ERROR)).append('\n'); continue; } if (event == END_ELEMENT && TESTCASE.equals(in.getLocalName())) { break; } } //order imortant! see revalidateTests List<TestOutput> outputs = Arrays.asList(new TestOutput(SYSTEMOUT, stdOutput), new TestOutput(SYSTEMERR, sysErrOutput)); return new JtregBackwardCompatibileTest(className, status, message, outputs, testName, failureOutput, errOutput.toString()); }
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. * //from w w w .ja v 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.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;// w ww . ja v a2s . com 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)); }