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:edu.harvard.iq.dvn.core.analysis.NetworkDataServiceBean.java

private void processXML(String fileName, NetworkDataFile ndf) throws XMLStreamException, IOException {

    File file = new File(fileName);
    FileReader fileReader = new FileReader(file);
    javax.xml.stream.XMLInputFactory xmlif = javax.xml.stream.XMLInputFactory.newInstance();
    xmlif.setProperty("javax.xml.stream.isCoalescing", java.lang.Boolean.TRUE);

    XMLStreamReader xmlr = xmlif.createXMLStreamReader(fileReader);
    for (int event = xmlr.next(); event != XMLStreamConstants.END_DOCUMENT; event = xmlr.next()) {
        if (event == XMLStreamConstants.START_ELEMENT) {

            if (xmlr.getLocalName().equals("key"))
                processKey(xmlr, ndf);/*from www  .  j  a  v a 2s .c o m*/
            else if (xmlr.getLocalName().equals("graph"))
                processGraph(xmlr, ndf);

        } else if (event == XMLStreamConstants.END_ELEMENT) {
            if (xmlr.getLocalName().equals("graphml"))
                return;
        }
    }

    // If #nodes and #edges is not set, then go thru list to count them
}

From source file:com.conx.logistics.kernel.bpm.impl.jbpm.core.mock.BPMGuvnorUtil.java

private List<String> getPackageNamesFromGuvnor() {
    List<String> packages = new ArrayList<String>();
    String packagesURL = getGuvnorProtocol() + "://" + getGuvnorHost() + "/" + getGuvnorSubdomain()
            + "/rest/packages/";
    try {//w  w  w .jav a  2 s.co m
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader reader = factory.createXMLStreamReader(getInputStreamForURL(packagesURL, "GET"));
        while (reader.hasNext()) {
            if (reader.next() == XMLStreamReader.START_ELEMENT) {
                if ("title".equals(reader.getLocalName())) {
                    String pname = reader.getElementText();
                    if (!pname.equalsIgnoreCase("Packages")) {
                        packages.add(pname);
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.error("Error retriving packages from guvnor: " + e.getMessage());
    }
    return packages;
}

From source file:com.conx.logistics.kernel.bpm.impl.jbpm.core.mock.BPMGuvnorUtil.java

public List<String> getAllProcessesInPackage(String pkgName) {
    List<String> processes = new ArrayList<String>();
    String assetsURL = getGuvnorProtocol() + "://" + getGuvnorHost() + "/" + getGuvnorSubdomain()
            + "/rest/packages/" + pkgName + "/assets/";

    try {//from ww w .jav  a 2  s . c  o  m
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader reader = factory.createXMLStreamReader(getInputStreamForURL(assetsURL, "GET"));

        String format = "";
        String title = "";
        while (reader.hasNext()) {
            int next = reader.next();
            if (next == XMLStreamReader.START_ELEMENT) {
                if ("format".equals(reader.getLocalName())) {
                    format = reader.getElementText();
                }
                if ("title".equals(reader.getLocalName())) {
                    title = reader.getElementText();
                }
                if ("asset".equals(reader.getLocalName())) {
                    if (format.equals(EXT_BPMN) || format.equals(EXT_BPMN2)) {
                        processes.add(title);
                        title = "";
                        format = "";
                    }
                }
            }
        }
        // last one
        if (format.equals(EXT_BPMN) || format.equals(EXT_BPMN2)) {
            processes.add(title);
        }
    } catch (Exception e) {
        logger.error("Error finding processes in package: " + e.getMessage());
    }
    return processes;
}

From source file:de.uzk.hki.da.sb.SIPFactoryTest.java

/**
 * @param premis/*from   w ww  . j a  v  a2 s . c om*/
 * @param publicRights 
 */
private boolean checkPremisFilePubStartDate(File premis, ContractRights rights) {

    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLStreamReader streamReader;
    try {
        streamReader = inputFactory.createXMLStreamReader(new FileInputStream(premis));
        while (streamReader.hasNext()) {
            int event = streamReader.next();
            switch (event) {
            case XMLStreamConstants.START_ELEMENT:
                if (streamReader.getLocalName().equals("startDate")) {

                    String startDate = streamReader.getElementText().substring(0, 10);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String publicDate = sdf.format(rights.getPublicRights().getStartDate());
                    if (startDate.trim().equals(publicDate.trim())) {
                        return true;
                    }
                }
            default:
                break;
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (XMLStreamException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:com.conx.logistics.kernel.bpm.impl.jbpm.core.mock.BPMGuvnorUtil.java

public boolean templateExistsInRepo(String templateName) throws Exception {
    List<String> allPackages = getPackageNames();
    try {//  w w w. j  ava  2  s  . co  m
        for (String pkg : allPackages) {
            String templateURL = getGuvnorProtocol() + "://" + getGuvnorHost() + "/" + getGuvnorSubdomain()
                    + "/rest/packages/" + pkg + "/assets/" + URLEncoder.encode(templateName, "UTF-8");

            URL checkURL = new URL(templateURL);
            HttpURLConnection checkConnection = (HttpURLConnection) checkURL.openConnection();
            checkConnection.setRequestMethod("GET");
            checkConnection.setRequestProperty("Accept", "application/atom+xml");
            checkConnection.setConnectTimeout(Integer.parseInt(getGuvnorConnectTimeout()));
            checkConnection.setReadTimeout(Integer.parseInt(getGuvnorReadTimeout()));
            applyAuth(checkConnection);
            checkConnection.connect();
            if (checkConnection.getResponseCode() == 200) {

                XMLInputFactory factory = XMLInputFactory.newInstance();
                XMLStreamReader reader = factory.createXMLStreamReader(checkConnection.getInputStream());

                boolean foundFormFormat = false;
                while (reader.hasNext()) {
                    if (reader.next() == XMLStreamReader.START_ELEMENT) {
                        if ("format".equals(reader.getLocalName())) {
                            reader.next();
                            String pname = reader.getElementText();
                            if ("flt".equalsIgnoreCase(pname)) {
                                foundFormFormat = true;
                                break;
                            }
                        }
                    }
                }
                return foundFormFormat;
            }
        }
    } catch (Exception e) {
        logger.error("Exception checking template url : " + e.getMessage());
        return false;
    }
    logger.info("Could not find process template for: " + templateName);
    return false;
}

From source file:demo.SourceHttpMessageConverter.java

private Source readStAXSource(InputStream body) {
    try {//from w  w w.j a  va 2 s.  c  o  m
        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, isSupportDtd());
        inputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, isProcessExternalEntities());
        if (!isProcessExternalEntities()) {
            inputFactory.setXMLResolver(NO_OP_XML_RESOLVER);
        }
        XMLStreamReader streamReader = inputFactory.createXMLStreamReader(body);
        return new StAXSource(streamReader);
    } catch (XMLStreamException ex) {
        throw new HttpMessageNotReadableException("Could not parse document: " + ex.getMessage(), ex);
    }
}

From source file:com.prowidesoftware.swift.io.parser.MxParser.java

/**
 * Takes an xml with an MX message and detects the specific message type
 * parsing just the namespace from the Document element. If the Document
 * element is not present, or without the namespace or if the namespace url
 * contains invalid content it will return null.
 * <br><br>//from  ww w . j  a va 2 s . com
 * Example of a recognizable Document element:<br>
 * <Doc:Document xmlns:Doc="urn:swift:xsd:camt.003.001.04" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 * <br>
 * The implementation is intended to be lightweight and efficient, based on {@link javax.xml.stream.XMLStreamReader} 
 *
 * @return id with the detected MX message type or null if it cannot be determined.
 * @since 7.7
 */
public MxId detectMessage() {
    if (StringUtils.isBlank(this.buffer)) {
        log.log(Level.SEVERE, "cannot detect message from null or empty content");
        return null;
    }
    final javax.xml.stream.XMLInputFactory xif = javax.xml.stream.XMLInputFactory.newInstance();
    try {
        final javax.xml.stream.XMLStreamReader reader = xif
                .createXMLStreamReader(new StringReader(this.buffer));
        while (reader.hasNext()) {
            int event = reader.next();
            if (javax.xml.stream.XMLStreamConstants.START_ELEMENT == event
                    && reader.getLocalName().equals(DOCUMENT_LOCALNAME)) {
                if (reader.getNamespaceCount() > 0) {
                    //log.finest("ELEMENT START: " + reader.getLocalName() + " , namespace count is: " + reader.getNamespaceCount());
                    for (int nsIndex = 0; nsIndex < reader.getNamespaceCount(); nsIndex++) {
                        final String nsPrefix = StringUtils.trimToNull(reader.getNamespacePrefix(nsIndex));
                        final String elementPrefix = StringUtils.trimToNull(reader.getPrefix());
                        if (StringUtils.equals(nsPrefix, elementPrefix)) {
                            String nsId = reader.getNamespaceURI(nsIndex);
                            //log.finest("\tNamepsace prefix: " + nsPrefix + " associated with URI " + nsId);
                            return new MxId(nsId);
                        }
                    }
                }
            }
        }
    } catch (final Exception e) {
        log.log(Level.SEVERE, "error while detecting message", e);
    }
    return null;
}

From source file:net.cloudkit.toolkit.DownloadTest.java

@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@Transactional/* w  ww  . j av a  2s  .  co m*/
@Test
public void test() throws Exception {

    Map<String, Object> cdl = new HashMap<>();
    Map<String, String> cdlBillHead = null;
    Map<String, String> cdlBillList = null;
    List<Map<String, String>> cdlBillLists = new ArrayList<>();
    Map<String, String> cdlBillDoc = null;
    List<Map<String, String>> cdlBillDocs = new ArrayList<>();

    // MESSAGE_CONFIG
    // InputStream
    InputStream in = null;
    try {

        // StAX?
        XMLInputFactory xif = XMLInputFactory.newInstance();
        // ?
        XMLStreamReader reader = xif
                .createXMLStreamReader(new FileInputStream(new File("D:\\temp\\bill\\CDL100000006531646.xml")));

        // 
        while (reader.hasNext()) {
            // ?
            int event = reader.next();

            // 
            // if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) {
            if (event == XMLStreamReader.START_ELEMENT) {
                // CdlBill/CdlBillHead
                if ("CdlBillHead".equals(reader.getLocalName())) {
                    cdlBillHead = new LinkedHashMap<>();
                }
                {
                    // BillSeq
                    if ("BillSeq".equals(reader.getLocalName())) {
                        cdlBillHead.put("BillSeq", reader.getElementText());
                    }
                    // ListNo
                    if ("ListNo".equals(reader.getLocalName())) {
                        cdlBillHead.put("ListNo", reader.getElementText());
                    }
                    // IEFlag
                    if ("IEFlag".equals(reader.getLocalName())) {
                        cdlBillHead.put("IEFlag", reader.getElementText());
                    }
                    // IEPort
                    if ("IEPort".equals(reader.getLocalName())) {
                        cdlBillHead.put("IEPort", reader.getElementText());
                    }
                    // IEDate
                    if ("IEDate".equals(reader.getLocalName())) {
                        cdlBillHead.put("IEDate", reader.getElementText());
                    }
                    // RecordsNo
                    if ("RecordsNo".equals(reader.getLocalName())) {
                        cdlBillHead.put("RecordsNo", reader.getElementText());
                    }
                    // TradeCode
                    if ("TradeCode".equals(reader.getLocalName())) {
                        cdlBillHead.put("TradeCode", reader.getElementText());
                    }
                    // TradeName
                    if ("TradeName".equals(reader.getLocalName())) {
                        cdlBillHead.put("TradeName", reader.getElementText());
                    }
                    // OwnerCode
                    if ("OwnerCode".equals(reader.getLocalName())) {
                        cdlBillHead.put("OwnerCode", reader.getElementText());
                    }
                    // OwnerName
                    if ("OwnerName".equals(reader.getLocalName())) {
                        cdlBillHead.put("OwnerName", reader.getElementText());
                    }
                    // TrafMode
                    if ("TrafMode".equals(reader.getLocalName())) {
                        cdlBillHead.put("TrafMode", reader.getElementText());
                    }
                    // ShipName
                    if ("ShipName".equals(reader.getLocalName())) {
                        cdlBillHead.put("ShipName", reader.getElementText());
                    }
                    // VoyageNo
                    if ("VoyageNo".equals(reader.getLocalName())) {
                        cdlBillHead.put("VoyageNo", reader.getElementText());
                    }
                    // BillNo
                    if ("BillNo".equals(reader.getLocalName())) {
                        cdlBillHead.put("BillNo", reader.getElementText());
                    }
                    // TradeMode
                    if ("TradeMode".equals(reader.getLocalName())) {
                        cdlBillHead.put("TradeMode", reader.getElementText());
                    }
                    // TradeCountry
                    if ("TradeCountry".equals(reader.getLocalName())) {
                        cdlBillHead.put("TradeCountry", reader.getElementText());
                    }
                    // DestinationPort
                    if ("DestinationPort".equals(reader.getLocalName())) {
                        cdlBillHead.put("DestinationPort", reader.getElementText());
                    }
                    // DistrictCode
                    if ("DistrictCode".equals(reader.getLocalName())) {
                        cdlBillHead.put("DistrictCode", reader.getElementText());
                    }
                    // PackNum
                    if ("PackNum".equals(reader.getLocalName())) {
                        cdlBillHead.put("PackNum", reader.getElementText());
                    }
                    // WrapType
                    if ("WrapType".equals(reader.getLocalName())) {
                        cdlBillHead.put("WrapType", reader.getElementText());
                    }
                    // GrossWt
                    if ("GrossWt".equals(reader.getLocalName())) {
                        cdlBillHead.put("GrossWt", reader.getElementText());
                    }
                    // NetWt
                    if ("NetWt".equals(reader.getLocalName())) {
                        cdlBillHead.put("NetWt", reader.getElementText());
                    }
                    // ListType
                    if ("ListType".equals(reader.getLocalName())) {
                        cdlBillHead.put("ListType", reader.getElementText());
                    }
                    // ListStat
                    if ("ListStat".equals(reader.getLocalName())) {
                        cdlBillHead.put("ListStat", reader.getElementText());
                    }
                    // DocuCodeCom
                    if ("DocuCodeCom".equals(reader.getLocalName())) {
                        cdlBillHead.put("DocuCodeCom", reader.getElementText());
                    }
                    // AgentCode
                    if ("AgentCode".equals(reader.getLocalName())) {
                        cdlBillHead.put("AgentCode", reader.getElementText());
                    }
                    // AgentName
                    if ("AgentName".equals(reader.getLocalName())) {
                        cdlBillHead.put("AgentName", reader.getElementText());
                    }
                    // DeclCustom
                    if ("DeclCustom".equals(reader.getLocalName())) {
                        cdlBillHead.put("DeclCustom", reader.getElementText());
                    }
                    // DeclDate
                    if ("DeclDate".equals(reader.getLocalName())) {
                        cdlBillHead.put("DeclDate", reader.getElementText());
                    }
                    // GType
                    if ("GType".equals(reader.getLocalName())) {
                        cdlBillHead.put("GType", reader.getElementText());
                    }

                }

                // CdlBill/CdlBillLists/CdlBillList
                if ("CdlBillList".equals(reader.getLocalName())) {
                    cdlBillList = new LinkedHashMap<>();
                }
                {
                    // GNo
                    if ("GNo".equals(reader.getLocalName())) {
                        cdlBillList.put("GNo", reader.getElementText());
                    }
                    // ItemNo
                    if ("ItemNo".equals(reader.getLocalName())) {
                        cdlBillList.put("ItemNo", reader.getElementText());
                    }
                    // CodeTs
                    if ("CodeTs".equals(reader.getLocalName())) {
                        cdlBillList.put("CodeTs", reader.getElementText());
                    }
                    // GName
                    if ("GName".equals(reader.getLocalName())) {
                        cdlBillList.put("GName", reader.getElementText());
                    }
                    // GModel
                    if ("GModel".equals(reader.getLocalName())) {
                        cdlBillList.put("GModel", reader.getElementText());
                    }
                    // GQty
                    if ("GQty".equals(reader.getLocalName())) {
                        cdlBillList.put("GQty", reader.getElementText());
                    }
                    // GUnit
                    if ("GUnit".equals(reader.getLocalName())) {
                        cdlBillList.put("GUnit", reader.getElementText());
                    }
                    // DeclPrice
                    if ("DeclPrice".equals(reader.getLocalName())) {
                        cdlBillList.put("DeclPrice", reader.getElementText());
                    }
                    // DeclTotal
                    if ("DeclTotal".equals(reader.getLocalName())) {
                        cdlBillList.put("DeclTotal", reader.getElementText());
                    }
                    // TradeCurr
                    if ("TradeCurr".equals(reader.getLocalName())) {
                        cdlBillList.put("TradeCurr", reader.getElementText());
                    }
                    // OriginalalCountry
                    if ("OriginalalCountry".equals(reader.getLocalName())) {
                        cdlBillList.put("OriginalalCountry", reader.getElementText());
                    }
                    // DutyMode
                    if ("DutyMode".equals(reader.getLocalName())) {
                        cdlBillList.put("DutyMode", reader.getElementText());
                    }
                    // Unit1
                    if ("Unit1".equals(reader.getLocalName())) {
                        cdlBillList.put("Unit1", reader.getElementText());
                    }
                    // Unit2
                    if ("Unit2".equals(reader.getLocalName())) {
                        cdlBillList.put("Unit2", reader.getElementText());
                    }
                }

                // CdlBill/CdlBillDocs/CdlBillDoc
                if ("CdlBillDoc".equals(reader.getLocalName())) {
                    cdlBillDoc = new LinkedHashMap<>();
                }
                {
                    // DocCode
                    if ("DocCode".equals(reader.getLocalName())) {
                        cdlBillDoc.put("DocCode", reader.getElementText());
                    }
                    // CertNo
                    if ("CertNo".equals(reader.getLocalName())) {
                        cdlBillDoc.put("CertNo", reader.getElementText());
                    }
                }
            }

            if (event == XMLStreamReader.END_ELEMENT) {
                // CdlBill/CdlBillHead
                if ("CdlBillHead".equals(reader.getLocalName())) {

                }

                // CdlBill/CdlBillLists/CdlBillList
                if ("CdlBillList".equals(reader.getLocalName())) {
                    cdlBillLists.add(cdlBillList);
                }

                // CdlBill/CdlBillDocs/CdlBillDoc
                if ("CdlBillDoc".equals(reader.getLocalName())) {
                    cdlBillDocs.add(cdlBillDoc);
                }
            }
        }
    } catch (XMLStreamException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    cdl.put("CdlBillHead", cdlBillHead);
    cdl.put("CdlBillLists", cdlBillLists);
    cdl.put("CdlBillDocs", cdlBillDocs);
    System.out.println(cdlBillLists.size() + " " + cdlBillDocs.size());
    persistentRepositoryService.save(cdl);

}

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

/**
 * /*from w w  w  .  j a  v  a 2  s  . c  om*/
 * @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:com.prowidesoftware.swift.io.parser.MxParser.java

/**
 * Convenient API to get structure information from an MX message.
 * <br ><br>/*  www.j  a v a2 s. c o m*/
 * This can be helpful when the actual content of an XML is unknown and 
 * some preprocessing of the XML must be done in order to parse or
 * validate its content properly.
 * <br >
 * The implementation is intended to be lightweight and efficient, based on {@link javax.xml.stream.XMLStreamReader}
 *  
 * @since 7.8.4
 */
public MxStructureInfo analizeMessage() {
    if (this.info != null) {
        return this.info;
    }
    this.info = new MxStructureInfo();
    if (StringUtils.isBlank(this.buffer)) {
        log.log(Level.WARNING, "cannot analize message from null or empty content");
        return this.info;
    }
    final javax.xml.stream.XMLInputFactory xif = javax.xml.stream.XMLInputFactory.newInstance();
    try {
        final javax.xml.stream.XMLStreamReader reader = xif
                .createXMLStreamReader(new StringReader(this.buffer));
        boolean first = true;
        while (reader.hasNext()) {
            int event = reader.next();
            if (javax.xml.stream.XMLStreamConstants.START_ELEMENT == event) {
                if (reader.getLocalName().equals(DOCUMENT_LOCALNAME)) {
                    this.info.containsDocument = true;
                    this.info.documentNamespace = readNamespace(reader);
                    this.info.documentPrefix = StringUtils.trimToNull(reader.getPrefix());
                } else if (reader.getLocalName().equals(HEADER_LOCALNAME)) {
                    this.info.containsHeader = true;
                    this.info.headerNamespace = readNamespace(reader);
                    this.info.headerPrefix = StringUtils.trimToNull(reader.getPrefix());
                } else if (first) {
                    this.info.containsWrapper = true;
                }
                first = false;
            }
        }
    } catch (final Exception e) {
        log.log(Level.SEVERE, "error while analizing message: " + e.getMessage());
        info.exception = e;
    }
    return this.info;
}