List of usage examples for javax.xml.stream XMLInputFactory newInstance
public static XMLInputFactory newInstance() throws FactoryConfigurationError
From source file:org.plasma.sdo.xml.StreamUnmarshaller.java
private void setup() { this.factory = XMLInputFactory.newInstance(); factory.setXMLResolver(new XMLResolver() { public Object resolveEntity(String publicID, String systemID, String baseURI, String namespace) throws XMLStreamException { log.debug("resolve: " + publicID + ":" + systemID + ":" + baseURI + ":" + namespace); return null; }//w w w. j a v a 2 s. c om }); factory.setEventAllocator(new EventAllocator()); 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); allocator = factory.getEventAllocator(); }
From source file:org.restcomm.connect.interpreter.rcml.Parser.java
public Parser(final Reader reader, final String xml, final ActorRef sender) throws IOException { super();// w w w . ja v a 2 s. c o m if (logger.isDebugEnabled()) { logger.debug("About to create new Parser for xml: " + xml); } this.xml = xml; this.sender = sender; final XMLInputFactory inputs = XMLInputFactory.newInstance(); inputs.setProperty("javax.xml.stream.isCoalescing", true); XMLStreamReader stream = null; try { stream = inputs.createXMLStreamReader(reader); document = parse(stream); if (document == null) { throw new IOException("There was an error parsing the RCML."); } iterator = document.iterator(); } catch (final XMLStreamException exception) { if (logger.isInfoEnabled()) { logger.info("There was an error parsing the RCML for xml: " + xml + " excpetion: ", exception); } sender.tell(new ParserFailed(exception, xml), null); } finally { if (stream != null) { try { stream.close(); } catch (final XMLStreamException nested) { throw new IOException(nested); } } } }
From source file:org.reusables.dbunit.autocomplete.AutoCompletionRules.java
private void parse(final URL rulesFileUrl) { InputStream input = null;//from ww w. j a v a 2 s . c o m XMLStreamReader parser = null; try { final XMLInputFactory factory = XMLInputFactory.newInstance(); input = rulesFileUrl.openStream(); parser = factory.createXMLStreamReader(input); for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) { if (event == XMLStreamConstants.START_ELEMENT && ELEM_RULES.equals(parser.getLocalName())) { parseRules(parser); } else if (event == XMLStreamConstants.START_ELEMENT && ELEM_TABLE.equals(parser.getLocalName())) { parseTable(parser); } } } catch (final XMLStreamException e) { throw new DbUnitAutoCompletionException("Error parsing xml stream.", e); } catch (final IOException e) { throw new DbUnitAutoCompletionException("Error reading stream.", e); } finally { IOUtils.closeQuietly(input); closeParser(parser); } }
From source file:org.rhq.enterprise.server.sync.SynchronizationManagerBean.java
private void validateExport(Subject subject, InputStream exportFile, Map<String, Configuration> importConfigs) throws ValidationException, XMLStreamException { XMLStreamReader rdr = XMLInputFactory.newInstance().createXMLStreamReader(exportFile); try {/*from w w w . ja v a2 s . c om*/ Set<ConsistencyValidatorFailureReport> failures = new HashSet<ConsistencyValidatorFailureReport>(); Set<ConsistencyValidator> consistencyValidators = new HashSet<ConsistencyValidator>(); while (rdr.hasNext()) { switch (rdr.next()) { case XMLStreamConstants.START_ELEMENT: String tagName = rdr.getName().getLocalPart(); if (SynchronizationConstants.VALIDATOR_ELEMENT.equals(tagName)) { ConsistencyValidator validator = null; String validatorClass = rdr.getAttributeValue(null, SynchronizationConstants.CLASS_ATTRIBUTE); if (!isConsistencyValidatorClass(validatorClass)) { LOG.info("The export file contains an unknown consistency validator: " + validatorClass + ". Ignoring."); continue; } try { validator = validateSingle(rdr, subject); } catch (Exception e) { failures.add(new ConsistencyValidatorFailureReport(validatorClass, printExceptionToString(e))); } if (validator != null) { consistencyValidators.add(validator); } } else if (SynchronizationConstants.ENTITIES_EXPORT_ELEMENT.equals(tagName)) { String synchronizerClass = rdr.getAttributeValue(null, SynchronizationConstants.ID_ATTRIBUTE); try { failures.addAll(validateEntities(rdr, subject, consistencyValidators, importConfigs)); } catch (Exception e) { throw new ValidationException( "Validation failed unexpectedly while processing the entities exported by the synchronizer '" + synchronizerClass + "'.", e); } } } } if (!failures.isEmpty()) { throw new ValidationException(failures); } } finally { rdr.close(); } }
From source file:org.rhq.enterprise.server.sync.SynchronizationManagerBean.java
private ImportReport importExportFile(Subject subject, InputStream exportFile, Map<String, Configuration> importerConfigs) throws ImportException, XMLStreamException { XMLStreamReader rdr = XMLInputFactory.newInstance().createXMLStreamReader(exportFile); ImportReport report = new ImportReport(); while (rdr.hasNext()) { switch (rdr.next()) { case XMLStreamReader.START_ELEMENT: String tagName = rdr.getName().getLocalPart(); if (SynchronizationConstants.ENTITIES_EXPORT_ELEMENT.equals(tagName)) { try { String synchronizer = rdr.getAttributeValue(null, SynchronizationConstants.ID_ATTRIBUTE); String notes = importSingle(subject, importerConfigs, rdr); if (notes != null) { report.getImporterNotes().put(synchronizer, notes); }/*from w w w . j a va2s .co m*/ } catch (Exception e) { //fail fast on the import errors... This runs in a single transaction //so all imports done so far will get rolled-back. //(Even if we change our minds later and run a transaction per importer //we should fail fast to prevent further damage due to possible //constraint violations in the db, etc.) throw new ImportException("Import failed.", e); } } break; } } return report; }
From source file:org.rhq.enterprise.server.sync.test.DeployedAgentPluginsValidatorTest.java
public void testCanExportAndImportState() throws Exception { final PluginManagerLocal pluginManager = context.mock(PluginManagerLocal.class); final DeployedAgentPluginsValidator validator = new DeployedAgentPluginsValidator(pluginManager); context.checking(new Expectations() { {/*www.j av a2 s . c om*/ oneOf(pluginManager).getInstalledPlugins(); will(returnValue(new ArrayList<Plugin>(getDeployedPlugins()))); } }); validator.initialize(null, null); StringWriter output = new StringWriter(); try { XMLOutputFactory ofactory = XMLOutputFactory.newInstance(); XMLStreamWriter wrt = ofactory.createXMLStreamWriter(output); //wrap the exported plugins in "something" so that we produce //a valid xml wrt.writeStartDocument(); wrt.writeStartElement("root"); validator.exportState(new ExportWriter(wrt)); wrt.writeEndDocument(); wrt.close(); StringReader input = new StringReader(output.toString()); try { XMLInputFactory ifactory = XMLInputFactory.newInstance(); XMLStreamReader rdr = ifactory.createXMLStreamReader(input); //push the reader to the start of the plugin elements //this is what is expected by the validators rdr.nextTag(); validator.initializeExportedStateValidation(new ExportReader(rdr)); rdr.close(); assertEquals(validator.getPluginsToValidate(), getDeployedPlugins()); } finally { input.close(); } } catch (Exception e) { LOG.error("Test failed. Output generated so far:\n" + output, e); throw e; } finally { output.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;/*w w w . j a va 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 ww. j a va 2 s . co 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.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 a2 s . co 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.sakaiproject.tags.impl.job.TagsExportedXMLSyncJob.java
public synchronized void syncAllTags() { long start = System.currentTimeMillis(); if (log.isInfoEnabled()) { log.info("Starting Full XML Tag Collection synchronization"); }/*from w ww .j ava 2 s .c o m*/ try { XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader xsr = factory.createXMLStreamReader(getTagsXmlInputStream()); xsr.next(); 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 = getString("tagLabel", element); String tagId = getString("tagId", element); String externalId = getString("externalId", element); String description = getString("description", element); long externalCreationDate = stringToLong(getString("externalCreationDate", element), 0L); long lastUpdateDateInExternalSystem = stringToLong( getString("lastUpdateDateInExternalSystem", element), 0L); String externalHierarchyCode = getString("externalHierarchyCode", element); String externalType = getString("externalType", element); String alternativeLabels = getString("alternativeLabels", element); String tagCollectionId = getString("tagCollectionId", element); if (collectionToUpdate != null && !collectionToUpdateMoreThanOne) { if (!(collectionToUpdate.equals(tagCollectionId))) { collectionToUpdateMoreThanOne = true; } } else { collectionToUpdate = tagCollectionId; } String data = getString("data", element); String parentId = getString("parentId", element); if (tagId != null && tagId.length() == VALID_ID_LENGTH) { if (tagWithIdIsPresent(tagId)) { updateLabelWithId(tagId, externalId, tagCollectionId, tagLabel, description, alternativeLabels, externalCreationDate, lastUpdateDateInExternalSystem, parentId, externalHierarchyCode, externalType, data); } else { updateOrCreateTagWithCollectionId(externalId, tagCollectionId, tagLabel, description, alternativeLabels, externalCreationDate, lastUpdateDateInExternalSystem, parentId, externalHierarchyCode, externalType, data); } } else { updateOrCreateTagWithCollectionId(externalId, tagCollectionId, tagLabel, description, alternativeLabels, externalCreationDate, lastUpdateDateInExternalSystem, parentId, externalHierarchyCode, externalType, data); } } updateTagCollectionSynchronizationWithCollectionId(collectionToUpdate, 0L); //We will delete the old ones when there is only one collectionID in the file. if (collectionToUpdate != null && !collectionToUpdateMoreThanOne) { deleteTagsOlderThanDateFromCollectionWithCollectionId(collectionToUpdate, start); } sendStatusMail(1, ""); } catch (Exception e) { log.warn("Full Tags XML can't be processed", e); sendStatusMail(2, e.getMessage()); } String collectionToUpdate = null; Boolean collectionToUpdateMoreThanOne = false; if (log.isInfoEnabled()) { log.info("Finished Full XML Tags synchronization in " + (System.currentTimeMillis() - start) + " ms"); } }