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:co.turnus.trace.io.XmlTraceReader.java

public XmlTraceReader(File file, TraceFactory factory) {
    try {/*from  w  w  w.  j  a  v  a 2  s  . co m*/
        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        String extension = TurnusUtils.getExtension(file);
        if (!extension.equals(TurnusExtension.TRACE) && !extension.equals(TurnusExtension.TRACE_COMPRESSED)) {
            throw new TurnusRuntimeException("Trace file reader: unsupported extension");
        }

        InputStream stream = new BufferedInputStream(new FileInputStream(file));
        if (extension.equals(TurnusExtension.TRACE_COMPRESSED)) {
            stream = new CompressorStreamFactory().createCompressorInputStream(CompressorStreamFactory.GZIP,
                    stream);
        }
        reader = inputFactory.createXMLStreamReader(stream);

    } catch (Exception e) {
        throw new TurnusRuntimeException("Error initializing the trace reader", e.getCause());
    }

    this.factory = factory;
    tempDep = new TempDependency();
    tempStep = new TempStep();
}

From source file:edu.harvard.i2b2.common.util.axis2.ServiceClient.java

public static OMElement getPayLoad(String requestPm) throws Exception {
    OMElement lineItem = null;//from   w  w w.j av  a 2s  .c  om
    try {
        StringReader strReader = new StringReader(requestPm);
        XMLInputFactory xif = XMLInputFactory.newInstance();
        XMLStreamReader reader = xif.createXMLStreamReader(strReader);

        StAXOMBuilder builder = new StAXOMBuilder(reader);
        lineItem = builder.getDocumentElement();
    } catch (FactoryConfigurationError e) {
        log.error(e.getMessage());
        throw new Exception(e);
    }
    return lineItem;
}

From source file:com.liferay.portal.util.LocalizationImpl.java

public String getLocalization(String xml, String requestedLanguageId, boolean useDefault) {

    String value = _getCachedValue(xml, requestedLanguageId, useDefault);

    if (value != null) {
        return value;
    } else {//from   w w  w .  ja  v a 2  s  .com
        value = StringPool.BLANK;
    }

    String systemDefaultLanguageId = LocaleUtil.toLanguageId(LocaleUtil.getDefault());

    String priorityLanguageId = null;

    Locale requestedLocale = LocaleUtil.fromLanguageId(requestedLanguageId);

    if (useDefault && LanguageUtil.isDuplicateLanguageCode(requestedLocale.getLanguage())) {

        Locale priorityLocale = LanguageUtil.getLocale(requestedLocale.getLanguage());

        if (!requestedLanguageId.equals(priorityLanguageId)) {
            priorityLanguageId = LocaleUtil.toLanguageId(priorityLocale);
        }
    }

    if (!Validator.isXml(xml)) {
        if (useDefault || requestedLanguageId.equals(systemDefaultLanguageId)) {

            value = xml;
        }

        _setCachedValue(xml, requestedLanguageId, useDefault, value);

        return value;
    }

    XMLStreamReader xmlStreamReader = null;

    ClassLoader portalClassLoader = PortalClassLoaderUtil.getClassLoader();

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    try {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(portalClassLoader);
        }

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();

        xmlStreamReader = xmlInputFactory.createXMLStreamReader(new UnsyncStringReader(xml));

        String defaultLanguageId = StringPool.BLANK;

        // Skip root node

        if (xmlStreamReader.hasNext()) {
            xmlStreamReader.nextTag();

            defaultLanguageId = xmlStreamReader.getAttributeValue(null, _DEFAULT_LOCALE);

            if (Validator.isNull(defaultLanguageId)) {
                defaultLanguageId = systemDefaultLanguageId;
            }
        }

        // Find specified language and/or default language

        String defaultValue = StringPool.BLANK;
        String priorityValue = StringPool.BLANK;

        while (xmlStreamReader.hasNext()) {
            int event = xmlStreamReader.next();

            if (event == XMLStreamConstants.START_ELEMENT) {
                String languageId = xmlStreamReader.getAttributeValue(null, _LANGUAGE_ID);

                if (Validator.isNull(languageId)) {
                    languageId = defaultLanguageId;
                }

                if (languageId.equals(defaultLanguageId) || languageId.equals(priorityLanguageId)
                        || languageId.equals(requestedLanguageId)) {

                    String text = xmlStreamReader.getElementText();

                    if (languageId.equals(defaultLanguageId)) {
                        defaultValue = text;
                    }

                    if (languageId.equals(priorityLanguageId)) {
                        priorityValue = text;
                    }

                    if (languageId.equals(requestedLanguageId)) {
                        value = text;
                    }

                    if (Validator.isNotNull(value)) {
                        break;
                    }
                }
            } else if (event == XMLStreamConstants.END_DOCUMENT) {
                break;
            }
        }

        if (useDefault && Validator.isNotNull(priorityLanguageId) && Validator.isNull(value)
                && Validator.isNotNull(priorityValue)) {

            value = priorityValue;
        }

        if (useDefault && Validator.isNull(value)) {
            value = defaultValue;
        }
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn(e, e);
        }
    } finally {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(contextClassLoader);
        }

        if (xmlStreamReader != null) {
            try {
                xmlStreamReader.close();
            } catch (Exception e) {
            }
        }
    }

    _setCachedValue(xml, requestedLanguageId, useDefault, value);

    return value;
}

From source file:com.autonomy.aci.client.services.impl.AbstractStAXProcessor.java

private void readObject(final ObjectInputStream inputStream) throws IOException, ClassNotFoundException {
    // Read in all the serialized properties...
    inputStream.defaultReadObject();/*  w w  w .java 2  s  . c  om*/

    // Recreate the XMLStreamReader factory...
    xmlInputFactory = XMLInputFactory.newInstance();
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.tiger.TigerXmlReader.java

@Override
public void getNext(JCas aJCas) throws IOException, CollectionException {
    Resource res = nextFile();/*from   w w  w  . ja  va2  s .  c o m*/
    initCas(aJCas, res);

    posMappingProvider.configure(aJCas.getCas());

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

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

        JAXBContext context = JAXBContext.newInstance(Meta.class, AnnotationDecl.class, TigerSentence.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();

        JCasBuilder jb = new JCasBuilder(aJCas);

        XMLEvent e = null;
        while ((e = xmlEventReader.peek()) != null) {
            if (isStartElement(e, "s")) {
                readSentence(jb, unmarshaller.unmarshal(xmlEventReader, TigerSentence.class).getValue());
            } else {
                xmlEventReader.next();
            }

        }

        jb.close();

        // Can only do that after the builder is closed, otherwise the text is not yet set in
        // the
        // CAS and we get "null" for all token strings.
        if (pennTreeEnabled) {
            for (ROOT root : select(aJCas, ROOT.class)) {
                PennTree pt = new PennTree(aJCas, root.getBegin(), root.getEnd());
                PennTreeNode rootNode = PennTreeUtils.convertPennTree(root);
                pt.setPennTree(PennTreeUtils.toPennTree(rootNode));
                pt.addToIndexes();
            }
        }
    } catch (XMLStreamException ex1) {
        throw new IOException(ex1);
    } catch (JAXBException ex2) {
        throw new IOException(ex2);
    } finally {
        closeQuietly(is);
    }
}

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

public void extract() {
    XMLInputFactory xif = XMLInputFactory.newInstance();
    XMLStreamReader reader = null;
    InputStream is = null;/*from w ww  .j a v a  2  s  .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:com.evolveum.midpoint.common.validator.Validator.java

public void validate(InputStream inputStream, OperationResult validatorResult,
        String objectResultOperationName) {

    XMLStreamReader stream = null;
    try {//from   w w w  .j  a v a2  s.c o  m

        Map<String, String> rootNamespaceDeclarations = new HashMap<String, String>();

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        stream = xmlInputFactory.createXMLStreamReader(inputStream);

        int eventType = stream.nextTag();
        if (eventType == XMLStreamConstants.START_ELEMENT) {
            if (!stream.getName().equals(SchemaConstants.C_OBJECTS)) {
                // This has to be an import file with a single objects. Try
                // to process it.
                OperationResult objectResult = validatorResult.createSubresult(objectResultOperationName);
                progress++;
                objectResult.addContext(OperationResult.CONTEXT_PROGRESS, progress);

                EventResult cont = null;
                try {
                    cont = readFromStreamAndValidate(stream, objectResult, rootNamespaceDeclarations,
                            validatorResult);
                } catch (RuntimeException e) {
                    // Make sure that unexpected error is recorded.
                    objectResult.recordFatalError(e);
                    throw e;
                }

                if (!cont.isCont()) {
                    String message = null;
                    if (cont.getReason() != null) {
                        message = cont.getReason();
                    } else {
                        message = "Object validation failed (no reason given)";
                    }
                    if (objectResult.isUnknown()) {
                        objectResult.recordFatalError(message);
                    }
                    validatorResult.recordFatalError(message);
                    return;
                }
                // return to avoid processing objects in loop
                validatorResult.computeStatus("Validation failed", "Validation warnings");
                return;
            }
            // Extract root namespace declarations
            for (int i = 0; i < stream.getNamespaceCount(); i++) {
                rootNamespaceDeclarations.put(stream.getNamespacePrefix(i), stream.getNamespaceURI(i));
            }
        } else {
            throw new SystemException("StAX Malfunction?");
        }

        while (stream.hasNext()) {
            eventType = stream.next();
            if (eventType == XMLStreamConstants.START_ELEMENT) {

                OperationResult objectResult = validatorResult.createSubresult(objectResultOperationName);
                progress++;
                objectResult.addContext(OperationResult.CONTEXT_PROGRESS, progress);

                EventResult cont = null;
                try {
                    // Read and validate individual object from the stream
                    cont = readFromStreamAndValidate(stream, objectResult, rootNamespaceDeclarations,
                            validatorResult);
                } catch (RuntimeException e) {
                    if (objectResult.isUnknown()) {
                        // Make sure that unexpected error is recorded.
                        objectResult.recordFatalError(e);
                    }
                    throw e;
                }

                if (objectResult.isError()) {
                    errors++;
                }

                objectResult.cleanupResult();
                validatorResult.summarize();

                if (cont.isStop()) {
                    if (cont.getReason() != null) {
                        validatorResult.recordFatalError("Processing has been stopped: " + cont.getReason());
                    } else {
                        validatorResult.recordFatalError("Processing has been stopped");
                    }
                    // This means total stop, no other objects will be
                    // processed
                    return;
                }
                if (!cont.isCont()) {
                    if (stopAfterErrors > 0 && errors >= stopAfterErrors) {
                        validatorResult.recordFatalError("Too many errors (" + errors + ")");
                        return;
                    }
                }
            }
        }

    } catch (XMLStreamException ex) {
        // validatorResult.recordFatalError("XML parsing error: " +
        // ex.getMessage()+" on line "+stream.getLocation().getLineNumber(),ex);
        validatorResult.recordFatalError("XML parsing error: " + ex.getMessage(), ex);
        if (handler != null) {
            handler.handleGlobalError(validatorResult);
        }
        return;
    }

    // Error count is sufficient. Detailed messages are in subresults
    validatorResult.computeStatus(errors + " errors, " + (progress - errors) + " passed");

}

From source file:com.qcadoo.model.internal.classconverter.ModelXmlToClassConverterImpl.java

private Map<String, Class<?>> findExistingClasses(final InputStream stream) throws XMLStreamException {
    XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(stream);
    Map<String, Class<?>> existingClasses = new HashMap<String, Class<?>>();

    while (reader.hasNext() && reader.next() > 0) {
        if (isTagStarted(reader, TAG_MODEL)) {
            String pluginIdentifier = getPluginIdentifier(reader);
            String modelName = getStringAttribute(reader, L_NAME);
            String className = ClassNameUtils.getFullyQualifiedClassName(pluginIdentifier, modelName);

            try {
                existingClasses.put(className, classLoader.loadClass(className));
                LOG.info("Class " + className + " already exists, skipping");
            } catch (ClassNotFoundException e) {
                LOG.info("Class " + className + " not found, will be generated");
            }/*from ww  w.  ja  v a 2s  .  co m*/

            break;
        }
    }

    reader.close();

    return existingClasses;
}

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

private void parseLocation(InputStream is, HttpClient httpClient, SitemapURLAdder sitemapURLAdder,
        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, sitemapURLAdder, resolvedLocations);
                parseState.loc = false;//from  w  w w .ja va2  s .  co m
            } else if (parseState.baseURL != null) {
                parseCharacters(parseState, value);
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            tag = xmlReader.getLocalName();
            parseEndElement(sitemapURLAdder, parseState, locationDir, tag);
            break;
        }
        if (!xmlReader.hasNext()) {
            break;
        }
        event = xmlReader.next();
    }
}

From source file:edu.uci.ics.jung.io.graphml.GraphMLReader2.java

/**
 * Verifies the object state and initializes this reader. All transformer
 * properties must be set and be non-null or a <code>GraphReaderException
 * </code> will be thrown. This method may be called more than once.
 * Successive calls will have no effect.
 *
 * @throws edu.uci.ics.jung.io.GraphIOException thrown if an error occurred.
 *///from   w  ww . ja  v a  2 s  . co m
public void init() throws GraphIOException {

    try {

        if (!initialized) {

            // Create the event reader.
            XMLInputFactory factory = XMLInputFactory.newInstance();
            xmlEventReader = factory.createXMLEventReader(fileReader);
            xmlEventReader = factory.createFilteredReader(xmlEventReader, new GraphMLEventFilter());

            initialized = true;
        }

    } catch (Exception e) {
        ExceptionConverter.convert(e);
    }
}