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:nl.knaw.huygens.tei.xpath.XPathUtil.java

public static Map<String, String> getNamespaceInfo(String xml) {
    Map<String, String> namespaces = Maps.newIdentityHashMap();
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    try {/*from  www .  jav a 2  s . c  o m*/
        XMLStreamReader xreader = inputFactory.createXMLStreamReader(IOUtils.toInputStream(xml, "UTF-8"));
        while (xreader.hasNext()) {
            if (xreader.next() == XMLStreamConstants.START_ELEMENT) {
                QName qName = xreader.getName();
                if (qName != null) {
                    addNamespace(namespaces, qName.getPrefix(), qName.getNamespaceURI());
                    for (int i = 0; i < xreader.getAttributeCount(); i++) {
                        addNamespace(namespaces, xreader.getAttributePrefix(i),
                                xreader.getAttributeNamespace(i));
                    }
                }
            }
        }
    } catch (XMLStreamException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return namespaces;
}

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 w w w .j  ava2  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 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.designer.eclipse.bpmnimport.BpmnFileReader.java

public void readBpmn() {
    try {/*from w w  w. j  a v  a 2s  . co 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);
    }/* w  w  w .jav  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 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 w  w.  j a  v a2  s. co  m*/
    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 {//  w w w.  j  a  va2s .  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.alex73.osm.converters.bel.Convert.java

public static void main(String[] args) throws Exception {
    loadStreetNamesForHouses();//w  w w.  jav  a  2s  .  co m

    InputStream in = new BZip2CompressorInputStream(
            new BufferedInputStream(new FileInputStream("tmp/belarus-latest.osm.bz2"), BUFFER_SIZE));

    // create xml event reader for input stream
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent newLine = eventFactory.createCharacters("\n");
    XMLInputFactory xif = XMLInputFactory.newInstance();
    XMLOutputFactory xof = XMLOutputFactory.newInstance();
    XMLEventReader reader = xif.createXMLEventReader(in);
    XMLEventWriter wrCyr = xof.createXMLEventWriter(
            new BufferedOutputStream(new FileOutputStream("tmp/belarus-bel.osm"), BUFFER_SIZE));
    XMLEventWriter wrInt = xof.createXMLEventWriter(
            new BufferedOutputStream(new FileOutputStream("tmp/belarus-intl.osm"), BUFFER_SIZE));

    // initialize jaxb
    JAXBContext jaxbCtx = JAXBContext.newInstance(Node.class, Way.class, Relation.class);
    Unmarshaller um = jaxbCtx.createUnmarshaller();
    Marshaller m = jaxbCtx.createMarshaller();
    m.setProperty(Marshaller.JAXB_FRAGMENT, true);
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

    XMLEvent e = null;
    while ((e = reader.peek()) != null) {
        boolean processed = false;
        if (e.isStartElement()) {
            StartElement se = (StartElement) e;
            switch (se.getName().getLocalPart()) {
            case "way":
                Way way = um.unmarshal(reader, Way.class).getValue();
                if (way.getId() == 25439425) {
                    System.out.println();
                }
                fixBel(way.getTag(), "name:be", "name");
                String nameBeHouse = houseStreetBe.get(way.getId());
                if (nameBeHouse != null) {
                    setTag(way.getTag(), "addr:street", nameBeHouse);
                }
                m.marshal(way, wrCyr);
                fixInt(way.getTag());
                m.marshal(way, wrInt);
                wrCyr.add(newLine);
                wrInt.add(newLine);
                processed = true;
                break;
            case "node":
                Node node = um.unmarshal(reader, Node.class).getValue();
                fixBel(node.getTag(), "name:be", "name");
                // fixBel(node.getTag(),"addr:street:be","addr:street");
                m.marshal(node, wrCyr);
                fixInt(node.getTag());
                m.marshal(node, wrInt);
                wrCyr.add(newLine);
                wrInt.add(newLine);
                processed = true;
                break;
            case "relation":
                Relation relation = um.unmarshal(reader, Relation.class).getValue();
                fixBel(relation.getTag(), "name:be", "name");
                // fixBel(relation.getTag(),"addr:street:be","addr:street");
                m.marshal(relation, wrCyr);
                fixInt(relation.getTag());
                m.marshal(relation, wrInt);
                wrCyr.add(newLine);
                wrInt.add(newLine);
                processed = true;
                break;
            }
        }
        if (!processed) {
            wrCyr.add(e);
            wrInt.add(e);
        }
        reader.next();
    }

    wrCyr.flush();
    wrCyr.close();
    wrInt.flush();
    wrInt.close();
    System.out.println("UniqueTranslatedTags: " + uniqueTranslatedTags);
}

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

public void testGetTextAsStreamWithoutCaching() throws Exception {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    if (factory.getClass().getName().equals("com.bea.xml.stream.MXParserFactory")) {
        // Skip the test on the StAX reference implementation because it
        // causes an out of memory error
        return;/*from   w w  w .ja  va 2 s  .c o m*/
    }
    DataSource ds = new RandomDataSource(654321, 64, 128, 20000000);
    Vector/*<InputStream>*/ v = new Vector/*<InputStream>*/();
    v.add(new ByteArrayInputStream("<a>".getBytes("ascii")));
    v.add(ds.getInputStream());
    v.add(new ByteArrayInputStream("</a>".getBytes("ascii")));
    factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.FALSE);
    XMLStreamReader reader = factory.createXMLStreamReader(new SequenceInputStream(v.elements()), "ascii");
    OMElement element = new StAXOMBuilder(reader).getDocumentElement();
    Reader in = ElementHelper.getTextAsStream(element, false);
    IOTestUtils.compareStreams(new InputStreamReader(ds.getInputStream(), "ascii"), in);
}

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

private static XMLInputFactory newXMLInputFactory(final ClassLoader classLoader,
        final StAXParserConfiguration configuration) {

    return (XMLInputFactory) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            ClassLoader savedClassLoader;
            if (classLoader == null) {
                savedClassLoader = null;
            } else {
                savedClassLoader = Thread.currentThread().getContextClassLoader();
                Thread.currentThread().setContextClassLoader(classLoader);
            }/*from   w w w .j  a  v  a  2 s  .c  om*/
            try {
                XMLInputFactory factory = XMLInputFactory.newInstance();
                // Woodstox by default creates coalescing parsers. Even if this violates
                // the StAX specs, for compatibility with Woodstox, we always enable the
                // coalescing mode. Note that we need to do that before loading
                // XMLInputFactory.properties so that this setting can be overridden.
                factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
                Map props = loadFactoryProperties("XMLInputFactory.properties");
                if (props != null) {
                    for (Iterator it = props.entrySet().iterator(); it.hasNext();) {
                        Map.Entry entry = (Map.Entry) it.next();
                        factory.setProperty((String) entry.getKey(), entry.getValue());
                    }
                }
                StAXDialect dialect = StAXDialectDetector.getDialect(factory.getClass());
                if (configuration != null) {
                    factory = configuration.configure(factory, dialect);
                }
                return new ImmutableXMLInputFactory(dialect.normalize(dialect.makeThreadSafe(factory)));
            } finally {
                if (savedClassLoader != null) {
                    Thread.currentThread().setContextClassLoader(savedClassLoader);
                }
            }
        }
    });
}

From source file:org.apache.axis2.format.ElementHelperTest.java

public void testGetTextAsStreamWithoutCaching() throws Exception {
    DataSource ds = new RandomDataSource(654321, 64, 128, 20000000);
    Vector<InputStream> v = new Vector<InputStream>();
    v.add(new ByteArrayInputStream("<a>".getBytes("ascii")));
    v.add(ds.getInputStream());//from  w  w  w  . j  a v a  2  s .co  m
    v.add(new ByteArrayInputStream("</a>".getBytes("ascii")));
    XMLInputFactory factory = XMLInputFactory.newInstance();
    factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.FALSE);
    XMLStreamReader reader = factory.createXMLStreamReader(new SequenceInputStream(v.elements()), "ascii");
    OMElement element = new StAXOMBuilder(reader).getDocumentElement();
    Reader in = ElementHelper.getTextAsStream(element, false);
    compareStreams(new InputStreamReader(ds.getInputStream(), "ascii"), in);
}