List of usage examples for javax.xml.stream XMLStreamReader hasNext
public boolean hasNext() throws XMLStreamException;
From source file:org.modeldriven.fuml.xmi.stream.StreamReader.java
@SuppressWarnings("unchecked") public Collection read(InputStream stream) { List<Object> results = new ArrayList<Object>(); InputStream source = stream;/*ww w.j a v a 2s . c om*/ StreamContext context = null; try { XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setXMLResolver(new XMLResolver() { @Override public Object resolveEntity(String publicID, String systemID, String baseURI, String namespace) throws XMLStreamException { // TODO Auto-generated method stub return null; } }); /* XStream xstream = new XStream(new StaxDriver() { protected XMLStreamReader createParser(Reader xml) throws XMLStreamException { return getInputFactory().createXMLStreamReader(xml); } protected XMLStreamReader createParser(InputStream xml) throws XMLStreamException { return getInputFactory().createXMLStreamReader(xml); } }); */ //factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES,Boolean.FALSE); //factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES,Boolean.TRUE); //set the IS_COALESCING property to true , if application desires to //get whole text data as one event. //factory.setProperty(XMLInputFactory.IS_COALESCING , Boolean.TRUE); factory.setEventAllocator(new EventAllocator()); allocator = factory.getEventAllocator(); XMLStreamReader streamReader = factory.createXMLStreamReader(stream); int eventType = streamReader.getEventType(); StreamNode node = null; StreamNode parent = null; int level = 0; int ignoredNodeLevel = -1; while (streamReader.hasNext()) { eventType = streamReader.next(); //if (log.isDebugEnabled()) // log.debug(this.getEventTypeString(eventType)); switch (eventType) { case XMLEvent.START_ELEMENT: level++; if (ignoredNodeLevel >= 0) break; XMLEvent event = allocateXMLEvent(streamReader); if (level == 1) { if (context != null) throw new XmiException("existing context unexpected"); context = new StreamContext(event); } // debugging if (event.toString().contains("plasma:PlasmaType")) { int foo = 1; foo++; } node = new StreamNode(event, context); if (node.isIgnored()) { if (log.isDebugEnabled()) { Location loc = event.getLocation(); String msg = "start ignoring elements - level: " + String.valueOf(level) + " - line:col[" + loc.getLineNumber() + ":" + loc.getColumnNumber() + "] - "; log.debug(msg); } ignoredNodeLevel = level; break; } logEventInfo(event); parent = null; if (nodes.size() > 0) { parent = nodes.peek(); parent.add(node); node.setParent(parent); if (isRootNode(node, context)) results.add(node); } else { if (isRootNode(node, context)) results.add(node); } nodes.push(node); fireStreamNodeCreated(node, parent); break; case XMLEvent.END_ELEMENT: if (ignoredNodeLevel >= 0) { if (ignoredNodeLevel == level) { if (log.isDebugEnabled()) { event = allocateXMLEvent(streamReader); Location loc = event.getLocation(); String msg = "end ignoring elements - level: " + String.valueOf(level) + " - line:col[" + loc.getLineNumber() + ":" + loc.getColumnNumber() + "] - "; log.debug(msg); } ignoredNodeLevel = -1; } level--; break; } level--; node = nodes.pop(); parent = null; if (nodes.size() > 0) parent = nodes.peek(); fireStreamNodeCompleted(node, parent); break; case XMLEvent.CHARACTERS: if (ignoredNodeLevel >= 0) break; node = nodes.peek(); event = allocateXMLEvent(streamReader); String data = event.asCharacters().getData(); if (data != null) { data = data.trim(); if (data.length() > 0) { if (log.isDebugEnabled()) log.debug("CHARACTERS: '" + data + "'"); if (data.length() > 0) { node = nodes.peek(); node.addCharactersEvent(event); } } } break; default: if (log.isDebugEnabled()) { event = allocateXMLEvent(streamReader); logEventInfo(event); } break; } } if (results.size() > 1) throw new XmiException("found multiple root nodes (" + results.size() + ")"); } catch (XMLStreamException e) { throw new XmiException(e); } finally { try { source.close(); } catch (IOException e) { } } return results; }
From source file:org.mule.module.xml.util.XMLUtils.java
public static void copy(XMLStreamReader reader, XMLStreamWriter writer, boolean fragment) throws XMLStreamException { // number of elements read in int read = 0; int event = reader.getEventType(); while (reader.hasNext()) { switch (event) { case XMLStreamConstants.START_ELEMENT: read++;//from ww w . ja v a 2 s.com writeStartElement(reader, writer); break; case XMLStreamConstants.END_ELEMENT: writer.writeEndElement(); read--; if (read <= 0 && !fragment) { return; } break; case XMLStreamConstants.CHARACTERS: writer.writeCharacters(reader.getText()); break; case XMLStreamConstants.START_DOCUMENT: case XMLStreamConstants.END_DOCUMENT: case XMLStreamConstants.ATTRIBUTE: case XMLStreamConstants.NAMESPACE: break; default: break; } event = reader.next(); } }
From source file:org.mule.modules.jive.api.xml.XmlMapper.java
/**Maps an xml from a {@link Reader} to a {@link Map}. * @param reader The {@link Reader} with the xml data * @return The map with the entity data/*w w w.ja va 2 s. c om*/ * */ @SuppressWarnings("unchecked") public final Map<String, Object> xml2map(final Reader reader) { final Map<String, Object> ret = new HashMap<String, Object>(); final Stack<Map<String, Object>> maps = new Stack<Map<String, Object>>(); Map<String, Object> current = ret; try { final XMLStreamReader r = xmlInputFactory.createXMLStreamReader(reader); StringBuilder lastText = new StringBuilder(); String currentElement = null; int returnCount = 0; while (r.hasNext()) { final int eventType = r.next(); if (eventType == CHARACTERS || eventType == CDATA || eventType == SPACE || eventType == ENTITY_REFERENCE) { lastText.append(r.getText()); } else if (eventType == END_DOCUMENT) { break; } else if (eventType == START_ELEMENT) { if (currentElement != null) { maps.push(current); final Map<String, Object> map = new HashMap<String, Object>(); if (StringUtils.startsWith(currentElement, "return")) { currentElement = currentElement + "--" + String.valueOf(returnCount); returnCount++; } current.put(currentElement, map); current = map; } currentElement = r.getLocalName(); } else if (eventType == END_ELEMENT) { if (currentElement == null) { current = maps.pop(); } else { current.put(currentElement, lastText.toString().trim()); currentElement = null; lastText = new StringBuilder(); } } else { throw new XMLStreamException("Unexpected event type " + eventType); } } final Object obj = ret.get(ret.keySet().iterator().next()); if (obj instanceof String) { Map<String, Object> responseTag = new HashMap<String, Object>(); responseTag.put("response", ret.keySet().iterator().next().toString()); return responseTag; } else { final Map<String, Object> returnXMLElement = (Map<String, Object>) ret .get(ret.keySet().iterator().next()); if (returnXMLElement.keySet().contains("return--1")) { return returnXMLElement; } return (Map<String, Object>) returnXMLElement.get("return--0"); } } catch (XMLStreamException e) { throw new UnhandledException(e); } }
From source file:org.mule.transport.sap.transformer.XmlToJcoFunctionTransformer.java
public JCoFunction transform(InputStream stream, String encoding) throws XMLStreamException { XMLStreamReader reader = null; XMLInputFactory factory = XMLInputFactory.newInstance(); String functionName = null;//from w ww . j a va 2 s . c om String tableName = null; String structureName = null; String rowId = null; String fieldName = null; String value = null; JCoFunction function = null; try { reader = factory.createXMLStreamReader(stream); String localName = null; while (reader.hasNext()) { int eventType = reader.next(); if (eventType == XMLStreamReader.START_DOCUMENT) { // find START_DOCUMENT } else if (eventType == XMLStreamReader.START_ELEMENT) { // find START_ELEMENT localName = reader.getLocalName(); logger.debug("START ELEMENT IS FOUND"); logger.debug("start localName = " + localName); if (localName.equals(MessageConstants.JCO)) { functionName = getAttributeValue(MessageConstants.JCO_ATTR_NAME, reader); try { function = this.connector.getAdapter().getFunction(functionName); } catch (JCoException e) { throw new XMLStreamException(e); } logger.debug("function name:" + functionName); } else if (functionName != null) { if (localName.equals(MessageConstants.IMPORT)) { //recordType = IMPORT; push(function.getImportParameterList()); } else if (localName.equals(MessageConstants.EXPORT)) { //recordType = EXPORT; push(function.getExportParameterList()); } else if (localName.equals(MessageConstants.TABLES)) { //recordType = TABLES; tableName = null; push(function.getTableParameterList()); } else if (localName.equals(MessageConstants.TABLE)) { if (tableName != null) { pop(); } tableName = getAttributeValue(MessageConstants.TABLE_ATTR_NAME, reader); logger.debug("tableName = " + tableName); push(this.record.getTable(tableName)); } else if (localName.equals(MessageConstants.STRUCTURE)) { structureName = getAttributeValue(MessageConstants.STRUCTURE_ATTR_NAME, reader); push(this.record.getStructure(structureName)); } else if (localName.equals(MessageConstants.ROW)) { rowId = getAttributeValue(MessageConstants.ROW_ATTR_ID, reader); logger.debug("rowId = " + rowId); if (this.record instanceof JCoTable) { ((JCoTable) this.record).appendRow(); } } else if (localName.equals(MessageConstants.FIELD)) { fieldName = getAttributeValue(MessageConstants.STRUCTURE_ATTR_NAME, reader); value = reader.getElementText().trim(); // get an element value logger.debug("FieldName = " + fieldName); logger.debug("value = " + value); this.record.setValue(fieldName, value); } } } else if (eventType == XMLStreamReader.END_DOCUMENT) { // find END_DOCUMENT logger.debug("END DOCUMENT IS FOUND"); } else if (eventType == XMLStreamReader.END_ELEMENT) { logger.debug("END ELEMENT IS FOUND"); logger.debug("end localName = " + localName); // find END_ELEMENT if (localName.equals(MessageConstants.IMPORT) || localName.equals(MessageConstants.EXPORT) || localName.equals(MessageConstants.TABLES) || localName.equals(MessageConstants.TABLE) || localName.equals(MessageConstants.STRUCTURE)) { pop(); } } } } catch (Exception e) { logger.fatal(e); throw new TransformerException(this, e); } finally { if (reader != null) { try { reader.close(); } catch (XMLStreamException ex) { } } if (stream != null) { try { stream.close(); } catch (IOException ex) { } } logger.debug("\n" + function.getImportParameterList().toXML()); logger.debug("\n" + function.getExportParameterList().toXML()); logger.debug("\n" + function.getTableParameterList().toXML()); return function; } }
From source file:org.netbeans.jbatch.modeler.spec.core.Definitions.java
public static Definitions load(ModelerFile file, String definitionId) { File savedFile = file.getFile(); Definitions definition_Load = null;/*from w w w.ja v a 2 s . co m*/ boolean definitionExist = false; XMLStreamReader xsr = null; try { if (savedFile.length() != 0) { XMLInputFactory xif = XMLInputFactory.newFactory(); StreamSource xml = new StreamSource(savedFile); xsr = xif.createXMLStreamReader(xml); xsr.nextTag(); if (definitionId == null) { while (xsr.hasNext() && !definitionExist) { if (xsr.getEventType() == XMLStreamConstants.START_ELEMENT && xsr.getLocalName().equals("definitions") && xsr.getAttributeValue(null, "id") == null) { definitionExist = true; } else { xsr.next(); } } } else { while (xsr.hasNext() && !definitionExist) { if (xsr.getEventType() == XMLStreamConstants.START_ELEMENT && xsr.getLocalName().equals("definitions") && definitionId.equals(xsr.getAttributeValue(null, "id"))) { definitionExist = true; } else { xsr.next(); } } } } JAXBContext jobContext; Unmarshaller jobUnmarshaller; // if (jobContext == null) { jobContext = JAXBContext.newInstance(new Class<?>[] { ShapeDesign.class, Definitions.class }); // } // if (jobUnmarshaller == null) { jobUnmarshaller = jobContext.createUnmarshaller(); jobUnmarshaller.setEventHandler(new ValidateJAXB()); // } if (definitionExist) { definition_Load = jobUnmarshaller.unmarshal(xsr, Definitions.class).getValue();//new StreamSource(savedFile) } if (xsr != null) { xsr.close(); } } catch (XMLStreamException ex) { Exceptions.printStackTrace(ex); } catch (JAXBException ex) { // io.getOut().println("Exception: " + ex.toString()); ex.printStackTrace(); System.out.println("Document XML Not Exist"); } return definition_Load; }
From source file:org.netbeans.jbatch.modeler.spec.core.Definitions.java
static void transformXMLStream(XMLStreamReader xmlStreamReader, XMLStreamWriter xmlStreamWriter) { try {/*from ww w . jav a 2s. c om*/ // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer t = tf.newTransformer(); // StAXSource source = new StAXSource(xmlStreamReader); // StAXResult result = new StAXResult(xmlStreamWriter); // t.transform(source, result); System.out.println("Defnition Id : " + xmlStreamReader.getAttributeValue(null, "id")); boolean finish = false; while (xmlStreamReader.hasNext() && !finish) { switch (xmlStreamReader.getEventType()) { case XMLEvent.START_ELEMENT: String prefix = xmlStreamReader.getPrefix(); String namespaceURI = xmlStreamReader.getNamespaceURI(); if (namespaceURI != null) { if (prefix != null) { xmlStreamWriter.writeStartElement(xmlStreamReader.getPrefix(), xmlStreamReader.getLocalName(), xmlStreamReader.getNamespaceURI()); } else { xmlStreamWriter.writeStartElement(xmlStreamReader.getNamespaceURI(), xmlStreamReader.getLocalName()); } } else { xmlStreamWriter.writeStartElement(xmlStreamReader.getLocalName()); } for (int i = 0; i < xmlStreamReader.getNamespaceCount(); i++) { xmlStreamWriter.writeNamespace(xmlStreamReader.getNamespacePrefix(i), xmlStreamReader.getNamespaceURI(i)); } int count = xmlStreamReader.getAttributeCount(); for (int i = 0; i < count; i++) { // xmlStreamWriter.writeAttribute(xmlStreamReader.getAttributePrefix(i), // xmlStreamReader.getAttributeNamespace(i), // xmlStreamReader.getAttributeLocalName(i), // xmlStreamReader.getAttributeValue(i)); String attrNamespaceURI = xmlStreamReader.getAttributeNamespace(i), attrPrefix = xmlStreamReader.getAttributePrefix(i); if (attrNamespaceURI != null) { if (attrPrefix != null) { xmlStreamWriter.writeAttribute(attrPrefix, attrNamespaceURI, xmlStreamReader.getAttributeLocalName(i), xmlStreamReader.getAttributeValue(i)); } else { xmlStreamWriter.writeAttribute(attrNamespaceURI, xmlStreamReader.getAttributeLocalName(i), xmlStreamReader.getAttributeValue(i)); } } else { xmlStreamWriter.writeAttribute(xmlStreamReader.getAttributeLocalName(i), xmlStreamReader.getAttributeValue(i)); } } break; case XMLEvent.END_ELEMENT: xmlStreamWriter.writeEndElement(); if (xmlStreamReader.getLocalName().equals("definitions")) { finish = true; } break; case XMLEvent.SPACE: case XMLEvent.CHARACTERS: xmlStreamWriter.writeCharacters(xmlStreamReader.getTextCharacters(), xmlStreamReader.getTextStart(), xmlStreamReader.getTextLength()); break; case XMLEvent.PROCESSING_INSTRUCTION: xmlStreamWriter.writeProcessingInstruction(xmlStreamReader.getPITarget(), xmlStreamReader.getPIData()); break; case XMLEvent.CDATA: xmlStreamWriter.writeCData(xmlStreamReader.getText()); break; case XMLEvent.COMMENT: xmlStreamWriter.writeComment(xmlStreamReader.getText()); break; case XMLEvent.ENTITY_REFERENCE: xmlStreamWriter.writeEntityRef(xmlStreamReader.getLocalName()); break; case XMLEvent.START_DOCUMENT: String encoding = xmlStreamReader.getCharacterEncodingScheme(); String version = xmlStreamReader.getVersion(); if (encoding != null && version != null) { xmlStreamWriter.writeStartDocument(encoding, version); } else if (version != null) { xmlStreamWriter.writeStartDocument(xmlStreamReader.getVersion()); } break; case XMLEvent.END_DOCUMENT: xmlStreamWriter.writeEndDocument(); break; case XMLEvent.DTD: xmlStreamWriter.writeDTD(xmlStreamReader.getText()); break; } if (!finish) { xmlStreamReader.next(); } } } catch (XMLStreamException ex) { Exceptions.printStackTrace(ex); } }
From source file:org.netbeans.jbatch.modeler.spec.core.Definitions.java
static void skipXMLStream(XMLStreamReader xmlStreamReader) { try {//from w ww. j ava2 s . co m boolean finish = false; while (xmlStreamReader.hasNext() && !finish) { switch (xmlStreamReader.getEventType()) { case XMLEvent.END_ELEMENT: if (xmlStreamReader.getLocalName().equals("definitions")) { finish = true; } break; } if (!finish) { xmlStreamReader.next(); } } } catch (XMLStreamException ex) { Exceptions.printStackTrace(ex); } }
From source file:org.netbeans.jbatch.modeler.specification.model.job.util.JobUtil.java
void transformXMLStream(XMLStreamReader xmlStreamReader, XMLStreamWriter xmlStreamWriter) { try {/*from www.j av a 2s . c om*/ // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer t = tf.newTransformer(); // StAXSource source = new StAXSource(xmlStreamReader); // StAXResult result = new StAXResult(xmlStreamWriter); // t.transform(source, result); boolean finish = false; while (xmlStreamReader.hasNext() && !finish) { switch (xmlStreamReader.getEventType()) { case XMLEvent.START_ELEMENT: String prefix = xmlStreamReader.getPrefix(); String namespaceURI = xmlStreamReader.getNamespaceURI(); if (namespaceURI != null) { if (prefix != null) { xmlStreamWriter.writeStartElement(xmlStreamReader.getPrefix(), xmlStreamReader.getLocalName(), xmlStreamReader.getNamespaceURI()); } else { xmlStreamWriter.writeStartElement(xmlStreamReader.getNamespaceURI(), xmlStreamReader.getLocalName()); } } else { xmlStreamWriter.writeStartElement(xmlStreamReader.getLocalName()); } for (int i = 0; i < xmlStreamReader.getNamespaceCount(); i++) { xmlStreamWriter.writeNamespace(xmlStreamReader.getNamespacePrefix(i), xmlStreamReader.getNamespaceURI(i)); } int count = xmlStreamReader.getAttributeCount(); for (int i = 0; i < count; i++) { // xmlStreamWriter.writeAttribute(xmlStreamReader.getAttributePrefix(i), // xmlStreamReader.getAttributeNamespace(i), // xmlStreamReader.getAttributeLocalName(i), // xmlStreamReader.getAttributeValue(i)); String attrNamespaceURI = xmlStreamReader.getAttributeNamespace(i), attrPrefix = xmlStreamReader.getAttributePrefix(i); if (attrNamespaceURI != null) { if (attrPrefix != null) { xmlStreamWriter.writeAttribute(attrPrefix, attrNamespaceURI, xmlStreamReader.getAttributeLocalName(i), xmlStreamReader.getAttributeValue(i)); } else { xmlStreamWriter.writeAttribute(attrNamespaceURI, xmlStreamReader.getAttributeLocalName(i), xmlStreamReader.getAttributeValue(i)); } } else { xmlStreamWriter.writeAttribute(xmlStreamReader.getAttributeLocalName(i), xmlStreamReader.getAttributeValue(i)); } } break; case XMLEvent.END_ELEMENT: xmlStreamWriter.writeEndElement(); if (xmlStreamReader.getLocalName().equals("definitions")) { finish = true; } break; case XMLEvent.SPACE: case XMLEvent.CHARACTERS: xmlStreamWriter.writeCharacters(xmlStreamReader.getTextCharacters(), xmlStreamReader.getTextStart(), xmlStreamReader.getTextLength()); break; case XMLEvent.PROCESSING_INSTRUCTION: xmlStreamWriter.writeProcessingInstruction(xmlStreamReader.getPITarget(), xmlStreamReader.getPIData()); break; case XMLEvent.CDATA: xmlStreamWriter.writeCData(xmlStreamReader.getText()); break; case XMLEvent.COMMENT: xmlStreamWriter.writeComment(xmlStreamReader.getText()); break; case XMLEvent.ENTITY_REFERENCE: xmlStreamWriter.writeEntityRef(xmlStreamReader.getLocalName()); break; case XMLEvent.START_DOCUMENT: String encoding = xmlStreamReader.getCharacterEncodingScheme(); String version = xmlStreamReader.getVersion(); if (encoding != null && version != null) { xmlStreamWriter.writeStartDocument(encoding, version); } else if (version != null) { xmlStreamWriter.writeStartDocument(xmlStreamReader.getVersion()); } break; case XMLEvent.END_DOCUMENT: xmlStreamWriter.writeEndDocument(); break; case XMLEvent.DTD: xmlStreamWriter.writeDTD(xmlStreamReader.getText()); break; } if (!finish) { xmlStreamReader.next(); } } } catch (XMLStreamException ex) { Exceptions.printStackTrace(ex); } }
From source file:org.opendatakit.briefcase.export.SubmissionParser.java
private static Optional<String> parseAttribute(Path submission, Reader ioReader, String attributeName, SubmissionExportErrorCallback onParsingError) { try {/* w w w .jav a2s. c o m*/ XMLStreamReader reader = xmlInputFactory.createXMLStreamReader(ioReader); while (reader.hasNext()) if (reader.next() == START_ELEMENT) for (int i = 0, c = reader.getAttributeCount(); i < c; ++i) if (reader.getAttributeLocalName(i).equals(attributeName)) return Optional.of(reader.getAttributeValue(i)); } catch (XMLStreamException e) { log.error("Can't parse submission", e); onParsingError.accept(submission, "parsing error"); } return Optional.empty(); }
From source file:org.openengsb.connector.promreport.internal.ProcessFileStore.java
private ProcessInstance readFrom(File processFile, String processInstanceId) { BufferedInputStream fis = null; try {/*from ww w. j a v a 2 s . c o m*/ fis = new BufferedInputStream(new FileInputStream(processFile)); XMLStreamReader xmlr = xmlif.createXMLStreamReader(fis); int eventType; while (xmlr.hasNext()) { eventType = xmlr.next(); if (eventType == XMLStreamConstants.START_ELEMENT && xmlr.getLocalName().equals("ProcessInstance") && xmlr.getAttributeValue(null, "id").equals(processInstanceId)) { return (ProcessInstance) createUnmarshaller().unmarshal(xmlr); } } } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(fis); } return null; }