List of usage examples for javax.xml.stream XMLStreamReader getAttributeValue
public String getAttributeValue(int index);
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// www. j av a 2s.co 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:babel.content.pages.PageVersion.java
public void unpersist(XMLStreamReader reader) throws XMLStreamException { String elemTag;/*from ww w.j a v a2s .c om*/ String elemAttrib; m_verProps.clear(); ; m_contentMeta.clear(); m_parseMeta.clear(); m_outLinks = null; m_content = new String(); while (true) { int event = reader.next(); if (event == XMLStreamConstants.END_ELEMENT && XML_TAG_PAGEVERSION.equals(reader.getName().toString())) { break; } if (event == XMLStreamConstants.START_ELEMENT) { elemTag = reader.getName().toString(); elemAttrib = reader.getAttributeValue(0); if ("MetaData".equals(elemTag)) { if ("VersionProperties".equals(elemAttrib)) { m_verProps.unpersist(reader); } else if ("ContentMetadata".equals(elemAttrib)) { m_contentMeta.unpersist(reader); } else if ("ParseMetadata".equals(elemAttrib)) { m_parseMeta.unpersist(reader); } } else if (XML_TAG_CONTENT.equals(elemTag)) { //m_content = new String(Base64.decodeBase64(reader.getElementText().getBytes())); m_content = reader.getElementText(); } //TODO: Not reading the out links } } }
From source file:com.tamingtext.tagrecommender.ExtractStackOverflowData.java
/** Extract as many as <code>limit</code> questions from the <code>reader</code> * provided, writing them to <code>writer</code>. * @param reader/*from w ww .j a va 2 s . c o m*/ * @param writer * @param limit * @return * @throws XMLStreamException */ protected int extractXMLData(XMLStreamReader reader, XMLStreamWriter writer, int limit) throws XMLStreamException { int questionCount = 0; int attrCount; boolean copyElement = false; writer.writeStartDocument(); writer.writeStartElement("posts"); writer.writeCharacters("\n"); while (reader.hasNext() && questionCount < limit) { switch (reader.next()) { case XMLEvent.START_ELEMENT: if (reader.getLocalName().equals("row")) { attrCount = reader.getAttributeCount(); for (int i = 0; i < attrCount; i++) { // copy only the questions. if (reader.getAttributeName(i).getLocalPart().equals("PostTypeId") && reader.getAttributeValue(i).equals("1")) { copyElement = true; break; } } if (copyElement) { writer.writeCharacters(" "); writer.writeStartElement("row"); for (int i = 0; i < attrCount; i++) { writer.writeAttribute(reader.getAttributeName(i).getLocalPart(), reader.getAttributeValue(i)); } writer.writeEndElement(); writer.writeCharacters("\n"); copyElement = false; questionCount++; } } break; } } writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); writer.close(); return questionCount; }
From source file:jp.co.atware.solr.geta.GETAssocComponent.java
/** * GETAssoc?????<code>NamedList</code>??????? * // www . jav a2s .c om * @param inputStream GETAssoc?? * @return <code>NamedList</code>? * @throws FactoryConfigurationError * @throws IOException */ protected NamedList<Object> convertResult(InputStream inputStream) throws FactoryConfigurationError, IOException { NamedList<Object> result = new NamedList<Object>(); LinkedList<NamedList<Object>> stack = new LinkedList<NamedList<Object>>(); stack.push(result); try { XMLStreamReader xml = XMLInputFactory.newInstance().createXMLStreamReader(inputStream); while (xml.hasNext()) { switch (xml.getEventType()) { case XMLStreamConstants.START_ELEMENT: NamedList<Object> element = new NamedList<Object>(); stack.peek().add(xml.getName().toString(), element); stack.push(element); for (int i = 0; i < xml.getAttributeCount(); i++) { String name = xml.getAttributeName(i).toString(); String value = xml.getAttributeValue(i); ValueOf valueOf = valueTransMap.get(name); if (valueOf != null) { try { element.add(name, valueOf.toValue(value)); } catch (NumberFormatException e) { element.add(name, value); } } else { element.add(name, value); } } break; case XMLStreamConstants.END_ELEMENT: stack.pop(); break; default: break; } xml.next(); } xml.close(); } catch (XMLStreamException e) { throw new IOException(e); } LOG.debug(result.toString()); return result; }
From source file:cz.muni.fi.mir.mathmlcanonicalization.MathMLCanonicalizer.java
/** * Loads configuration from XML file, overriding the properties. *///from w w w. j a v a2 s .c o m private void loadXMLConfiguration(InputStream xmlConfigurationStream) throws ConfigException, XMLStreamException { assert xmlConfigurationStream != null; final XMLInputFactory inputFactory = XMLInputFactory.newInstance(); final XMLStreamReader reader = inputFactory.createXMLStreamReader(xmlConfigurationStream); boolean config = false; Module module = null; while (reader.hasNext()) { final int event = reader.next(); switch (event) { case XMLStreamConstants.START_ELEMENT: { String name = reader.getLocalName(); if (name.equals("config")) { config = true; break; } if (config && name.equals("module")) { if (reader.getAttributeCount() == 1) { final String attributeName = reader.getAttributeLocalName(0); final String attributeValue = reader.getAttributeValue(0); if (attributeName.equals("name") && attributeValue != null) { String fullyQualified = Settings.class.getPackage().getName() + ".modules." + attributeValue; try { Class<?> moduleClass = Class.forName(fullyQualified); module = (Module) moduleClass.newInstance(); } catch (InstantiationException ex) { LOGGER.log(Level.SEVERE, ex.getMessage(), ex); throw new ConfigException("cannot instantiate module " + attributeValue, ex); } catch (IllegalAccessException ex) { LOGGER.log(Level.SEVERE, ex.getMessage(), ex); throw new ConfigException("cannot access module " + attributeValue, ex); } catch (ClassNotFoundException ex) { LOGGER.log(Level.SEVERE, ex.getMessage(), ex); throw new ConfigException("cannot load module " + attributeValue, ex); } } } } if (config && name.equals("property")) { if (reader.getAttributeCount() == 1) { final String attributeName = reader.getAttributeLocalName(0); final String attributeValue = reader.getAttributeValue(0); if (attributeName.equals("name") && attributeValue != null) { if (module == null) { if (Settings.isProperty(attributeValue)) { Settings.setProperty(attributeValue, reader.getElementText()); } else { throw new ConfigException("configuration not valid\n" + "Tried to override non-existing global property " + attributeValue); } } else { if (module.isProperty(attributeValue)) { module.setProperty(attributeValue, reader.getElementText()); } else { throw new ConfigException("configuration not valid\n" + "configuration tried to override non-existing property " + attributeValue); } } } } } break; } case XMLStreamConstants.END_ELEMENT: { if (config && reader.getLocalName().equals("module")) { addModule(module); module = null; } if (config && reader.getLocalName().equals("config")) { config = false; } } } } }
From source file:davmail.exchange.ews.EWSMethod.java
protected String getAttributeValue(XMLStreamReader reader, String attributeName) { for (int i = 0; i < reader.getAttributeCount(); i++) { if (attributeName.equals(reader.getAttributeLocalName(i))) { return reader.getAttributeValue(i); }//from www . j a v a 2s. c o m } return null; }
From source file:com.hp.alm.ali.rest.client.AliRestClient.java
private List<String> getAttributeValues(InputStream xml, String elemName, String attrName) { try {//from ww w. j av a2 s. co m XMLInputFactory factory = XmlUtils.createBasicInputFactory(); XMLStreamReader parser; parser = factory.createXMLStreamReader(xml); List<String> result = new LinkedList<String>(); while (true) { int event = parser.next(); if (event == XMLStreamConstants.END_DOCUMENT) { parser.close(); break; } if (event == XMLStreamConstants.START_ELEMENT && elemName.equals(parser.getLocalName())) { for (int i = 0; i < parser.getAttributeCount(); i++) { String localName = parser.getAttributeLocalName(i); if (attrName.equals(localName)) { result.add(parser.getAttributeValue(i)); break; } } } } return result; } catch (XMLStreamException e) { throw new RuntimeException(e); } finally { try { xml.close(); } catch (IOException e) { // ignore } } }
From source file:StAXStreamTreeViewer.java
private void parseRestOfDocument(XMLStreamReader reader, DefaultMutableTreeNode current) throws XMLStreamException { while (reader.hasNext()) { int type = reader.next(); switch (type) { case XMLStreamConstants.START_ELEMENT: DefaultMutableTreeNode element = new DefaultMutableTreeNode(reader.getLocalName()); current.add(element);//from w ww. j a v a2s . c om current = element; if (reader.getNamespaceURI() != null) { String prefix = reader.getPrefix(); if (prefix == null) { prefix = "[None]"; } DefaultMutableTreeNode namespace = new DefaultMutableTreeNode( "prefix = '" + prefix + "', URI = '" + reader.getNamespaceURI() + "'"); current.add(namespace); } if (reader.getAttributeCount() > 0) { for (int i = 0; i < reader.getAttributeCount(); i++) { DefaultMutableTreeNode attribute = new DefaultMutableTreeNode( "Attribute (name = '" + reader.getAttributeLocalName(i) + "', value = '" + reader.getAttributeValue(i) + "')"); String attURI = reader.getAttributeNamespace(i); if (attURI != null) { String attPrefix = reader.getAttributePrefix(i); if (attPrefix == null || attPrefix.equals("")) { attPrefix = "[None]"; } DefaultMutableTreeNode attNamespace = new DefaultMutableTreeNode( "prefix=" + attPrefix + ",URI=" + attURI); attribute.add(attNamespace); } current.add(attribute); } } break; case XMLStreamConstants.END_ELEMENT: current = (DefaultMutableTreeNode) current.getParent(); break; case XMLStreamConstants.CHARACTERS: if (!reader.isWhiteSpace()) { DefaultMutableTreeNode data = new DefaultMutableTreeNode("CD:" + reader.getText()); current.add(data); } break; case XMLStreamConstants.DTD: DefaultMutableTreeNode dtd = new DefaultMutableTreeNode("DTD:" + reader.getText()); current.add(dtd); break; case XMLStreamConstants.SPACE: break; case XMLStreamConstants.COMMENT: DefaultMutableTreeNode comment = new DefaultMutableTreeNode(reader.getText()); current.add(comment); break; default: System.out.println(type); } } }
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 {/* w w w . ja v a 2 s . c o 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:com.clustercontrol.agent.winevent.WinEventMonitor.java
/** * XMLStAX???EventLogRecord????//from w ww . j a v a 2 s . c o m * @param eventXmlStream * @return EventLogRecord? */ private ArrayList<EventLogRecord> parseEventXML(InputStream eventXmlStream) { ArrayList<EventLogRecord> eventlogs = new ArrayList<EventLogRecord>(); try { XMLInputFactory xmlif = XMLInputFactory.newInstance(); /** * OpenJDK7/OracleJDK7??"]"?2????????????????????????????? * ?XML?????????OpenJDK7/OracleJDK7???????/?????????? * URL??????????????? * * URL * http://docs.oracle.com/javase/jp/6/api/javax/xml/stream/XMLStreamReader.html#next() */ String xmlCoalescingKey = "javax.xml.stream.isCoalescing";// TODO JRE??????????????????? if (m_log.isDebugEnabled()) { m_log.debug(xmlCoalescingKey + " = true"); } xmlif.setProperty(xmlCoalescingKey, true); XMLStreamReader xmlr = xmlif.createXMLStreamReader(eventXmlStream); while (xmlr.hasNext()) { switch (xmlr.getEventType()) { case XMLStreamConstants.START_ELEMENT: m_log.trace("EventType : XMLStreamConstants.START_ELEMENT"); String localName = xmlr.getLocalName(); m_log.trace("local name : " + localName); if ("Event".equals(localName)) { EventLogRecord eventlog = new EventLogRecord(); eventlogs.add(eventlog); m_log.debug("create new EventLogRecord"); } else { String attrLocalName = null; String attrValue = null; if (xmlr.getAttributeCount() != 0) { attrLocalName = xmlr.getAttributeLocalName(0); attrValue = xmlr.getAttributeValue(0); m_log.trace("attribute local name : " + attrLocalName); m_log.trace("attribute local value : " + attrValue); } if ("Provider".equals(localName)) { if ("Name".equals(attrLocalName)) { m_log.trace("target value : " + attrValue); EventLogRecord eventlog = eventlogs.get(eventlogs.size() - 1); eventlog.setProviderName(attrValue); m_log.debug("set ProviderName : " + eventlog.getProviderName()); } } // Get-WinEvent/wevtutil.exe else if ("TimeCreated".equals(localName) && "SystemTime".equals(attrLocalName)) { m_log.trace("target value : " + attrValue); // "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z'"???S???????????? String formatedDateString = attrValue.replaceAll("\\..*Z", ""); m_log.trace("formatted target value : " + formatedDateString); DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); EventLogRecord eventlog = eventlogs.get(eventlogs.size() - 1); ; try { eventlog.setTimeCreated(sdf.parse(formatedDateString)); } catch (ParseException e) { // do nothing m_log.error("set TimeCreated Error", e); } m_log.debug("set TimeCreated : " + eventlog.getTimeCreated()); } // Get-EventLog if ("TimeGenerated".equals(localName) && "SystemTime".equals(attrLocalName)) { m_log.trace("target value : " + attrValue); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss'Z'"); sdf.setTimeZone(HinemosTime.getTimeZone()); EventLogRecord eventlog = eventlogs.get(eventlogs.size() - 1); ; try { eventlog.setTimeCreated(sdf.parse(attrValue)); } catch (ParseException e) { // do nothing m_log.error("set TimeCreated Error", e); } m_log.debug("set TimeCreated : " + eventlog.getTimeCreated()); } else { targetProperty = localName; m_log.trace("target property : " + targetProperty); } } break; case XMLStreamConstants.SPACE: case XMLStreamConstants.CHARACTERS: m_log.trace("EventType : XMLStreamConstants.CHARACTERS, length=" + xmlr.getTextLength()); if (targetProperty != null) { try { EventLogRecord eventlog = eventlogs.get(eventlogs.size() - 1); ; if ("EventID".equals(targetProperty)) { eventlog.setId(Integer.parseInt(new String(xmlr.getTextCharacters(), xmlr.getTextStart(), xmlr.getTextLength()))); m_log.debug("set EventID : " + eventlog.getId()); } // Get-WinEvent/wevtutil.exe else if ("Level".equals(targetProperty)) { if (eventlog.getLevel() == WinEventConstant.UNDEFINED) { eventlog.setLevel(Integer.parseInt(new String(xmlr.getTextCharacters(), xmlr.getTextStart(), xmlr.getTextLength()))); m_log.debug("set Level : " + eventlog.getLevel()); } } else if ("Task".equals(targetProperty)) { if (eventlog.getTask() == WinEventConstant.UNDEFINED) { eventlog.setTask(Integer.parseInt(new String(xmlr.getTextCharacters(), xmlr.getTextStart(), xmlr.getTextLength()))); m_log.debug("set Task : " + eventlog.getTask()); } } else if ("Keywords".equals(targetProperty)) { // TODO ????????0x8080000000000000 //eventlog.setKeywords(Long.decode(new String(xmlr.getTextCharacters(), xmlr.getTextStart(), xmlr.getTextLength()))); //m_log.debug("set Keywords : " + eventlog.getKeywords()); } else if ("EventRecordId".equals(targetProperty)) { eventlog.setRecordId(Long.parseLong(new String(xmlr.getTextCharacters(), xmlr.getTextStart(), xmlr.getTextLength()))); m_log.debug("set RecordId : " + eventlog.getRecordId()); } else if ("Channel".equals(targetProperty)) { eventlog.setLogName(new String(xmlr.getTextCharacters(), xmlr.getTextStart(), xmlr.getTextLength())); m_log.debug("set LogName : " + eventlog.getLogName()); } else if ("Computer".equals(targetProperty)) { eventlog.setMachineName(new String(xmlr.getTextCharacters(), xmlr.getTextStart(), xmlr.getTextLength())); m_log.debug("set MachineName : " + eventlog.getMachineName()); } else if ("Message".equals(targetProperty)) { String message = new String(xmlr.getTextCharacters(), xmlr.getTextStart(), xmlr.getTextLength()); message = message.replaceAll(tmpReturnCode, "\r\n"); message = message.replaceAll(tmpLtCode, "<"); message = message.replaceAll(tmpGtCode, ">"); eventlog.setMessage(message); m_log.debug("set Message : " + eventlog.getMessage()); } else if ("Data".equals(targetProperty)) { String data = new String(xmlr.getTextCharacters(), xmlr.getTextStart(), xmlr.getTextLength()); eventlog.getData().add(data); m_log.debug("set Data : " + data); } else { m_log.debug("unknown target property : " + targetProperty); } } catch (NumberFormatException e) { m_log.debug("number parse error", e); } } targetProperty = null; break; default: // break; } xmlr.next(); } xmlr.close(); } catch (XMLStreamException e) { m_log.warn("parseEvent() xmlstream error", e); } return eventlogs; }