Search in sources :

Example 16 with Characters

use of javax.xml.stream.events.Characters in project sirix by sirixdb.

the class XMLUpdateShredder method updateOnly.

/**
 * Update a shreddered file.
 *
 * @throws SirixException if sirix encounters something went wrong
 */
private void updateOnly() throws SirixException {
    try {
        // Initialize variables.
        mLevelInToShredder = 0;
        // mIsLastNode = false;
        mMovedToRightSibling = false;
        boolean firstEvent = true;
        // If structure already exists, make a sync against the current structure.
        if (mMaxNodeKey == 0) {
            // If no content is in the XML, a normal insertNewContent is executed.
            new XMLShredder.Builder(mWtx, mReader, mInsert).build().call();
        } else {
            if (mWtx.getKind() == Kind.DOCUMENT) {
                // Find the start key for the update operation.
                long startkey = Fixed.DOCUMENT_NODE_KEY.getStandardProperty() + 1;
                while (!mWtx.moveTo(startkey).hasMoved()) {
                    startkey++;
                }
            }
            XMLEvent event = null;
            StringBuilder sBuilder = new StringBuilder();
            final XMLEventFactory fac = XMLEventFactory.newInstance();
            // Iterate over all nodes.
            while (mReader.hasNext()) {
                // Parsing the next event.
                if (mDelete == EDelete.ATSTARTMIDDLE) {
                    /*
             * Do not move StAX parser forward if nodes have been deleted at the start or in the
             * middle of a subtree.
             */
                    mDelete = EDelete.NODELETE;
                } else {
                    // After an insert or after nodes were equal.
                    event = mReader.nextEvent();
                    if (event.isCharacters() && event.asCharacters().isWhiteSpace()) {
                        continue;
                    }
                    assert event != null;
                    if (firstEvent) {
                        // Setup start element from StAX parser.
                        firstEvent = false;
                        if (event.getEventType() == XMLStreamConstants.START_DOCUMENT) {
                            while (mReader.hasNext() && event.getEventType() != XMLStreamConstants.START_ELEMENT) {
                                event = mReader.nextEvent();
                            }
                            assert event.getEventType() == XMLStreamConstants.START_ELEMENT;
                        }
                        if (event.getEventType() != XMLStreamConstants.START_ELEMENT) {
                            throw new IllegalStateException("StAX parser has to be on START_DOCUMENT or START_ELEMENT event!");
                        }
                        // Get root element of subtree or whole XML document to shredder.
                        mRootElem = event.asStartElement().getName();
                    } else if (event != null && event.isEndElement() && mRootElem.equals(event.asEndElement().getName()) && mLevelInToShredder == 1) {
                        // End with shredding if end_elem equals root-elem.
                        break;
                    }
                }
                assert event != null;
                switch(event.getEventType()) {
                    case XMLStreamConstants.START_ELEMENT:
                        processStartTag(event.asStartElement());
                        break;
                    case XMLStreamConstants.CHARACTERS:
                        sBuilder.append(event.asCharacters().getData());
                        while (mReader.peek().getEventType() == XMLStreamConstants.CHARACTERS) {
                            sBuilder.append(mReader.nextEvent().asCharacters().getData());
                        }
                        final Characters text = fac.createCharacters(sBuilder.toString().trim());
                        processCharacters(text);
                        sBuilder = new StringBuilder();
                        break;
                    case XMLStreamConstants.END_ELEMENT:
                        processEndTag();
                        break;
                    default:
                }
            }
            // if (!mIsLastNode) {
            // if (mInserted) {
            // // Remove next node after node, which was inserted, because it must
            // have been deleted.
            // if (mWtx.moveToRightSibling()) {
            // mWtx.remove();
            // }
            // } else {
            // // Remove current node (cursor has been moved to the next node
            // already).
            // mWtx.remove();
            // }
            // 
            // // Also remove any siblings.
            // boolean hasRightSibling = false;
            // while (mWtx.getStructuralNode().hasRightSibling()) {
            // hasRightSibling = true;
            // mWtx.remove();
            // }
            // if (hasRightSibling) {
            // mWtx.remove();
            // }
            // }
            mReader.close();
        }
    // TODO: use Java7 multi-catch feature.
    } catch (final XMLStreamException e) {
        throw new SirixIOException(e);
    } catch (final IOException e) {
        throw new SirixIOException(e);
    }
}
Also used : XMLStreamException(javax.xml.stream.XMLStreamException) XMLEventFactory(javax.xml.stream.XMLEventFactory) Characters(javax.xml.stream.events.Characters) XMLEvent(javax.xml.stream.events.XMLEvent) SirixIOException(org.sirix.exception.SirixIOException) IOException(java.io.IOException) SirixIOException(org.sirix.exception.SirixIOException)

Example 17 with Characters

use of javax.xml.stream.events.Characters in project tutorials by eugenp.

the class StaxParser method getAllTutorial.

public List<Tutorial> getAllTutorial() {
    boolean bTitle = false;
    boolean bDescription = false;
    boolean bDate = false;
    boolean bAuthor = false;
    List<Tutorial> tutorials = new ArrayList<Tutorial>();
    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLEventReader eventReader = factory.createXMLEventReader(new FileReader(this.getFile()));
        Tutorial current = null;
        while (eventReader.hasNext()) {
            XMLEvent event = eventReader.nextEvent();
            switch(event.getEventType()) {
                case XMLStreamConstants.START_ELEMENT:
                    StartElement startElement = event.asStartElement();
                    String qName = startElement.getName().getLocalPart();
                    if (qName.equalsIgnoreCase("tutorial")) {
                        current = new Tutorial();
                        Iterator<Attribute> attributes = startElement.getAttributes();
                        while (attributes.hasNext()) {
                            Attribute currentAt = attributes.next();
                            if (currentAt.getName().toString().equalsIgnoreCase("tutId")) {
                                current.setTutId(currentAt.getValue());
                            } else if (currentAt.getName().toString().equalsIgnoreCase("type")) {
                                current.setType(currentAt.getValue());
                            }
                        }
                    } else if (qName.equalsIgnoreCase("title")) {
                        bTitle = true;
                    } else if (qName.equalsIgnoreCase("description")) {
                        bDescription = true;
                    } else if (qName.equalsIgnoreCase("date")) {
                        bDate = true;
                    } else if (qName.equalsIgnoreCase("author")) {
                        bAuthor = true;
                    }
                    break;
                case XMLStreamConstants.CHARACTERS:
                    Characters characters = event.asCharacters();
                    if (bTitle) {
                        if (current != null) {
                            current.setTitle(characters.getData());
                        }
                        bTitle = false;
                    }
                    if (bDescription) {
                        if (current != null) {
                            current.setDescription(characters.getData());
                        }
                        bDescription = false;
                    }
                    if (bDate) {
                        if (current != null) {
                            current.setDate(characters.getData());
                        }
                        bDate = false;
                    }
                    if (bAuthor) {
                        if (current != null) {
                            current.setAuthor(characters.getData());
                        }
                        bAuthor = false;
                    }
                    break;
                case XMLStreamConstants.END_ELEMENT:
                    EndElement endElement = event.asEndElement();
                    if (endElement.getName().getLocalPart().equalsIgnoreCase("tutorial")) {
                        if (current != null) {
                            tutorials.add(current);
                        }
                    }
                    break;
            }
        }
    } catch (FileNotFoundException | XMLStreamException e) {
        e.printStackTrace();
    }
    return tutorials;
}
Also used : Tutorial(com.baeldung.xml.binding.Tutorial) Attribute(javax.xml.stream.events.Attribute) EndElement(javax.xml.stream.events.EndElement) Characters(javax.xml.stream.events.Characters) ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) StartElement(javax.xml.stream.events.StartElement) XMLStreamException(javax.xml.stream.XMLStreamException) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader) FileReader(java.io.FileReader) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 18 with Characters

use of javax.xml.stream.events.Characters in project solr-cmd-utils by tblsoft.

the class SolrXmlParser method parse.

public void parse() throws Exception {
    XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    InputStream is = IOUtils.getInputStream(getInputFileName());
    XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(is);
    boolean isDoc = false;
    boolean isFacet = false;
    boolean isArr = false;
    int lstCounter = 0;
    String currentValue = "";
    String currentName = "";
    List<String> possibleStartElements = Arrays.asList("date,arr,str,bool,double,float,long,int".split(","));
    while (xmlEventReader.hasNext()) {
        XMLEvent xmlEvent = xmlEventReader.nextEvent();
        if (xmlEvent.isStartElement()) {
            StartElement startElement = xmlEvent.asStartElement();
            if (startElement.getAttributeByName(new QName("name")) != null) {
                currentName = startElement.getAttributeByName(new QName("name")).getValue();
            }
            if (startElement.getName().getLocalPart().equals("doc")) {
                isDoc = true;
            }
            if (startElement.getName().getLocalPart().equals("lst")) {
                lstCounter++;
                if (isFacet)
                    if ("facet_fields".equals(currentName)) {
                        isFacet = true;
                    }
            }
        } else if (xmlEvent.isEndElement()) {
            EndElement endElement = xmlEvent.asEndElement();
            if (endElement.getName().getLocalPart().equals("doc")) {
                isDoc = false;
                endDocument();
            } else if (endElement.getName().getLocalPart().equals("arr")) {
                currentName = "";
            } else if (isDoc && possibleStartElements.contains(endElement.getName().getLocalPart())) {
                if (currentName != null && !"".equals(currentName)) {
                    field(currentName, currentValue);
                }
                currentValue = "";
            } else if (endElement.getName().getLocalPart().equals("lst")) {
                lstCounter--;
            } else {
            }
        } else if (xmlEvent.isCharacters()) {
            Characters characters = xmlEvent.asCharacters();
            currentValue = characters.getData();
        }
    }
    is.close();
    xmlEventReader.close();
}
Also used : StartElement(javax.xml.stream.events.StartElement) EndElement(javax.xml.stream.events.EndElement) InputStream(java.io.InputStream) QName(javax.xml.namespace.QName) Characters(javax.xml.stream.events.Characters) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 19 with Characters

use of javax.xml.stream.events.Characters in project rpki-validator-3 by RIPE-NCC.

the class RrdpParser method delta.

public Delta delta(final InputStream inputStream) {
    final Map<String, DeltaElement> objects = new HashMap<>();
    try {
        final XMLInputFactory factory = XMLInputFactory.newInstance();
        final XMLEventReader eventReader = factory.createXMLEventReader(inputStream);
        String sessionId = null;
        BigInteger serial = null;
        String uri = null;
        String hash = null;
        StringBuilder base64 = new StringBuilder();
        boolean inPublishElement = false;
        final Base64.Decoder decoder = Base64.getDecoder();
        while (eventReader.hasNext()) {
            final XMLEvent event = eventReader.nextEvent();
            switch(event.getEventType()) {
                case XMLStreamConstants.START_ELEMENT:
                    final StartElement startElement = event.asStartElement();
                    final String qName = startElement.getName().getLocalPart();
                    switch(qName) {
                        case "publish":
                            uri = getAttr(startElement, "uri", "Uri is not present in 'publish' element");
                            hash = getAttr(startElement, "hash");
                            inPublishElement = true;
                            break;
                        case "withdraw":
                            uri = getAttr(startElement, "uri", "Uri is not present in 'publish' element");
                            hash = getAttr(startElement, "hash", "Hash is not present in 'withdraw' element");
                            break;
                        case "delta":
                            serial = new BigInteger(getAttr(startElement, "serial", "Notification serial is not present"));
                            sessionId = getAttr(startElement, "session_id", "Session id is not present");
                            break;
                    }
                    break;
                case XMLStreamConstants.CHARACTERS:
                    final Characters characters = event.asCharacters();
                    if (inPublishElement) {
                        final String thisBase64 = characters.getData();
                        base64.append(thisBase64.replaceAll("\\s", ""));
                    }
                    break;
                case XMLStreamConstants.END_ELEMENT:
                    final EndElement endElement = event.asEndElement();
                    final String qqName = endElement.getName().getLocalPart();
                    switch(qqName) {
                        case "publish":
                            final byte[] decoded = decoder.decode(base64.toString());
                            objects.put(uri, new DeltaPublish(decoded, uri, Hex.parse(hash)));
                            base64 = new StringBuilder();
                            break;
                        case "withdraw":
                            objects.put(uri, new DeltaWithdraw(uri, Hex.parse(hash)));
                            break;
                    }
                    break;
            }
        }
        return new Delta(objects, sessionId, serial);
    } catch (XMLStreamException e) {
        throw new RrdpException("Couldn't parse snapshot: ", e);
    }
}
Also used : Base64(java.util.Base64) HashMap(java.util.HashMap) EndElement(javax.xml.stream.events.EndElement) Characters(javax.xml.stream.events.Characters) StartElement(javax.xml.stream.events.StartElement) XMLStreamException(javax.xml.stream.XMLStreamException) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader) BigInteger(java.math.BigInteger) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 20 with Characters

use of javax.xml.stream.events.Characters in project midpoint by Evolveum.

the class MidpointFunctionsImpl method parseXmlToMap.

@Override
public Map<String, String> parseXmlToMap(String xml) {
    Map<String, String> resultingMap = new HashMap<>();
    if (xml != null && !xml.isEmpty()) {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        String value = "";
        String startName = "";
        InputStream stream = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));
        boolean isRootElement = true;
        try {
            XMLEventReader eventReader = factory.createXMLEventReader(stream);
            while (eventReader.hasNext()) {
                XMLEvent event = eventReader.nextEvent();
                int code = event.getEventType();
                if (code == XMLStreamConstants.START_ELEMENT) {
                    StartElement startElement = event.asStartElement();
                    startName = startElement.getName().getLocalPart();
                    if (!isRootElement) {
                        resultingMap.put(startName, null);
                    } else {
                        isRootElement = false;
                    }
                } else if (code == XMLStreamConstants.CHARACTERS) {
                    Characters characters = event.asCharacters();
                    if (!characters.isWhiteSpace()) {
                        StringBuilder valueBuilder;
                        if (value != null) {
                            valueBuilder = new StringBuilder(value).append(" ").append(characters.getData());
                        } else {
                            valueBuilder = new StringBuilder(characters.getData());
                        }
                        value = valueBuilder.toString();
                    }
                } else if (code == XMLStreamConstants.END_ELEMENT) {
                    EndElement endElement = event.asEndElement();
                    String endName = endElement.getName().getLocalPart();
                    if (endName.equals(startName)) {
                        if (value != null) {
                            resultingMap.put(endName, value);
                            value = null;
                        }
                    } else {
                        LOGGER.trace("No value between xml tags, tag name : {}", endName);
                    }
                } else if (code == XMLStreamConstants.END_DOCUMENT) {
                    isRootElement = true;
                }
            }
        } catch (XMLStreamException e) {
            StringBuilder error = new StringBuilder("Xml stream exception wile parsing xml string").append(e.getLocalizedMessage());
            throw new SystemException(error.toString());
        }
    } else {
        LOGGER.trace("Input xml string null or empty.");
    }
    return resultingMap;
}
Also used : EndElement(javax.xml.stream.events.EndElement) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Characters(javax.xml.stream.events.Characters) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) StartElement(javax.xml.stream.events.StartElement) XMLStreamException(javax.xml.stream.XMLStreamException) ByteArrayInputStream(java.io.ByteArrayInputStream) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Aggregations

Characters (javax.xml.stream.events.Characters)33 XMLEvent (javax.xml.stream.events.XMLEvent)21 XMLStreamException (javax.xml.stream.XMLStreamException)20 EndElement (javax.xml.stream.events.EndElement)11 StartElement (javax.xml.stream.events.StartElement)11 XMLEventReader (javax.xml.stream.XMLEventReader)6 QName (javax.xml.namespace.QName)5 XMLInputFactory (javax.xml.stream.XMLInputFactory)5 Test (org.junit.Test)5 Attribute (javax.xml.stream.events.Attribute)4 EntityDeclaration (javax.xml.stream.events.EntityDeclaration)4 EntityReference (javax.xml.stream.events.EntityReference)4 HashMap (java.util.HashMap)3 Namespace (javax.xml.stream.events.Namespace)3 StartDocument (javax.xml.stream.events.StartDocument)3 InputStream (java.io.InputStream)2 BigInteger (java.math.BigInteger)2 ArrayList (java.util.ArrayList)2 Base64 (java.util.Base64)2 ProcessingInstruction (javax.xml.stream.events.ProcessingInstruction)2