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:microsoft.exchange.webservices.data.core.EwsXmlReader.java

public XMLEventReader readSubtree()
        throws XMLStreamException, FileNotFoundException, ServiceXmlDeserializationException {

    if (!this.isStartElement()) {
        throw new ServiceXmlDeserializationException("The current position is not the start of an element.");
    }/* w w  w . ja  v a 2 s .  c om*/

    XMLEventReader eventReader = null;
    InputStream in = null;
    XMLEvent startEvent = this.presentEvent;
    XMLEvent event = startEvent;
    StringBuilder str = new StringBuilder();
    str.append(startEvent);
    do {
        event = this.xmlReader.nextEvent();
        str.append(event);
    } while (!checkEndElement(startEvent, event));

    try {

        XMLInputFactory inputFactory = XMLInputFactory.newInstance();

        try {
            in = new ByteArrayInputStream(str.toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            LOG.error(e);
        }
        eventReader = inputFactory.createXMLEventReader(in);

    } catch (Exception e) {
        LOG.error(e);
    }
    return eventReader;
}

From source file:edu.unc.lib.dl.util.TripleStoreQueryServiceMulgaraImpl.java

/**
 * @param query//  ww  w.j ava  2  s .  c om
 *            an ITQL command
 * @return the message returned by Mulgara
 * @throws RemoteException
 *             for communication failure
 */
public String storeCommand(String query) {
    String result = null;
    String response = this.sendTQL(query);
    if (response != null) {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
        try (StringReader sr = new StringReader(response)) {
            XMLEventReader r = factory.createXMLEventReader(sr);
            boolean inMessage = false;
            StringBuffer message = new StringBuffer();
            while (r.hasNext()) {
                XMLEvent e = r.nextEvent();
                if (e.isStartElement()) {
                    StartElement s = e.asStartElement();
                    if ("message".equals(s.getName().getLocalPart())) {
                        inMessage = true;
                    }
                } else if (e.isEndElement()) {
                    EndElement end = e.asEndElement();
                    if ("message".equals(end.getName().getLocalPart())) {
                        inMessage = false;
                    }
                } else if (inMessage && e.isCharacters()) {
                    message.append(e.asCharacters().getData());
                }
            }
            r.close();
            result = message.toString();
        } catch (XMLStreamException e) {
            e.printStackTrace();
        }
    }
    return result;
}

From source file:com.logiware.accounting.domain.EdiInvoice.java

private void createEcuLineInvoice(File file) throws Exception {
    InputStream inputStream = null;
    XMLEventReader eventReader = null;
    try {//w  w w  .j  a v  a2s.  co  m
        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        inputStream = new FileInputStream(file);
        eventReader = inputFactory.createXMLEventReader(inputStream);
        while (eventReader.hasNext()) {
            XMLEvent event = eventReader.nextEvent();
            if (event.isStartElement()) {
                StartElement startElement = event.asStartElement();
                if ("Header".equalsIgnoreCase(startElement.getName().toString())) {
                    isHeader = true;
                    elements.add("Header");
                } else if ("Body".equalsIgnoreCase(startElement.getName().toString())) {
                    isBody = true;
                    elements.add("Body");
                } else if (isBody && "Information".equalsIgnoreCase(startElement.getName().toString())) {
                    isInformation = true;
                    elements.add("Information");
                } else if (isBody && !isInformation
                        && "Details".equalsIgnoreCase(startElement.getName().toString())) {
                    isDetails = true;
                    elements.add("Details");
                } else if (isBody && !isInformation && !isDetails
                        && "Summary".equalsIgnoreCase(startElement.getName().toString())) {
                    isSummary = true;
                    elements.add("Summary");
                } else if (null == elementType) {
                    setElementType(startElement);
                } else if (null != elementType && null == characterType) {
                    setCharacterType(startElement);
                }
            } else if (event.isCharacters()) {
                setValue(event.asCharacters());
            } else if (event.isEndElement()) {
                EndElement endElement = event.asEndElement();
                if (null != characterType && null != elementType) {
                    removeCharacterType();
                } else if (null != elementType) {
                    removeElementType(endElement);
                } else if (isSummary && "Summary".equalsIgnoreCase(endElement.getName().toString())) {
                    isSummary = false;
                } else if (isDetails && "Details".equalsIgnoreCase(endElement.getName().toString())) {
                    isDetails = false;
                } else if (isBody && "Information".equalsIgnoreCase(endElement.getName().toString())) {
                    isInformation = false;
                } else if ("Body".equalsIgnoreCase(endElement.getName().toString())) {
                    isBody = false;
                } else if ("Header".equalsIgnoreCase(endElement.getName().toString())) {
                    isHeader = false;
                }
            }
        }
        this.company = Company.ECU_LINE;
        status = new EdiInvoiceDAO().getStatus(vendorNumber, invoiceNumber);
        if (!elements.contains("Header")) {
            throw new AccountingException("Bad File. <Header> element missing");
        } else if (!elements.contains("Body")) {
            throw new AccountingException("Bad File. <Body> missing");
        } else if (!elements.contains("Information")) {
            throw new AccountingException("Bad File. <Information> element under <Body> missing");
        } else if (!elements.contains("Details")) {
            throw new AccountingException("Bad File. <Details> element under <Body> missing");
        } else if (!elements.contains("Summary")) {
            throw new AccountingException("Bad File. <Summary> element under <Body> missing");
        } else if (!elements.contains("Applicationreference")) {
            throw new AccountingException("Bad File. <Applicationreference> element under <Header> missing");
        } else if (!elements.contains("Reference")) {
            throw new AccountingException("Bad File. <Reference> element under <Header> missing");
        } else if (!elements.contains("Sender")) {
            throw new AccountingException("Bad File. <Sender> element under <Header> missing");
        } else if (!elements.contains("Code")) {
            throw new AccountingException("Bad File. <Code> element under <Sender> of <Header> missing");
        } else if (!elements.contains("Invoice")) {
            throw new AccountingException(
                    "Bad File. <Invoice> element under <Information> element of <Body> missing");
        } else if (!elements.contains("RelatedReferences")) {
            throw new AccountingException(
                    "Bad File. <RelatedReferences> element under <Information> element of <Body> missing");
        } else if (!elements.contains("BY")) {
            throw new AccountingException(
                    "Bad File. <Parties Qualifier=\"BY\"> under <Information> element of <Body> missing");
        } else if (!elements.contains("SU")) {
            throw new AccountingException(
                    "Bad File. <Parties Qualifier=\"SU\"> under <Information> element of <Body> missing");
        } else if (!elements.contains("PaymentTerms")) {
            throw new AccountingException(
                    "Bad File. <PaymentTerms> element under <Information> element of <Body> missing");
        } else if (!elements.contains("ShipmentInformation")) {
            throw new AccountingException(
                    "Bad File. <ShipmentInformation> element under <Information> element of <Body> missing");
        } else if (!elements.contains("Detail")) {
            throw new AccountingException(
                    "Bad File. <Detail> element under <Details> element of <Body> missing");
        } else if (!elements.contains("TotalMonetaryAmount")) {
            throw new AccountingException(
                    "Bad File. <TotalMonetaryAmount> element under <Summary> element of <Body> missing");
        } else if (!elements.contains("TotalMonetaryAmountGroupByVAT")) {
            throw new AccountingException(
                    "Bad File. <TotalMonetaryAmountGroupByVAT> element under <Summary> element of <Body> missing");
        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (null != eventReader) {
            eventReader.close();
        }
        if (null != inputStream) {
            inputStream.close();
        }
    }
}

From source file:com.ikanow.infinit.e.harvest.enrichment.custom.UnstructuredAnalysisHarvester.java

/**
 * processMeta - handle an individual field
 *///ww  w .j a  va2 s .  c  om
private void processMeta(DocumentPojo f, metaField m, String text, SourcePojo source,
        UnstructuredAnalysisConfigPojo uap) {

    boolean bAllowDuplicates = false;
    if ((null != m.flags) && m.flags.contains("U")) {
        bAllowDuplicates = true;
    }
    if ((null == m.scriptlang) || m.scriptlang.equalsIgnoreCase("regex")) {

        Pattern metaPattern = createRegex(m.script, m.flags);

        int timesToRun = 1;
        Object[] currField = null;
        if ((null != m.flags) && m.flags.contains("c")) {
            currField = f.getMetadata().get(m.fieldName);
        }
        if (null != currField) { // chained metadata
            timesToRun = currField.length;
            text = (String) currField[0];
        } //TESTED

        Matcher matcher = metaPattern.matcher(text);
        LinkedList<String> Llist = null;

        for (int ii = 0; ii < timesToRun; ++ii) {
            if (ii > 0) { // (else either just text, or in the above "chained metadata" initialization above)
                text = (String) currField[ii];
                matcher = metaPattern.matcher(text);
            } //TESTED

            StringBuffer prefix = new StringBuffer(m.fieldName).append(':');
            int nFieldNameLen = m.fieldName.length() + 1;

            try {
                while (matcher.find()) {
                    if (null == Llist) {
                        Llist = new LinkedList<String>();
                    }
                    if (null == m.groupNum) {
                        m.groupNum = 0;
                    }
                    String toAdd = matcher.group(m.groupNum);
                    if (null != m.replace) {
                        toAdd = metaPattern.matcher(toAdd).replaceFirst(m.replace);
                    }
                    if ((null != m.flags) && m.flags.contains("H")) {
                        toAdd = StringEscapeUtils.unescapeHtml(toAdd);
                    }
                    prefix.setLength(nFieldNameLen);
                    prefix.append(toAdd);
                    String dupCheck = prefix.toString();

                    if (!regexDuplicates.contains(dupCheck)) {
                        Llist.add(toAdd);
                        if (!bAllowDuplicates) {
                            regexDuplicates.add(dupCheck);
                        }
                    }
                }
            } catch (Exception e) {
                this._context.getHarvestStatus().logMessage("processMeta1: " + e.getMessage(), true);
            }
        } //(end metadata chaining handling)
        if (null != Llist) {
            if (null != currField) { // (overwrite)
                f.getMetadata().put(m.fieldName, Llist.toArray());
            } else {
                f.addToMetadata(m.fieldName, Llist.toArray());
            }
        } //TESTED
    } else if (m.scriptlang.equalsIgnoreCase("javascript")) {
        if (null == f.getMetadata()) {
            f.setMetadata(new LinkedHashMap<String, Object[]>());
        }
        //set the script engine up if necessary
        if ((null != source) && (null != uap)) {
            //(these are null if called from new processing pipeline vs legacy code)
            intializeScriptEngine(source, uap);
        }

        try {
            //TODO (INF-2488): in new format, this should only happen in between contentMeta blocks/docs
            // (also should be able to use SAH _document object I think?)

            // Javascript: the user passes in 
            Object[] currField = f.getMetadata().get(m.fieldName);
            if ((null == m.flags) || m.flags.isEmpty()) {
                if (null == currField) {
                    engine.put("text", text);
                    engine.put("_iterator", null);
                }
                //(otherwise will just pass the current fields in there)
            } else { // flags specified
                if (m.flags.contains("t")) { // text
                    engine.put("text", text);
                }
                if (m.flags.contains("d")) { // entire document (minus ents and assocs)
                    GsonBuilder gb = new GsonBuilder();
                    Gson g = gb.create();
                    List<EntityPojo> ents = f.getEntities();
                    List<AssociationPojo> assocs = f.getAssociations();
                    try {
                        f.setEntities(null);
                        f.setAssociations(null);
                        engine.put("document", g.toJson(f));
                        securityManager.eval(engine, JavaScriptUtils.initScript);
                    } finally {
                        f.setEntities(ents);
                        f.setAssociations(assocs);
                    }
                }
                if (m.flags.contains("m")) { // metadata
                    GsonBuilder gb = new GsonBuilder();
                    Gson g = gb.create();
                    engine.put("_metadata", g.toJson(f.getMetadata()));
                    securityManager.eval(engine, JavaScriptUtils.iteratorMetaScript);
                }
            } //(end flags processing)

            if (null != currField) {
                f.getMetadata().remove(m.fieldName);

                GsonBuilder gb = new GsonBuilder();
                Gson g = gb.create();
                engine.put("_iterator", g.toJson(currField));
                securityManager.eval(engine, JavaScriptUtils.iteratorDocScript);
            }
            //TESTED (handling of flags, and replacing of existing fields, including when field is null but specified)

            Object returnVal = securityManager.eval(engine, m.script);

            if (null != returnVal) {
                if (returnVal instanceof String) { // The only easy case
                    Object[] array = new Object[1];
                    if ((null != m.flags) && m.flags.contains("H")) {
                        returnVal = StringEscapeUtils.unescapeHtml((String) returnVal);
                    }
                    array[0] = returnVal;
                    f.addToMetadata(m.fieldName, array);
                } else { // complex object or array - in either case the engine turns these into
                         // internal.NativeArray or internal.NativeObject

                    BasicDBList outList = JavaScriptUtils.parseNativeJsObject(returnVal, engine);
                    f.addToMetadata(m.fieldName, outList.toArray());
                }
            }
        } catch (ScriptException e) {

            _context.getHarvestStatus().logMessage(HarvestExceptionUtils.createExceptionMessage(e).toString(),
                    true);

            // Just do nothing and log
            // e.printStackTrace();
            //DEBUG (don't output log messages per doc)
            //logger.error(e.getMessage());
        } catch (Exception e) {

            _context.getHarvestStatus().logMessage(HarvestExceptionUtils.createExceptionMessage(e).toString(),
                    true);

            // Just do nothing and log
            // e.printStackTrace();
            //DEBUG (don't output log messages per doc)
            //logger.error(e.getMessage());
        }
    } else if (m.scriptlang.equalsIgnoreCase("xpath")) {

        String xpath = m.script;

        try {
            createHtmlCleanerIfNeeded();

            int timesToRun = 1;
            Object[] currField = null;
            if ((null != m.flags) && m.flags.contains("c")) {
                currField = f.getMetadata().get(m.fieldName);
            }
            if (null != currField) { // chained metadata
                f.getMetadata().remove(m.fieldName); // (so will add to the end)
                timesToRun = currField.length;
                text = (String) currField[0];
            } //TESTED

            for (int ii = 0; ii < timesToRun; ++ii) {
                if (ii > 0) { // (else either just text, or in the above "chained metadata" initialization above)
                    text = (String) currField[ii];
                } //TESTED

                TagNode node = cleaner.clean(new ByteArrayInputStream(text.getBytes()));

                //NewCode : Only use html cleaner for cleansing
                //use JAXP for full Xpath lib
                Document doc = new DomSerializer(new CleanerProperties()).createDOM(node);

                String extraRegex = extractRegexFromXpath(xpath);

                if (extraRegex != null)
                    xpath = xpath.replace(extraRegex, "");

                XPath xpa = XPathFactory.newInstance().newXPath();
                NodeList res = (NodeList) xpa.evaluate(xpath, doc, XPathConstants.NODESET);

                if (res.getLength() > 0) {
                    if ((null != m.flags) && (m.flags.contains("o"))) { // "o" for object
                        m.groupNum = -1; // (see bConvertToObject below)
                    }
                    StringBuffer prefix = new StringBuffer(m.fieldName).append(':');
                    int nFieldNameLen = m.fieldName.length() + 1;
                    ArrayList<Object> Llist = new ArrayList<Object>(res.getLength());
                    boolean bConvertToObject = ((m.groupNum != null) && (m.groupNum == -1));
                    boolean convertToXml = ((null != m.flags) && (m.flags.contains("x")));
                    for (int i = 0; i < res.getLength(); i++) {
                        Node info_node = res.item(i);
                        if ((null != m.flags) && (m.flags.contains("g"))) {
                            Llist.add(parseHtmlTable(info_node, m.replace));
                        } else if (bConvertToObject || convertToXml) {
                            // Try to create a JSON object out of this
                            StringWriter writer = new StringWriter();
                            try {
                                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                                transformer.transform(new DOMSource(info_node), new StreamResult(writer));
                            } catch (TransformerException e1) {
                                continue;
                            }

                            if (bConvertToObject) {
                                try {
                                    JSONObject subObj = XML.toJSONObject(writer.toString());
                                    if (xpath.endsWith("*")) { // (can have any number of different names here)
                                        Llist.add(XmlToMetadataParser.convertJsonObjectToLinkedHashMap(subObj));
                                    } //TESTED
                                    else {
                                        String[] rootNames = JSONObject.getNames(subObj);
                                        if (1 == rootNames.length) {
                                            // (don't think it can't be any other number in fact)
                                            subObj = subObj.getJSONObject(rootNames[0]);
                                        }
                                        boolean bUnescapeHtml = ((null != m.flags) && m.flags.contains("H"));
                                        Llist.add(XmlToMetadataParser.convertJsonObjectToLinkedHashMap(subObj,
                                                bUnescapeHtml));
                                    } //TESTED
                                } catch (JSONException e) { // Just carry on
                                    continue;
                                }
                                //TESTED
                            } else { // leave in XML form
                                Llist.add(writer.toString().substring(38)); // +38: (step over <?xml version="1.0" encoding="UTF-8"?>)
                            } //TESTED (xpath_test.json)
                        } else { // Treat this as string, either directly or via regex
                            String info = info_node.getTextContent().trim();
                            if (extraRegex == null || extraRegex.isEmpty()) {
                                prefix.setLength(nFieldNameLen);
                                prefix.append(info);
                                String dupCheck = prefix.toString();

                                if (!regexDuplicates.contains(dupCheck)) {
                                    if ((null != m.flags) && m.flags.contains("H")) {
                                        info = StringEscapeUtils.unescapeHtml(info);
                                    }
                                    Llist.add(info);
                                    if (!bAllowDuplicates) {
                                        regexDuplicates.add(dupCheck);
                                    }
                                }
                            } else { // Apply regex to the string
                                Pattern dataRegex = createRegex(extraRegex, m.flags);
                                Matcher dataMatcher = dataRegex.matcher(info);
                                boolean result = dataMatcher.find();
                                while (result) {
                                    String toAdd;
                                    if (m.groupNum != null)
                                        toAdd = dataMatcher.group(m.groupNum);
                                    else
                                        toAdd = dataMatcher.group();
                                    prefix.setLength(nFieldNameLen);
                                    prefix.append(toAdd);
                                    String dupCheck = prefix.toString();

                                    if (!regexDuplicates.contains(dupCheck)) {
                                        if ((null != m.flags) && m.flags.contains("H")) {
                                            toAdd = StringEscapeUtils.unescapeHtml(toAdd);
                                        }
                                        Llist.add(toAdd);
                                        if (!bAllowDuplicates) {
                                            regexDuplicates.add(dupCheck);
                                        }
                                    }

                                    result = dataMatcher.find();
                                }
                            } //(regex vs no regex)
                        } //(end string vs object)
                    }
                    if (Llist.size() > 0) {
                        f.addToMetadata(m.fieldName, Llist.toArray());
                    }
                }
            } //(end loop over metadata objects if applicable)

        } catch (IOException ioe) {
            _context.getHarvestStatus().logMessage(HarvestExceptionUtils.createExceptionMessage(ioe).toString(),
                    true);

            // Just do nothing and log
            //DEBUG (don't output log messages per doc)
            //logger.error(ioe.getMessage());
        } catch (ParserConfigurationException e1) {
            _context.getHarvestStatus().logMessage(HarvestExceptionUtils.createExceptionMessage(e1).toString(),
                    true);
            // Just do nothing and log
            //DEBUG (don't output log messages per doc)
            //logger.error(e1.getMessage());
        } catch (XPathExpressionException e1) {
            _context.getHarvestStatus().logMessage("Error evaluating xpath expression: " + xpath, true);
        }
    } else if (m.scriptlang.equalsIgnoreCase("stream")) { // XML or JSON streaming interface
        // which one?
        try {
            boolean json = false;
            boolean xml = false;
            for (int i = 0; i < 128; ++i) {
                if ('<' == text.charAt(i)) {
                    xml = true;
                    break;
                }
                if ('{' == text.charAt(i) || '[' == text.charAt(i)) {
                    json = true;
                    break;
                }
                if (!Character.isSpaceChar(text.charAt(i))) {
                    break;
                }
            } //TESTED (too many spaces: meta_stream_test, test4; incorrect chars: test3, xml: test1, json: test2)

            boolean textNotObject = m.flags == null || !m.flags.contains("o");

            List<DocumentPojo> docs = new LinkedList<DocumentPojo>();
            List<String> levelOneFields = null;
            if (null != m.script) {
                levelOneFields = Arrays.asList(m.script.split("\\s*,\\s*"));
                if ((1 == levelOneFields.size()) && levelOneFields.get(0).isEmpty()) {
                    // convert [""] to null
                    levelOneFields = null;
                }
            } //TESTED (json and xml)

            if (xml) {
                XmlToMetadataParser parser = new XmlToMetadataParser(levelOneFields, null, null, null, null,
                        null, Integer.MAX_VALUE);
                XMLInputFactory factory = XMLInputFactory.newInstance();
                factory.setProperty(XMLInputFactory.IS_COALESCING, true);
                factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
                XMLStreamReader reader = null;
                try {
                    reader = factory.createXMLStreamReader(new ByteArrayInputStream(text.getBytes()));
                    docs = parser.parseDocument(reader, textNotObject);
                } finally {
                    if (null != reader)
                        reader.close();
                }
            } //TESTED (meta_stream_test, test1)
            if (json) {
                JsonReader jsonReader = null;
                try {
                    JsonToMetadataParser parser = new JsonToMetadataParser(null, levelOneFields, null, null,
                            Integer.MAX_VALUE);
                    jsonReader = new JsonReader(
                            new InputStreamReader(new ByteArrayInputStream(text.getBytes()), "UTF-8"));
                    jsonReader.setLenient(true);
                    docs = parser.parseDocument(jsonReader, textNotObject);
                } finally {
                    if (null != jsonReader)
                        jsonReader.close();
                }
            } //TESTED (meta_stream_test test2)

            if (!docs.isEmpty()) {
                ArrayList<String> Llist = null;
                ArrayList<Object> LlistObj = null;
                if (textNotObject) {
                    Llist = new ArrayList<String>(docs.size());
                } else {
                    LlistObj = new ArrayList<Object>(docs.size());
                }
                for (DocumentPojo doc : docs) {
                    if ((null != doc.getFullText()) || (null != doc.getMetadata())) {
                        if (textNotObject) {
                            Llist.add(doc.getFullText());
                        } //TESTED
                        else if (xml) {
                            LlistObj.add(doc.getMetadata());
                        } //TESTED
                        else if (json) {
                            Object o = doc.getMetadata();
                            if (null != o) {
                                o = doc.getMetadata().get("json");
                                if (o instanceof Object[]) {
                                    LlistObj.addAll(Arrays.asList((Object[]) o));
                                } else if (null != o) {
                                    LlistObj.add(o);
                                } //TESTED
                            }
                        } //TESTED
                    }
                } //TESTED
                if ((null != Llist) && !Llist.isEmpty()) {
                    f.addToMetadata(m.fieldName, Llist.toArray());
                } //TESTED
                if ((null != LlistObj) && !LlistObj.isEmpty()) {
                    f.addToMetadata(m.fieldName, LlistObj.toArray());
                } //TESTED

            } //TESTED (meta_stream_test test1,test2)
        } //(end try)
        catch (Exception e) { // various parsing errors
            _context.getHarvestStatus().logMessage(HarvestExceptionUtils.createExceptionMessage(e).toString(),
                    true);
        }
    } //TESTED (meta_stream_test)

    // (don't currently support other script types)
}

From source file:com.ibm.bi.dml.runtime.controlprogram.parfor.opt.PerfTestTool.java

/**
 * /*from   w ww  .  jav a2 s . c  o  m*/
 * @param fname
 * @throws XMLStreamException
 * @throws IOException
 */
private static void readProfile(String fname) throws XMLStreamException, IOException {
    //init profile map
    _profile = new HashMap<Integer, HashMap<Integer, CostFunction>>();

    //read existing profile
    FileInputStream fis = new FileInputStream(fname);

    try {
        //xml parsing
        XMLInputFactory xif = XMLInputFactory.newInstance();
        XMLStreamReader xsr = xif.createXMLStreamReader(fis);

        int e = xsr.nextTag(); // profile start

        while (true) //read all instructions
        {
            e = xsr.nextTag(); // instruction start
            if (e == XMLStreamConstants.END_ELEMENT)
                break; //reached profile end tag

            //parse instruction
            int ID = Integer.parseInt(xsr.getAttributeValue(null, XML_ID));
            //String name = xsr.getAttributeValue(null, XML_NAME).trim().replaceAll(" ", Lops.OPERAND_DELIMITOR);
            HashMap<Integer, CostFunction> tmp = new HashMap<Integer, CostFunction>();
            _profile.put(ID, tmp);

            while (true) {
                e = xsr.nextTag(); // cost function start
                if (e == XMLStreamConstants.END_ELEMENT)
                    break; //reached instruction end tag

                //parse cost function
                TestMeasure m = TestMeasure.valueOf(xsr.getAttributeValue(null, XML_MEASURE));
                TestVariable lv = TestVariable.valueOf(xsr.getAttributeValue(null, XML_VARIABLE));
                InternalTestVariable[] pv = parseTestVariables(
                        xsr.getAttributeValue(null, XML_INTERNAL_VARIABLES));
                DataFormat df = DataFormat.valueOf(xsr.getAttributeValue(null, XML_DATAFORMAT));
                int tDefID = getTestDefID(m, lv, df, pv);

                xsr.next(); //read characters
                double[] params = parseParams(xsr.getText());
                boolean multidim = _regTestDef.get(tDefID).getInternalVariables().length > 1;
                CostFunction cf = new CostFunction(params, multidim);
                tmp.put(tDefID, cf);

                xsr.nextTag(); // cost function end
                //System.out.println("added cost function");
            }
        }
        xsr.close();
    } finally {
        IOUtilFunctions.closeSilently(fis);
    }

    //mark profile as successfully read
    _flagReadData = true;
}

From source file:ca.uhn.fhir.util.XmlUtil.java

static XMLInputFactory newInputFactory() throws FactoryConfigurationError {
    XMLInputFactory inputFactory;
    try {//from www  . ja v a 2s.co  m
        inputFactory = XMLInputFactory.newInstance();
        throwUnitTestExceptionIfConfiguredToDoSo();
    } catch (Throwable e) {
        throw new ConfigurationException("Unable to initialize StAX - XML processing is disabled", e);
    }
    return inputFactory;
}

From source file:org.wso2.carbon.apimgt.impl.utils.APIUtil.java

/**
 * Build OMElement from inputstream//w w w .  j  a v a2  s  . com
 *
 * @param inputStream
 * @return
 * @throws Exception
 */
public static OMElement buildOMElement(InputStream inputStream) throws Exception {
    XMLStreamReader parser;
    StAXOMBuilder builder;
    try {
        parser = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
        builder = new StAXOMBuilder(parser);
    } catch (XMLStreamException e) {
        String msg = "Error in initializing the parser.";
        log.error(msg, e);
        throw new Exception(msg, e);
    }

    return builder.getDocumentElement();
}

From source file:net.xy.jcms.controller.configurations.parser.UsecaseParser.java

/**
 * parses usecases out from an xml file//ww w.  j ava2s . c o  m
 * 
 * @param in
 * @param loader
 *            used for retrieving configuration included resources and also
 *            for retrieving the controllers
 * @return value
 * @throws XMLStreamException
 * @throws ClassNotFoundException
 */
public static Usecase[] parse(final InputStream in, final ClassLoader loader)
        throws XMLStreamException, ClassNotFoundException {
    final XMLInputFactory factory = XMLInputFactory.newInstance();
    factory.setProperty("javax.xml.stream.isCoalescing", true);
    // not supported by the reference implementation
    // factory.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.TRUE);
    final XMLStreamReader parser = factory.createXMLStreamReader(in);
    while (parser.hasNext()) {
        final int event = parser.next();
        if (event == XMLStreamConstants.START_ELEMENT && parser.getName().getLocalPart().equals("usecases")) {
            return parseUsecases(parser, loader);
        }
    }
    throw new IllegalArgumentException("No usecases section found. [" + parser.getLocation() + "]");
}

From source file:net.xy.jcms.controller.configurations.parser.UsecaseParser.java

/**
 * method for parsing single usecase xml files. one per file.
 * // w w  w .ja  v a 2  s.  c  om
 * @param in
 * @param loader
 * @return parsed usecase
 * @throws XMLStreamException
 * @throws ClassNotFoundException
 */
public static Usecase parseSingle(final InputStream in, final ClassLoader loader)
        throws XMLStreamException, ClassNotFoundException {
    final XMLInputFactory factory = XMLInputFactory.newInstance();
    factory.setProperty("javax.xml.stream.isCoalescing", true);
    // not supported by the reference implementation
    // factory.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.TRUE);
    final XMLStreamReader parser = factory.createXMLStreamReader(in);
    while (parser.hasNext()) {
        final int event = parser.next();
        if (event == XMLStreamConstants.START_ELEMENT && parser.getName().getLocalPart().equals("usecase")) {
            return parseUsecase(parser, loader);
        }
    }
    throw new IllegalArgumentException("No usecases section found. [" + parser.getLocation() + "]");
}