public Stack<Map<String, String>> parseXml(File file) throws Exception { String name = "", value; Stack<Map<String, String>> rows = new Stack<>(); XMLStreamReader xr = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream(file)); while (xr.hasNext()) { int e = xr.next(); switch (e) { case XMLStreamReader.START_ELEMENT: { name = xr.getLocalName(); break; } case XMLStreamReader.CHARACTERS: { Map<String, String> map = newHashMap(); value = xr.getText(); map.put(name, value); rows.push(map); break; } } } return rows; }
private final void expectTag(String expElem, XMLStreamReader sr) throws XMLStreamException { if (!expElem.equals(sr.getLocalName())) { throw new XMLStreamException( "Unexpected element <" + sr.getLocalName() + ">: expecting <" + expElem + ">", sr.getLocation()); } }
protected Object wbxmlStream2Object(InputStream in, boolean event) throws Exception { XMLStreamReader xmlStreamReader = null; XMLEventReader xmlEventReader = null; try { if (event) { xmlEventReader = inFact.createXMLEventReader(in); } else { xmlStreamReader = inFact.createXMLStreamReader(in); } if (jc == null) { jc = JAXBContext.newInstance(Class.forName(this.def.getClazz())); } Unmarshaller unmarshaller = jc.createUnmarshaller(); if (event) { return unmarshaller.unmarshal(xmlEventReader); } else { return unmarshaller.unmarshal(xmlStreamReader); } } finally { if (xmlStreamReader != null) { try { xmlStreamReader.close(); } catch (Exception e) { } } if (xmlEventReader != null) { try { xmlEventReader.close(); } catch (Exception e) { } } } }
public static void parse(final XMLStreamReader reader, final XmlRpcListener listener) throws XMLStreamException, XmlRpcException { listener.startResponse(); boolean paramDetected = false; boolean faultDetected = false; int type = -1; do { type = reader.nextTag(); if (type == START_ELEMENT) { final String tag = reader.getName().getLocalPart(); if (XmlRpcConstants.FAULT.equals(tag)) { faultDetected = true; FaultHelper.parse(reader, listener); break; } else if (XmlRpcConstants.PARAMS.equals(tag)) { paramDetected = true; ParamHelper.parse(reader, listener); } } else if (type == XMLStreamReader.END_ELEMENT && XmlRpcConstants.RESPONSE.equals(reader.getName().getLocalPart())) { break; } } while (type != END_DOCUMENT); if (paramDetected && faultDetected) { throw new XmlRpcException("Cannot specify both fault and parameters in XML-RPC response."); } listener.endResponse(); }
protected Way parseWay() throws XMLStreamException { WayData wd = new WayData(); readCommon(wd); Way w = new Way(wd.getId(), wd.getVersion()); w.setVisible(wd.isVisible()); w.load(wd); externalIdMap.put(wd.getPrimitiveId(), w); Collection<Long> nodeIds = new ArrayList<Long>(); while (true) { int event = parser.next(); if (event == XMLStreamConstants.START_ELEMENT) { if (parser.getLocalName().equals("nd")) { nodeIds.add(parseWayNode(w)); } else if (parser.getLocalName().equals("tag")) { parseTag(w); } else { parseUnknown(); } } else if (event == XMLStreamConstants.END_ELEMENT) { break; } } if (w.isDeleted() && nodeIds.size() > 0) { System.out.println(tr("Deleted way {0} contains nodes", w.getUniqueId())); nodeIds = new ArrayList<Long>(); } ways.put(wd.getUniqueId(), nodeIds); return w; }
public static ContainerListenerMetaData parse(XMLStreamReader reader) throws XMLStreamException { ContainerListenerMetaData containerListener = new ContainerListenerMetaData(); // Handle elements while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { final Element element = Element.forName(reader.getLocalName()); switch (element) { case CLASS_NAME: containerListener.setListenerClass(getElementText(reader)); break; case MODULE: containerListener.setModule(getElementText(reader)); break; case LISTENER_TYPE: containerListener.setListenerType(ContainerListenerType.valueOf(getElementText(reader))); break; case PARAM: List<ParamValueMetaData> params = containerListener.getParams(); if (params == null) { params = new ArrayList<ParamValueMetaData>(); containerListener.setParams(params); } params.add(ParamValueMetaDataParser.parse(reader)); break; default: throw unexpectedElement(reader); } } return containerListener; }
private static void parse(XMLStreamReader reader, URL wsdlUrl, Set<String> excludedPorts) throws XMLStreamException, WiseRuntimeException { int iterate; try { iterate = reader.nextTag(); } catch (XMLStreamException e) { // skip non-tag elements iterate = reader.nextTag(); } switch (iterate) { case END_ELEMENT: { // we're done break; } case START_ELEMENT: { if (match(reader, WSDL_NS, DEFINITIONS)) { String targetNS = reader.getAttributeValue(null, TARGET_NAMESPACE); parseDefinitions(reader, targetNS, wsdlUrl, excludedPorts); } else { throw new WiseRuntimeException( "Unexpected element '" + reader.getLocalName() + "' found parsing " + wsdlUrl.toExternalForm()); } } } }
private static void parseResources( final File root, final XMLStreamReader reader, final ModuleSpec.Builder specBuilder) throws XMLStreamException { // xsd:choice while (reader.hasNext()) { switch (reader.nextTag()) { case XMLStreamConstants.END_ELEMENT: { return; } case XMLStreamConstants.START_ELEMENT: { switch (Element.of(reader.getName())) { case RESOURCE_ROOT: { parseResourceRoot(root, reader, specBuilder); break; } default: throw unexpectedContent(reader); } break; } default: { throw unexpectedContent(reader); } } } throw endOfDocument(reader.getLocation()); }
private static void parseFilterList( final XMLStreamReader reader, final MultiplePathFilterBuilder builder) throws XMLStreamException { // xsd:choice while (reader.hasNext()) { switch (reader.nextTag()) { case XMLStreamConstants.END_ELEMENT: { return; } case XMLStreamConstants.START_ELEMENT: { switch (Element.of(reader.getName())) { case INCLUDE: parsePath(reader, true, builder); break; case EXCLUDE: parsePath(reader, false, builder); break; default: throw unexpectedContent(reader); } break; } default: { throw unexpectedContent(reader); } } } throw endOfDocument(reader.getLocation()); }
private static ModuleSpec parseDocument( final File root, XMLStreamReader reader, ModuleSpec.Builder specBuilder) throws XMLStreamException { while (reader.hasNext()) { switch (reader.nextTag()) { case XMLStreamConstants.START_DOCUMENT: { parseRootElement(root, reader, specBuilder); return specBuilder.create(); } case XMLStreamConstants.START_ELEMENT: { if (Element.of(reader.getName()) != Element.MODULE) { throw unexpectedContent(reader); } parseModuleContents(root, reader, specBuilder); parseEndDocument(reader); return specBuilder.create(); } default: { throw unexpectedContent(reader); } } } throw endOfDocument(reader.getLocation()); }
private static void parseDependencies( final XMLStreamReader reader, final ModuleSpec.Builder specBuilder) throws XMLStreamException { // xsd:choice while (reader.hasNext()) { switch (reader.nextTag()) { case XMLStreamConstants.END_ELEMENT: { return; } case XMLStreamConstants.START_ELEMENT: { switch (Element.of(reader.getName())) { case MODULE: parseModuleDependency(reader, specBuilder); break; default: throw unexpectedContent(reader); } break; } default: { throw unexpectedContent(reader); } } } throw endOfDocument(reader.getLocation()); }
public int next() throws XMLStreamException { switch (state) { case STATE_START_DOCUMENT: state = STATE_IN_FRAGMENT; return START_ELEMENT; case STATE_IN_FRAGMENT: int type = parent.next(); switch (type) { case START_ELEMENT: depth++; break; case END_ELEMENT: if (depth == 0) { state = STATE_FRAGMENT_END; } else { depth--; } } return type; case STATE_FRAGMENT_END: // Consume the event from the parent to put the parser in a well-defined state parent.next(); state = STATE_END_DOCUMENT; return END_DOCUMENT; default: throw new NoSuchElementException("End of document reached"); } }
private WikiObjectProperty readObjectProperty(XMLStreamReader xmlReader, WikiClass wikiClass) throws XMLStreamException, FilterException { xmlReader.nextTag(); WikiObjectProperty property = new WikiObjectProperty(); property.name = xmlReader.getLocalName(); String type; if (wikiClass != null) { WikiClassProperty classProperty = wikiClass.properties.get(property.name); type = classProperty != null ? classProperty.type : null; } else { type = null; } try { property.value = this.propertySerializerManager.getPropertySerializer(type).read(xmlReader); } catch (ComponentLookupException e) { throw new FilterException("Failed to get a property parser", e); } xmlReader.nextTag(); return property; }
@Override public WikiObject read(XMLStreamReader xmlReader) throws XMLStreamException, FilterException { WikiObject wikiObject = new WikiObject(); for (xmlReader.nextTag(); xmlReader.isStartElement(); xmlReader.nextTag()) { String elementName = xmlReader.getLocalName(); if (elementName.equals(XARClassModel.ELEMENT_CLASS)) { wikiObject.wikiClass = this.classReader.read(xmlReader); } else if (elementName.equals(XARObjectPropertyModel.ELEMENT_PROPERTY)) { wikiObject.properties.add(readObjectProperty(xmlReader, wikiObject.wikiClass)); } else { String value = xmlReader.getElementText(); EventParameter parameter = XARObjectModel.OBJECT_PARAMETERS.get(elementName); if (parameter != null) { Object wsValue = convert(parameter.type, value); if (wsValue != null) { wikiObject.parameters.put(parameter.name, wsValue); } } } } return wikiObject; }
/** * Processes elements and its sub-elements. * * @param reader XML stream reader * @throws XMLStreamException Thrown if problem occurred while reading XML stream. * @throws SQLException Thrown if problem occurred while communicating with database. */ private static void processElement(final XMLStreamReader reader) throws XMLStreamException, SQLException { switch (reader.getNamespaceURI()) { case Namespaces.VYMENNY_FORMAT_TYPY: switch (reader.getLocalName()) { case "VymennyFormat": exchangeFormatConvertor.convert(reader); break; default: XMLUtils.processUnsupported(reader); } break; case Namespaces.SPECIALNI_VYMENNY_FORMAT_TYPY: switch (reader.getLocalName()) { case "SpecialniVymennyFormat": specialExchangeFormatConvertor.convert(reader); break; default: XMLUtils.processUnsupported(reader); } break; default: XMLUtils.processUnsupported(reader); } }
private static void parsePath( final XMLStreamReader reader, final boolean include, final MultiplePathFilterBuilder builder) throws XMLStreamException { String path = null; final Set<Attribute> required = EnumSet.of(Attribute.PATH); final int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { final Attribute attribute = Attribute.of(reader.getAttributeName(i)); required.remove(attribute); switch (attribute) { case PATH: path = reader.getAttributeValue(i); break; default: throw unexpectedContent(reader); } } if (!required.isEmpty()) { throw missingAttributes(reader.getLocation(), required); } builder.addFilter(PathFilters.match(path), include); // consume remainder of element parseNoContent(reader); }
@Override protected void readAttributes(XMLStreamReader reader, MdmiBusinessElementRule object) { object.setName(reader.getAttributeValue(null, BusinessElemRuleValidate.s_nameField)); object.setDescription(reader.getAttributeValue(null, BusinessElemRuleValidate.s_descName)); object.setRuleExpressionLanguage( reader.getAttributeValue(null, BusinessElemRuleValidate.s_ruleLangName)); }
private static void parseEndDocument(final XMLStreamReader reader) throws XMLStreamException { while (reader.hasNext()) { switch (reader.next()) { case XMLStreamConstants.END_DOCUMENT: { return; } case XMLStreamConstants.CHARACTERS: { if (!reader.isWhiteSpace()) { throw unexpectedContent(reader); } // ignore break; } case XMLStreamConstants.COMMENT: case XMLStreamConstants.SPACE: { // ignore break; } default: { throw unexpectedContent(reader); } } } return; }
protected static XMLStreamReader2 constructStreamReaderForFile(XMLInputFactory f, String filename) throws IOException, XMLStreamException { File inf = new File(filename); XMLStreamReader sr = f.createXMLStreamReader(inf.toURL().toString(), new FileReader(inf)); assertEquals(sr.getEventType(), START_DOCUMENT); return (XMLStreamReader2) sr; }
public static void traverse(XMLStreamReader streamReader, StaxClosure closure) throws XMLStreamException { while (streamReader.hasNext()) { streamReader.next(); closure.process(streamReader); } }
@Override public ISORecord inspect(ISORecord record, Connection conn, SQLDialect dialect) throws MetadataInspectorException { ISORecord result = record; try { // create temporary sink for normalized XML ByteArrayOutputStream bos = new ByteArrayOutputStream(); XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(bos); writer = new NamespaceNormalizingXMLStreamWriter(writer, nsBindings); // create normalized copy XMLStreamReader reader = record.getAsXMLStream(); XMLAdapter.writeElement(writer, reader); reader.close(); writer.close(); InputStream is = new ByteArrayInputStream(bos.toByteArray()); XMLStreamReader xmlStream = XMLInputFactory.newInstance().createXMLStreamReader(is); result = new ISORecord(xmlStream); } catch (Throwable t) { LOG.error( "Namespace normalization failed. Proceeding with unnormalized record. Error: " + t.getMessage()); } return result; }
/** * FIXME Comment this * * @param reader * @param attributeName * @return the string representing raw attribute textx */ private String rawAttributeText(XMLStreamReader reader, String attributeName) { String attributeString = reader.getAttributeValue("", attributeName) == null ? null : reader.getAttributeValue("", attributeName).trim(); return attributeString; }
private void parseBounds(String generator) throws XMLStreamException { String minlon = parser.getAttributeValue(null, "minlon"); String minlat = parser.getAttributeValue(null, "minlat"); String maxlon = parser.getAttributeValue(null, "maxlon"); String maxlat = parser.getAttributeValue(null, "maxlat"); String origin = parser.getAttributeValue(null, "origin"); if (minlon != null && maxlon != null && minlat != null && maxlat != null) { if (origin == null) { origin = generator; } Bounds bounds = new Bounds( Double.parseDouble(minlat), Double.parseDouble(minlon), Double.parseDouble(maxlat), Double.parseDouble(maxlon)); if (bounds.isOutOfTheWorld()) { Bounds copy = new Bounds(bounds); bounds.normalize(); System.out.println("Bbox " + copy + " is out of the world, normalized to " + bounds); } DataSource src = new DataSource(bounds, origin); ds.dataSources.add(src); } else { throwException( tr( "Missing mandatory attributes on element ''bounds''. Got minlon=''{0}'',minlat=''{1}'',maxlon=''{3}'',maxlat=''{4}'', origin=''{5}''.", minlon, minlat, maxlon, maxlat, origin)); } jumpToEnd(); }
private void parseArtifactVersions( final XMLStreamReader reader, final FeaturePackDescription result) throws XMLStreamException { final Set<Artifact> artifactVersions = result.getArtifactVersions(); while (reader.hasNext()) { switch (reader.nextTag()) { case XMLStreamConstants.END_ELEMENT: { return; } case XMLStreamConstants.START_ELEMENT: { final Element element = Element.of(reader.getName()); switch (element) { case ARTIFACT: artifactVersions.add(parseArtifact(reader)); break; default: throw ParsingUtils.unexpectedContent(reader); } break; } default: { throw ParsingUtils.unexpectedContent(reader); } } } throw ParsingUtils.endOfDocument(reader.getLocation()); }
protected Relation parseRelation() throws XMLStreamException { RelationData rd = new RelationData(); readCommon(rd); Relation r = new Relation(rd.getId(), rd.getVersion()); r.setVisible(rd.isVisible()); r.load(rd); externalIdMap.put(rd.getPrimitiveId(), r); Collection<RelationMemberData> members = new ArrayList<RelationMemberData>(); while (true) { int event = parser.next(); if (event == XMLStreamConstants.START_ELEMENT) { if (parser.getLocalName().equals("member")) { members.add(parseRelationMember(r)); } else if (parser.getLocalName().equals("tag")) { parseTag(r); } else { parseUnknown(); } } else if (event == XMLStreamConstants.END_ELEMENT) { break; } } if (r.isDeleted() && members.size() > 0) { System.out.println(tr("Deleted relation {0} contains members", r.getUniqueId())); members = new ArrayList<RelationMemberData>(); } relations.put(rd.getUniqueId(), members); return r; }
/** * Post: reader will be unchanged or on success at {@link XMLStreamConstants #END_ELEMENT} of the * matching element or at {@link XMLStreamConstants #START_ELEMENT} of the next element if * requested. * * @param reader pointing to the current element. * @param elementName of the current element. * @param defaultValue to return if the current name was not the one given or the value could not * be parsed as a integer. * @param nextElemOnSucces if true the reader will be moved to the next tag if the retrieval was * successful. * @return the text of the current element (which should have element name) parsed as a integer. * @throws XMLStreamException from {@link XMLStreamReader#getElementText()}. */ public static int getElementTextAsInteger( XMLStreamReader reader, QName elementName, int defaultValue, boolean nextElemOnSucces) throws XMLStreamException { int value = defaultValue; if (elementName.equals(reader.getName()) && reader.isStartElement()) { String s = reader.getElementText(); if (s != null) { try { value = Integer.parseInt(s); if (nextElemOnSucces) { nextElement(reader); } } catch (NumberFormatException nfe) { LOG.debug( reader.getLocation() + ") Value " + s + " in element: " + elementName + " was not a parsable integer, returning integer value: " + defaultValue); } } } return value; }
protected Document wbxmlStream2Doc(InputStream in, boolean event) throws Exception { XMLStreamReader xmlStreamReader = null; XMLEventReader xmlEventReader = null; try { if (event) { xmlEventReader = inFact.createXMLEventReader(in); } else { xmlStreamReader = inFact.createXMLStreamReader(in); } Transformer xformer = TransformerFactory.newInstance().newTransformer(); StAXSource staxSource = event ? new StAXSource(xmlEventReader) : new StAXSource(xmlStreamReader); DOMResult domResult = new DOMResult(); xformer.transform(staxSource, domResult); Document doc = (Document) domResult.getNode(); doc.normalize(); return doc; } finally { if (xmlStreamReader != null) { try { xmlStreamReader.close(); } catch (Exception e) { } } if (xmlEventReader != null) { try { xmlEventReader.close(); } catch (Exception e) { } } } }
/** * Returns the attributes of the element that the given {@link XMLStreamReader} points to. * * @param reader xml stream, must not be <code>null</code> and point to a {@link * XMLStreamConstants#START_ELEMENT} * @return attributes of the element, can be empty, but never <code>null</code> */ public static Map<QName, String> getAttributes(XMLStreamReader reader) { HashMap<QName, String> attrs = new HashMap<QName, String>(); for (int i = 0; i < reader.getAttributeCount(); i++) { attrs.put(reader.getAttributeName(i), reader.getAttributeValue(i)); } return attrs; }
private List<String> getPackageNamesFromGuvnor() { List<String> packages = new ArrayList<String>(); String packagesURL = getGuvnorProtocol() + "://" + getGuvnorHost() + "/" + getGuvnorSubdomain() + "/rest/packages/"; try { XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader reader = factory.createXMLStreamReader(getInputStreamForURL(packagesURL, "GET")); while (reader.hasNext()) { if (reader.next() == XMLStreamReader.START_ELEMENT) { if ("title".equals(reader.getLocalName())) { String pname = reader.getElementText(); if (!pname.equalsIgnoreCase("Packages")) { packages.add(pname); } } } } } catch (Exception e) { logger.error("Error retriving packages from guvnor: " + e.getMessage()); } return packages; }
private static boolean get( XMLStreamReader parser, String xmlElem, String[] xmlNames, String[] strRet) { boolean ret = true; int maxElem = strRet.length; for (int i = 0; i < maxElem; ++i) { strRet[i] = ""; } try { while (parser.hasNext()) { int event = parser.next(); if (event == XMLStreamConstants.END_ELEMENT) { if (parser.getLocalName().equals(xmlElem)) { break; } } if (event == XMLStreamConstants.START_ELEMENT) { for (int i = 0; i < maxElem; ++i) { if (parser.getLocalName().equals(xmlNames[i])) { strRet[i] = parser.getElementText(); break; } } } } } catch (Exception ex) { ret = false; Log.fehlerMeldung(467256394, ex); } return ret; }