Example usage for org.xml.sax XMLReader setContentHandler

List of usage examples for org.xml.sax XMLReader setContentHandler

Introduction

In this page you can find the example usage for org.xml.sax XMLReader setContentHandler.

Prototype

public void setContentHandler(ContentHandler handler);

Source Link

Document

Allow an application to register a content event handler.

Usage

From source file:com.cloudhopper.sxmp.SxmpParser.java

/**
public Node parse(InputSource source) throws IOException, SAXException {
//        _dtd=null;//w w  w  . j ava 2s . c  o m
Handler handler = new Handler();
XMLReader reader = _parser.getXMLReader();
reader.setContentHandler(handler);
reader.setErrorHandler(handler);
reader.setEntityResolver(handler);
if (logger.isDebugEnabled())
    logger.debug("parsing: sid=" + source.getSystemId() + ",pid=" + source.getPublicId());
_parser.parse(source, handler);
if (handler.error != null)
    throw handler.error;
Node root = (Node)handler.root;
handler.reset();
return root;
}
        
public synchronized Node parse(String xml) throws IOException, SAXException {
ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes());
return parse(is);
}
        
public synchronized Node parse(File file) throws IOException, SAXException {
return parse(new InputSource(file.toURI().toURL().toString()));
}
        
public synchronized Node parse(InputStream in) throws IOException, SAXException {
//_dtd=null;
Handler handler = new Handler();
XMLReader reader = _parser.getXMLReader();
reader.setContentHandler(handler);
reader.setErrorHandler(handler);
reader.setEntityResolver(handler);
_parser.parse(new InputSource(in), handler);
if (handler.error != null)
    throw handler.error;
Node root = (Node)handler.root;
handler.reset();
return root;
}
 */

public Operation parse(InputStream in)
        throws SxmpParsingException, IOException, SAXException, ParserConfigurationException {
    // create a new SAX parser
    SAXParserFactory factory = SAXParserFactory.newInstance();
    //factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

    SAXParser parser = factory.newSAXParser();
    //_parser.getXMLReader().setFeature("http://xml.org/sax/features/validation", validating);
    parser.getXMLReader().setFeature("http://xml.org/sax/features/namespaces", true);
    parser.getXMLReader().setFeature("http://xml.org/sax/features/namespace-prefixes", true);
    parser.getXMLReader().setFeature("http://javax.xml.XMLConstants/feature/secure-processing", true);

    //_dtd=null;
    Handler handler = new Handler();
    XMLReader reader = parser.getXMLReader();
    reader.setContentHandler(handler);
    reader.setErrorHandler(handler);
    reader.setEntityResolver(handler);

    // try parsing (may throw an SxmpParsingException in the handler)
    try {
        parser.parse(new InputSource(in), handler);
    } catch (com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException e) {
        throw new SxmpParsingException(SxmpErrorCode.INVALID_XML, "XML encoding mismatch", null);
    }

    // check if there was an error
    if (handler.error != null) {
        throw handler.error;
    }

    // check to see if an operation was actually parsed
    if (handler.getOperation() == null) {
        throw new SxmpParsingException(SxmpErrorCode.MISSING_REQUIRED_ELEMENT,
                "The operation type [" + handler.operationType.getValue() + "] requires a request element",
                new PartialOperation(handler.operationType));
    }

    // if we got here, an operation was parsed -- now we need to validate it
    // to make sure that it has all required elements
    try {
        handler.getOperation().validate();
    } catch (SxmpErrorException e) {
        throw new SxmpParsingException(e.getErrorCode(), e.getErrorMessage(), handler.getOperation());
    }

    return handler.getOperation();
}

From source file:net.ontopia.topicmaps.xml.TMXMLReader.java

@Override
public void importInto(TopicMapIF topicmap) throws IOException {
    // Check that store is ok
    TopicMapStoreIF store = topicmap.getStore();
    if (store == null)
        throw new IOException("Topic map not connected to a store.");

    XMLReader parser;
    try {/*  ww  w  .jav  a 2 s.  c om*/
        parser = DefaultXMLReaderFactory.createXMLReader();
    } catch (SAXException e) {
        throw new IOException("Problems occurred when creating SAX2 XMLReader: " + e.getMessage());
    }

    // Register content handlers
    ContentHandler handler = new TMXMLContentHandler(topicmap, base_address);
    if (validate)
        handler = new ValidatingContentHandler(handler, getTMXMLSchema(), true);
    parser.setContentHandler(handler);

    // Parse input source
    try {
        parser.parse(source);
    } catch (SAXException e) {
        if (e.getException() instanceof IOException)
            throw (IOException) e.getException();
        throw new OntopiaRuntimeException(e);
        //throw new IOException("XML related problem: " + e.toString());
    }
}

From source file:self.philbrown.javaQuery.AjaxTask.java

@Override
protected TaskResponse doInBackground(Void... arg0) {
    //handle cached responses
    CachedResponse cachedResponse = URLresponses
            .get(String.format(Locale.US, "%s_?=%s", options.url(), options.dataType()));
    //handle ajax caching option
    if (cachedResponse != null) {
        if (options.cache()) {
            if (new Date().getTime() - cachedResponse.timestamp.getTime() < options.cacheTimeout()) {
                //return cached response
                Success s = new Success();
                s.obj = cachedResponse.response;
                s.reason = "cached response";
                s.headers = null;//w  w w  . ja  v a  2 s.  co  m
                return s;
            }
        }

    }

    if (request == null) {
        String type = options.type();
        if (type == null)
            type = "GET";
        if (type.equalsIgnoreCase("DELETE")) {
            request = new HttpDelete(options.url());
        } else if (type.equalsIgnoreCase("GET")) {
            request = new HttpGet(options.url());
        } else if (type.equalsIgnoreCase("HEAD")) {
            request = new HttpHead(options.url());
        } else if (type.equalsIgnoreCase("OPTIONS")) {
            request = new HttpOptions(options.url());
        } else if (type.equalsIgnoreCase("POST")) {
            request = new HttpPost(options.url());
        } else if (type.equalsIgnoreCase("PUT")) {
            request = new HttpPut(options.url());
        } else if (type.equalsIgnoreCase("TRACE")) {
            request = new HttpTrace(options.url());
        } else if (type.equalsIgnoreCase("CUSTOM")) {
            try {
                request = options.customRequest();
            } catch (Exception e) {
                request = null;
            }

            if (request == null) {
                Log.w("javaQuery.ajax",
                        "CUSTOM type set, but AjaxOptions.customRequest is invalid. Defaulting to GET.");
                request = new HttpGet();
            }

        } else {
            //default to GET
            request = new HttpGet();
        }
    }

    Map<String, Object> args = new HashMap<String, Object>();
    args.put("options", options);
    args.put("request", request);
    EventCenter.trigger("ajaxPrefilter", args, null);

    if (options.headers() != null) {
        if (options.headers().authorization() != null) {
            options.headers()
                    .authorization(options.headers().authorization() + " " + options.getEncodedCredentials());
        } else if (options.username() != null) {
            //guessing that authentication is basic
            options.headers().authorization("Basic " + options.getEncodedCredentials());
        }

        for (Entry<String, String> entry : options.headers().map().entrySet()) {
            request.addHeader(entry.getKey(), entry.getValue());
        }
    }

    if (options.data() != null) {
        try {
            Method setEntity = request.getClass().getMethod("setEntity", new Class<?>[] { HttpEntity.class });
            if (options.processData() == null) {
                setEntity.invoke(request, new StringEntity(options.data().toString()));
            } else {
                Class<?> dataProcessor = Class.forName(options.processData());
                Constructor<?> constructor = dataProcessor.getConstructor(new Class<?>[] { Object.class });
                setEntity.invoke(request, constructor.newInstance(options.data()));
            }
        } catch (Throwable t) {
            Log.w("Ajax", "Could not post data");
        }
    }

    HttpParams params = new BasicHttpParams();

    if (options.timeout() != 0) {
        HttpConnectionParams.setConnectionTimeout(params, options.timeout());
        HttpConnectionParams.setSoTimeout(params, options.timeout());
    }

    HttpClient client = new DefaultHttpClient(params);

    HttpResponse response = null;
    try {

        if (options.cookies() != null) {
            CookieStore cookies = new BasicCookieStore();
            for (Entry<String, String> entry : options.cookies().entrySet()) {
                cookies.addCookie(new BasicClientCookie(entry.getKey(), entry.getValue()));
            }
            HttpContext httpContext = new BasicHttpContext();
            httpContext.setAttribute(ClientContext.COOKIE_STORE, cookies);
            response = client.execute(request, httpContext);
        } else {
            response = client.execute(request);
        }

        if (options.dataFilter() != null) {
            if (options.context() != null)
                options.dataFilter().invoke(new $(options.context()), response, options.dataType());
            else
                options.dataFilter().invoke(null, response, options.dataType());
        }

        StatusLine statusLine = response.getStatusLine();

        Function function = options.statusCode().get(statusLine);
        if (function != null) {
            if (options.context() != null)
                function.invoke(new $(options.context()));
            else
                function.invoke(null);
        }

        if (statusLine.getStatusCode() >= 300) {
            //an error occurred
            Error e = new Error();
            AjaxError error = new AjaxError();
            error.request = request;
            error.options = options;
            e.status = statusLine.getStatusCode();
            e.reason = statusLine.getReasonPhrase();
            error.status = e.status;
            error.reason = e.reason;
            e.headers = response.getAllHeaders();
            e.error = error;
            return e;
        } else {
            //handle dataType
            String dataType = options.dataType();
            if (dataType == null)
                dataType = "text";
            Object parsedResponse = null;
            boolean success = true;
            try {
                if (dataType.equalsIgnoreCase("text") || dataType.equalsIgnoreCase("html")) {
                    parsedResponse = parseText(response);
                } else if (dataType.equalsIgnoreCase("xml")) {
                    if (options.customXMLParser() != null) {
                        InputStream is = response.getEntity().getContent();
                        if (options.SAXContentHandler() != null)
                            options.customXMLParser().parse(is, options.SAXContentHandler());
                        else
                            options.customXMLParser().parse(is, new DefaultHandler());
                        parsedResponse = "Response handled by custom SAX parser";
                    } else if (options.SAXContentHandler() != null) {
                        InputStream is = response.getEntity().getContent();

                        SAXParserFactory factory = SAXParserFactory.newInstance();

                        factory.setFeature("http://xml.org/sax/features/namespaces", false);
                        factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true);

                        SAXParser parser = factory.newSAXParser();

                        XMLReader reader = parser.getXMLReader();
                        reader.setContentHandler(options.SAXContentHandler());
                        reader.parse(new InputSource(is));
                        parsedResponse = "Response handled by custom SAX content handler";
                    } else {
                        parsedResponse = parseXML(response);
                    }
                } else if (dataType.equalsIgnoreCase("json")) {
                    parsedResponse = parseJSON(response);
                } else if (dataType.equalsIgnoreCase("script")) {
                    parsedResponse = parseScript(response);
                } else if (dataType.equalsIgnoreCase("image")) {
                    parsedResponse = parseImage(response);
                }
            } catch (ClientProtocolException cpe) {
                if (options.debug())
                    cpe.printStackTrace();
                success = false;
                Error e = new Error();
                AjaxError error = new AjaxError();
                error.request = request;
                error.options = options;
                e.status = statusLine.getStatusCode();
                e.reason = statusLine.getReasonPhrase();
                error.status = e.status;
                error.reason = e.reason;
                e.headers = response.getAllHeaders();
                e.error = error;
                return e;
            } catch (Exception ioe) {
                if (options.debug())
                    ioe.printStackTrace();
                success = false;
                Error e = new Error();
                AjaxError error = new AjaxError();
                error.request = request;
                error.options = options;
                e.status = statusLine.getStatusCode();
                e.reason = statusLine.getReasonPhrase();
                error.status = e.status;
                error.reason = e.reason;
                e.headers = response.getAllHeaders();
                e.error = error;
                return e;
            }
            if (success) {
                //Handle cases where successful requests still return errors (these include
                //configurations in AjaxOptions and HTTP Headers
                String key = String.format(Locale.US, "%s_?=%s", options.url(), options.dataType());
                CachedResponse cache = URLresponses.get(key);
                Date now = new Date();
                //handle ajax caching option
                if (cache != null) {
                    if (options.cache()) {
                        if (now.getTime() - cache.timestamp.getTime() < options.cacheTimeout()) {
                            parsedResponse = cache;
                        } else {
                            cache.response = parsedResponse;
                            cache.timestamp = now;
                            synchronized (URLresponses) {
                                URLresponses.put(key, cache);
                            }
                        }
                    }

                }
                //handle ajax ifModified option
                Header[] lastModifiedHeaders = response.getHeaders("last-modified");
                if (lastModifiedHeaders.length >= 1) {
                    try {
                        Header h = lastModifiedHeaders[0];
                        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
                        Date lastModified = format.parse(h.getValue());
                        if (options.ifModified() && lastModified != null) {
                            if (cache.lastModified != null && cache.lastModified.compareTo(lastModified) == 0) {
                                //request response has not been modified. 
                                //Causes an error instead of a success.
                                Error e = new Error();
                                AjaxError error = new AjaxError();
                                error.request = request;
                                error.options = options;
                                e.status = statusLine.getStatusCode();
                                e.reason = statusLine.getReasonPhrase();
                                error.status = e.status;
                                error.reason = e.reason;
                                e.headers = response.getAllHeaders();
                                e.error = error;
                                Function func = options.statusCode().get(304);
                                if (func != null) {
                                    if (options.context() != null)
                                        func.invoke(new $(options.context()));
                                    else
                                        func.invoke(null);
                                }
                                return e;
                            } else {
                                cache.lastModified = lastModified;
                                synchronized (URLresponses) {
                                    URLresponses.put(key, cache);
                                }
                            }
                        }
                    } catch (Throwable t) {
                        Log.e("Ajax", "Could not parse Last-Modified Header");
                    }

                }

                //Now handle a successful request

                Success s = new Success();
                s.obj = parsedResponse;
                s.reason = statusLine.getReasonPhrase();
                s.headers = response.getAllHeaders();
                return s;
            }
            //success
            Success s = new Success();
            s.obj = parsedResponse;
            s.reason = statusLine.getReasonPhrase();
            s.headers = response.getAllHeaders();
            return s;
        }

    } catch (Throwable t) {
        if (options.debug())
            t.printStackTrace();
        if (t instanceof java.net.SocketTimeoutException) {
            Error e = new Error();
            AjaxError error = new AjaxError();
            error.request = request;
            error.options = options;
            e.status = 0;
            String reason = t.getMessage();
            if (reason == null)
                reason = "Socket Timeout";
            e.reason = reason;
            error.status = e.status;
            error.reason = e.reason;
            if (response != null)
                e.headers = response.getAllHeaders();
            else
                e.headers = new Header[0];
            e.error = error;
            return e;
        }
        return null;
    }
}

From source file:com.flipzu.flipzu.FlipInterface.java

public FlipUser getUser(String username, String token) throws IOException {
    String data = "username=" + username + "&access_token=" + token;
    String url = WSServer + "/api/get_user.xml";

    debug.logV(TAG, "getUser for username " + username);

    DefaultHttpClient hc = new DefaultHttpClient();

    ResponseHandler<String> res = new ResponseHandler<String>() {
        public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }/*from   w  ww .j  av  a  2  s. co  m*/

            HttpEntity entity = response.getEntity();
            return entity == null ? null : EntityUtils.toString(entity, "UTF-8");
        }
    };

    HttpPost postMethod = new HttpPost(url);

    postMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

    if (data != null) {
        StringEntity tmp = null;
        try {
            tmp = new StringEntity(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            debug.logE(TAG, "getUser ERROR", e.getCause());
            return null;
        }

        postMethod.setEntity(tmp);
    }

    String response = hc.execute(postMethod, res);

    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        UserHandler myUserHandler = new UserHandler();
        xr.setContentHandler(myUserHandler);

        InputSource inputSource = new InputSource();
        inputSource.setEncoding("UTF-8");
        inputSource.setCharacterStream(new StringReader(response));

        xr.parse(inputSource);

        FlipUser parsedData = myUserHandler.getParsedData();

        return parsedData;

    } catch (ParserConfigurationException e) {
        return null;
    } catch (SAXException e) {
        return null;
    }
}

From source file:edu.lternet.pasta.dml.dataquery.DataquerySpecification.java

/**
 * Set up the SAX parser for reading the XML serialized query
 *///from   w w w .ja  va  2 s  .  c o m
private XMLReader initializeParser() {
    XMLReader parser = null;

    // Set up the SAX document handlers for parsing
    try {

        // Get an instance of the parser
        parser = XMLReaderFactory.createXMLReader(parserName);

        // Set the ContentHandler to this instance
        parser.setContentHandler(this);

        // Set the error Handler to this instance
        parser.setErrorHandler(this);

    } catch (Exception e) {
        System.err.println("Error in QuerySpcecification.initializeParser " + e.toString());
    }

    return parser;
}

From source file:com.flipzu.flipzu.FlipInterface.java

private FlipUser setFollowUnfollow(String username, String token, boolean follow) throws IOException {
    String data = "username=" + username + "&access_token=" + token;
    String url;/* ww w .j a v a 2s. c o m*/
    if (follow) {
        url = WSServer + "/api/set_follow.xml";
    } else {
        url = WSServer + "/api/set_unfollow.xml";
    }

    debug.logV(TAG, "setFollow for username " + username);

    DefaultHttpClient hc = new DefaultHttpClient();

    ResponseHandler<String> res = new ResponseHandler<String>() {
        public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }

            HttpEntity entity = response.getEntity();
            return entity == null ? null : EntityUtils.toString(entity, "UTF-8");
        }
    };

    HttpPost postMethod = new HttpPost(url);

    postMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

    if (data != null) {
        StringEntity tmp = null;
        try {
            tmp = new StringEntity(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            debug.logE(TAG, "getUser ERROR", e.getCause());
            return null;
        }

        postMethod.setEntity(tmp);
    }

    String response = hc.execute(postMethod, res);

    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        UserHandler myUserHandler = new UserHandler();
        xr.setContentHandler(myUserHandler);

        InputSource inputSource = new InputSource();
        inputSource.setEncoding("UTF-8");
        inputSource.setCharacterStream(new StringReader(response));

        xr.parse(inputSource);

        FlipUser parsedData = myUserHandler.getParsedData();

        return parsedData;

    } catch (ParserConfigurationException e) {
        return null;
    } catch (SAXException e) {
        return null;
    }
}

From source file:com.flipzu.flipzu.FlipInterface.java

private List<BroadcastDataSet> sendRequest(String url, String data) throws IOException {
    DefaultHttpClient hc = new DefaultHttpClient();

    ResponseHandler<String> res = new ResponseHandler<String>() {
        public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }//from   ww w.  j  a  v a2  s .c o m

            HttpEntity entity = response.getEntity();
            return entity == null ? null : EntityUtils.toString(entity, "UTF-8");
        }
    };

    HttpPost postMethod = new HttpPost(url);

    postMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

    if (data != null) {
        StringEntity tmp = null;
        try {
            tmp = new StringEntity(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            debug.logE(TAG, "sendRequest ERROR", e.getCause());
            return null;
        }

        postMethod.setEntity(tmp);
    }

    String response = hc.execute(postMethod, res);

    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        TimelineHandler myTimelineHandler = new TimelineHandler();
        xr.setContentHandler(myTimelineHandler);

        InputSource inputSource = new InputSource();
        inputSource.setEncoding("UTF-8");
        inputSource.setCharacterStream(new StringReader(response));

        xr.parse(inputSource);

        List<BroadcastDataSet> parsedDataSet = myTimelineHandler.getParsedData();

        return parsedDataSet;

    } catch (ParserConfigurationException e) {
        return null;
    } catch (SAXException e) {
        return null;
    }
}

From source file:de.suse.swamp.core.util.BugzillaTools.java

private synchronized void xmlToData(String url) throws Exception {

    HttpState initialState = new HttpState();

    String authUsername = swamp.getProperty("BUGZILLA_AUTH_USERNAME");
    String authPassword = swamp.getProperty("BUGZILLA_AUTH_PWD");

    if (authUsername != null && authUsername.length() != 0) {
        Credentials defaultcreds = new UsernamePasswordCredentials(authUsername, authPassword);
        initialState.setCredentials(AuthScope.ANY, defaultcreds);
    } else {//from  w ww.j  a  v a  2 s .com
        Cookie[] cookies = getCookies();
        for (int i = 0; i < cookies.length; i++) {
            initialState.addCookie(cookies[i]);
            Logger.DEBUG("Added Cookie: " + cookies[i].getName() + "=" + cookies[i].getValue(), log);
        }
    }
    HttpClient httpclient = new HttpClient();
    httpclient.setState(initialState);
    HttpMethod httpget = new GetMethod(url);
    try {
        httpclient.executeMethod(httpget);
    } catch (Exception e) {
        throw new Exception("Could not get URL " + url);
    }

    String content = httpget.getResponseBodyAsString();
    char[] chars = content.toCharArray();

    // removing illegal characters from bugzilla output.
    for (int i = 0; i < chars.length; i++) {
        if (chars[i] < 32 && chars[i] != 9 && chars[i] != 10 && chars[i] != 13) {
            Logger.DEBUG("Removing illegal character: '" + chars[i] + "' on position " + i, log);
            chars[i] = ' ';
        }
    }
    Logger.DEBUG(String.valueOf(chars), log);
    CharArrayReader reader = new CharArrayReader(chars);
    XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
    parser.setFeature("http://xml.org/sax/features/validation", false);
    // disable parsing of external dtd
    parser.setFeature("http://xml.org/sax/features/external-general-entities", false);
    parser.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    parser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    parser.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    // get XML File
    BugzillaReader handler = new BugzillaReader();
    parser.setContentHandler(handler);
    InputSource source = new InputSource();
    source.setCharacterStream(reader);
    source.setEncoding("utf-8");
    try {
        parser.parse(source);
    } catch (SAXParseException spe) {
        spe.printStackTrace();
        throw spe;
    }
    httpget.releaseConnection();
    if (errormsg != null) {
        throw new Exception(errormsg);
    }
}

From source file:com.xmobileapp.rockplayer.LastFmEventImporter.java

/*********************************
 * //w ww. ja v a 2 s.  c om
 * Get Artist Events
 * @throws SAXException 
 * @throws ParserConfigurationException 
 *
 *********************************/
public void getArtistEvents() throws SAXException, ParserConfigurationException {
    /*
     * Initialize Artist Cursor
     */
    artistCursor = ((RockPlayer) context).contentResolver.query(MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI,
            ((RockPlayer) context).ARTIST_COLS, // we should minimize the number of columns
            null, // all albums 
            null, // parameters to the previous parameter - which is null also 
            null // sort order, SQLite-like
    );

    /*
     * Declare & Initialize some vars
     */
    String artistName = null;
    String artistNameFiltered = null;
    String artistConcertFileName = null;
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxParserFactory.newSAXParser();
    XMLReader xmlReader = saxParser.getXMLReader();
    XMLArtistEventHandler xmlHandler = new XMLArtistEventHandler();
    xmlHandler.myLocation = this.myLocation;
    xmlReader.setContentHandler(xmlHandler);

    /*
     * Set Distance Limit
     */
    xmlHandler.MAX_DISTANCE = this.concertRadius;

    /*
     * Loop through the artists
     */
    artistCursor.moveToFirst();
    for (int i = 0; i < artistCursor.getCount(); i++) {
        /*
         * Get artist name
         */
        artistName = artistCursor.getString(artistCursor.getColumnIndex(MediaStore.Audio.Artists.ARTIST));
        if (artistName.equals("<unknown>")) {
            artistCursor.moveToNext();
            continue;
        }
        artistNameFiltered = filterString(artistName);
        artistConcertFileName = ((RockPlayer) context).FILEX_CONCERT_PATH + validateFileName(artistName);

        /*
         * UI feedback
         */
        Bundle data = new Bundle();
        data.putString("info", artistName);
        Message msg = new Message();
        msg.setData(data);
        ((RockPlayer) context).analyseConcertInfoHandler.sendMessage(msg);

        /*
         * If we dont have yet or info is too old, update the concert info of this artist
         */
        if (hasConcertInfo(artistName) == false || concertInfoNeedsUpdate(artistName) == true) {
            Log.i("INET", "Getting concert info from LastFM");
            if (hasConcertInfo(artistName) == false)
                Log.i("INET", "Because there is no concert info yet");
            if (concertInfoNeedsUpdate(artistName) == true)
                Log.i("INET", "Because Info is too old");

            File artistConcertFile = new File(artistConcertFileName);
            if (!artistConcertFile.exists()) {
                try {
                    artistConcertFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            URL lastFmApiRequest;
            try {
                lastFmApiRequest = new URL(
                        this.LAST_FM_API_URL + "&artist=" + URLEncoder.encode(artistNameFiltered));
                BufferedInputStream bufferedURLStream = new BufferedInputStream(lastFmApiRequest.openStream());
                BufferedOutputStream bufferedFileWriter = new BufferedOutputStream(
                        new FileOutputStream(artistConcertFile));

                byte[] buf = new byte[1024];
                int len;
                while ((len = bufferedURLStream.read(buf)) >= 0)
                    bufferedFileWriter.write(buf, 0, len);
                bufferedURLStream.close();
                bufferedFileWriter.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        /*
         * get event list from cached XML files
         */
        File artistConcertFile = new File(artistConcertFileName);
        if (artistConcertFile.exists() && artistConcertFile.length() > 0) {
            try {
                BufferedReader xmlFileReader = new BufferedReader(
                        new InputStreamReader(new FileInputStream(artistConcertFile)));
                xmlHandler.resetList();
                xmlHandler.artist = artistName;
                xmlReader.parse(new InputSource(xmlFileReader));
                insertListInListByDate(xmlHandler.artistEventList);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        artistCursor.moveToNext();
    }

    /*
     * Debug
     */
    ArtistEvent artistEventDebug = null;
    if (!artistEventList.isEmpty()) {
        artistEventList.getFirst();
        ListIterator<ArtistEvent> listIterator = artistEventList.listIterator(0);
        for (artistEventDebug = listIterator.next(); listIterator
                .hasNext() == true; artistEventDebug = listIterator.next()) {
            if (artistEventDebug != null)
                Log.i("DBG", artistEventDebug.date + " " + artistEventDebug.city);
            //   Log.i("DBG", artistEventDebug.date+" "+artistEventDebug.city+" "+artistEventDebug.artist);
            else
                Log.i("DBG", "NULL");
        }
    }
    /*
     * Update Adapter
     */
    eventLinkedListAdapter = new EventLinkedListAdapter(context, R.layout.eventlist_item, artistEventList);
    if (eventLinkedListAdapter == null)
        Log.i("NULL", "NULL");
    ((RockPlayer) context).updateEventListHandler.sendEmptyMessage(0);

    /*
     * Give feedback to the user
     */
    Bundle data = new Bundle();
    Message msg = new Message();
    data.putString("info", "Done!");
    msg.setData(data);
    ((RockPlayer) context).analyseConcertInfoHandler.sendMessage(msg);
}

From source file:com.entertailion.java.fling.FlingFrame.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  ava2  s  . 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());
                            trackedServers.add(dialServer);
                        }
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "parse device description", e);
                    }
                }
            }
        }).start();
    }
}