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.docx4j.openpackaging.io3.Load3.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.//www .jav a2s .c o m * @param partByteArrays * @param ctm * @param resolvedPartUri * @param rel * @return * @throws Docx4JException including if result is null */ public Part getRawPart(ContentTypeManager ctm, String resolvedPartUri, Relationship rel) throws Docx4JException { Part part = null; InputStream is = null; try { try { log.debug("resolved uri: " + 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.debug("ctm returned " + part.getClass().getName()); if (part instanceof org.docx4j.openpackaging.parts.ThemePart || part instanceof org.docx4j.openpackaging.parts.DocPropsCorePart || part instanceof org.docx4j.openpackaging.parts.DocPropsCustomPart || part instanceof org.docx4j.openpackaging.parts.DocPropsExtendedPart || part instanceof org.docx4j.openpackaging.parts.CustomXmlDataStoragePropertiesPart || part instanceof org.docx4j.openpackaging.parts.digitalsignature.XmlSignaturePart || part instanceof org.docx4j.openpackaging.parts.JaxbXmlPart) { // Nothing to do here } else if (part instanceof org.docx4j.openpackaging.parts.WordprocessingML.BinaryPart) { log.debug("Detected BinaryPart " + part.getClass().getName()); // Note that this is done lazily, since the below lines are commented out // is = partStore.loadPart( resolvedPartUri); // ((BinaryPart)part).setBinaryData(is); } else if (part instanceof org.docx4j.openpackaging.parts.CustomXmlDataStoragePart) { // ContentTypeManager initially detects them as CustomXmlDataStoragePart; // the below changes as necessary // Is it a part we know? is = partStore.loadPart(resolvedPartUri); 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) { is = partStore.loadPart(resolvedPartUri); // 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(ctm, resolvedPartUri); log.warn("Using BinaryPart for " + resolvedPartUri); // is = partStore.loadPart( resolvedPartUri); // ((BinaryPart)part).setBinaryData(is); } } catch (Exception ex) { // IOException, URISyntaxException ex.printStackTrace(); throw new Docx4JException("Failed to getPart", ex); } finally { IOUtils.closeQuietly(is); } if (part == null) { throw new Docx4JException( "cannot find part " + resolvedPartUri + " from rel " + rel.getId() + "=" + rel.getTarget()); } return part; }
From source file:org.docx4j.openpackaging.parts.JaxbXmlPart.java
/** * Unmarshal XML data from the specified InputStream and return the * resulting content tree. Validation event location information may be * incomplete when using this form of the unmarshal API. * * <p>/*from w w w.ja v a2 s .c om*/ * Implements <a href="#unmarshalGlobal">Unmarshal Global Root Element</a>. * * @param is * the InputStream to unmarshal XML data from * @return the newly created root object of the java content tree * * @throws JAXBException * If any unexpected errors occur while unmarshalling */ public E unmarshal(java.io.InputStream is) throws JAXBException { try { /* To avoid possible XML External Entity Injection attack, * we need to configure the processor. * * We use STAX XMLInputFactory to do that. * * createXMLStreamReader(is) is 40% slower than unmarshal(is). * * But it seems to be the best we can do ... * * org.w3c.dom.Document doc = XmlUtils.getNewDocumentBuilder().parse(is) * unmarshal(doc) * * ie DOM is 5x slower than unmarshal(is) * */ 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 = jc.createUnmarshaller(); JaxbValidationEventHandler eventHandler = new JaxbValidationEventHandler(); if (is.markSupported()) { // Only fail hard if we know we can restart eventHandler.setContinue(false); } u.setEventHandler(eventHandler); try { jaxbElement = (E) XmlUtils.unwrap(u.unmarshal(xsr)); } catch (UnmarshalException ue) { if (ue.getLinkedException() != null && ue.getLinkedException().getMessage().contains("entity")) { /* Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[10,19] Message: The entity "xxe" was referenced, but not declared. at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(Unknown Source) at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(Unknown Source) */ log.error(ue.getMessage(), ue); throw ue; } if (is.markSupported()) { // When reading from zip, we use a ByteArrayInputStream, // which does support this. log.info("encountered unexpected content; pre-processing"); eventHandler.setContinue(true); try { Templates mcPreprocessorXslt = JaxbValidationEventHandler.getMcPreprocessor(); is.reset(); JAXBResult result = XmlUtils.prepareJAXBResult(jc); XmlUtils.transform(new StreamSource(is), mcPreprocessorXslt, null, result); jaxbElement = (E) XmlUtils.unwrap(result.getResult()); } catch (Exception e) { throw new JAXBException("Preprocessing exception", e); } } else { log.error(ue.getMessage(), ue); log.error(".. and mark not supported"); throw ue; } } } catch (XMLStreamException e1) { log.error(e1.getMessage(), e1); throw new JAXBException(e1); } return jaxbElement; }
From source file:org.docx4j.XmlUtils.java
public static Object unmarshal(InputStream is, JAXBContext jc) throws JAXBException { // Guard against XXE 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 = null;/*from w w w. jav a 2 s.co m*/ try { xsr = xif.createXMLStreamReader(is); } catch (XMLStreamException e) { throw new JAXBException(e); } Object o = null; Unmarshaller u = jc.createUnmarshaller(); JaxbValidationEventHandler eventHandler = new JaxbValidationEventHandler(); // if (is.markSupported()) { // // Only fail hard if we know we can restart // eventHandler.setContinue(false); // } u.setEventHandler(eventHandler); try { o = u.unmarshal(xsr); return o; } catch (UnmarshalException ue) { if (ue.getLinkedException() != null && ue.getLinkedException().getMessage().contains("entity")) { /* Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[10,19] Message: The entity "xxe" was referenced, but not declared. at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(Unknown Source) at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(Unknown Source) */ log.error(ue.getMessage(), ue); throw ue; } if (is.markSupported()) { // When reading from zip, we use a ByteArrayInputStream, // which does support this. log.info("encountered unexpected content; pre-processing"); eventHandler.setContinue(true); try { Templates mcPreprocessorXslt = JaxbValidationEventHandler.getMcPreprocessor(); is.reset(); JAXBResult result = XmlUtils.prepareJAXBResult(jc); XmlUtils.transform(new StreamSource(is), mcPreprocessorXslt, null, result); return //XmlUtils.unwrap( result.getResult(); } catch (Exception e) { throw new JAXBException("Preprocessing exception", e); } } else { log.error(ue.getMessage(), ue); log.error(".. and mark not supported"); throw ue; } } }
From source file:org.flowable.bpmn.converter.BpmnXMLConverter.java
public BpmnModel convertToBpmnModel(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); }//from www. ja va2 s .co m 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 XMLException(e.getMessage(), e); } // XML conversion return convertToBpmnModel(xtr); } catch (UnsupportedEncodingException e) { throw new XMLException("The bpmn 2.0 xml is not UTF8 encoded", e); } catch (XMLStreamException e) { throw new XMLException("Error while reading the BPMN 2.0 XML", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOGGER.debug("Problem closing BPMN input stream", e); } } } }
From source file:org.flowable.cmmn.converter.CmmnXmlConverter.java
public CmmnModel convertToCmmnModel(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 w w. java2 s . c o m 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); } if (encoding == null) { encoding = DEFAULT_ENCODING; } if (validateSchema) { try (InputStreamReader in = new InputStreamReader(inputStreamProvider.getInputStream(), encoding)) { if (!enableSafeBpmnXml) { validateModel(inputStreamProvider); } else { validateModel(xif.createXMLStreamReader(in)); } } catch (UnsupportedEncodingException e) { throw new CmmnXMLException("The CMMN 1.1 xml is not properly encoded", e); } catch (XMLStreamException e) { throw new CmmnXMLException("Error while reading the CMMN 1.1 XML", e); } catch (Exception e) { throw new CmmnXMLException(e.getMessage(), e); } } // The input stream is closed after schema validation try (InputStreamReader in = new InputStreamReader(inputStreamProvider.getInputStream(), encoding)) { // XML conversion return convertToCmmnModel(xif.createXMLStreamReader(in)); } catch (UnsupportedEncodingException e) { throw new CmmnXMLException("The CMMN 1.1 xml is not properly encoded", e); } catch (XMLStreamException e) { throw new CmmnXMLException("Error while reading the CMMN 1.1 XML", e); } catch (IOException e) { throw new CmmnXMLException(e.getMessage(), e); } }
From source file:org.gephi.io.importer.api.ImportUtils.java
public static XMLStreamReader getXMLReader(Reader reader) { try {/*from w w w . j a v a 2 s. c o m*/ XMLInputFactory inputFactory = XMLInputFactory.newInstance(); if (inputFactory.isPropertySupported("javax.xml.stream.isValidating")) { inputFactory.setProperty("javax.xml.stream.isValidating", Boolean.FALSE); } inputFactory.setXMLReporter(new XMLReporter() { @Override public void report(String message, String errorType, Object relatedInformation, Location location) throws XMLStreamException { throw new RuntimeException("Error:" + errorType + ", message : " + message); //System.out.println("Error:" + errorType + ", message : " + message); } }); return inputFactory.createXMLStreamReader(reader); } catch (XMLStreamException ex) { throw new RuntimeException(NbBundle.getMessage(ImportUtils.class, "ImportUtils.error_io")); } }
From source file:org.jboss.loom.migrators.logging.LoggingMigrator.java
@Override public void loadSourceServerConfig(MigrationContext ctx) throws LoadMigrationException { try {/*ww w . j ava 2s . co m*/ File log4jConfFile = Utils.createPath( //super.getGlobalConfig().getAS5Config().getDir(), "server", //super.getGlobalConfig().getAS5Config().getProfileName(), //"conf", "jboss-log4j.xml"); super.getGlobalConfig().getAS5Config().getConfDir(), "jboss-log4j.xml"); XMLInputFactory xif = XMLInputFactory.newFactory(); xif.setProperty(XMLInputFactory.SUPPORT_DTD, false); XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource(log4jConfFile)); //if( ! log4jConfFile.canRead()) // throw new LoadMigrationException("Cannot find/open file: " + log4jConfFile.getAbsolutePath()); Unmarshaller unmarshaller = JAXBContext.newInstance(LoggingAS5Bean.class).createUnmarshaller(); LoggingAS5Bean loggingAS5 = (LoggingAS5Bean) unmarshaller.unmarshal(xsr); MigratorData mData = new MigratorData(); if (loggingAS5.getCategories() != null) { mData.getConfigFragments().addAll(loggingAS5.getCategories()); } if (loggingAS5.getLoggers() != null) { mData.getConfigFragments().addAll(loggingAS5.getLoggers()); } mData.getConfigFragments().addAll(loggingAS5.getAppenders()); mData.getConfigFragments().add(loggingAS5.getRootLoggerAS5()); ctx.getMigrationData().put(LoggingMigrator.class, mData); } catch (JAXBException | XMLStreamException e) { throw new LoadMigrationException(e); } }
From source file:org.jmecsoftware.plugins.tests.utils.StaxParser.java
/** * Stax parser for a given stream handler and iso control chars set awarness to on. * The iso control chars in the xml file will be replaced by simple spaces, usefull for * potentially bogus XML files to parse, this has a small perfs overhead so use it only when necessary * * @param streamHandler the xml stream handler * @param isoControlCharsAwareParser true or false *///w w w.j av a 2 s.c o m public StaxParser(XmlStreamHandler streamHandler, boolean isoControlCharsAwareParser) { this.streamHandler = streamHandler; XMLInputFactory xmlFactory = XMLInputFactory.newInstance(); if (xmlFactory instanceof WstxInputFactory) { WstxInputFactory wstxInputfactory = (WstxInputFactory) xmlFactory; wstxInputfactory.configureForLowMemUsage(); wstxInputfactory.getConfig().setUndeclaredEntityResolver(new UndeclaredEntitiesXMLResolver()); } xmlFactory.setProperty(XMLInputFactory.IS_VALIDATING, false); xmlFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false); this.isoControlCharsAwareParser = isoControlCharsAwareParser; inf = new SMInputFactory(xmlFactory); }
From source file:org.odata4j.format.xml.AtomFeedFormatParserExt.java
private XMLEventReader2 createXMLEventReader(Reader reader) { XMLInputFactory factory = XMLInputFactory.newInstance(); //XXE on its own can be prevented by setting IS_SUPPORT_EXTERNAL_ENTITIES to false but this will not //prevent a billion laugh attack. Setting IS_REPLACING_ENTITY_REFERENCES to false does //not force the implementation to not process internal entity references. //Safest thing to do is to set SUPPORT_DTD to false to prevent both XXE and billion laugh. factory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE); XMLEventReader2 xmlEventReader2 = new StaxXMLInputFactory2Ext(factory).createXMLEventReader(reader); return xmlEventReader2; }
From source file:org.opendaylight.controller.config.persist.storage.file.xml.model.Config.java
public static Config fromXml(File from) { if (isEmpty(from)) { return new Config(); }//from ww w . ja v a 2 s .c o m try { JAXBContext jaxbContext = JAXBContext.newInstance(Config.class); Unmarshaller um = jaxbContext.createUnmarshaller(); XMLInputFactory xif = XMLInputFactory.newFactory(); xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); xif.setProperty(XMLInputFactory.SUPPORT_DTD, false); XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource(from)); return ((Config) um.unmarshal(xsr)); } catch (JAXBException | XMLStreamException e) { throw new PersistException("Unable to restore configuration", e); } }