Example usage for android.sax RootElement getContentHandler

List of usage examples for android.sax RootElement getContentHandler

Introduction

In this page you can find the example usage for android.sax RootElement getContentHandler.

Prototype

public ContentHandler getContentHandler() 

Source Link

Document

Gets the SAX ContentHandler .

Usage

From source file:com.byteridge.bookcircle.utils.ResponseParser.java

public static Response parse(InputStream inputStream) throws IOException, SAXException {
    final Response response = new Response();
    RootElement root = new RootElement("GoodreadsResponse");
    response.set_Book(Book.appendSingletonListener(root, 0));
    response.set_Request(Request.appendSingletonListener(root));
    response.set_User(User.appendSingletonListener(root, 0));
    response.set_Shelves(Shelves.appendSingletonListener(root, 0));
    response.set_Reviews(Reviews.appendSingletonListener(root, 0));
    response.set_Review(Review.appendSingletonListener(root, 0));
    try {//from w  w  w .j  a  v  a  2  s .c o m
        Xml.parse(inputStream, Xml.Encoding.UTF_8, root.getContentHandler());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return response;
}

From source file:com.byteridge.bookcircle.framework.listener.ResponseParser.java

public static Response parse(InputStream inputStream) throws IOException, SAXException {
    final Response response = new Response();

    RootElement root = new RootElement("GoodreadsResponse");

    response.set_Book(Book.appendSingletonListener(root, 0));
    response.set_Request(Request.appendSingletonListener(root));
    response.set_User(User.appendSingletonListener(root, 0));
    response.set_Shelves(Shelves.appendSingletonListener(root, 0));
    response.set_Reviews(Reviews.appendSingletonListener(root, 0));

    response.set_Review(Review.appendSingletonListener(root, 0));

    try {//  w  ww  . ja  v  a  2s.c  o  m
        Xml.parse(inputStream, Xml.Encoding.UTF_8, root.getContentHandler());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return response;
}

From source file:com.onesadjam.yagrac.xml.ResponseParser.java

public static Response parse(InputStream inputStream) throws IOException, SAXException {
    final Response response = new Response();

    RootElement root = new RootElement("GoodreadsResponse");

    response.set_Book(Book.appendSingletonListener(root, 0));
    response.set_Request(Request.appendSingletonListener(root));
    response.set_User(User.appendSingletonListener(root, 0));
    response.set_Shelves(Shelves.appendSingletonListener(root, 0));
    response.set_Reviews(Reviews.appendSingletonListener(root, 0));
    response.set_Search(Search.appendSingletonListener(root, 0));
    response.set_Followers(Followers.appendSingletonListener(root, 0));
    response.set_Friends(Friends.appendSingletonListener(root, 0));
    response.set_Following(Following.appendSingletonListener(root, 0));
    response.set_Updates(Update.appendArrayListener(root, 0));
    response.set_Review(Review.appendSingletonListener(root, 0));
    response.set_Author(Author.appendSingletonListener(root, 0));
    response.set_Comments(Comments.appendSingletonListener(root, 0));
    response.set_Events(Event.appendArrayListener(root, 0));

    try {//from  w  w  w  .  j  a v a  2  s  .  co m
        Xml.parse(inputStream, Xml.Encoding.UTF_8, root.getContentHandler());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return response;
}

From source file:uk.co.jarofgreen.cityoutdoors.API.BaseCall.java

protected void makeCall(RootElement root) {
    Element errorTag = root.getChild("error");
    errorTag.setStartElementListener(new StartElementListener() {
        public void start(Attributes attributes) {
            errorCode = attributes.getValue("code");
        }//from  w  w  w . j  av  a  2 s.c o m
    });
    errorTag.setEndTextElementListener(new EndTextElementListener() {
        public void end(String body) {
            errorMessage = body;
        }
    });

    try {
        httppost.setEntity(multipartEntity);
        response = httpclient.execute(httppost);
        entity = response.getEntity();
        is = entity.getContent();

        Xml.parse(is, Xml.Encoding.UTF_8, root.getContentHandler());
    } catch (SocketException e) {
        errorCode = "A1";
        errorMessage = "Can not connect to internet";
    } catch (UnknownHostException e) {
        errorCode = "A2";
        errorMessage = "Can not connect to internet";
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.codebutler.rsp.Playlist.java

public void fetchItems(final FetchItemsProgressListener progressListener) throws Exception {
    if (mItems != null)
        throw new Exception("fetchItems() already called!");

    mItems = new SortedArrayList<Item>(new Comparator<Item>() {
        public int compare(Item first, Item second) {
            return first.getTitle().compareToIgnoreCase(second.getTitle());
        }//from w w w.j  a v  a  2 s. com
    });

    mOrderedArtists = new SortedArrayList<Artist>(new Comparator<Artist>() {
        public int compare(Artist first, Artist second) {
            return first.getName().compareToIgnoreCase(second.getName());
        }
    });

    mArtists = new HashMap<String, Artist>();

    mAlbums = new SortedArrayList<Album>(new Comparator<Album>() {
        public int compare(Album first, Album second) {
            return first.getName().compareToIgnoreCase(second.getName());
        }
    });

    URL url = mServer.buildUrl("db/" + Integer.toString(mId));
    Log.d("FetchItems", url.toString());

    DefaultHttpClient client = new DefaultHttpClient();

    String password = mServer.getPassword();
    if (password != null && password.length() > 0) {
        UsernamePasswordCredentials creds;
        creds = new UsernamePasswordCredentials("user", password);
        client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
    }

    HttpGet method = new HttpGet(url.toURI());

    InputStream stream = client.execute(method).getEntity().getContent();

    try {
        /*
         <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
         <response>
        <status>
            <errorcode>0</errorcode>
            <errorstring></errorstring>
            <records>0</records>
            <totalrecords>1</totalrecords>
        </status>
        <items>
            <item>
                <id>1</id>
                <title>Rock Robotic (Osx Mix)</title>
                <artist>Oscillator X</artist>
                <album>Techno * Techyes</album>
                <genre>Dance &amp; DJ</genre>
                <type>mp3</type>
                <bitrate>192</bitrate>
                <samplerate>44100</samplerate>
                <song_length>61440</song_length>
                <file_size>1474560</file_size>
                <year>0</year>
                <track>15</track>
                <total_tracks>0</total_tracks>
                <disc>0</disc>
                <total_discs>0</total_discs>
                <bpm>0</bpm>
                <compilation>0</compilation>
                <rating>0</rating>
                <play_count>4</play_count>
                <description>MPEG audio file</description>
                <time_added>1270096204</time_added>
                <time_modified>1270078936</time_modified>
                <time_played>1270156178</time_played>
                <disabled>0</disabled>
                <codectype>mpeg</codectype>
            </item>
        </items>
         </response>
         */

        RootElement rootElement = new RootElement("response");
        Element itemsElement = rootElement.getChild("items");
        Element itemElement = itemsElement.getChild("item");
        Element idElement = itemElement.getChild("id");
        Element titleElement = itemElement.getChild("title");
        Element artistElement = itemElement.getChild("artist");
        Element albumElement = itemElement.getChild("album");
        Element lengthElement = itemElement.getChild("song_length");

        itemElement.setElementListener(new ElementListener() {
            public void start(Attributes arg0) {
                mCurrentItem = new Item(Playlist.this);
            }

            public void end() {
                mItems.add(mCurrentItem);

                // Artist cache
                String artistName = mCurrentItem.getArtist();
                if (artistName != null && artistName.trim().length() > 0) {
                    Artist artist = mArtists.get(artistName);
                    if (artist == null) {
                        artist = new Artist(artistName);
                        mArtists.put(artistName, artist);
                        mOrderedArtists.add(artist);
                    }

                    // Album cache
                    // FIXME: This should support compilation albums!
                    String albumName = mCurrentItem.getAlbum();
                    if (albumName != null && albumName.trim().length() > 0) {
                        Album album = artist.getAlbum(albumName);
                        if (album == null) {
                            album = new Album(artist, albumName);
                            artist.addAlbum(album);
                            mAlbums.add(album);
                        }
                        album.addItem(mCurrentItem);
                    }
                }

                mCurrentItem = null;

                if (progressListener != null) {
                    if ((mItems.size() % 100) == 0)
                        progressListener.onProgressChange(mItems.size());
                }
            }
        });

        idElement.setEndTextElementListener(new EndTextElementListener() {
            public void end(String body) {
                mCurrentItem.setId(Integer.parseInt(body));
            }
        });

        titleElement.setEndTextElementListener(new EndTextElementListener() {
            public void end(String body) {
                mCurrentItem.setTitle(body);
            }
        });

        artistElement.setEndTextElementListener(new EndTextElementListener() {
            public void end(String body) {
                mCurrentItem.setArtist(body);
            }
        });

        albumElement.setEndTextElementListener(new EndTextElementListener() {
            public void end(String body) {
                mCurrentItem.setAlbum(body);
            }
        });

        lengthElement.setEndTextElementListener(new EndTextElementListener() {
            public void end(String body) {
                mCurrentItem.setDuration(Long.parseLong(body) / 1000);
            }
        });

        android.util.Xml.parse(stream, Xml.Encoding.UTF_8, rootElement.getContentHandler());
    } finally {
        stream.close();
    }
}

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

public void parse(int mode, String url, final Database db) {
    Element entry;/* w  w w. j  a v a  2s .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));
    }
}