List of usage examples for javax.xml.stream XMLInputFactory newFactory
public static XMLInputFactory newFactory() throws FactoryConfigurationError
From source file:org.apache.tomcat.maven.plugin.tomcat7.run.AbstractRunMojo.java
protected StandardContext parseContextFile(File file) throws MojoExecutionException { try {/*w w w. j a v a 2 s . c om*/ StandardContext standardContext = new StandardContext(); XMLStreamReader reader = XMLInputFactory.newFactory().createXMLStreamReader(new FileInputStream(file)); int tag = reader.next(); while (true) { if (tag == XMLStreamConstants.START_ELEMENT && StringUtils.equals("Context", reader.getLocalName())) { String path = reader.getAttributeValue(null, "path"); if (StringUtils.isNotBlank(path)) { standardContext.setPath(path); } String docBase = reader.getAttributeValue(null, "docBase"); if (StringUtils.isNotBlank(docBase)) { standardContext.setDocBase(docBase); } } if (!reader.hasNext()) { break; } tag = reader.next(); } return standardContext; } catch (XMLStreamException e) { throw new MojoExecutionException(e.getMessage(), e); } catch (FileNotFoundException e) { throw new MojoExecutionException(e.getMessage(), e); } }
From source file:org.apereo.portal.io.xml.IdentityImportExportTestUtilities.java
public static <T> void testIdentityImportExport(TransactionOperations transactionOperations, final IDataImporter<T> dataImporter, final IDataExporter<?> dataExporter, Resource resource, Function<T, String> getName) throws Exception { final String importData = toString(resource); final XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory(); final XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(new StringReader(importData)); //Unmarshall from XML final Unmarshaller unmarshaller = dataImporter.getUnmarshaller(); final StAXSource source = new StAXSource(xmlEventReader); @SuppressWarnings("unchecked") final T dataImport = (T) unmarshaller.unmarshal(source); //Make sure the data was unmarshalled assertNotNull("Unmarshalled import data was null", dataImport); //Import the data dataImporter.importData(dataImport); //Export the data final String name = getName.apply(dataImport); final Object dataExport = transactionOperations.execute(new TransactionCallback<Object>() { /* (non-Javadoc) * @see org.springframework.transaction.support.TransactionCallback#doInTransaction(org.springframework.transaction.TransactionStatus) *//* w ww .java 2 s. c o m*/ @Override public Object doInTransaction(TransactionStatus status) { return dataExporter.exportData(name); } }); //Make sure the data was exported assertNotNull("Exported data was null", dataExport); //Marshall to XML final Marshaller marshaller = dataExporter.getMarshaller(); final StringWriter result = new StringWriter(); marshaller.marshal(dataExport, new StreamResult(result)); //Compare the exported XML data with the imported XML data, they should match final String resultString = result.toString(); try { XMLUnit.setIgnoreWhitespace(true); Diff d = new Diff(new StringReader(importData), new StringReader(resultString)); assertTrue("Export result differs from import" + d, d.similar()); } catch (Exception e) { throw new XmlTestException("Failed to assert similar between import XML and export XML", resultString, e); } catch (Error e) { throw new XmlTestException("Failed to assert similar between import XML and export XML", resultString, e); } }
From source file:org.apereo.portal.io.xml.PortalDataKeyFileProcessor.java
PortalDataKeyFileProcessor(Map<PortalDataKey, IPortalDataType> dataKeyTypes, IPortalDataHandlerService.BatchImportOptions options) { this.dataKeyTypes = dataKeyTypes; this.options = options; this.xmlInputFactory = XMLInputFactory.newFactory(); //Set the input buffer to 2k bytes. This appears to work for reading just enough to get the start element event for //all of the data files in a single read operation. this.xmlInputFactory.setProperty(WstxInputProperties.P_INPUT_BUFFER_LENGTH, 2000); this.xmlInputFactory.setProperty(XMLInputFactory2.P_LAZY_PARSING, true); //Do as little parsing as possible, just want basic info this.xmlInputFactory.setProperty(XMLInputFactory.IS_VALIDATING, false); //Don't do any validation here this.xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); //Don't load referenced DTDs here }
From source file:org.apereo.portal.rendering.StaticDocumentComponent.java
@Override public PipelineEventReader<XMLEventReader, XMLEvent> getEventReader(HttpServletRequest request, HttpServletResponse response) {/*w ww. j av a 2 s.c o m*/ final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); final DocumentBuilder documentBuilder; try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } final InputStream documentStream; try { documentStream = this.document.getInputStream(); } catch (IOException e) { throw new RuntimeException(e); } final Document document; try { document = documentBuilder.parse(documentStream); } catch (SAXException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(documentStream); } final XMLInputFactory inputFactory = XMLInputFactory.newFactory(); final DOMSource source = new DOMSource(document); final XMLEventReader streamReader; try { streamReader = inputFactory.createXMLEventReader(source); } catch (XMLStreamException e) { throw new RuntimeException(e); } return new PipelineEventReaderImpl<XMLEventReader, XMLEvent>(streamReader); }
From source file:org.apereo.portal.url.xml.XsltPortalUrlProviderTest.java
@Before public void setup() throws Exception { final ResourceLoaderURIResolver resolver = new ResourceLoaderURIResolver( new ClassRelativeResourceLoader(getClass())); this.tFactory = TransformerFactory.newInstance(); this.tFactory.setURIResolver(resolver); this.tFactory.setErrorListener(new SimpleTransformErrorListener(LogFactory.getLog(getClass()))); //Load the XML document so it reads the same way the rendering pipeline reads XML final XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory(); final XMLEventReader eventReader = xmlInputFactory .createXMLEventReader(this.getClass().getResourceAsStream("test.xml")); final XMLStreamReader streamReader = new FixedXMLEventStreamReader(eventReader); xmlSource = new StAXSource(streamReader); xslTemplate = tFactory.newTemplates(new StreamSource(this.getClass().getResourceAsStream("test.xsl"))); expected = IOUtils.toString(this.getClass().getResourceAsStream("result.xml")); }
From source file:org.codice.ddf.spatial.ogc.csw.catalog.common.GetRecordsRequest.java
/** * Convert the KVP values into a GetRecordsType, validates format of fields and enumeration * constraints required to meet the schema requirements of the GetRecordsType. No further * validation is done at this point// w w w.ja v a 2 s. c o m * * @return GetRecordsType representation of this key-value representation * @throws CswException * An exception when some field cannot be converted to the equivalent GetRecordsType * value */ public GetRecordsType get202RecordsType() throws CswException { GetRecordsType getRecords = new GetRecordsType(); getRecords.setOutputSchema(getOutputSchema()); getRecords.setRequestId(getRequestId()); if (getMaxRecords() != null) { getRecords.setMaxRecords(getMaxRecords()); } if (getStartPosition() != null) { getRecords.setStartPosition(getStartPosition()); } if (getOutputFormat() != null) { getRecords.setOutputFormat(getOutputFormat()); } if (getResponseHandler() != null) { getRecords.setResponseHandler(Arrays.asList(getResponseHandler())); } if (getResultType() != null) { try { getRecords.setResultType(ResultType.fromValue(getResultType())); } catch (IllegalArgumentException iae) { LOGGER.warn("Failed to find \"{}\" as a valid ResultType, Exception {}", getResultType(), iae); throw new CswException( "A CSW getRecords request ResultType must be \"hits\", \"results\", or \"validate\""); } } if (getDistributedSearch() != null && getDistributedSearch()) { DistributedSearchType disSearch = new DistributedSearchType(); disSearch.setHopCount(getHopCount()); getRecords.setDistributedSearch(disSearch); } QueryType query = new QueryType(); Map<String, String> namespaces = parseNamespaces(getNamespace()); List<QName> typeNames = typeStringToQNames(getTypeNames(), namespaces); query.setTypeNames(typeNames); if (getElementName() != null && getElementSetName() != null) { LOGGER.warn( "CSW getRecords request received with mutually exclusive ElementName and SetElementName set"); throw new CswException( "A CSW getRecords request can only have an \"ElementName\" or an \"ElementSetName\""); } if (getElementName() != null) { query.setElementName(typeStringToQNames(getElementName(), namespaces)); } if (getElementSetName() != null) { try { ElementSetNameType eleSetName = new ElementSetNameType(); eleSetName.setTypeNames(typeNames); eleSetName.setValue(ElementSetType.fromValue(getElementSetName())); query.setElementSetName(eleSetName); } catch (IllegalArgumentException iae) { LOGGER.warn("Failed to find \"{}\" as a valid elementSetType, Exception {}", getElementSetName(), iae); throw new CswException( "A CSW getRecords request ElementSetType must be \"brief\", \"summary\", or \"full\""); } } if (getSortBy() != null) { SortByType sort = new SortByType(); List<SortPropertyType> sortProps = new LinkedList<SortPropertyType>(); String[] sortOptions = getSortBy().split(","); for (String sortOption : sortOptions) { if (sortOption.lastIndexOf(':') < 1) { throw new CswException("Invalid Sort Order format: " + getSortBy()); } SortPropertyType sortProperty = new SortPropertyType(); PropertyNameType propertyName = new PropertyNameType(); String propName = StringUtils.substringBeforeLast(sortOption, ":"); String direction = StringUtils.substringAfterLast(sortOption, ":"); propertyName.setContent(Arrays.asList((Object) propName)); SortOrderType sortOrder; if (direction.equals("A")) { sortOrder = SortOrderType.ASC; } else if (direction.equals("D")) { sortOrder = SortOrderType.DESC; } else { throw new CswException("Invalid Sort Order format: " + getSortBy()); } sortProperty.setPropertyName(propertyName); sortProperty.setSortOrder(sortOrder); sortProps.add(sortProperty); } sort.setSortProperty(sortProps); query.setElementName(typeStringToQNames(getElementName(), namespaces)); query.setSortBy(sort); } if (getConstraint() != null) { QueryConstraintType queryConstraint = new QueryConstraintType(); if (getConstraintLanguage().equalsIgnoreCase(CswConstants.CONSTRAINT_LANGUAGE_CQL)) { queryConstraint.setCqlText(getConstraint()); } else if (getConstraintLanguage().equalsIgnoreCase(CswConstants.CONSTRAINT_LANGUAGE_FILTER)) { try { XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory(); xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); XMLStreamReader xmlStreamReader = xmlInputFactory .createXMLStreamReader(new StringReader(constraint)); Unmarshaller unmarshaller = JAX_BCONTEXT.createUnmarshaller(); @SuppressWarnings("unchecked") JAXBElement<FilterType> jaxbFilter = (JAXBElement<FilterType>) unmarshaller .unmarshal(xmlStreamReader); queryConstraint.setFilter(jaxbFilter.getValue()); } catch (JAXBException e) { throw new CswException("JAXBException parsing OGC Filter:" + getConstraint(), e); } catch (Exception e) { throw new CswException("Unable to parse OGC Filter:" + getConstraint(), e); } } else { throw new CswException("Invalid Constraint Language defined: " + getConstraintLanguage()); } query.setConstraint(queryConstraint); } JAXBElement<QueryType> jaxbQuery = new JAXBElement<QueryType>(new QName(CswConstants.CSW_OUTPUT_SCHEMA), QueryType.class, query); getRecords.setAbstractQuery(jaxbQuery); return getRecords; }
From source file:org.commonjava.maven.ext.manip.util.PomPeek.java
private void parseCoordElements(final File pom) { Reader reader = null;/*from w w w . j ava2 s . c om*/ XMLStreamReader xml = null; try { reader = new FileReader(pom); xml = XMLInputFactory.newFactory().createXMLStreamReader(reader); final Stack<String> path = new Stack<String>(); while (xml.hasNext()) { final int evt = xml.next(); switch (evt) { case START_ELEMENT: { final String elem = xml.getLocalName(); path.push(elem); if (captureValue(elem, path, xml)) { // seems like xml.getElementText() traverses the END_ELEMENT event... path.pop(); } break; } case END_ELEMENT: { final String elem = xml.getLocalName(); if (MODULES_ELEM.equals(elem)) { modulesDone = true; } path.pop(); break; } default: { } } if (foundAll()) { return; } } } catch (final IOException e) { logger.warn("Failed to peek at POM coordinate for: " + pom + " Reason: " + e.getMessage() + "\nThis POM will NOT be available as an ancestor to other models during effective-model building.", e); } catch (final XMLStreamException e) { logger.warn("Failed to peek at POM coordinate for: " + pom + " Reason: " + e.getMessage() + "\nThis POM will NOT be available as an ancestor to other models during effective-model building.", e); } catch (final FactoryConfigurationError e) { logger.warn("Failed to peek at POM coordinate for: " + pom + " Reason: " + e.getMessage() + "\nThis POM will NOT be available as an ancestor to other models during effective-model building.", e); } finally { if (xml != null) { try { xml.close(); } catch (final XMLStreamException e) { } } try { reader.close(); } catch (final IOException ioe) { } } }
From source file:org.commonjava.maven.galley.maven.parse.PomPeek.java
private void parseCoordElements() { InputStream in = null;//w w w . java 2s .co m XMLStreamReader xml = null; try { if (pom != null) { in = new FileInputStream(pom); } else if (transfer != null) { in = transfer.openInputStream(false); } else { in = stream; } xml = XMLInputFactory.newFactory().createXMLStreamReader(in); final Stack<String> path = new Stack<>(); while (xml.hasNext()) { final int evt = xml.next(); switch (evt) { case START_ELEMENT: { final String elem = xml.getLocalName(); if (captureValue(elem, path, xml)) { // seems like xml.getElementText() traverses the END_ELEMENT event... path.pop(); } break; } case END_ELEMENT: { path.pop(); break; } default: { } } if (foundAll()) { return; } } } catch (final IOException | FactoryConfigurationError | XMLStreamException e) { logger.warn("Failed to peek at POM coordinate for: " + pom + " Reason: " + e.getMessage() + "\nThis POM will NOT be available as an ancestor to other models during effective-model building.", e); } finally { if (xml != null) { try { xml.close(); } catch (final XMLStreamException e) { logger.warn("Failed to close XMLStreamReader: " + e.getMessage(), e); } } closeQuietly(in); } }
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 {/*from w w w. ja v a2s. c o 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.fcrepo.migration.foxml.FoxmlInputStreamFedoraObjectProcessor.java
/** * foxml input stream fedora object processor. * @param is the input stream/* w ww.j a v a2 s .co m*/ * @param fetcher the fetcher * @param resolver the resolver * @param localFedoraServer the host and port (formatted like "localhost:8080") of the fedora 3 server * from which the content exposed by the "is" parameter comes. * @throws XMLStreamException xml stream exception */ public FoxmlInputStreamFedoraObjectProcessor(final InputStream is, final URLFetcher fetcher, final InternalIDResolver resolver, final String localFedoraServer) throws XMLStreamException { this.fetcher = fetcher; this.idResolver = resolver; this.localFedoraServer = localFedoraServer; final XMLInputFactory factory = XMLInputFactory.newFactory(); reader = factory.createXMLStreamReader(is); reader.nextTag(); final Map<String, String> attributes = getAttributes(reader, "PID", "VERSION", "FEDORA_URI", "schemaLocation"); if (attributes.get("VERSION") == null || !attributes.get("VERSION").equals("1.1")) { isFedora2 = true; } objectInfo = new DefaultObjectInfo(attributes.get("PID"), attributes.get("FEDORA_URI")); while (reader.next() == XMLStreamConstants.CHARACTERS) { } tempFiles = new ArrayList<File>(); }