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.bordercloud.sparql.Endpoint.java

private void init(String endpoint, Boolean readOnly, Boolean debug, String proxy_host, //todo
        Integer proxy_port//todo
) {/*  w  w  w.  j av a2 s  . c om*/
    try {
        URL url = new URL(endpoint);

        if (readOnly) {
            _endpoint = endpoint;
        } else {
            _endpoint = endpoint;
            _endpoint_root = url.getProtocol() + "://" + url.getHost() + url.getFile();
        }
    } catch (MalformedURLException mue) {
        System.out.println("Ouch - a MalformedURLException happened.");
        mue.printStackTrace();
    }

    // Init Sax class
    SAXParserFactory parserSPARQL = SAXParserFactory.newInstance();
    _parser = null;

    try {
        _parser = parserSPARQL.newSAXParser();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }

    _debug = debug;
    _endpoint_write = "";
    _readOnly = readOnly;

    _proxy_host = proxy_host;
    _proxy_port = proxy_port;

    if (_proxy_host != null && _proxy_port != 0) {
        //todo
    } else {
        //todo
    }

    // init parameter in the standard
    _nameParameterQueryRead = "query";
    _nameParameterQueryWrite = "update";

    //FIX for Wikidata
    if (endpoint == "https://query.wikidata.org/sparql") {
        _MethodHTTPRead = "GET";
    } else {
        _MethodHTTPRead = "POST"; // by default
    }
}

From source file:com.commonsware.android.EMusicDownloader.SingleBook.java

private void getInfoFromXML() {

    final ProgressDialog dialog = ProgressDialog.show(this, "", getString(R.string.loading), true, true);
    setProgressBarIndeterminateVisibility(true);

    Thread t3 = new Thread() {
        public void run() {

            waiting(200);//ww w  . jav a 2s  .c o m

            try {

                URL url = new URL(urlAddress);
                SAXParserFactory spf = SAXParserFactory.newInstance();
                SAXParser sp = spf.newSAXParser();
                XMLReader xr = sp.getXMLReader();
                XMLHandlerSingleBook myXMLHandler = new XMLHandlerSingleBook();
                xr.setContentHandler(myXMLHandler);
                xr.parse(new InputSource(url.openStream()));

                genre = myXMLHandler.genre;
                publisher = myXMLHandler.publisher;
                narrator = myXMLHandler.narrator;
                edition = myXMLHandler.edition;
                artist = myXMLHandler.author;
                authorId = myXMLHandler.authorId;
                if (edition == null) {
                    edition = "";
                }
                date = myXMLHandler.releaseDate;
                rating = myXMLHandler.rating;
                sampleURL = myXMLHandler.sampleURL;
                imageURL = myXMLHandler.imageURL;

                statuscode = myXMLHandler.statuscode;

                if (statuscode != 200 && statuscode != 206) {
                    throw new Exception();
                }

                blurb = myXMLHandler.blurb;
                blurb = blurb.replace("<br> ", "<br>");
                blurbSource = myXMLHandler.blurbSource;

                handlerSetContent.sendEmptyMessage(0);
                dialog.dismiss();
                updateImage();

            } catch (Exception e) {

                final Exception ef = e;
                nameTextView.post(new Runnable() {
                    public void run() {
                        nameTextView.setText(R.string.couldnt_get_book_info);
                    }
                });
                dialog.dismiss();

            }

            handlerDoneLoading.sendEmptyMessage(0);

        }
    };
    t3.start();
}

From source file:com.wadpam.ricotta.web.IndexController.java

protected void importXML(String blobKey, InputStream in)
        throws ParserConfigurationException, SAXException, IOException {
    SAXParser parser = SAXParserFactory.newInstance().newSAXParser();

    DefaultHandler dh = new RicottaImportHandler(blobKey, uberDao);
    parser.parse(in, dh);/*from  w  w  w  .  j av  a2  s.  co m*/
}

From source file:ensen.controler.DBpediaLookupClient.java

public String getOneResource(String query, String classes, int numberOfRes) throws Exception {

    HttpClient client = new HttpClient();
    // client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
    String query2 = URLEncoder.encode(query, "utf-8");
    HttpMethod method = new GetMethod(
            gatway + "QueryString=" + query2 + "&QueryClass=" + classes + "&MaxHits=" + numberOfRes);
    // method.setFollowRedirects(true);
    try {//from   ww  w . j  a  va 2 s . co  m
        client.executeMethod(method);
        InputStream ins = method.getResponseBodyAsStream();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser sax = factory.newSAXParser();
        sax.parse(ins, this);
    } catch (HttpException he) {
        System.out.println("Http error connecting to lookup.dbpedia.org");
    } catch (IOException ioe) {
        System.out.println("Unable to connect to lookup.dbpedia.org");
    } catch (Exception e) {
        System.out.println("Error: " + e.getMessage());
    }
    method.releaseConnection();

    String resource = "";
    int num_results = Results.size();
    if (num_results > 0) {
        for (DBpediaLookupResModel res : Results) {
            resource = URLDecoder.decode(res.uri);
            /*
             * if (res.uri.contains("http://")) { Resource O =
             * model.createResource(res.uri); Property P =
             * model.createProperty("http://ensen.org/data#has-a"); Literal
             * O1 = model.createLiteral(res.label + ""); Literal O2 =
             * model.createLiteral(res.desc + ""); Property P1 =
             * model.createProperty
             * ("http://www.w3.org/2000/01/rdf-schema#label"); Property P2 =
             * model.createProperty(
             * "http://www.w3.org/1999/02/22-rdf-syntax-ns#description");
             * O.addProperty(P1, O1); O.addProperty(P2, O2);
             * 
             * for (String cat : res.cats) { Resource OO =
             * model.createResource(cat); Property PP =
             * model.createProperty("http://purl.org/dc/terms/subject");
             * O.addProperty(PP, OO); } for (String c : res.classes) {
             * Resource OO = model.createResource(c); Property PP =
             * model.createProperty
             * ("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
             * O.addProperty(PP, OO); } core.addProperty(P, O);
             * 
             * }
             */
        }
    }

    return resource;
}

From source file:egat.cli.strategyregret.StrategyRegretCommandHandler.java

protected void processStrategicGame(MutableStrategicGame game) throws CommandProcessingException {
    try {//from  w  w  w .ja  v a2  s.co m
        Profile profile = null;

        if (uniform) {
            Player[] players = game.players().toArray(new Player[0]);
            Strategy[] strategies = new Strategy[players.length];

            for (int i = 0; i < players.length; i++) {
                Action[] actions = ((Set<Action>) game.getActions(players[i])).toArray(new Action[0]);
                Number[] distribution = new Number[actions.length];
                Arrays.fill(distribution, 1.0 / distribution.length);
                strategies[i] = Games.createStrategy(actions, distribution);
            }

            profile = Games.createProfile(players, strategies);

        } else {
            InputStream inputStream = null;

            inputStream = new FileInputStream(profilePath);

            SAXParserFactory factory = SAXParserFactory.newInstance();

            SAXParser parser = factory.newSAXParser();

            ProfileHandler handler = new ProfileHandler();

            parser.parse(inputStream, handler);

            profile = handler.getProfile();
        }

        findRegret(profile, game);
    } catch (NonexistentPayoffException e) {
        System.err.println(String.format("Could not calculate regret. %s", e.getMessage()));
    } catch (FileNotFoundException e) {
        throw new CommandProcessingException(e);
    } catch (ParserConfigurationException e) {
        throw new CommandProcessingException(e);
    } catch (SAXException e) {
        throw new CommandProcessingException(e);
    } catch (IOException e) {
        throw new CommandProcessingException(e);
    }
}

From source file:bg.fourweb.android.rss.Parser.java

public Feed parse(final String url, ProgressObserver obs) {
    final HttpClient client = CompatHttp.getHttpClient();

    // configure the HTTP client
    client.getParams().setIntParameter("http.socket.timeout", opts.getConnectionTimeout());

    try {/*  ww  w .  java2 s  . c  o  m*/
        final HttpUriRequest get = new HttpGet(url);
        final HttpResponse resp = client.execute(get);

        // prepare content length (it's needed for progress indication)
        int contentLength = 0;
        final Header[] contentLengthHeaders = resp.getHeaders("Content-Length");
        if (ArrayUtils.isEmpty(contentLengthHeaders) == false) {
            final Header contentLengthHeader = contentLengthHeaders[0];
            final String contentLengthValue = contentLengthHeader.getValue();
            if (StringUtils.isEmpty(contentLengthValue) == false) {
                try {
                    contentLength = Integer.parseInt(contentLengthValue);
                } catch (NumberFormatException ignored) {
                    // NOP
                }
            }
        }

        // prepare progress observers
        final ProgressInputStream body = new ProgressInputStream(resp.getEntity().getContent(), contentLength);
        if (obs != null) {
            body.addProgressObserver(obs);
        }

        // handler
        h = prepareHandler();

        // parse
        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        parser.parse(body, h);
        return h.getProductFeed();
    } catch (Throwable e) {
        if (DBG) {
            Log.w(TAG, "", e);
        }
    } finally {
        CompatHttp.closeHttpClient(client);
    }
    return null;
}

From source file:de.uzk.hki.da.convert.PublishXSLTConversionStrategy.java

/**
 * Creates the xml source./*from www  . j av a2 s.c o  m*/
 *
 * @param file the file
 * @return the source
 */
private Source createXMLSource(File file) {
    // disable validation in order to prevent url resolution of DTDs etc.
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    spf.setValidating(false);
    try {
        spf.setFeature("http://xml.org/sax/features/validation", false);
        spf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
        spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    } catch (Exception e) {
        logger.warn(e.getMessage());
    }
    XMLReader reader;
    try {
        reader = spf.newSAXParser().getXMLReader();
    } catch (Exception e) {
        throw new IllegalStateException("Unable to create SAXParser", e);
    }

    return new SAXSource(reader, new InputSource(file.getAbsolutePath()));
}

From source file:de.uni_freiburg.informatik.ultimate.licence_manager.authors.SvnAuthorProvider.java

private SvnBlameSAXHandler parseSvnBlameOutput(InputStream input)
        throws ParserConfigurationException, SAXException, IOException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();
    SvnBlameSAXHandler handler = new SvnBlameSAXHandler();
    saxParser.parse(input, handler);/*  w w  w. ja  va 2  s.  c  o  m*/
    return handler;
}

From source file:com.zegoggles.smssync.auth.XOAuthConsumer.java

private String extractEmail(HttpResponse response)
        throws ParserConfigurationException, SAXException, IOException {
    final XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
    final FeedHandler feedHandler = new FeedHandler();
    xmlReader.setContentHandler(feedHandler);
    xmlReader.parse(new InputSource(response.getEntity().getContent()));
    return feedHandler.getEmail();
}