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:org.wso2.carbon.repository.core.ResourceStorer.java

private void restoreRecursively(String path, XMLStreamReader xmlReader, DumpReader dumpReader,
        long currentVersion, boolean resourceExists) throws RepositoryException, XMLStreamException {
    while (!xmlReader.isStartElement() && xmlReader.hasNext()) {
        xmlReader.next();
    }/*from  ww  w . j av  a2s . c  o  m*/

    if (!xmlReader.hasNext()) {
        return;
    }

    if (!xmlReader.getLocalName().equals(DumpConstants.RESOURCE)) {
        String msg = "Invalid dump to restore at " + path;
        log.error(msg);
        throw new RepositoryException(msg);
    }

    String incomingParentPath = xmlReader.getAttributeValue(null, DumpConstants.RESOURCE_PATH);

    String resourceName = xmlReader.getAttributeValue(null, DumpConstants.RESOURCE_NAME);
    String ignoreConflictsStrValue = xmlReader.getAttributeValue(null, DumpConstants.IGNORE_CONFLICTS);

    boolean ignoreConflicts = true;

    if (ignoreConflictsStrValue != null && Boolean.toString(false).equals(ignoreConflictsStrValue)) {
        ignoreConflicts = false;
    }

    String isCollectionString = xmlReader.getAttributeValue(null, DumpConstants.RESOURCE_IS_COLLECTION);
    boolean isCollection = isCollectionString.equals(DumpConstants.RESOURCE_IS_COLLECTION_TRUE);

    if (path.equals(RepositoryConstants.ROOT_PATH) && !isCollection) {
        String msg = "Illegal to restore a non-collection in place of root collection.";
        log.error(msg);
        throw new RepositoryException(msg);
    }

    String status = xmlReader.getAttributeValue(null, DumpConstants.RESOURCE_STATUS);

    if (DumpConstants.RESOURCE_DELETED.equals(status) && resourceExists) {
        delete(path);
        return;
    }

    ResourceImpl resourceImpl;
    byte[] contentBytes = new byte[0];

    if (isCollection) {
        resourceImpl = new CollectionImpl();
    } else {
        resourceImpl = new ResourceImpl();
    }

    boolean isCreatorExisting = false;
    boolean isCreatedTimeExisting = false;
    boolean isUpdaterExisting = false;
    boolean isUpdatedTimeExisting = false;
    long dumpingResourceVersion = -1;

    do {
        xmlReader.next();
    } while (!xmlReader.isStartElement() && xmlReader.hasNext());

    while (xmlReader.hasNext()) {
        String localName = xmlReader.getLocalName();

        // setMediaType
        if (localName.equals(DumpConstants.MEDIA_TYPE)) {
            String text = xmlReader.getElementText();
            if (text.indexOf('/') < 0) {
                text = MediaTypesUtils.getMediaType("dummy." + text);
            }
            if (text != null) {
                resourceImpl.setMediaType(text);
            }
            // now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        } else if (localName.equals(DumpConstants.CREATOR)) {
            String text = xmlReader.getElementText();
            if (text != null) {
                resourceImpl.setAuthorUserName(text);
                isCreatorExisting = true;
            }
            // now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
        // version: just to keep track of the server changes
        else if (localName.equals(DumpConstants.VERSION)) {
            String text = xmlReader.getElementText();
            if (text != null) {
                dumpingResourceVersion = Long.parseLong(text);
            }
            // now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
        // uuid: just to keep track of the server changes
        else if (localName.equals(DumpConstants.UUID)) {
            String text = xmlReader.getElementText();
            if (text != null) {
                resourceImpl.setUUID(text);
            }
            // now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
        // createdTime
        else if (localName.equals(DumpConstants.CREATED_TIME)) {
            String text = xmlReader.getElementText();
            if (text != null) {
                long date = Long.parseLong(text);
                resourceImpl.setCreatedTime(new Date(date));
                isCreatedTimeExisting = true;
            }
            // now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
        // setLastUpdater
        else if (localName.equals(DumpConstants.LAST_UPDATER)) {
            String text = xmlReader.getElementText();
            if (text != null) {
                resourceImpl.setLastUpdaterUserName(text);
                isUpdaterExisting = true;
            }
            // now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
        // LastModified
        else if (localName.equals(DumpConstants.LAST_MODIFIED)) {
            String text = xmlReader.getElementText();
            if (text != null) {
                long date = Long.parseLong(text);
                resourceImpl.setLastModified(new Date(date));
                isUpdatedTimeExisting = true;
            }
            // now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
        // get description
        else if (localName.equals(DumpConstants.DESCRIPTION)) {
            String text = xmlReader.getElementText();
            if (text != null) {
                resourceImpl.setDescription(text);
            }
            // now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
        // get properties
        else if (localName.equals(DumpConstants.PROPERTIES)) {
            // iterating trying to find the children..
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
            while (xmlReader.hasNext() && xmlReader.getLocalName().equals(DumpConstants.PROPERTY_ENTRY)) {
                String key = xmlReader.getAttributeValue(null, DumpConstants.PROPERTY_ENTRY_KEY);
                String text = xmlReader.getElementText();
                if (text.equals("")) {
                    text = null;
                }
                if (text != null) {
                    resourceImpl.addPropertyWithNoUpdate(key, text);
                }
                do {
                    xmlReader.next();
                } while (!xmlReader.isStartElement() && xmlReader.hasNext());
            }
        }
        // get content
        else if (localName.equals(DumpConstants.CONTENT)) {
            String text = xmlReader.getElementText();
            // we keep content as base64 encoded
            if (text != null) {
                contentBytes = DatatypeConverter.parseBase64Binary(text);
            }
            do {
                xmlReader.next();
            } while ((!xmlReader.isStartElement() && xmlReader.hasNext())
                    && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals(DumpConstants.RESOURCE)));
        }

        // getting rating information
        else if (localName.equals(DumpConstants.ASSOCIATIONS)) {
            // iterating trying to find the children..
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
            while (xmlReader.hasNext() && xmlReader.getLocalName().equals(DumpConstants.ASSOCIATION_ENTRY)) {
                String source = null;
                String destination = null;
                String type = null;

                do {
                    xmlReader.next();
                } while (!xmlReader.isStartElement() && xmlReader.hasNext());

                localName = xmlReader.getLocalName();
                while (xmlReader.hasNext() && (localName.equals(DumpConstants.ASSOCIATION_ENTRY_SOURCE)
                        || localName.equals(DumpConstants.ASSOCIATION_ENTRY_DESTINATION)
                        || localName.equals(DumpConstants.ASSOCIATION_ENTRY_TYPE))) {
                    if (localName.equals(DumpConstants.ASSOCIATION_ENTRY_SOURCE)) {
                        String text = xmlReader.getElementText();
                        if (text != null) {
                            source = text;
                        }
                    } else if (localName.equals(DumpConstants.ASSOCIATION_ENTRY_DESTINATION)) {
                        String text = xmlReader.getElementText();
                        if (text != null) {
                            destination = text;
                        }
                    } else if (localName.equals(DumpConstants.ASSOCIATION_ENTRY_TYPE)) {
                        String text = xmlReader.getElementText();
                        if (text != null) {
                            type = text;
                        }
                    }
                    do {
                        xmlReader.next();
                    } while (!xmlReader.isStartElement() && xmlReader.hasNext());
                    if (xmlReader.hasNext()) {
                        localName = xmlReader.getLocalName();
                    }
                }
                // get the source and destination as absolute paths
                source = RepositoryUtils.getAbsoluteAssociationPath(source, path);
                if (destination.startsWith(DumpConstants.EXTERNAL_ASSOCIATION_DESTINATION_PREFIX)) {
                    destination = destination
                            .substring(DumpConstants.EXTERNAL_ASSOCIATION_DESTINATION_PREFIX.length());
                } else {
                    destination = RepositoryUtils.getAbsoluteAssociationPath(destination, path);
                }
                //                    associationList.add(new Association(source, destination, type));
            }
        }

        // getting children, just storing in array list now, will used at the end
        // we are keeping old name to keep backward compatibility.
        else if (localName.equals(DumpConstants.CHILDREN) || localName.equals(DumpConstants.CHILDS)) {
            // we keep the stream to call this function recursively
            break;
        } else if (localName.equals(DumpConstants.RESOURCE)) {
            // we keep the stream to call this function recursively
            break;
        } else {
            // we don't mind having unwanted elements, now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
    }

    if (!ignoreConflicts) {
        // so we handling the conflicts.
        if (dumpingResourceVersion > 0) {
            if (currentVersion == -1) {
                // the current version == -1 means the resource is deleted in the server
                // but since the client is sending a version number, it has a previously checkout
                // resource
                String msg = "Resource is deleted in the server, resource path: " + path + ".";
                log.error(msg);
                throw new RepositoryException(msg);
            }
            // we should check whether our dump is up-to-date
            if (currentVersion > dumpingResourceVersion) {
                // that mean the current resource is updated before the current version
                // so we have to notify user to get an update
                String msg = "Resource is in a newer version than the restoring version. " + "resource path: "
                        + path + ".";
                log.error(msg);
                throw new RepositoryException(msg);
            }
        }
    }

    // completing the empty fields
    if (!isCreatorExisting) {
        String creator = CurrentContext.getUser();
        resourceImpl.setAuthorUserName(creator);
    }

    if (!isCreatedTimeExisting) {
        long now = System.currentTimeMillis();
        resourceImpl.setCreatedTime(new Date(now));
    }

    if (!isUpdaterExisting) {
        String updater = CurrentContext.getUser();
        resourceImpl.setLastUpdaterUserName(updater);
    }

    if (!isUpdatedTimeExisting) {
        long now = System.currentTimeMillis();
        resourceImpl.setLastModified(new Date(now));
    }

    if (resourceImpl.getUUID() == null) {
        setUUIDForResource(resourceImpl);
    }

    // create sym links
    String linkRestoration = resourceImpl.getPropertyValue(InternalConstants.REGISTRY_LINK_RESTORATION);
    if (linkRestoration != null) {
        String[] parts = linkRestoration.split(RepositoryConstants.URL_SEPARATOR);

        if (parts.length == 4) {
            if (parts[2] != null && parts[2].length() == 0) {
                parts[2] = null;
            }
            if (parts[0] != null && parts[1] != null && parts[3] != null) {
                InternalUtils.registerHandlerForRemoteLinks(RepositoryContext.getBaseInstance(), parts[0],
                        parts[1], parts[2], parts[3]);
            }
        } else if (parts.length == 3) {
            // here parts[0] the current path, path[1] is the target path.
            if (parts[0] != null && parts[1] != null) {
                // first we are calculating the relative path of path[1] to path[0]
                String relativeTargetPath = RepositoryUtils.getRelativeAssociationPath(parts[1], parts[0]);
                // then we derive the absolute path with reference to the current path.
                String absoluteTargetPath = RepositoryUtils.getAbsoluteAssociationPath(relativeTargetPath,
                        path);
                InternalUtils.registerHandlerForSymbolicLinks(RepositoryContext.getBaseInstance(), path,
                        absoluteTargetPath, parts[2]);
            }
        }
    }

    synchronized (this) {
        ResourceIDImpl resourceID = null;
        ResourceDO resourceDO = null;

        if (resourceDAO.resourceExists(path)) {
            resourceID = resourceDAO.getResourceID(path);
            resourceDO = resourceDAO.getResourceDO(resourceID);

            if (resourceDO == null) {
                if (isCollection) {
                    resourceID = resourceDAO.getResourceID(path, isCollection);

                    if (resourceID != null) {
                        resourceDO = resourceDAO.getResourceDO(resourceID);
                    }
                }

                if (resourceDO == null) {
                    return;
                }
            }
        }

        if (DumpConstants.RESOURCE_UPDATED.equals(status) || DumpConstants.RESOURCE_ADDED.equals(status)
                || DumpConstants.RESOURCE_DUMP.equals(status)) {
            if (resourceDAO.resourceExists(path)) {
                if (DumpConstants.RESOURCE_DUMP.equals(status)) {
                    delete(path);
                } else {
                    deleteNode(resourceID, resourceDO, true);
                }
            }

            if (resourceID == null) {
                // need to create a resourceID
                String parentPath = RepositoryUtils.getParentPath(path);

                ResourceIDImpl parentResourceID = resourceDAO.getResourceID(parentPath, true);
                if (parentResourceID == null || !resourceDAO.resourceExists(parentResourceID)) {
                    addEmptyCollection(parentPath);
                    if (parentResourceID == null) {
                        parentResourceID = resourceDAO.getResourceID(parentPath, true);
                    }
                }
                resourceDAO.createAndApplyResourceID(path, parentResourceID, resourceImpl);
            } else {
                resourceImpl.setPathID(resourceID.getPathID());
                resourceImpl.setName(resourceID.getName());
                resourceImpl.setPath(path);
            }

            // adding resource followed by content (for nonCollection)
            if (!isCollection) {
                int contentId = 0;

                if (contentBytes.length > 0) {
                    contentId = resourceDAO.addContentBytes(new ByteArrayInputStream(contentBytes));
                }

                resourceImpl.setDbBasedContentID(contentId);
            }

            resourceDO = resourceImpl.getResourceDO();
            resourceDAO.addResourceDO(resourceDO);
            resourceImpl.setVersionNumber(resourceDO.getVersion());

            // adding the properties.
            resourceDAO.addProperties(resourceImpl);
        }
    }

    if (!xmlReader.hasNext() || !(xmlReader.getLocalName().equals(DumpConstants.CHILDREN)
            || xmlReader.getLocalName().equals(DumpConstants.CHILDS))) {
        // finished the recursion
        return;
    }

    do {
        xmlReader.next();
        if (xmlReader.isEndElement() && (xmlReader.getLocalName().equals(DumpConstants.CHILDREN)
                || xmlReader.getLocalName().equals(DumpConstants.CHILDS))) {
            // this means empty children, just quit from here
            // before that we have to set the cursor to the start of the next element
            if (xmlReader.hasNext()) {
                do {
                    xmlReader.next();
                } while ((!xmlReader.isStartElement() && xmlReader.hasNext()) && !(xmlReader.isEndElement()
                        && xmlReader.getLocalName().equals(DumpConstants.RESOURCE)));
            }
            Resource resource = get(path);

            if (resource instanceof Collection) {
                String[] existingChildren = ((Collection) resource).getChildPaths();
                for (String existingChild : existingChildren) {
                    delete(existingChild);
                }
            }

            return;
        }
    } while (!xmlReader.isStartElement() && xmlReader.hasNext());

    int i = 0;

    if (xmlReader.hasNext() && xmlReader.getLocalName().equals(DumpConstants.RESOURCE)) {
        Set<String> childPathSet = new HashSet<String>();

        while (true) {
            if (i != 0) {
                dumpReader.setReadingChildResourceIndex(i);

                // otherwise we will set the stuff for the next resource
                // get an xlm reader in the checking child by parent mode.
                xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(dumpReader);

                while (!xmlReader.isStartElement() && xmlReader.hasNext()) {
                    xmlReader.next();
                }
            }

            String absoluteChildPath;

            if (incomingParentPath != null) {
                // the code to support backward compatibility.
                // prepare the children absolute path
                String incomingChildPath = xmlReader.getAttributeValue(null, DumpConstants.RESOURCE_PATH);
                /*                    if (!incomingChildPath.startsWith(incomingParentPath)) {
                //break;
                                    }*/

                String relativeChildPath;

                if (incomingParentPath.equals(RepositoryConstants.ROOT_PATH)) {
                    relativeChildPath = incomingChildPath;
                } else {
                    if (incomingParentPath.contains(incomingChildPath)) {
                        relativeChildPath = incomingChildPath.substring(incomingParentPath.length());
                    } else {
                        // this happens only at some custom editing of dump.xml
                        relativeChildPath = null;
                    }
                }
                if (relativeChildPath != null) {
                    if (path.equals(RepositoryConstants.ROOT_PATH)) {
                        absoluteChildPath = relativeChildPath;
                    } else {
                        absoluteChildPath = path + relativeChildPath;
                    }
                } else {
                    String checkoutRoot = path.substring(0, path.length() - incomingParentPath.length());
                    absoluteChildPath = checkoutRoot + incomingChildPath;
                }
            } else if (resourceName != null) {
                String childName = xmlReader.getAttributeValue(null, DumpConstants.RESOURCE_NAME);
                absoluteChildPath = path
                        + (path.equals(RepositoryConstants.ROOT_PATH) ? "" : RepositoryConstants.PATH_SEPARATOR)
                        + childName;
            } else {
                String msg = "Error in deriving the child paths for collection. path: " + path + ".";
                log.error(msg);
                throw new RepositoryException(msg);
            }

            // we give the control back to the child.
            dumpReader.setCheckingChildByParent(false);

            dumpReader.setReadingChildResourceIndex(i);
            // call the check in method recursively

            recursionRepository.restoreRecursively(absoluteChildPath, dumpReader);
            childPathSet.add(absoluteChildPath);

            dumpReader.setCheckingChildByParent(true);

            try {
                if (dumpReader.isLastResource(i)) {
                    dumpReader.setCheckingChildByParent(false);
                    break;
                }
            } catch (IOException e) {
                String msg = "Error in checking the last resource exists.";
                log.error(msg, e);
                throw new RepositoryException(msg + e.getMessage(), e);
            }
            // by this time i ++ child resource should exist
            i++;
        }

        Collection parent = (Collection) get(path);
        String[] existingChildren = parent.getChildPaths();

        for (String existingChild : existingChildren) {
            if (!childPathSet.contains(existingChild)) {
                delete(existingChild);
            }
        }
    }
}

From source file:org.xwiki.filter.xar.internal.input.AttachmentReader.java

@Override
public WikiAttachment read(XMLStreamReader xmlReader, XARInputProperties properties)
        throws XMLStreamException, FilterException {
    WikiAttachment wikiAttachment = new WikiAttachment();

    for (xmlReader.nextTag(); xmlReader.isStartElement(); xmlReader.nextTag()) {
        String elementName = xmlReader.getLocalName();

        EventParameter parameter = XARAttachmentModel.ATTACHMENT_PARAMETERS.get(elementName);

        if (parameter != null) {
            Object wsValue = convert(parameter.type, xmlReader.getElementText());
            if (wsValue != null) {
                wikiAttachment.parameters.put(parameter.name, wsValue);
            }/*from  www  .j  av a2 s. co m*/
        } else {
            if (XARAttachmentModel.ELEMENT_NAME.equals(elementName)) {
                wikiAttachment.name = xmlReader.getElementText();
            } else if (XARAttachmentModel.ELEMENT_CONTENT_SIZE.equals(elementName)) {
                wikiAttachment.size = Long.valueOf(xmlReader.getElementText());
            } else if (XARAttachmentModel.ELEMENT_CONTENT.equals(elementName)) {
                // We copy the attachment content to use it later. We can't directly send it as a stream because XAR
                // specification does not force any order for the attachment properties and we need to be sure we
                // have everything when sending the event.

                // Allocate a temporary file in case the attachment content is big
                File temporaryFile;
                try {
                    temporaryFile = File.createTempFile("xar/attachments/attachment", ".bin");
                    temporaryFile.deleteOnExit();
                } catch (IOException e) {
                    throw new FilterException(e);
                }

                // Create a deferred file based content (if the content is bigger than 10000 bytes it will end up in
                // a file)
                wikiAttachment.content = new DeferredFileOutputStream(100000, temporaryFile);

                // Copy the content to byte array or file depending on its size
                for (xmlReader.next(); xmlReader.isCharacters(); xmlReader.next()) {
                    try {
                        wikiAttachment.content.write(xmlReader.getText().getBytes(StandardCharsets.UTF_8));
                    } catch (IOException e) {
                        throw new FilterException(e);
                    }
                }
            }
        }
    }

    return wikiAttachment;
}

From source file:pl.datamatica.traccar.api.GPXParser.java

public Result parse(InputStream inputStream, Device device)
        throws XMLStreamException, ParseException, IOException {
    Result result = new Result();

    TimeZone tz = TimeZone.getTimeZone("UTC");
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    DateFormat dateFormatWithMS = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

    dateFormat.setTimeZone(tz);//from   ww  w.ja va 2 s. com
    dateFormatWithMS.setTimeZone(tz);

    XMLStreamReader xsr = XMLInputFactory.newFactory().createXMLStreamReader(inputStream);
    ObjectMapper jsonMapper = new ObjectMapper();

    result.positions = new LinkedList<>();
    Position position = null;
    Stack<String> extensionsElements = new Stack<>();
    boolean extensionsStarted = false;
    Map<String, Object> other = null;

    while (xsr.hasNext()) {
        xsr.next();
        if (xsr.getEventType() == XMLStreamReader.START_ELEMENT) {
            if (xsr.getLocalName().equalsIgnoreCase("trkpt")) {
                position = new Position();
                position.setLongitude(Double.parseDouble(xsr.getAttributeValue(null, "lon")));
                position.setLatitude(Double.parseDouble(xsr.getAttributeValue(null, "lat")));
                position.setValid(Boolean.TRUE);
                position.setDevice(device);
            } else if (xsr.getLocalName().equalsIgnoreCase("time")) {
                if (position != null) {
                    String strTime = xsr.getElementText();
                    if (strTime.length() == 20) {
                        position.setTime(dateFormat.parse(strTime));
                    } else {
                        position.setTime(dateFormatWithMS.parse(strTime));
                    }
                }
            } else if (xsr.getLocalName().equalsIgnoreCase("ele") && position != null) {
                position.setAltitude(Double.parseDouble(xsr.getElementText()));
            } else if (xsr.getLocalName().equalsIgnoreCase("address") && position != null) {
                position.setAddress(StringEscapeUtils.unescapeXml(xsr.getElementText()));
            } else if (xsr.getLocalName().equalsIgnoreCase("protocol") && position != null) {
                position.setProtocol(xsr.getElementText());
            } else if (xsr.getLocalName().equalsIgnoreCase("speed") && position != null) {
                position.setSpeed(Double.parseDouble(xsr.getElementText()));
            } else if (xsr.getLocalName().equalsIgnoreCase("power") && position != null) {
                position.setPower(Double.parseDouble(xsr.getElementText()));
            } else if (xsr.getLocalName().equalsIgnoreCase("course") && position != null) {
                position.setCourse(Double.parseDouble(xsr.getElementText()));
            } else if (xsr.getLocalName().equalsIgnoreCase("other") && position != null) {
                position.setOther(StringEscapeUtils.unescapeXml(xsr.getElementText()));
            } else if (xsr.getLocalName().equalsIgnoreCase("extensions")) {
                other = new LinkedHashMap<>();
                extensionsStarted = true;
            } else if (position != null && extensionsStarted && other != null) {
                extensionsElements.push(xsr.getLocalName());
            }
        } else if (xsr.getEventType() == XMLStreamReader.END_ELEMENT) {
            if (xsr.getLocalName().equalsIgnoreCase("trkpt")) {
                if (other == null) {
                    other = new HashMap<>();
                }

                if (position.getOther() != null) {
                    if (position.getOther().startsWith("<")) {
                        XMLStreamReader otherReader = XMLInputFactory.newFactory()
                                .createXMLStreamReader(new StringReader(position.getOther()));
                        while (otherReader.hasNext()) {
                            if (otherReader.next() == XMLStreamReader.START_ELEMENT
                                    && !otherReader.getLocalName().equals("info")) {
                                other.put(otherReader.getLocalName(), otherReader.getElementText());
                            }
                        }
                    } else {
                        Map<String, Object> parsedOther = jsonMapper.readValue(position.getOther(),
                                LinkedHashMap.class);
                        other.putAll(parsedOther);
                    }
                }

                if (other.containsKey("protocol") && position.getProtocol() == null) {
                    position.setProtocol(other.get("protocol").toString());
                } else if (!other.containsKey("protocol") && position.getProtocol() == null) {
                    position.setProtocol("gpx_import");
                }

                other.put("import_type", (result.positions.isEmpty() ? "import_start" : "import"));

                position.setOther(jsonMapper.writeValueAsString(other));

                result.positions.add(position);
                if (result.latestPosition == null
                        || result.latestPosition.getTime().compareTo(position.getTime()) < 0) {
                    result.latestPosition = position;
                }
                position = null;
                other = null;
            } else if (xsr.getLocalName().equalsIgnoreCase("extensions")) {
                extensionsStarted = false;
            } else if (extensionsStarted) {
                extensionsElements.pop();
            }
        } else if (extensionsStarted && other != null && xsr.getEventType() == XMLStreamReader.CHARACTERS
                && !xsr.getText().trim().isEmpty() && !extensionsElements.empty()) {
            String name = "";
            for (int i = 0; i < extensionsElements.size(); i++) {
                name += (name.length() > 0 ? "-" : "") + extensionsElements.get(i);
            }

            other.put(name, xsr.getText());
        }
    }

    if (result.positions.size() > 1) {
        Position last = ((LinkedList<Position>) result.positions).getLast();
        Map<String, Object> parsedOther = jsonMapper.readValue(last.getOther(), LinkedHashMap.class);
        parsedOther.put("import_type", "import_end");
        last.setOther(jsonMapper.writeValueAsString(parsedOther));
    }

    return result;
}

From source file:rjc.jplanner.model.Plan.java

/******************************************* loadXML *******************************************/
public void loadXML(XMLStreamReader xsr, String filename, String fileloc) throws XMLStreamException {
    // as id of plan-calendar read before the calendars, need temporary store
    int calendarId = -1;

    // load plan from XML stream
    while (xsr.hasNext()) {
        // if reached end of plan data, exit loop
        if (xsr.isEndElement() && xsr.getLocalName().equals(XmlLabels.XML_PLAN_DATA))
            break;

        // if start element read data
        if (xsr.isStartElement())
            switch (xsr.getLocalName()) {
            case XmlLabels.XML_JPLANNER:
                loadXmlJPlanner(xsr);/*www.j  av a 2s  . co m*/
                break;
            case XmlLabels.XML_PLAN_DATA:
                calendarId = loadXmlPlan(xsr);
                break;
            case XmlLabels.XML_DAY_DATA:
                daytypes.loadXML(xsr);
                break;
            case XmlLabels.XML_CAL_DATA:
                calendars.loadXML(xsr);
                break;
            case XmlLabels.XML_RES_DATA:
                resources.loadXML(xsr);
                break;
            case XmlLabels.XML_TASK_DATA:
                tasks.loadXML(xsr);
                break;
            default:
                JPlanner.trace("Unhandled start element '" + xsr.getLocalName() + "'");
                break;
            }

        xsr.next();
    }

    // if calendar-id still negative, default to first calendar
    if (calendarId < 0)
        m_calendar = calendar(0);
    else
        m_calendar = calendar(calendarId);

    m_filename = filename;
    m_fileLocation = fileloc;
}

From source file:savant.plugin.PluginIndex.java

public PluginIndex(URL url) throws IOException {
    urls = new HashMap<String, URL>();
    try {// ww  w .j a  v a 2 s . c  om
        XMLStreamReader reader = XMLInputFactory.newInstance()
                .createXMLStreamReader(NetworkUtils.openStream(url));
        boolean done = false;
        String id = null;
        do {
            switch (reader.next()) {
            case XMLStreamConstants.START_ELEMENT:
                String elemName = reader.getLocalName();
                if (elemName.equals("leaf")) {
                    id = reader.getAttributeValue(null, "id");
                } else if (elemName.equals("url")) {
                    if (id != null) {
                        try {
                            urls.put(id, new URL(reader.getElementText()));
                        } catch (MalformedURLException x) {
                            LOG.info("Unable to parse \"" + reader.getElementText() + "\" as a plugin URL.");
                        }
                        id = null;
                    }
                }
                break;
            case XMLStreamConstants.END_DOCUMENT:
                reader.close();
                done = true;
                break;
            }
        } while (!done);
    } catch (XMLStreamException x) {
        throw new IOException("Unable to get version number from web-site.", x);
    }
}

From source file:savant.plugin.Tool.java

/**
 * The tool's arguments are contained in the associated plugin.xml file.
 *//* www  .j  a  v  a2  s. c  om*/
void parseDescriptor() throws XMLStreamException, FileNotFoundException {
    XMLStreamReader reader = XMLInputFactory.newInstance()
            .createXMLStreamReader(new FileInputStream(getDescriptor().getFile()));
    do {
        switch (reader.next()) {
        case XMLStreamConstants.START_ELEMENT:
            String elemName = reader.getLocalName().toLowerCase();
            if (elemName.equals("tool")) {
                baseCommand = reader.getElementText();
            } else if (elemName.equals("arg")) {
                // There's lots of crud in the XML file; we're just interested in the <arg> elements.
                arguments.add(new ToolArgument(reader));
            } else if (elemName.equals("progress")) {
                progressRegex = Pattern.compile(reader.getElementText());
            } else if (elemName.equals("error")) {
                errorRegex = Pattern.compile(reader.getElementText());
            }
            break;
        case XMLStreamConstants.END_DOCUMENT:
            reader.close();
            reader = null;
            break;
        }
    } while (reader != null);
}

From source file:savant.util.Version.java

/**
 * Factory method which construct a Version object from a URL pointing to an XML file.
 * @param url URL of our version.xml file
 * @return the version number read from the file
 *//*  ww  w  .  j a  va2s . c  o  m*/
public static Version fromURL(URL url) throws IOException {
    try {
        XMLStreamReader reader = XMLInputFactory.newInstance()
                .createXMLStreamReader(NetworkUtils.openStream(url));
        boolean done = false;
        boolean foundCurrentVersion = false;
        do {
            switch (reader.next()) {
            case XMLStreamConstants.START_ELEMENT:
                String elemName = reader.getLocalName();
                if (elemName.equals("version")
                        && "current_release".equals(reader.getAttributeValue(null, "status"))) {
                    foundCurrentVersion = true;
                } else if (foundCurrentVersion && elemName.equals("name")) {
                    return new Version(reader.getElementText());
                } else {
                    foundCurrentVersion = false;
                }
                break;
            case XMLStreamConstants.END_DOCUMENT:
                reader.close();
                done = true;
                break;
            }
        } while (!done);
    } catch (XMLStreamException x) {
        throw new IOException("Unable to get version number from web-site.", x);
    }
    return null;
}

From source file:tkwatch.Utilities.java

/**
 * Finds the value of the named element, if any, in an XML string. Adapted
 * from Vohra and Vohra, <i>Pro XML Development with Java Technology</i>, p.
 * 47.//from   ww w . j a  v  a2  s  .c  o  m
 * 
 * @param desiredElementName
 *            The name of the element to search for in the XML string.
 * @param xmlString
 *            The XML string to search for an account number.
 * 
 * @return Returns the element value(s) as formatted in the incoming string
 *         (if found) as a <code>Vector<String></code>, <code>null</code>
 *         otherwise.
 */
public static final Vector<String> getValueFromXml(final String desiredElementName, final String xmlString) {
    Vector<String> elementValue = new Vector<String>();
    String elementValueText = null;
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    try {
        String elementName = "";
        StringReader stringReader = new StringReader(xmlString);
        XMLStreamReader reader = inputFactory.createXMLStreamReader(stringReader);
        while (reader.hasNext()) {
            int eventType = reader.getEventType();
            switch (eventType) {
            case XMLStreamConstants.START_ELEMENT:
                elementName = reader.getLocalName();
                if (elementName.equals(desiredElementName)) {
                    elementValueText = reader.getAttributeValue(0);
                    System.out.println("START_ELEMENT case, element name is " + elementName
                            + ", element value is " + elementValueText);
                }
                break;
            case XMLStreamConstants.ATTRIBUTE:
                elementName = reader.getLocalName();
                if (elementName.equals(desiredElementName)) {
                    elementValueText = reader.getElementText();
                    System.out.println("ATTRIBUTE case, element name is " + elementName + ", element value is "
                            + elementValueText);
                    elementValue.add(elementValueText);
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                elementName = reader.getLocalName();
                if (elementName.equals(desiredElementName)) {
                    System.out.println("END_ELEMENT case, element name is " + elementName
                            + ", element value is " + elementValueText);
                }
                break;
            default:
                elementName = reader.getLocalName();
                if (elementName != null) {
                    if (elementName.equals(desiredElementName)) {
                        System.out.println("default case, element name is " + elementName);
                    }
                }
                break;
            }
            reader.next();
        }
    } catch (XMLStreamException e) {
        TradekingException.handleException(e);
    }
    return (elementValue.isEmpty() ? null : elementValue);
}

From source file:tpt.dbweb.cat.io.TaggedTextXMLReader.java

private Iterator<TaggedText> getIterator(InputStream is, String errorMessageInfo) {

    XMLStreamReader tmpxsr = null;
    try {/*from w  w  w  . ja va2  s.c om*/
        XMLInputFactory xif = XMLInputFactory.newInstance();
        xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
        xif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
        xif.setProperty(XMLInputFactory.IS_VALIDATING, false);
        tmpxsr = xif.createXMLStreamReader(is);
    } catch (XMLStreamException | FactoryConfigurationError e) {
        e.printStackTrace();
        return null;
    }

    final XMLStreamReader xsr = tmpxsr;
    return new PeekIterator<TaggedText>() {

        @Override
        protected TaggedText internalNext() {
            ArrayList<TextSpan> openMarks = new ArrayList<>();
            StringBuilder pureTextSB = new StringBuilder();
            ArrayList<TextSpan> marks = new ArrayList<>();
            marks.add(new TextSpan(null, 0, 0));
            TaggedText tt = null;

            try {
                loop: while (xsr.hasNext()) {
                    xsr.next();
                    int event = xsr.getEventType();
                    switch (event) {
                    case XMLStreamConstants.START_ELEMENT:
                        if ("articles".equals(xsr.getLocalName())) {
                        } else if ("article".equals(xsr.getLocalName())) {
                            tt = new TaggedText();
                            for (int i = 0; i < xsr.getAttributeCount(); i++) {
                                if ("id".equals(xsr.getAttributeLocalName(i))) {
                                    tt.id = xsr.getAttributeValue(i);
                                }
                                tt.info().put(xsr.getAttributeLocalName(i), xsr.getAttributeValue(i));
                            }

                        } else if ("mark".equals(xsr.getLocalName())) {
                            TextSpan tr = new TextSpan(null, pureTextSB.length(), pureTextSB.length());
                            for (int i = 0; i < xsr.getAttributeCount(); i++) {
                                tr.info().put(xsr.getAttributeLocalName(i), xsr.getAttributeValue(i));
                            }

                            openMarks.add(tr);
                        } else if ("br".equals(xsr.getLocalName())) {
                            // TODO: how to propagate tags from the input to the output?
                        } else {
                            log.warn("ignore tag " + xsr.getLocalName());
                        }
                        break;
                    case XMLStreamConstants.END_ELEMENT:
                        if ("mark".equals(xsr.getLocalName())) {

                            // search corresponding <mark ...>
                            TextSpan tr = openMarks.remove(openMarks.size() - 1);
                            if (tr == null) {
                                log.warn("markend at " + xsr.getLocation().getCharacterOffset()
                                        + " has no corresponding mark tag");
                                break;
                            }

                            tr.end = pureTextSB.length();
                            marks.add(tr);

                        } else if ("article".equals(xsr.getLocalName())) {
                            tt.text = StringUtils.stripEnd(pureTextSB.toString().trim(), " \t\n");
                            pureTextSB = new StringBuilder();

                            tt.mentions = new ArrayList<>();
                            for (TextSpan mark : marks) {

                                String entity = mark.info().get("entity");
                                if (entity == null) {
                                    entity = mark.info().get("annotation");
                                }
                                if (entity != null) {
                                    EntityMention e = new EntityMention(tt.text, mark.start, mark.end, entity);
                                    String minMention = mark.info().get("min");
                                    String mention = e.getMention();
                                    if (minMention != null && !"".equals(minMention)) {
                                        Pattern p = Pattern.compile(Pattern.quote(minMention));
                                        Matcher m = p.matcher(mention);
                                        if (m.find()) {
                                            TextSpan min = new TextSpan(e.text, e.start + m.start(),
                                                    e.start + m.end());
                                            e.min = min;
                                            if (m.find()) {
                                                log.warn("found " + minMention + " two times in \"" + mention
                                                        + "\"");
                                            }
                                        } else {
                                            String prefix = Utility.findLongestPrefix(mention, minMention);
                                            log.warn("didn't find min mention '" + minMention + "' in text '"
                                                    + mention + "', longest prefix found: '" + prefix
                                                    + "' in article " + tt.id);
                                        }
                                    }

                                    mark.info().remove("min");
                                    mark.info().remove("entity");
                                    if (mark.info().size() > 0) {
                                        e.info().putAll(mark.info());
                                    }
                                    tt.mentions.add(e);
                                }
                            }
                            openMarks.clear();
                            marks.clear();
                            break loop;
                        }
                        break;
                    case XMLStreamConstants.CHARACTERS:
                        String toadd = xsr.getText();
                        if (pureTextSB.length() == 0) {
                            toadd = StringUtils.stripStart(toadd, " \t\n");
                        }
                        if (toadd.contains("thanks")) {
                            log.info("test");
                        }
                        pureTextSB.append(toadd);
                        break;
                    }

                }
            } catch (XMLStreamException e) {
                log.error("{}", errorMessageInfo);
                throw new RuntimeException(e);
            }
            if (tt != null && tt.mentions != null) {
                tt.mentions.sort(null);
            }
            return tt;
        }
    };
}