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.deegree.services.csw.exporthandling.GetCapabilitiesHelper.java

private void writeTemplateElement(XMLStreamWriter writer, XMLStreamReader inStream,
        Map<String, String> varToValue) throws XMLStreamException {

    if (inStream.getEventType() != XMLStreamConstants.START_ELEMENT) {
        throw new XMLStreamException("Input stream does not point to a START_ELEMENT event.");
    }//www  . ja  va 2s  .com
    int openElements = 0;
    boolean firstRun = true;
    while (firstRun || openElements > 0) {
        firstRun = false;
        int eventType = inStream.getEventType();

        switch (eventType) {
        case CDATA: {
            writer.writeCData(inStream.getText());
            break;
        }
        case CHARACTERS: {
            String s = new String(inStream.getTextCharacters(), inStream.getTextStart(),
                    inStream.getTextLength());
            // TODO optimize
            for (String param : varToValue.keySet()) {
                String value = varToValue.get(param);
                s = s.replace(param, value);
            }
            writer.writeCharacters(s);

            break;
        }
        case END_ELEMENT: {
            writer.writeEndElement();
            openElements--;
            break;
        }
        case START_ELEMENT: {
            if (inStream.getNamespaceURI() == "" || inStream.getPrefix() == DEFAULT_NS_PREFIX
                    || inStream.getPrefix() == null) {
                writer.writeStartElement(inStream.getLocalName());
            } else {
                if (writer.getNamespaceContext().getPrefix(inStream.getPrefix()) == "") {
                    // TODO handle special cases for prefix binding, see
                    // http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/javax/xml/namespace/NamespaceContext.html#getNamespaceURI(java.lang.String)
                    writer.setPrefix(inStream.getPrefix(), inStream.getNamespaceURI());
                }
                writer.writeStartElement(inStream.getPrefix(), inStream.getLocalName(),
                        inStream.getNamespaceURI());
            }
            // copy all namespace bindings
            for (int i = 0; i < inStream.getNamespaceCount(); i++) {
                String nsPrefix = inStream.getNamespacePrefix(i);
                String nsURI = inStream.getNamespaceURI(i);
                writer.writeNamespace(nsPrefix, nsURI);
            }

            // copy all attributes
            for (int i = 0; i < inStream.getAttributeCount(); i++) {
                String localName = inStream.getAttributeLocalName(i);
                String nsPrefix = inStream.getAttributePrefix(i);
                String value = inStream.getAttributeValue(i);
                String nsURI = inStream.getAttributeNamespace(i);
                if (nsURI == null) {
                    writer.writeAttribute(localName, value);
                } else {
                    writer.writeAttribute(nsPrefix, nsURI, localName, value);
                }
            }

            openElements++;
            break;
        }
        default: {
            break;
        }
        }
        if (openElements > 0) {
            inStream.next();
        }
    }
}

From source file:org.deegree.services.wps.execute.ExecuteResponseXMLWriter.java

private static void exportXMLOutput(XMLStreamWriter writer, ComplexOutputImpl output)
        throws XMLStreamException {

    // "wps:ComplexData" element
    writer.writeStartElement(WPS_NS, "ComplexData");

    String mimeType = output.getRequestedMimeType();
    if (mimeType != null) {
        writer.writeAttribute("mimeType", mimeType);
    }//from   w w  w  . j  a va  2 s.c om

    String schema = output.getRequestedSchema();
    if (schema != null) {
        writer.writeAttribute("schema", schema);
    }

    // NOTE: Providing the encoding attribute doesn't make any sense for inline XML output (always defined by the
    // surrounding document)

    XMLStreamReader reader = output.getStreamReader();

    // skip start document event
    // apadberg: the following line was necessary when Axiom 1.2.8 is used,
    // it is commented out because of revised behavior in Axiom 1.2.9
    if (reader.getEventType() == XMLStreamConstants.START_DOCUMENT) {
        reader.next();
    }

    if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) {
        XMLAdapter.writeElement(writer, reader);
    } else {
        LOG.warn("No element in XMLOutput found, skipping it in response document.");
    }

    writer.writeEndElement();
}

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

private static Continuation<Styling<?>> getContn(String text, Continuation<Styling<?>> contn,
        final Updater<Styling<?>> updater) {
    XMLInputFactory fac = XMLInputFactory.newInstance();
    Expression expr;//from   w w w. j  a v  a 2 s . com
    try {
        XMLStreamReader reader = fac.createXMLStreamReader(new StringReader(text));
        reader.next();
        expr = Filter110XMLDecoder.parseExpression(reader);
    } catch (XMLParsingException e) {
        String[] ss = text.split("}");
        expr = new ValueReference(new QName(ss[0].substring(1), ss[1]));
    } catch (XMLStreamException e) {
        String[] ss = text.split("}");
        expr = new ValueReference(new QName(ss[0].substring(1), ss[1]));
    }
    final Expression expr2 = expr;
    return new Continuation<Styling<?>>(contn) {
        @Override
        public void updateStep(Styling<?> base, Feature obj, XPathEvaluator<Feature> evaluator) {
            try {
                Object[] evald = expr2.evaluate(obj, evaluator);
                if (evald.length == 0) {
                    LOG.warn("The following expression in a style evaluated to null:\n{}", expr2);
                } else {
                    updater.update(base, evald[0].toString());
                }
            } catch (FilterEvaluationException e) {
                LOG.warn("Evaluating the following expression resulted in an error '{}':\n{}",
                        e.getLocalizedMessage(), expr2);
            }
        }
    };
}

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

/**
 * @param id/*from  ww w .  j av a  2s  . co  m*/
 * @return the corresponding style from the database
 */
public synchronized Style getStyle(int id) {
    Style style = pool.get(id);
    if (style != null) {
        return style;
    }

    XMLInputFactory fac = XMLInputFactory.newInstance();

    PreparedStatement stmt = null;
    ResultSet rs = null;
    Connection conn = null;
    try {
        conn = connProvider.getConnection();
        stmt = conn.prepareStatement(
                "select type, fk, minscale, maxscale, sld, name from " + schema + ".styles where id = ?");
        stmt.setInt(1, id);
        LOG.debug("Fetching styles using query '{}'.", stmt);
        rs = stmt.executeQuery();
        if (rs.next()) {
            String type = rs.getString("type");
            int key = rs.getInt("fk");
            String name = rs.getString("name");

            if (type != null) {
                final Symbolizer<?> sym;
                switch (Type.valueOf(type.toUpperCase())) {
                case LINE:
                    Pair<LineStyling, Continuation<LineStyling>> lpair = getLineStyling(key, conn);
                    if (lpair.second != null) {
                        sym = new Symbolizer<LineStyling>(lpair.first, lpair.second, null, null, null, -1, -1);
                    } else {
                        sym = new Symbolizer<LineStyling>(lpair.first, null, null, null, -1, -1);
                    }
                    break;
                case POINT:
                    Pair<PointStyling, Continuation<PointStyling>> pair = getPointStyling(key, conn);
                    if (pair.second != null) {
                        sym = new Symbolizer<PointStyling>(pair.first, pair.second, null, null, null, -1, -1);
                    } else {
                        sym = new Symbolizer<PointStyling>(pair.first, null, null, null, -1, -1);
                    }
                    break;
                case POLYGON:
                    Pair<PolygonStyling, Continuation<PolygonStyling>> ppair = getPolygonStyling(key, conn);
                    if (ppair.second != null) {
                        sym = new Symbolizer<PolygonStyling>(ppair.first, ppair.second, null, null, null, -1,
                                -1);
                    } else {
                        sym = new Symbolizer<PolygonStyling>(ppair.first, null, null, null, -1, -1);
                    }
                    break;
                case TEXT:
                    Triple<TextStyling, Continuation<TextStyling>, String> p = getTextStyling(key, conn);
                    XMLStreamReader reader = fac.createXMLStreamReader(new StringReader(p.third));
                    reader.next();
                    final Expression expr = Filter110XMLDecoder.parseExpression(reader);
                    if (p.second != null) {
                        sym = new Symbolizer<TextStyling>(p.first, p.second, null, null, null, -1, -1);
                    } else {
                        sym = new Symbolizer<TextStyling>(p.first, null, null, null, -1, -1);
                    }
                    labels.put((Symbolizer) sym, new Continuation<StringBuffer>() {
                        @Override
                        public void updateStep(StringBuffer base, Feature f,
                                XPathEvaluator<Feature> evaluator) {
                            try {
                                Object[] evald = expr.evaluate(f, evaluator);
                                if (evald.length == 0) {
                                    LOG.warn("The following expression in a style evaluated to null:\n{}",
                                            expr);
                                } else {
                                    base.append(evald[0]);
                                }
                            } catch (FilterEvaluationException e) {
                                LOG.warn("Evaluating the following expression resulted in an error '{}':\n{}",
                                        e.getLocalizedMessage(), expr);
                            }
                        }
                    });
                    break;
                default:
                    sym = null;
                    break;
                }

                LinkedList<Pair<Continuation<LinkedList<Symbolizer<?>>>, DoublePair>> rules = new LinkedList<Pair<Continuation<LinkedList<Symbolizer<?>>>, DoublePair>>();

                DoublePair scale = new DoublePair(NEGATIVE_INFINITY, POSITIVE_INFINITY);
                Double min = (Double) rs.getObject("minscale");
                if (min != null) {
                    scale.first = min;
                }
                Double max = (Double) rs.getObject("maxscale");
                if (max != null) {
                    scale.second = max;
                }

                Continuation<LinkedList<Symbolizer<?>>> contn = new Continuation<LinkedList<Symbolizer<?>>>() {
                    @Override
                    public void updateStep(LinkedList<Symbolizer<?>> base, Feature f,
                            XPathEvaluator<Feature> evaluator) {
                        base.add(sym);
                    }
                };
                rules.add(new Pair<Continuation<LinkedList<Symbolizer<?>>>, DoublePair>(contn, scale));

                Style result = new Style(rules, labels, null, name == null ? ("" + id) : name, null);
                pool.put(id, result);
                return result;
            }
            String sld = rs.getString("sld");
            if (sld != null) {
                try {
                    Style res = new SymbologyParser()
                            .parse(fac.createXMLStreamReader(baseSystemId, new StringReader(sld)));
                    if (name != null) {
                        res.setName(name);
                    }
                    pool.put(id, res);
                    return res;
                } catch (XMLStreamException e) {
                    LOG.debug("Could not parse SLD snippet for id '{}', error was '{}'", id,
                            e.getLocalizedMessage());
                    LOG.trace("Stack trace:", e);
                } catch (FactoryConfigurationError e) {
                    LOG.debug("Could not parse SLD snippet for id '{}', error was '{}'", id,
                            e.getLocalizedMessage());
                    LOG.trace("Stack trace:", e);
                }
            }

            LOG.debug("For style id '{}', no SLD snippet was found and no symbolizer referenced.", id);
        }
        return null;
    } catch (Throwable e) {
        LOG.info("Unable to read style from DB: '{}'.", e.getLocalizedMessage());
        LOG.trace("Stack trace:", e);
        return null;
    } finally {
        JDBCUtils.close(rs, stmt, conn, LOG);
    }
}

From source file:org.deegree.tools.rendering.viewer.File3dImporter.java

public static List<WorldRenderableObject> open(Frame parent, String fileName) {

    if (fileName == null || "".equals(fileName.trim())) {
        throw new InvalidParameterException("the file name may not be null or empty");
    }/*from   w w  w  . jav a2 s.  c o m*/
    fileName = fileName.trim();

    CityGMLImporter openFile2;
    XMLInputFactory fac = XMLInputFactory.newInstance();
    InputStream in = null;
    try {
        XMLStreamReader reader = fac.createXMLStreamReader(in = new FileInputStream(fileName));
        reader.next();
        String ns = "http://www.opengis.net/citygml/1.0";
        openFile2 = new CityGMLImporter(null, null, null, reader.getNamespaceURI().equals(ns));
    } catch (Throwable t) {
        openFile2 = new CityGMLImporter(null, null, null, false);
    } finally {
        IOUtils.closeQuietly(in);
    }

    final CityGMLImporter openFile = openFile2;

    final JDialog dialog = new JDialog(parent, "Loading", true);

    dialog.getContentPane().setLayout(new BorderLayout());
    dialog.getContentPane().add(
            new JLabel("<HTML>Loading file:<br>" + fileName + "<br>Please wait!</HTML>", SwingConstants.CENTER),
            BorderLayout.NORTH);
    final JProgressBar progressBar = new JProgressBar();
    progressBar.setStringPainted(true);
    progressBar.setIndeterminate(false);
    dialog.getContentPane().add(progressBar, BorderLayout.CENTER);

    dialog.pack();
    dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
    dialog.setResizable(false);
    dialog.setLocationRelativeTo(parent);

    final Thread openThread = new Thread() {
        /**
         * Opens the file in a separate thread.
         */
        @Override
        public void run() {
            // openFile.openFile( progressBar );
            if (dialog.isDisplayable()) {
                dialog.setVisible(false);
                dialog.dispose();
            }
        }
    };
    openThread.start();

    dialog.setVisible(true);
    List<WorldRenderableObject> result = null;
    try {
        result = openFile.importFromFile(fileName, 6, 2);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    gm = openFile.getQmList();

    //
    // if ( result != null ) {
    // openGLEventListener.addDataObjectToScene( result );
    // File f = new File( fileName );
    // setTitle( WIN_TITLE + f.getName() );
    // } else {
    // showExceptionDialog( "The file: " + fileName
    // + " could not be read,\nSee error log for detailed information." );
    // }
    return result;
}

From source file:org.deegree.workspace.standard.DefaultResourceLocation.java

@Override
public String getNamespace() {
    InputStream fis = null;/*from w ww .j  a  v a 2 s  .co  m*/
    XMLStreamReader in = null;
    try {
        in = XMLInputFactory.newInstance().createXMLStreamReader(fis = getAsStream());
        while (!in.isStartElement()) {
            in.next();
        }
        return in.getNamespaceURI();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        IOUtils.closeQuietly(fis);
    }
    return null;
}

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

private DMMeta readMeta(final XMLStreamReader reader) throws XMLStreamException {
    final DMMeta meta = new DMMeta();
    boolean continueMeta = true;
    do {//from   w  ww.j ava  2 s . c  o  m
        switch (reader.next()) {
        case XMLEvent.START_ELEMENT:
            switch (DMMeta.getKey(reader.getLocalName())) {
            case DMMeta.FORMAT:
                meta.put(DMMeta.FORMAT, reader.getElementText());
                break;
            case DMMeta.TYPE:
                meta.put(DMMeta.TYPE, reader.getElementText());
                break;
            default:
                break;
            }
            break;
        case XMLEvent.END_ELEMENT:
            continueMeta = false;
            break;
        default:
            break;
        }
    } while (continueMeta);

    return meta;
}

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

private static void jumpToStartTag(final XMLStreamReader reader, final String tag) throws XMLStreamException {
    while (reader.next() != XMLStreamReader.START_ELEMENT || !reader.getLocalName().equals(tag)) {
        continue;
    }//  www  .  j av  a2 s.c o  m
}

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

private static void jumpToEndTag(final XMLStreamReader reader, final String tag) throws XMLStreamException {
    while (reader.next() != XMLStreamReader.END_ELEMENT || !reader.getLocalName().equals(tag)) {
        continue;
    }// w  w w  . j  a v  a 2  s.co m
}

From source file:org.eclipse.sw360.licenseinfo.parsers.AbstractCLIParser.java

protected <T> boolean hasThisXMLRootElement(AttachmentContent content, String rootElementNamespace,
        String rootElementName, User user, T context) throws TException {
    XMLInputFactory xmlif = XMLInputFactory.newFactory();
    XMLStreamReader xmlStreamReader = null;
    InputStream attachmentStream = null;
    try {//from www  .j  a v a 2s  . co  m
        attachmentStream = attachmentConnector.getAttachmentStream(content, user, context);
        xmlStreamReader = xmlif.createXMLStreamReader(attachmentStream);

        //skip to first element
        while (xmlStreamReader.hasNext() && xmlStreamReader.next() != XMLStreamConstants.START_ELEMENT)
            ;
        xmlStreamReader.require(XMLStreamConstants.START_ELEMENT, rootElementNamespace, rootElementName);
        return true;
    } catch (XMLStreamException | SW360Exception e) {
        return false;
    } finally {
        if (null != xmlStreamReader) {
            try {
                xmlStreamReader.close();
            } catch (XMLStreamException e) {
                // ignore it
            }
        }
        closeQuietly(attachmentStream, log);
    }
}