Example usage for javax.xml.stream XMLInputFactory newInstance

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

Introduction

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

Prototype

public static XMLInputFactory newInstance() throws FactoryConfigurationError 

Source Link

Document

Creates a new instance of the factory in exactly the same manner as the #newFactory() method.

Usage

From source file:org.dkpro.core.io.xces.XcesXmlReader.java

@Override
public void getNext(JCas aJCas) throws IOException, CollectionException {

    Resource res = nextFile();/*ww  w .j a v a 2s.co m*/
    initCas(aJCas, res);

    InputStream is = null;

    try {
        is = CompressionUtils.getInputStream(res.getLocation(), res.getInputStream());

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(is);

        JAXBContext context = JAXBContext.newInstance(XcesBody.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();

        unmarshaller.setEventHandler(new ValidationEventHandler() {
            public boolean handleEvent(ValidationEvent event) {
                throw new RuntimeException(event.getMessage(), event.getLinkedException());
            }
        });

        JCasBuilder jb = new JCasBuilder(aJCas);

        XMLEvent e = null;
        while ((e = xmlEventReader.peek()) != null) {

            if (isStartElement(e, "body")) {
                try {
                    XcesBody paras = (XcesBody) unmarshaller.unmarshal(xmlEventReader, XcesBody.class)
                            .getValue();
                    readPara(jb, paras);
                } catch (RuntimeException ex) {
                    System.out.println("Unable to parse XCES format: " + ex);
                }
            } else {
                xmlEventReader.next();
            }

        }
        jb.close();

    } catch (XMLStreamException ex1) {
        throw new IOException(ex1);
    } catch (JAXBException e1) {
        throw new IOException(e1);
    } finally {
        closeQuietly(is);
    }

}

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 ww . j av  a  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  .j a  v  a  2 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  w  w . j  a  v  a  2s .c o  m
* 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 ww .  j  a  va  2s. c  om
    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.elissa.web.server.TransformerServlet.java

private void revisitSequenceFlows(Definitions def, String orig) {
    try {//w  w w . ja  v  a  2 s  .  co  m
        Map<String, Map<String, String>> sequenceFlowMapping = new HashMap<String, Map<String, String>>();
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(orig));
        while (reader.hasNext()) {
            if (reader.next() == XMLStreamReader.START_ELEMENT) {
                if ("sequenceFlow".equals(reader.getLocalName())) {
                    String id = "";
                    String source = "";
                    String target = "";
                    for (int i = 0; i < reader.getAttributeCount(); i++) {
                        if ("id".equals(reader.getAttributeLocalName(i))) {
                            id = reader.getAttributeValue(i);
                        }
                        if ("sourceRef".equals(reader.getAttributeLocalName(i))) {
                            source = reader.getAttributeValue(i);
                        }
                        if ("targetRef".equals(reader.getAttributeLocalName(i))) {
                            target = reader.getAttributeValue(i);
                        }
                    }
                    Map<String, String> valueMap = new HashMap<String, String>();
                    valueMap.put("sourceRef", source);
                    valueMap.put("targetRef", target);
                    sequenceFlowMapping.put(id, valueMap);
                }
            }
        }
        List<RootElement> rootElements = def.getRootElements();
        for (RootElement root : rootElements) {
            if (root instanceof Process) {
                Process process = (Process) root;
                List<FlowElement> flowElements = process.getFlowElements();
                for (FlowElement fe : flowElements) {
                    if (fe instanceof SequenceFlow) {
                        SequenceFlow sf = (SequenceFlow) fe;
                        if (sequenceFlowMapping.containsKey(sf.getId())) {
                            sf.setSourceRef(
                                    getFlowNode(def, sequenceFlowMapping.get(sf.getId()).get("sourceRef")));
                            sf.setTargetRef(
                                    getFlowNode(def, sequenceFlowMapping.get(sf.getId()).get("targetRef")));
                        } else {
                            _logger.error("Could not find mapping for sequenceFlow: " + sf.getId());
                        }
                    }
                }
            }
        }
    } catch (FactoryConfigurationError e) {
        _logger.error(e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        _logger.error(e.getMessage());
        e.printStackTrace();
    }
}

From source file:org.elissa.web.server.TransformerServlet.java

private void addBpmnDiInfo(Definitions def, String gpd) {
    try {/*  w w w . j  a v  a  2 s  .co m*/
        Map<String, Bounds> _bounds = new HashMap<String, Bounds>();
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(gpd));
        while (reader.hasNext()) {
            if (reader.next() == XMLStreamReader.START_ELEMENT) {
                if ("node".equals(reader.getLocalName())) {
                    Bounds b = DcFactory.eINSTANCE.createBounds();
                    String nodeName = null;
                    String nodeX = null;
                    String nodeY = null;
                    String nodeWidth = null;
                    String nodeHeight = null;
                    for (int i = 0; i < reader.getAttributeCount(); i++) {
                        if ("name".equals(reader.getAttributeLocalName(i))) {
                            nodeName = reader.getAttributeValue(i);
                        } else if ("x".equals(reader.getAttributeLocalName(i))) {
                            nodeX = reader.getAttributeValue(i);
                        } else if ("y".equals(reader.getAttributeLocalName(i))) {
                            nodeY = reader.getAttributeValue(i);
                        } else if ("width".equals(reader.getAttributeLocalName(i))) {
                            nodeWidth = reader.getAttributeValue(i);
                        } else if ("height".equals(reader.getAttributeLocalName(i))) {
                            nodeHeight = reader.getAttributeValue(i);
                        }
                    }
                    b.setX(new Float(nodeX).floatValue());
                    b.setY(new Float(nodeY).floatValue());
                    b.setWidth(new Float(nodeWidth).floatValue());
                    b.setHeight(new Float(nodeHeight).floatValue());
                    _bounds.put(nodeName, b);
                }
            }
        }

        for (RootElement rootElement : def.getRootElements()) {
            if (rootElement instanceof Process) {
                Process process = (Process) rootElement;
                BpmnDiFactory diFactory = BpmnDiFactory.eINSTANCE;
                BPMNDiagram diagram = diFactory.createBPMNDiagram();
                BPMNPlane plane = diFactory.createBPMNPlane();
                plane.setBpmnElement(process);
                diagram.setPlane(plane);
                for (FlowElement flowElement : process.getFlowElements()) {
                    if (flowElement instanceof FlowNode) {
                        Bounds b = _bounds.get(flowElement.getId());
                        if (b != null) {
                            BPMNShape shape = diFactory.createBPMNShape();
                            shape.setBpmnElement(flowElement);
                            shape.setBounds(b);
                            plane.getPlaneElement().add(shape);
                        }
                    } else if (flowElement instanceof SequenceFlow) {
                        SequenceFlow sequenceFlow = (SequenceFlow) flowElement;
                        BPMNEdge edge = diFactory.createBPMNEdge();
                        edge.setBpmnElement(flowElement);
                        DcFactory dcFactory = DcFactory.eINSTANCE;
                        Point point = dcFactory.createPoint();
                        if (sequenceFlow.getSourceRef() != null) {
                            Bounds sourceBounds = _bounds.get(sequenceFlow.getSourceRef().getId());
                            point.setX(sourceBounds.getX() + (sourceBounds.getWidth() / 2));
                            point.setY(sourceBounds.getY() + (sourceBounds.getHeight() / 2));
                        }
                        edge.getWaypoint().add(point);
                        //                      List<Point> dockers = _dockers.get(sequenceFlow.getId());
                        //                      for (int i = 1; i < dockers.size() - 1; i++) {
                        //                         edge.getWaypoint().add(dockers.get(i));
                        //                      }
                        point = dcFactory.createPoint();
                        if (sequenceFlow.getTargetRef() != null) {
                            Bounds targetBounds = _bounds.get(sequenceFlow.getTargetRef().getId());
                            point.setX(targetBounds.getX() + (targetBounds.getWidth() / 2));
                            point.setY(targetBounds.getY() + (targetBounds.getHeight() / 2));
                        }
                        edge.getWaypoint().add(point);
                        plane.getPlaneElement().add(edge);
                    }
                }

                def.getDiagrams().add(diagram);
            }
        }
    } catch (FactoryConfigurationError e) {
        _logger.error("Exception adding bpmndi info: " + e.getMessage());
    } catch (Exception e) {
        _logger.error("Exception adding bpmndi info: " + e.getMessage());
    }
}

From source file:org.elissa.web.server.TransformerServlet.java

private String[] findPackageAndAssetNameForUUID(String uuid, IDiagramProfile profile) {
    List<String> packages = new ArrayList<String>();
    String packagesURL = ExternalInfo.getExternalProtocol(profile) + "://"
            + ExternalInfo.getExternalHost(profile) + "/" + profile.getExternalLoadURLSubdomain().substring(0,
                    profile.getExternalLoadURLSubdomain().indexOf("/"))
            + "/rest/packages/";
    try {/*from   w  w  w.ja va 2 s. c  o  m*/
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader reader = factory
                .createXMLStreamReader(getInputStreamForURL(packagesURL, "GET", profile));
        while (reader.hasNext()) {
            if (reader.next() == XMLStreamReader.START_ELEMENT) {
                if ("title".equals(reader.getLocalName())) {
                    packages.add(reader.getElementText());
                }
            }
        }
    } catch (Exception e) {
        // we dont want to barf..just log that error happened
        _logger.error(e.getMessage());
    }

    boolean gotPackage = false;
    String[] pkgassetnames = new String[2];
    for (String nextPackage : packages) {
        String packageAssetURL = ExternalInfo.getExternalProtocol(profile) + "://"
                + ExternalInfo.getExternalHost(profile) + "/"
                + profile.getExternalLoadURLSubdomain().substring(0,
                        profile.getExternalLoadURLSubdomain().indexOf("/"))
                + "/rest/packages/" + nextPackage + "/assets/";
        try {
            XMLInputFactory factory = XMLInputFactory.newInstance();
            XMLStreamReader reader = factory
                    .createXMLStreamReader(getInputStreamForURL(packageAssetURL, "GET", profile));
            String title = "";
            while (reader.hasNext()) {
                int next = reader.next();
                if (next == XMLStreamReader.START_ELEMENT) {
                    if ("title".equals(reader.getLocalName())) {
                        title = reader.getElementText();
                    }
                    if ("uuid".equals(reader.getLocalName())) {
                        String eleText = reader.getElementText();
                        if (uuid.equals(eleText)) {
                            pkgassetnames[0] = nextPackage;
                            pkgassetnames[1] = title;
                            gotPackage = true;
                        }
                    }
                }
            }
        } catch (Exception e) {
            // we dont want to barf..just log that error happened
            _logger.error(e.getMessage());
        }
        if (gotPackage) {
            // noo need to loop through rest of packages
            break;
        }
    }
    return pkgassetnames;
}

From source file:org.emonocot.job.io.StaxEventItemReader.java

/**
 * @throws Exception if there is a problem opening the resource
 *//*from   w  w  w.jav  a 2  s  . co  m*/
protected final void doOpen() throws Exception {
    Assert.notNull(resource, "The Resource must not be null.");

    noInput = false;
    if (!resource.exists()) {
        if (strict) {
            throw new IllegalStateException("Input resource must exist" + " (reader is in 'strict' mode)");
        }
        noInput = true;
        logger.warn("Input resource does not exist " + resource.getDescription());
        return;
    }
    if (!resource.isReadable()) {
        if (strict) {
            throw new IllegalStateException(
                    "Input resource must be readable" + " (reader is in 'strict' mode)");
        }
        noInput = true;
        logger.warn("Input resource is not readable " + resource.getDescription());
        return;
    }

    reader = new InputStreamReader(resource.getInputStream(), this.encoding);
    eventReader = XMLInputFactory.newInstance().createXMLEventReader(reader);
    fragmentReader = new DefaultFragmentEventReader(eventReader);

}

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);
    }/*w w w.  j  ava 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 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);
            }
        }
    }
}