Example usage for android.util Xml parse

List of usage examples for android.util Xml parse

Introduction

In this page you can find the example usage for android.util Xml parse.

Prototype

public static void parse(InputStream in, Encoding encoding, ContentHandler contentHandler)
        throws IOException, SAXException 

Source Link

Document

Parses xml from the given input stream and fires events on the given SAX handler.

Usage

From source file:vn.mbm.phimp.me.gallery3d.picasa.PicasaApi.java

public int getAlbumPhotos(AccountManager accountManager, SyncResult syncResult, AlbumEntry album,
        GDataParser.EntryHandler handler) {
    // Construct the query URL for user albums.
    StringBuilder builder = new StringBuilder(BASE_URL);
    builder.append("user/");
    builder.append(Uri.encode(mAuth.user));
    builder.append("/albumid/");
    builder.append(album.id);/*from ww w.ja v  a2s. c  om*/
    builder.append(BASE_QUERY_STRING);
    builder.append("&kind=photo");
    try {
        // Send the request.
        synchronized (mOperation) {
            GDataClient.Operation operation = mOperation;
            operation.inOutEtag = album.photosEtag;
            boolean retry = false;
            int numRetries = 1;
            do {
                retry = false;
                synchronized (mClient) {
                    mClient.get(builder.toString(), operation);
                }
                switch (operation.outStatus) {
                case HttpStatus.SC_OK:
                    break;
                case HttpStatus.SC_NOT_MODIFIED:
                    return RESULT_NOT_MODIFIED;
                case HttpStatus.SC_FORBIDDEN:
                case HttpStatus.SC_UNAUTHORIZED:
                    // We need to reset the authtoken and retry only once.
                    if (!retry) {
                        retry = true;
                        accountManager.invalidateAuthToken(PicasaService.SERVICE_NAME, mAuth.authToken);
                    }
                    if (numRetries == 0) {
                        ++syncResult.stats.numAuthExceptions;
                    }
                    break;
                default:
                    Log.e(TAG, "getAlbumPhotos: " + builder.toString() + ", unexpected status code "
                            + operation.outStatus);
                    ++syncResult.stats.numIoExceptions;
                    return RESULT_ERROR;
                }
                --numRetries;
            } while (retry && numRetries >= 0);

            // Store the new ETag for the album/photos feed.
            album.photosEtag = operation.inOutEtag;

            // Parse the response.
            synchronized (mParser) {
                GDataParser parser = mParser;
                parser.setEntry(mPhotoInstance);
                parser.setHandler(handler);
                try {
                    Xml.parse(operation.outBody, Xml.Encoding.UTF_8, parser);
                } catch (SocketException e) {
                    Log.e(TAG, "getAlbumPhotos: " + e);
                    ++syncResult.stats.numIoExceptions;
                    e.printStackTrace();
                    return RESULT_ERROR;
                }
            }
        }
        return RESULT_OK;
    } catch (IOException e) {
        Log.e(TAG, "getAlbumPhotos: " + e);
        ++syncResult.stats.numIoExceptions;
        e.printStackTrace();
    } catch (SAXException e) {
        Log.e(TAG, "getAlbumPhotos: " + e);
        ++syncResult.stats.numParseExceptions;
        e.printStackTrace();
    }
    return RESULT_ERROR;
}

From source file:com.ocp.picasa.PicasaApi.java

public int getAlbumPhotos(AccountManager accountManager, SyncResult syncResult, AlbumEntry album,
        GDataParser.EntryHandler handler) {
    // Construct the query URL for user albums.
    StringBuilder builder = new StringBuilder(BASE_URL);
    builder.append("user/");
    builder.append(Uri.encode(mAuth.user));
    builder.append("/albumid/");
    builder.append(album.id);/*from  w ww  .j a va2 s. co m*/
    builder.append(BASE_QUERY_STRING);
    builder.append("&kind=photo");
    try {
        // Send the request.
        synchronized (mOperation) {
            GDataClient.Operation operation = mOperation;
            operation.inOutEtag = album.photosEtag;
            boolean retry = false;
            int numRetries = 1;
            do {
                retry = false;
                synchronized (mClient) {
                    mClient.get(builder.toString(), operation);
                }
                switch (operation.outStatus) {
                case HttpStatus.SC_OK:
                    break;
                case HttpStatus.SC_NOT_MODIFIED:
                    return RESULT_NOT_MODIFIED;
                case HttpStatus.SC_FORBIDDEN:
                case HttpStatus.SC_UNAUTHORIZED:
                    // We need to reset the authtoken and retry only once.
                    if (!retry) {
                        retry = true;
                        accountManager.invalidateAuthToken(PicasaService.SERVICE_NAME, mAuth.authToken);
                    }
                    if (numRetries == 0) {
                        ++syncResult.stats.numAuthExceptions;
                    }
                    break;
                default:
                    Log.e(Gallery.TAG, TAG + ": " + "getAlbumPhotos: " + builder.toString()
                            + ", unexpected status code " + operation.outStatus);
                    ++syncResult.stats.numIoExceptions;
                    return RESULT_ERROR;
                }
                --numRetries;
            } while (retry && numRetries >= 0);

            // Store the new ETag for the album/photos feed.
            album.photosEtag = operation.inOutEtag;

            // Parse the response.
            synchronized (mParser) {
                GDataParser parser = mParser;
                parser.setEntry(mPhotoInstance);
                parser.setHandler(handler);
                try {
                    Xml.parse(operation.outBody, Xml.Encoding.UTF_8, parser);
                } catch (SocketException e) {
                    Log.e(Gallery.TAG, TAG + ": " + "getAlbumPhotos: " + e);
                    ++syncResult.stats.numIoExceptions;
                    e.printStackTrace();
                    return RESULT_ERROR;
                }
            }
        }
        return RESULT_OK;
    } catch (IOException e) {
        Log.e(Gallery.TAG, TAG + ": " + "getAlbumPhotos: " + e);
        ++syncResult.stats.numIoExceptions;
        e.printStackTrace();
    } catch (SAXException e) {
        Log.e(Gallery.TAG, TAG + ": " + "getAlbumPhotos: " + e);
        ++syncResult.stats.numParseExceptions;
        e.printStackTrace();
    }
    return RESULT_ERROR;
}

From source file:com.timtory.wmgallery.picasa.PicasaApi.java

public int getAlbumPhotos(AccountManager accountManager, SyncResult syncResult, AlbumEntry album,
        GDataParser.EntryHandler handler) {
    // Construct the query URL for user albums.
    String baseUrl = Settings.Secure.getString(mContentResolver, SETTINGS_PICASA_GDATA_BASE_URL_KEY);
    StringBuilder builder = new StringBuilder(baseUrl != null ? baseUrl : DEFAULT_BASE_URL);
    builder.append("user/");
    builder.append(Uri.encode(mAuth.user));
    builder.append("/albumid/");
    builder.append(album.id);//from  www . ja  va2 s . c o m
    builder.append(BASE_QUERY_STRING);
    builder.append("&kind=photo");
    try {
        // Send the request.
        synchronized (mOperation) {
            GDataClient.Operation operation = mOperation;
            operation.inOutEtag = album.photosEtag;
            boolean retry = false;
            int numRetries = 1;
            do {
                retry = false;
                synchronized (mClient) {
                    mClient.get(builder.toString(), operation);
                }
                switch (operation.outStatus) {
                case HttpStatus.SC_OK:
                    break;
                case HttpStatus.SC_NOT_MODIFIED:
                    return RESULT_NOT_MODIFIED;
                case HttpStatus.SC_FORBIDDEN:
                case HttpStatus.SC_UNAUTHORIZED:
                    // We need to reset the authtoken and retry only once.
                    if (!retry) {
                        retry = true;
                        accountManager.invalidateAuthToken(PicasaService.SERVICE_NAME, mAuth.authToken);
                    }
                    if (numRetries == 0) {
                        ++syncResult.stats.numAuthExceptions;
                    }
                    break;
                default:
                    Log.e(TAG, "getAlbumPhotos: " + builder.toString() + ", unexpected status code "
                            + operation.outStatus);
                    ++syncResult.stats.numIoExceptions;
                    return RESULT_ERROR;
                }
                --numRetries;
            } while (retry && numRetries >= 0);

            // Store the new ETag for the album/photos feed.
            album.photosEtag = operation.inOutEtag;

            // Parse the response.
            synchronized (mParser) {
                GDataParser parser = mParser;
                parser.setEntry(mPhotoInstance);
                parser.setHandler(handler);
                try {
                    Xml.parse(operation.outBody, Xml.Encoding.UTF_8, parser);
                } catch (SocketException e) {
                    Log.e(TAG, "getAlbumPhotos: " + e);
                    ++syncResult.stats.numIoExceptions;
                    e.printStackTrace();
                    return RESULT_ERROR;
                }
            }
        }
        return RESULT_OK;
    } catch (IOException e) {
        Log.e(TAG, "getAlbumPhotos: " + e);
        ++syncResult.stats.numIoExceptions;
        e.printStackTrace();
    } catch (SAXException e) {
        Log.e(TAG, "getAlbumPhotos: " + e);
        ++syncResult.stats.numParseExceptions;
        e.printStackTrace();
    }
    return RESULT_ERROR;
}

From source file:org.mythdroid.util.UpdateService.java

private void getAvailableVersions() {

    final URL url;
    try {/*w  ww  .j av a2  s. co m*/
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        ErrUtil.logErr(e);
        return;
    }

    entries = new ArrayList<DownloadEntry>(2);

    try {
        Xml.parse(url.openStream(), Xml.Encoding.UTF_8, handler);
    } catch (SocketException e) {
        ErrUtil.logErr(e);
    } catch (SAXException e) {
        ErrUtil.logErr(e);
    } catch (IOException e) {
        ErrUtil.logErr(e);
    }

    if (entries.size() != 2)
        return;

    for (int i = 0; i < 2; i++) {

        String version;
        final DownloadEntry entry = entries.get(i);
        int start = -1;
        if ((start = entry.title.indexOf("MythDroid")) != -1) { //$NON-NLS-1$
            start += 10;
            int end = entry.title.indexOf(".apk"); //$NON-NLS-1$
            if (end == -1)
                continue;
            version = entry.title.substring(start, end);
            try {
                MDVer = new Version(version, entry.url);
            } catch (NumberFormatException e) {
                MDVer = null;
            }
        } else if ((start = entry.title.indexOf("mdd")) != -1) { //$NON-NLS-1$
            start += 4;
            int end = entry.title.indexOf(".tgz"); //$NON-NLS-1$
            if (end == -1)
                continue;
            version = entry.title.substring(start, end);
            try {
                MDDVer = new Version(version, entry.url);
            } catch (NumberFormatException e) {
                MDDVer = null;
            }
        } else
            ErrUtil.logErr("Unexpected title: " + entry.title); //$NON-NLS-1$

    }

}

From source file:com.gimranov.zandy.app.XMLResponseParser.java

public void parse(int mode, String url, final Database db) {
    Element entry;/*from   ww w.  j  a  v a  2  s  .c  o  m*/
    RootElement root;
    // we have a different root for indiv. items
    if (mode == MODE_FEED) {
        root = new RootElement(ATOM_NAMESPACE, "feed");
        entry = root.getChild(ATOM_NAMESPACE, "entry");
    } else {
        // MODE_ITEM, MODE_COLLECTION
        Log.d(TAG, "Parsing in entry mode");
        root = new RootElement(ATOM_NAMESPACE, "entry");
        entry = (Element) root;
    }

    if (mode == MODE_FEED) {
        root.getChild(ATOM_NAMESPACE, "link").setStartElementListener(new StartElementListener() {
            public void start(Attributes attributes) {
                String rel = "";
                String href = "";
                int length = attributes.getLength();
                // I shouldn't have to walk through, but the namespacing isn't working here
                for (int i = 0; i < length; i++) {
                    if ("rel".equals(attributes.getQName(i)))
                        rel = attributes.getValue(i);
                    if ("href".equals(attributes.getQName(i)))
                        href = attributes.getValue(i);
                }
                // We try to get a parent collection if necessary / possible
                if (rel.contains("self")) {
                    // Try to get a parent collection
                    int colloc = href.indexOf("/collections/");
                    int itemloc = href.indexOf("/items");
                    // Our URL looks like this:
                    //       https://api.zotero.org/users/5770/collections/2AJUSIU9/items?content=json
                    if (colloc != -1 && itemloc != -1) {
                        // The string "/collections/" is thirteen characters long
                        String id = href.substring(colloc + 13, itemloc);
                        Log.d(TAG, "Collection key: " + id);
                        parent = ItemCollection.load(id, db);
                        if (parent != null)
                            parent.loadChildren(db);
                    } else {
                        Log.d(TAG, "Key extraction failed from root; maybe this isn't a collection listing?");
                    }
                }
                // If there are more items, queue them up to be handled too
                if (rel.contains("next")) {
                    Log.d(TAG, "Found continuation: " + href);
                    APIRequest req = new APIRequest(href, "get", null);
                    req.query = href;
                    req.disposition = "xml";
                    queue.add(req);
                }
            }
        });
    }

    entry.setElementListener(new ElementListener() {
        public void start(Attributes attributes) {
            item = new Item();
            collection = new ItemCollection();
            attachment = new Attachment();
            Log.d(TAG, "New entry");
        }

        public void end() {
            if (items == true) {
                if (updateKey != null && updateType != null && updateType.equals("item")) {
                    // We have an incoming new version of an item
                    Item existing = Item.load(updateKey, db);
                    if (existing != null) {
                        Log.d(TAG, "Updating newly created item to replace temporary key: " + updateKey + " => "
                                + item.getKey() + "");
                        item.getKey();
                        existing.dirty = APIRequest.API_CLEAN;
                        // We need to update the parent key in attachments as well,
                        // so they aren't orphaned after we update the item key here
                        ArrayList<Attachment> atts = Attachment.forItem(existing, db);
                        for (Attachment a : atts) {
                            Log.d(TAG, "Propagating item key replacement to attachment with key: " + a.key);
                            a.parentKey = item.getKey();
                            a.save(db);
                        }
                        // We can't set the new key until after updating child attachments
                        existing.setKey(item.getKey());
                        if (!existing.getType().equals("attachment"))
                            existing.save(db);
                    }
                } else if (updateKey != null && updateType != null && updateType.equals("attachment")) {
                    // We have an incoming new version of an item
                    Attachment existing = Attachment.load(updateKey, db);
                    if (existing != null) {
                        Log.d(TAG, "Updating newly created attachment to replace temporary key: " + updateKey
                                + " => " + attachment.key + "");
                        existing.dirty = APIRequest.API_CLEAN;
                        // we don't change the ZFS status...
                        existing.key = attachment.key;
                        existing.save(db);
                    }
                } else {
                    item.dirty = APIRequest.API_CLEAN;
                    attachment.dirty = APIRequest.API_CLEAN;
                    if ((attachment.url != null && !"".equals(attachment.url))
                            || attachment.content.optInt("linkMode") == Attachment.MODE_IMPORTED_FILE
                            || attachment.content.optInt("linkMode") == Attachment.MODE_IMPORTED_URL)
                        attachment.status = Attachment.AVAILABLE;

                    if (!item.getType().equals("attachment") && !item.getType().equals("note")) {
                        Item oldItem = Item.load(item.getKey(), db);
                        // Check timestamps to see if it's different; if not, we should
                        // stop following the Atom continuation links
                        if (oldItem != null && oldItem.getTimestamp().equals(item.getTimestamp())) {
                            followNext = false;
                        }
                        item.save(db);
                    } else {
                        // Don't touch ZFS status here
                        Attachment existing = Attachment.load(attachment.key, db);
                        if (existing != null) {
                            attachment.status = existing.status;
                        }
                        attachment.save(db);
                    }
                }

                if (!item.getType().equals("attachment") && !item.getType().equals("note")
                        && item.getChildren() != null && !item.getChildren().equals("0")) {
                    queue.add(APIRequest.children(item));
                    Log.d(TAG, "Queued children request for item: " + item.getTitle() + " " + item.getKey());
                    Log.d(TAG, "Item has children: " + item.getChildren());
                }

                // Add to containing collection
                if (!item.getType().equals("attachment") && parent != null)
                    parent.add(item, true, db);

                request.getHandler().onUpdate(request);

                Log.d(TAG, "Done parsing item entry.");
                return;
            }

            if (!items) {
                if (updateKey != null && updateType != null && updateType.equals("collection")) {
                    // We have an incoming new version of a collection
                    ItemCollection existing = ItemCollection.load(updateKey, db);
                    if (existing != null) {
                        Log.d(TAG, "Updating newly created collection to replace temporary key: " + updateKey
                                + " => " + collection.getKey() + "");
                        existing.setKey(collection.getKey());
                        existing.dirty = APIRequest.API_CLEAN;
                        existing.save(db);
                    }
                    Log.d(TAG, "Done parsing new collection entry.");
                    // We don't need to load again, since a new collection can't be stale
                    return;
                }

                ItemCollection ic = ItemCollection.load(collection.getKey(), db);
                if (ic != null) {
                    if (!ic.getTimestamp().equals(collection.getTimestamp())) {
                        // In this case, we have data, but we should refresh it
                        collection.dirty = APIRequest.API_STALE;
                    } else {
                        // Collection hasn't changed!
                        collection = ic;
                        // We also don't need the next page, if we already saw this one
                        followNext = false;
                    }
                } else {
                    // This means that we haven't seen the collection before, so it must be
                    // a new one, and we don't have contents for it.
                    collection.dirty = APIRequest.API_MISSING;
                }
                Log.d(TAG, "Status: " + collection.dirty + " for " + collection.getTitle());
                collection.save(db);
                Log.d(TAG, "Done parsing a collection entry.");
                return;
            }
        }
    });
    entry.getChild(ATOM_NAMESPACE, "title").setEndTextElementListener(new EndTextElementListener() {
        public void end(String body) {
            item.setTitle(body);
            collection.setTitle(body);
            attachment.title = body;
            Log.d(TAG, body);
        }
    });
    entry.getChild(Z_NAMESPACE, "key").setEndTextElementListener(new EndTextElementListener() {
        public void end(String body) {
            item.setKey(body);
            collection.setKey(body);
            attachment.key = body;
            Log.d(TAG, body);
        }
    });
    entry.getChild(ATOM_NAMESPACE, "updated").setEndTextElementListener(new EndTextElementListener() {
        public void end(String body) {
            item.setTimestamp(body);
            collection.setTimestamp(body);
            Log.d(TAG, body);
        }
    });
    entry.getChild(Z_NAMESPACE, "itemType").setEndTextElementListener(new EndTextElementListener() {
        public void end(String body) {
            item.setType(body);
            items = true;
            Log.d(TAG, body);
        }
    });
    entry.getChild(Z_NAMESPACE, "numChildren").setEndTextElementListener(new EndTextElementListener() {
        public void end(String body) {
            item.setChildren(body);
            Log.d(TAG, body);
        }
    });
    entry.getChild(Z_NAMESPACE, "year").setEndTextElementListener(new EndTextElementListener() {
        public void end(String body) {
            item.setYear(body);
            Log.d(TAG, body);
        }
    });
    entry.getChild(Z_NAMESPACE, "creatorSummary").setEndTextElementListener(new EndTextElementListener() {
        public void end(String body) {
            item.setCreatorSummary(body);
            Log.d(TAG, body);
        }
    });
    entry.getChild(ATOM_NAMESPACE, "id").setEndTextElementListener(new EndTextElementListener() {
        public void end(String body) {
            item.setId(body);
            collection.setId(body);
            Log.d(TAG, body);
        }
    });
    entry.getChild(ATOM_NAMESPACE, "link").setStartElementListener(new StartElementListener() {
        public void start(Attributes attributes) {
            String rel = "";
            String href = "";
            int length = attributes.getLength();
            // I shouldn't have to walk through, but the namespacing isn't working here
            for (int i = 0; i < length; i++) {
                if ("rel".equals(attributes.getQName(i)))
                    rel = attributes.getValue(i);
                if ("href".equals(attributes.getQName(i)))
                    href = attributes.getValue(i);
            }
            if (rel != null && rel.equals("up")) {
                int start = href.indexOf("/items/");
                // Trying to pull out the key of attachment parent
                attachment.parentKey = href.substring(start + 7, start + 7 + 8);
                Log.d(TAG, "Setting parentKey to: " + attachment.parentKey);
            } else if (rel != null && rel.equals("enclosure")) {
                attachment.url = href;
                attachment.status = Attachment.AVAILABLE;
                Log.d(TAG, "url= " + attachment.url);
            } else if (rel != null)
                Log.d(TAG, "rel=" + rel + " href=" + href);
        }
    });
    entry.getChild(ATOM_NAMESPACE, "content").setStartElementListener(new StartElementListener() {
        public void start(Attributes attributes) {
            String etag = attributes.getValue(Z_NAMESPACE, "etag");
            item.setEtag(etag);
            collection.setEtag(etag);
            attachment.etag = etag;
            Log.d(TAG, "etag: " + etag);
        }
    });
    entry.getChild(ATOM_NAMESPACE, "content").setEndTextElementListener(new EndTextElementListener() {
        public void end(String body) {
            try {
                JSONObject obj = new JSONObject(body);
                try {
                    collection.setParent(obj.getString("parent"));
                } catch (JSONException e) {
                    Log.d(TAG, "No parent found in JSON content; not a subcollection or not a collection");
                }
                item.setContent(obj);
                attachment.content = obj;
            } catch (JSONException e) {
                Log.e(TAG, "JSON parse exception loading content", e);
            }
            Log.d(TAG, body);
        }
    });
    try {
        Xml.parse(this.input, Xml.Encoding.UTF_8, root.getContentHandler());
        if (parent != null) {
            parent.saveChildren(db);
            parent.markClean();
            parent.save(db);
        }
        db.close();
    } catch (Exception e) {
        Log.e(TAG, "exception loading content", e);
        Crashlytics.logException(new Exception("Exception parsing data", e));
    }
}

From source file:org.mythdroid.activities.Guide.java

/**
 * Fetch and parse guide data from the backend
 * @param start Date that guide should start at
 * @param end Date that guide should end at
 *///from   w w w.  j a v a 2 s  .c o m
private void getGuideData(Date start, Date end) {

    if (Globals.haveServices()) {
        try {
            channels = guideService.GetProgramGuide(start, end);
        } catch (IOException e) {
            ErrUtil.postErr(this, e);
            return;
        }
        return;
    }

    // No services api - use MythXML

    XMLHandler handler = new XMLHandler("GetProgramGuideResponse"); //$NON-NLS-1$
    Element root = handler.rootElement();

    root.getChild("NumOfChannels").setTextElementListener( //$NON-NLS-1$
            new EndTextElementListener() {
                @Override
                public void end(String body) {
                    channels.ensureCapacity(Integer.valueOf(body));
                }
            });

    Element chanElement = root.getChild("ProgramGuide") //$NON-NLS-1$
            .getChild("Channels") //$NON-NLS-1$
            .getChild("Channel"); //$NON-NLS-1$

    chanElement.setStartElementListener(new ChannelXMLParser(this, chanElement, new ChannelListener() {
        @Override
        public void channel(Channel chan) {
            channels.add(chan);
        }
    }));

    HttpFetcher fetcher = null;

    try {

        URL url = new URL(Globals.getBackend().getStatusURL() + "/Myth/GetProgramGuide?" + //$NON-NLS-1$
                "StartTime=" + Globals.dateFormat(start) + //$NON-NLS-1$
                "&EndTime=" + Globals.dateFormat(end) + //$NON-NLS-1$
                "&StartChanId=0" + "&NumOfChannels=-1" + "&Details=1" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        );

        LogUtil.debug("Fetching XML from " + url.toString()); //$NON-NLS-1$

        fetcher = new HttpFetcher(url.toString(), Globals.muxConns);
        InputStream is = fetcher.getInputStream();
        if (is == null)
            throw new IOException(Messages.getString("Guide.0")); //$NON-NLS-1$

        Xml.parse(is, Xml.Encoding.UTF_8, handler);

    } catch (SAXException e) {
        ErrUtil.postErr(this, Messages.getString("Guide.13")); //$NON-NLS-1$
    } catch (IOException e) {
        ErrUtil.postErr(this, e);
    } finally {
        if (fetcher != null)
            try {
                fetcher.endStream();
            } catch (IOException e) {
            }
    }

}

From source file:org.m2x.rssreader.service.FetcherService.java

private int refreshFeed(String feedId) {
    RssAtomParser handler = null;//from   www  . j  ava 2 s . c  o m

    ContentResolver cr = getContentResolver();
    Cursor cursor = cr.query(FeedColumns.CONTENT_URI(feedId), null, null, null, null);

    if (!cursor.moveToFirst()) {
        cursor.close();
        return 0;
    }

    int urlPosition = cursor.getColumnIndex(FeedColumns.URL);
    int titlePosition = cursor.getColumnIndex(FeedColumns.NAME);
    int fetchmodePosition = cursor.getColumnIndex(FeedColumns.FETCH_MODE);
    int realLastUpdatePosition = cursor.getColumnIndex(FeedColumns.REAL_LAST_UPDATE);
    int iconPosition = cursor.getColumnIndex(FeedColumns.ICON);
    int retrieveFullTextPosition = cursor.getColumnIndex(FeedColumns.RETRIEVE_FULLTEXT);

    HttpURLConnection connection = null;
    try {
        String feedUrl = cursor.getString(urlPosition);
        connection = NetworkUtils.setupConnection(feedUrl);
        String contentType = connection.getContentType();
        int fetchMode = cursor.getInt(fetchmodePosition);

        handler = new RssAtomParser(new Date(cursor.getLong(realLastUpdatePosition)), feedId,
                cursor.getString(titlePosition), feedUrl, cursor.getInt(retrieveFullTextPosition) == 1);
        handler.setFetchImages(PrefUtils.getBoolean(PrefUtils.FETCH_PICTURES, true));

        if (fetchMode == 0) {
            if (contentType != null && contentType.startsWith(CONTENT_TYPE_TEXT_HTML)) {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(NetworkUtils.getConnectionInputStream(connection)));

                String line;
                int posStart = -1;

                while ((line = reader.readLine()) != null) {
                    if (line.contains(HTML_BODY)) {
                        break;
                    } else {
                        Matcher matcher = FEED_LINK_PATTERN.matcher(line);

                        if (matcher.find()) { // not "while" as only one link is needed
                            line = matcher.group();
                            posStart = line.indexOf(HREF);

                            if (posStart > -1) {
                                String url = line.substring(posStart + 6, line.indexOf('"', posStart + 10))
                                        .replace("&amp", "&");

                                ContentValues values = new ContentValues();

                                if (url.startsWith("/")) {
                                    int index = feedUrl.indexOf('/', 8);

                                    if (index > -1) {
                                        url = feedUrl.substring(0, index) + url;
                                    } else {
                                        url = feedUrl + url;
                                    }
                                } else if (!url.startsWith(Constants.HTTP_SCHEME)
                                        && !url.startsWith(Constants.HTTPS_SCHEME)) {
                                    url = feedUrl + '/' + url;
                                }
                                values.put(FeedColumns.URL, url);
                                cr.update(FeedColumns.CONTENT_URI(feedId), values, null, null);
                                connection.disconnect();
                                connection = NetworkUtils.setupConnection(url);
                                contentType = connection.getContentType();
                                break;
                            }
                        }
                    }
                }
                // this indicates a badly configured feed
                if (posStart == -1) {
                    connection.disconnect();
                    connection = NetworkUtils.setupConnection(feedUrl);
                    contentType = connection.getContentType();
                }
            }

            if (contentType != null) {
                int index = contentType.indexOf(CHARSET);

                if (index > -1) {
                    int index2 = contentType.indexOf(';', index);

                    try {
                        Xml.findEncodingByName(index2 > -1 ? contentType.substring(index + 8, index2)
                                : contentType.substring(index + 8));
                        fetchMode = FETCHMODE_DIRECT;
                    } catch (UnsupportedEncodingException usee) {
                        fetchMode = FETCHMODE_REENCODE;
                    }
                } else {
                    fetchMode = FETCHMODE_REENCODE;
                }

            } else {
                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(NetworkUtils.getConnectionInputStream(connection)));

                char[] chars = new char[20];

                int length = bufferedReader.read(chars);

                String xmlDescription = new String(chars, 0, length);

                connection.disconnect();
                connection = NetworkUtils.setupConnection(connection.getURL());

                int start = xmlDescription != null ? xmlDescription.indexOf(ENCODING) : -1;

                if (start > -1) {
                    try {
                        Xml.findEncodingByName(
                                xmlDescription.substring(start + 10, xmlDescription.indexOf('"', start + 11)));
                        fetchMode = FETCHMODE_DIRECT;
                    } catch (UnsupportedEncodingException usee) {
                        fetchMode = FETCHMODE_REENCODE;
                    }
                } else {
                    // absolutely no encoding information found
                    fetchMode = FETCHMODE_DIRECT;
                }
            }

            ContentValues values = new ContentValues();
            values.put(FeedColumns.FETCH_MODE, fetchMode);
            cr.update(FeedColumns.CONTENT_URI(feedId), values, null, null);
        }

        switch (fetchMode) {
        default:
        case FETCHMODE_DIRECT: {
            if (contentType != null) {
                int index = contentType.indexOf(CHARSET);

                int index2 = contentType.indexOf(';', index);

                InputStream inputStream = NetworkUtils.getConnectionInputStream(connection);
                Xml.parse(inputStream,
                        Xml.findEncodingByName(index2 > -1 ? contentType.substring(index + 8, index2)
                                : contentType.substring(index + 8)),
                        handler);
            } else {
                InputStreamReader reader = new InputStreamReader(
                        NetworkUtils.getConnectionInputStream(connection));
                Xml.parse(reader, handler);
            }
            break;
        }
        case FETCHMODE_REENCODE: {
            ByteArrayOutputStream ouputStream = new ByteArrayOutputStream();
            InputStream inputStream = NetworkUtils.getConnectionInputStream(connection);

            byte[] byteBuffer = new byte[4096];

            int n;
            while ((n = inputStream.read(byteBuffer)) > 0) {
                ouputStream.write(byteBuffer, 0, n);
            }

            String xmlText = ouputStream.toString();

            int start = xmlText != null ? xmlText.indexOf(ENCODING) : -1;

            if (start > -1) {
                Xml.parse(new StringReader(new String(ouputStream.toByteArray(),
                        xmlText.substring(start + 10, xmlText.indexOf('"', start + 11)))), handler);
            } else {
                // use content type
                if (contentType != null) {
                    int index = contentType.indexOf(CHARSET);

                    if (index > -1) {
                        int index2 = contentType.indexOf(';', index);

                        try {
                            StringReader reader = new StringReader(new String(ouputStream.toByteArray(),
                                    index2 > -1 ? contentType.substring(index + 8, index2)
                                            : contentType.substring(index + 8)));
                            Xml.parse(reader, handler);
                        } catch (Exception ignored) {
                        }
                    } else {
                        StringReader reader = new StringReader(new String(ouputStream.toByteArray()));
                        Xml.parse(reader, handler);
                    }
                }
            }
            break;
        }
        }

        connection.disconnect();
    } catch (FileNotFoundException e) {
        if (handler == null || (handler != null && !handler.isDone() && !handler.isCancelled())) {
            ContentValues values = new ContentValues();

            // resets the fetchmode to determine it again later
            values.put(FeedColumns.FETCH_MODE, 0);

            values.put(FeedColumns.ERROR, getString(R.string.error_feed_error));
            cr.update(FeedColumns.CONTENT_URI(feedId), values, null, null);
        }
    } catch (Throwable e) {
        if (handler == null || (handler != null && !handler.isDone() && !handler.isCancelled())) {
            ContentValues values = new ContentValues();

            // resets the fetchmode to determine it again later
            values.put(FeedColumns.FETCH_MODE, 0);

            values.put(FeedColumns.ERROR,
                    e.getMessage() != null ? e.getMessage() : getString(R.string.error_feed_process));
            cr.update(FeedColumns.CONTENT_URI(feedId), values, null, null);
        }
    } finally {

        /* check and optionally find favicon */
        try {
            if (handler != null && cursor.getBlob(iconPosition) == null) {
                String feedLink = handler.getFeedLink();
                if (feedLink != null) {
                    NetworkUtils.retrieveFavicon(this, new URL(feedLink), feedId);
                } else {
                    NetworkUtils.retrieveFavicon(this, connection.getURL(), feedId);
                }
            }
        } catch (Throwable ignored) {
        }

        if (connection != null) {
            connection.disconnect();
        }
    }

    cursor.close();

    return handler != null ? handler.getNewCount() : 0;
}

From source file:net.czlee.debatekeeper.FormatChooserActivity.java

/**
 * Populates the master styles list, <code>mStylesList</code>.  Should be called when this
 * Activity is created, or whenever we want to refresh the styles list. If there is an error so
 * serious that it can't even get the list, we show a dialog to that effect, and leave the list
 * empty.//from   w w  w.  j a  va  2s.com
 */
private void populateStylesList() {
    String[] fileList;

    try {
        fileList = mFilesManager.list();
    } catch (IOException e) {
        e.printStackTrace();
        ListIOErrorDialogFragment fragment = new ListIOErrorDialogFragment();
        fragment.show(getSupportFragmentManager(), DIALOG_TAG_LIST_IO_ERROR);
        return;
    }

    for (String filename : fileList) {
        if (!filename.endsWith(".xml"))
            continue;

        InputStream is;

        try {
            is = mFilesManager.open(filename);
        } catch (IOException e) {
            Log.e(TAG, "Couldn't find file: " + filename);
            continue;
        }

        try {
            Xml.parse(is, Encoding.UTF_8, new GetDebateFormatNameXmlContentHandler());

        } catch (AllInformationFoundException e) {
            // This exception means the XML parsing was successful - we just
            // use it to stop the parser.
            if (mCurrentStyleName != null)
                mStylesList.add(new DebateFormatListEntry(filename, mCurrentStyleName));

        } catch (SAXException | IOException e) {
            mCurrentStyleName = null;
        }

    }

    // Sort alphabetically by style name and tell observers
    mStylesArrayAdapter.sort(new StyleEntryComparatorByStyleName());
    mStylesArrayAdapter.notifyDataSetChanged();
}

From source file:nl.privacybarometer.privacyvandaag.service.FetcherService.java

private int refreshFeed(String feedId, long keepDateBorderTime) {
    RssAtomParser handler = null;/*from  ww  w .j  a  v a 2 s  .co  m*/

    ContentResolver cr = getContentResolver();
    Cursor cursor = cr.query(FeedColumns.CONTENT_URI(feedId), null, null, null, null);

    if (cursor.moveToFirst()) {
        int urlPosition = cursor.getColumnIndex(FeedColumns.URL);
        int idPosition = cursor.getColumnIndex(FeedColumns._ID);
        int titlePosition = cursor.getColumnIndex(FeedColumns.NAME);
        int fetchModePosition = cursor.getColumnIndex(FeedColumns.FETCH_MODE);
        int realLastUpdatePosition = cursor.getColumnIndex(FeedColumns.REAL_LAST_UPDATE);
        int iconPosition = cursor.getColumnIndex(FeedColumns.ICON);
        int retrieveFullscreenPosition = cursor.getColumnIndex(FeedColumns.RETRIEVE_FULLTEXT);

        /* ModPrivacyVandaag: if Fetchmode = 99, do not refresh this feed. */
        int fetchMode = cursor.getInt(fetchModePosition);
        if (fetchMode == FETCHMODE_DO_NOT_FETCH) {
            cursor.close();
            return 0;
        }
        // end of this added block of code; commented out initialize of fetchmode on line 520
        String id = cursor.getString(idPosition);
        HttpURLConnection connection = null;
        try {
            String feedUrl = cursor.getString(urlPosition);
            connection = NetworkUtils.setupConnection(feedUrl);
            String contentType = connection.getContentType();
            handler = new RssAtomParser(new Date(cursor.getLong(realLastUpdatePosition)), keepDateBorderTime,
                    id, cursor.getString(titlePosition), feedUrl,
                    cursor.getInt(retrieveFullscreenPosition) == 1);
            handler.setFetchImages(NetworkUtils.needDownloadPictures());
            // Log.e (TAG,"feedUrl = "+feedUrl);

            if (fetchMode == 0) {
                if (contentType != null && contentType.startsWith(CONTENT_TYPE_TEXT_HTML)) {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(connection.getInputStream()));

                    String line;
                    int posStart = -1;

                    while ((line = reader.readLine()) != null) {
                        if (line.contains(HTML_BODY)) {
                            break;
                        } else {
                            Matcher matcher = FEED_LINK_PATTERN.matcher(line);

                            if (matcher.find()) { // not "while" as only one link is needed
                                line = matcher.group();
                                posStart = line.indexOf(HREF);

                                if (posStart > -1) {
                                    String url = line.substring(posStart + 6, line.indexOf('"', posStart + 10))
                                            .replace(Constants.AMP_SG, Constants.AMP);

                                    ContentValues values = new ContentValues();

                                    if (url.startsWith(Constants.SLASH)) {
                                        int index = feedUrl.indexOf('/', 8);

                                        if (index > -1) {
                                            url = feedUrl.substring(0, index) + url;
                                        } else {
                                            url = feedUrl + url;
                                        }
                                    } else if (!url.startsWith(Constants.HTTP_SCHEME)
                                            && !url.startsWith(Constants.HTTPS_SCHEME)) {
                                        url = feedUrl + '/' + url;
                                    }
                                    values.put(FeedColumns.URL, url);
                                    cr.update(FeedColumns.CONTENT_URI(id), values, null, null);
                                    connection.disconnect();
                                    connection = NetworkUtils.setupConnection(url);
                                    contentType = connection.getContentType();
                                    break;
                                }
                            }
                        }
                    }
                    // this indicates a badly configured feed
                    if (posStart == -1) {
                        connection.disconnect();
                        connection = NetworkUtils.setupConnection(feedUrl);
                        contentType = connection.getContentType();
                    }
                }

                if (contentType != null) {
                    int index = contentType.indexOf(CHARSET);
                    if (index > -1) {
                        int index2 = contentType.indexOf(';', index);

                        try {
                            Xml.findEncodingByName(index2 > -1 ? contentType.substring(index + 8, index2)
                                    : contentType.substring(index + 8));
                            fetchMode = FETCHMODE_DIRECT;
                        } catch (UnsupportedEncodingException ignored) {
                            fetchMode = FETCHMODE_REENCODE;
                        }
                    } else {
                        fetchMode = FETCHMODE_REENCODE;
                    }

                } else {
                    BufferedReader bufferedReader = new BufferedReader(
                            new InputStreamReader(connection.getInputStream()));

                    char[] chars = new char[20];

                    int length = bufferedReader.read(chars);

                    String xmlDescription = new String(chars, 0, length);

                    connection.disconnect();
                    connection = NetworkUtils.setupConnection(connection.getURL());

                    int start = xmlDescription.indexOf(ENCODING);

                    if (start > -1) {
                        try {
                            Xml.findEncodingByName(xmlDescription.substring(start + 10,
                                    xmlDescription.indexOf('"', start + 11)));
                            fetchMode = FETCHMODE_DIRECT;
                        } catch (UnsupportedEncodingException ignored) {
                            fetchMode = FETCHMODE_REENCODE;
                        }
                    } else {
                        // absolutely no encoding information found
                        fetchMode = FETCHMODE_DIRECT;
                    }
                }

                ContentValues values = new ContentValues();
                values.put(FeedColumns.FETCH_MODE, fetchMode);
                cr.update(FeedColumns.CONTENT_URI(id), values, null, null);
            }

            switch (fetchMode) {
            default:
            case FETCHMODE_DIRECT: {
                if (contentType != null) {
                    int index = contentType.indexOf(CHARSET);
                    int index2 = contentType.indexOf(';', index);

                    InputStream inputStream = connection.getInputStream();
                    Xml.parse(inputStream,
                            Xml.findEncodingByName(index2 > -1 ? contentType.substring(index + 8, index2)
                                    : contentType.substring(index + 8)),
                            handler);
                } else {
                    InputStreamReader reader = new InputStreamReader(connection.getInputStream());
                    Xml.parse(reader, handler);
                }
                break;
            }
            case FETCHMODE_REENCODE: {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                InputStream inputStream = connection.getInputStream();

                byte[] byteBuffer = new byte[4096];

                int n;
                while ((n = inputStream.read(byteBuffer)) > 0) {
                    outputStream.write(byteBuffer, 0, n);
                }

                String xmlText = outputStream.toString();

                int start = xmlText != null ? xmlText.indexOf(ENCODING) : -1;

                if (start > -1) {
                    Xml.parse(new StringReader(new String(outputStream.toByteArray(),
                            xmlText.substring(start + 10, xmlText.indexOf('"', start + 11)))), handler);
                } else {
                    // use content type
                    if (contentType != null) {
                        int index = contentType.indexOf(CHARSET);
                        if (index > -1) {
                            int index2 = contentType.indexOf(';', index);

                            try {
                                StringReader reader = new StringReader(new String(outputStream.toByteArray(),
                                        index2 > -1 ? contentType.substring(index + 8, index2)
                                                : contentType.substring(index + 8)));
                                Xml.parse(reader, handler);
                            } catch (Exception e) {
                                Log.e("Privacy Vandaag: ", "Error reading string " + e.getMessage());
                            }
                        } else {
                            StringReader reader = new StringReader(xmlText);
                            Xml.parse(reader, handler);
                        }
                    }
                }
                break;
            }
            }

            connection.disconnect();
        } catch (FileNotFoundException e) {
            if (handler == null || (!handler.isDone() && !handler.isCancelled())) {
                ContentValues values = new ContentValues();

                // resets the fetch mode to determine it again later
                values.put(FeedColumns.FETCH_MODE, 0);

                values.put(FeedColumns.ERROR, getString(R.string.error_feed_error));
                cr.update(FeedColumns.CONTENT_URI(id), values, null, null);
            }
        } catch (Throwable e) {
            if (handler == null || (!handler.isDone() && !handler.isCancelled())) {
                ContentValues values = new ContentValues();

                // resets the fetch mode to determine it again later
                values.put(FeedColumns.FETCH_MODE, 0);

                values.put(FeedColumns.ERROR,
                        e.getMessage() != null ? e.getMessage() : getString(R.string.error_feed_process));
                cr.update(FeedColumns.CONTENT_URI(id), values, null, null);
                handler = null; // If an error has occurred, reset the new articles counter for this feed to avoid notifications.
            }
        } finally {
            /* check and optionally find favicon */
            /* No longer needed, because the icons of the feeds are included in the package */
            /*
                try {
                    if (handler != null && cursor.getBlob(iconPosition) == null) {
                        String feedLink = handler.getFeedLink();
                        if (feedLink != null) {
                            NetworkUtils.retrieveFavicon(this, new URL(feedLink), id);
                        } else {
                            NetworkUtils.retrieveFavicon(this, connection.getURL(), id);
                        }
                    }
                } catch (Throwable ignored) {
                }
            */
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    cursor.close();

    int newArticles = (handler != null) ? handler.getNewCount() : 0;
    //Log.e(TAG, "Test notification is gegeven voor feedID " + feedId);
    //if (newArticles == 0 ) newArticles =2;      // ONLY FOR TESTING !!!!

    // Check of meldingen voor deze feed aanstaat, anders newArticles op 0 zetten
    if (newArticles > 0) {
        boolean notifyFeed = true;
        switch (Integer.parseInt(feedId)) {
        case 1: // feedID Privacy Barometer
            notifyFeed = PrefUtils.getBoolean(PrefUtils.NOTIFY_PRIVACYBAROMETER, true);
            break;
        case 2: // feedID Bits of Freedom
            notifyFeed = PrefUtils.getBoolean(PrefUtils.NOTIFY_BITSOFFREEDOM, true);
            break;
        case 3: // feedID Privacy First
            notifyFeed = PrefUtils.getBoolean(PrefUtils.NOTIFY_PRIVACYFIRST, true);
            break;
        case 4: // feedID Autoriteit Persoonsgegevens
            notifyFeed = PrefUtils.getBoolean(PrefUtils.NOTIFY_AUTORITEITPERSOONSGEGEVENS, true);
        }
        if (!notifyFeed)
            newArticles = 0; // geen melding als de meldingen voor deze feed uitstaan.
    }
    //Log.e(TAG, "Nieuwe artikelen is " + newArticles);

    return newArticles;
}

From source file:org.totschnig.myexpenses.util.Utils.java

public static Result analyzeGrisbiFileWithSAX(InputStream is) {
    GrisbiHandler handler = new GrisbiHandler();
    try {//from  w ww. ja v  a  2  s . c o m
        Xml.parse(is, Xml.Encoding.UTF_8, handler);
    } catch (IOException e) {
        return new Result(false, R.string.parse_error_other_exception, e.getMessage());
    } catch (GrisbiHandler.FileVersionNotSupportedException e) {
        return new Result(false, R.string.parse_error_grisbi_version_not_supported, e.getMessage());
    } catch (SAXException e) {
        return new Result(false, R.string.parse_error_parse_exception);
    }
    return handler.getResult();
}