Example usage for javax.xml.stream XMLEventReader hasNext

List of usage examples for javax.xml.stream XMLEventReader hasNext

Introduction

In this page you can find the example usage for javax.xml.stream XMLEventReader hasNext.

Prototype

@Override
public boolean hasNext();

Source Link

Document

Check if there are more events.

Usage

From source file:com.streamsets.pipeline.lib.salesforce.BulkRecordCreator.java

private Field pullMap(XMLEventReader reader) throws StageException, XMLStreamException {
    LinkedHashMap<String, Field> map = new LinkedHashMap<>();
    String type = null;//from w w w. j  ava  2 s.  co  m

    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();
        if (event.isStartElement()) {
            if (event.asStartElement().getName().getLocalPart().equals(TYPE)) {
                // Move to content
                event = reader.nextEvent();
                type = event.asCharacters().getData().toLowerCase();
                // Consume closing tag
                reader.nextEvent();
            } else {
                String fieldName = event.asStartElement().getName().getLocalPart();
                Attribute attr = event.asStartElement().getAttributeByName(XSI_TYPE);
                if (attr != null && attr.getValue().equals(S_OBJECT)) {
                    // Element is a nested record
                    map.put(fieldName, pullMap(reader));
                } else {
                    event = reader.nextEvent();
                    if (event.isCharacters()) {
                        // Element is a field value
                        String fieldValue = event.asCharacters().getData();
                        if (type == null) {
                            throw new StageException(Errors.FORCE_38);
                        }
                        com.sforce.soap.partner.Field sfdcField = getFieldMetadata(type, fieldName);

                        Field field = createField(fieldValue, sfdcField);
                        if (conf.createSalesforceNsHeaders) {
                            setHeadersOnField(field, getFieldMetadata(type, fieldName));
                        }

                        map.put(fieldName, field);

                        // Consume closing tag
                        reader.nextEvent();
                    } else if (event.isStartElement()) {
                        // Element is a nested list of records
                        // Advance over <done>, <queryLocator> to record list
                        while (!(event.isStartElement()
                                && event.asStartElement().getName().getLocalPart().equals(RECORDS))) {
                            event = reader.nextEvent();
                        }

                        // Read record list
                        List<Field> recordList = new ArrayList<>();
                        while (event.isStartElement()
                                && event.asStartElement().getName().getLocalPart().equals(RECORDS)) {
                            recordList.add(pullMap(reader));
                            event = reader.nextEvent();
                        }
                        map.put(fieldName, Field.create(recordList));
                    }
                }
            }
        } else if (event.isEndElement()) {
            // Done with record
            return Field.createListMap(map);
        }
    }

    throw new StageException(Errors.FORCE_39);
}

From source file:com.predic8.membrane.core.interceptor.rest.REST2SOAPInterceptor.java

private String getRootElementNamespace(InputStream stream) {
    try {/*from   ww w.j a  va 2 s .co m*/
        XMLEventReader xer = XMLInputFactory.newFactory().createXMLEventReader(stream);
        while (xer.hasNext()) {
            XMLEvent event = xer.nextEvent();
            if (event.isStartElement())
                return event.asStartElement().getName().getNamespaceURI();
        }
    } catch (XMLStreamException e) {
        log.error("Could not determine root element namespace for check whether namespace is SOAP 1.2.", e);
    }
    return null;
}

From source file:com.predic8.membrane.core.interceptor.schemavalidation.SchematronValidator.java

@Override
public Outcome validateMessage(Exchange exc, Message msg, String source) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {// ww  w .  ja  v  a  2s  . c  o  m
        Transformer transformer = transformers.take();
        try {
            transformer.transform(new StreamSource(xopr.reconstituteIfNecessary(msg)), new StreamResult(baos));
        } finally {
            transformers.put(transformer);
        }

        byte[] result = baos.toByteArray();

        // check for errors
        XMLEventReader parser;
        synchronized (xmlInputFactory) {
            parser = xmlInputFactory.createXMLEventReader(new ByteArrayInputStream(result));
        }
        while (parser.hasNext()) {
            XMLEvent event = parser.nextEvent();
            if (event.isStartElement()) {
                StartElement startElement = (StartElement) event;
                if (startElement.getName().getLocalPart().equals("failed-assert")) {
                    setErrorMessage(exc, new String(result, UTF_8_CHARSET), false, source);
                    invalid.incrementAndGet();
                    return Outcome.ABORT;
                }
            }
        }

    } catch (TransformerException e) {
        setErrorMessage(exc, e.getMessage(), true, source);
        invalid.incrementAndGet();
        return Outcome.ABORT;
    } catch (Exception e) {
        log.error("", e);
        setErrorMessage(exc, "internal error", true, source);
        invalid.incrementAndGet();
        return Outcome.ABORT;
    }
    valid.incrementAndGet();
    return Outcome.CONTINUE;
}

From source file:com.streamsets.pipeline.lib.xml.StreamingXmlParser.java

void skipIgnorable(XMLEventReader reader) throws XMLStreamException {
    while (reader.hasNext() && isIgnorable(reader.peek())) {
        reader.nextEvent();/*www.j  a v a  2 s.  c om*/
    }
}

From source file:org.eclipse.swordfish.core.configuration.xml.XmlToPropertiesTransformerImpl.java

public void loadConfiguration(URL path) {
    Assert.notNull(path);/*w w  w. j  a  v a2s .  co m*/
    InputStream inputStream = null;
    try {
        inputStream = path.openStream();
        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        LinkedList<String> currentElements = new LinkedList<String>();
        XMLEventReader eventReader = inputFactory.createXMLEventReader(inputStream);
        Map<String, List<String>> props = new HashMap<String, List<String>>();
        // Read the XML document
        while (eventReader.hasNext()) {
            XMLEvent event = eventReader.nextEvent();
            if (event.isCharacters() && !event.asCharacters().isWhiteSpace()) {
                putElement(props, getQualifiedName(currentElements), event.asCharacters().getData());

            } else if (event.isStartElement()) {
                currentElements.add(event.asStartElement().getName().getLocalPart());
                for (Iterator attrIt = event.asStartElement().getAttributes(); attrIt.hasNext();) {
                    Attribute attribute = (Attribute) attrIt.next();
                    putElement(props, getQualifiedName(currentElements) + "[@" + attribute.getName() + "]",
                            attribute.getValue());

                }
            } else if (event.isAttribute()) {
            } else if (event.isEndElement()) {
                String lastElem = event.asEndElement().getName().getLocalPart();
                if (!currentElements.getLast().equals(lastElem)) {
                    throw new UnsupportedOperationException(lastElem + "," + currentElements.getLast());
                }
                currentElements.removeLast();
            }
        }
        properties = flattenProperties(props);
    } catch (Exception ex) {
        throw new SwordfishException(ex);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ex) {
            }
        }
    }
}

From source file:com.streamsets.pipeline.lib.xml.StreamingXmlParser.java

boolean hasNext(XMLEventReader reader) throws XMLStreamException {
    skipIgnorable(reader);
    return reader.hasNext();
}

From source file:fr.dutra.confluence2wordpress.core.sync.DefaultAttachmentsSynchronizer.java

private Set<Attachment> parseForAttachments(ContentEntityObject page) throws SynchronizationException {
    Set<Attachment> attachments = new HashSet<Attachment>();
    try {// w  w  w  . ja v a  2 s.co  m
        XMLEventReader r = StaxUtils.getReader(page);
        String fileName = null;
        String pageTitle = null;
        String spaceKey = null;
        try {
            while (r.hasNext()) {
                XMLEvent e = r.nextEvent();
                if (e.isStartElement()) {
                    StartElement startElement = e.asStartElement();
                    QName name = startElement.getName();
                    if (name.equals(ATTACHMENT_QNAME)) {
                        Attribute att = startElement.getAttributeByName(FILENAME_QNAME);
                        if (att != null) {
                            fileName = att.getValue();
                        }
                    } else if (name.equals(PAGE_QNAME)) {
                        Attribute title = startElement.getAttributeByName(TITLE_QNAME);
                        if (title != null) {
                            pageTitle = title.getValue();
                        }
                        Attribute space = startElement.getAttributeByName(SPACE_QNAME);
                        if (space != null) {
                            spaceKey = space.getValue();
                        }
                    }
                } else if (e.isEndElement()) {
                    EndElement endElement = e.asEndElement();
                    if (endElement.getName().equals(ATTACHMENT_QNAME)) {
                        ContentEntityObject attachmentPage;
                        if (pageTitle == null) {
                            attachmentPage = page;
                        } else {
                            attachmentPage = pageManager.getPage(spaceKey, pageTitle);
                        }
                        Attachment attachment = attachmentManager.getAttachment(attachmentPage, fileName);
                        attachments.add(attachment);
                        fileName = null;
                        pageTitle = null;
                        spaceKey = null;
                    }
                }
            }
        } finally {
            r.close();
        }
    } catch (XMLStreamException e) {
        throw new SynchronizationException("Cannot read page: " + page.getTitle(), e);
    }
    return attachments;
}

From source file:org.callimachusproject.rdfa.test.RDFaGenerationTest.java

void testPI(XMLEventReader xml) throws Exception {
    while (xml.hasNext()) {
        XMLEvent e = xml.nextEvent();
        if (e.isProcessingInstruction()) {
            if (e.toString().contains("repository clear") || e.toString().contains("clear repository")) {
                source.clear();/*from   w  w w . j ava  2 s  .  c  o  m*/
            }
        }
    }
}

From source file:org.lieuofs.geo.territoire.biz.dao.EtatTerritoireFichierXmlDao.java

/**************************************************/

@PostConstruct//www.j av  a  2s  .c  o m
public void chargerResource()
        throws IOException, XMLStreamException, FactoryConfigurationError, ParseException {
    XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(fichier.getInputStream(),
            this.charsetName);
    EtatTerritoirePersistant etatTerritoire = null;
    while (reader.hasNext()) {
        XMLEvent event = (XMLEvent) reader.next();
        if (event.isStartElement()) {
            StartElement element = (StartElement) event;
            String nomElem = element.getName().toString();
            if ("country".equals(nomElem)) {
                etatTerritoire = new EtatTerritoirePersistant();
            } else if ("id".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setNumeroOFS(Integer.parseInt(characters.getData()));
            } else if ("unId".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                if (null == etatTerritoire.getInfosISO())
                    etatTerritoire.setInfosISO(new InfosONUetISO3166());
                etatTerritoire.getInfosISO().setCodeNumeriqueONU(Integer.parseInt(characters.getData()));
            } else if ("iso2Id".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                if (null == etatTerritoire.getInfosISO())
                    etatTerritoire.setInfosISO(new InfosONUetISO3166());
                etatTerritoire.getInfosISO().setCodeIsoAlpha2(characters.getData());
            } else if ("iso3Id".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                if (null == etatTerritoire.getInfosISO())
                    etatTerritoire.setInfosISO(new InfosONUetISO3166());
                etatTerritoire.getInfosISO().setCodeIsoAlpha3(characters.getData());
            } else if ("shortNameDe".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterFormeCourte("de", characters.getData());
            } else if ("shortNameFr".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterFormeCourte("fr", characters.getData());
            } else if ("shortNameIt".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterFormeCourte("it", characters.getData());
            } else if ("shortNameEn".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterFormeCourte("en", characters.getData());
            } else if ("officialNameDe".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterDesignationOfficielle("de", characters.getData());
            } else if ("officialNameFr".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterDesignationOfficielle("fr", characters.getData());
            } else if ("officialNameIt".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterDesignationOfficielle("it", characters.getData());
            } else if ("continent".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setNumContinent(Integer.parseInt(characters.getData()));
            } else if ("region".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setNumRegion(Integer.parseInt(characters.getData()));
            } else if ("state".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setEtat(Boolean.valueOf(characters.getData()));
            } else if ("areaState".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setNumEtatRattachement(Integer.parseInt(characters.getData()));
            } else if ("unMember".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setMembreONU(Boolean.valueOf(characters.getData()));
            } else if ("unEntryDate".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setDateEntreeONU(dateFmt.parse(characters.getData()));
            } else if ("recognizedCh".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setReconnuSuisse(Boolean.valueOf(characters.getData()));
            } else if ("recognizedDate".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setDateReconnaissance(dateFmt.parse(characters.getData()));
            } else if ("remarkDe".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterRemarque("de", characters.getData());
            } else if ("remarkFr".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterRemarque("fr", characters.getData());
            } else if ("remarkIt".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterRemarque("it", characters.getData());
            } else if ("entryValid".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setValide(Boolean.valueOf(characters.getData()));
            } else if ("dateOfChange".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setDateDernierChangement(dateFmt.parse(characters.getData()));
            }
        } else if (event.isEndElement()) {
            EndElement element = (EndElement) event;
            if ("country".equals(element.getName().toString())) {
                stockerEtatTerritoire(etatTerritoire);
            }
        }
    }
}

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

public static Map.Entry<Integer, XmlElement> getAtomElement(final XMLEventReader reader,
        final XMLEventWriter discarded, final String name,
        final Collection<Map.Entry<String, String>> filterAttrs, final int initialDepth, final int minDepth,
        final int maxDepth, final boolean filterInOr) throws Exception {

    int depth = initialDepth;
    StartElement start = null;//from  w w w.j  av a 2s.c  o m

    while (reader.hasNext() && start == null) {
        final XMLEvent event = reader.nextEvent();

        if (event.getEventType() == XMLStreamConstants.START_ELEMENT) {
            depth++;

            if ((StringUtils.isBlank(name)
                    || name.trim().equals(event.asStartElement().getName().getLocalPart()))
                    && (minDepth < 0 || minDepth <= depth) && (maxDepth < 0 || maxDepth >= depth)) {

                boolean match = filterAttrs == null || filterAttrs.isEmpty() || !filterInOr;

                for (Map.Entry<String, String> filterAttr : filterAttrs == null
                        ? Collections.<Map.Entry<String, String>>emptySet()
                        : filterAttrs) {
                    final Attribute attr = event.asStartElement()
                            .getAttributeByName(new QName(filterAttr.getKey().trim()));

                    if (attr == null || !filterAttr.getValue().trim().equals(attr.getValue())) {
                        match = filterInOr ? match : false;
                    } else {
                        match = filterInOr ? true : match;
                    }
                }

                if (match) {
                    start = event.asStartElement();
                }
            }

        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT) {
            depth--;
        }

        if (start == null) {
            if (discarded != null) {
                discarded.add(event);
            }
        }
    }

    if (start == null) {
        throw new Exception(String.format("Could not find an element named '%s'", name));
    }

    return new SimpleEntry<Integer, XmlElement>(Integer.valueOf(depth - 1), getAtomElement(start, reader));
}