Example usage for javax.xml.parsers SAXParserFactory newInstance

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

Introduction

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

Prototype


public static SAXParserFactory newInstance() 

Source Link

Document

Obtain a new instance of a SAXParserFactory .

Usage

From source file:com.joliciel.frenchTreebank.upload.TreebankSAXParser.java

public void parseDocument(String filePath) {
    //get or create the treebank file
    treebankFile = this.getTreebankService().loadOrCreateTreebankFile(filePath);

    //get a factory
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {//from  w w w  .java2s .c  o  m

        //get a new instance of parser
        SAXParser sp = spf.newSAXParser();

        //parse the file and also register this class for call backs
        sp.parse(filePath, this);

    } catch (SAXException se) {
        se.printStackTrace();
    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    } catch (IOException ie) {
        ie.printStackTrace();
    }
}

From source file:it.wami.map.mongodeploy.OsmToMongoDB.java

/**
 * @param args/*  w  ww .j  av a 2s. c  o m*/
 */
public static void main(String[] args) {

    if (args == null || args.length == 0 || args.length < 2) {
        System.out.println(Options.USAGE);
        return;
    }

    parseCommandOptions(args);

    MongoClientOptions mco = new MongoClientOptions.Builder().connectionsPerHost(150000)
            .threadsAllowedToBlockForConnectionMultiplier(10000).build();

    MongoClient mongoClient = createMongo(options.getHost(), options.getPort(), mco);

    DB db = mongoClient.getDB(options.getDbName());
    DBCollection nodes = db.createCollection(OsmSaxHandler.COLL_NODES, null);
    createNodesIndex(nodes);
    /*DBCollection ways = */
    DBCollection ways = db.createCollection(OsmSaxHandler.COLL_WAYS, null);
    createWaysIndex(ways);
    /*DBCollection relations = */
    DBCollection relations = db.createCollection(OsmSaxHandler.COLL_RELATIONS, null);
    createRelationsIndex(relations);
    db.createCollection(OsmSaxHandler.COLL_TAGS, null);

    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = null;
    try {
        saxParser = factory.newSAXParser();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }

    DefaultHandler handler = new OsmSaxHandler(db, options);

    try {
        if (options.getInput().contains(".bz2")) {
            try {
                saxParser.parse(getInputStreamForBZ2File(options.getInput()), handler);
            } catch (CompressorException e) {
                e.printStackTrace();
            }
        } else if (options.getInput().contains(".osm")) {
            saxParser.parse(options.getInput(), handler);
        } else {
            throw new IllegalArgumentException("input must be an osm file or a bz2.");
        }
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:de.topicmapslab.tmcledit.model.psiprovider.internal.Subj3ctPSIProvider.java

public Set<PSIProviderResult> getSubjectIdentifier() {
    if (getName().length() == 0)
        return Collections.emptySet();

    HttpMethod method = null;/*  w w w .  j a  va2  s .  c om*/
    try {
        String url = "http://api.subj3ct.com/subjects/search";

        HttpClient client = new HttpClient();
        method = new GetMethod(url);

        ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(2);
        params.add(new NameValuePair("format", "xml"));
        params.add(new NameValuePair("query", getName()));
        method.setQueryString(params.toArray(new NameValuePair[params.size()]));

        client.getParams().setSoTimeout(5000);
        client.executeMethod(method);

        String result = method.getResponseBodyAsString();

        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        Subj3ctXmlHandler handler = new Subj3ctXmlHandler();
        parser.parse(new InputSource(new StringReader(result)), handler);

        List<Subje3ctResult> resultList = handler.getResultList();
        if (resultList.size() == 0) {
            return Collections.emptySet();
        }

        Set<PSIProviderResult> resultSet = new HashSet<PSIProviderResult>(resultList.size());
        for (Subje3ctResult r : resultList) {
            String description = "";
            if (r.name != null)
                description = "Name: " + r.name + "\n";
            if (r.description != null)
                description += "Description: " + r.description + "\n";

            description += "\n\nThis service is provided by http://www.subj3ct.com";

            resultSet.add(new PSIProviderResult(r.identifier, description));
        }

        return Collections.unmodifiableSet(resultSet);
    } catch (UnknownHostException e) {
        // no http connection -> no results
        TmcleditEditPlugin.logInfo(e);
        return Collections.emptySet();
    } catch (SocketTimeoutException e) {
        // timeout -> no results
        TmcleditEditPlugin.logInfo(e);
        return Collections.emptySet();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}

From source file:io.dataapps.chlorine.mask.MaskFactory.java

public MaskFactory(FinderEngine fEngine, InputStream in) {
    engine = fEngine;//  www.j  av a 2 s.  co  m
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();

        DefaultHandler handler = new DefaultHandler() {

            boolean bName = false;
            boolean bClass = false;
            boolean bConfiguration = false;
            boolean bDefault = false;

            String name = "";
            String className = "";
            String configuration = "";
            String defaultStr;

            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                if (qName.equalsIgnoreCase("NAME")) {
                    bName = true;
                } else if (qName.equalsIgnoreCase("CLASS")) {
                    bClass = true;
                } else if (qName.equalsIgnoreCase("CONFIGURATION")) {
                    bConfiguration = true;
                } else if (qName.equalsIgnoreCase("DEFAULT")) {
                    bDefault = 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("CLASS")) {
                    bClass = false;
                    className = className.trim();
                } else if (qName.equalsIgnoreCase("CONFIGURATION")) {
                    bConfiguration = false;
                    configuration = configuration.trim();
                } else if (qName.equalsIgnoreCase("DEFAULT")) {
                    bDefault = false;
                    defaultMasker = defaultStr.trim();
                } else if (qName.equalsIgnoreCase("MASKER")) {

                    if (!name.isEmpty() && !className.isEmpty() && !configuration.isEmpty()) {
                        try {
                            Class<?> klass = Thread.currentThread().getContextClassLoader()
                                    .loadClass(className);
                            Masker masker = (Masker) klass.newInstance();
                            masker.init(engine, configuration);
                            maskers.put(name, masker);
                        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                            LOG.error(e);
                        }
                    } else {
                        if (name.isEmpty()) {
                            LOG.error("The name for a masker cannot be empty");
                        }
                        if (className.isEmpty()) {
                            LOG.error("The class name for a masker cannot be empty");
                        }
                        if (configuration.isEmpty()) {
                            LOG.error("The configuration for a masker cannot be empty");
                        }
                    }
                    name = "";
                    configuration = "";
                    className = "";
                    defaultStr = "";
                }
            }

            public void characters(char ch[], int start, int length) throws SAXException {
                if (bName) {
                    name += new String(ch, start, length);
                } else if (bClass) {
                    className += new String(ch, start, length);
                } else if (bConfiguration) {
                    configuration += new String(ch, start, length);
                } else if (bDefault) {
                    defaultStr += new String(ch, start, length);
                }
            }
        };

        saxParser.parse(in, handler);

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

From source file:de.tudarmstadt.ukp.dkpro.core.io.xml.XmlReaderText.java

@Override
public void getNext(CAS aCAS) throws IOException, CollectionException {
    Resource res = nextFile();/*from ww w  . j a va  2 s . co  m*/
    initCas(aCAS, res);

    InputStream is = null;

    try {
        JCas jcas = aCAS.getJCas();

        is = res.getInputStream();

        // Create handler
        Handler handler = newSaxHandler();
        handler.setJCas(jcas);
        handler.setLogger(getLogger());

        // Parser XML
        SAXParserFactory pf = SAXParserFactory.newInstance();
        SAXParser parser = pf.newSAXParser();

        InputSource source = new InputSource(is);
        source.setPublicId(res.getLocation());
        source.setSystemId(res.getLocation());
        parser.parse(source, handler);

        // Set up language
        if (getConfigParameterValue(PARAM_LANGUAGE) != null) {
            aCAS.setDocumentLanguage((String) getConfigParameterValue(PARAM_LANGUAGE));
        }
    } catch (CASException e) {
        throw new CollectionException(e);
    } catch (ParserConfigurationException e) {
        throw new CollectionException(e);
    } catch (SAXException e) {
        throw new IOException(e);
    } finally {
        closeQuietly(is);
    }
}

From source file:com.ibm.jaql.lang.expr.xml.XmlToJsonFn.java

@Override
public JsonValue eval(Context context) throws Exception {
    if (parser == null) {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        parser = factory.newSAXParser().getXMLReader();
        handler = new XmlToJsonHandler2();
        parser.setContentHandler(handler);
    }//from w  ww  .j a  v  a  2s .co m

    JsonString s = (JsonString) exprs[0].eval(context);
    if (s == null) {
        return null;
    }
    parser.parse(new InputSource(new StringReader(s.toString())));
    return handler.result;
}

From source file:jcurl.core.io.SetupSaxDeSer.java

private static synchronized SAXParser newParser() throws SAXException {
    if (spf == null) {
        spf = SAXParserFactory.newInstance();
        // http://www.cafeconleche.org/slides/xmlone/london2002/namespaces/36.html
        // http://xml.apache.org/xerces-j/features.html
        // spf.setFeature("http://xml.org/sax/features/namespaces", true);
        // spf.setFeature("http://xml.org/sax/features/namespace-prefixes",
        // true);
        spf.setNamespaceAware(true);/*w ww .ja v a2 s  .c  o m*/
        spf.setValidating(false);
    }
    try {
        final SAXParser sp = spf.newSAXParser();
        if (log.isDebugEnabled())
            log.debug(sp.getClass().getName());
        return sp;
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
}

From source file:gsn.tests.performance.Queries.java

public Queries(int nbQueries, int nbThreads) {
    this.nbQueries = nbQueries;
    this.nbThreads = nbThreads;
    executor = Executors.newFixedThreadPool(nbThreads);
    saxParserFactory = SAXParserFactory.newInstance();
    mapping = new HashMap<String, ArrayList<DataField>>();
}

From source file:applab.search.client.ImageManager.java

public static void updateLocalImages() {
    // Get remote list
    InputStream xmlStream = getImageXml();

    // Get local list
    HashMap<String, File> localImageList = getLocalImageList();

    // Init Sax Parser & XML Handler
    SAXParser xmlParser;// w w  w. j  a  va  2s.  c  o  m
    ImageXmlParseHandler xmlHandler = new ImageXmlParseHandler();
    xmlHandler.setLocalImageList(localImageList);

    if (xmlStream == null) {
        return;
    }
    try {
        if (xmlStream != null) {
            xmlParser = SAXParserFactory.newInstance().newSAXParser();

            // This line was causing problems on android 2.2 (IDEOS)
            // xmlParser.reset();

            xmlParser.parse(xmlStream, xmlHandler);

            // Delete local files not on remote list
            for (Entry<String, File> localImage : localImageList.entrySet()) {
                File file = localImage.getValue();
                String sha1Hash = localImage.getKey();
                // Confirm this is the file we intend to delete (a new file with the same name may have been downloaded)
                if (ImageFilesUtility.getSHA1Hash(file).equalsIgnoreCase(sha1Hash)) {
                    ImageFilesUtility.deleteFile(file);
                }
            }
        }
    } catch (SAXException e) {
        Log.e("ImageManager", "Error while parsing XML: " + e);
    } catch (IOException e) {
        Log.e("ImageManager", "Error while parsing XML: " + e);
    } catch (ParserConfigurationException e) {
        Log.e("ImageManager", "Error while parsing XML: " + e);
    }
}

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

/**
 * Returns list of known subscriptions./*from w  ww  .  j av a 2  s .  c  om*/
 */
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;
}