Example usage for javax.xml.stream XMLStreamReader next

List of usage examples for javax.xml.stream XMLStreamReader next

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamReader next.

Prototype

public int next() throws XMLStreamException;

Source Link

Document

Get next parsing event - a processor may return all contiguous character data in a single chunk, or it may split it into several chunks.

Usage

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

/**
 * @param premis/*from   w  ww  .j a v  a 2 s.com*/
 * @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:dk.statsbiblioteket.util.xml.XMLStepperTest.java

public void testIterateTags() throws Exception {
    XMLStreamReader xml = xmlFactory.createXMLStreamReader(new StringReader(SAMPLE));
    assertTrue("The first 'bar' should be findable", XMLStepper.findTagStart(xml, "bar"));
    xml.next();

    final AtomicInteger count = new AtomicInteger(0);
    XMLStepper.iterateTags(xml, new XMLStepper.Callback() {
        @Override//w  w  w. ja v  a 2s . c  o  m
        public boolean elementStart(XMLStreamReader xml, List<String> tags, String current)
                throws XMLStreamException {
            count.incrementAndGet();
            return false;
        }
    });
    assertEquals("Only a single content should be visited", 1, count.get());
    assertTrue("The second 'bar' should be findable", XMLStepper.findTagStart(xml, "bar"));
}

From source file:com.microsoft.tfs.core.ws.runtime.types.StaxAnyContentType.java

@Override
public void readFromElement(final XMLStreamReader reader) throws XMLStreamException {
    FastTempOutputStream ftos = null;//from ww w .ja v  a 2 s .  c  o  m
    XMLStreamWriter writer = null;

    /*
     * When this method is called, the writer is positioned at the element
     * that contains the "any" content. Process the child elements until the
     * container is done.
     */

    /*
     * Advance one event to get the first child.
     */
    int event = reader.next();

    do {
        if (event == XMLStreamConstants.START_ELEMENT) {
            /*
             * Parse the child element into its own temp file. The copier
             * will read the child's end element.
             */
            try {
                /*
                 * Get a new fast temp output stream.
                 */
                ftos = new FastTempOutputStream(heapStorageLimitBytes, initialHeapStorageSizeBytes);

                tempOutputStreams.add(ftos);

                /*
                 * Create a writer.
                 */
                writer = StaxFactoryProvider.getXMLOutputFactory().createXMLStreamWriter(ftos,
                        SOAPRequestEntity.SOAP_ENCODING);
                writer.writeStartDocument();

                StaxUtils.copyCurrentElement(reader, writer);

                /*
                 * Make sure to finish off the document.
                 */
                writer.writeEndDocument();
            } finally {
                if (writer != null) {
                    writer.close();
                }

                /*
                 * Closing writers does not close the underlying stream, so
                 * close that manually. This is required so the temp stream
                 * can be read from.
                 */
                if (ftos != null) {
                    try {
                        ftos.close();
                    } catch (final IOException e) {
                        log.error(e);
                    }
                }

            }
        }
    } while ((event = reader.next()) != XMLStreamConstants.END_ELEMENT);
}

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

/**
 * Convenient API to get structure information from an MX message.
 * <br ><br>//from  ww w.j  av  a 2  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;
}

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 {//from w  ww  .j  a  v a 2  s.c om
        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: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 {// w  w  w . ja va  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:com.hp.alm.ali.rest.client.AliRestClient.java

private List<String> getAttributeValues(InputStream xml, String elemName, String attrName) {
    try {//from w ww . j  a v  a 2s  .c  om
        XMLInputFactory factory = XmlUtils.createBasicInputFactory();
        XMLStreamReader parser;
        parser = factory.createXMLStreamReader(xml);
        List<String> result = new LinkedList<String>();
        while (true) {
            int event = parser.next();
            if (event == XMLStreamConstants.END_DOCUMENT) {
                parser.close();
                break;
            }
            if (event == XMLStreamConstants.START_ELEMENT && elemName.equals(parser.getLocalName())) {

                for (int i = 0; i < parser.getAttributeCount(); i++) {
                    String localName = parser.getAttributeLocalName(i);
                    if (attrName.equals(localName)) {
                        result.add(parser.getAttributeValue(i));
                        break;
                    }
                }
            }
        }
        return result;
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            xml.close();
        } catch (IOException e) {
            // ignore
        }
    }
}

From source file:iTests.framework.utils.WebuiTestUtils.java

/**
 * retrieves the license key from gigaspaces installation license key
 * @throws javax.xml.stream.FactoryConfigurationError
 * @throws javax.xml.stream.XMLStreamException
 * @throws java.io.IOException// w w w  .  j av  a  2  s.c  o m
 */
public String getLicenseKey() throws XMLStreamException, FactoryConfigurationError, IOException {

    String licensekey = LICENSE_PATH.replace("lib/required/../../", "");
    InputStream is = new FileInputStream(new File(licensekey));
    XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(is);
    int element;
    while (true) {
        element = parser.next();
        if (element == XMLStreamReader.START_ELEMENT) {
            if (parser.getName().toString().equals("licensekey")) {
                return parser.getElementText();
            }
        }
        if (element == XMLStreamReader.END_DOCUMENT) {
            break;
        }
    }
    return null;

}

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

@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@Transactional/*from  ww  w.j a  v a  2s.  c  o 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:ca.efendi.datafeeds.messaging.FtpSubscriptionMessageListener.java

private void parse(FtpSubscription ftpSubscription, final InputStream is) throws XMLStreamException {
    final XMLInputFactory factory = XMLInputFactory.newInstance();
    factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, true);
    factory.setProperty(XMLInputFactory.IS_COALESCING, true);
    final XMLStreamReader reader = factory.createXMLStreamReader(is, "UTF-8");
    CJProduct product = null;/* ww w .  j a  v a 2 s . c  om*/
    String tagContent = null;
    //final ServiceContext serviceContext = new ServiceContext();

    //ServiceContext serviceContext = ServiceContextFactory.getInstance(
    //        BlogsEntry.class.getName(), actionRequest);

    //serviceContext.setScopeGroupId(20159);
    while (reader.hasNext()) {
        final int event = reader.next();
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            //tagContent = "";
            if ("product".equals(reader.getLocalName())) {
                product = _cjProductLocalService.createCJProduct(0);
            }
            break;
        case XMLStreamConstants.CHARACTERS:
            //tagContent += reader.getText().trim();
            tagContent = reader.getText().trim();
            break;
        case XMLStreamConstants.END_ELEMENT:
            switch (reader.getLocalName()) {
            case "product":
                try {

                    _log.warn("refreshing document...");
                    _cjProductLocalService.refresh(ftpSubscription, product);
                } catch (final SystemException e) {
                    _log.error(e);
                } catch (final PortalException e) {
                    _log.error(e);
                }
                break;
            case "programname":
                product.setProgramName(tagContent);
                break;
            case "programurl":
                product.setProgramUrl(tagContent);
                break;
            case "catalogname":
                product.setCatalogName(tagContent);
                break;
            case "lastupdated":
                product.setLastUpdated(tagContent);
                break;
            case "name":
                product.setName(tagContent);
                break;
            case "keywords":
                product.setKeywords(tagContent);
                break;
            case "description":
                product.setDescription(tagContent);
                break;
            case "sku":
                product.setSku(tagContent);
                break;
            case "manufacturer":
                product.setManufacturer(tagContent);
                break;
            case "manufacturerid":
                product.setManufacturerId(tagContent);
                break;
            case "currency":
                product.setCurrency(tagContent);
                break;
            case "price":
                product.setPrice(tagContent);
                break;
            case "buyurl":
                product.setBuyUrl(tagContent);
                break;
            case "impressionurl":
                product.setImpressionUrl(tagContent);
                break;
            case "imageurl":
                product.setImageUrl(tagContent);
                break;
            case "instock":
                product.setInStock(tagContent);
                break;
            }
            break;
        case XMLStreamConstants.START_DOCUMENT:
            break;
        }
    }
}