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:com.funtl.framework.smoke.core.modules.act.service.ActProcessService.java

/**
 * ??//w ww . j  a  v a 2 s .  c  o m
 *
 * @param procDefId
 * @throws UnsupportedEncodingException
 * @throws XMLStreamException
 */
@Transactional(readOnly = false)
public org.activiti.engine.repository.Model convertToModel(String procDefId)
        throws UnsupportedEncodingException, XMLStreamException {

    ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
            .processDefinitionId(procDefId).singleResult();
    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);

    BpmnJsonConverter converter = new BpmnJsonConverter();
    ObjectNode modelNode = converter.convertToJson(bpmnModel);
    org.activiti.engine.repository.Model modelData = repositoryService.newModel();
    modelData.setKey(processDefinition.getKey());
    modelData.setName(processDefinition.getResourceName());
    modelData.setCategory(processDefinition.getCategory());//.getDeploymentId());
    modelData.setDeploymentId(processDefinition.getDeploymentId());
    modelData.setVersion(Integer.parseInt(
            String.valueOf(repositoryService.createModelQuery().modelKey(modelData.getKey()).count() + 1)));

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

    repositoryService.saveModel(modelData);

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

    return modelData;
}

From source file:com.norconex.collector.http.sitemap.impl.DefaultSitemapResolver.java

private void parseLocation(InputStream is, DefaultHttpClient httpClient, SitemapURLStore sitemapURLStore,
        Set<String> resolvedLocations, String location) throws XMLStreamException {

    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    inputFactory.setProperty(XMLInputFactory.IS_COALESCING, true);
    XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(is);
    ParseState parseState = new ParseState();

    String locationDir = StringUtils.substringBeforeLast(location, "/");
    int event = xmlReader.getEventType();
    while (true) {
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            String tag = xmlReader.getLocalName();
            parseStartElement(parseState, tag);
            break;
        case XMLStreamConstants.CHARACTERS:
            String value = xmlReader.getText();
            if (parseState.sitemapIndex && parseState.loc) {
                resolveLocation(value, httpClient, sitemapURLStore, resolvedLocations);
                parseState.loc = false;/*  w  w  w. j av  a2  s.c  o  m*/
            } else if (parseState.baseURL != null) {
                parseCharacters(parseState, value);
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            tag = xmlReader.getLocalName();
            parseEndElement(sitemapURLStore, parseState, locationDir, tag);
            break;
        }
        if (!xmlReader.hasNext()) {
            break;
        }
        event = xmlReader.next();
    }
}

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

public ModelRepresentation importCaseModel(HttpServletRequest request, MultipartFile file) {

    String fileName = file.getOriginalFilename();
    if (fileName != null && (fileName.endsWith(".cmmn") || fileName.endsWith(".cmmn.xml"))) {
        try {//from w  ww .jav a2  s  . co  m
            XMLInputFactory xif = XmlUtil.createSafeXmlInputFactory();
            InputStreamReader xmlIn = new InputStreamReader(file.getInputStream(), "UTF-8");
            XMLStreamReader xtr = xif.createXMLStreamReader(xmlIn);
            CmmnModel cmmnModel = cmmnXmlConverter.convertToCmmnModel(xtr);
            if (CollectionUtils.isEmpty(cmmnModel.getCases())) {
                throw new BadRequestException("No cases found in definition " + fileName);
            }

            if (cmmnModel.getLocationMap().size() == 0) {
                throw new BadRequestException("No CMMN DI found in definition " + fileName);
            }

            ObjectNode modelNode = cmmnJsonConverter.convertToJson(cmmnModel);

            Case caseModel = cmmnModel.getPrimaryCase();
            String name = caseModel.getId();
            if (StringUtils.isNotEmpty(caseModel.getName())) {
                name = caseModel.getName();
            }
            String description = caseModel.getDocumentation();

            ModelRepresentation model = new ModelRepresentation();
            model.setKey(caseModel.getId());
            model.setName(name);
            model.setDescription(description);
            model.setModelType(AbstractModel.MODEL_TYPE_CMMN);
            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 .cmmn and .cmmn.xml files are supported not " + fileName);
    }
}

From source file:org.flowable.ui.modeler.service.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 w ww.ja va 2 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:cz.muni.fi.mir.mathmlcanonicalization.MathMLCanonicalizer.java

/**
 * Loads configuration from XML file, overriding the properties.
 *//*  w  w  w . ja v  a 2  s  .  c  om*/
private void loadXMLConfiguration(InputStream xmlConfigurationStream)
        throws ConfigException, XMLStreamException {
    assert xmlConfigurationStream != null;
    final XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    final XMLStreamReader reader = inputFactory.createXMLStreamReader(xmlConfigurationStream);

    boolean config = false;
    Module module = null;
    while (reader.hasNext()) {
        final int event = reader.next();
        switch (event) {
        case XMLStreamConstants.START_ELEMENT: {
            String name = reader.getLocalName();
            if (name.equals("config")) {
                config = true;
                break;
            }

            if (config && name.equals("module")) {
                if (reader.getAttributeCount() == 1) {
                    final String attributeName = reader.getAttributeLocalName(0);
                    final String attributeValue = reader.getAttributeValue(0);

                    if (attributeName.equals("name") && attributeValue != null) {
                        String fullyQualified = Settings.class.getPackage().getName() + ".modules."
                                + attributeValue;
                        try {
                            Class<?> moduleClass = Class.forName(fullyQualified);
                            module = (Module) moduleClass.newInstance();
                        } catch (InstantiationException ex) {
                            LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
                            throw new ConfigException("cannot instantiate module " + attributeValue, ex);
                        } catch (IllegalAccessException ex) {
                            LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
                            throw new ConfigException("cannot access module " + attributeValue, ex);
                        } catch (ClassNotFoundException ex) {
                            LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
                            throw new ConfigException("cannot load module " + attributeValue, ex);
                        }
                    }
                }
            }

            if (config && name.equals("property")) {
                if (reader.getAttributeCount() == 1) {
                    final String attributeName = reader.getAttributeLocalName(0);
                    final String attributeValue = reader.getAttributeValue(0);

                    if (attributeName.equals("name") && attributeValue != null) {
                        if (module == null) {
                            if (Settings.isProperty(attributeValue)) {
                                Settings.setProperty(attributeValue, reader.getElementText());
                            } else {
                                throw new ConfigException("configuration not valid\n"
                                        + "Tried to override non-existing global property " + attributeValue);
                            }
                        } else {
                            if (module.isProperty(attributeValue)) {
                                module.setProperty(attributeValue, reader.getElementText());
                            } else {
                                throw new ConfigException("configuration not valid\n"
                                        + "configuration tried to override non-existing property "
                                        + attributeValue);
                            }
                        }
                    }
                }
            }

            break;
        }
        case XMLStreamConstants.END_ELEMENT: {
            if (config && reader.getLocalName().equals("module")) {
                addModule(module);

                module = null;
            }

            if (config && reader.getLocalName().equals("config")) {
                config = false;
            }
        }
        }
    }
}

From source file:at.lame.hellonzb.parser.NzbParser.java

/**
 * This is the constructor of the class.
 * It parses the given XML file.//w  w w .j a  v a2s.  com
 *
 * @param mainApp The main application object
 * @param file The file name of the nzb file to parse
 * @throws XMLStreamException 
 * @throws IOException 
 */
public NzbParser(HelloNzbCradle mainApp, String file) throws XMLStreamException, IOException, ParseException {
    this.mainApp = mainApp;

    DownloadFile currentFile = null;
    DownloadFileSegment currentSegment = null;
    boolean groupFlag = false;
    boolean segmentFlag = false;

    this.name = file.trim();
    this.name = file.substring(0, file.length() - 4);
    this.downloadFiles = new Vector<DownloadFile>();

    this.origTotalSize = 0;
    this.downloadedBytes = 0;

    // create XML parser
    String string = reformatInputStream(file);
    InputStream in = new ByteArrayInputStream(string.getBytes());
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader parser = factory.createXMLStreamReader(in);

    // parse nzb file with a Java XML parser
    while (parser.hasNext()) {
        switch (parser.getEventType()) {
        // parser has reached the end of the xml file
        case XMLStreamConstants.END_DOCUMENT:
            parser.close();
            break;

        // parser has found a new element
        case XMLStreamConstants.START_ELEMENT:
            String elemName = parser.getLocalName().toLowerCase();
            if (elemName.equals("file")) {
                currentFile = newDownloadFile(parser);
                boolean found = false;
                for (DownloadFile dlf : downloadFiles)
                    if (dlf.getFilename().equals(currentFile.getFilename())) {
                        found = true;
                        break;
                    }

                if (!found)
                    downloadFiles.add(currentFile);
            } else if (elemName.equals("group"))
                groupFlag = true;
            else if (elemName.equals("segment")) {
                currentSegment = newDownloadFileSegment(parser, currentFile);
                currentFile.addSegment(currentSegment);
                segmentFlag = true;
            }
            break;

        // end of element
        case XMLStreamConstants.END_ELEMENT:
            groupFlag = false;
            segmentFlag = false;
            break;

        // get the elements value(s)
        case XMLStreamConstants.CHARACTERS:
            if (!parser.isWhiteSpace()) {
                if (groupFlag && (currentFile != null))
                    currentFile.addGroup(parser.getText());
                else if (segmentFlag && (currentSegment != null))
                    currentSegment.setArticleId(parser.getText());
            }
            break;

        // any other parser event?
        default:
            break;
        }

        parser.next();
    }

    checkFileSegments();
    this.origTotalSize = getCurrTotalSize();
}

From source file:com.ikanow.infinit.e.data_model.custom.InfiniteFileInputXmlParser.java

@Override
public InfiniteFileInputParser initialize(InputStream inStream, SourceFileConfigPojo fileConfig)
        throws IOException {

    // Processing logic

    levelOneFields = new ArrayList<String>();
    ignoreFields = new ArrayList<String>();
    if (null != fileConfig.XmlPreserveCase) {
        this.bPreserveCase = fileConfig.XmlPreserveCase;
    }/*from ww w  .j ava2s  .  c o  m*/
    XmlSourceName = fileConfig.XmlSourceName;
    PKElement = fileConfig.XmlPrimaryKey;
    setLevelOneField(fileConfig.XmlRootLevelValues);
    setIgnoreField(fileConfig.XmlIgnoreValues);
    AttributePrefix = fileConfig.XmlAttributePrefix;

    _sb = new StringBuffer();

    // Input stream -> reader

    XMLInputFactory factory = XMLInputFactory.newInstance();
    factory.setProperty(XMLInputFactory.IS_COALESCING, true);
    factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
    try {
        _xmlStreamReader = factory.createXMLStreamReader(inStream);
    } catch (XMLStreamException e) {
        throw new IOException(e);
    }

    return this;
}

From source file:com.tamingtext.tagrecommender.ExtractStackOverflowData.java

public void extract() {
    XMLInputFactory xif = XMLInputFactory.newInstance();
    XMLStreamReader reader = null;
    InputStream is = null;/*  w  w w  . j  a v  a  2s  .c o m*/

    XMLOutputFactory xof = XMLOutputFactory.newInstance();
    XMLStreamWriter writer = null;
    OutputStream os = null;

    try {
        log.info("Reading data from " + inputFile);

        is = new FileInputStream(inputFile);
        reader = xif.createXMLStreamReader(is);

        os = new FileOutputStream(trainingOutputFile);
        writer = xof.createXMLStreamWriter(os);
        int trainingDataCount = extractXMLData(reader, writer, trainingDataSize);
        os.close();

        os = new FileOutputStream(testOutputFile);
        writer = xof.createXMLStreamWriter(os);
        int testDataCount = extractXMLData(reader, writer, testDataSize);
        os.close();

        log.info("Extracted " + trainingDataCount + " rows of training data");
        log.info("Extracted " + testDataCount + " rows of test data");
    } catch (XMLStreamException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:de.codesourcery.eve.skills.util.XMLMapper.java

public <T> Collection<T> read(Class<T> clasz, IFieldConverters converters, InputStream instream)
        throws XMLStreamException, IOException, IllegalArgumentException, InstantiationException,
        IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException {

    final Collection<T> result = new ArrayList<T>();

    try {//from  w ww  .ja  v a 2 s.c  o  m

        final BeanDescription desc = createBeanDescription(clasz);

        /* 
         * Create inverse mapping attribute name -> field. 
         */
        final Map<String, Field> inverseMapping = new HashMap<String, Field>();

        if (!this.propertyNameMappings.isEmpty()) {

            // key = property name  / value = attribute name
            for (Map.Entry<String, String> propToAttribute : this.propertyNameMappings.entrySet()) {
                inverseMapping.put(propToAttribute.getValue(), desc.getFieldByName(propToAttribute.getKey()));
            }

        } else { // create default mappings
            for (Field f : desc.getFields()) {
                inverseMapping.put(f.getName(), f);
            }
        }

        final int fieldCount = desc.getFields().size();

        final XMLInputFactory factory = XMLInputFactory.newInstance();
        final XMLStreamReader parser = factory.createXMLStreamReader(instream);

        boolean inRow = false;

        final Constructor<T> constructor = clasz.getConstructor(new Class<?>[0]);

        for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
            switch (event) {
            case XMLStreamConstants.START_ELEMENT:
                if ("row".equals(parser.getLocalName())) { // parse row
                    if (inRow) {
                        throw new XMLStreamException("Found nested <row> tag ?", parser.getLocation());
                    }
                    inRow = true;

                    final T bean = constructor.newInstance(new Object[0]);
                    for (int i = 0; i < fieldCount; i++) {
                        final String attrName = parser.getAttributeLocalName(i);
                        final String attrValue = parser.getAttributeValue(i);
                        final Field field = inverseMapping.get(attrName);

                        if (!NIL.equals(attrValue)) {
                            final Object fieldValue = converters.getConverter(field)
                                    .toObject(fromAttributeValue(attrValue), field.getType());
                            field.set(bean, fieldValue);
                        } else {
                            field.set(bean, null);
                        }

                    }
                    result.add(bean);
                }
                break;

            case XMLStreamConstants.END_ELEMENT:
                if ("row".equals(parser.getLocalName())) { // parse row
                    if (!inRow) {
                        throw new XMLStreamException("Found </row> tag without start tag at ",
                                parser.getLocation());
                    }
                    inRow = false;
                }
                break;

            }
        }
    } finally {
        instream.close();
    }

    return result;
}