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:com.entertailion.java.caster.DeviceFinder.java

public void onBroadcastFound(final BroadcastAdvertisement advert) {
    if (advert.getLocation() != null) {
        new Thread(new Runnable() {
            public void run() {
                Log.d(LOG_TAG, "location=" + advert.getLocation());
                HttpResponse response = new HttpRequestHelper().sendHttpGet(advert.getLocation());
                if (response != null) {
                    String appsUrl = null;
                    Header header = response.getLastHeader(HEADER_APPLICATION_URL);
                    if (header != null) {
                        appsUrl = header.getValue();
                        if (!appsUrl.endsWith("/")) {
                            appsUrl = appsUrl + "/";
                        }/* w ww  .j  av  a2s.  c o  m*/
                        Log.d(LOG_TAG, "appsUrl=" + appsUrl);
                    }
                    try {
                        InputStream inputStream = response.getEntity().getContent();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

                        InputSource inStream = new org.xml.sax.InputSource();
                        inStream.setCharacterStream(reader);
                        SAXParserFactory spf = SAXParserFactory.newInstance();
                        SAXParser sp = spf.newSAXParser();
                        XMLReader xr = sp.getXMLReader();
                        BroadcastHandler broadcastHandler = new BroadcastHandler();
                        xr.setContentHandler(broadcastHandler);
                        xr.parse(inStream);
                        Log.d(LOG_TAG, "modelName=" + broadcastHandler.getDialServer().getModelName());
                        // Only handle ChromeCast devices; not other DIAL
                        // devices like ChromeCast devices
                        if (broadcastHandler.getDialServer().getModelName().equals(CHROME_CAST_MODEL_NAME)) {
                            Log.d(LOG_TAG,
                                    "ChromeCast device found: " + advert.getIpAddress().getHostAddress());
                            DialServer dialServer = new DialServer(advert.getLocation(), advert.getIpAddress(),
                                    advert.getPort(), appsUrl,
                                    broadcastHandler.getDialServer().getFriendlyName(),
                                    broadcastHandler.getDialServer().getUuid(),
                                    broadcastHandler.getDialServer().getManufacturer(),
                                    broadcastHandler.getDialServer().getModelName());
                            trackedDialServers.add(dialServer);
                        }
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "parse device description", e);
                    }
                }
            }
        }).start();
    }
}

From source file:cn.com.loopj.android.http.SaxAsyncHttpResponseHandler.java

/**
 * Deconstructs response into given content handler
 *
 * @param entity returned HttpEntity//from w  ww .j  a  v a2s.c  o m
 * @return deconstructed response
 * @throws IOException if there is problem assembling SAX response from stream
 * @see HttpEntity
 */
@Override
protected byte[] getResponseData(HttpEntity entity) throws IOException {
    if (entity != null) {
        InputStream instream = entity.getContent();
        InputStreamReader inputStreamReader = null;
        if (instream != null) {
            try {
                SAXParserFactory sfactory = SAXParserFactory.newInstance();
                SAXParser sparser = sfactory.newSAXParser();
                XMLReader rssReader = sparser.getXMLReader();
                rssReader.setContentHandler(handler);
                inputStreamReader = new InputStreamReader(instream, getCharset());
                rssReader.parse(new InputSource(inputStreamReader));
            } catch (SAXException e) {
                AsyncHttpClient.log.e(LOG_TAG, "getResponseData exception", e);
            } catch (ParserConfigurationException e) {
                AsyncHttpClient.log.e(LOG_TAG, "getResponseData exception", e);
            } finally {
                AsyncHttpClient.silentCloseInputStream(instream);
                if (inputStreamReader != null) {
                    try {
                        inputStreamReader.close();
                    } catch (IOException e) {
                        /*ignore*/ }
                }
            }
        }
    }
    return null;
}

From source file:com.inferiorhumanorgans.WayToGo.Agency.NextBus.RouteConfig.RouteConfigXMLTask.java

@Override
protected Void doInBackground(final NextBusAgency... someAgencies) {
    super.doInBackground(someAgencies);

    final String ourNBName = theAgency.getNextBusName();

    Log.i(LOG_NAME, "Trying to get the route config for " + ourNBName + ".");
    Log.i(LOG_NAME, "Fetching from: " + NB_URL_BASE + ourNBName);
    InputStream ourInputStream = null;
    ClientConnectionManager ourConnectionManager = new ThreadSafeClientConnManager(params, registry);
    DefaultHttpClient ourHttpClient = new DefaultHttpClient(ourConnectionManager, params);

    final HttpGet getRequest = new HttpGet(NB_URL_BASE + Uri.encode(ourNBName));
    try {//from  ww  w  .  java 2s  .c  o  m
        ourInputStream = ourHttpClient.execute(getRequest).getEntity().getContent();
    } catch (ClientProtocolException ex) {
        Logger.getLogger(LOG_NAME).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(LOG_NAME).log(Level.SEVERE, null, ex);
    }
    Log.i(LOG_NAME, "Done with the route config for " + ourNBName + ".");

    try {
        SAXParserFactory ourParserFactory = SAXParserFactory.newInstance();
        SAXParser ourParser = ourParserFactory.newSAXParser();

        XMLReader xr = ourParser.getXMLReader();

        RouteConfigXMLHandler ourDataHandler = new RouteConfigXMLHandler(this);
        xr.setContentHandler(ourDataHandler);

        xr.parse(new InputSource(ourInputStream));

    } catch (ParserConfigurationException pce) {
        Log.e(LOG_NAME + "SAX XML", "sax parse error", pce);
    } catch (AbortXMLParsingException abrt) {
        Log.i(LOG_NAME + "AsyncXML", "Cancelled!!!!!");
    } catch (SAXException se) {
        Log.e(LOG_NAME + "SAX XML", "sax error", se);
    } catch (IOException ioe) {
        Log.e(LOG_NAME + "SAX XML", "sax parse io error", ioe);
    }
    Log.i(LOG_NAME + "SAX XML", "Done parsing XML for " + ourNBName);
    return null;
}

From source file:com.android.yijiang.kzx.http.SaxAsyncHttpResponseHandler.java

/**
 * Deconstructs response into given content handler
 *
 * @param entity returned HttpEntity/*from w ww  .j  av  a2 s .  c o m*/
 * @return deconstructed response
 * @throws java.io.IOException
 * @see org.apache.http.HttpEntity
 */
@Override
protected byte[] getResponseData(HttpEntity entity) throws IOException {
    if (entity != null) {
        InputStream instream = entity.getContent();
        InputStreamReader inputStreamReader = null;
        if (instream != null) {
            try {
                SAXParserFactory sfactory = SAXParserFactory.newInstance();
                SAXParser sparser = sfactory.newSAXParser();
                XMLReader rssReader = sparser.getXMLReader();
                rssReader.setContentHandler(handler);
                inputStreamReader = new InputStreamReader(instream, DEFAULT_CHARSET);
                rssReader.parse(new InputSource(inputStreamReader));
            } catch (SAXException e) {
                Log.e(LOG_TAG, "getResponseData exception", e);
            } catch (ParserConfigurationException e) {
                Log.e(LOG_TAG, "getResponseData exception", e);
            } finally {
                AsyncHttpClient.silentCloseInputStream(instream);
                if (inputStreamReader != null) {
                    try {
                        inputStreamReader.close();
                    } catch (IOException e) {
                        /*ignore*/ }
                }
            }
        }
    }
    return null;
}

From source file:com.fdwills.external.http.SaxAsyncHttpResponseHandler.java

/**
 * Deconstructs response into given content handler
 *
 * @param entity returned HttpEntity/*w w  w. j a v  a 2 s .  c o m*/
 * @return deconstructed response
 * @throws java.io.IOException
 * @see org.apache.http.HttpEntity
 */
@Override
protected byte[] getResponseData(HttpEntity entity) throws IOException {
    if (entity != null) {
        InputStream instream = entity.getContent();
        InputStreamReader inputStreamReader = null;
        if (instream != null) {
            try {
                SAXParserFactory sfactory = SAXParserFactory.newInstance();
                SAXParser sparser = sfactory.newSAXParser();
                XMLReader rssReader = sparser.getXMLReader();
                rssReader.setContentHandler(handler);
                inputStreamReader = new InputStreamReader(instream, DEFAULT_CHARSET);
                rssReader.parse(new InputSource(inputStreamReader));
            } catch (SAXException e) {
                Log.e(LOG_TAG, "getResponseData exception", e);
            } catch (ParserConfigurationException e) {
                Log.e(LOG_TAG, "getResponseData exception", e);
            } finally {
                AsyncHttpClient.silentCloseInputStream(instream);
                if (inputStreamReader != null) {
                    try {
                        inputStreamReader.close();
                    } catch (IOException e) { /*ignore*/
                    }
                }
            }
        }
    }
    return null;
}

From source file:org.gots.weather.provider.google.GoogleWeatherTask.java

@Override
protected WeatherConditionInterface doInBackground(Object... arg0) {
    if (force || ws == null) {

        try {//from   w w w.ja v  a  2  s.  co  m

            // android.os.Debug.waitForDebugger();
            /*************/

            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url.toURI());

            // create a response handler
            ResponseHandler<String> responseHandler = new BasicResponseHandler();

            String responseBody = httpclient.execute(httpget, responseHandler);
            // Log.d(DEBUG_TAG, "response from httpclient:n "+responseBody);

            ByteArrayInputStream is = new ByteArrayInputStream(responseBody.getBytes());

            /* Get a SAXParser from the SAXPArserFactory. */
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();

            /* Get the XMLReader of the SAXParser we created. */
            XMLReader xr = sp.getXMLReader();

            /* Create a new ContentHandler and apply it to the XML-Reader */
            GoogleWeatherHandler gwh = new GoogleWeatherHandler();
            xr.setContentHandler(gwh);

            // InputSource is = new InputSource(url.openStream());
            /* Parse the xml-data our URL-call returned. */
            xr.parse(new InputSource(is));

            /* Our Handler now provides the parsed weather-data to us. */
            ws = gwh.getWeatherSet();
        } catch (Exception e) {
            Log.e("WeatherManager", "WeatherQueryError", e);

        }
        force = false;
    }
    Calendar requestCalendar = Calendar.getInstance();
    requestCalendar.setTime(requestedDay);
    if (ws == null)
        return new WeatherCondition(requestedDay);
    else if (requestCalendar.get(Calendar.DAY_OF_YEAR) == Calendar.getInstance().get(Calendar.DAY_OF_YEAR))
        return ws.getWeatherCurrentCondition();
    else if (requestCalendar.get(Calendar.DAY_OF_YEAR) > Calendar.getInstance().get(Calendar.DAY_OF_YEAR))
        return ws.getWeatherForecastConditions().get(
                requestCalendar.get(Calendar.DAY_OF_YEAR) - Calendar.getInstance().get(Calendar.DAY_OF_YEAR));
    return new WeatherCondition(requestedDay);

}

From source file:com.rightscale.service.FeedScraper.java

public void run() {
    int pollPeriod = DEFAULT_POLL_PERIOD;

    while (false == _shouldStop) {
        boolean error = false;
        int interesting = 0;

        try {/*from  ww w  .j a  v  a2  s . c  om*/
            HttpEntity response = getEntity(null, null);

            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();

            AtomParser parser = new AtomParser(this);
            xr.setContentHandler(parser);
            xr.parse(new InputSource(response.getContent()));
            response.consumeContent();
            interesting = parser.getNumInteresting();
        } catch (Exception e) {
            Log.e("FeedScraper", e.getClass().getName());
            e.printStackTrace();
            error = true;
        }

        if (error) {
            pollPeriod = ERROR_POLL_PERIOD;
        } else if (interesting == 0) {
            pollPeriod = (int) (pollPeriod * 1.5);
            pollPeriod = Math.max(pollPeriod, MAX_POLL_PERIOD);
        } else {
            pollPeriod = DEFAULT_POLL_PERIOD;
        }

        try {
            Thread.sleep(pollPeriod);
        } catch (InterruptedException e) {
            //someone may have set _shouldStop on us...
        }
    }
}

From source file:com.comcast.cqs.test.stress.CqsStressTester.java

public static List<CQSMessage> deserializeMessage(String serializedMessage) {
    javax.xml.parsers.SAXParserFactory fac = new org.apache.xerces.jaxp.SAXParserFactoryImpl();
    javax.xml.parsers.SAXParser saxParser;
    SaxHandler p = new SaxHandler();
    try {//from  w  w  w .j a  v a  2  s  .  c o  m
        saxParser = fac.newSAXParser();
        saxParser.parse(new ByteArrayInputStream(serializedMessage.getBytes()), p);
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    CQSMessage cqsMessage = null;

    try {
        if (p.getValueByKey("Body") == null) {
            return new ArrayList<CQSMessage>();
        }
        cqsMessage = new CQSMessage(p.getValueByKey("Body"), p.getAttributes());
        cqsMessage.setMessageId(p.getValueByKey("MessageId"));
        cqsMessage.setReceiptHandle(p.getValueByKey("ReceiptHandle"));
        cqsMessage.setMD5OfBody(p.getValueByKey("MD5OfBody"));
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return java.util.Arrays.asList(cqsMessage);
}

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

@Transactional
public void load() {
    // 1. Check wether we are allowed to load default content into the DB
    final List<SyncopeConf> res = confDAO.findAll();

    if (res == null || res.size() > 0) {
        LOG.info("Data found in the database, leaving untouched");
        return;/*from   ww w .ja va  2s.  c om*/
    }

    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());

            final String updateViews = views.get(idx).toString().replaceAll("\\n", " ");
            entityManager.createNativeQuery(updateViews).executeUpdate();
        }

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

    // 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());

            final String updateIndexed = indexes.get(idx).toString();
            entityManager.createNativeQuery(updateIndexed).executeUpdate();
        }

        LOG.debug("Indexes created, go for default content");
    } catch (Exception e) {
        LOG.error("While creating indexes", e);
    }

    // noop workflow
    //        entityManager.createNativeQuery("DELETE FROM ACT_GE_PROPERTY").executeUpdate();

    // 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 (Exception e) {
        LOG.error("While loading default content", e);
    }
}

From source file:fr.ybo.transportsbordeaux.tbcapi.Keolis.java

/**
 * @param <ObjetKeolis> type d'objet Keolis.
 * @param url           url.//from  w  w  w .jav  a2s .c o m
 * @param handler       handler.
 * @return liste d'objets Keolis.
 * @throws TbcErreurReseaux en cas d'erreur rseau.
 */
private <ObjetKeolis> List<ObjetKeolis> appelKeolis(String url, KeolisHandler<ObjetKeolis> handler)
        throws ErreurReseau {
    LOG_YBO.debug("Appel d'une API Keolis sur l'url '" + url + '\'');
    long startTime = System.nanoTime() / 1000;
    HttpClient httpClient = HttpUtils.getHttpClient();
    HttpUriRequest httpPost = new HttpPost(url);
    List<ObjetKeolis> answer;
    try {
        HttpResponse reponse = httpClient.execute(httpPost);
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        if (reponse == null || reponse.getEntity() == null) {
            throw new ErreurReseau("Erreur lors de la rcupration de la rponse http");
        }
        reponse.getEntity().writeTo(ostream);
        String contenu = new String(ostream.toByteArray(), "ISO-8859-1");
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        parser.parse(new ByteArrayInputStream(contenu.getBytes("UTF-8")), handler);
        answer = handler.getObjets();
    } catch (IOException socketException) {
        throw new ErreurReseau(socketException);
    } catch (SAXException saxException) {
        throw new ErreurReseau(saxException);
    } catch (ParserConfigurationException exception) {
        throw new KeolisException("Erreur lors de l'appel  l'API keolis", exception);
    }
    if (answer == null) {
        throw new ErreurReseau("Erreur dans la rponse donnes par Keolis.");
    }
    long elapsedTime = System.nanoTime() / 1000 - startTime;
    LOG_YBO.debug("Rponse de Keolis en " + elapsedTime + "s");
    return answer;
}