Example usage for javax.xml.stream XMLInputFactory newInstance

List of usage examples for javax.xml.stream XMLInputFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.stream XMLInputFactory newInstance.

Prototype

public static XMLInputFactory newInstance() throws FactoryConfigurationError 

Source Link

Document

Creates a new instance of the factory in exactly the same manner as the #newFactory() method.

Usage

From source file:org.deegree.style.persistence.sld.SldStyleStoreBuilder.java

@Override
public StyleStore build() {
    InputStream in = null;/*  w ww .  j  a  va  2s  .c o  m*/
    XMLStreamReader reader = null;
    try {
        in = metadata.getLocation().getAsStream();
        DefaultResourceLocation<StyleStore> loc = (DefaultResourceLocation<StyleStore>) metadata.getLocation();
        XMLInputFactory fac = XMLInputFactory.newInstance();
        reader = fac.createXMLStreamReader(loc.getFile().toString(), in);
        Map<String, LinkedList<Style>> map = getStyles(reader);
        return new SLDStyleStore(map, metadata);
    } catch (Exception e) {
        throw new ResourceInitException("Could not read SLD style config.", e);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (XMLStreamException e) {
            // eat it
        }
        closeQuietly(in);
    }
}

From source file:org.deegree.style.persistence.sld.SLDStyleStoreProvider.java

@Override
public SLDStyleStore create(URL configUrl) throws ResourceInitException {
    InputStream in = null;//from w ww . j  a v a 2 s  .c  om
    XMLStreamReader reader = null;
    try {
        in = configUrl.openStream();
        XMLInputFactory fac = XMLInputFactory.newInstance();
        reader = fac.createXMLStreamReader(configUrl.toExternalForm(), in);
        Map<String, LinkedList<Style>> map = getStyles(reader);
        return new SLDStyleStore(map);
    } catch (Throwable e) {
        throw new ResourceInitException("Could not read SLD style config.", e);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (XMLStreamException e) {
            // eat it
        }
        closeQuietly(in);
    }
}

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 ww  w  .  j  a  v a2  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  w w  w  . ja v  a 2  s .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.alkis.BackReferenceFixer.java

public static void main(String[] args) {
    Options opts = initOptions();/*from   w  ww.ja  va2 s  . c  o  m*/
    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
        CommandLine line = new PosixParser().parse(opts, args);
        String input = line.getOptionValue('i');
        String output = line.getOptionValue('o');
        String schema = line.getOptionValue('s');
        fis = new FileInputStream(input);
        fos = new FileOutputStream(output);
        XMLInputFactory xifac = XMLInputFactory.newInstance();
        XMLOutputFactory xofac = XMLOutputFactory.newInstance();
        XMLStreamReader xreader = xifac.createXMLStreamReader(input, fis);
        IndentingXMLStreamWriter xwriter = new IndentingXMLStreamWriter(xofac.createXMLStreamWriter(fos));
        GMLStreamReader reader = GMLInputFactory.createGMLStreamReader(GMLVersion.GML_32, xreader);

        AppSchema appSchema = new GMLAppSchemaReader(null, null, schema).extractAppSchema();
        reader.setApplicationSchema(appSchema);

        GMLStreamWriter writer = GMLOutputFactory.createGMLStreamWriter(GMLVersion.GML_32, xwriter);
        XlinkedObjectsHandler handler = new XlinkedObjectsHandler(true, null, new GmlXlinkOptions());
        writer.setReferenceResolveStrategy(handler);

        QName prop = new QName(ns601, "dientZurDarstellungVon");

        Map<String, List<String>> refs = new HashMap<String, List<String>>();
        Map<String, List<String>> types = new HashMap<String, List<String>>();
        Map<String, String> bindings = null;

        for (Feature f : reader.readFeatureCollectionStream()) {
            if (bindings == null) {
                bindings = f.getType().getSchema().getNamespaceBindings();
            }
            for (Property p : f.getProperties(prop)) {
                FeatureReference ref = (FeatureReference) p.getValue();
                List<String> list = refs.get(ref.getId());
                if (list == null) {
                    list = new ArrayList<String>();
                    refs.put(ref.getId(), list);
                }
                list.add(f.getId());
                list = types.get(ref.getId());
                if (list == null) {
                    list = new ArrayList<String>();
                    types.put(ref.getId(), list);
                }
                list.add("inversZu_dientZurDarstellungVon_" + f.getType().getName().getLocalPart());
            }
        }

        QName[] inversePropNames = new QName[] {
                new QName(ns601, "inversZu_dientZurDarstellungVon_AP_Darstellung"),
                new QName(ns601, "inversZu_dientZurDarstellungVon_AP_LTO"),
                new QName(ns601, "inversZu_dientZurDarstellungVon_AP_PTO"),
                new QName(ns601, "inversZu_dientZurDarstellungVon_AP_FPO"),
                new QName(ns601, "inversZu_dientZurDarstellungVon_AP_KPO_3D"),
                new QName(ns601, "inversZu_dientZurDarstellungVon_AP_LPO"),
                new QName(ns601, "inversZu_dientZurDarstellungVon_AP_PPO") };

        reader.close();
        fis.close();
        writer.setNamespaceBindings(bindings);

        fis = new FileInputStream(input);
        xreader = xifac.createXMLStreamReader(input, fis);
        reader = GMLInputFactory.createGMLStreamReader(GMLVersion.GML_32, xreader);
        reader.setApplicationSchema(appSchema);

        if (bindings != null) {
            for (Map.Entry<String, String> e : bindings.entrySet()) {
                if (!e.getKey().isEmpty()) {
                    xwriter.setPrefix(e.getValue(), e.getKey());
                }
            }
        }
        xwriter.writeStartDocument();
        xwriter.setPrefix("gml", "http://www.opengis.net/gml/3.2");
        xwriter.writeStartElement("http://www.opengis.net/gml/3.2", "FeatureCollection");
        xwriter.writeNamespace("gml", "http://www.opengis.net/gml/3.2");

        GmlDocumentIdContext ctx = new GmlDocumentIdContext(GMLVersion.GML_32);

        for (Feature f : reader.readFeatureCollectionStream()) {
            if (refs.containsKey(f.getId())) {
                List<Property> props = new ArrayList<Property>(f.getProperties());
                ListIterator<Property> iter = props.listIterator();
                String name = iter.next().getName().getLocalPart();
                while (name.equals("lebenszeitintervall") || name.equals("modellart") || name.equals("anlass")
                        || name.equals("zeigtAufExternes") || name.equals("istTeilVon")
                        || name.equals("identifier")) {
                    if (iter.hasNext()) {
                        name = iter.next().getName().getLocalPart();
                    } else {
                        break;
                    }
                }
                if (iter.hasPrevious()) {
                    iter.previous();
                }
                for (QName propName : inversePropNames) {
                    Iterator<String> idIter = refs.get(f.getId()).iterator();
                    Iterator<String> typeIter = types.get(f.getId()).iterator();
                    while (idIter.hasNext()) {
                        String id = idIter.next();
                        if (typeIter.next().equals(propName.getLocalPart())) {
                            PropertyType pt = f.getType().getPropertyDeclaration(propName);
                            Property p = new GenericProperty(pt, new FeatureReference(ctx, "#" + id, null));
                            iter.add(p);
                        }
                    }
                }
                f.setProperties(props);

            }
            xwriter.writeStartElement("http://www.opengis.net/gml/3.2", "featureMember");
            writer.write(f);
            xwriter.writeEndElement();
        }

        xwriter.writeEndElement();
        xwriter.close();
    } catch (Throwable e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(fos);
    }
}

From source file:org.deegree.tools.crs.XMLCoordinateTransform.java

private static void doTransform(CommandLine line) throws IllegalArgumentException, TransformationException,
        UnknownCRSException, IOException, XMLStreamException, FactoryConfigurationError {

    // TODO source srs should actually override all srsName attributes in document, not just be the default
    ICRS sourceCRS = null;//ww w.  j  a  v a 2 s .  com
    String sourceCRSId = line.getOptionValue(OPT_S_SRS);
    if (sourceCRSId != null) {
        sourceCRS = CRSManager.lookup(sourceCRSId);
    }

    String targetCRSId = line.getOptionValue(OPT_T_SRS);
    ICRS targetCRS = CRSManager.lookup(targetCRSId);

    String transId = line.getOptionValue(OPT_TRANSFORMATION);
    List<Transformation> trans = null;
    if (transId != null) {
        Transformation t = CRSManager.getTransformation(null, transId);
        if (t != null) {
            trans = Collections.singletonList(CRSManager.getTransformation(null, transId));
        } else {
            throw new IllegalArgumentException(
                    "Specified transformation id '" + transId + "' does not exist in CRS database.");
        }
    }

    GMLVersion gmlVersion = GMLVersion.GML_31;
    String gmlVersionString = line.getOptionValue(OPT_GML_VERSION);
    if (gmlVersionString != null) {
        gmlVersion = GMLVersion.valueOf(gmlVersionString);
    }

    String i = line.getOptionValue(OPT_INPUT);
    File inputFile = new File(i);
    if (!inputFile.exists()) {
        throw new IllegalArgumentException("Input file '" + inputFile + "' does not exist.");
    }
    XMLStreamReader xmlReader = XMLInputFactory.newInstance()
            .createXMLStreamReader(new FileInputStream(inputFile));

    String o = line.getOptionValue(OPT_OUTPUT);
    XMLStreamWriter xmlWriter = null;
    if (o != null) {
        File outputFile = new File(o);
        xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(new FileOutputStream(outputFile),
                "UTF-8");
    } else {
        xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(System.out, "UTF-8");
    }

    xmlWriter = new IndentingXMLStreamWriter(xmlWriter, "    ");
    xmlWriter.writeStartDocument("UTF-8", "1.0");
    XMLTransformer transformer = new XMLTransformer(targetCRS);
    transformer.transform(xmlReader, xmlWriter, sourceCRS, gmlVersion, false, trans);
    xmlWriter.close();
}

From source file:org.deegree.tools.rendering.r2d.se.PostgreSQLImporter.java

/**
 * @param args//from   w  w  w  . ja  v a  2 s  .  co  m
 * @throws XMLStreamException
 * @throws FactoryConfigurationError
 * @throws IOException
 */
public static void main(String[] args) throws XMLStreamException, FactoryConfigurationError, IOException {
    Options options = initOptions();

    // for the moment, using the CLI API there is no way to respond to a help argument; see
    // https://issues.apache.org/jira/browse/CLI-179
    if (args.length == 0 || (args.length > 0 && (args[0].contains("help") || args[0].contains("?")))) {
        CommandUtils.printHelp(options, PostgreSQLImporter.class.getSimpleName(), null, null);
    }

    try {
        new PosixParser().parse(options, args);

        String inputFile = options.getOption("sldfile").getValue();
        String url = options.getOption("dburl").getValue();
        String user = options.getOption("dbuser").getValue();
        String pass = options.getOption("dbpassword").getValue();
        if (pass == null) {
            pass = "";
        }
        String schema = options.getOption("schema").getValue();
        if (schema == null) {
            schema = "public";
        }

        XMLInputFactory fac = XMLInputFactory.newInstance();
        Style style = new SymbologyParser(true)
                .parse(fac.createXMLStreamReader(new FileInputStream(inputFile)));

        Workspace workspace = new DefaultWorkspace(new File("nonexistant"));
        ResourceLocation<ConnectionProvider> loc = ConnectionProviderUtils.getSyntheticProvider("style", url,
                user, pass);
        workspace.startup();
        workspace.getLocationHandler().addExtraResource(loc);
        workspace.initAll();

        if (style.isSimple()) {
            new PostgreSQLWriter("style", schema, workspace).write(style, null);
        } else {
            new PostgreSQLWriter("style", schema, workspace).write(new FileInputStream(inputFile),
                    style.getName());
        }
        workspace.destroy();
    } catch (ParseException exp) {
        System.err.println(Messages.getMessage("TOOL_COMMANDLINE_ERROR", exp.getMessage()));
        // printHelp( options );
    }

}

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  ww w.ja  v  a2 s  . com*/
    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;/* www .j a va  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.dkpro.core.io.xces.XcesBasicXmlReader.java

@Override
public void getNext(JCas aJCas) throws IOException, CollectionException {

    Resource res = nextFile();/*from  w w  w.  j  av a2s. co  m*/
    initCas(aJCas, res);

    InputStream is = null;

    try {
        is = CompressionUtils.getInputStream(res.getLocation(), res.getInputStream());
        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        XMLEventReader xmlEventReaderBasic = xmlInputFactory.createXMLEventReader(is);

        //JAXB context for XCES body with basic type
        JAXBContext contextBasic = JAXBContext.newInstance(XcesBodyBasic.class);
        Unmarshaller unmarshallerBasic = contextBasic.createUnmarshaller();

        unmarshallerBasic.setEventHandler(new ValidationEventHandler() {
            public boolean handleEvent(ValidationEvent event) {
                throw new RuntimeException(event.getMessage(), event.getLinkedException());
            }
        });

        JCasBuilder jb = new JCasBuilder(aJCas);

        XMLEvent eBasic = null;
        while ((eBasic = xmlEventReaderBasic.peek()) != null) {
            if (isStartElement(eBasic, "body")) {
                try {
                    XcesBodyBasic parasBasic = (XcesBodyBasic) unmarshallerBasic
                            .unmarshal(xmlEventReaderBasic, XcesBodyBasic.class).getValue();
                    readPara(jb, parasBasic);
                } catch (RuntimeException ex) {
                    getLogger().warn("Input is not in basic xces format.");
                }
            } else {
                xmlEventReaderBasic.next();
            }

        }
        jb.close();

    } catch (XMLStreamException ex1) {
        throw new IOException(ex1);
    } catch (JAXBException e1) {
        throw new IOException(e1);
    } finally {
        closeQuietly(is);
    }

}