List of usage examples for javax.xml.stream XMLStreamReader close
public void close() throws XMLStreamException;
From source file:org.deegree.style.persistence.sld.SldStyleStoreBuilder.java
@Override public StyleStore build() { InputStream in = null;//from ww w.j a va 2s.c o m XMLStreamReader reader = null; try { in = metadata.getLocation().getAsStream(); DefaultResourceLocation<StyleStore> loc = (DefaultResourceLocation<StyleStore>) metadata.getLocation(); XMLInputFactory fac = XMLInputFactory.newInstance(); reader = fac.createXMLStreamReader(loc.getFile().toString(), in); Map<String, LinkedList<Style>> map = getStyles(reader); return new SLDStyleStore(map, metadata); } catch (Exception e) { throw new ResourceInitException("Could not read SLD style config.", e); } finally { try { if (reader != null) { reader.close(); } } catch (XMLStreamException e) { // eat it } closeQuietly(in); } }
From source file:org.deegree.style.persistence.sld.SLDStyleStoreProvider.java
@Override public SLDStyleStore create(URL configUrl) throws ResourceInitException { InputStream in = null;//w ww . j av a2 s . c om XMLStreamReader reader = null; try { in = configUrl.openStream(); XMLInputFactory fac = XMLInputFactory.newInstance(); reader = fac.createXMLStreamReader(configUrl.toExternalForm(), in); Map<String, LinkedList<Style>> map = getStyles(reader); return new SLDStyleStore(map); } catch (Throwable e) { throw new ResourceInitException("Could not read SLD style config.", e); } finally { try { if (reader != null) { reader.close(); } } catch (XMLStreamException e) { // eat it } closeQuietly(in); } }
From source file:org.deegree.workspace.standard.DefaultResourceLocation.java
@Override public String getNamespace() { InputStream fis = null;/*ww w .j a va 2s . co m*/ XMLStreamReader in = null; try { in = XMLInputFactory.newInstance().createXMLStreamReader(fis = getAsStream()); while (!in.isStartElement()) { in.next(); } return in.getNamespaceURI(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } IOUtils.closeQuietly(fis); } return null; }
From source file:org.eclipse.koneki.protocols.omadm.client.basic.DMBasicSession.java
private void readMessage(final InputStream in) throws XMLStreamException { final XMLStreamReader reader = this.dmClient.createXMLStreamReader(in, ENCODING, new StreamFilter() { @Override//from w w w . ja v a 2 s .c o m public boolean accept(final XMLStreamReader reader) { return !reader.isWhiteSpace() && !reader.isStandalone(); } }); jumpToStartTag(reader, "SyncHdr"); //$NON-NLS-1$ readSyncHdr(reader); reader.nextTag(); readSyncBody(reader); reader.nextTag(); reader.close(); }
From source file:org.eclipse.sw360.licenseinfo.parsers.AbstractCLIParser.java
protected <T> boolean hasThisXMLRootElement(AttachmentContent content, String rootElementNamespace, String rootElementName, User user, T context) throws TException { XMLInputFactory xmlif = XMLInputFactory.newFactory(); XMLStreamReader xmlStreamReader = null; InputStream attachmentStream = null; try {/* w w w . ja v a2 s. co m*/ attachmentStream = attachmentConnector.getAttachmentStream(content, user, context); xmlStreamReader = xmlif.createXMLStreamReader(attachmentStream); //skip to first element while (xmlStreamReader.hasNext() && xmlStreamReader.next() != XMLStreamConstants.START_ELEMENT) ; xmlStreamReader.require(XMLStreamConstants.START_ELEMENT, rootElementNamespace, rootElementName); return true; } catch (XMLStreamException | SW360Exception e) { return false; } finally { if (null != xmlStreamReader) { try { xmlStreamReader.close(); } catch (XMLStreamException e) { // ignore it } } closeQuietly(attachmentStream, log); } }
From source file:org.graphipedia.wikipedia.parser.SimpleStaxParser.java
/** * Parses a XML file. /*from ww w . java 2 s . c om*/ * @param inputStream The input XML stream. * @throws IOException when something goes wrong while reading the input file. * @throws XMLStreamException when something goes wrong while parsing the XML file. */ private void parse(InputStream inputStream) throws IOException, XMLStreamException { XMLStreamReader reader = XML_INPUT_FACTORY.createXMLStreamReader(inputStream, "UTF-8"); try { parseElements(reader); } finally { reader.close(); inputStream.close(); } }
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;// w w w . ja v a2 s. c o m 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.neo4j.gis.spatial.osm.OSMImporter.java
public void importFile(OSMWriter<?> osmWriter, String dataset, boolean allPoints, Charset charset) throws IOException, XMLStreamException { System.out.println("Importing with osm-writer: " + osmWriter); osmWriter.getOrCreateOSMDataset(layerName); osm_dataset = osmWriter.getDatasetId(); long startTime = System.currentTimeMillis(); long[] times = new long[] { 0L, 0L, 0L, 0L }; javax.xml.stream.XMLInputFactory factory = javax.xml.stream.XMLInputFactory.newInstance(); CountedFileReader reader = new CountedFileReader(dataset, charset); javax.xml.stream.XMLStreamReader parser = factory.createXMLStreamReader(reader); int countXMLTags = 0; beginProgressMonitor(100);/*from w w w . j a v a2 s. co m*/ setLogContext(dataset); boolean startedWays = false; boolean startedRelations = false; try { ArrayList<String> currentXMLTags = new ArrayList<String>(); int depth = 0; Map<String, Object> wayProperties = null; ArrayList<Long> wayNodes = new ArrayList<Long>(); Map<String, Object> relationProperties = null; ArrayList<Map<String, Object>> relationMembers = new ArrayList<Map<String, Object>>(); LinkedHashMap<String, Object> currentNodeTags = new LinkedHashMap<String, Object>(); while (true) { updateProgressMonitor(reader.getPercentRead()); incrLogContext(); int event = parser.next(); if (event == javax.xml.stream.XMLStreamConstants.END_DOCUMENT) { break; } switch (event) { case javax.xml.stream.XMLStreamConstants.START_ELEMENT: currentXMLTags.add(depth, parser.getLocalName()); String tagPath = currentXMLTags.toString(); if (tagPath.equals("[osm]")) { osmWriter.setDatasetProperties(extractProperties(parser)); } else if (tagPath.equals("[osm, bounds]")) { osmWriter.addOSMBBox(extractProperties("bbox", parser)); } else if (tagPath.equals("[osm, node]")) { // <node id="269682538" lat="56.0420950" // lon="12.9693483" user="sanna" uid="31450" // visible="true" version="1" changeset="133823" // timestamp="2008-06-11T12:36:28Z"/> osmWriter.createOSMNode(extractProperties("node", parser)); } else if (tagPath.equals("[osm, way]")) { // <way id="27359054" user="spull" uid="61533" // visible="true" version="8" changeset="4707351" // timestamp="2010-05-15T15:39:57Z"> if (!startedWays) { startedWays = true; times[0] = System.currentTimeMillis(); osmWriter.optimize(); times[1] = System.currentTimeMillis(); } wayProperties = extractProperties("way", parser); wayNodes.clear(); } else if (tagPath.equals("[osm, way, nd]")) { Map<String, Object> properties = extractProperties(parser); wayNodes.add(Long.parseLong(properties.get("ref").toString())); } else if (tagPath.endsWith("tag]")) { Map<String, Object> properties = extractProperties(parser); currentNodeTags.put(properties.get("k").toString(), properties.get("v").toString()); } else if (tagPath.equals("[osm, relation]")) { // <relation id="77965" user="Grillo" uid="13957" // visible="true" version="24" changeset="5465617" // timestamp="2010-08-11T19:25:46Z"> if (!startedRelations) { startedRelations = true; times[2] = System.currentTimeMillis(); osmWriter.optimize(); times[3] = System.currentTimeMillis(); } relationProperties = extractProperties("relation", parser); relationMembers.clear(); } else if (tagPath.equals("[osm, relation, member]")) { relationMembers.add(extractProperties(parser)); } if (startedRelations) { if (countXMLTags < 10) { log("Starting tag at depth " + depth + ": " + currentXMLTags.get(depth) + " - " + currentXMLTags.toString()); for (int i = 0; i < parser.getAttributeCount(); i++) { log("\t" + currentXMLTags.toString() + ": " + parser.getAttributeLocalName(i) + "[" + parser.getAttributeNamespace(i) + "," + parser.getAttributePrefix(i) + "," + parser.getAttributeType(i) + "," + "] = " + parser.getAttributeValue(i)); } } countXMLTags++; } depth++; break; case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (currentXMLTags.toString().equals("[osm, node]")) { osmWriter.addOSMNodeTags(allPoints, currentNodeTags); } else if (currentXMLTags.toString().equals("[osm, way]")) { osmWriter.createOSMWay(wayProperties, wayNodes, currentNodeTags); } else if (currentXMLTags.toString().equals("[osm, relation]")) { osmWriter.createOSMRelation(relationProperties, relationMembers, currentNodeTags); } depth--; currentXMLTags.remove(depth); // log("Ending tag at depth "+depth+": "+currentTags.get(depth)); break; default: break; } } } finally { endProgressMonitor(); parser.close(); osmWriter.finish(); this.osm_dataset = osmWriter.getDatasetId(); } describeTimes(startTime, times); osmWriter.describeMissing(); osmWriter.describeLoaded(); long stopTime = System.currentTimeMillis(); log("info | Elapsed time in seconds: " + (1.0 * (stopTime - startTime) / 1000.0)); stats.dumpGeomStats(); stats.printTagStats(); }
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 ww .j a v a 2 s . c om*/ 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.openanzo.services.serialization.XMLBackupReader.java
/** * Parse the data within the reader, passing the results to the IRepositoryHandler * // w w w . ja v a 2 s.c o m * @param reader * reader containing the data * @param handler * Handler which will handle the elements within the data * @throws AnzoException */ private void parseBackup(Reader reader, final IBackupHandler handler) throws AnzoException { try { XMLStreamReader parser = XMLFactoryFinder.getXMLInputFactory().createXMLStreamReader(reader); for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) { switch (event) { case XMLStreamConstants.START_ELEMENT: if (SerializationConstants.namedGraph.equals(parser.getLocalName())) { graphUri = parser.getAttributeValue(null, SerializationConstants.namedGraphUri); String meta = parser.getAttributeValue(null, SerializationConstants.metadataGraphUri); String uuidString = parser.getAttributeValue(null, SerializationConstants.namedGraphUUID); namedGraphUri = Constants.valueFactory.createURI(graphUri); metaURI = Constants.valueFactory.createURI(meta); uuid = Constants.valueFactory.createURI(uuidString); revisioned = Boolean .parseBoolean(parser.getAttributeValue(null, SerializationConstants.revisioned)); } else if (SerializationConstants.revisions.equals(parser.getLocalName())) { revisions = new ArrayList<BackupRevision>(); } else if (SerializationConstants.revisionInfo.equals(parser.getLocalName())) { long revision = Long .parseLong(parser.getAttributeValue(null, SerializationConstants.revision)); Long start = Long.valueOf(parser.getAttributeValue(null, SerializationConstants.start)); String endString = parser.getAttributeValue(null, SerializationConstants.end); Long end = (endString != null) ? Long.valueOf(endString) : -1; lastModified = Constants.valueFactory .createURI(parser.getAttributeValue(null, SerializationConstants.lastModifiedBy)); revisions.add(new BackupRevision(revision, start, end, lastModified)); } else if (SerializationConstants.statement.equals(parser.getLocalName())) { if (processGraph) { if (revisioned) { String startString = parser.getAttributeValue(null, SerializationConstants.start); String endString = parser.getAttributeValue(null, SerializationConstants.end); if (startString != null) start = Long.valueOf(startString); if (endString != null) end = Long.valueOf(endString); } } } else if (SerializationConstants.statements.equals(parser.getLocalName())) { if (processGraph) { metadata = !parser.getAttributeValue(null, SerializationConstants.namedGraphUri) .equals(graphUri); } } else if (SerializationConstants.subject.equals(parser.getLocalName())) { if (processGraph) { nodeType = parser.getAttributeValue(null, SerializationConstants.subjectType); } } else if (SerializationConstants.predicate.equals(parser.getLocalName())) { } else if (SerializationConstants.object.equals(parser.getLocalName())) { if (processGraph) { nodeType = parser.getAttributeValue(null, SerializationConstants.objectType); language = parser.getAttributeValue(null, SerializationConstants.language); datatype = parser.getAttributeValue(null, SerializationConstants.dataType); } } else if (SerializationConstants.namedGraphUri.equals(parser.getLocalName())) { } break; case XMLStreamConstants.END_ELEMENT: if (SerializationConstants.namedGraph.equals(parser.getLocalName())) { graphUri = null; namedGraphUri = null; metaURI = null; uuid = null; revisioned = true; revisions = null; } else if (SerializationConstants.revisionInfo.equals(parser.getLocalName())) { } else if (SerializationConstants.revisions.equals(parser.getLocalName())) { processGraph = handler.handleNamedGraph(revisioned, namedGraphUri, metaURI, uuid, revisions); revisions = null; } else if (SerializationConstants.statement.equals(parser.getLocalName())) { if (processGraph) { handler.handleStatement(metadata, revisioned, Constants.valueFactory.createStatement(currentSubject, currentPredicate, currentObject, currentNamedGraphURI), start, end); start = null; end = null; } } else if (SerializationConstants.subject.equals(parser.getLocalName())) { if (processGraph) { if (NodeType.BNODE.name().equals(nodeType)) { currentSubject = Constants.valueFactory.createBNode(currentValue); } else { currentSubject = Constants.valueFactory.createURI(currentValue); } currentValue = null; nodeType = null; } } else if (SerializationConstants.predicate.equals(parser.getLocalName())) { if (processGraph) { currentPredicate = Constants.valueFactory.createURI(currentValue); currentValue = null; } } else if (SerializationConstants.object.equals(parser.getLocalName())) { if (processGraph) { if (NodeType.BNODE.name().equals(nodeType)) { currentObject = Constants.valueFactory.createBNode(currentValue); } else if (NodeType.URI.name().equals(nodeType)) { currentObject = Constants.valueFactory.createURI(currentValue); } else if (NodeType.LITERAL.name().equals(nodeType)) { if (currentValue == null) { currentValue = ""; } else if (Base64 .isArrayByteBase64(currentValue.getBytes(Constants.byteEncoding))) { currentValue = new String( Base64.decodeBase64(currentValue.getBytes(Constants.byteEncoding)), Constants.byteEncoding); } if (datatype != null) { currentObject = Constants.valueFactory.createLiteral(currentValue, Constants.valueFactory.createURI(datatype)); } else if (language != null) { currentObject = Constants.valueFactory.createLiteral(currentValue, language); } else { currentObject = Constants.valueFactory.createLiteral(currentValue); } } currentValue = null; nodeType = null; language = null; datatype = null; } } else if (SerializationConstants.namedGraphUri.equals(parser.getLocalName())) { if (processGraph) { currentNamedGraphURI = Constants.valueFactory.createURI(currentValue); currentValue = null; } } break; case XMLStreamConstants.CHARACTERS: if (parser.hasText()) currentValue = parser.getText(); break; case XMLStreamConstants.CDATA: if (parser.hasText()) currentValue = parser.getText(); break; } } parser.close(); } catch (XMLStreamException ex) { throw new AnzoException(ExceptionConstants.IO.READ_ERROR, ex, ex.getMessage()); } catch (UnsupportedEncodingException uee) { throw new AnzoException(ExceptionConstants.IO.ENCODING_ERROR, uee); } }