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.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 .j a v  a2 s.  co 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.fcrepo.migration.foxml.FoxmlInputStreamFedoraObjectProcessor.java

/**
 * foxml input stream fedora object processor.
 * @param is the input stream//from   w w w . j a v  a  2  s  .c om
 * @param fetcher the fetcher
 * @param resolver the resolver
 * @param localFedoraServer the host and port (formatted like "localhost:8080") of the fedora 3 server
 *                          from which the content exposed by the "is" parameter comes.
 * @throws XMLStreamException xml stream exception
 */
public FoxmlInputStreamFedoraObjectProcessor(final InputStream is, final URLFetcher fetcher,
        final InternalIDResolver resolver, final String localFedoraServer) throws XMLStreamException {
    this.fetcher = fetcher;
    this.idResolver = resolver;
    this.localFedoraServer = localFedoraServer;
    final XMLInputFactory factory = XMLInputFactory.newFactory();
    reader = factory.createXMLStreamReader(is);
    reader.nextTag();
    final Map<String, String> attributes = getAttributes(reader, "PID", "VERSION", "FEDORA_URI",
            "schemaLocation");
    if (attributes.get("VERSION") == null || !attributes.get("VERSION").equals("1.1")) {
        isFedora2 = true;
    }
    objectInfo = new DefaultObjectInfo(attributes.get("PID"), attributes.get("FEDORA_URI"));
    while (reader.next() == XMLStreamConstants.CHARACTERS) {
    }

    tempFiles = new ArrayList<File>();
}

From source file:org.flockdata.integration.FileProcessor.java

private int processXMLFile(String file, ExtractProfile extractProfile) throws IOException, FlockException,
        IllegalAccessException, InstantiationException, ClassNotFoundException {
    try {/*from   www.  j av a  2  s . c o m*/
        int rows = 0;
        StopWatch watch = new StopWatch();
        StreamSource source = new StreamSource(file);
        XMLInputFactory xif = XMLInputFactory.newFactory();
        XMLStreamReader xsr = xif.createXMLStreamReader(source);

        XmlMappable mappable = (XmlMappable) Class.forName(extractProfile.getHandler()).newInstance();
        mappable.positionReader(xsr);

        String dataType = mappable.getDataType();
        watch.start();
        try {
            long then = new DateTime().getMillis();
            while (xsr.getLocalName().equals(dataType)) {
                EntityInputBean entityInputBean = Transformer.toEntity(mappable, xsr,
                        extractProfile.getContentModel());
                rows++;
                xsr.nextTag();
                getPayloadWriter().writeEntity(entityInputBean);

                if (stopProcessing(rows, then)) {
                    break;
                }

            }
        } finally {
            getPayloadWriter().flush();
        }
        return endProcess(watch, rows, 0);

    } catch (XMLStreamException | JAXBException e1) {
        throw new IOException(e1);
    }
}

From source file:org.flowable.app.service.editor.FlowableModelQueryService.java

public ModelRepresentation importProcessModel(HttpServletRequest request, MultipartFile file) {

    String fileName = file.getOriginalFilename();
    if (fileName != null && (fileName.endsWith(".bpmn") || fileName.endsWith(".bpmn20.xml"))) {
        try {/*from  www  . j  a  v a2 s .c  o  m*/
            XMLInputFactory xif = XmlUtil.createSafeXmlInputFactory();
            InputStreamReader xmlIn = new InputStreamReader(file.getInputStream(), "UTF-8");
            XMLStreamReader xtr = xif.createXMLStreamReader(xmlIn);
            BpmnModel bpmnModel = bpmnXmlConverter.convertToBpmnModel(xtr);
            if (CollectionUtils.isEmpty(bpmnModel.getProcesses())) {
                throw new BadRequestException("No process found in definition " + fileName);
            }

            if (bpmnModel.getLocationMap().size() == 0) {
                BpmnAutoLayout bpmnLayout = new BpmnAutoLayout(bpmnModel);
                bpmnLayout.execute();
            }

            ObjectNode modelNode = bpmnJsonConverter.convertToJson(bpmnModel);

            org.flowable.bpmn.model.Process process = bpmnModel.getMainProcess();
            String name = process.getId();
            if (StringUtils.isNotEmpty(process.getName())) {
                name = process.getName();
            }
            String description = process.getDocumentation();

            ModelRepresentation model = new ModelRepresentation();
            model.setKey(process.getId());
            model.setName(name);
            model.setDescription(description);
            model.setModelType(AbstractModel.MODEL_TYPE_BPMN);
            Model newModel = modelService.createModel(model, modelNode.toString(),
                    SecurityUtils.getCurrentUserObject());
            return new ModelRepresentation(newModel);

        } catch (BadRequestException e) {
            throw e;

        } catch (Exception e) {
            logger.error("Import failed for " + fileName, e);
            throw new BadRequestException(
                    "Import failed for " + fileName + ", error message " + e.getMessage());
        }
    } else {
        throw new BadRequestException(
                "Invalid file name, only .bpmn and .bpmn20.xml files are supported not " + fileName);
    }
}

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  a  va  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);
            }
        }
    }
}

From source file:org.flowable.cmmn.converter.CmmnXmlConverter.java

public CmmnModel convertToCmmnModel(InputStreamProvider inputStreamProvider, boolean validateSchema,
        boolean enableSafeBpmnXml, String encoding) {
    XMLInputFactory xif = XMLInputFactory.newInstance();

    if (xif.isPropertySupported(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES)) {
        xif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
    }/*  w  ww  .ja  va2  s  .co m*/
    if (xif.isPropertySupported(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES)) {
        xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
    }
    if (xif.isPropertySupported(XMLInputFactory.SUPPORT_DTD)) {
        xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
    }

    if (encoding == null) {
        encoding = DEFAULT_ENCODING;
    }

    if (validateSchema) {
        try (InputStreamReader in = new InputStreamReader(inputStreamProvider.getInputStream(), encoding)) {
            if (!enableSafeBpmnXml) {
                validateModel(inputStreamProvider);
            } else {
                validateModel(xif.createXMLStreamReader(in));
            }
        } catch (UnsupportedEncodingException e) {
            throw new CmmnXMLException("The CMMN 1.1 xml is not properly encoded", e);
        } catch (XMLStreamException e) {
            throw new CmmnXMLException("Error while reading the CMMN 1.1 XML", e);
        } catch (Exception e) {
            throw new CmmnXMLException(e.getMessage(), e);
        }
    }
    // The input stream is closed after schema validation
    try (InputStreamReader in = new InputStreamReader(inputStreamProvider.getInputStream(), encoding)) {
        // XML conversion
        return convertToCmmnModel(xif.createXMLStreamReader(in));
    } catch (UnsupportedEncodingException e) {
        throw new CmmnXMLException("The CMMN 1.1 xml is not properly encoded", e);
    } catch (XMLStreamException e) {
        throw new CmmnXMLException("Error while reading the CMMN 1.1 XML", e);
    } catch (IOException e) {
        throw new CmmnXMLException(e.getMessage(), e);
    }
}

From source file:org.flowable.ui.modeler.service.FlowableDecisionTableService.java

public ModelRepresentation importDecisionTable(HttpServletRequest request, MultipartFile file) {

    String fileName = file.getOriginalFilename();
    if (fileName != null && (fileName.endsWith(".dmn") || fileName.endsWith(".xml"))) {
        try {/*ww  w  . j a  v a2 s . c  o m*/

            XMLInputFactory xif = XmlUtil.createSafeXmlInputFactory();
            InputStreamReader xmlIn = new InputStreamReader(file.getInputStream(), "UTF-8");
            XMLStreamReader xtr = xif.createXMLStreamReader(xmlIn);

            DmnDefinition dmnDefinition = dmnXmlConverter.convertToDmnModel(xtr);

            if (dmnDefinition.getDecisions().size() == 0) {
                throw new FlowableException("No decisions found in " + fileName);
            }

            ObjectNode editorJsonNode = dmnJsonConverter.convertToJson(dmnDefinition);

            // remove id to avoid InvalidFormatException when deserializing
            editorJsonNode.remove("id");

            // set to latest model version
            editorJsonNode.put("modelVersion", 2);

            ModelRepresentation modelRepresentation = new ModelRepresentation();
            modelRepresentation.setKey(dmnDefinition.getDecisions().get(0).getId());
            modelRepresentation.setName(dmnDefinition.getName());
            modelRepresentation.setDescription(dmnDefinition.getDescription());
            modelRepresentation.setModelType(AbstractModel.MODEL_TYPE_DECISION_TABLE);
            Model model = modelService.createModel(modelRepresentation, editorJsonNode.toString(),
                    SecurityUtils.getCurrentUserObject());
            return new ModelRepresentation(model);

        } catch (Exception e) {
            LOGGER.error("Could not import decision table model", e);
            throw new InternalServerErrorException("Could not import decision table model");
        }
    } else {
        throw new BadRequestException(
                "Invalid file name, only .dmn or .xml files are supported not " + fileName);
    }

}

From source file:org.geowebcache.georss.StaxGeoRSSReader.java

public StaxGeoRSSReader(final Reader feed) throws XMLStreamException, FactoryConfigurationError {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    reader = factory.createXMLStreamReader(feed);

    reader.nextTag();//from w  w w. j  a v  a  2 s  . com
    reader.require(START_ELEMENT, null, null);
    QName name = reader.getName();

    if (!(ATOM.NSURI.equals(name.getNamespaceURI()) || "feed".equals(name.getLocalPart()))) {
        throw new IllegalArgumentException("Document is not a GeoRSS feed. Root element: " + name);
    }
    findFirstEntry();
    gmlParser = new GML31ParsingUtils();
}

From source file:org.gephi.io.importer.api.ImportUtils.java

public static XMLStreamReader getXMLReader(Reader reader) {
    try {/*from  w  ww  .  ja va 2s  .  c  o  m*/
        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        if (inputFactory.isPropertySupported("javax.xml.stream.isValidating")) {
            inputFactory.setProperty("javax.xml.stream.isValidating", Boolean.FALSE);
        }
        inputFactory.setXMLReporter(new XMLReporter() {

            @Override
            public void report(String message, String errorType, Object relatedInformation, Location location)
                    throws XMLStreamException {
                throw new RuntimeException("Error:" + errorType + ", message : " + message);
                //System.out.println("Error:" + errorType + ", message : " + message);
            }
        });
        return inputFactory.createXMLStreamReader(reader);
    } catch (XMLStreamException ex) {
        throw new RuntimeException(NbBundle.getMessage(ImportUtils.class, "ImportUtils.error_io"));
    }
}

From source file:org.intermine.webservice.client.results.XMLTableResult.java

private void init() {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    try {//ww w.  j  a va 2  s .c  o m
        xmlReader = factory.createXMLStreamReader(getReader());
    } catch (XMLStreamException e) {
        throw new RuntimeException("Error parsing XML result response", e);
    }
}