Example usage for javax.xml.stream XMLStreamReader getLocalName

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

Introduction

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

Prototype

public String getLocalName();

Source Link

Document

Returns the (local) name of the current event.

Usage

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);
            }/*  ww w  .j  ava 2s  . c  o 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:org.xwiki.filter.xar.internal.input.DocumentLocaleReader.java

private void readDocument(XMLStreamReader xmlReader, Object filter, XARInputFilter proxyFilter)
        throws XMLStreamException, FilterException {
    this.currentSourceType = SourceType.DOCUMENT;

    // Initialize with a few defaults (thing that don't exist in old XAR format)
    this.currentDocumentRevisionParameters.put(XWikiWikiDocumentFilter.PARAMETER_SYNTAX, Syntax.XWIKI_1_0);
    this.currentDocumentRevisionParameters.put(XWikiWikiDocumentFilter.PARAMETER_HIDDEN, false);

    // Reference//from  w w  w .jav a 2  s  . c o m
    String referenceString = xmlReader.getAttributeValue(null, XARDocumentModel.ATTRIBUTE_DOCUMENT_REFERENCE);
    if (StringUtils.isNotEmpty(referenceString)) {
        this.currentDocumentReference = this.relativeResolver.resolve(referenceString, EntityType.DOCUMENT);
        this.currentSpaceReference = this.currentDocumentReference.getParent();

        // Send needed wiki spaces event if possible
        switchWikiSpace(proxyFilter, false);
    }

    // Locale
    String localeString = xmlReader.getAttributeValue(null, XARDocumentModel.ATTRIBUTE_DOCUMENT_LOCALE);
    if (localeString != null) {
        this.currentDocumentLocale = toLocale(localeString);
        this.localeFromLegacy = false;
    }

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

        if (elementName.equals(XARAttachmentModel.ELEMENT_ATTACHMENT)) {
            readAttachment(xmlReader, filter, proxyFilter);
        } else if (elementName.equals(XARObjectModel.ELEMENT_OBJECT)) {
            readObject(xmlReader, filter, proxyFilter);
        } else if (elementName.equals(XARClassModel.ELEMENT_CLASS)) {
            readClass(xmlReader, filter, proxyFilter);
        } else {
            String value = xmlReader.getElementText();

            if (XarDocumentModel.ELEMENT_SPACE.equals(elementName)) {
                this.currentLegacySpace = value;

                if (this.currentDocumentReference == null) {
                    // Its an old thing
                    if (this.currentLegacyDocument == null) {
                        this.currentSpaceReference = new EntityReference(value, EntityType.SPACE);
                    } else {
                        this.currentDocumentReference = new LocalDocumentReference(this.currentLegacySpace,
                                this.currentLegacyDocument);
                        this.currentSpaceReference = this.currentDocumentReference.getParent();
                    }

                    // Send needed wiki spaces event if possible
                    switchWikiSpace(proxyFilter, false);
                }
            } else if (XarDocumentModel.ELEMENT_NAME.equals(elementName)) {
                this.currentLegacyDocument = value;

                if (this.currentDocumentReference == null) {
                    // Its an old thing
                    if (this.currentLegacySpace != null) {
                        this.currentDocumentReference = new LocalDocumentReference(this.currentLegacySpace,
                                this.currentLegacyDocument);
                        this.currentSpaceReference = this.currentDocumentReference.getParent();
                    }
                }
            } else if (XarDocumentModel.ELEMENT_LOCALE.equals(elementName)) {
                if (this.localeFromLegacy) {
                    this.currentDocumentLocale = toLocale(value);
                }
            } else if (XarDocumentModel.ELEMENT_REVISION.equals(elementName)) {
                this.currentDocumentRevision = value;
            } else {
                EventParameter parameter = XARDocumentModel.DOCUMENT_PARAMETERS.get(elementName);

                if (parameter != null) {
                    Object wsValue = convert(parameter.type, value);
                    if (wsValue != null) {
                        this.currentDocumentParameters.put(parameter.name, wsValue);
                    }
                } else {
                    parameter = XARDocumentModel.DOCUMENTLOCALE_PARAMETERS.get(elementName);

                    if (parameter != null) {
                        Object wsValue = convert(parameter.type, value);
                        if (wsValue != null) {
                            this.currentDocumentLocaleParameters.put(parameter.name, wsValue);
                        }
                    } else {
                        parameter = XARDocumentModel.DOCUMENTREVISION_PARAMETERS.get(elementName);

                        if (parameter != null) {
                            Object objectValue;
                            if (parameter.type == EntityReference.class) {
                                objectValue = this.relativeResolver.resolve(value, EntityType.DOCUMENT);
                            } else {
                                objectValue = convert(parameter.type, value);
                            }

                            if (objectValue != null) {
                                this.currentDocumentRevisionParameters.put(parameter.name, objectValue);
                            }
                        } else {
                            // Unknown property
                            // TODO: log something ?
                        }
                    }
                }
            }
        }
    }

    sendBeginWikiDocumentRevision(proxyFilter, true);
    sendWikiAttachments(proxyFilter);
    sendWikiClass(proxyFilter);
    sendWikiObjects(proxyFilter);
    sendEndWikiDocument(proxyFilter);
}

From source file:org.xwiki.store.filesystem.internal.migration.R910100XWIKI14871DataMigration.java

private void migrateMetadatas(Session session) throws IOException, XMLStreamException,
        FactoryConfigurationError, ParserConfigurationException, SAXException {
    this.logger.info("Migrating filesystem attachment metadatas storded in [{}]",
            this.fstools.getStorageLocationFile());

    File pathByIdStore = this.fstools.getGlobalFile("DELETED_ATTACHMENT_ID_MAPPINGS.xml");
    if (pathByIdStore.exists()) {
        try (FileInputStream stream = new FileInputStream(pathByIdStore)) {
            XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(stream);

            // <deletedattachmentids>
            xmlReader.nextTag();/*ww  w . j  ava 2s.  c om*/

            for (xmlReader.nextTag(); xmlReader.isStartElement(); xmlReader.nextTag()) {
                // <entry>
                xmlReader.nextTag();

                String value1 = xmlReader.getElementText();
                xmlReader.nextTag();
                String value2 = xmlReader.getElementText();

                long id;
                String path;
                if (xmlReader.getLocalName().equals("path")) {
                    id = Long.valueOf(value1);
                    path = value2;
                } else {
                    id = Long.valueOf(value2);
                    path = value1;
                }

                // </entry>
                xmlReader.nextTag();

                File directory = new File(path);
                if (!directory.exists()) {
                    this.logger.warn("[{}] does not exist", directory);

                    continue;
                }

                if (!directory.isDirectory()) {
                    this.logger.warn("[{}] is not a directory", directory);

                    continue;
                }

                storeDeletedAttachment(directory, id, session);
            }
        }
    }
}

From source file:org.xwiki.wikistream.confluence.xml.internal.ConfluenceXMLPackage.java

private void createTree() throws XMLStreamException, FactoryConfigurationError, NumberFormatException,
        IOException, ConfigurationException, WikiStreamException {
    this.tree = new File(this.directory, "tree");
    this.tree.mkdir();

    InputStream stream = new FileInputStream(getEntities());

    XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(stream);

    xmlReader.nextTag();/*from w  ww  .j a  va 2  s.  c  om*/

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

        if (elementName.equals("object")) {
            readObject(xmlReader);
        } else {
            StAXUtils.skipElement(xmlReader);
        }
    }
}

From source file:org.xwiki.wikistream.confluence.xml.internal.ConfluenceXMLPackage.java

private int readObjectProperties(XMLStreamReader xmlReader, PropertiesConfiguration properties)
        throws XMLStreamException, WikiStreamException, ConfigurationException, IOException {
    int id = -1;/*from   w ww.  j  a va2  s  .c o  m*/

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

        if (elementName.equals("id")) {
            id = Integer.valueOf(xmlReader.getElementText());

            properties.setProperty("id", id);
        } else if (elementName.equals("property")) {
            String propertyName = xmlReader.getAttributeValue(null, "name");

            properties.setProperty(propertyName, readProperty(xmlReader));
        } else if (elementName.equals("collection")) {
            String propertyName = xmlReader.getAttributeValue(null, "name");

            properties.setProperty(propertyName, readProperty(xmlReader));
        } else {
            StAXUtils.skipElement(xmlReader);
        }
    }

    return id;
}

From source file:org.xwiki.wikistream.confluence.xml.internal.ConfluenceXMLPackage.java

private Integer readIdProperty(XMLStreamReader xmlReader) throws WikiStreamException, XMLStreamException {
    xmlReader.nextTag();//w  w w . ja va2  s. co  m

    if (!xmlReader.getLocalName().equals("id")) {
        throw new WikiStreamException(
                String.format("Was expecting id element but found [%s]", xmlReader.getLocalName()));
    }

    Integer value = Integer.valueOf(xmlReader.getElementText());

    xmlReader.nextTag();

    return value;
}

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

public WikiAttachment read(XMLStreamReader xmlReader) throws XMLStreamException, WikiStreamException {
    WikiAttachment wikiAttachment = new WikiAttachment();

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

        String value = xmlReader.getElementText();

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

        if (parameter != null) {
            Object wsValue = convert(parameter.type, value);
            if (wsValue != null) {
                wikiAttachment.parameters.put(parameter.name, wsValue);
            }//w w  w  .  j  a v a 2  s  .  c o m
        } else {
            if (XARAttachmentModel.ELEMENT_NAME.equals(elementName)) {
                wikiAttachment.name = value;
            } else if (XARAttachmentModel.ELEMENT_CONTENT.equals(elementName)) {
                wikiAttachment.content = Base64.decodeBase64(value.getBytes());
            }
        }
    }

    return wikiAttachment;
}

From source file:org.xwiki.xar.internal.XarUtils.java

/**
 * Extract {@link LocalDocumentReference} from a XAR document XML stream.
 * /*from   w  ww  .java  2  s.  com*/
 * @param documentStream the stream to parse
 * @return the reference extracted from the stream
 * @throws XarException when failing to parse the document stream
 * @since 5.4M1
 */
public static LocalDocumentReference getReference(InputStream documentStream) throws XarException {
    XMLStreamReader xmlReader;
    try {
        xmlReader = XML_INPUT_FACTORY.createXMLStreamReader(documentStream);
    } catch (XMLStreamException e) {
        throw new XarException("Failed to create a XML read", e);
    }

    EntityReference reference = null;
    Locale locale = null;

    String legacySpace = null;
    String legacyPage = null;

    try {
        // <xwikidoc>

        xmlReader.nextTag();

        xmlReader.require(XMLStreamReader.START_ELEMENT, null, XarDocumentModel.ELEMENT_DOCUMENT);

        // Reference
        String referenceString = xmlReader.getAttributeValue(null,
                XarDocumentModel.ATTRIBUTE_DOCUMENT_REFERENCE);
        if (referenceString != null) {
            reference = RESOLVER.resolve(referenceString, EntityType.DOCUMENT);
        }

        // Locale
        String localeString = xmlReader.getAttributeValue(null, XarDocumentModel.ATTRIBUTE_DOCUMENT_LOCALE);
        if (localeString != null) {
            if (localeString.isEmpty()) {
                locale = Locale.ROOT;
            } else {
                locale = LocaleUtils.toLocale(localeString);
            }
        }

        // Legacy fallback
        if (reference == null || locale == null) {
            for (xmlReader.nextTag(); xmlReader.isStartElement(); xmlReader.nextTag()) {
                String elementName = xmlReader.getLocalName();

                if (XarDocumentModel.ELEMENT_NAME.equals(elementName)) {
                    if (reference == null) {
                        legacyPage = xmlReader.getElementText();

                        if (legacySpace != null && locale != null) {
                            break;
                        }
                    } else if (locale != null) {
                        break;
                    }
                } else if (XarDocumentModel.ELEMENT_SPACE.equals(elementName)) {
                    if (reference == null) {
                        legacySpace = xmlReader.getElementText();

                        if (legacyPage != null && locale != null) {
                            break;
                        }
                    } else if (locale != null) {
                        break;
                    }
                } else if (XarDocumentModel.ELEMENT_LOCALE.equals(elementName)) {
                    if (locale == null) {
                        String value = xmlReader.getElementText();
                        if (value.length() == 0) {
                            locale = Locale.ROOT;
                        } else {
                            locale = LocaleUtils.toLocale(value);
                        }
                    }

                    if (reference != null || (legacySpace != null && legacyPage != null)) {
                        break;
                    }
                } else {
                    StAXUtils.skipElement(xmlReader);
                }
            }
        }
    } catch (XMLStreamException e) {
        throw new XarException("Failed to parse document", e);
    } finally {
        try {
            xmlReader.close();
        } catch (XMLStreamException e) {
            throw new XarException("Failed to close XML reader", e);
        }
    }

    if (reference == null) {
        if (legacySpace == null) {
            throw new XarException("Missing space element");
        }
        if (legacyPage == null) {
            throw new XarException("Missing page element");
        }

        reference = new LocalDocumentReference(legacySpace, legacyPage);
    }

    if (locale == null) {
        throw new XarException("Missing locale element");
    }

    return new LocalDocumentReference(reference, locale);
}

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  v  a  2s  . c  om
    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);/*from   w  w  w.  j  a  v a2 s  .c o 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;
}