List of usage examples for javax.xml.stream XMLStreamReader close
public void close() throws XMLStreamException;
From source file:org.rhq.plugins.hadoop.HadoopServerConfigurationDelegate.java
private static void updateFile(File configFile, Map<String, PropertySimple> allProps) throws IOException, InterruptedException, XMLStreamException { InputStream in = null;//from w ww . jav a 2s .co m XMLStreamReader rdr = null; OutputStream out = null; XMLStreamWriter outWrt = null; try { Set<String> processedPropertyNames = new HashSet<String>(); in = new BufferedInputStream(new FileInputStream(configFile)); rdr = XML_INPUT_FACTORY.createXMLStreamReader(in); File tmpFile = File.createTempFile("hadoop-plugin", null); out = new FileOutputStream(tmpFile); outWrt = XML_OUTPUT_FACTORY.createXMLStreamWriter(out); ByteArrayOutputStream stash = new ByteArrayOutputStream(); XMLStreamWriter stashWrt = XML_OUTPUT_FACTORY.createXMLStreamWriter(stash); boolean outputActive = true; outWrt.writeStartDocument(); while (rdr.hasNext()) { int event = rdr.next(); XMLStreamWriter wrt = outputActive ? outWrt : stashWrt; switch (event) { case XMLStreamConstants.ATTRIBUTE: break; case XMLStreamConstants.CDATA: wrt.writeCData(rdr.getText()); break; case XMLStreamConstants.CHARACTERS: wrt.writeCharacters(rdr.getText()); break; case XMLStreamConstants.COMMENT: wrt.writeComment(rdr.getText()); break; case XMLStreamConstants.DTD: wrt.writeDTD(rdr.getText()); break; case XMLStreamConstants.END_DOCUMENT: wrt.writeEndDocument(); break; case XMLStreamConstants.END_ELEMENT: if (PROPERTY_TAG_NAME.equals(rdr.getName().getLocalPart())) { String encoding = rdr.getEncoding(); if (encoding == null) { encoding = "UTF-8"; } String propertyTagSoFar = Charset.forName(encoding) .decode(ByteBuffer.wrap(stash.toByteArray())).toString(); DetectedPropertyNameAndUpdatedTag propAndTag = updateProperty(propertyTagSoFar, allProps); //yes, we're intentionally circumventing the xml stream writer, because we already have the XML data we want to write. outWrt.flush(); out.write(propAndTag.updatedTag.getBytes("UTF-8")); processedPropertyNames.add(propAndTag.propertyName); //reset stuff stash.reset(); wrt = outWrt; outputActive = true; } else if (CONFIGURATION_TAG_NAME.equals(rdr.getName().getLocalPart())) { //now add the new props for (String prop : processedPropertyNames) { allProps.remove(prop); } for (Map.Entry<String, PropertySimple> e : allProps.entrySet()) { outWrt.writeStartElement(PROPERTY_TAG_NAME); outWrt.writeStartElement(NAME_TAG_NAME); outWrt.writeCharacters(e.getKey()); outWrt.writeEndElement(); outWrt.writeStartElement(VALUE_TAG_NAME); outWrt.writeCharacters(e.getValue().getStringValue()); outWrt.writeEndElement(); outWrt.writeEndElement(); } } wrt.writeEndElement(); break; case XMLStreamConstants.ENTITY_DECLARATION: //XXX could not find what to do with this break; case XMLStreamConstants.ENTITY_REFERENCE: wrt.writeEntityRef(rdr.getText()); break; case XMLStreamConstants.NAMESPACE: for (int i = 0; i < rdr.getNamespaceCount(); ++i) { wrt.writeNamespace(rdr.getNamespacePrefix(i), rdr.getNamespaceURI(i)); } break; case XMLStreamConstants.NOTATION_DECLARATION: //XXX could not find what to do with this break; case XMLStreamConstants.PROCESSING_INSTRUCTION: wrt.writeProcessingInstruction(rdr.getPITarget(), rdr.getPIData()); break; case XMLStreamConstants.SPACE: wrt.writeCharacters(rdr.getText()); break; case XMLStreamConstants.START_DOCUMENT: //this seems to be never called for some strange reason //wrt.writeStartDocument(); break; case XMLStreamConstants.START_ELEMENT: wrt.writeStartElement(rdr.getName().getPrefix(), rdr.getName().getLocalPart(), rdr.getName().getNamespaceURI()); for (int i = 0; i < rdr.getAttributeCount(); ++i) { wrt.writeAttribute(rdr.getAttributePrefix(i), rdr.getAttributeNamespace(i), rdr.getAttributeLocalName(i), rdr.getAttributeValue(i)); } if (PROPERTY_TAG_NAME.equals(rdr.getName().getLocalPart())) { wrt.writeCharacters(""); outputActive = false; } break; } } outWrt.flush(); out.flush(); out.close(); in.close(); //now copy the temp file in the place of the original one FileUtil.copyFile(tmpFile, configFile); } finally { rdr.close(); outWrt.flush(); outWrt.close(); try { in.close(); } finally { out.flush(); out.close(); } } }
From source file:org.roda.core.index.utils.SolrUtils.java
public static SolrInputDocument getDescriptiveMetadataFields(Binary binary, String metadataType, String metadataVersion) throws GenericException { SolrInputDocument doc;//from www . j a v a 2 s. c o m Map<String, String> parameters = new HashMap<>(); parameters.put("prefix", RodaConstants.INDEX_OTHER_DESCRIPTIVE_DATA_PREFIX); Reader transformationResult = RodaUtils.applyMetadataStylesheet(binary, RodaConstants.CORE_CROSSWALKS_INGEST, metadataType, metadataVersion, parameters); try { XMLLoader loader = new XMLLoader(); XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(transformationResult); boolean parsing = true; doc = null; while (parsing) { int event = parser.next(); if (event == XMLStreamConstants.END_DOCUMENT) { parser.close(); parsing = false; } else if (event == XMLStreamConstants.START_ELEMENT) { String currTag = parser.getLocalName(); if ("doc".equals(currTag)) { doc = loader.readDoc(parser); } } } } catch (XMLStreamException | FactoryConfigurationError e) { throw new GenericException("Could not process descriptive metadata binary " + binary.getStoragePath(), e); } finally { IOUtils.closeQuietly(transformationResult); } return doc == null ? new SolrInputDocument() : validateDescriptiveMetadataFields(doc); }
From source file:org.roda.core.index.utils.SolrUtils.java
public static SolrInputDocument premisToSolr(PreservationMetadataType preservationMetadataType, AIP aip, String representationUUID, String fileUUID, Binary binary) throws GenericException { SolrInputDocument doc;//from w w w.ja va2 s. c o m Map<String, String> stylesheetOpt = new HashMap<>(); stylesheetOpt.put(RodaConstants.PRESERVATION_EVENT_OBJECT_CLASS, PreservationMetadataEventClass.REPOSITORY.toString()); if (aip != null) { stylesheetOpt.put(RodaConstants.PRESERVATION_EVENT_OBJECT_CLASS, PreservationMetadataEventClass.AIP.toString()); stylesheetOpt.put(RodaConstants.PRESERVATION_EVENT_AIP_ID, aip.getId()); if (representationUUID != null) { stylesheetOpt.put(RodaConstants.PRESERVATION_EVENT_REPRESENTATION_UUID, representationUUID); stylesheetOpt.put(RodaConstants.PRESERVATION_EVENT_OBJECT_CLASS, PreservationMetadataEventClass.REPRESENTATION.toString()); } if (fileUUID != null) { stylesheetOpt.put(RodaConstants.PRESERVATION_EVENT_FILE_UUID, fileUUID); stylesheetOpt.put(RodaConstants.PRESERVATION_EVENT_OBJECT_CLASS, PreservationMetadataEventClass.FILE.toString()); } } Reader reader = null; try { reader = RodaUtils.applyMetadataStylesheet(binary, RodaConstants.CORE_CROSSWALKS_INGEST_OTHER, RodaConstants.PREMIS_METADATA_TYPE, RodaConstants.PREMIS_METADATA_VERSION, stylesheetOpt); XMLLoader loader = new XMLLoader(); XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(reader); boolean parsing = true; doc = null; while (parsing) { int event = parser.next(); if (event == XMLStreamConstants.END_DOCUMENT) { parser.close(); parsing = false; } else if (event == XMLStreamConstants.START_ELEMENT && "doc".equals(parser.getLocalName())) { doc = loader.readDoc(parser); } } } catch (XMLStreamException | FactoryConfigurationError e) { throw new GenericException("Could not process PREMIS " + binary.getStoragePath(), e); } finally { IOUtils.closeQuietly(reader); } if (preservationMetadataType == PreservationMetadataType.EVENT && doc != null) { try { List<LinkingIdentifier> agents = PremisV3Utils.extractAgentsFromEvent(binary); for (LinkingIdentifier id : agents) { doc.addField(RodaConstants.PRESERVATION_EVENT_LINKING_AGENT_IDENTIFIER, JsonUtils.getJsonFromObject(id)); } } catch (org.roda.core.data.v2.validation.ValidationException e) { LOGGER.warn("Error setting linking agent field: {}", e.getMessage()); } try { List<LinkingIdentifier> sources = PremisV3Utils.extractObjectFromEvent(binary); for (LinkingIdentifier id : sources) { doc.addField(RodaConstants.PRESERVATION_EVENT_LINKING_SOURCE_OBJECT_IDENTIFIER, JsonUtils.getJsonFromObject(id)); } } catch (org.roda.core.data.v2.validation.ValidationException e) { LOGGER.warn("Error setting linking source field: {}", e.getMessage()); } try { List<LinkingIdentifier> outcomes = PremisV3Utils.extractObjectFromEvent(binary); for (LinkingIdentifier id : outcomes) { doc.addField(RodaConstants.PRESERVATION_EVENT_LINKING_OUTCOME_OBJECT_IDENTIFIER, JsonUtils.getJsonFromObject(id)); } } catch (org.roda.core.data.v2.validation.ValidationException e) { LOGGER.warn("Error setting linking outcome field: {}", e.getMessage()); } // indexing active state and permissions if (aip != null) { doc.addField(RodaConstants.STATE, aip.getState().toString()); setPermissions(aip.getPermissions(), doc); } else { doc.addField(RodaConstants.STATE, AIPState.ACTIVE); } } // set uuid from id defined in xslt if (doc != null) { doc.addField(RodaConstants.INDEX_UUID, doc.getFieldValue(RodaConstants.PRESERVATION_EVENT_ID)); } else { doc = new SolrInputDocument(); } return doc; }
From source file:org.sakaiproject.nakamura.importer.ImportSiteArchiveServlet.java
private void processContentXml(InputStream in, String sitePath, Session session, ZipFile zip) throws XMLStreamException { Map<String, Resource> resources = new HashMap<String, Resource>(); String currentResourceId = null; XMLStreamReader reader = xmlInputFactory.createXMLStreamReader(in); for (int event = reader.next(); event != XMLStreamReader.END_DOCUMENT; event = reader.next()) { String localName = null;//from w ww .java2s. c om switch (event) { case XMLStreamReader.START_ELEMENT: localName = reader.getLocalName(); if ("archive".equalsIgnoreCase(localName)) { final String system = reader.getAttributeValue(null, "system"); boolean supportedVersion = false; for (String version : supportedVersions) { if (version.equalsIgnoreCase(system)) { supportedVersion = true; } } if (!supportedVersion) { throw new Error("Not a supported version: " + system); } break; } if ("collection".equalsIgnoreCase(localName) || "resource".equalsIgnoreCase(localName)) { // grab the resource's attributes Resource resource = new Resource(); for (int i = 0; i < reader.getAttributeCount(); i++) { resource.attributes.put(reader.getAttributeLocalName(i).toLowerCase(), reader.getAttributeValue(i)); } currentResourceId = resource.getId(); resources.put(currentResourceId, resource); break; } if ("property".equalsIgnoreCase(localName)) { Resource resource = resources.get(currentResourceId); final String name = reader.getAttributeValue(null, "name"); String value = reader.getAttributeValue(null, "value"); if (value != null && !"".equals(value)) { if (reader.getAttributeValue(null, "enc").equalsIgnoreCase("BASE64")) { value = new String(base64.decode(value)); } resource.properties.put(name, value); } break; } break; case XMLStreamReader.END_ELEMENT: localName = reader.getLocalName(); if ("collection".equalsIgnoreCase(localName) || "resource".equalsIgnoreCase(localName)) { makeResource(resources.get(currentResourceId), sitePath, session, zip); } break; } // end switch } // end for reader.close(); }
From source file:org.sakaiproject.tags.impl.job.MeshTagsSyncJob.java
public synchronized void syncAllTags() { long start = System.currentTimeMillis(); if (log.isInfoEnabled()) { log.info("Starting MESH Tag Collection synchronization"); }//from ww w . j a v a 2 s . c o m try { XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader xsr = factory.createXMLStreamReader(getTagsXmlInputStream()); xsr.next(); xsr.nextTag(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); while (xsr.nextTag() == XMLStreamConstants.START_ELEMENT) { DOMResult result = new DOMResult(); t.transform(new StAXSource(xsr), result); Node nNode = result.getNode(); Element element = ((Document) nNode).getDocumentElement(); String tagLabel = "undefined"; counterTotal++; try { Element descriptorName = (Element) element.getElementsByTagName("DescriptorName").item(0); tagLabel = getString("String", descriptorName); String externalId = getString("DescriptorUI", element); String description = getString("Annotation", element); long externalCreationDate = xmlDateToMs(element.getElementsByTagName("DateCreated").item(0), externalId); long lastUpdateDateInExternalSystem = xmlDateToMs( element.getElementsByTagName("DateRevised").item(0), externalId); String externalHierarchyCode = xmlTreeToString( element.getElementsByTagName("TreeNumberList").item(0), externalId); String externalType = element.getAttribute("DescriptorClass"); String alternativeLabels = xmlToAlternativeLabels( element.getElementsByTagName("ConceptList").item(0), externalId); updateOrCreateTagWithExternalSourceName(externalId, "MESH", tagLabel, description, alternativeLabels, externalCreationDate, lastUpdateDateInExternalSystem, null, externalHierarchyCode, externalType, null); counterSuccess++; lastSuccessfulLabel = tagLabel; } catch (Exception e) { log.warn("Mesh XML can't be processed for this Label: " + tagLabel + ". If the value is undefined, then, the previous successful label was: " + lastSuccessfulLabel, e); sendStatusMail(2, e.getMessage()); } if (counterTotal % 1000 == 0) { log.info(counterSuccess + "/" + counterTotal + " labels processed correctly... and still processing. " + (counterTotal - counterSuccess) + " errors by the moment"); } } // end while xsr.close(); updateTagCollectionSynchronization("MESH", 0L); deleteTagsOlderThanDateFromCollection("MESH", start); sendStatusMail(1, "Imported from MESH finished. Num of labels processed successfully " + counterSuccess + "of" + counterTotal); } catch (XMLStreamException ex) { log.warn("Mesh XML can't be processed", ex); } catch (Exception e) { log.warn("Mesh XML can't be processed", e); sendStatusMail(2, e.getMessage()); } if (log.isInfoEnabled()) { log.info("Finished Mesh Tags synchronization in " + (System.currentTimeMillis() - start) + " ms"); } counterTotal = 0; counterSuccess = 0; lastSuccessfulLabel = ""; }
From source file:org.slc.sli.api.resources.config.StAXMsgBodyReader.java
/** * Deserializer for XML => EntityBody * @param body xml as an input stream/* www . j a v a 2 s. c om*/ * @return a EntityBody object that corresponds to the xml * @throws XMLStreamException */ public EntityBody deserialize(final InputStream body) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory.createXMLStreamReader(body); try { return readDocument(reader); } finally { reader.close(); } }
From source file:org.slc.sli.modeling.wadl.reader.WadlReader.java
/** * Reads XMI from an {@link InputStream}. * * @param stream/*from w ww .jav a 2 s .c o m*/ * The {@link InputStream}. * @return The parsed {@link Model}. */ public static final Application readApplication(final InputStream stream) { if (stream == null) { throw new IllegalArgumentException("stream"); } final XMLInputFactory factory = XMLInputFactory.newInstance(); try { final XMLStreamReader reader = factory.createXMLStreamReader(stream); try { return readDocument(reader); } finally { reader.close(); } } catch (final XMLStreamException e) { throw new WadlRuntimeException(e); } }
From source file:org.slc.sli.modeling.xmi.comp.XmiMappingReader.java
/** * Reads XMI from an {@link InputStream}. * // w ww . jav a 2 s . c o m * @param stream * The {@link InputStream}. * @return The parsed {@link Model}. */ public static final XmiComparison readDocument(final InputStream stream) { final XMLInputFactory factory = XMLInputFactory.newInstance(); try { final XMLStreamReader reader = factory.createXMLStreamReader(stream); try { return readDocument(reader); } finally { reader.close(); } } catch (final XMLStreamException e) { throw new XmiCompRuntimeException(e); } }
From source file:org.slc.sli.modeling.xmi.reader.XmiReader.java
/** * Reads XMI from an {@link InputStream}. * * @param stream/*from w w w . j a va 2 s . co m*/ * The {@link InputStream}. * @return The parsed {@link Model}. */ public static final Model readModel(final InputStream stream) { final XMLInputFactory factory = XMLInputFactory.newInstance(); try { final XMLStreamReader reader = factory.createXMLStreamReader(stream); try { return readDocument(reader); } finally { reader.close(); } } catch (final XMLStreamException e) { throw new XmiRuntimeException(e); } }
From source file:org.talend.dataprep.schema.xls.XlsUtils.java
/** * read workbook xml spec to get non hidden sheets * * @param inputStream/*from ww w .j a v a 2s. c o m*/ * @return */ public static List<String> getActiveSheetsFromWorkbookSpec(InputStream inputStream) throws XMLStreamException { // If doesn't support mark, wrap up if (!inputStream.markSupported()) { inputStream = new PushbackInputStream(inputStream, 8); } XMLStreamReader streamReader = XML_INPUT_FACTORY.createXMLStreamReader(inputStream); try { /* * * <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <workbook * xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" * xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"> <fileVersion appName="xl" * lastEdited="5" lowestEdited="5" rupBuild="9303" codeName="{8C4F1C90-05EB-6A55-5F09-09C24B55AC0B}"/> * <workbookPr codeName="ThisWorkbook" defaultThemeVersion="124226"/> <bookViews> <workbookView xWindow="0" * yWindow="732" windowWidth="22980" windowHeight="8868" firstSheet="1" activeTab="8"/> </bookViews> * <sheets> <sheet name="formdata" sheetId="4" state="hidden" r:id="rId1"/> <sheet name="MONDAY" sheetId="1" * r:id="rId2"/> <sheet name="TUESDAY" sheetId="8" r:id="rId3"/> <sheet name="WEDNESDAY" sheetId="10" * r:id="rId4"/> <sheet name="THURSDAY" sheetId="11" r:id="rId5"/> <sheet name="FRIDAY" sheetId="12" * r:id="rId6"/> <sheet name="SATURDAY" sheetId="13" r:id="rId7"/> <sheet name="SUNDAY" sheetId="14" * r:id="rId8"/> <sheet name="WEEK SUMMARY" sheetId="15" r:id="rId9"/> </sheets> * */ // we only want sheets not with state=hidden List<String> names = new ArrayList<>(); while (streamReader.hasNext()) { switch (streamReader.next()) { case START_ELEMENT: if (StringUtils.equals(streamReader.getLocalName(), "sheet")) { Map<String, String> attributesValues = getAttributesNameValue(streamReader); if (!attributesValues.isEmpty()) { String sheetState = attributesValues.get("state"); if (!StringUtils.equals(sheetState, "hidden")) { String sheetName = attributesValues.get("name"); names.add(sheetName); } } } break; case XMLStreamConstants.END_ELEMENT: if (StringUtils.equals(streamReader.getLocalName(), "sheets")) { // shortcut to stop parsing return names; } break; default: // no op } } return names; } finally { if (streamReader != null) { streamReader.close(); } } }