List of usage examples for javax.xml.stream XMLStreamConstants END_DOCUMENT
int END_DOCUMENT
To view the source code for javax.xml.stream XMLStreamConstants END_DOCUMENT.
Click Source Link
From source file:com.graphhopper.reader.osm.OSMInputFile.java
private ReaderElement getNextXML() throws XMLStreamException { int event = parser.next(); if (fileheader != null) { ReaderElement copyfileheader = fileheader; fileheader = null;//from ww w .j a va 2 s .c o m return copyfileheader; } while (event != XMLStreamConstants.END_DOCUMENT) { if (event == XMLStreamConstants.START_ELEMENT) { String idStr = parser.getAttributeValue(null, "id"); if (idStr != null) { String name = parser.getLocalName(); long id = 0; switch (name.charAt(0)) { case 'n': // note vs. node if ("node".equals(name)) { id = Long.parseLong(idStr); return OSMXMLHelper.createNode(id, parser); } break; case 'w': { id = Long.parseLong(idStr); return OSMXMLHelper.createWay(id, parser); } case 'r': id = Long.parseLong(idStr); return OSMXMLHelper.createRelation(id, parser); } } } event = parser.next(); } parser.close(); return null; }
From source file:com.flexive.chemistry.webdav.TextDocumentResource.java
/** * Set the value of a property, stream points to the start of the property tag. * * @param parser the XML parser//from w w w . j a v a 2 s. c om * @throws XMLStreamException on parsing errors */ protected void processProperty(XMLStreamReader parser) throws XMLStreamException { int level = 0; String name = null; for (int i = 0; i < parser.getAttributeCount(); i++) { if ("name".equals(parser.getAttributeName(i).getLocalPart())) { name = parser.getAttributeValue(i); break; } } if (name == null) { if (LOG.isTraceEnabled()) { LOG.trace("property without name attribute encountered"); } return; } String value = null; for (int event = parser.nextTag(); event != XMLStreamConstants.END_DOCUMENT && level >= 0; event = parser.nextTag()) { switch (event) { case XMLStreamConstants.START_ELEMENT: if ("value".equals(parser.getLocalName())) { value = parser.getElementText().trim(); } else if ("name".equals(parser.getLocalName())) { name = parser.getElementText(); } else { level++; } break; case XMLStreamConstants.END_ELEMENT: level--; break; } } if (value != null) { if (LOG.isTraceEnabled()) { LOG.trace("Setting field " + name + " to " + value); } try { object.setValue(name, value); } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("Failed to set field " + name + " (ignored): " + e.getMessage()); } } } }
From source file:com.liferay.portal.util.LocalizationImpl.java
public String getLocalization(String xml, String requestedLanguageId, boolean useDefault) { String value = _getCachedValue(xml, requestedLanguageId, useDefault); if (value != null) { return value; } else {//from w ww . j ava 2s .c om value = StringPool.BLANK; } String systemDefaultLanguageId = LocaleUtil.toLanguageId(LocaleUtil.getDefault()); String priorityLanguageId = null; Locale requestedLocale = LocaleUtil.fromLanguageId(requestedLanguageId); if (useDefault && LanguageUtil.isDuplicateLanguageCode(requestedLocale.getLanguage())) { Locale priorityLocale = LanguageUtil.getLocale(requestedLocale.getLanguage()); if (!requestedLanguageId.equals(priorityLanguageId)) { priorityLanguageId = LocaleUtil.toLanguageId(priorityLocale); } } if (!Validator.isXml(xml)) { if (useDefault || requestedLanguageId.equals(systemDefaultLanguageId)) { value = xml; } _setCachedValue(xml, requestedLanguageId, useDefault, value); return value; } XMLStreamReader xmlStreamReader = null; ClassLoader portalClassLoader = PortalClassLoaderUtil.getClassLoader(); Thread currentThread = Thread.currentThread(); ClassLoader contextClassLoader = currentThread.getContextClassLoader(); try { if (contextClassLoader != portalClassLoader) { currentThread.setContextClassLoader(portalClassLoader); } XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlStreamReader = xmlInputFactory.createXMLStreamReader(new UnsyncStringReader(xml)); String defaultLanguageId = StringPool.BLANK; // Skip root node if (xmlStreamReader.hasNext()) { xmlStreamReader.nextTag(); defaultLanguageId = xmlStreamReader.getAttributeValue(null, _DEFAULT_LOCALE); if (Validator.isNull(defaultLanguageId)) { defaultLanguageId = systemDefaultLanguageId; } } // Find specified language and/or default language String defaultValue = StringPool.BLANK; String priorityValue = StringPool.BLANK; 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; } if (languageId.equals(defaultLanguageId) || languageId.equals(priorityLanguageId) || languageId.equals(requestedLanguageId)) { String text = xmlStreamReader.getElementText(); if (languageId.equals(defaultLanguageId)) { defaultValue = text; } if (languageId.equals(priorityLanguageId)) { priorityValue = text; } if (languageId.equals(requestedLanguageId)) { value = text; } if (Validator.isNotNull(value)) { break; } } } else if (event == XMLStreamConstants.END_DOCUMENT) { break; } } if (useDefault && Validator.isNotNull(priorityLanguageId) && Validator.isNull(value) && Validator.isNotNull(priorityValue)) { value = priorityValue; } if (useDefault && Validator.isNull(value)) { value = defaultValue; } } catch (Exception e) { if (_log.isWarnEnabled()) { _log.warn(e, e); } } finally { if (contextClassLoader != portalClassLoader) { currentThread.setContextClassLoader(contextClassLoader); } if (xmlStreamReader != null) { try { xmlStreamReader.close(); } catch (Exception e) { } } } _setCachedValue(xml, requestedLanguageId, useDefault, value); return value; }
From source file:fr.inria.oak.paxquery.pact.io.XmlNavTreePatternInputFormat.java
@Override public Record nextRecord(Record record) throws IOException { if (this.pactRecordsIterator != null) { if (this.pactRecordsIterator.hasNext()) { if (this.attachDocumentID) { record.addField(new StringValue(this.documentID)); RecordOperations.concatenate(record, this.pactRecordsIterator.next()); } else this.pactRecordsIterator.next().copyTo(record); //return true; return record; }/*from ww w .j a va 2s . c o m*/ this.pactRecordsIterator = null; this.extractor.getRecords().clear(); } try { while (this.streamReader.hasNext()) { this.streamReader.next(); if (this.streamReader.getEventType() == XMLStreamConstants.START_ELEMENT) { this.extractor.startElement(); } else if (this.streamReader.getEventType() == XMLStreamConstants.END_ELEMENT) { this.extractor.endElement(); } else if (this.streamReader.getEventType() == XMLStreamConstants.CHARACTERS) { this.extractor.characters(); } else if (this.streamReader.getEventType() == XMLStreamConstants.END_DOCUMENT) { this.reachedEnd = true; } if (this.extractor.getRecords().size() != 0) { this.pactRecordsIterator = this.extractor.getRecords().iterator(); if (this.attachDocumentID) { record.addField(new StringValue(this.documentID)); RecordOperations.concatenate(record, this.pactRecordsIterator.next()); } else this.pactRecordsIterator.next().copyTo(record); //return true; return record; } } //return false; return null; } catch (XMLStreamException e) { logger.error("XMLStreamException", e); //return false; return null; } }
From source file:org.javelin.sws.ext.bind.internal.model.ComplexTypePattern.java
@Override public T consumeValue(XMLEventReader eventReader, UnmarshallingContext context) throws XMLStreamException { // first create an object to be filled (using PropertyAccessors - direct or bean) according to the content model T object = BeanUtils.instantiate(this.getJavaType()); // the order is dictated by incoming events, not by the mode // TODO: create a property to enable strict unmarshalling - dictated by content model // only this (ContentModel) pattern iterates over XML Events XMLEvent event = null;//from ww w . ja v a2 s .c o m PropertyMetadataValue<T, ?> pmv = null; // this loop will only handle first level of start elements and only single end element // deeper levels will be handled by nested patterns while (true) { boolean end = false; event = eventReader.peek(); pmv = null; switch (event.getEventType()) { case XMLStreamConstants.ATTRIBUTE: pmv = this.consumeNestedAttribute(eventReader, context); break; case XMLStreamConstants.CDATA: case XMLStreamConstants.CHARACTERS: // TODO: XMLEvent.ENTITY_REFERENCE? if (this.simpleContent != null) { pmv = this.consumeSimpleContent(eventReader, context); break; } case XMLStreamConstants.COMMENT: case XMLStreamConstants.DTD: case XMLStreamConstants.SPACE: case XMLStreamConstants.ENTITY_DECLARATION: case XMLStreamConstants.NOTATION_DECLARATION: case XMLStreamConstants.PROCESSING_INSTRUCTION: eventReader.nextEvent(); break; case XMLStreamConstants.ENTITY_REFERENCE: // TODO: XMLEvent.ENTITY_REFERENCE? eventReader.nextEvent(); break; case XMLStreamConstants.START_DOCUMENT: // strange break; case XMLStreamConstants.START_ELEMENT: pmv = this.consumeNestedElement(eventReader, context); break; case XMLStreamConstants.END_ELEMENT: // TODO: in mixed content there will be more than one end element it this content model's level case XMLStreamConstants.END_DOCUMENT: end = true; break; } if (end) break; if (pmv != null) pmv.getMetadata().setValue(object, pmv.getValue()); } return (T) object; }
From source file:com.evolveum.polygon.connector.hcm.DocumentProcessing.java
public Map<String, Object> parseXMLData(HcmConnectorConfiguration conf, ResultsHandler handler, Map<String, Object> schemaAttributeMap, Filter query) { XMLInputFactory factory = XMLInputFactory.newInstance(); try {/*from w w w .java 2s. c o m*/ String uidAttributeName = conf.getUidAttribute(); String primariId = conf.getPrimaryId(); String startName = ""; String value = null; StringBuilder assignmentXMLBuilder = null; List<String> builderList = new ArrayList<String>(); Integer nOfIterations = 0; Boolean isSubjectToQuery = false; Boolean isAssigment = false; Boolean evaluateAttr = true; Boolean specificAttributeQuery = false; XMLEventReader eventReader = factory.createXMLEventReader(new FileReader(conf.getFilePath())); List<String> dictionary = populateDictionary(FIRSTFLAG); if (!attrsToGet.isEmpty()) { attrsToGet.add(uidAttributeName); attrsToGet.add(primariId); specificAttributeQuery = true; evaluateAttr = false; LOGGER.ok("The uid and primary id were added to the queried attribute list"); schemaAttributeMap = modifySchemaAttributeMap(schemaAttributeMap); } while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); Integer code = event.getEventType(); if (code == XMLStreamConstants.START_ELEMENT) { StartElement startElement = event.asStartElement(); startName = startElement.getName().getLocalPart(); if (!evaluateAttr && attrsToGet.contains(startName)) { evaluateAttr = true; } if (!elementIsEmployeeData) { if (startName.equals(EMPLOYEES)) { if (dictionary.contains(nOfIterations.toString())) { LOGGER.ok("The defined number of iterations has been hit: {0}", nOfIterations.toString()); break; } else { startName = ""; elementIsEmployeeData = true; nOfIterations++; } } } else if (evaluateAttr) { if (!isAssigment) { if (!ASSIGNMENTTAG.equals(startName)) { } else { assignmentXMLBuilder = new StringBuilder(); isAssigment = true; } } else { builderList = processAssignment(startName, null, START, builderList); } if (multiValuedAttributesList.contains(startName)) { elementIsMultiValued = true; } } } else if (elementIsEmployeeData) { if (code == XMLStreamConstants.CHARACTERS && evaluateAttr) { Characters characters = event.asCharacters(); if (!characters.isWhiteSpace()) { StringBuilder valueBuilder; if (value != null) { valueBuilder = new StringBuilder(value).append("") .append(characters.getData().toString()); } else { valueBuilder = new StringBuilder(characters.getData().toString()); } value = valueBuilder.toString(); // value = StringEscapeUtils.escapeXml10(value); // LOGGER.info("The attribute value for: {0} is // {1}", startName, value); } } else if (code == XMLStreamConstants.END_ELEMENT) { EndElement endElement = event.asEndElement(); String endName = endElement.getName().getLocalPart(); isSubjectToQuery = checkFilter(endName, value, query, uidAttributeName); if (!isSubjectToQuery) { attributeMap.clear(); elementIsEmployeeData = false; value = null; endName = EMPLOYEES; } if (endName.equals(EMPLOYEES)) { attributeMap = handleEmployeeData(attributeMap, schemaAttributeMap, handler, uidAttributeName, primariId); elementIsEmployeeData = false; } else if (evaluateAttr) { if (endName.equals(startName)) { if (value != null) { if (!isAssigment) { if (!elementIsMultiValued) { attributeMap.put(startName, value); } else { multiValuedAttributeBuffer.put(startName, value); } } else { value = StringEscapeUtils.escapeXml10(value); builderList = processAssignment(endName, value, VALUE, builderList); builderList = processAssignment(endName, null, END, builderList); } // LOGGER.info("Attribute name: {0} and the // Attribute value: {1}", endName, value); value = null; } } else { if (endName.equals(ASSIGNMENTTAG)) { builderList = processAssignment(endName, null, CLOSE, builderList); // if (assigmentIsActive) { for (String records : builderList) { assignmentXMLBuilder.append(records); } attributeMap.put(ASSIGNMENTTAG, assignmentXMLBuilder.toString()); // } else { // } builderList = new ArrayList<String>(); // assigmentIsActive = false; isAssigment = false; } else if (multiValuedAttributesList.contains(endName)) { processMultiValuedAttributes(multiValuedAttributeBuffer); } } } if (specificAttributeQuery && evaluateAttr) { evaluateAttr = false; } } } else if (code == XMLStreamConstants.END_DOCUMENT) { handleBufferedData(uidAttributeName, primariId, handler); } } } catch (FileNotFoundException e) { StringBuilder errorBuilder = new StringBuilder("File not found at the specified path.") .append(e.getLocalizedMessage()); LOGGER.error("File not found at the specified path: {0}", e); throw new ConnectorIOException(errorBuilder.toString()); } catch (XMLStreamException e) { LOGGER.error("Unexpected processing error while parsing the .xml document : {0}", e); StringBuilder errorBuilder = new StringBuilder( "Unexpected processing error while parsing the .xml document. ") .append(e.getLocalizedMessage()); throw new ConnectorIOException(errorBuilder.toString()); } return attributeMap; }
From source file:edu.harvard.iq.dvn.core.analysis.NetworkDataServiceBean.java
private void processXML(String fileName, NetworkDataFile ndf) throws XMLStreamException, IOException { File file = new File(fileName); FileReader fileReader = new FileReader(file); javax.xml.stream.XMLInputFactory xmlif = javax.xml.stream.XMLInputFactory.newInstance(); xmlif.setProperty("javax.xml.stream.isCoalescing", java.lang.Boolean.TRUE); XMLStreamReader xmlr = xmlif.createXMLStreamReader(fileReader); for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) { if (event == XMLStreamConstants.START_ELEMENT) { if (xmlr.getLocalName().equals("key")) processKey(xmlr, ndf);//from w w w . ja va 2 s . com else if (xmlr.getLocalName().equals("graph")) processGraph(xmlr, ndf); } else if (event == XMLStreamConstants.END_ELEMENT) { if (xmlr.getLocalName().equals("graphml")) return; } } // If #nodes and #edges is not set, then go thru list to count them }
From source file:ca.uhn.fhir.parser.XmlParser.java
private <T> T doXmlLoop(XMLEventReader streamReader, ParserState<T> parserState) { ourLog.trace("Entering XML parsing loop with state: {}", parserState); try {/*from ww w .ja v a 2 s . c o m*/ List<String> heldComments = new ArrayList<String>(1); while (streamReader.hasNext()) { XMLEvent nextEvent = streamReader.nextEvent(); try { switch (nextEvent.getEventType()) { case XMLStreamConstants.START_ELEMENT: { StartElement elem = nextEvent.asStartElement(); String namespaceURI = elem.getName().getNamespaceURI(); if ("extension".equals(elem.getName().getLocalPart())) { Attribute urlAttr = elem.getAttributeByName(new QName("url")); String url; if (urlAttr == null || isBlank(urlAttr.getValue())) { getErrorHandler().missingRequiredElement(new ParseLocation("extension"), "url"); url = null; } else { url = urlAttr.getValue(); } parserState.enteringNewElementExtension(elem, url, false); } else if ("modifierExtension".equals(elem.getName().getLocalPart())) { Attribute urlAttr = elem.getAttributeByName(new QName("url")); String url; if (urlAttr == null || isBlank(urlAttr.getValue())) { getErrorHandler().missingRequiredElement(new ParseLocation("modifierExtension"), "url"); url = null; } else { url = urlAttr.getValue(); } parserState.enteringNewElementExtension(elem, url, true); } else { String elementName = elem.getName().getLocalPart(); parserState.enteringNewElement(namespaceURI, elementName); } if (!heldComments.isEmpty()) { for (String next : heldComments) { parserState.commentPre(next); } heldComments.clear(); } @SuppressWarnings("unchecked") Iterator<Attribute> attributes = elem.getAttributes(); for (Iterator<Attribute> iter = attributes; iter.hasNext();) { Attribute next = iter.next(); parserState.attributeValue(next.getName().getLocalPart(), next.getValue()); } break; } case XMLStreamConstants.END_DOCUMENT: case XMLStreamConstants.END_ELEMENT: { if (!heldComments.isEmpty()) { for (String next : heldComments) { parserState.commentPost(next); } heldComments.clear(); } parserState.endingElement(); // if (parserState.isComplete()) { // return parserState.getObject(); // } break; } case XMLStreamConstants.CHARACTERS: { parserState.string(nextEvent.asCharacters().getData()); break; } case XMLStreamConstants.COMMENT: { Comment comment = (Comment) nextEvent; String commentText = comment.getText(); heldComments.add(commentText); break; } } parserState.xmlEvent(nextEvent); } catch (DataFormatException e) { throw new DataFormatException("DataFormatException at [" + nextEvent.getLocation().toString() + "]: " + e.getMessage(), e); } } return parserState.getObject(); } catch (XMLStreamException e) { throw new DataFormatException(e); } }
From source file:edu.utah.further.core.api.xml.XmlUtil.java
/** * Basic StAX element printout. For more sophisticated functionality, use * {@link XmlStreamPrinter}./*from w ww. j a v a 2 s. c o m*/ * * @param reader * reader * @return reader's next element textual representation */ public static String getEventSimpleString(final XMLStreamReader reader) { switch (reader.getEventType()) { case XMLStreamConstants.START_ELEMENT: return "START_ELEMENT:\t\"" + reader.getLocalName() + "\""; case XMLStreamConstants.END_ELEMENT: return "END_ELEMENT:\t\"" + reader.getLocalName() + "\""; case XMLStreamConstants.START_DOCUMENT: return "START_DOCUMENT"; case XMLStreamConstants.END_DOCUMENT: return "END_DOCUMENT"; case XMLStreamConstants.CHARACTERS: return "CHARACTERS:\t\"" + reader.getText() + "\"" + " blank? " + StringUtils.isWhitespace(reader.getText()); case XMLStreamConstants.SPACE: return "SPACE:\t\"" + reader.getText() + "\""; default: return "EVENT:\t" + reader.getEventType(); } }
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 {/*from w w w .j ava 2 s .co 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; }