List of usage examples for javax.xml.stream XMLStreamReader getAttributeCount
public int getAttributeCount();
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/* w w w . j a v 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:cz.muni.fi.mir.mathmlcanonicalization.MathMLCanonicalizer.java
/** * Loads configuration from XML file, overriding the properties. *//*from w w w. ja v a 2s . 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:jp.co.atware.solr.geta.GETAssocComponent.java
/** * GETAssoc?????<code>NamedList</code>??????? * /* w ww. j av a 2s .co m*/ * @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: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);/*ww w .java 2 s. com*/ 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:com.hp.alm.ali.rest.client.AliRestClient.java
private List<String> getAttributeValues(InputStream xml, String elemName, String attrName) { try {/* w ww. ja v a 2s .c om*/ 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: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); }// w w w .j a v a 2s. c o m } return null; }
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. * // w ww. ja va 2 s. co 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.rapidminer.gui.properties.OperatorPropertyPanel.java
/** * Starts a progress thread which parses the parameter descriptions for the provided operator , * cleans the {@link #parameterDescriptionCache}, and stores parsed descriptions in the * {@link #parameterDescriptionCache}.// w w w . j av a2 s .c om */ private void parseParameterDescriptions(final Operator operator) { parameterDescriptionCache.clear(); URL documentationURL = OperatorDocumentationBrowser.getDocResourcePath(operator); if (documentationURL != null) { try (InputStream documentationStream = documentationURL.openStream()) { XMLStreamReader reader = XML_STREAM_FACTORY.createXMLStreamReader(documentationStream); String parameterKey = null; // The builder that stores the parameter description text StringBuilder parameterTextBuilder = null; boolean inParameters = false; while (reader.hasNext()) { switch (reader.next()) { case XMLStreamReader.START_ELEMENT: if (!inParameters && reader.getLocalName().equals(TAG_PARAMETERS)) { inParameters = true; } else { AttributesImpl attributes = new AttributesImpl(); for (int i = 0; i < reader.getAttributeCount(); i++) { attributes.addAttribute("", reader.getAttributeLocalName(i), reader.getAttributeName(i).toString(), reader.getAttributeType(i), reader.getAttributeValue(i)); } // Check if no parameter was found if (reader.getLocalName().equals(TAG_PARAMETER)) { parameterKey = attributes.getValue(ATTRIBUTE_PARAMETER_KEY); // In case a parameter key was found, create a new string // builder if (parameterKey != null) { parameterTextBuilder = new StringBuilder(); } } if (parameterTextBuilder != null) { appendParameterStartTag(reader.getLocalName(), attributes, parameterTextBuilder); } } break; case XMLStreamReader.END_ELEMENT: // end parsing when end of parameters element is reached if (reader.getLocalName().equals(TAG_PARAMETERS)) { return; } if (parameterTextBuilder != null) { // otherwise add element to description text parameterTextBuilder.append("</"); parameterTextBuilder.append(reader.getLocalName()); parameterTextBuilder.append(">"); // Store description when parameter element ends if (reader.getLocalName().equals(TAG_PARAMETER)) { final String parameterDescription = parameterTextBuilder.toString(); final String key = parameterKey; if (!parameterDescriptionCache.containsKey(parameterKey)) { Source xmlSource = new StreamSource(new StringReader(parameterDescription)); try { String desc = OperatorDocToHtmlConverter.applyXSLTTransformation(xmlSource); parameterDescriptionCache.put(key, StringEscapeUtils.unescapeHtml(desc)); } catch (TransformerException e) { // ignore } } } } break; case XMLStreamReader.CHARACTERS: if (parameterTextBuilder != null) { parameterTextBuilder.append(StringEscapeUtils.escapeHtml(reader.getText())); } break; default: // ignore other events break; } } } catch (IOException | XMLStreamException e) { // ignore } } }
From source file:com.clustercontrol.agent.winevent.WinEventMonitor.java
/** * XMLStAX???EventLogRecord????//from w w w . j a v a2s .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; }
From source file:ddf.catalog.source.solr.DynamicSchemaResolver.java
/** * Given xml as a string, this method will parse out element text and CDATA text. It separates * each by one space character./* w ww. java 2 s .c o m*/ * * @param xmlDatas List of XML as {@code String} * @return parsed CDATA and element text */ protected List<String> parseTextFrom(List<Serializable> xmlDatas) { StringBuilder builder = new StringBuilder(); List<String> parsedTexts = new ArrayList<>(); XMLStreamReader xmlStreamReader = null; StringReader sr = null; long starttime = System.currentTimeMillis(); try { for (Serializable xmlData : xmlDatas) { // xml parser does not handle leading whitespace sr = new StringReader(xmlData.toString()); xmlStreamReader = XML_INPUT_FACTORY.createXMLStreamReader(sr); while (xmlStreamReader.hasNext()) { int event = xmlStreamReader.next(); if (event == XMLStreamConstants.CHARACTERS || event == XMLStreamConstants.CDATA) { String text = xmlStreamReader.getText(); if (StringUtils.isNotBlank(text)) { builder.append(" ").append(text.trim()); } } if (event == XMLStreamConstants.START_ELEMENT) { for (int i = 0; i < xmlStreamReader.getAttributeCount(); i++) { String text = xmlStreamReader.getAttributeValue(i); if (StringUtils.isNotBlank(text)) { builder.append(" ").append(text.trim()); } } } } parsedTexts.add(builder.toString()); builder.setLength(0); } } catch (XMLStreamException e1) { LOGGER.warn("Failure occurred in parsing the xml data. No data has been stored or indexed.", e1); } finally { IOUtils.closeQuietly(sr); if (xmlStreamReader != null) { try { xmlStreamReader.close(); } catch (XMLStreamException e) { LOGGER.debug("Exception closing XMLStreamReader", e); } } } long endTime = System.currentTimeMillis(); LOGGER.debug("Parsing took {} ms", endTime - starttime); return parsedTexts; }