Example usage for javax.xml.stream XMLInputFactory IS_SUPPORTING_EXTERNAL_ENTITIES

List of usage examples for javax.xml.stream XMLInputFactory IS_SUPPORTING_EXTERNAL_ENTITIES

Introduction

In this page you can find the example usage for javax.xml.stream XMLInputFactory IS_SUPPORTING_EXTERNAL_ENTITIES.

Prototype

String IS_SUPPORTING_EXTERNAL_ENTITIES

To view the source code for javax.xml.stream XMLInputFactory IS_SUPPORTING_EXTERNAL_ENTITIES.

Click Source Link

Document

The property that requires the parser to resolve external parsed entities

Usage

From source file:org.activiti.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  ww w  .j a v  a  2s .  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);
    }

    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 RuntimeException("Could not validate XML with BPMN 2.0 XSD", e);
        }

        // XML conversion
        return convertToBpmnModel(xtr);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("The bpmn 2.0 xml is not UTF8 encoded", e);
    } catch (XMLStreamException e) {
        throw new RuntimeException("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.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);
    }/*from  w  w  w . j a  v a 2 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);
    }

    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.impl.builder.StAXOMBuilder.java

/**
 * The getText() method for a DOCTYPE returns the 
 * subset of the DOCTYPE (not the direct infoset).
 * This may force the parser to get information from 
 * the network.//from   w ww.  j a v a 2s  . c om
 * @return doctype subset
 * @throws OMException
 */
private String getDTDText() throws OMException {
    String text = null;
    try {
        text = parser.getText();
    } catch (RuntimeException e) {
        // Woodstox (and perhaps other parsers)
        // attempts to load the external subset even if
        // external enties is false.  So ignore this error
        // if external entity support is explicitly disabled.
        Boolean b = (Boolean) parser.getProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES);
        if (b == null || b == Boolean.TRUE) {
            throw e;
        }
        if (log.isDebugEnabled()) {
            log.debug("An exception occurred while calling getText() for a DOCTYPE.  "
                    + "The exception is ignored because external " + "entites support is disabled.  "
                    + "The ignored exception is " + e);
        }
    }
    return text;
}

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/*from w w w  . jav  a2  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.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./* w w  w  .  j a  va  2  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;
}

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./*from w  w  w  .java2 s  . 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 ww.j  a v  a 2  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;//  ww w .j  av 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 w ww. j  a  va  2 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);
    }//from www. j av  a 2s  .  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);
    }
}