Example usage for javax.xml.stream XMLStreamReader getElementText

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

Introduction

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

Prototype

public String getElementText() throws XMLStreamException;

Source Link

Document

Reads the content of a text-only element, an exception is thrown if this is not a text-only element.

Usage

From source file:org.apache.jackrabbit.oak.benchmark.wikipedia.WikipediaImport.java

public int importWikipedia(Session session) throws Exception {
    long start = System.currentTimeMillis();
    int count = 0;
    int code = 0;

    if (doReport) {
        System.out.format("Importing %s...%n", dump);
    }/*  w  w w .  ja va 2  s .c  om*/

    String type = "nt:unstructured";
    if (session.getWorkspace().getNodeTypeManager().hasNodeType("oak:Unstructured")) {
        type = "oak:Unstructured";
    }
    Node wikipedia = session.getRootNode().addNode("wikipedia", type);

    int levels = 0;
    if (!flat) {
        // calculate the number of levels needed, based on the rough
        // estimate that the average XML size of a page is about 1kB
        for (long pages = dump.length() / 1024; pages > 256; pages /= 256) {
            levels++;
        }
    }

    String title = null;
    String text = null;
    XMLInputFactory factory = XMLInputFactory.newInstance();
    StreamSource source;
    if (dump.getName().endsWith(".xml")) {
        source = new StreamSource(dump);
    } else {
        CompressorStreamFactory csf = new CompressorStreamFactory();
        source = new StreamSource(
                csf.createCompressorInputStream(new BufferedInputStream(new FileInputStream(dump))));
    }
    haltImport = false;
    XMLStreamReader reader = factory.createXMLStreamReader(source);
    while (reader.hasNext() && !haltImport) {
        switch (reader.next()) {
        case XMLStreamConstants.START_ELEMENT:
            if ("title".equals(reader.getLocalName())) {
                title = reader.getElementText();
            } else if ("text".equals(reader.getLocalName())) {
                text = reader.getElementText();
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            if ("page".equals(reader.getLocalName())) {
                String name = Text.escapeIllegalJcrChars(title);
                Node parent = wikipedia;
                if (levels > 0) {
                    int n = name.length();
                    for (int i = 0; i < levels; i++) {
                        int hash = name.substring(min(i, n)).hashCode();
                        parent = JcrUtils.getOrAddNode(parent, String.format("%02x", hash & 0xff));
                    }
                }
                Node page = parent.addNode(name);
                page.setProperty("title", title);
                page.setProperty("text", text);
                code += title.hashCode();
                code += text.hashCode();
                count++;
                if (count % 1000 == 0) {
                    batchDone(session, start, count);
                }

                pageAdded(title, text);
            }
            break;
        }
    }

    session.save();

    if (doReport) {
        long millis = System.currentTimeMillis() - start;
        System.out.format("Imported %d pages in %d seconds (%.2fms/page)%n", count, millis / 1000,
                (double) millis / count);
    }

    return code;
}

From source file:org.apache.syncope.client.console.widgets.reconciliation.ReconciliationReportParser.java

public static ReconciliationReport parse(final Date run, final InputStream in) throws XMLStreamException {
    XMLStreamReader streamReader = INPUT_FACTORY.createXMLStreamReader(in);
    streamReader.nextTag(); // root
    streamReader.nextTag(); // report
    streamReader.nextTag(); // reportlet

    ReconciliationReport report = new ReconciliationReport(run);

    List<Missing> missing = new ArrayList<>();
    List<Misaligned> misaligned = new ArrayList<>();
    Set<String> onSyncope = null;
    Set<String> onResource = null;

    Any user = null;/* w ww . ja v a2  s . c o  m*/
    Any group = null;
    Any anyObject = null;
    String lastAnyType = null;
    while (streamReader.hasNext()) {
        if (streamReader.isStartElement()) {
            switch (streamReader.getLocalName()) {
            case "users":
                Anys users = new Anys();
                users.setTotal(Integer.valueOf(streamReader.getAttributeValue("", "total")));
                report.setUsers(users);
                break;

            case "user":
                user = new Any();
                user.setType(AnyTypeKind.USER.name());
                user.setKey(streamReader.getAttributeValue("", "key"));
                user.setName(streamReader.getAttributeValue("", "username"));
                report.getUsers().getAnys().add(user);
                break;

            case "groups":
                Anys groups = new Anys();
                groups.setTotal(Integer.valueOf(streamReader.getAttributeValue("", "total")));
                report.setGroups(groups);
                break;

            case "group":
                group = new Any();
                group.setType(AnyTypeKind.GROUP.name());
                group.setKey(streamReader.getAttributeValue("", "key"));
                group.setName(streamReader.getAttributeValue("", "groupName"));
                report.getGroups().getAnys().add(group);
                break;

            case "anyObjects":
                lastAnyType = streamReader.getAttributeValue("", "type");
                Anys anyObjects = new Anys();
                anyObjects.setAnyType(lastAnyType);
                anyObjects.setTotal(Integer.valueOf(streamReader.getAttributeValue("", "total")));
                report.getAnyObjects().add(anyObjects);
                break;

            case "anyObject":
                anyObject = new Any();
                anyObject.setType(lastAnyType);
                anyObject.setKey(streamReader.getAttributeValue("", "key"));
                final String anyType = lastAnyType;
                IterableUtils.find(report.getAnyObjects(), new Predicate<Anys>() {

                    @Override
                    public boolean evaluate(final Anys anys) {
                        return anyType.equals(anys.getAnyType());
                    }
                }).getAnys().add(anyObject);
                break;

            case "missing":
                missing.add(new Missing(streamReader.getAttributeValue("", "resource"),
                        streamReader.getAttributeValue("", "connObjectKeyValue")));
                break;

            case "misaligned":
                misaligned.add(new Misaligned(streamReader.getAttributeValue("", "resource"),
                        streamReader.getAttributeValue("", "connObjectKeyValue"),
                        streamReader.getAttributeValue("", "name")));
                break;

            case "onSyncope":
                onSyncope = new HashSet<>();
                break;

            case "onResource":
                onResource = new HashSet<>();
                break;

            case "value":
                Set<String> set = onSyncope == null ? onResource : onSyncope;
                set.add(streamReader.getElementText());
                break;

            default:
            }
        } else if (streamReader.isEndElement()) {
            switch (streamReader.getLocalName()) {
            case "user":
                user.getMissing().addAll(missing);
                user.getMisaligned().addAll(misaligned);
                missing.clear();
                misaligned.clear();
                break;

            case "group":
                group.getMissing().addAll(missing);
                group.getMisaligned().addAll(misaligned);
                missing.clear();
                misaligned.clear();
                break;

            case "anyObject":
                anyObject.getMissing().addAll(missing);
                anyObject.getMisaligned().addAll(misaligned);
                missing.clear();
                misaligned.clear();
                break;

            case "onSyncope":
                misaligned.get(misaligned.size() - 1).getOnSyncope().addAll(onSyncope);
                onSyncope = null;
                break;

            case "onResource":
                misaligned.get(misaligned.size() - 1).getOnResource().addAll(onResource);
                onResource = null;
                break;

            default:
            }

        }

        streamReader.next();
    }

    return report;
}

From source file:org.commonjava.maven.ext.manip.util.PomPeek.java

private boolean captureValue(final String elem, final Stack<String> path, final XMLStreamReader xml)
        throws XMLStreamException {
    final String pathStr = join(path, ":");
    final String key = CAPTURED_PATHS.get(pathStr);
    if (key != null) {
        elementValues.put(key, xml.getElementText().trim());

        return true;
    } else if (MODULE_ELEM.equals(elem)) {
        modules.add(xml.getElementText().trim());
    }/*from w  ww .j  ava2 s .  c o  m*/

    return false;
}

From source file:org.commonjava.maven.galley.maven.parse.PomPeek.java

private boolean captureValue(final String elem, final Stack<String> path, final XMLStreamReader xml)
        throws XMLStreamException {
    final boolean isModule = path.contains(MODULES_ELEM) && !path.contains(PLUGINS_ELEM);

    path.push(elem);//w  w  w  .  j  av  a2 s  . com

    final String pathStr = join(path, ":");
    final String key = CAPTURED_PATHS.get(pathStr);

    if (key != null) {
        elementValues.put(key, xml.getElementText().trim());

        return true;
    } else if (captureModules && isModule) {
        modules.add(xml.getElementText().trim());
        return true;
    }

    return false;
}

From source file:org.deegree.services.wps.input.EmbeddedComplexInput.java

@Override
public InputStream getValueAsBinaryStream() {

    XMLStreamReader xmlStream = null;
    String textValue = null;//from www.j a va2  s. c o  m
    try {
        try {
            xmlStream = XMLInputFactory.newInstance().createXMLStreamReader(store.getInputStream());
        } catch (Throwable t) {
            throw new RuntimeException(t.getMessage());
        }
        XMLStreamUtils.skipStartDocument(xmlStream);
        textValue = xmlStream.getElementText();
    } catch (XMLStreamException e) {
        LOG.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage());
    } finally {
        if (xmlStream != null) {
            try {
                xmlStream.close();
            } catch (XMLStreamException e) {
                // nothing to do
            }
        }
    }

    ByteArrayInputStream is = null;

    if ("base64".equals(getEncoding())) {
        LOG.debug("Performing base64 decoding of embedded ComplexInput: " + textValue);
        is = new ByteArrayInputStream(Base64.decodeBase64(textValue));
    } else {
        LOG.warn("Unsupported encoding '" + getEncoding() + "'.");
        is = new ByteArrayInputStream(textValue.getBytes());
    }

    return is;
}

From source file:org.deegree.style.se.parser.GraphicSymbologyParser.java

private Pair<Mark, Continuation<Mark>> parseMark(XMLStreamReader in) throws XMLStreamException {
    in.require(START_ELEMENT, null, "Mark");

    Mark base = new Mark();
    Continuation<Mark> contn = null;

    in.nextTag();/*from ww w .j  a va 2 s . co m*/

    while (!(in.isEndElement() && in.getLocalName().equals("Mark"))) {
        if (in.isEndElement()) {
            in.nextTag();
        }

        if (in.getLocalName().equals("WellKnownName")) {
            String wkn = in.getElementText();
            try {
                base.wellKnown = SimpleMark.valueOf(wkn.toUpperCase());
            } catch (IllegalArgumentException e) {
                LOG.warn("Specified unsupported WellKnownName of '{}', using square instead.", wkn);
                base.wellKnown = SimpleMark.SQUARE;
            }
        } else
            sym: if (in.getLocalName().equals("OnlineResource") || in.getLocalName().equals("InlineContent")) {
                LOG.debug("Loading mark from external file.");
                Triple<InputStream, String, Continuation<StringBuffer>> pair = getOnlineResourceOrInlineContent(
                        in);
                if (pair == null) {
                    in.nextTag();
                    break sym;
                }
                InputStream is = pair.first;
                in.nextTag();

                in.require(START_ELEMENT, null, "Format");
                String format = in.getElementText();
                in.require(END_ELEMENT, null, "Format");

                in.nextTag();
                if (in.getLocalName().equals("MarkIndex")) {
                    base.markIndex = Integer.parseInt(in.getElementText());
                }

                if (is != null) {
                    try {
                        java.awt.Font font = null;
                        if (format.equalsIgnoreCase("ttf")) {
                            font = createFont(TRUETYPE_FONT, is);
                        }
                        if (format.equalsIgnoreCase("type1")) {
                            font = createFont(TYPE1_FONT, is);
                        }

                        if (format.equalsIgnoreCase("svg")) {
                            base.shape = ShapeHelper.getShapeFromSvg(is, pair.second);
                        }

                        if (font == null && base.shape == null) {
                            LOG.warn("Mark was not loaded, because the format '{}' is not supported.", format);
                            break sym;
                        }

                        if (font != null && base.markIndex >= font.getNumGlyphs() - 1) {
                            LOG.warn("The font only contains {} glyphs, but the index given was {}.",
                                    font.getNumGlyphs(), base.markIndex);
                            break sym;
                        }

                        base.font = font;
                    } catch (FontFormatException e) {
                        LOG.debug("Stack trace:", e);
                        LOG.warn("The file was not a valid '{}' file: '{}'", format, e.getLocalizedMessage());
                    } catch (IOException e) {
                        LOG.debug("Stack trace:", e);
                        LOG.warn("The file could not be read: '{}'.", e.getLocalizedMessage());
                    } finally {
                        closeQuietly(is);
                    }
                }
            } else if (in.getLocalName().equals("Fill")) {
                final Pair<Fill, Continuation<Fill>> fill = context.fillParser.parseFill(in);
                base.fill = fill.first;
                if (fill.second != null) {
                    contn = new Continuation<Mark>(contn) {
                        @Override
                        public void updateStep(Mark base, Feature f, XPathEvaluator<Feature> evaluator) {
                            fill.second.evaluate(base.fill, f, evaluator);
                        }
                    };
                }
            } else if (in.getLocalName().equals("Stroke")) {
                final Pair<Stroke, Continuation<Stroke>> stroke = context.strokeParser.parseStroke(in);
                base.stroke = stroke.first;
                if (stroke.second != null) {
                    contn = new Continuation<Mark>(contn) {
                        @Override
                        public void updateStep(Mark base, Feature f, XPathEvaluator<Feature> evaluator) {
                            stroke.second.evaluate(base.stroke, f, evaluator);
                        }
                    };
                }
            } else if (in.isStartElement()) {
                Location loc = in.getLocation();
                LOG.error("Found unknown element '{}' at line {}, column {}, skipping.",
                        new Object[] { in.getLocalName(), loc.getLineNumber(), loc.getColumnNumber() });
                skipElement(in);
            }
    }

    in.require(END_ELEMENT, null, "Mark");

    return new Pair<Mark, Continuation<Mark>>(base, contn);
}

From source file:org.deegree.style.se.parser.GraphicSymbologyParser.java

private Triple<BufferedImage, String, Continuation<List<BufferedImage>>> parseExternalGraphic(
        final XMLStreamReader in) throws IOException, XMLStreamException {
    // TODO color replacement

    in.require(START_ELEMENT, null, "ExternalGraphic");

    String format = null;//from w w  w. j a va2  s  .  co m
    BufferedImage img = null;
    String url = null;
    Triple<InputStream, String, Continuation<StringBuffer>> pair = null;
    Continuation<List<BufferedImage>> contn = null; // needs to be list to be updateable by reference...

    while (!(in.isEndElement() && in.getLocalName().equals("ExternalGraphic"))) {
        in.nextTag();

        if (in.getLocalName().equals("Format")) {
            format = in.getElementText();
        } else if (in.getLocalName().equals("OnlineResource") || in.getLocalName().equals("InlineContent")) {
            pair = getOnlineResourceOrInlineContent(in);
        } else if (in.isStartElement()) {
            Location loc = in.getLocation();
            LOG.error("Found unknown element '{}' at line {}, column {}, skipping.",
                    new Object[] { in.getLocalName(), loc.getLineNumber(), loc.getColumnNumber() });
            skipElement(in);
        }
    }

    try {
        if (pair != null) {
            if (pair.first != null && format != null && (format.toLowerCase().indexOf("svg") == -1)) {
                img = ImageIO.read(pair.first);
            }
            url = pair.second;

            final Continuation<StringBuffer> sbcontn = pair.third;

            if (pair.third != null) {
                final LinkedHashMap<String, BufferedImage> cache = new LinkedHashMap<String, BufferedImage>(
                        256) {
                    private static final long serialVersionUID = -6847956873232942891L;

                    @Override
                    protected boolean removeEldestEntry(Map.Entry<String, BufferedImage> eldest) {
                        return size() > 256; // yeah, hardcoded max size... TODO
                    }
                };
                contn = new Continuation<List<BufferedImage>>() {
                    @Override
                    public void updateStep(List<BufferedImage> base, Feature f,
                            XPathEvaluator<Feature> evaluator) {
                        StringBuffer sb = new StringBuffer();
                        sbcontn.evaluate(sb, f, evaluator);
                        String file = sb.toString();
                        if (cache.containsKey(file)) {
                            base.add(cache.get(file));
                            return;
                        }
                        try {
                            BufferedImage i;
                            if (context.location != null) {
                                i = ImageIO.read(context.location.resolve(file));
                            } else {
                                i = ImageIO.read(resolve(file, in));
                            }
                            base.add(i);
                            cache.put(file, i);
                        } catch (MalformedURLException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                };
            }
        }
    } finally {
        if (pair != null) {
            try {
                pair.first.close();
            } catch (Exception e) {
                LOG.trace("Stack trace when closing input stream:", e);
            }
        }
    }

    return new Triple<BufferedImage, String, Continuation<List<BufferedImage>>>(img, url, contn);
}

From source file:org.deegree.style.se.parser.GraphicSymbologyParser.java

private Triple<InputStream, String, Continuation<StringBuffer>> getOnlineResourceOrInlineContent(
        XMLStreamReader in) throws XMLStreamException {
    if (in.getLocalName().equals("OnlineResource")) {
        String str = in.getAttributeValue(XLNNS, "href");

        if (str == null) {
            Continuation<StringBuffer> contn = context.parser.updateOrContinue(in, "OnlineResource",
                    new StringBuffer(), SBUPDATER, null).second;
            return new Triple<InputStream, String, Continuation<StringBuffer>>(null, null, contn);
        }//from   w  ww .  j  a  v  a  2  s .com

        String strUrl = null;
        try {
            URL url;
            if (context.location != null) {
                url = context.location.resolveToUrl(str);
            } else {
                url = resolve(str, in);
            }
            strUrl = url.toExternalForm();
            LOG.debug("Loading from URL '{}'", url);
            in.nextTag();
            return new Triple<InputStream, String, Continuation<StringBuffer>>(url.openStream(), strUrl, null);
        } catch (IOException e) {
            LOG.debug("Stack trace:", e);
            LOG.warn("Could not retrieve content at URL '{}'.", str);
            return null;
        }
    } else if (in.getLocalName().equals("InlineContent")) {
        String format = in.getAttributeValue(null, "encoding");
        if (format.equalsIgnoreCase("base64")) {
            ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decodeBase64(in.getElementText()));
            return new Triple<InputStream, String, Continuation<StringBuffer>>(bis, null, null);
        }
        // if ( format.equalsIgnoreCase( "xml" ) ) {
        // // TODO
        // }
    } else if (in.isStartElement()) {
        Location loc = in.getLocation();
        LOG.error("Found unknown element '{}' at line {}, column {}, skipping.",
                new Object[] { in.getLocalName(), loc.getLineNumber(), loc.getColumnNumber() });
        skipElement(in);
    }

    return null;
}

From source file:org.eclipse.koneki.protocols.omadm.client.basic.DMBasicSession.java

private void readSyncHdr(final XMLStreamReader reader) throws XMLStreamException {
    jumpToStartTag(reader, "MsgID"); //$NON-NLS-1$

    this.currentServerMsgID = reader.getElementText();

    jumpToStartTag(reader, "RespURI"); //$NON-NLS-1$
    try {/*  w ww  .j  ava  2s.  c  o m*/
        String newServer = reader.getElementText();
        if (newServer != null) {
            server = new URI(newServer);
        }
    } catch (URISyntaxException e) {
        Activator.logError("Malformed RespURI in sync header", e); //$NON-NLS-1$
    }

    jumpToEndTag(reader, "SyncHdr"); //$NON-NLS-1$

    this.statusManager.putStatus(this.currentServerMsgID, "0", "SyncHdr", null, null, //$NON-NLS-1$ //$NON-NLS-2$
            String.valueOf(StatusCode.AUTHENTICATION_ACCEPTED.getCode()));
}

From source file:org.eclipse.koneki.protocols.omadm.client.basic.DMBasicSession.java

private void readAlert(final XMLStreamReader reader) throws XMLStreamException {
    /*//from  w ww.  java2s.  com
     * TODO : Manage Alert commands
     */
    reader.nextTag();
    // CmdID
    final String cmdID = reader.getElementText();
    reader.nextTag();

    this.statusManager.putStatus(this.currentServerMsgID, cmdID, "Alert", null, null, "406"); //$NON-NLS-1$ //$NON-NLS-2$

    jumpToEndTag(reader, "Alert"); //$NON-NLS-1$
}