Example usage for javax.xml.parsers SAXParserFactory newSAXParser

List of usage examples for javax.xml.parsers SAXParserFactory newSAXParser

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParserFactory newSAXParser.

Prototype


public abstract SAXParser newSAXParser() throws ParserConfigurationException, SAXException;

Source Link

Document

Creates a new instance of a SAXParser using the currently configured factory parameters.

Usage

From source file:de.badw.strauss.glyphpicker.controller.alltab.TeiLoadWorker.java

/**
 * Instantiates a new TeiLoadWorker.//from   w w  w  . j a  va2s  . c  om
 *
 * @param dataSource The data source object providing the loading parameters
 */
public TeiLoadWorker(DataSource dataSource) {
    this.dataSource = dataSource;

    i18n = ResourceBundle.getBundle("GlyphPicker");

    SAXParserFactory parserFactory = SAXParserFactoryImpl.newInstance();
    try {
        parser = parserFactory.newSAXParser();
    } catch (ParserConfigurationException e) {
        LOGGER.error(e);
    } catch (SAXException e) {
        LOGGER.error(e);
    }
}

From source file:com.sismics.util.AdblockUtil.java

/**
 * Returns list of known subscriptions.//from   w  w  w. ja  v a2s  . com
 */
public List<Subscription> getSubscriptions() {
    if (subscriptions == null) {
        subscriptions = new ArrayList<Subscription>();

        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser;
        try {
            parser = factory.newSAXParser();
            parser.parse(AdblockUtil.class.getResourceAsStream("/adblock/subscriptions.xml"),
                    new SubscriptionParser(subscriptions));
        } catch (Exception e) {
            log.error("Error parsing subscriptions", e);
        }
    }
    return subscriptions;
}

From source file:com.sparsity.dex.etl.config.impl.XMLConfigurationProvider.java

public void load() throws DexUtilsException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);/*from   w w w.  j a  v a2 s . c  o  m*/
    factory.setNamespaceAware(true);

    try {
        SAXParser parser = factory.newSAXParser();
        DexUtilsHandler handler = new DexUtilsHandler(config);
        parser.parse(xml.getAbsolutePath(), handler);
    } catch (Exception e) {
        String msg = new String("Parsing error.");
        log.error(msg, e);
        throw new DexUtilsException(msg, e);
    }
    log.info("Loaded configuration from " + xml.getAbsolutePath());
}

From source file:me.crime.loader.DataBaseLoader.java

public DataBaseLoader() {

    classMap_.put("ciras.db.Crime", Crime.class.getName());
    classMap_.put("ciras.db.Address", Address.class.getName());
    classMap_.put("ciras.db.Arrested", Arrested.class.getName());
    classMap_.put("ciras.db.URCCatagories", URCCatagories.class.getName());
    classMap_.put("ciras.db.GeoPoint", GeoPoint.class.getName());

    try {/* w w w  .ja v a 2 s .c  o m*/
        SAXParserFactory factory = SAXParserFactory.newInstance();
        parser_ = factory.newSAXParser();
    } catch (ParserConfigurationException e) {
        DataBaseLoader.log_.error(e);
    } catch (SAXException e) {
        DataBaseLoader.log_.error(e);
    }
}

From source file:com.dhenton9000.excel.ExcelParser.java

public SheetResults parse(InputStream inputStream) throws Exception {

    OPCPackage pkg = OPCPackage.open(inputStream);
    XSSFReader reader = new XSSFReader(pkg);
    this.sst = reader.getSharedStringsTable();

    SAXParserFactory saxFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxFactory.newSAXParser();
    XMLReader parser = saxParser.getXMLReader();
    parser.setContentHandler(this);

    // There should only be one sheet
    final Iterator<InputStream> it = reader.getSheetsData();
    final InputStream sheet = it.next();

    final InputSource sheetSource = new InputSource(sheet);
    parser.parse(sheetSource);// w  w  w.  ja v a  2  s  .  c  o  m
    sheet.close();

    return getSheetResults();

}

From source file:de.mpg.mpdl.inge.xmltransforming.TestBase.java

/**
 * @param xmlData/*from   w  w w .  ja  va 2  s. c  om*/
 * @return
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws UnsupportedEncodingException
 */
private static String getNameSpaceFromXml(final String xmlData)
        throws ParserConfigurationException, SAXException, IOException, UnsupportedEncodingException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();
    DefaultHandler handler = new DefaultHandler() {
        private String nameSpace = null;
        private boolean first = true;

        public void startElement(String uri, String localName, String qName, Attributes attributes) {
            if (first) {
                if (qName.contains(":")) {
                    String prefix = qName.substring(0, qName.indexOf(":"));
                    String attributeName = "xmlns:" + prefix;
                    nameSpace = attributes.getValue(attributeName);
                } else {
                    nameSpace = attributes.getValue("xmlns");
                }
                first = false;
            }

        }

        public String toString() {
            return nameSpace;
        }
    };
    parser.parse(new ByteArrayInputStream(xmlData.getBytes("UTF-8")), handler);
    String nameSpace = handler.toString();
    return nameSpace;
}

From source file:org.syncope.core.init.ContentLoader.java

@Transactional
public void load() {
    // 0. DB connection, to be used below
    Connection conn = DataSourceUtils.getConnection(dataSource);

    // 1. Check wether we are allowed to load default content into the DB
    Statement statement = null;/* w  ww  .j  a va2  s. com*/
    ResultSet resultSet = null;
    boolean existingData = false;
    try {
        statement = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

        resultSet = statement.executeQuery("SELECT * FROM " + SyncopeConf.class.getSimpleName());
        resultSet.last();

        existingData = resultSet.getRow() > 0;
    } catch (SQLException e) {
        LOG.error("Could not access to table " + SyncopeConf.class.getSimpleName(), e);

        // Setting this to true make nothing to be done below
        existingData = true;
    } finally {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException e) {
            LOG.error("While closing SQL result set", e);
        }
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException e) {
            LOG.error("While closing SQL statement", e);
        }
    }

    if (existingData) {
        LOG.info("Data found in the database, leaving untouched");
        return;
    }

    LOG.info("Empty database found, loading default content");

    // 2. Create views
    LOG.debug("Creating views");
    try {
        InputStream viewsStream = getClass().getResourceAsStream("/views.xml");
        Properties views = new Properties();
        views.loadFromXML(viewsStream);

        for (String idx : views.stringPropertyNames()) {
            LOG.debug("Creating view {}", views.get(idx).toString());

            try {
                statement = conn.createStatement();
                statement.executeUpdate(views.get(idx).toString().replaceAll("\\n", " "));
                statement.close();
            } catch (SQLException e) {
                LOG.error("Could not create view ", e);
            }
        }

        LOG.debug("Views created, go for indexes");
    } catch (Throwable t) {
        LOG.error("While creating views", t);
    }

    // 3. Create indexes
    LOG.debug("Creating indexes");
    try {
        InputStream indexesStream = getClass().getResourceAsStream("/indexes.xml");
        Properties indexes = new Properties();
        indexes.loadFromXML(indexesStream);

        for (String idx : indexes.stringPropertyNames()) {
            LOG.debug("Creating index {}", indexes.get(idx).toString());

            try {
                statement = conn.createStatement();
                statement.executeUpdate(indexes.get(idx).toString());
                statement.close();
            } catch (SQLException e) {
                LOG.error("Could not create index ", e);
            }
        }

        LOG.debug("Indexes created, go for default content");
    } catch (Throwable t) {
        LOG.error("While creating indexes", t);
    } finally {
        DataSourceUtils.releaseConnection(conn, dataSource);
    }

    try {
        conn.close();
    } catch (SQLException e) {
        LOG.error("While closing SQL connection", e);
    }

    // 4. Load default content
    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {
        SAXParser parser = factory.newSAXParser();
        parser.parse(getClass().getResourceAsStream("/content.xml"), importExport);
        LOG.debug("Default content successfully loaded");
    } catch (Throwable t) {
        LOG.error("While loading default content", t);
    }
}

From source file:org.apache.commons.rdf.impl.sparql.SparqlClient.java

List<Map<String, RdfTerm>> queryResultSet(final String query) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(endpoint);
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("query", query));
    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    CloseableHttpResponse response2 = httpclient.execute(httpPost);

    try {//from www.ja v  a2 s  .co  m
        HttpEntity entity2 = response2.getEntity();
        InputStream in = entity2.getContent();
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        SAXParser saxParser = spf.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        final SparqlsResultsHandler sparqlsResultsHandler = new SparqlsResultsHandler();
        xmlReader.setContentHandler(sparqlsResultsHandler);
        xmlReader.parse(new InputSource(in));
        /*
         for (int ch = in.read(); ch != -1; ch = in.read()) {
         System.out.print((char)ch);
         }
         */
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity2);
        return sparqlsResultsHandler.getResults();
    } catch (ParserConfigurationException ex) {
        throw new RuntimeException(ex);
    } catch (SAXException ex) {
        throw new RuntimeException(ex);
    } finally {
        response2.close();
    }

}

From source file:nz.co.wholemeal.christchurchmetro.Stop.java

public ArrayList getArrivals() throws Exception {
    arrivals.clear();//from  w  w  w. jav a  2  s.  c o m

    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        URL source = new URL(arrivalURL + platformTag);
        EtaHandler handler = new EtaHandler();
        xr.setContentHandler(handler);
        xr.parse(new InputSource(source.openStream()));
        lastArrivalFetch = System.currentTimeMillis();
    } catch (Exception e) {
        throw e;
    }

    Collections.sort(arrivals, new ComparatorByEta());
    return arrivals;
}

From source file:io.dataapps.chlorine.finder.DefaultFinderProvider.java

DefaultFinderProvider(InputStream in, final boolean ignoreEnabledFlag) {
    try {//from  ww  w  . j av a2s .c o m

        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();

        DefaultHandler handler = new DefaultHandler() {

            boolean bName = false;
            boolean bPattern = false;
            boolean bClass = false;
            boolean bEnabled = false;
            boolean bFlags = false;
            String name = "";
            String pattern = "";
            String className = "";
            String strFlags = "";
            int flags = RegexFinder.DEFAULT_FLAGS;
            String strEnabled = "";
            boolean enabled = true;

            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {

                if (qName.equalsIgnoreCase("NAME")) {
                    bName = true;
                } else if (qName.equalsIgnoreCase("PATTERN")) {
                    bPattern = true;
                } else if (qName.equalsIgnoreCase("CLASS")) {
                    bClass = true;
                } else if (qName.equalsIgnoreCase("FLAGS")) {
                    bFlags = true;
                } else if (qName.equalsIgnoreCase("ENABLED")) {
                    bEnabled = true;
                }
            }

            public void endElement(String uri, String localName, String qName) throws SAXException {

                if (qName.equalsIgnoreCase("NAME")) {
                    bName = false;
                    name = name.trim();
                } else if (qName.equalsIgnoreCase("PATTERN")) {
                    bPattern = false;
                    pattern = pattern.trim();
                } else if (qName.equalsIgnoreCase("CLASS")) {
                    bClass = false;
                    className = className.trim();
                } else if (qName.equalsIgnoreCase("FLAGS")) {
                    bFlags = false;
                    flags = Integer.parseInt(strFlags.trim());
                } else if (qName.equalsIgnoreCase("ENABLED")) {
                    bEnabled = false;
                    enabled = Boolean.parseBoolean(strEnabled.trim());
                } else if (qName.equalsIgnoreCase("FINDER")) {
                    if (ignoreEnabledFlag || enabled) {
                        if (!className.isEmpty()) {
                            try {
                                Class<?> klass = Thread.currentThread().getContextClassLoader()
                                        .loadClass(className);
                                finders.add((Finder) klass.newInstance());
                            } catch (ClassNotFoundException | InstantiationException
                                    | IllegalAccessException e) {
                                LOG.error(e);
                            }

                        } else if (flags != RegexFinder.DEFAULT_FLAGS) {
                            finders.add(new RegexFinder(name, pattern, flags));
                        } else {
                            finders.add(new RegexFinder(name, pattern));
                        }
                    }
                    name = "";
                    pattern = "";
                    className = "";
                    flags = RegexFinder.DEFAULT_FLAGS;
                    strFlags = "";
                    enabled = true;
                    strEnabled = "";
                }
            }

            public void characters(char ch[], int start, int length) throws SAXException {

                if (bName) {
                    name += new String(ch, start, length);
                } else if (bPattern) {
                    pattern += new String(ch, start, length);
                } else if (bClass) {
                    className += new String(ch, start, length);
                } else if (bEnabled) {
                    strEnabled += new String(ch, start, length);
                } else if (bFlags) {
                    strFlags += new String(ch, start, length);
                }
            }

        };

        saxParser.parse(in, handler);

    } catch (Exception e) {
        LOG.error(e);
    }
}