List of usage examples for javax.xml.stream XMLInputFactory setProperty
public abstract void setProperty(java.lang.String name, Object value) throws java.lang.IllegalArgumentException;
From source file:org.activiti.dmn.xml.converter.DmnXMLConverter.java
public DmnDefinition convertToDmnModel(InputStreamProvider inputStreamProvider, boolean validateSchema, boolean enableSafeBpmnXml, String encoding) { XMLInputFactory xif = XMLInputFactory.newInstance(); if (xif.isPropertySupported(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES)) { xif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false); }/* w ww . ja va 2s . com*/ if (xif.isPropertySupported(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES)) { xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); } if (xif.isPropertySupported(XMLInputFactory.SUPPORT_DTD)) { xif.setProperty(XMLInputFactory.SUPPORT_DTD, false); } InputStreamReader in = null; try { in = new InputStreamReader(inputStreamProvider.getInputStream(), encoding); XMLStreamReader xtr = xif.createXMLStreamReader(in); try { if (validateSchema) { if (!enableSafeBpmnXml) { validateModel(inputStreamProvider); } else { validateModel(xtr); } // The input stream is closed after schema validation in = new InputStreamReader(inputStreamProvider.getInputStream(), encoding); xtr = xif.createXMLStreamReader(in); } } catch (Exception e) { throw new DmnXMLException(e.getMessage(), e); } // XML conversion return convertToDmnModel(xtr); } catch (UnsupportedEncodingException e) { throw new DmnXMLException("The dmn xml is not UTF8 encoded", e); } catch (XMLStreamException e) { throw new DmnXMLException("Error while reading the BPMN 2.0 XML", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOGGER.debug("Problem closing DMN input stream", e); } } } }
From source file:org.apache.axiom.om.util.ElementHelperTest.java
public void testGetTextAsStreamWithoutCaching() throws Exception { XMLInputFactory factory = XMLInputFactory.newInstance(); if (factory.getClass().getName().equals("com.bea.xml.stream.MXParserFactory")) { // Skip the test on the StAX reference implementation because it // causes an out of memory error return;/*ww w . java 2 s.c o m*/ } DataSource ds = new RandomDataSource(654321, 64, 128, 20000000); Vector/*<InputStream>*/ v = new Vector/*<InputStream>*/(); v.add(new ByteArrayInputStream("<a>".getBytes("ascii"))); v.add(ds.getInputStream()); v.add(new ByteArrayInputStream("</a>".getBytes("ascii"))); factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.FALSE); XMLStreamReader reader = factory.createXMLStreamReader(new SequenceInputStream(v.elements()), "ascii"); OMElement element = new StAXOMBuilder(reader).getDocumentElement(); Reader in = ElementHelper.getTextAsStream(element, false); IOTestUtils.compareStreams(new InputStreamReader(ds.getInputStream(), "ascii"), in); }
From source file:org.apache.axiom.om.util.StAXUtils.java
private static XMLInputFactory newXMLInputFactory(final ClassLoader classLoader, final StAXParserConfiguration configuration) { return (XMLInputFactory) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { ClassLoader savedClassLoader; if (classLoader == null) { savedClassLoader = null; } else { savedClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(classLoader); }//from w w w.j a v a2s. c om try { XMLInputFactory factory = XMLInputFactory.newInstance(); // Woodstox by default creates coalescing parsers. Even if this violates // the StAX specs, for compatibility with Woodstox, we always enable the // coalescing mode. Note that we need to do that before loading // XMLInputFactory.properties so that this setting can be overridden. factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); Map props = loadFactoryProperties("XMLInputFactory.properties"); if (props != null) { for (Iterator it = props.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); factory.setProperty((String) entry.getKey(), entry.getValue()); } } StAXDialect dialect = StAXDialectDetector.getDialect(factory.getClass()); if (configuration != null) { factory = configuration.configure(factory, dialect); } return new ImmutableXMLInputFactory(dialect.normalize(dialect.makeThreadSafe(factory))); } finally { if (savedClassLoader != null) { Thread.currentThread().setContextClassLoader(savedClassLoader); } } } }); }
From source file:org.apache.axis2.format.ElementHelperTest.java
public void testGetTextAsStreamWithoutCaching() throws Exception { DataSource ds = new RandomDataSource(654321, 64, 128, 20000000); Vector<InputStream> v = new Vector<InputStream>(); v.add(new ByteArrayInputStream("<a>".getBytes("ascii"))); v.add(ds.getInputStream());//from w w w . j a va 2s . c o m v.add(new ByteArrayInputStream("</a>".getBytes("ascii"))); XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.FALSE); XMLStreamReader reader = factory.createXMLStreamReader(new SequenceInputStream(v.elements()), "ascii"); OMElement element = new StAXOMBuilder(reader).getDocumentElement(); Reader in = ElementHelper.getTextAsStream(element, false); compareStreams(new InputStreamReader(ds.getInputStream(), "ascii"), in); }
From source file:org.apache.ddlutils.io.DatabaseIO.java
/** * Creates a new, initialized XML input factory object. * //from w ww.j ava 2 s . co m * @return The factory object */ private XMLInputFactory getXMLInputFactory() { XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty("javax.xml.stream.isCoalescing", Boolean.TRUE); factory.setProperty("javax.xml.stream.isNamespaceAware", Boolean.TRUE); return factory; }
From source file:org.apache.ddlutils.io.DataReader.java
/** * Creates a new, initialized XML input factory object. * /*from w w w . j a v a 2s.c o m*/ * @return The factory object */ private XMLInputFactory getXMLInputFactory() { XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty("javax.xml.stream.isCoalescing", Boolean.TRUE); factory.setProperty("javax.xml.stream.isNamespaceAware", Boolean.FALSE); return factory; }
From source file:org.apache.tajo.catalog.store.XMLCatalogSchemaManager.java
protected void loadFromXmlFiles() throws IOException, XMLStreamException, URISyntaxException { XMLInputFactory xmlIf = XMLInputFactory.newInstance(); final List<StoreObject> storeObjects = new ArrayList<>(); xmlIf.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); for (String resname : listResources()) { URL filePath = ClassLoader.getSystemResource(resname); if (filePath == null) { throw new FileNotFoundException(resname); }// w w w. j av a 2 s. c om loadFromXmlFile(xmlIf, filePath, storeObjects); } mergeXmlSchemas(storeObjects); }
From source file:org.auraframework.impl.root.parser.handler.IncludeDefRefHandlerTest.java
private XMLStreamReader getReader(Source<?> source) throws XMLStreamException { XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false); XMLStreamReader xmlReader = xmlInputFactory.createXMLStreamReader(source.getSystemId(), source.getHashingReader());//from w w w. j a va2 s.co m xmlReader.next(); return xmlReader; }
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// www. jav a2s.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.docx4j.openpackaging.io.LoadFromZipNG.java
/** * Get a Part (except a relationships part), but not its relationships part * or related parts. Useful if you need quick access to just this part. * This can be called directly from outside the library, in which case * the Part will not be owned by a Package until the calling code makes it so. * @see To get a Part and all its related parts, and add all to a package, use * getPart.//from w ww . j a v a2 s . c o m * @param partByteArrays * @param ctm * @param resolvedPartUri * @param rel * @return * @throws Docx4JException including if result is null */ public static Part getRawPart(HashMap<String, ByteArray> partByteArrays, ContentTypeManager ctm, String resolvedPartUri, Relationship rel) throws Docx4JException { Part part = null; InputStream is = null; try { try { log.debug("resolved uri: " + resolvedPartUri); is = getInputStreamFromZippedPart(partByteArrays, resolvedPartUri); // Get a subclass of Part appropriate for this content type // This will throw UnrecognisedPartException in the absence of // specific knowledge. Hence it is important to get the is // first, as we do above. part = ctm.getPart("/" + resolvedPartUri, rel); log.info("ctm returned " + part.getClass().getName()); if (part instanceof org.docx4j.openpackaging.parts.ThemePart) { ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).setJAXBContext(Context.jcThemePart); ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).unmarshal(is); } else if (part instanceof org.docx4j.openpackaging.parts.DocPropsCorePart) { ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).setJAXBContext(Context.jcDocPropsCore); ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).unmarshal(is); } else if (part instanceof org.docx4j.openpackaging.parts.DocPropsCustomPart) { ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).setJAXBContext(Context.jcDocPropsCustom); ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).unmarshal(is); } else if (part instanceof org.docx4j.openpackaging.parts.DocPropsExtendedPart) { ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).setJAXBContext(Context.jcDocPropsExtended); ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).unmarshal(is); } else if (part instanceof org.docx4j.openpackaging.parts.CustomXmlDataStoragePropertiesPart) { ((org.docx4j.openpackaging.parts.JaxbXmlPart) part) .setJAXBContext(Context.jcCustomXmlProperties); ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).unmarshal(is); } else if (part instanceof org.docx4j.openpackaging.parts.digitalsignature.XmlSignaturePart) { ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).setJAXBContext(Context.jcXmlDSig); ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).unmarshal(is); } else if (part instanceof org.docx4j.openpackaging.parts.JaxbXmlPart) { // MainDocument part, Styles part, Font part etc //((org.docx4j.openpackaging.parts.JaxbXmlPart)part).setJAXBContext(Context.jc); ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).unmarshal(is); } else if (part instanceof org.docx4j.openpackaging.parts.WordprocessingML.BinaryPart) { log.debug("Detected BinaryPart " + part.getClass().getName()); ((BinaryPart) part).setBinaryData(is); } else if (part instanceof org.docx4j.openpackaging.parts.CustomXmlDataStoragePart) { // Is it a part we know? try { XMLInputFactory xif = XMLInputFactory.newInstance(); xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); xif.setProperty(XMLInputFactory.SUPPORT_DTD, false); // a DTD is merely ignored, its presence doesn't cause an exception XMLStreamReader xsr = xif.createXMLStreamReader(is); Unmarshaller u = Context.jc.createUnmarshaller(); Object o = u.unmarshal(xsr); log.debug(o.getClass().getName()); PartName name = part.getPartName(); if (o instanceof CoverPageProperties) { part = new DocPropsCoverPagePart(name); ((DocPropsCoverPagePart) part).setJaxbElement((CoverPageProperties) o); } else if (o instanceof org.opendope.conditions.Conditions) { part = new ConditionsPart(name); ((ConditionsPart) part).setJaxbElement((org.opendope.conditions.Conditions) o); } else if (o instanceof org.opendope.xpaths.Xpaths) { part = new XPathsPart(name); ((XPathsPart) part).setJaxbElement((org.opendope.xpaths.Xpaths) o); } else if (o instanceof org.opendope.questions.Questionnaire) { part = new QuestionsPart(name); ((QuestionsPart) part).setJaxbElement((org.opendope.questions.Questionnaire) o); } else if (o instanceof org.opendope.answers.Answers) { part = new StandardisedAnswersPart(name); ((StandardisedAnswersPart) part).setJaxbElement((org.opendope.answers.Answers) o); } else if (o instanceof org.opendope.components.Components) { part = new ComponentsPart(name); ((ComponentsPart) part).setJaxbElement((org.opendope.components.Components) o); } else if (o instanceof JAXBElement<?> && XmlUtils.unwrap(o) instanceof org.docx4j.bibliography.CTSources) { part = new BibliographyPart(name); ((BibliographyPart) part) .setJaxbElement((JAXBElement<org.docx4j.bibliography.CTSources>) o); } else { log.error("TODO: handle known CustomXmlPart part " + o.getClass().getName()); CustomXmlDataStorage data = getCustomXmlDataStorageClass().factory(); is.reset(); data.setDocument(is); // Not necessarily JAXB, that's just our method name ((org.docx4j.openpackaging.parts.CustomXmlDataStoragePart) part).setData(data); } } catch (javax.xml.bind.UnmarshalException ue) { log.warn("No JAXB model for this CustomXmlDataStorage part; " + ue.getMessage()); CustomXmlDataStorage data = getCustomXmlDataStorageClass().factory(); is.reset(); data.setDocument(is); // Not necessarily JAXB, that's just our method name ((org.docx4j.openpackaging.parts.CustomXmlDataStoragePart) part).setData(data); } } else if (part instanceof org.docx4j.openpackaging.parts.XmlPart) { // try { ((XmlPart) part).setDocument(is); // Experimental 22/6/2011; don't fall back to binary (which we used to) // } catch (Docx4JException d) { // // This isn't an XML part after all, // // even though ContentTypeManager detected it as such // // So get it as a binary part // part = getBinaryPart(partByteArrays, ctm, resolvedPartUri); // log.warn("Could not parse as XML, so using BinaryPart for " // + resolvedPartUri); // ((BinaryPart)part).setBinaryData(is); // } } else { // Shouldn't happen, since ContentTypeManagerImpl should // return an instance of one of the above, or throw an // Exception. log.error("No suitable part found for: " + resolvedPartUri); part = null; } } catch (PartUnrecognisedException e) { log.error("PartUnrecognisedException shouldn't happen anymore!", e); // Try to get it as a binary part part = getBinaryPart(partByteArrays, ctm, resolvedPartUri); log.warn("Using BinaryPart for " + resolvedPartUri); ((BinaryPart) part).setBinaryData(is); } } catch (Exception ex) { // IOException, URISyntaxException ex.printStackTrace(); throw new Docx4JException("Failed to getPart", ex); } finally { if (is != null) { try { is.close(); } catch (IOException exc) { exc.printStackTrace(); } } } if (part == null) { throw new Docx4JException( "cannot find part " + resolvedPartUri + " from rel " + rel.getId() + "=" + rel.getTarget()); } return part; }