/*
* GNU LESSER GENERAL PUBLIC LICENSE
* Version 3, 29 June 2007
*
* Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
* Everyone is permitted to copy and distribute verbatim copies
* of this license document, but changing it is not allowed.
*
*
* This version of the GNU Lesser General Public License incorporates
* the terms and conditions of version 3 of the GNU General Public
* License, supplemented by the additional permissions listed below.
*
* 0. Additional Definitions.
*
* As used herein, "this License" refers to version 3 of the GNU Lesser
* General Public License, and the "GNU GPL" refers to version 3 of the GNU
* General Public License.
*
* "The Library" refers to a covered work governed by this License,
* other than an Application or a Combined Work as defined below.
*
* An "Application" is any work that makes use of an interface provided
* by the Library, but which is not otherwise based on the Library.
* Defining a subclass of a class defined by the Library is deemed a mode
* of using an interface provided by the Library.
*
* A "Combined Work" is a work produced by combining or linking an
* Application with the Library. The particular version of the Library
* with which the Combined Work was made is also called the "Linked
* Version".
*
* The "Minimal Corresponding Source" for a Combined Work means the
* Corresponding Source for the Combined Work, excluding any source code
* for portions of the Combined Work that, considered in isolation, are
* based on the Application, and not on the Linked Version.
*
* The "Corresponding Application Code" for a Combined Work means the
* object code and/or source code for the Application, including any data
* and utility programs needed for reproducing the Combined Work from the
* Application, but excluding the System Libraries of the Combined Work.
*
* 1. Exception to Section 3 of the GNU GPL.
*
* You may convey a covered work under sections 3 and 4 of this License
* without being bound by section 3 of the GNU GPL.
*
* 2. Conveying Modified Versions.
*
* If you modify a copy of the Library, and, in your modifications, a
* facility refers to a function or data to be supplied by an Application
* that uses the facility (other than as an argument passed when the
* facility is invoked), then you may convey a copy of the modified
* version:
*
* a) under this License, provided that you make a good faith effort to
* ensure that, in the event an Application does not supply the
* function or data, the facility still operates, and performs
* whatever part of its purpose remains meaningful, or
*
* b) under the GNU GPL, with none of the additional permissions of
* this License applicable to that copy.
*
* 3. Object Code Incorporating Material from Library Header Files.
*
* The object code form of an Application may incorporate material from
* a header file that is part of the Library. You may convey such object
* code under terms of your choice, provided that, if the incorporated
* material is not limited to numerical parameters, data structure
* layouts and accessors, or small macros, inline functions and templates
* (ten or fewer lines in length), you do both of the following:
*
* a) Give prominent notice with each copy of the object code that the
* Library is used in it and that the Library and its use are
* covered by this License.
*
* b) Accompany the object code with a copy of the GNU GPL and this license
* document.
*
* 4. Combined Works.
*
* You may convey a Combined Work under terms of your choice that,
* taken together, effectively do not restrict modification of the
* portions of the Library contained in the Combined Work and reverse
* engineering for debugging such modifications, if you also do each of
* the following:
*
* a) Give prominent notice with each copy of the Combined Work that
* the Library is used in it and that the Library and its use are
* covered by this License.
*
* b) Accompany the Combined Work with a copy of the GNU GPL and this license
* document.
*
* c) For a Combined Work that displays copyright notices during
* execution, include the copyright notice for the Library among
* these notices, as well as a reference directing the user to the
* copies of the GNU GPL and this license document.
*
* d) Do one of the following:
*
* 0) Convey the Minimal Corresponding Source under the terms of this
* License, and the Corresponding Application Code in a form
* suitable for, and under terms that permit, the user to
* recombine or relink the Application with a modified version of
* the Linked Version to produce a modified Combined Work, in the
* manner specified by section 6 of the GNU GPL for conveying
* Corresponding Source.
*
* 1) Use a suitable shared library mechanism for linking with the
* Library. A suitable mechanism is one that (a) uses at run time
* a copy of the Library already present on the user's computer
* system, and (b) will operate properly with a modified version
* of the Library that is interface-compatible with the Linked
* Version.
*
* e) Provide Installation Information, but only if you would otherwise
* be required to provide such information under section 6 of the
* GNU GPL, and only to the extent that such information is
* necessary to install and execute a modified version of the
* Combined Work produced by recombining or relinking the
* Application with a modified version of the Linked Version. (If
* you use option 4d0, the Installation Information must accompany
* the Minimal Corresponding Source and Corresponding Application
* Code. If you use option 4d1, you must provide the Installation
* Information in the manner specified by section 6 of the GNU GPL
* for conveying Corresponding Source.)
*
* 5. Combined Libraries.
*
* You may place library facilities that are a work based on the
* Library side by side in a single library together with other library
* facilities that are not Applications and are not covered by this
* License, and convey such a combined library under terms of your
* choice, if you do both of the following:
*
* a) Accompany the combined library with a copy of the same work based
* on the Library, uncombined with any other library facilities,
* conveyed under the terms of this License.
*
* b) Give prominent notice with the combined library that part of it
* is a work based on the Library, and explaining where to find the
* accompanying uncombined form of the same work.
*
* 6. Revised Versions of the GNU Lesser General Public License.
*
* The Free Software Foundation may publish revised and/or new versions
* of the GNU Lesser General Public License from time to time. Such new
* versions will be similar in spirit to the present version, but may
* differ in detail to address new problems or concerns.
*
* Each version is given a distinguishing version number. If the
* Library as you received it specifies that a certain numbered version
* of the GNU Lesser General Public License "or any later version"
* applies to it, you have the option of following the terms and
* conditions either of that published version or of any later version
* published by the Free Software Foundation. If the Library as you
* received it does not specify a version number of the GNU Lesser
* General Public License, you may choose any version of the GNU Lesser
* General Public License ever published by the Free Software Foundation.
*
* If the Library as you received it specifies that a proxy can decide
* whether future versions of the GNU Lesser General Public License shall
* apply, that proxy's public statement of acceptance of any version is
* permanent authorization for you to choose that version for the
* Library.
*/
package fb4java.service;
import fb4java.Facebook4j;
import fb4java.beans.Album;
import fb4java.beans.Comment;
import fb4java.beans.Message;
import fb4java.beans.Note;
import fb4java.beans.Notification;
import fb4java.beans.NotificationStatus;
import fb4java.beans.Post;
import fb4java.beans.Profile;
import fb4java.beans.Status;
import fb4java.beans.Stream;
import fb4java.beans.interfaces.Parameterable;
import fb4java.http.HttpResponseMessage;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
/**
*
* fb4java<br />
* fb4java.service
*
* @author Choongsan Ro
* @version 1.0 2010. 2. 26.
*/
public class DataRetrievalService extends Service {
private static final String FRIEND_GET = "friends.get";
private static final String MESSAGE_GETTHREADSINFOLDER = "Message.getThreadsInFolder";
private static final String NOTES_GET = "notes.get";
private static final String NOTIFICATIONS_GET = "notifications.get";
private static final String NOTIFICATIONS_GETLIST = "notifications.getList";
private static final String STATUS_GET = "status.get";
private static final String STREAM_GET = "stream.get";
private static final String STREAM_GETCOMMENTS = "stream.getComments";
private static final String USERS_GETINFO = "users.getInfo";
private static final String USERS_GET_LOGGEDINUSER = "users.getLoggedInUser";
private static final String USERS_GETSTANDARDINFO = "users.getStandardInfo";
private static final String USERS_ISAPPUSER = "users.isAppUser";
private static final String USERS_ISVERIFIED = "users.isVerified";
/**
*
* @param f4j
*/
public DataRetrievalService(Facebook4j f4j) {
super(f4j);
}
/**
*
* @return
* @throws ClientProtocolException
* @throws URISyntaxException
* @throws IOException
* @throws JSONException
*/
public ArrayList<Parameterable> getFriendList(Class<? extends Parameterable> type) throws ClientProtocolException,
URISyntaxException, IOException, JSONException {
ArrayList<Parameterable> friendList = new ArrayList<Parameterable>();
ArrayList<Long> friendIds = getFriendsId();
Long[] friendIdArray = new Long[1];
friendIdArray = friendIds.toArray(friendIdArray);
try {
getUserInfo(friendIdArray, friendList, type);
} catch (InstantiationException e) {
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
}
return friendList;
}
/**
*
* @return
* @throws ClientProtocolException
* @throws URISyntaxException
* @throws IOException
* @throws JSONException
*/
public ArrayList<Long> getFriendsId() throws ClientProtocolException, URISyntaxException, IOException,
JSONException {
ArrayList<Long> friendList = new ArrayList<Long>();
Map<String, String> listOfMethods = getBasicParams();
listOfMethods.put(METHOD, FRIEND_GET);
HttpResponseMessage response = f4j.sendGetRequest(listOfMethods);
JSONArray jArray = new JSONArray(response.getResponse());
int jArraySize = jArray.length();
for (int a = 0; a < jArraySize; a++) {
friendList.add(jArray.getLong(a));
}
return friendList;
}
/**
* This method doesn't work without <b>read_mailbox</b> extended permission
*
* @param folder_id
* folder id. It should be one of following : <br/>
* 0 : Inbox <br />
* 1 : Outbox <br />
* 4 : Updates <br/>
* Other integers will be treated as empty value.
* @param uid
* user id whose inbox threads you are returning.
* @param limit
* indicates the number of htreads to return.
* @param offset
* indicates how many threads to skip from the most recent thread
* @throws IOException
* @throws URISyntaxException
* @throws ClientProtocolException
* @throws JSONException
*/
public void getMessageThreadsInFolder(int folder_id, int uid, int limit, int offset)
throws ClientProtocolException, URISyntaxException, IOException, JSONException {
Map<String, String> listOfMethods = getBasicParams();
if (folder_id == 0 || folder_id == 1 || folder_id == 4) {
listOfMethods.put("folder_id", "" + folder_id);
}
if (uid > 0) {
listOfMethods.put("uid", "" + uid);
}
if (limit > 0) {
listOfMethods.put("limit", "" + limit);
}
if (offset > 0) {
listOfMethods.put("offset", "" + offset);
}
listOfMethods.put(METHOD, MESSAGE_GETTHREADSINFOLDER);
HttpResponseMessage response = f4j.sendGetRequest(listOfMethods);
JSONObject root = new JSONObject(response.getResponse());
// TODO response parsing
}
public ArrayList<Note> getNotes(long userId) throws ClientProtocolException, URISyntaxException, IOException,
JSONException {
Map<String, String> listOfMethods = getBasicParams();
ArrayList<Note> rslt = new ArrayList<Note>();
if (userId > 0) {
listOfMethods.put("uid", "" + userId);
}
listOfMethods.put(METHOD, NOTES_GET);
HttpResponseMessage response = f4j.sendGetRequest(listOfMethods);
JSONArray root = new JSONArray(response.getResponse());
int numOfNotes = root.length();
for (int a = 0; a < numOfNotes; a++) {
JSONObject aNote = root.getJSONObject(a);
rslt.add(new Note(aNote));
}
return rslt;
}
/**
*
* @param start_time
* @param include_read
* @return
* @throws ClientProtocolException
* @throws URISyntaxException
* @throws IOException
* @throws JSONException
*/
public ArrayList<Notification> getNotificationList(long start_time, boolean include_read)
throws ClientProtocolException, URISyntaxException, IOException, JSONException {
Map<String, String> listOfMethods = getBasicParams();
ArrayList<Notification> rslt = new ArrayList<Notification>();
if (start_time > 0) {
listOfMethods.put("start_time", "" + start_time);
}
listOfMethods.put("include_read", "" + include_read);
listOfMethods.put(METHOD, NOTIFICATIONS_GETLIST);
HttpResponseMessage response = f4j.sendGetRequest(listOfMethods);
JSONObject root = new JSONObject(response.getResponse());
JSONArray notificationArr = root.getJSONArray("notifications");
for (int a = 0; a < notificationArr.length(); a++) {
JSONObject aNotification = notificationArr.getJSONObject(a);
rslt.add(new Notification(aNotification));
}
return rslt;
}
public NotificationStatus getNotifications() throws ClientProtocolException, URISyntaxException, IOException,
JSONException {
Map<String, String> listOfMethods = getBasicParams();
listOfMethods.put(METHOD, NOTIFICATIONS_GET);
HttpResponseMessage response = f4j.sendGetRequest(listOfMethods);
JSONObject root = new JSONObject(response.getResponse());
return new NotificationStatus(root);
}
/**
* It retrieves logged-in user's status.
*
* @param limit
* Number of status to be returned. Default value is 100.
* @return status list
* @throws ClientProtocolException
* @throws URISyntaxException
* @throws IOException
* @throws JSONException
* @throws JSONException
*/
public ArrayList<Status> getStatus(int limit) throws ClientProtocolException, URISyntaxException, IOException,
JSONException {
ArrayList<Status> rtnValue = new ArrayList<Status>();
Map<String, String> listOfMethods = getBasicParams();
if (limit > 0) {
listOfMethods.put("limit", "" + limit);
}
listOfMethods.put(METHOD, STATUS_GET);
HttpResponseMessage response = f4j.sendGetRequest(listOfMethods);
JSONArray jArray = new JSONArray(response.getResponse());
int arraySize = jArray.length();
for (int a = 0; a < arraySize; a++) {
JSONObject jObj;
try {
jObj = jArray.getJSONObject(a);
rtnValue.add(new Status(jObj.getLong("uid"), jObj.getLong("source"), jObj.getLong("status_id"),
new Date(jObj.getLong("time") * 1000), jObj.getString("message")));
} catch (JSONException e) {
e.printStackTrace();
}
}
return rtnValue;
}
/**
*
* @return
* @throws ClientProtocolException
* @throws URISyntaxException
* @throws IOException
* @throws JSONException
*/
public Stream getStream() throws ClientProtocolException, URISyntaxException, IOException, JSONException {
return getStream(-1, null, -1, -1, -1, null, null);
}
/**
*
* @param viewerId
* The user ID for whom you are fetching stream data. You can
* pass 0 for this parameter to retrieve publicly viewable
* information. However, desktop applications must always specify
* a viewer as well as a session key. (Default value is the
* current session user.)
* @param srcIds
* An array containing all the stream data for the user profiles,
* Pages, groups, and events connected to the viewer_id. You can
* filter the stream to include posts by the IDs you specify
* here. (Default value is all connections of the viewer.)
* @param startTime
* The earliest time (in Unix time) for which to retrieve posts
* from the stream. The start_time uses the updated_time field in
* the stream (FQL) table as the baseline for determining the
* earliest time for which to get the stream. (Default value is 1
* day ago.)
* @param endTime
* The latest time (in Unix time) for which to retrieve posts
* from the stream. The end_time uses the updated_time field in
* the stream (FQL) table as the baseline for determining the
* latest time for which to get the stream. (Default value is
* now.)
* @param limit
* A 32-bit int representing the total number of posts to return.
* (Default value is 30 posts.)
* @param filterKey
* A filter associated with the user. Filters get returned by
* stream.getFilters or the stream_filter FQL table. To filter
* for stream posts from your application, look for a filter with
* a filter_key set to "app_YOURAPPLICATIONID".
* @param metadata
* A JSON-encoded array in which you can specify one or more of
* the following when you call stream.get: <br>
* <li>albums -- to request the user's aid (album ID)</li> <br>
* <li>profiles -- to request the user's ID (user ID or Page ID)</li>
* <br>
* <li>photo_tags to request the user's pid (photo ID)</li> <br>
* <li>strip_tags(field) -- to strip out any HTML markup and
* encoding in an attachment field. You can specify this function
* more than once if you want to remove markup from multiple
* fields.</li> <br>
* These parameters are all optional. (Default value is false for
* all keys.)
* @return
* @throws IOException
* @throws URISyntaxException
* @throws ClientProtocolException
* @throws JSONException
*/
public Stream getStream(long viewerId, JSONArray srcIds, long startTime, long endTime, int limit, String filterKey,
JSONArray metadata) throws ClientProtocolException, URISyntaxException, IOException, JSONException {
Stream stream = new Stream();
Map<String, String> listOfMethods = getBasicParams();
if (viewerId >= 0) {
listOfMethods.put("viewer_id", "" + viewerId);
}
if (srcIds != null && srcIds.length() > 0) {
listOfMethods.put("source_ids", srcIds.toString());
}
if (startTime > 0) {
listOfMethods.put("start_time", "" + startTime);
}
if (endTime > 0) {
listOfMethods.put("end_time", "" + endTime);
}
if (limit > 0) {
listOfMethods.put("limit", "" + limit);
}
if (filterKey != null && !filterKey.trim().equals("")) {
listOfMethods.put("filter_key", filterKey);
}
if (metadata != null && metadata.length() > 0) {
listOfMethods.put("metadata", metadata.toString());
}
listOfMethods.put(METHOD, STREAM_GET);
HttpResponseMessage response = f4j.sendGetRequest(listOfMethods);
JSONObject root = new JSONObject(response.getResponse());
// lists that stream can hold
ArrayList<Post> postList = new ArrayList<Post>();
ArrayList<Album> albumList = new ArrayList<Album>();
ArrayList<Profile> profileList = new ArrayList<Profile>();
// handle posts
try {
Object postListObj = root.opt("posts");
if (postListObj != null && postListObj instanceof JSONArray) {
JSONArray posts = (JSONArray) postListObj;
int postSize = posts.length();
for (int a = 0; a < postSize; a++) {
JSONObject jObj = posts.getJSONObject(a);
Post p = new Post();
p.postId = jObj.getString("post_id");
p.viewerId = jObj.getLong("viewer_id");
p.sourceId = jObj.getLong("source_id");
p.type = jObj.getInt("type");
// jObj.getLong("app_id");
p.actorId = jObj.getLong("actor_id");
p.targetId = jObj.getString("target_id");
p.message = jObj.getString("message");
JSONObject comments = jObj.getJSONObject("comments");
p.numOfComments = comments.getInt("count");
Object chkCmtObj = comments.get("comment_list");
if (chkCmtObj instanceof JSONArray) {
JSONArray commentArray = comments.getJSONArray("comment_list");
int commentsSize = commentArray.length();
if (commentsSize > 0) {
ArrayList<Comment> commentList = new ArrayList<Comment>();
for (int b = 0; b < commentsSize; b++) {
JSONObject comment = commentArray.getJSONObject(b);
Comment co = new Comment();
co.fromid = comment.getLong("fromid");
co.time = new Date(comment.getLong("time") * 1000);
co.message = comment.getString("text");
co.id = comment.getString("id");
commentList.add(co);
}
p.comments = commentList;
}
}
p.updateDate = new Date(jObj.getLong("updated_time") * 1000);
p.creationDate = new Date(jObj.getLong("created_time") * 1000);
postList.add(p);
}
}
} catch (JSONException jsone) {
jsone.printStackTrace();
}
// handle albums
try {
Object albumListObj = root.opt("albums");
if (albumListObj != null && albumListObj instanceof JSONArray) {
JSONArray albums = (JSONArray) albumListObj;
int albumsSize = albums.length();
for (int a = 0; a < albumsSize; a++) {
JSONObject jObj = albums.getJSONObject(a);
Album album = new Album();
album.aid = jObj.getString("aid");
album.coverPid = jObj.getString("cover_pid");
album.owner = jObj.getLong("owner");
album.name = jObj.getString("name");
album.created = new Date(jObj.getLong("created") * 1000);
album.modified = new Date(jObj.getLong("modified") * 1000);
album.description = jObj.getString("description");
album.link = jObj.getString("link");
album.objectId = jObj.getLong("object_id");
album.modifiedMajor = new Date(jObj.getLong("modified_major") * 1000);
album.type = jObj.getString("type");
albumList.add(album);
}
}
} catch (JSONException jsone) {
jsone.printStackTrace();
}
// handle profiles
try {
Object profileListObj = root.opt("profiles");
if (profileListObj != null && profileListObj instanceof JSONArray) {
JSONArray profiles = (JSONArray) profileListObj;
int profileSize = profiles.length();
for (int a = 0; a < profileSize; a++) {
JSONObject jObj = profiles.getJSONObject(a);
Profile p = new Profile();
p.id = jObj.getLong("id");
p.url = jObj.getString("url");
p.name = jObj.getString("name");
p.picSquare = jObj.getString("pic_square");
p.type = jObj.getString("type");
profileList.add(p);
}
}
} catch (JSONException jsone) {
jsone.printStackTrace();
}
// handle photo_tags
// not implemented yet
// try {
// JSONArray photoTags = root.getJSONArray("photo_tags");
// int photoTagsSize = photoTags.length();
// for (int a = 0; a < photoTagsSize; a++) {
// // JSONObject jObj = photoTags.getJSONObject(a);
// }
// } catch (JSONException jsone) {
// jsone.printStackTrace();
// }
stream.postList = postList;
stream.albumList = albumList;
stream.profileList = profileList;
return stream;
}
/**
*
* @param postId
* @return
* @throws ClientProtocolException
* @throws URISyntaxException
* @throws IOException
* @throws JSONException
*/
public ArrayList<Comment> getStreamComment(String postId) throws ClientProtocolException, URISyntaxException,
IOException, JSONException {
if (postId == null || postId.trim().equals("")) {
throw new IllegalArgumentException("Argument 'postId' is null. Please insert postId.");
}
ArrayList<Comment> commentList = new ArrayList<Comment>();
Map<String, String> listOfMethods = getBasicParams();
listOfMethods.put(METHOD, STREAM_GETCOMMENTS);
listOfMethods.put("post_id", postId);
HttpResponseMessage response = f4j.sendGetRequest(listOfMethods);
String output = response.getResponse().trim();
if (output != null && !output.equals("") && output.charAt(0) != '{') {
JSONArray jArray = new JSONArray(output);
int arrSize = jArray.length();
for (int a = 0; a < arrSize; a++) {
JSONObject jObj = jArray.getJSONObject(a);
Comment comment = new Comment();
comment.fromid = jObj.getLong("fromid");
comment.time = new Date(jObj.getLong("time") * 1000);
comment.message = jObj.getString("text");
comment.id = jObj.getString("id");
commentList.add(comment);
}
}
return commentList;
}
public ArrayList<Message> getThreadsInFolder() {
return null;
}
/**
* Retrieves userinfo based on class which extends BasicUserInfo.
*
* @param <T>
* class that extends BasicUserInfo
* @param uid
* userid
* @param userInfo
*
* @throws ClientProtocolException
* @throws URISyntaxException
* @throws IOException
* @throws JSONException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public void getUserInfo(Long[] uids, ArrayList<Parameterable> userInfo, Class<? extends Parameterable> type)
throws ClientProtocolException, URISyntaxException, IOException, JSONException, InstantiationException,
IllegalAccessException {
Map<String, String> listOfMethods = getBasicParams();
if (uids == null || uids.length < 0) {
throw new IllegalArgumentException("");
}
StringBuffer userid = new StringBuffer();
for (long uid : uids) {
userid.append(uid);
userid.append(',');
}
userid.deleteCharAt(userid.length() - 1);// delete last comma
listOfMethods.put("uids", userid.toString());
listOfMethods.put(METHOD, USERS_GETINFO);
Parameterable basicInfo = type.newInstance();
listOfMethods.put("fields", basicInfo.getFields());
HttpResponseMessage response = f4j.sendGetRequest(listOfMethods);
JSONArray jArray = new JSONArray(response.getResponse());
int jArraySize = jArray.length();
for (int a = 0; a < jArraySize; a++) {
JSONObject jObj = jArray.getJSONObject(a);
Parameterable bInfo = type.newInstance();
bInfo.setJSONObject(jObj);
userInfo.add(bInfo);
}
}
}