Example usage for javax.xml.stream XMLInputFactory createXMLStreamReader

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

Introduction

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

Prototype

public abstract XMLStreamReader createXMLStreamReader(java.io.InputStream stream) throws XMLStreamException;

Source Link

Document

Create a new XMLStreamReader from a java.io.InputStream

Usage

From source file:org.activiti.designer.eclipse.bpmnimport.BpmnFileReader.java

public void readBpmn() {
    try {/*from www.ja v  a 2 s.c o m*/
        XMLInputFactory xif = XMLInputFactory.newInstance();
        InputStreamReader in = new InputStreamReader(fileStream, "UTF-8");
        XMLStreamReader xtr = xif.createXMLStreamReader(in);
        bpmnParser.parseBpmn(xtr);

        if (bpmnParser.bpmnList.size() == 0)
            return;

        org.eclipse.bpmn2.Process process = Bpmn2Factory.eINSTANCE.createProcess();
        String processId = processName.replace(" ", "");
        process.setId(processId);
        if (bpmnParser.process != null && StringUtils.isNotEmpty(bpmnParser.process.getName())) {
            process.setName(bpmnParser.process.getName());
        } else {
            process.setName(processName);
        }
        if (bpmnParser.process != null && StringUtils.isNotEmpty(bpmnParser.process.getNamespace())) {
            process.setNamespace(bpmnParser.process.getNamespace());
        }

        Documentation documentation = null;
        if (bpmnParser.process == null || bpmnParser.process.getDocumentation().size() == 0) {
            documentation = Bpmn2Factory.eINSTANCE.createDocumentation();
            documentation.setId("documentation_process");
            documentation.setText("");
        } else {
            documentation = bpmnParser.process.getDocumentation().get(0);
        }

        process.getDocumentation().add(documentation);

        if (bpmnParser.process != null && bpmnParser.process.getExecutionListeners().size() > 0) {
            process.getExecutionListeners().addAll(bpmnParser.process.getExecutionListeners());
        }
        diagram.eResource().getContents().add(process);

        if (PreferencesUtil.getBooleanPreference(Preferences.IMPORT_USE_BPMNDI)
                && bpmnParser.bpmdiInfoFound == true) {
            useBPMNDI = true;
            drawDiagramWithBPMNDI(diagram, featureProvider, bpmnParser.bpmnList, bpmnParser.sequenceFlowList,
                    bpmnParser.locationMap);
        } else {

            List<FlowElement> wrongOrderList = createDiagramElements(bpmnParser.bpmnList);
            if (wrongOrderList.size() > 0) {

                int counter = 0;
                while (wrongOrderList.size() > 0 && counter < 10) {
                    int sizeBefore = wrongOrderList.size();
                    wrongOrderList = createDiagramElements(wrongOrderList);

                    if (sizeBefore <= wrongOrderList.size()) {
                        counter++;
                    } else {
                        counter = 0;
                    }
                }
            }
            drawSequenceFlows();
        }
        setFriendlyIds();
        xtr.close();
        in.close();
        fileStream.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

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 www . j av  a2  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.activiti.editor.ui.ConvertProcessDefinitionPopupWindow.java

protected void addButtons() {
    // Cancel/* w  ww. j av  a  2s.c  om*/
    Button cancelButton = new Button(i18nManager.getMessage(Messages.BUTTON_CANCEL));
    cancelButton.addStyleName(Reindeer.BUTTON_SMALL);
    cancelButton.addListener(new ClickListener() {

        private static final long serialVersionUID = 1L;

        public void buttonClick(ClickEvent event) {
            close();
        }
    });

    // Convert
    Button convertButton = new Button(i18nManager.getMessage(Messages.PROCESS_CONVERT_POPUP_CONVERT_BUTTON));
    convertButton.addStyleName(Reindeer.BUTTON_SMALL);
    convertButton.addListener(new ClickListener() {

        private static final long serialVersionUID = 1L;

        public void buttonClick(ClickEvent event) {

            try {
                InputStream bpmnStream = repositoryService.getResourceAsStream(
                        processDefinition.getDeploymentId(), processDefinition.getResourceName());
                XMLInputFactory xif = XMLInputFactory.newInstance();
                InputStreamReader in = new InputStreamReader(bpmnStream, "UTF-8");
                XMLStreamReader xtr = xif.createXMLStreamReader(in);
                BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr);

                if (bpmnModel.getMainProcess() == null || bpmnModel.getMainProcess().getId() == null) {
                    notificationManager.showErrorNotification(Messages.MODEL_IMPORT_FAILED,
                            i18nManager.getMessage(Messages.MODEL_IMPORT_INVALID_BPMN_EXPLANATION));
                } else {

                    if (bpmnModel.getLocationMap().size() == 0) {
                        notificationManager.showErrorNotification(Messages.MODEL_IMPORT_INVALID_BPMNDI,
                                i18nManager.getMessage(Messages.MODEL_IMPORT_INVALID_BPMNDI_EXPLANATION));
                    } else {

                        BpmnJsonConverter converter = new BpmnJsonConverter();
                        ObjectNode modelNode = converter.convertToJson(bpmnModel);
                        Model modelData = repositoryService.newModel();

                        ObjectNode modelObjectNode = new ObjectMapper().createObjectNode();
                        modelObjectNode.put(MODEL_NAME, processDefinition.getName());
                        modelObjectNode.put(MODEL_REVISION, 1);
                        modelObjectNode.put(MODEL_DESCRIPTION, processDefinition.getDescription());
                        modelData.setMetaInfo(modelObjectNode.toString());
                        modelData.setName(processDefinition.getName());

                        repositoryService.saveModel(modelData);

                        repositoryService.addModelEditorSource(modelData.getId(),
                                modelNode.toString().getBytes("utf-8"));

                        close();
                        ExplorerApp.get().getViewManager().showEditorProcessDefinitionPage(modelData.getId());

                        URL explorerURL = ExplorerApp.get().getURL();
                        URL url = new URL(explorerURL.getProtocol(), explorerURL.getHost(),
                                explorerURL.getPort(), explorerURL.getPath().replace("/ui", "")
                                        + "service/editor?id=" + modelData.getId());
                        ExplorerApp.get().getMainWindow().open(new ExternalResource(url));
                    }
                }

            } catch (Exception e) {
                notificationManager.showErrorNotification("error", e);
            }
        }
    });

    // Alignment
    HorizontalLayout buttonLayout = new HorizontalLayout();
    buttonLayout.setSpacing(true);
    buttonLayout.addComponent(cancelButton);
    buttonLayout.addComponent(convertButton);
    addComponent(buttonLayout);
    windowLayout.setComponentAlignment(buttonLayout, Alignment.BOTTOM_RIGHT);
}

From source file:org.activiti.editor.ui.ImportUploadReceiver.java

protected void deployUploadedFile() {
    try {//from   w w  w .ja  v  a 2s  .  co  m
        try {
            if (fileName.endsWith(".bpmn20.xml") || fileName.endsWith(".bpmn")) {
                validFile = true;
                BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
                XMLInputFactory xif = XMLInputFactory.newInstance();
                InputStreamReader in = new InputStreamReader(
                        new ByteArrayInputStream(outputStream.toByteArray()), "UTF-8");
                XMLStreamReader xtr = xif.createXMLStreamReader(in);
                BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr);
                xmlConverter.convertToBpmnModel(xtr);

                if (bpmnModel.getMainProcess() == null || bpmnModel.getMainProcess().getId() == null) {
                    notificationManager.showErrorNotification(Messages.MODEL_IMPORT_FAILED,
                            i18nManager.getMessage(Messages.MODEL_IMPORT_INVALID_BPMN_EXPLANATION));
                } else {

                    if (bpmnModel.getLocationMap().size() == 0) {
                        notificationManager.showErrorNotification(Messages.MODEL_IMPORT_INVALID_BPMNDI,
                                i18nManager.getMessage(Messages.MODEL_IMPORT_INVALID_BPMNDI_EXPLANATION));
                    } else {

                        String processName = null;
                        if (StringUtils.isNotEmpty(bpmnModel.getMainProcess().getName())) {
                            processName = bpmnModel.getMainProcess().getName();
                        } else {
                            processName = bpmnModel.getMainProcess().getId();
                        }

                        modelData = repositoryService.newModel();
                        ObjectNode modelObjectNode = new ObjectMapper().createObjectNode();
                        modelObjectNode.put(MODEL_NAME, processName);
                        modelObjectNode.put(MODEL_REVISION, 1);
                        modelData.setMetaInfo(modelObjectNode.toString());
                        modelData.setName(processName);

                        repositoryService.saveModel(modelData);

                        BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
                        ObjectNode editorNode = jsonConverter.convertToJson(bpmnModel);

                        repositoryService.addModelEditorSource(modelData.getId(),
                                editorNode.toString().getBytes("utf-8"));
                    }
                }
            } else {
                notificationManager.showErrorNotification(Messages.MODEL_IMPORT_INVALID_FILE,
                        i18nManager.getMessage(Messages.MODEL_IMPORT_INVALID_FILE_EXPLANATION));
            }
        } catch (Exception e) {
            String errorMsg = e.getMessage().replace(System.getProperty("line.separator"), "<br/>");
            notificationManager.showErrorNotification(Messages.MODEL_IMPORT_FAILED, errorMsg);
        }
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                notificationManager.showErrorNotification("Server-side error", e.getMessage());
            }
        }
    }
}

From source file:org.apache.axiom.om.util.StAXUtils.java

public static XMLStreamReader createXMLStreamReader(StAXParserConfiguration configuration, final InputStream in)
        throws XMLStreamException {

    final XMLInputFactory inputFactory = getXMLInputFactory(configuration);
    try {// w ww  .  ja  va  2s.  c o  m
        XMLStreamReader reader = (XMLStreamReader) AccessController
                .doPrivileged(new PrivilegedExceptionAction() {
                    public Object run() throws XMLStreamException {
                        return inputFactory.createXMLStreamReader(in);
                    }
                });

        if (isDebugEnabled) {
            log.debug("XMLStreamReader is " + reader.getClass().getName());
        }
        return reader;
    } catch (PrivilegedActionException pae) {
        throw (XMLStreamException) pae.getException();
    }
}

From source file:org.apache.axiom.om.util.StAXUtils.java

public static XMLStreamReader createXMLStreamReader(StAXParserConfiguration configuration, final Reader in)
        throws XMLStreamException {

    final XMLInputFactory inputFactory = getXMLInputFactory(configuration);
    try {//from   ww  w.  j av  a 2s. c  om
        XMLStreamReader reader = (XMLStreamReader) AccessController
                .doPrivileged(new PrivilegedExceptionAction() {
                    public Object run() throws XMLStreamException {
                        return inputFactory.createXMLStreamReader(in);
                    }
                });
        if (isDebugEnabled) {
            log.debug("XMLStreamReader is " + reader.getClass().getName());
        }
        return reader;
    } catch (PrivilegedActionException pae) {
        throw (XMLStreamException) pae.getException();
    }
}

From source file:org.apache.axis2.jaxws.message.databinding.impl.DataSourceBlockImpl.java

@Override
protected XMLStreamReader _getReaderFromBO(Object busObj, Object busContext)
        throws XMLStreamException, WebServiceException {
    try {/* w w w.  j a v  a  2  s . c  o m*/
        if (busObj instanceof DataSource) {
            XMLInputFactory f = StAXUtils.getXMLInputFactory();

            XMLStreamReader reader = f.createXMLStreamReader(((DataSource) busObj).getInputStream());
            StAXUtils.releaseXMLInputFactory(f);
            return reader;
        }
        throw ExceptionFactory.makeWebServiceException(
                Messages.getMessage("SourceNotSupported", busObject.getClass().getName()));
    } catch (Exception e) {
        String className = (busObj == null) ? "none" : busObj.getClass().getName();
        throw ExceptionFactory.makeWebServiceException(Messages.getMessage("SourceReadErr", className), e);
    }
}

From source file:org.apache.axis2.jaxws.message.databinding.impl.SourceBlockImpl.java

@Override
protected XMLStreamReader _getReaderFromBO(Object busObj, Object busContext)
        throws XMLStreamException, WebServiceException {
    try {//from ww  w .jav a 2 s  .c om
        // TODO not sure if this is always the most performant way to do this.
        /* The following code failed in some (CTS) environments. 
        if (busObj instanceof DOMSource) {
           // Let's use our own DOMReader for now...
           Element element = null;
                   
           // Business Object msut be a Document or Element
           Node node = ((DOMSource)busObj).getNode();
           if(node instanceof Document){
           element = ((Document)node).getDocumentElement();
           }else{
           element = (Element) ((DOMSource)busObj).getNode();
           }
                   
           // We had some problems with testers producing DOMSources w/o Namespaces.  
           // It's easy to catch this here.
           if (element.getLocalName() == null) {
           throw new XMLStreamException(ExceptionFactory.
                   makeWebServiceException(Messages.getMessage("JAXBSourceNamespaceErr")));
           }
                   
           return new DOMReader(element);
        } 
        */

        if (busObj instanceof StreamSource) {
            XMLInputFactory f = StAXUtils.getXMLInputFactory();

            XMLStreamReader reader = f.createXMLStreamReader((Source) busObj);
            StAXUtils.releaseXMLInputFactory(f);
            return reader;
        }
        //TODO: For GM we need to only use this approach when absolutely necessary.
        // For example, we don't want to do this if this is a (1.6) StaxSource or if the 
        // installed parser provides a better solution.
        //TODO: Uncomment this code if woodstock parser handles 
        // JAXBSource and SAXSource correctly.
        //return inputFactory.createXMLStreamReader((Source) busObj);
        return _slow_getReaderFromSource((Source) busObj);
    } catch (Exception e) {
        String className = (busObj == null) ? "none" : busObj.getClass().getName();
        throw ExceptionFactory.makeWebServiceException(Messages.getMessage("SourceReadErr", className), e);
    }
}

From source file:org.apache.axis2.saaj.SOAPPartImpl.java

public void setContent(Source source) throws SOAPException {
    try {/*  w  w  w .j  a v  a 2s  .c o m*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        XMLStreamReader reader;

        if (source instanceof StreamSource) {
            reader = inputFactory.createXMLStreamReader(source);
        } else {
            Result result = new StreamResult(baos);
            Transformer xformer = TransformerFactory.newInstance().newTransformer();
            xformer.transform(source, result);
            InputStream is = new ByteArrayInputStream(baos.toByteArray());
            reader = inputFactory.createXMLStreamReader(is);
        }

        StAXSOAPModelBuilder builder1 = null;
        if (this.envelope.element.getOMFactory() instanceof SOAP11Factory) {
            builder1 = new StAXSOAPModelBuilder(reader, (SOAP11Factory) this.envelope.element.getOMFactory(),
                    null);
        } else if (this.envelope.element.getOMFactory() instanceof SOAP12Factory) {
            builder1 = new StAXSOAPModelBuilder(reader, (SOAP12Factory) this.envelope.element.getOMFactory(),
                    null);
        }

        org.apache.axiom.soap.SOAPEnvelope soapEnvelope = builder1.getSOAPEnvelope();
        envelope = new SOAPEnvelopeImpl((org.apache.axiom.soap.impl.dom.SOAPEnvelopeImpl) soapEnvelope);
        envelope.element.build();
        this.document = envelope.getOwnerDocument();
        envelope.setSOAPPartParent(this);
    } catch (TransformerFactoryConfigurationError e) {
        log.error(e);
        throw new SOAPException(e);
    } catch (Exception e) {
        log.error(e);
        throw new SOAPException(e);
    }
}

From source file:org.apache.jackrabbit.oak.benchmark.wikipedia.WikipediaImport.java

public int importWikipedia(Session session) throws Exception {
    long start = System.currentTimeMillis();
    int count = 0;
    int code = 0;

    if (doReport) {
        System.out.format("Importing %s...%n", dump);
    }//from  w  w  w .j a  va 2  s .  co  m

    String type = "nt:unstructured";
    if (session.getWorkspace().getNodeTypeManager().hasNodeType("oak:Unstructured")) {
        type = "oak:Unstructured";
    }
    Node wikipedia = session.getRootNode().addNode("wikipedia", type);

    int levels = 0;
    if (!flat) {
        // calculate the number of levels needed, based on the rough
        // estimate that the average XML size of a page is about 1kB
        for (long pages = dump.length() / 1024; pages > 256; pages /= 256) {
            levels++;
        }
    }

    String title = null;
    String text = null;
    XMLInputFactory factory = XMLInputFactory.newInstance();
    StreamSource source;
    if (dump.getName().endsWith(".xml")) {
        source = new StreamSource(dump);
    } else {
        CompressorStreamFactory csf = new CompressorStreamFactory();
        source = new StreamSource(
                csf.createCompressorInputStream(new BufferedInputStream(new FileInputStream(dump))));
    }
    haltImport = false;
    XMLStreamReader reader = factory.createXMLStreamReader(source);
    while (reader.hasNext() && !haltImport) {
        switch (reader.next()) {
        case XMLStreamConstants.START_ELEMENT:
            if ("title".equals(reader.getLocalName())) {
                title = reader.getElementText();
            } else if ("text".equals(reader.getLocalName())) {
                text = reader.getElementText();
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            if ("page".equals(reader.getLocalName())) {
                String name = Text.escapeIllegalJcrChars(title);
                Node parent = wikipedia;
                if (levels > 0) {
                    int n = name.length();
                    for (int i = 0; i < levels; i++) {
                        int hash = name.substring(min(i, n)).hashCode();
                        parent = JcrUtils.getOrAddNode(parent, String.format("%02x", hash & 0xff));
                    }
                }
                Node page = parent.addNode(name);
                page.setProperty("title", title);
                page.setProperty("text", text);
                code += title.hashCode();
                code += text.hashCode();
                count++;
                if (count % 1000 == 0) {
                    batchDone(session, start, count);
                }

                pageAdded(title, text);
            }
            break;
        }
    }

    session.save();

    if (doReport) {
        long millis = System.currentTimeMillis() - start;
        System.out.format("Imported %d pages in %d seconds (%.2fms/page)%n", count, millis / 1000,
                (double) millis / count);
    }

    return code;
}