List of usage examples for javax.xml.stream XMLInputFactory createXMLStreamReader
public abstract XMLStreamReader createXMLStreamReader(java.io.InputStream stream) throws XMLStreamException;
From source file:org.apache.padaf.xmpbox.parser.XMPDocumentBuilder.java
/** * Parsing method. Return a XMPMetadata object with all elements read * //from ww w .j a v a 2s . c om * @param xmp * serialized XMP * @return Metadata with all information read * @throws XmpParsingException * When element expected not found * @throws XmpSchemaException * When instancing schema object failed or in PDF/A Extension * case, if its namespace miss * @throws XmpUnknownValueTypeException * When ValueType found not correspond to basic type and not has * been declared in current schema * @throws XmpExpectedRdfAboutAttribute * When rdf:Description not contains rdf:about attribute * @throws XmpXpacketEndException * When xpacket end Processing Instruction is missing or is * incorrect * @throws BadFieldValueException * When treat a Schema associed to a schema Description in PDF/A * Extension schema */ public XMPMetadata parse(byte[] xmp) throws XmpParsingException, XmpSchemaException, XmpUnknownValueTypeException, XmpExpectedRdfAboutAttribute, XmpXpacketEndException, BadFieldValueException { if (!(this instanceof XMPDocumentPreprocessor)) { for (XMPDocumentPreprocessor processor : preprocessors) { NSMapping additionalNSMapping = processor.process(xmp); this.nsMap.importNSMapping(additionalNSMapping); } } ByteArrayInputStream is = new ByteArrayInputStream(xmp); try { XMLInputFactory factory = XMLInputFactory.newInstance(); reader.set(factory.createXMLStreamReader(is)); // expect xpacket processing instruction expectNext(XMLStreamReader.PROCESSING_INSTRUCTION, "Did not find initial xpacket processing instruction"); XMPMetadata metadata = parseInitialXpacket(reader.get().getPIData()); // expect x:xmpmeta expectNextTag(XMLStreamReader.START_ELEMENT, "Did not find initial x:xmpmeta"); expectName("adobe:ns:meta/", "xmpmeta"); // expect rdf:RDF expectNextTag(XMLStreamReader.START_ELEMENT, "Did not find initial rdf:RDF"); expectName("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "RDF"); nsMap.resetComplexBasicTypesDeclarationInEntireXMPLevel(); // add all namespaces which could declare nsURI of a basicValueType // all others declarations are ignored int nsCount = reader.get().getNamespaceCount(); for (int i = 0; i < nsCount; i++) { if (nsMap.isComplexBasicTypes(reader.get().getNamespaceURI(i))) { nsMap.setComplexBasicTypesDeclarationForLevelXMP(reader.get().getNamespaceURI(i), reader.get().getNamespacePrefix(i)); } } // now work on each rdf:Description int type = reader.get().nextTag(); while (type == XMLStreamReader.START_ELEMENT) { parseDescription(metadata); type = reader.get().nextTag(); } // all description are finished // expect end of rdf:RDF expectType(XMLStreamReader.END_ELEMENT, "Expected end of descriptions"); expectName("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "RDF"); // expect ending xmpmeta expectNextTag(XMLStreamReader.END_ELEMENT, "Did not find initial x:xmpmeta"); expectName("adobe:ns:meta/", "xmpmeta"); // expect final processing instruction expectNext(XMLStreamReader.PROCESSING_INSTRUCTION, "Did not find final xpacket processing instruction"); // treats xpacket end if (!reader.get().getPITarget().equals("xpacket")) { throw new XmpXpacketEndException("Excepted PI xpacket"); } String xpackData = reader.get().getPIData(); // end attribute must be present and placed in first // xmp spec says Other unrecognized attributes can follow, but // should be ignored if (xpackData.startsWith("end=")) { // check value (5 for end='X') if (xpackData.charAt(5) != 'r' && xpackData.charAt(5) != 'w') { throw new XmpXpacketEndException("Excepted xpacket 'end' attribute with value 'r' or 'w' "); } } else { // should find end='r/w' throw new XmpXpacketEndException( "Excepted xpacket 'end' attribute (must be present and placed in first)"); } metadata.setEndXPacket(xpackData); // return constructed object return metadata; } catch (XMLStreamException e) { throw new XmpParsingException("An error has occured when processing the underlying XMP source", e); } finally { reader.remove(); IOUtils.closeQuietly(is); } }
From source file:org.apache.sysml.runtime.controlprogram.parfor.opt.PerfTestTool.java
private static void readProfile(String fname) throws XMLStreamException, IOException { //init profile map _profile = new HashMap<Integer, HashMap<Integer, CostFunction>>(); //read existing profile FileInputStream fis = new FileInputStream(fname); try {/* w w w. j a v a 2s . com*/ //xml parsing XMLInputFactory xif = XMLInputFactory.newInstance(); XMLStreamReader xsr = xif.createXMLStreamReader(fis); int e = xsr.nextTag(); // profile start while (true) //read all instructions { e = xsr.nextTag(); // instruction start if (e == XMLStreamConstants.END_ELEMENT) break; //reached profile end tag //parse instruction int ID = Integer.parseInt(xsr.getAttributeValue(null, XML_ID)); //String name = xsr.getAttributeValue(null, XML_NAME).trim().replaceAll(" ", Lops.OPERAND_DELIMITOR); HashMap<Integer, CostFunction> tmp = new HashMap<Integer, CostFunction>(); _profile.put(ID, tmp); while (true) { e = xsr.nextTag(); // cost function start if (e == XMLStreamConstants.END_ELEMENT) break; //reached instruction end tag //parse cost function TestMeasure m = TestMeasure.valueOf(xsr.getAttributeValue(null, XML_MEASURE)); TestVariable lv = TestVariable.valueOf(xsr.getAttributeValue(null, XML_VARIABLE)); InternalTestVariable[] pv = parseTestVariables( xsr.getAttributeValue(null, XML_INTERNAL_VARIABLES)); DataFormat df = DataFormat.valueOf(xsr.getAttributeValue(null, XML_DATAFORMAT)); int tDefID = getTestDefID(m, lv, df, pv); xsr.next(); //read characters double[] params = parseParams(xsr.getText()); boolean multidim = _regTestDef.get(tDefID).getInternalVariables().length > 1; CostFunction cf = new CostFunction(params, multidim); tmp.put(tDefID, cf); xsr.nextTag(); // cost function end //System.out.println("added cost function"); } } xsr.close(); } finally { IOUtilFunctions.closeSilently(fis); } //mark profile as successfully read _flagReadData = true; }
From source file:org.apache.tajo.catalog.store.XMLCatalogSchemaManager.java
protected void loadFromXmlFile(XMLInputFactory xmlIf, URL filePath, List<StoreObject> storeObjects) throws IOException, XMLStreamException { XMLStreamReader xmlReader;/*from w w w.java 2 s. com*/ xmlReader = xmlIf.createXMLStreamReader(filePath.openStream()); try { while (xmlReader.hasNext()) { if (xmlReader.next() == XMLStreamConstants.START_ELEMENT && "store".equals(xmlReader.getLocalName())) { StoreObject catalogStore = loadCatalogStore(xmlReader); if (catalogStore != null) { storeObjects.add(catalogStore); } } } } finally { try { xmlReader.close(); } catch (XMLStreamException ignored) { } } }
From source file:org.apereo.portal.portlet.rendering.PortletEventCoordinatationService.java
protected Event unmarshall(IPortletWindow portletWindow, Event event) { //TODO make two types of Event impls, one for marshalled data and one for unmarshalled data String value = (String) event.getValue(); final XMLInputFactory xmlInputFactory = this.xmlUtilities.getXmlInputFactory(); final XMLStreamReader xml; try {//from ww w .j a va 2 s . c om xml = xmlInputFactory.createXMLStreamReader(new StringReader(value)); } catch (XMLStreamException e) { throw new IllegalStateException("Failed to create XMLStreamReader for portlet event: " + event, e); } // now test if object is jaxb final EventDefinition eventDefinitionDD = getEventDefintion(portletWindow, event.getQName()); final PortletDefinition portletDefinition = portletWindow.getPlutoPortletWindow().getPortletDefinition(); final PortletApplicationDefinition application = portletDefinition.getApplication(); final String portletApplicationName = application.getName(); final ClassLoader loader; try { loader = portletContextService.getClassLoader(portletApplicationName); } catch (PortletContainerException e) { throw new IllegalStateException( "Failed to get ClassLoader for portlet application: " + portletApplicationName, e); } final String eventType = eventDefinitionDD.getValueType(); final Class<? extends Serializable> clazz; try { clazz = loader.loadClass(eventType).asSubclass(Serializable.class); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Declared event type '" + eventType + "' cannot be found in portlet application: " + portletApplicationName, e); } //TODO cache JAXBContext in registered portlet application final JAXBElement<? extends Serializable> result; try { final JAXBContext jc = JAXBContext.newInstance(clazz); final Unmarshaller unmarshaller = jc.createUnmarshaller(); result = unmarshaller.unmarshal(xml, clazz); } catch (JAXBException e) { throw new IllegalArgumentException("Cannot create JAXBContext for event type '" + eventType + "' from portlet application: " + portletApplicationName, e); } return new EventImpl(event.getQName(), result.getValue()); }
From source file:org.atomserver.core.validators.SimpleXMLContentValidator.java
private void validateWellFormed(Reader reader) throws BadContentException { try {//from w ww. ja v a 2 s.c om // we will simply walk the doc and see if it throws an Exception XMLInputFactory xif = new WstxInputFactory(); XMLStreamReader xmlreader = xif.createXMLStreamReader(reader); while (xmlreader.hasNext()) { // Errors won't occur unless we actually access the data... touchEvent(xmlreader); } xmlreader.close(); } catch (XMLStreamException ee) { String msg = "Not well-formed XML :: XMLStreamException:: " + ee.getMessage(); log.error(msg); throw new BadContentException(msg); } }
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 ww . j a v a2 s . co 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.deegree.maven.ithelper.ServiceIntegrationTestHelper.java
public void testCapabilities(String service) throws MojoFailureException { String address = createBaseURL() + "services/" + service.toLowerCase() + "?request=GetCapabilities&service=" + service;/*from ww w . j a va 2s. c om*/ try { log.info("Reading capabilities from " + address); String input = IOUtils.toString(new URL(address).openStream(), "UTF-8"); XMLInputFactory fac = XMLInputFactory.newInstance(); XMLStreamReader in = fac.createXMLStreamReader(new StringReader(input)); in.next(); if (in.getLocalName().toLowerCase().contains("exception")) { log.error("Actual response was:"); log.error(input); throw new MojoFailureException("Retrieving capabilities from " + address + " failed."); } } catch (Throwable e) { log.debug("Failed to retrieve capabilities.", e); throw new MojoFailureException( "Retrieving capabilities for " + service + " failed: " + e.getLocalizedMessage(), e); } }
From source file:org.deegree.maven.XMLCatalogueMojo.java
@Override public void execute() throws MojoExecutionException, MojoFailureException { File target = new File(project.getBasedir(), "target"); target.mkdirs();/*from w ww . j av a 2 s . c om*/ target = new File(target, "deegree.xmlcatalog"); PrintStream catalogOut = null; try { catalogOut = new PrintStream(new FileOutputStream(target), true, "UTF-8"); final PrintStream catalog = catalogOut; addDependenciesToClasspath(project, artifactResolver, artifactFactory, metadataSource, localRepository); final XMLInputFactory fac = XMLInputFactory.newInstance(); final Reflections r = new Reflections("/META-INF/schemas/"); class CurrentState { String location; } final CurrentState state = new CurrentState(); r.collect("META-INF/schemas", new Predicate<String>() { @Override public boolean apply(String input) { state.location = input; return input != null && input.endsWith(".xsd"); } }, new Serializer() { @Override public Reflections read(InputStream in) { try { XMLStreamReader reader = fac.createXMLStreamReader(in); nextElement(reader); String location = "classpath:META-INF/schemas/" + state.location; String ns = reader.getAttributeValue(null, "targetNamespace"); catalog.println("PUBLIC \"" + ns + "\" \"" + location + "\""); } catch (Throwable e) { getLog().error(e); } return r; } @Override public File save(Reflections reflections, String filename) { return null; } @Override public String toString(Reflections reflections) { return null; } }); } catch (Throwable t) { throw new MojoFailureException("Creating xml catalog failed: " + t.getLocalizedMessage(), t); } finally { closeQuietly(catalogOut); } }
From source file:org.deegree.style.persistence.se.SeStyleStoreBuilder.java
@Override public StyleStore build() { InputStream in = null;/*from w ww . ja v a2 s .c om*/ XMLStreamReader reader = null; try { in = metadata.getLocation().getAsStream(); XMLInputFactory fac = XMLInputFactory.newInstance(); reader = fac.createXMLStreamReader(in); SymbologyParser parser = new SymbologyParser(metadata.getLocation()); Style style = parser.parse(reader); return new SEStyleStore(style, metadata); } catch (Exception e) { throw new ResourceInitException("Could not read SE style file.", e); } finally { try { if (reader != null) { reader.close(); } } catch (XMLStreamException e) { // eat it } closeQuietly(in); } }
From source file:org.deegree.style.se.parser.PostgreSQLReader.java
private static Continuation<Styling<?>> getContn(String text, Continuation<Styling<?>> contn, final Updater<Styling<?>> updater) { XMLInputFactory fac = XMLInputFactory.newInstance(); Expression expr;/*w w w . j a v a2s.com*/ try { XMLStreamReader reader = fac.createXMLStreamReader(new StringReader(text)); reader.next(); expr = Filter110XMLDecoder.parseExpression(reader); } catch (XMLParsingException e) { String[] ss = text.split("}"); expr = new ValueReference(new QName(ss[0].substring(1), ss[1])); } catch (XMLStreamException e) { String[] ss = text.split("}"); expr = new ValueReference(new QName(ss[0].substring(1), ss[1])); } final Expression expr2 = expr; return new Continuation<Styling<?>>(contn) { @Override public void updateStep(Styling<?> base, Feature obj, XPathEvaluator<Feature> evaluator) { try { Object[] evald = expr2.evaluate(obj, evaluator); if (evald.length == 0) { LOG.warn("The following expression in a style evaluated to null:\n{}", expr2); } else { updater.update(base, evald[0].toString()); } } catch (FilterEvaluationException e) { LOG.warn("Evaluating the following expression resulted in an error '{}':\n{}", e.getLocalizedMessage(), expr2); } } }; }