List of usage examples for javax.xml.stream XMLStreamReader require
public void require(int type, String namespaceURI, String localName) throws XMLStreamException;
From source file:net.landora.animeinfo.anidb.AniDBHTTPManager.java
public Anime downloadAnime(int aid) { InputStream is = null;//w ww . ja v a 2 s . c o m try { // URL url = new URL(String.format("%s&request=anime&aid=%d", HTTP_URL, aid)); // is = new GZIPInputStream(url.openStream()); is = new BufferedInputStream(new FileInputStream("/home/bdickie/anidb/http_test.xml")); XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(is); reader.nextTag(); reader.require(XMLStreamReader.START_ELEMENT, null, "anime"); Anime anime = new Anime(); anime.setAnimeId(Integer.parseInt(reader.getAttributeValue(null, "id"))); anime.setHentai(Boolean.parseBoolean(reader.getAttributeValue(null, "restricted"))); anime.setLastLoaded(Calendar.getInstance()); while (reader.nextTag() != XMLStreamReader.END_ELEMENT) { String tagName = reader.getLocalName(); if (tagName.equals("type")) { anime.setType(nextString(reader)); } else if (tagName.equals("episodecount")) { anime.setEpisodeCount(Integer.parseInt(nextString(reader))); } else if (tagName.equals("startdate")) { // anime.setStartDate(nextString(reader)); } else if (tagName.equals("enddate")) { // anime.setEndDate(nextString(reader)); } else if (tagName.equals("description")) { anime.setDescription(nextString(reader)); } else if (tagName.equals("picture")) { anime.setPictureFileName(nextString(reader)); } else if (tagName.equals("titles")) { List<AnimeName> names = new ArrayList<AnimeName>(); while (reader.nextTag() != XMLStreamReader.END_ELEMENT) { reader.require(XMLStreamReader.START_ELEMENT, null, "title"); AnimeName name = new AnimeName(); for (int i = 0; i < reader.getAttributeCount(); i++) { String aname = reader.getAttributeLocalName(i); if (aname.equals("type")) { name.setType(reader.getAttributeValue(i)); } else if (aname.equals("lang")) { name.setLanguage(reader.getAttributeValue(i)); } } name.setName(nextString(reader)); name.setAnime(anime); names.add(name); } for (AnimeName name : names) { if (name.getType().equalsIgnoreCase("main")) { anime.setNameMain(name.getName()); } else if (name.getType().equalsIgnoreCase("official") && name.getLanguage().equalsIgnoreCase("en")) { anime.setNameEnglish(name.getName()); } } anime.setNames(names); } else if (tagName.equals("ratings")) { while (reader.nextTag() != XMLStreamReader.END_ELEMENT) { String tagName2 = reader.getLocalName(); int count = Integer.parseInt(reader.getAttributeValue(null, "count")); float value = Float.parseFloat(nextString(reader)); if (tagName2.equals("permanent")) { anime.setRatingPermanent(value); anime.setRatingPermanentVotes(count); } else if (tagName2.equals("temporary")) { anime.setRatingTemporary(value); anime.setRatingTemporaryVotes(count); } } } else if (tagName.equals("categories")) { while (reader.nextTag() != XMLStreamReader.END_ELEMENT) { reader.require(XMLStreamReader.START_ELEMENT, null, "category"); int categoryid = Integer.parseInt(reader.getAttributeValue(null, "id")); int weight = Integer.parseInt(reader.getAttributeValue(null, "weight")); AnimeCategory category = AnimeDBA.getAnimeCategory(categoryid); if (category == null) { return null; } ignoreTag(reader); } } else { ignoreTag(reader); } } reader.close(); return anime; } catch (Exception e) { log.error("Error downloading anime: " + aid, e); return null; } finally { if (is != null) { IOUtils.closeQuietly(is); } } }
From source file:de.huxhorn.sulky.plist.impl.PropertyListReader.java
private Object readValue(XMLStreamReader reader) throws XMLStreamException { int type = reader.getEventType(); if (XMLStreamConstants.START_ELEMENT == type && TRUE_NODE.equals(reader.getLocalName())) { reader.nextTag();/* w ww . ja v a 2s . com*/ reader.require(XMLStreamConstants.END_ELEMENT, null, TRUE_NODE); reader.nextTag(); return Boolean.TRUE; } if (XMLStreamConstants.START_ELEMENT == type && FALSE_NODE.equals(reader.getLocalName())) { reader.nextTag(); reader.require(XMLStreamConstants.END_ELEMENT, null, FALSE_NODE); reader.nextTag(); return Boolean.FALSE; } if (XMLStreamConstants.START_ELEMENT == type && REAL_NODE.equals(reader.getLocalName())) { String text = StaxUtilities.readSimpleTextNodeIfAvailable(reader, null, REAL_NODE); return Double.parseDouble(text); } if (XMLStreamConstants.START_ELEMENT == type && INTEGER_NODE.equals(reader.getLocalName())) { String text = StaxUtilities.readSimpleTextNodeIfAvailable(reader, null, INTEGER_NODE); return Long.parseLong(text); } if (XMLStreamConstants.START_ELEMENT == type && STRING_NODE.equals(reader.getLocalName())) { return StaxUtilities.readSimpleTextNodeIfAvailable(reader, null, STRING_NODE); } if (XMLStreamConstants.START_ELEMENT == type && DATA_NODE.equals(reader.getLocalName())) { return readData(reader); } if (XMLStreamConstants.START_ELEMENT == type && DATE_NODE.equals(reader.getLocalName())) { return readDate(reader); } if (XMLStreamConstants.START_ELEMENT == type && ARRAY_NODE.equals(reader.getLocalName())) { return readArray(reader); } if (XMLStreamConstants.START_ELEMENT == type && DICT_NODE.equals(reader.getLocalName())) { return readDict(reader); } throw new RuntimeException("Unexpected XML-Node: " + reader.getLocalName()); }
From source file:com.pocketsoap.salesforce.soap.ChatterClient.java
private <T> T makeSoapRequest(String serverUrl, RequestEntity req, ResponseParser<T> respParser) throws XMLStreamException, IOException { PostMethod post = new PostMethod(serverUrl); post.addRequestHeader("SOAPAction", "\"\""); post.setRequestEntity(req);/*from w w w .j a v a 2 s. c om*/ HttpClient http = new HttpClient(); int sc = http.executeMethod(post); if (sc != 200 && sc != 500) throw new IOException("request to " + serverUrl + " returned unexpected HTTP status code of " + sc + ", check configuration."); XMLInputFactory f = XMLInputFactory.newInstance(); f.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); XMLStreamReader rdr = f.createXMLStreamReader(post.getResponseBodyAsStream()); rdr.require(XMLStreamReader.START_DOCUMENT, null, null); rdr.nextTag(); rdr.require(XMLStreamReader.START_ELEMENT, SOAP_NS, "Envelope"); rdr.nextTag(); // TODO, should handle a Header appearing in the response. rdr.require(XMLStreamReader.START_ELEMENT, SOAP_NS, "Body"); rdr.nextTag(); if (rdr.getLocalName().equals("Fault")) { throw handleSoapFault(rdr); } try { T response = respParser.parse(rdr); while (rdr.hasNext()) rdr.next(); return response; } finally { try { rdr.close(); } finally { post.releaseConnection(); } } }
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. * /*from w ww . j av a 2 s . c om*/ * @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: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 www. j a va 2s . 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:net.landora.video.info.file.FileInfoManager.java
private synchronized Map<String, FileInfo> parseCacheFile(File file) { InputStream is = null;//from w ww .ja v a 2s. c o m try { is = new BufferedInputStream(new FileInputStream(file)); if (COMPRESS_INFO_FILE) { is = new GZIPInputStream(is); } XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(is); reader.nextTag(); reader.require(XMLStreamReader.START_ELEMENT, null, "files"); Map<String, FileInfo> files = new HashMap<String, FileInfo>(); while (reader.nextTag() != XMLStreamReader.END_ELEMENT) { reader.require(XMLStreamReader.START_ELEMENT, null, "file"); FileInfo info = new FileInfo(); String filename = reader.getAttributeValue(null, "filename"); info.setFilename(filename); info.setE2dkHash(reader.getAttributeValue(null, "ed2k")); info.setFileSize(Long.parseLong(reader.getAttributeValue(null, "length"))); info.setLastModified(Long.parseLong(reader.getAttributeValue(null, "lastmodified"))); info.setMetadataSource(reader.getAttributeValue(null, "metadatasource")); info.setMetadataId(reader.getAttributeValue(null, "metadataid")); info.setVideoId(reader.getAttributeValue(null, "videoid")); files.put(filename, info); XMLUtilities.ignoreTag(reader); } reader.close(); return files; } catch (Exception e) { log.error("Error parsing file cache.", e); return new HashMap<String, FileInfo>(); } finally { if (is != null) { IOUtils.closeQuietly(is); } } }
From source file:net.landora.animeinfo.mylistreader.ListReader.java
public boolean download(InputStream input) throws Throwable { TarInputStream is = null;/*from w w w . j a v a 2 s.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<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:net.landora.anidb.mylist.ListReader.java
public boolean download(InputStream input) throws Throwable { TarInputStream is = null;/*from w w w . j a va 2 s . 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<>(); 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:com.microsoft.windowsazure.storage.table.TableParser.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 ww w . j a v a2 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. */ private static <T extends TableEntity, R> TableResult parseAtomEntity(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); String etag = StringEscapeUtils.unescapeHtml4( xmlr.getAttributeValue(ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.ETAG)); res.setEtag(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)) { 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(readAtomProperties(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().remove(TableConstants.PARTITION_KEY); if (tempProp != null) { partitionKey = tempProp.getValueAsString(); } tempProp = res.getProperties().remove(TableConstants.ROW_KEY); if (tempProp != null) { rowKey = tempProp.getValueAsString(); } tempProp = res.getProperties().remove(TableConstants.TIMESTAMP); if (tempProp != null) { 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:de.huxhorn.sulky.plist.impl.PropertyListReader.java
public PropertyList read(XMLStreamReader reader) throws XMLStreamException { int type = reader.getEventType(); if (XMLStreamConstants.START_DOCUMENT == type) { do {//w ww .j a v a 2s.c o m reader.next(); type = reader.getEventType(); } while (XMLStreamConstants.START_ELEMENT != type); } PropertyList result = new PropertyList(); if (XMLStreamConstants.START_ELEMENT == type && PLIST_NODE.equals(reader.getLocalName())) { reader.nextTag(); type = reader.getEventType(); if (!(XMLStreamConstants.END_ELEMENT == type && PLIST_NODE.equals(reader.getLocalName()))) { result.setRoot(readValue(reader)); } reader.require(XMLStreamConstants.END_ELEMENT, null, PLIST_NODE); } return result; }