List of usage examples for javax.xml.stream XMLStreamReader getAttributeValue
public String getAttributeValue(String namespaceURI, String localName);
From source file:net.landora.animeinfo.anidb.AniDBHTTPManager.java
public Anime downloadAnime(int aid) { InputStream is = null;/*from w ww . jav a2 s. c om*/ 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:org.maodian.flyingcat.xmpp.state.StreamState.java
private void doHandle(XmppContext context, XMLStreamReader xmlsr, XMLStreamWriter xmlsw) throws XMLStreamException { xmlsr.nextTag();/* w w w . j ava2 s .com*/ QName qname = new QName(XmppNamespace.STREAM, "stream"); if (!xmlsr.getName().equals(qname)) { throw new XmppException(StreamError.INVALID_NAMESPACE).set("QName", xmlsr.getName()); } // throw exception if client version > 1.0 BigDecimal version = new BigDecimal(xmlsr.getAttributeValue("", "version")); if (version.compareTo(SUPPORTED_VERSION) > 0) { throw new XmppException(StreamError.UNSUPPORTED_VERSION); } xmlsw.writeStartDocument(); xmlsw.writeStartElement("stream", "stream", XmppNamespace.STREAM); xmlsw.writeNamespace("stream", XmppNamespace.STREAM); xmlsw.writeDefaultNamespace(XmppNamespace.CLIENT_CONTENT); xmlsw.writeAttribute("id", RandomStringUtils.randomAlphabetic(32)); xmlsw.writeAttribute("version", "1.0"); xmlsw.writeAttribute("from", "localhost"); xmlsw.writeAttribute(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI, "lang", "en"); String from = xmlsr.getAttributeValue(null, "from"); if (from != null) { xmlsw.writeAttribute("to", from); } // features xmlsw.writeStartElement(XmppNamespace.STREAM, "features"); writeFeatures(xmlsw); xmlsw.writeEndElement(); }
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 *///from w ww .j a v a 2 s.c om 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:com.sazneo.export.file.FileProcessor.java
/** * Process the XML file//from w w w .j a v a 2 s . c o m */ 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:au.org.ala.bhl.DocumentPaginator.java
private void paginateImpl(XMLStreamReader parser, PageHandler handler) throws Exception { if (parser == null) { return;//from w w w . java2 s . c o m } StringBuilder buffer = new StringBuilder(); String currentPage = null; while (true) { int event = parser.next(); if (event == XMLStreamConstants.END_DOCUMENT) { parser.close(); break; } if (event == XMLStreamConstants.START_ELEMENT) { if (parser.getLocalName().equals("PARAM")) { String attrName = parser.getAttributeValue("", "name"); if (attrName.equals("PAGE")) { if (!StringUtils.isEmpty(currentPage)) { if (handler != null) { handler.handlePage(currentPage, buffer.toString()); } } buffer = new StringBuilder(); currentPage = parser.getAttributeValue("", "value"); } } } if (event == XMLStreamConstants.CHARACTERS) { String value = StringUtils.trim(parser.getText()); if (!StringUtils.isEmpty(value)) { buffer.append(value).append(" "); } } } }
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 w w w.j a va2 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:net.landora.video.info.file.FileInfoManager.java
private synchronized Map<String, FileInfo> parseCacheFile(File file) { InputStream is = null;/* www. ja va 2 s. c om*/ 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:com.ibm.bi.dml.runtime.controlprogram.parfor.opt.PerfTestTool.java
/** * //from w ww . j a v a2 s . c o m * @param fname * @throws XMLStreamException * @throws IOException */ private static void readProfile(String fname) throws XMLStreamException, IOException { //init profile map _profile = new HashMap<Integer, HashMap<Integer, CostFunction>>(); //read existing profile FileInputStream fis = new FileInputStream(fname); try { //xml parsing XMLInputFactory xif = XMLInputFactory.newInstance(); XMLStreamReader xsr = xif.createXMLStreamReader(fis); int e = xsr.nextTag(); // profile start while (true) //read all instructions { e = xsr.nextTag(); // instruction start if (e == XMLStreamConstants.END_ELEMENT) break; //reached profile end tag //parse instruction int ID = Integer.parseInt(xsr.getAttributeValue(null, XML_ID)); //String name = xsr.getAttributeValue(null, XML_NAME).trim().replaceAll(" ", Lops.OPERAND_DELIMITOR); HashMap<Integer, CostFunction> tmp = new HashMap<Integer, CostFunction>(); _profile.put(ID, tmp); while (true) { e = xsr.nextTag(); // cost function start if (e == XMLStreamConstants.END_ELEMENT) break; //reached instruction end tag //parse cost function TestMeasure m = TestMeasure.valueOf(xsr.getAttributeValue(null, XML_MEASURE)); TestVariable lv = TestVariable.valueOf(xsr.getAttributeValue(null, XML_VARIABLE)); InternalTestVariable[] pv = parseTestVariables( xsr.getAttributeValue(null, XML_INTERNAL_VARIABLES)); DataFormat df = DataFormat.valueOf(xsr.getAttributeValue(null, XML_DATAFORMAT)); int tDefID = getTestDefID(m, lv, df, pv); xsr.next(); //read characters double[] params = parseParams(xsr.getText()); boolean multidim = _regTestDef.get(tDefID).getInternalVariables().length > 1; CostFunction cf = new CostFunction(params, multidim); tmp.put(tDefID, cf); xsr.nextTag(); // cost function end //System.out.println("added cost function"); } } xsr.close(); } finally { IOUtilFunctions.closeSilently(fis); } //mark profile as successfully read _flagReadData = true; }
From source file:com.liferay.portal.util.LocalizationImpl.java
private void _copyNonExempt(XMLStreamReader xmlStreamReader, XMLStreamWriter xmlStreamWriter, String exemptLanguageId, String defaultLanguageId, boolean cdata) throws XMLStreamException { while (xmlStreamReader.hasNext()) { int event = xmlStreamReader.next(); if (event == XMLStreamConstants.START_ELEMENT) { String languageId = xmlStreamReader.getAttributeValue(null, _LANGUAGE_ID); if (Validator.isNull(languageId)) { languageId = defaultLanguageId; }/*from w w w . j a v a2 s. c o m*/ if (!languageId.equals(exemptLanguageId)) { xmlStreamWriter.writeStartElement(xmlStreamReader.getLocalName()); xmlStreamWriter.writeAttribute(_LANGUAGE_ID, languageId); while (xmlStreamReader.hasNext()) { event = xmlStreamReader.next(); if ((event == XMLStreamConstants.CHARACTERS) || (event == XMLStreamConstants.CDATA)) { String text = xmlStreamReader.getText(); if (cdata) { xmlStreamWriter.writeCData(text); } else { xmlStreamWriter.writeCharacters(xmlStreamReader.getText()); } break; } else if (event == XMLStreamConstants.END_ELEMENT) { break; } } xmlStreamWriter.writeEndElement(); } } else if (event == XMLStreamConstants.END_DOCUMENT) { break; } } }
From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.ddi.DDIFileReader.java
private String processLabl(XMLStreamReader xmlr, String level) throws XMLStreamException { String levelAttributeValue = xmlr.getAttributeValue(null, "level"); if (level.equalsIgnoreCase(levelAttributeValue)) { return parseText(xmlr); }//from w w w . j ava2 s . c om throw new XMLStreamException( "Invalid label, level \"" + level + "\" expected, \"" + levelAttributeValue + "\" found."); }