FacebookRestClientpublic class FacebookRestClient extends Object implements IFacebookRestClientA FacebookRestClient that uses the XML result format. This means results from calls
to the Facebook API are returned as XML and transformed into instances of Document.
Allocate an instance of this class to make Facebook API requests. |
Fields Summary |
---|
public static final String | TARGET_API_VERSIONAPI version to request when making calls to the server | public static final String | ERROR_TAGFlag indicating an erroneous response | public static final String | FB_SERVERFacebook API server, part 1 | public static final String | SERVER_ADDRFacebook API server, part 2a | public static final String | HTTPS_SERVER_ADDRFacebook API server, part 2b | public static URL | SERVER_URLFacebook API server, part 3a | public static URL | HTTPS_SERVER_URLFacebook API server, part 3b | protected final String | _secret | protected final String | _apiKey | protected final URL | _serverUrl | protected String | rawResponse | protected String | _sessionKey | protected boolean | _isDesktop | protected String | _sessionSecret | protected long | _userId | public static int | NUM_AUTOAPPENDED_PARAMSnumber of params that the client automatically appends to every API call | private static boolean | DEBUG | protected Boolean | _debug | protected File | _uploadFile | protected static final String | CRLF | protected static final String | PREF | protected static final int | UPLOAD_BUFFER_SIZE | public static final String | MARKETPLACE_STATUS_DEFAULT | public static final String | MARKETPLACE_STATUS_NOT_SUCCESS | public static final String | MARKETPLACE_STATUS_SUCCESS |
Constructors Summary |
---|
public FacebookRestClient(String apiKey, String secret)Constructor
this(SERVER_URL, apiKey, secret, null);
| public FacebookRestClient(String apiKey, String secret, String sessionKey)Constructor
this(SERVER_URL, apiKey, secret, sessionKey);
| public FacebookRestClient(String serverAddr, String apiKey, String secret, String sessionKey)Constructor
this(new URL(serverAddr), apiKey, secret, sessionKey);
| public FacebookRestClient(URL serverUrl, String apiKey, String secret, String sessionKey)Constructor
_sessionKey = sessionKey;
_apiKey = apiKey;
_secret = secret;
_serverUrl = (null != serverUrl) ? serverUrl : SERVER_URL;
|
Methods Summary |
---|
public java.lang.String | auth_createToken()Call this function and store the result, using it to generate the
appropriate login url and then to retrieve the session information.
Document d = this.callMethod(FacebookMethod.AUTH_CREATE_TOKEN);
return d.getFirstChild().getTextContent();
| public java.lang.String | auth_getSession(java.lang.String authToken)Call this function to retrieve the session information after your user has
logged in.
Document d =
this.callMethod(FacebookMethod.AUTH_GET_SESSION, new Pair<String, CharSequence>("auth_token",
authToken.toString()));
this._sessionKey =
d.getElementsByTagName("session_key").item(0).getFirstChild().getTextContent();
this._userId =
Long.parseLong(d.getElementsByTagName("uid").item(0).getFirstChild().getTextContent());
if (this._isDesktop)
this._sessionSecret =
d.getElementsByTagName("secret").item(0).getFirstChild().getTextContent();
return this._sessionKey;
| public long | auth_getUserId(java.lang.String authToken)
if (null == this._sessionKey)
auth_getSession(authToken);
return this.users_getLoggedInUser();
| protected org.w3c.dom.Document | callMethod(com.facebook.api.IFacebookMethod method, com.facebook.api.Pair paramPairs)Call the specified method, with the given parameters, and return a DOM tree with the results.
return callMethod(method, Arrays.asList(paramPairs));
| protected org.w3c.dom.Document | callMethod(com.facebook.api.IFacebookMethod method, java.util.Collection paramPairs)Call the specified method, with the given parameters, and return a DOM tree with the results.
this.rawResponse = null;
HashMap<String, CharSequence> params =
new HashMap<String, CharSequence>(2 * method.numTotalParams());
params.put("method", method.methodName());
params.put("api_key", _apiKey);
params.put("v", TARGET_API_VERSION);
if (method.requiresSession()) {
params.put("call_id", Long.toString(System.currentTimeMillis()));
params.put("session_key", _sessionKey);
}
CharSequence oldVal;
for (Pair<String, CharSequence> p: paramPairs) {
oldVal = params.put(p.first, p.second);
if (oldVal != null)
System.out.println("For parameter " + p.first + ", overwrote old value " + oldVal +
" with new value " + p.second + ".");
}
assert (!params.containsKey("sig"));
String signature = generateSignature(FacebookSignatureUtil.convert(params.entrySet()), method.requiresSession());
params.put("sig", signature);
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
boolean doHttps = this.isDesktop() && FacebookMethod.AUTH_GET_SESSION.equals(method);
InputStream data =
method.takesFile() ? postFileRequest(method.methodName(), params) : postRequest(method.methodName(),
params,
doHttps,
true);
/*int current = 0;
StringBuffer buffer = new StringBuffer();
while (current != -1) {
current = data.read();
if (current != -1) {
buffer.append((char)current);
}
}*/
BufferedReader in = new BufferedReader(new InputStreamReader(data, "UTF-8"));
StringBuffer buffer = new StringBuffer();
String line;
while ((line = in.readLine()) != null) {
buffer.append(line);
}
String xmlResp = new String(buffer);
this.rawResponse = xmlResp;
Document doc = builder.parse(new ByteArrayInputStream(xmlResp.getBytes("UTF-8")));
doc.normalizeDocument();
stripEmptyTextNodes(doc);
if (isDebug())
FacebookRestClient.printDom(doc, method.methodName() + "| "); // TEST
NodeList errors = doc.getElementsByTagName(ERROR_TAG);
if (errors.getLength() > 0) {
int errorCode =
Integer.parseInt(errors.item(0).getFirstChild().getFirstChild().getTextContent());
String message = errors.item(0).getFirstChild().getNextSibling().getTextContent();
// FIXME: additional printing done for debugging only
System.out.println("Facebook returns error code " + errorCode);
for (Map.Entry<String,CharSequence> entry : params.entrySet())
System.out.println(" - " + entry.getKey() + " -> " + entry.getValue());
throw new FacebookException(errorCode, message);
}
return doc;
}
catch (java.net.SocketException ex) {
System.err.println("Socket exception when calling facebook method: " + ex.getMessage());
}
catch (javax.xml.parsers.ParserConfigurationException ex) {
System.err.println("huh?");
ex.printStackTrace();
}
catch (org.xml.sax.SAXException ex) {
throw new IOException("error parsing xml");
}
return null;
| private void | checkError()
if (this.rawResponse.contains("error_response")) {
//<error_code>xxx</error_code>
Integer code = Integer.parseInt(this.rawResponse.substring(this.rawResponse.indexOf("<error_code>") + "<error_code>".length(),
this.rawResponse.indexOf("</error_code>") + "</error_code>".length()));
throw new FacebookException(code, "The request could not be completed!");
}
| public java.lang.String | data_getUserPreference(java.lang.Integer prefId)Lookup a single preference value for the current user.
if ((prefId < 0) || (prefId > 200)) {
throw new FacebookException(ErrorCode.GEN_INVALID_PARAMETER, "The preference id must be an integer value from 0-200.");
}
this.callMethod(FacebookMethod.DATA_GET_USER_PREFERENCE, new Pair<String, CharSequence>("pref_id", Integer.toString(prefId)));
this.checkError();
if (! this.rawResponse.contains("</data_getUserPreference_response>")) {
//there is no value set for this preference yet
return null;
}
String result = this.rawResponse.substring(0, this.rawResponse.indexOf("</data_getUserPreference_response>"));
result = result.substring(result.indexOf("facebook.xsd\">") + "facebook.xsd\">".length());
return reconstructValue(result);
| public java.util.Map | data_getUserPreferences()Get a map containing all preference values set for the current user.
Document response = this.callMethod(FacebookMethod.DATA_GET_USER_PREFERENCES);
this.checkError();
Map<Integer, String> results = new HashMap<Integer, String>();
NodeList ids = response.getElementsByTagName("pref_id");
NodeList values = response.getElementsByTagName("value");
for (int count = 0; count < ids.getLength(); count++) {
results.put(Integer.parseInt(ids.item(count).getFirstChild().getTextContent()),
reconstructValue(values.item(count).getFirstChild().getTextContent()));
}
return results;
| public void | data_setUserPreference(java.lang.Integer prefId, java.lang.String value)Set a user-preference value. The value can be any string up to 127 characters in length,
while the preference id can only be an integer between 0 and 200. Any preference set applies
only to the current user of the application.
To clear a user-preference, specify null as the value parameter. The values of "0" and "" will
be stored as user-preferences with a literal value of "0" and "" respectively.
if ((prefId < 0) || (prefId > 200)) {
throw new FacebookException(ErrorCode.GEN_INVALID_PARAMETER, "The preference id must be an integer value from 0-200.");
}
if ((value != null) && (value.length() > 127)) {
throw new FacebookException(ErrorCode.GEN_INVALID_PARAMETER, "The preference value cannot be longer than 128 characters.");
}
value = normalizePreferenceValue(value);
Collection<Pair<String, CharSequence>> params = new ArrayList<Pair<String, CharSequence>>();
params.add(new Pair<String, CharSequence>("pref_id", Integer.toString(prefId)));
params.add(new Pair<String, CharSequence>("value", value));
this.callMethod(FacebookMethod.DATA_SET_USER_PREFERENCE, params);
this.checkError();
| public void | data_setUserPreferences(java.util.Map values, boolean replace)Set multiple user-preferences values. The values can be strings up to 127 characters in length,
while the preference id can only be an integer between 0 and 200. Any preferences set apply
only to the current user of the application.
To clear a user-preference, specify null as its value in the map. The values of "0" and "" will
be stored as user-preferences with a literal value of "0" and "" respectively.
JSONObject map = new JSONObject();
for (Integer key : values.keySet()) {
if ((key < 0) || (key > 200)) {
throw new FacebookException(ErrorCode.GEN_INVALID_PARAMETER, "The preference id must be an integer value from 0-200.");
}
if ((values.get(key) != null) && (values.get(key).length() > 127)) {
throw new FacebookException(ErrorCode.GEN_INVALID_PARAMETER, "The preference value cannot be longer than 128 characters.");
}
try {
map.put(Integer.toString(key), normalizePreferenceValue(values.get(key)));
}
catch (JSONException e) {
FacebookException ex = new FacebookException(ErrorCode.GEN_INVALID_PARAMETER, "Error when translating {key="
+ key + ", value=" + values.get(key) + "}to JSON!");
ex.setStackTrace(e.getStackTrace());
throw ex;
}
}
Collection<Pair<String, CharSequence>> params = new ArrayList<Pair<String, CharSequence>>();
params.add(new Pair<String, CharSequence>("values", map.toString()));
if (replace) {
params.add(new Pair<String, CharSequence>("replace", "true"));
}
this.callMethod(FacebookMethod.DATA_SET_USER_PREFERENCES, params);
this.checkError();
| private static java.lang.CharSequence | delimit(java.util.Collection iterable)
// could add a thread-safe version that uses StringBuffer as well
if (iterable == null || iterable.isEmpty())
return null;
StringBuilder buffer = new StringBuilder();
boolean notFirst = false;
for (Object item: iterable) {
if (notFirst)
buffer.append(",");
else
notFirst = true;
buffer.append(item.toString());
}
return buffer;
| protected static java.lang.CharSequence | delimit(java.util.Collection entries, java.lang.CharSequence delimiter, java.lang.CharSequence equals, boolean doEncode)
if (entries == null || entries.isEmpty())
return null;
StringBuilder buffer = new StringBuilder();
boolean notFirst = false;
for (Map.Entry<String, CharSequence> entry: entries) {
if (notFirst)
buffer.append(delimiter);
else
notFirst = true;
CharSequence value = entry.getValue();
buffer.append(entry.getKey()).append(equals).append(doEncode ? encode(value) : value);
}
return buffer;
| private static java.lang.String | encode(java.lang.CharSequence target)
String result = (target != null) ? target.toString() : "";
try {
result = URLEncoder.encode(result, "UTF8");
}
catch (UnsupportedEncodingException e) {
System.err.println("Unsuccessful attempt to encode '" + result + "' into UTF8");
}
return result;
| public org.w3c.dom.Document | events_get(java.lang.Long userId, java.util.Collection eventIds, java.lang.Long startTime, java.lang.Long endTime)Returns all visible events according to the filters specified. This may be used to find all events of a user, or to query specific eids.
ArrayList<Pair<String, CharSequence>> params =
new ArrayList<Pair<String, CharSequence>>(FacebookMethod.EVENTS_GET.numParams());
boolean hasUserId = null != userId && 0 != userId;
boolean hasEventIds = null != eventIds && !eventIds.isEmpty();
boolean hasStart = null != startTime && 0 != startTime;
boolean hasEnd = null != endTime && 0 != endTime;
if (hasUserId)
params.add(new Pair<String, CharSequence>("uid", Long.toString(userId)));
if (hasEventIds)
params.add(new Pair<String, CharSequence>("eids", delimit(eventIds)));
if (hasStart)
params.add(new Pair<String, CharSequence>("start_time", startTime.toString()));
if (hasEnd)
params.add(new Pair<String, CharSequence>("end_time", endTime.toString()));
return this.callMethod(FacebookMethod.EVENTS_GET, params);
| public org.w3c.dom.Document | events_getMembers(java.lang.Number eventId)Retrieves the membership list of an event
assert (null != eventId);
return this.callMethod(FacebookMethod.EVENTS_GET_MEMBERS,
new Pair<String, CharSequence>("eid", eventId.toString()));
| protected static boolean | extractBoolean(org.w3c.dom.Document doc)
String content = doc.getFirstChild().getTextContent();
return 1 == Integer.parseInt(content);
| protected int | extractInt(org.w3c.dom.Document doc)Extracts an Integer from a document that consists of an Integer only.
return Integer.parseInt(doc.getFirstChild().getTextContent());
| public boolean | fbml_refreshImgSrc(java.lang.String imageUrl)Recaches the image with the specified imageUrl.
return fbml_refreshImgSrc(new URL(imageUrl));
| public boolean | fbml_refreshImgSrc(java.net.URL imageUrl)Recaches the image with the specified imageUrl.
return extractBoolean(this.callMethod(FacebookMethod.FBML_REFRESH_IMG_SRC,
new Pair<String, CharSequence>("url", imageUrl.toString())));
| public boolean | fbml_refreshRefUrl(java.lang.String url)Recaches the referenced url.
return fbml_refreshRefUrl(new URL(url));
| public boolean | fbml_refreshRefUrl(java.net.URL url)Recaches the referenced url.
return extractBoolean(this.callMethod(FacebookMethod.FBML_REFRESH_REF_URL,
new Pair<String, CharSequence>("url", url.toString())));
| public boolean | fbml_setRefHandle(java.lang.String handle, java.lang.String markup)Associates the specified FBML markup with the specified handle/id. The markup can then be referenced using the fb:ref FBML
tag, to allow a given snippet to be reused easily across multiple users, and also to allow the application to update
the fbml for multiple users more easily without having to make a seperate call for each user, by just changing the FBML
markup that is associated with the handle/id.
if ((handle == null) || ("".equals(handle))) {
throw new FacebookException(ErrorCode.GEN_INVALID_PARAMETER, "The FBML handle may not be null or empty!");
}
if (markup == null) {
markup = "";
}
Collection<Pair<String, CharSequence>> params = new ArrayList<Pair<String, CharSequence>>();
params.add(new Pair<String, CharSequence>("handle", handle));
params.add(new Pair<String, CharSequence>("fbml", markup));
return extractBoolean(this.callMethod(FacebookMethod.FBML_SET_REF_HANDLE, params));
| protected org.w3c.dom.Document | feedHandler(com.facebook.api.FacebookMethod feedMethod, java.lang.CharSequence title, java.lang.CharSequence body, java.util.Collection images, java.lang.Integer priority)
assert (images == null || images.size() <= 4);
ArrayList<Pair<String, CharSequence>> params =
new ArrayList<Pair<String, CharSequence>>(feedMethod.numParams());
params.add(new Pair<String, CharSequence>("title", title));
if (null != body)
params.add(new Pair<String, CharSequence>("body", body));
if (null != priority)
params.add(new Pair<String, CharSequence>("priority", priority.toString()));
if (null != images && !images.isEmpty()) {
int image_count = 0;
for (IPair image: images) {
++image_count;
assert (image.getFirst() != null);
params.add(new Pair<String, CharSequence>(String.format("image_%d", image_count),
image.getFirst().toString()));
if (image.getSecond() != null)
params.add(new Pair<String, CharSequence>(String.format("image_%d_link", image_count),
image.getSecond().toString()));
}
}
return this.callMethod(feedMethod, params);
| protected boolean | feedHandlerBoolean(com.facebook.api.FacebookMethod feedMethod, java.lang.CharSequence title, java.lang.CharSequence body, java.util.Collection images, java.lang.Integer priority)
assert (images == null || images.size() <= 4);
ArrayList<Pair<String, CharSequence>> params =
new ArrayList<Pair<String, CharSequence>>(feedMethod.numParams());
params.add(new Pair<String, CharSequence>("title", title));
if (null != body)
params.add(new Pair<String, CharSequence>("body", body));
if (null != priority)
params.add(new Pair<String, CharSequence>("priority", priority.toString()));
if (null != images && !images.isEmpty()) {
int image_count = 0;
for (IPair image: images) {
++image_count;
assert (image.getFirst() != null);
params.add(new Pair<String, CharSequence>(String.format("image_%d", image_count),
image.getFirst().toString()));
if (image.getSecond() != null)
params.add(new Pair<String, CharSequence>(String.format("image_%d_link", image_count),
image.getSecond().toString()));
}
}
this.callMethod(feedMethod, params);
return this.rawResponse.contains(">1<"); //a code of '1' indicates success
| public boolean | feed_PublishTemplatizedAction(com.facebook.api.TemplatizedAction action)Publishes a templatized action for the current user. The action will appear in their minifeed,
and may appear in their friends' newsfeeds depending upon a number of different factors. When
a template match exists between multiple distinct users (like "Bob recommends Bizou" and "Sally
recommends Bizou"), the feed entries may be combined in the newfeed (to something like "Bob and sally
recommend Bizou"). This happens automatically, and *only* if the template match between the two
feed entries is identical.
Feed entries are not aggregated for a single user (so "Bob recommends Bizou" and "Bob recommends Le
Charm" *will not* become "Bob recommends Bizou and Le Charm").
If the user's action involves one or more of their friends, list them in the 'targetIds' parameter.
For example, if you have "Bob says hi to Sally and Susie", and Sally's UID is 1, and Susie's UID is 2,
then pass a 'targetIds' paramters of "1,2". If you pass this parameter, you can use the "{target}" token
in your templates. Probably it also makes it more likely that Sally and Susie will see the feed entry
in their newsfeed, relative to any other friends Bob might have. It may be a good idea to always send
a list of all the user's friends, and avoid using the "{target}" token, to maximize distribution of the
story through the newsfeed.
The only strictly required parameter is 'titleTemplate', which must contain the "{actor}" token somewhere
inside of it. All other parameters, options, and tokens are optional, and my be set to null if
being omitted.
Not that stories will only be aggregated if *all* templates match and *all* template parameters match, so
if two entries have the same templateTitle and titleData, but a different bodyTemplate, they will not
aggregate. Probably it's better to use bodyGeneral instead of bodyTemplate, for the extra flexibility
it provides.
Note that this method is replacing 'feed_publishActionOfUser', which has been deprecated by Facebook.
For specific details, visit http://wiki.developers.facebook.com/index.php/Feed.publishTemplatizedAction
return this.feed_publishTemplatizedAction(action.getTitleTemplate(), action.getTitleParams(), action.getBodyTemplate(), action.getBodyParams(), action.getBodyGeneral(), action.getPictures(), action.getTargetIds());
| public boolean | feed_publishActionOfUser(java.lang.CharSequence title, java.lang.CharSequence body, java.util.Collection images)
return this.feed_publishActionOfUser(title, body, images, null);
| public boolean | feed_publishActionOfUser(java.lang.CharSequence title, java.lang.CharSequence body, java.util.Collection images, java.lang.Integer priority)Publish the notification of an action taken by a user to newsfeed.
return feedHandlerBoolean(FacebookMethod.FEED_PUBLISH_ACTION_OF_USER, title, body, images, priority);
| public boolean | feed_publishActionOfUser(java.lang.String title, java.lang.String body)
return feed_publishActionOfUser(title, body, null, null);
| public boolean | feed_publishActionOfUser(java.lang.CharSequence title, java.lang.CharSequence body)
return feed_publishActionOfUser(title, body, null, null);
| public boolean | feed_publishActionOfUser(java.lang.CharSequence title, java.lang.CharSequence body, java.lang.Integer priority)
return feed_publishActionOfUser(title, body, null, priority);
| public boolean | feed_publishStoryToUser(java.lang.CharSequence title, java.lang.CharSequence body, java.util.Collection images)Publish a story to the logged-in user's newsfeed.
return feed_publishStoryToUser(title, body, images, null);
| public boolean | feed_publishStoryToUser(java.lang.CharSequence title, java.lang.CharSequence body, java.util.Collection images, java.lang.Integer priority)Publish a story to the logged-in user's newsfeed.
return feedHandlerBoolean(FacebookMethod.FEED_PUBLISH_STORY_TO_USER, title, body, images, priority);
| public boolean | feed_publishStoryToUser(java.lang.String title, java.lang.String body)
return feed_publishStoryToUser(title, body, null, null);
| public boolean | feed_publishStoryToUser(java.lang.String title, java.lang.String body, java.lang.Integer priority)
return feed_publishStoryToUser(title, body, null, priority);
| public boolean | feed_publishStoryToUser(java.lang.CharSequence title, java.lang.CharSequence body)
return feed_publishStoryToUser(title, body, null, null);
| public boolean | feed_publishStoryToUser(java.lang.CharSequence title, java.lang.CharSequence body, java.lang.Integer priority)
return feed_publishStoryToUser(title, body, null, priority);
| public boolean | feed_publishTemplatizedAction(java.lang.Long actorId, java.lang.CharSequence titleTemplate)
return this.feed_publishTemplatizedAction(titleTemplate.toString(), null, null, null, null, null, null);
| public boolean | feed_publishTemplatizedAction(java.lang.Long actorId, java.lang.CharSequence titleTemplate, java.util.Map titleData, java.lang.CharSequence bodyTemplate, java.util.Map bodyData, java.lang.CharSequence bodyGeneral, java.util.Collection targetIds, java.util.Collection images)
return this.feed_publishTemplatizedAction(titleTemplate.toString(),
titleData.toString(), bodyTemplate.toString(), bodyData.toString(), bodyGeneral.toString(), images, targetIds.toString());
| public boolean | feed_publishTemplatizedAction(java.lang.Integer actorId, java.lang.CharSequence titleTemplate, java.util.Map titleData, java.lang.CharSequence bodyTemplate, java.util.Map bodyData, java.lang.CharSequence bodyGeneral, java.util.Collection targetIds, java.util.Collection images)
return this.feed_publishTemplatizedAction((long)actorId.intValue(), titleTemplate, titleData, bodyTemplate, bodyData, bodyGeneral, targetIds, images);
| public boolean | feed_publishTemplatizedAction(java.lang.String titleTemplate, java.lang.String titleData, java.lang.String bodyTemplate, java.lang.String bodyData, java.lang.String bodyGeneral, java.util.Collection pictures, java.lang.String targetIds)Publishes a templatized action for the current user. The action will appear in their minifeed,
and may appear in their friends' newsfeeds depending upon a number of different factors. When
a template match exists between multiple distinct users (like "Bob recommends Bizou" and "Sally
recommends Bizou"), the feed entries may be combined in the newfeed (to something like "Bob and sally
recommend Bizou"). This happens automatically, and *only* if the template match between the two
feed entries is identical.
Feed entries are not aggregated for a single user (so "Bob recommends Bizou" and "Bob recommends Le
Charm" *will not* become "Bob recommends Bizou and Le Charm").
If the user's action involves one or more of their friends, list them in the 'targetIds' parameter.
For example, if you have "Bob says hi to Sally and Susie", and Sally's UID is 1, and Susie's UID is 2,
then pass a 'targetIds' paramters of "1,2". If you pass this parameter, you can use the "{target}" token
in your templates. Probably it also makes it more likely that Sally and Susie will see the feed entry
in their newsfeed, relative to any other friends Bob might have. It may be a good idea to always send
a list of all the user's friends, and avoid using the "{target}" token, to maximize distribution of the
story through the newsfeed.
The only strictly required parameter is 'titleTemplate', which must contain the "{actor}" token somewhere
inside of it. All other parameters, options, and tokens are optional, and my be set to null if
being omitted.
Not that stories will only be aggregated if *all* templates match and *all* template parameters match, so
if two entries have the same templateTitle and titleData, but a different bodyTemplate, they will not
aggregate. Probably it's better to use bodyGeneral instead of bodyTemplate, for the extra flexibility
it provides.
Note that this method is replacing 'feed_publishActionOfUser', which has been deprecated by Facebook.
For specific details, visit http://wiki.developers.facebook.com/index.php/Feed.publishTemplatizedAction
return templatizedFeedHandler(FacebookMethod.FEED_PUBLISH_TEMPLATIZED_ACTION, titleTemplate, titleData, bodyTemplate,
bodyData, bodyGeneral, pictures, targetIds);
| public org.w3c.dom.Document | fql_query(java.lang.CharSequence query)Retrieves the results of a Facebook Query Language query
assert (null != query);
return this.callMethod(FacebookMethod.FQL_QUERY,
new Pair<String, CharSequence>("query", query));
| public org.w3c.dom.Document | friends_areFriends(long userId1, long userId2)Retrieves the friends of the currently logged in user.
return this.callMethod(FacebookMethod.FRIENDS_ARE_FRIENDS,
new Pair<String, CharSequence>("uids1", Long.toString(userId1)),
new Pair<String, CharSequence>("uids2", Long.toString(userId2)));
| public org.w3c.dom.Document | friends_areFriends(java.util.Collection userIds1, java.util.Collection userIds2)
assert (userIds1 != null && userIds2 != null);
assert (!userIds1.isEmpty() && !userIds2.isEmpty());
assert (userIds1.size() == userIds2.size());
return this.callMethod(FacebookMethod.FRIENDS_ARE_FRIENDS,
new Pair<String, CharSequence>("uids1", delimit(userIds1)),
new Pair<String, CharSequence>("uids2", delimit(userIds2)));
| public org.w3c.dom.Document | friends_get()Retrieves the friends of the currently logged in user.
return this.callMethod(FacebookMethod.FRIENDS_GET);
| public org.w3c.dom.Document | friends_getAppUsers()Retrieves the friends of the currently logged in user, who are also users
of the calling application.
return this.callMethod(FacebookMethod.FRIENDS_GET_APP_USERS);
| private java.lang.String | generateSignature(java.util.List params, boolean requiresSession)
String secret = (isDesktop() && requiresSession) ? this._sessionSecret : this._secret;
return FacebookSignatureUtil.generateSignature(params, secret);
| public java.lang.String | getRawResponse()Returns a string representation for the last API response recieved from Facebook, exactly as sent by the API server.
Note that calling this method consumes the data held in the internal buffer, and thus it may only be called once per API
call.
String result = this.rawResponse;
this.rawResponse = null;
return result;
| public java.lang.String | getResponseFormat()The response format in which results to FacebookMethod calls are returned
return "xml";
| public java.lang.Object | getResponsePOJO()Returns a JAXB object of the type that corresponds to the last API call made on the client. Each
Facebook Platform API call that returns a Document object has a JAXB response object associated
with it. The naming convention is generally intuitive. For example, if you invoke the
'user_getInfo' API call, the associated JAXB response object is 'UsersGetInfoResponse'.
An example of how to use this method:
FacebookRestClient client = new FacebookRestClient("apiKey", "secretKey", "sessionId");
client.friends_get();
FriendsGetResponse response = (FriendsGetResponse)client.getResponsePOJO();
List friends = response.getUid();
This is particularly useful in the case of API calls that return a Document object, as working
with the JAXB response object is generally much simple than trying to walk/parse the DOM by
hand.
This method can be safely called multiple times, though note that it will only return the
response-object corresponding to the most recent Facebook Platform API call made.
Note that you must cast the return value of this method to the correct type in order to do anything
useful with it.
if (this.rawResponse == null) {
return null;
}
JAXBContext jc;
Object pojo = null;
try {
jc = JAXBContext.newInstance("com.facebook.api.schema");
Unmarshaller unmarshaller = jc.createUnmarshaller();
pojo = unmarshaller.unmarshal(new ByteArrayInputStream(this.rawResponse.getBytes("UTF-8")));
} catch (JAXBException e) {
System.err.println("getResponsePOJO() - Could not unmarshall XML stream into POJO");
e.printStackTrace();
}
catch (NullPointerException e) {
System.err.println("getResponsePOJO() - Could not unmarshall XML stream into POJO.");
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
System.err.println("getResponsePOJO() - Could not unmarshall XML stream into POJO.");
e.printStackTrace();
}
return pojo;
| public org.w3c.dom.Document | groups_get(java.lang.Long userId, java.util.Collection groupIds)Retrieves the groups associated with a user
boolean hasGroups = (null != groupIds && !groupIds.isEmpty());
if (null != userId)
return hasGroups ?
this.callMethod(FacebookMethod.GROUPS_GET, new Pair<String, CharSequence>("uid",
userId.toString()),
new Pair<String, CharSequence>("gids", delimit(groupIds))) :
this.callMethod(FacebookMethod.GROUPS_GET,
new Pair<String, CharSequence>("uid", userId.toString()));
else
return hasGroups ?
this.callMethod(FacebookMethod.GROUPS_GET, new Pair<String, CharSequence>("gids",
delimit(groupIds))) :
this.callMethod(FacebookMethod.GROUPS_GET);
| public org.w3c.dom.Document | groups_getMembers(java.lang.Number groupId)Retrieves the membership list of a group
assert (null != groupId);
return this.callMethod(FacebookMethod.GROUPS_GET_MEMBERS,
new Pair<String, CharSequence>("gid", groupId.toString()));
| public boolean | isDebug()Check to see if debug mode is enabled.
return (null == _debug) ? FacebookRestClient.DEBUG : _debug.booleanValue();
| public boolean | isDesktop()Check to see if the client is running in desktop mode.
return this._isDesktop;
| public java.lang.Long | marketplace_createListing(java.lang.Long listingId, boolean showOnProfile, org.json.JSONObject listing)Create a new marketplace listing, or modify an existing one.
return this.marketplace_createListing(listingId, showOnProfile, listing.toString());
| public java.lang.Long | marketplace_createListing(boolean showOnProfile, org.json.JSONObject listing)Create a new marketplace listing.
return this.marketplace_createListing(0l, showOnProfile, listing.toString());
| public java.lang.Long | marketplace_createListing(java.lang.Boolean showOnProfile, com.facebook.api.MarketplaceListing attrs)Create a marketplace listing
return this.marketplace_createListing(null, showOnProfile, attrs.getAttribs());
| public java.lang.Long | marketplace_createListing(java.lang.Long listingId, boolean showOnProfile, java.lang.String attributes)Create a new marketplace listing, or modify an existing one.
if (listingId == null) {
listingId = 0l;
}
MarketListing test = new MarketListing(attributes);
if (!test.verify()) {
throw new FacebookException(ErrorCode.GEN_INVALID_PARAMETER, "The specified listing is invalid!");
}
Collection<Pair<String, CharSequence>> params = new ArrayList<Pair<String, CharSequence>>();
params.add(new Pair<String, CharSequence>("listing_id", listingId.toString()));
if (showOnProfile) {
params.add(new Pair<String, CharSequence>("show_on_profile", "true"));
}
params.add(new Pair<String, CharSequence>("listing_attrs", attributes));
this.callMethod(FacebookMethod.MARKET_CREATE_LISTING, params);
String result = this.rawResponse.substring(0, this.rawResponse.indexOf("</marketplace"));
result = result.substring(result.lastIndexOf(">") + 1);
return Long.parseLong(result);
| public java.lang.Long | marketplace_createListing(java.lang.Long listingId, boolean showOnProfile, com.facebook.api.MarketListing listing)Create a new marketplace listing, or modify an existing one.
return this.marketplace_createListing(listingId, showOnProfile, listing.getAttribs());
| public java.lang.Long | marketplace_createListing(boolean showOnProfile, com.facebook.api.MarketListing listing)Create a new marketplace listing.
return this.marketplace_createListing(0l, showOnProfile, listing.getAttribs());
| public java.lang.Long | marketplace_editListing(java.lang.Long listingId, java.lang.Boolean showOnProfile, com.facebook.api.MarketplaceListing attrs)Modify a marketplace listing
return this.marketplace_createListing(listingId, showOnProfile, attrs.getAttribs());
| public java.lang.Long | marketplace_editListing(java.lang.Long listingId, java.lang.Boolean showOnProfile, com.facebook.api.MarketListing attrs)Modify a marketplace listing
return this.marketplace_createListing(listingId, showOnProfile, attrs);
| public java.util.List | marketplace_getCategories()Return a list of all valid Marketplace categories.
this.callMethod(FacebookMethod.MARKET_GET_CATEGORIES);
MarketplaceGetCategoriesResponse resp = (MarketplaceGetCategoriesResponse)this.getResponsePOJO();
return resp.getMarketplaceCategory();
| public org.w3c.dom.Document | marketplace_getCategoriesObject()Return a list of all valid Marketplace categories.
return this.callMethod(FacebookMethod.MARKET_GET_CATEGORIES);
| public java.util.List | marketplace_getListings(java.util.List listingIds, java.util.List uids)Retrieve listings from the marketplace. The listings can be filtered by listing-id or user-id (or both).
String listings = stringify(listingIds);
String users = stringify(uids);
Collection<Pair<String, CharSequence>> params = new ArrayList<Pair<String, CharSequence>>();
if (listings != null) {
params.add(new Pair<String, CharSequence>("listing_ids", listings));
}
if (uids != null) {
params.add(new Pair<String, CharSequence>("uids", users));
}
this.callMethod(FacebookMethod.MARKET_GET_LISTINGS, params);
MarketplaceGetListingsResponse resp = (MarketplaceGetListingsResponse)this.getResponsePOJO();
return resp.getListing();
| public org.w3c.dom.Document | marketplace_getListings(java.util.Collection listingIds, java.util.Collection userIds)
ArrayList<Pair<String, CharSequence>> params =
new ArrayList<Pair<String, CharSequence>>(FacebookMethod.MARKETPLACE_GET_LISTINGS.numParams());
if (null != listingIds && !listingIds.isEmpty()) {
params.add(new Pair<String, CharSequence>("listing_ids", delimit(listingIds)));
}
if (null != userIds && !userIds.isEmpty()) {
params.add(new Pair<String, CharSequence>("uids", delimit(userIds)));
}
assert !params.isEmpty() : "Either listingIds or userIds should be provided";
return this.callMethod(FacebookMethod.MARKETPLACE_GET_LISTINGS, params);
| public java.util.List | marketplace_getSubCategories()Return a list of all valid Marketplace subcategories.
this.callMethod(FacebookMethod.MARKET_GET_SUBCATEGORIES);
MarketplaceGetSubCategoriesResponse resp = (MarketplaceGetSubCategoriesResponse)this.getResponsePOJO();
return resp.getMarketplaceSubcategory();
| public org.w3c.dom.Document | marketplace_getSubCategories(java.lang.CharSequence category)
if (category != null) {
return this.callMethod(FacebookMethod.MARKET_GET_SUBCATEGORIES, new Pair<String, CharSequence>("category", category));
}
return this.callMethod(FacebookMethod.MARKET_GET_SUBCATEGORIES);
| public boolean | marketplace_removeListing(java.lang.Long listingId, com.facebook.api.MarketListingStatus status)Remove a listing from the marketplace by id.
if (status == null) {
status = MarketListingStatus.DEFAULT;
}
if (listingId == null) {
return false;
}
Collection<Pair<String, CharSequence>> params = new ArrayList<Pair<String, CharSequence>>();
params.add(new Pair<String, CharSequence>("listing_id", listingId.toString()));
params.add(new Pair<String, CharSequence>("status", status.getName()));
this.callMethod(FacebookMethod.MARKET_REMOVE_LISTING, params);
return this.rawResponse.contains(">1<"); //a code of '1' indicates success
| public boolean | marketplace_removeListing(java.lang.Long listingId)
return this.marketplace_removeListing(listingId, MarketListingStatus.DEFAULT);
| public boolean | marketplace_removeListing(java.lang.Long listingId, java.lang.CharSequence status)
return this.marketplace_removeListing(listingId);
| public java.util.List | marketplace_search(com.facebook.api.MarketListingCategory category, com.facebook.api.MarketListingSubcategory subcategory, java.lang.String searchTerm)Search the marketplace listings by category, subcategory, and keyword.
if ("".equals(searchTerm)) {
searchTerm = null;
}
if ((subcategory != null) && (category == null)) {
throw new FacebookException(ErrorCode.GEN_INVALID_PARAMETER, "You cannot search by subcategory without also specifying a category!");
}
Collection<Pair<String, CharSequence>> params = new ArrayList<Pair<String, CharSequence>>();
if (category != null) {
params.add(new Pair<String, CharSequence>("category", category.getName()));
}
if (subcategory != null) {
params.add(new Pair<String, CharSequence>("subcategory", subcategory.getName()));
}
if (searchTerm != null) {
params.add(new Pair<String, CharSequence>("query", searchTerm));
}
this.callMethod(FacebookMethod.MARKET_SEARCH, params);
MarketplaceSearchResponse resp = (MarketplaceSearchResponse)this.getResponsePOJO();
return resp.getListing();
| public org.w3c.dom.Document | marketplace_search(java.lang.CharSequence category, java.lang.CharSequence subCategory, java.lang.CharSequence query)
if ("".equals(query)) {
query = null;
}
if ((subCategory != null) && (category == null)) {
throw new FacebookException(ErrorCode.GEN_INVALID_PARAMETER, "You cannot search by subcategory without also specifying a category!");
}
Collection<Pair<String, CharSequence>> params = new ArrayList<Pair<String, CharSequence>>();
if (category != null) {
params.add(new Pair<String, CharSequence>("category", category));
}
if (subCategory != null) {
params.add(new Pair<String, CharSequence>("subcategory", subCategory));
}
if (query != null) {
params.add(new Pair<String, CharSequence>("query", query));
}
return this.callMethod(FacebookMethod.MARKET_SEARCH, params);
| private java.lang.String | normalizePreferenceValue(java.lang.String input)
if (input == null) {
return "0";
}
return "_" + input;
| public org.w3c.dom.Document | notifications_get()Retrieves the outstanding notifications for the session user.
return this.callMethod(FacebookMethod.NOTIFICATIONS_GET);
| public java.net.URL | notifications_send(java.util.Collection recipientIds, java.lang.CharSequence notification, java.lang.CharSequence email)Send a notification message to the specified users.
assert (null != recipientIds && !recipientIds.isEmpty());
assert (null != notification);
Document d;
if (email != null) {
d = this.callMethod(FacebookMethod.NOTIFICATIONS_SEND,
new Pair<String, CharSequence>("to_ids", delimit(recipientIds)),
new Pair<String, CharSequence>("notification", notification),
new Pair<String, CharSequence>("email", email));
}
else {
d = this.callMethod(FacebookMethod.NOTIFICATIONS_SEND,
new Pair<String, CharSequence>("to_ids", delimit(recipientIds)),
new Pair<String, CharSequence>("notification", notification));
}
String url = d.getFirstChild().getTextContent();
return (null == url || "".equals(url)) ? null : new URL(url);
| public java.net.URL | notifications_sendRequest(java.util.Collection recipientIds, java.lang.CharSequence type, java.lang.CharSequence content, java.net.URL image, boolean isInvite)Send a request or invitations to the specified users.
assert (null != recipientIds && !recipientIds.isEmpty());
assert (null != type);
assert (null != content);
assert (null != image);
Document d =
this.callMethod(FacebookMethod.NOTIFICATIONS_SEND_REQUEST,
new Pair<String, CharSequence>("to_ids", delimit(recipientIds)),
new Pair<String, CharSequence>("type", type),
new Pair<String, CharSequence>("content", content),
new Pair<String, CharSequence>("image", image.toString()),
new Pair<String, CharSequence>("invite", isInvite ? "1" : "0"));
String url = d.getFirstChild().getTextContent();
return (null == url || "".equals(url)) ? null : new URL(url);
| public org.w3c.dom.Document | pages_getInfo(java.util.Collection pageIds, java.util.EnumSet fields)Retrieves the requested profile fields for the Facebook Pages with the given
pageIds . Can be called for pages that have added the application
without establishing a session.
if (pageIds == null || pageIds.isEmpty()) {
throw new IllegalArgumentException("pageIds cannot be empty or null");
}
if (fields == null || fields.isEmpty()) {
throw new IllegalArgumentException("fields cannot be empty or null");
}
IFacebookMethod method =
null == this._sessionKey ? FacebookMethod.PAGES_GET_INFO_NO_SESSION : FacebookMethod.PAGES_GET_INFO;
return this.callMethod(method,
new Pair<String, CharSequence>("page_ids", delimit(pageIds)),
new Pair<String, CharSequence>("fields", delimit(fields)));
| public org.w3c.dom.Document | pages_getInfo(java.util.Collection pageIds, java.util.Set fields)Retrieves the requested profile fields for the Facebook Pages with the given
pageIds . Can be called for pages that have added the application
without establishing a session.
if (pageIds == null || pageIds.isEmpty()) {
throw new IllegalArgumentException("pageIds cannot be empty or null");
}
if (fields == null || fields.isEmpty()) {
throw new IllegalArgumentException("fields cannot be empty or null");
}
IFacebookMethod method =
null == this._sessionKey ? FacebookMethod.PAGES_GET_INFO_NO_SESSION : FacebookMethod.PAGES_GET_INFO;
return this.callMethod(method,
new Pair<String, CharSequence>("page_ids", delimit(pageIds)),
new Pair<String, CharSequence>("fields", delimit(fields)));
| public org.w3c.dom.Document | pages_getInfo(java.lang.Long userId, java.util.EnumSet fields)Retrieves the requested profile fields for the Facebook Pages of the user with the given
userId .
if (fields == null || fields.isEmpty()) {
throw new IllegalArgumentException("fields cannot be empty or null");
}
if (userId == null) {
userId = this._userId;
}
return this.callMethod(FacebookMethod.PAGES_GET_INFO,
new Pair<String, CharSequence>("uid", userId.toString()),
new Pair<String, CharSequence>("fields", delimit(fields)));
| public org.w3c.dom.Document | pages_getInfo(java.lang.Long userId, java.util.Set fields)Retrieves the requested profile fields for the Facebook Pages of the user with the given
userId .
if (fields == null || fields.isEmpty()) {
throw new IllegalArgumentException("fields cannot be empty or null");
}
if (userId == null) {
userId = this._userId;
}
return this.callMethod(FacebookMethod.PAGES_GET_INFO,
new Pair<String, CharSequence>("uid", userId.toString()),
new Pair<String, CharSequence>("fields", delimit(fields)));
| public boolean | pages_isAdmin(java.lang.Long pageId)Checks whether the logged-in user for this session is an admin of the page
with the given pageId .
return extractBoolean(this.callMethod(FacebookMethod.PAGES_IS_ADMIN,
new Pair<String, CharSequence>("page_id",
pageId.toString())));
| public boolean | pages_isAppAdded(java.lang.Long pageId)Checks whether a page has added the application
return extractBoolean(this.callMethod(FacebookMethod.PAGES_IS_APP_ADDED,
new Pair<String,CharSequence>("page_id", pageId.toString())));
| public boolean | pages_isFan(java.lang.Long pageId, java.lang.Long userId)Checks whether a user is a fan of the page with the given pageId .
return extractBoolean(this.callMethod(FacebookMethod.PAGES_IS_FAN,
new Pair<String,CharSequence>("page_id", pageId.toString()),
new Pair<String,CharSequence>("uid", userId.toString())));
| public boolean | pages_isFan(java.lang.Long pageId)Checks whether the logged-in user is a fan of the page with the given pageId .
return extractBoolean(this.callMethod(FacebookMethod.PAGES_IS_FAN,
new Pair<String,CharSequence>("page_id", pageId.toString())));
| public boolean | photos_addTag(java.lang.Long photoId, java.lang.Long taggedUserId, java.lang.Double xPct, java.lang.Double yPct)Adds a tag to a photo.
return photos_addTag(photoId, xPct, yPct, taggedUserId, null);
| public boolean | photos_addTag(java.lang.Long photoId, java.lang.CharSequence tagText, java.lang.Double xPct, java.lang.Double yPct)Adds a tag to a photo.
return photos_addTag(photoId, xPct, yPct, null, tagText);
| private boolean | photos_addTag(java.lang.Long photoId, java.lang.Double xPct, java.lang.Double yPct, java.lang.Long taggedUserId, java.lang.CharSequence tagText)
assert (null != photoId && !photoId.equals(0));
assert (null != taggedUserId || null != tagText);
assert (null != xPct && xPct >= 0 && xPct <= 100);
assert (null != yPct && yPct >= 0 && yPct <= 100);
Document d =
this.callMethod(FacebookMethod.PHOTOS_ADD_TAG, new Pair<String, CharSequence>("pid",
photoId.toString()),
new Pair<String, CharSequence>("tag_uid", taggedUserId.toString()),
new Pair<String, CharSequence>("x", xPct.toString()),
new Pair<String, CharSequence>("y", yPct.toString()));
return extractBoolean(d);
| public org.w3c.dom.Document | photos_addTags(java.lang.Long photoId, java.util.Collection tags)Adds several tags to a photo.
assert (photoId > 0);
assert (null != tags && !tags.isEmpty());
String tagStr = null;
try {
JSONArray jsonTags=new JSONArray();
for (PhotoTag tag : tags) {
jsonTags.put(tag.jsonify());
}
tagStr = jsonTags.toString();
}
catch (Exception ignored) {}
return this.callMethod(FacebookMethod.PHOTOS_ADD_TAG,
new Pair<String, CharSequence>("pid", photoId.toString()),
new Pair<String, CharSequence>("tags", tagStr));
| public org.w3c.dom.Document | photos_createAlbum(java.lang.String albumName)Creates an album.
return this.photos_createAlbum(albumName, null/*description*/, null/*location*/);
| public org.w3c.dom.Document | photos_createAlbum(java.lang.String name, java.lang.String description, java.lang.String location)Creates an album.
assert (null != name && !"".equals(name));
ArrayList<Pair<String, CharSequence>> params =
new ArrayList<Pair<String, CharSequence>>(FacebookMethod.PHOTOS_CREATE_ALBUM.numParams());
params.add(new Pair<String, CharSequence>("name", name));
if (null != description)
params.add(new Pair<String, CharSequence>("description", description));
if (null != location)
params.add(new Pair<String, CharSequence>("location", location));
return this.callMethod(FacebookMethod.PHOTOS_CREATE_ALBUM, params);
| public org.w3c.dom.Document | photos_get(java.lang.Long subjId, java.lang.Long albumId, java.util.Collection photoIds)Used to retrieve photo objects using the search parameters (one or more of the
parameters must be provided).
ArrayList<Pair<String, CharSequence>> params =
new ArrayList<Pair<String, CharSequence>>(FacebookMethod.PHOTOS_GET.numParams());
boolean hasUserId = null != subjId && 0 != subjId;
boolean hasAlbumId = null != albumId && 0 != albumId;
boolean hasPhotoIds = null != photoIds && !photoIds.isEmpty();
assert (hasUserId || hasAlbumId || hasPhotoIds);
if (hasUserId)
params.add(new Pair<String, CharSequence>("subj_id", Long.toString(subjId)));
if (hasAlbumId)
params.add(new Pair<String, CharSequence>("aid", Long.toString(albumId)));
if (hasPhotoIds)
params.add(new Pair<String, CharSequence>("pids", delimit(photoIds)));
return this.callMethod(FacebookMethod.PHOTOS_GET, params);
| public org.w3c.dom.Document | photos_get(java.lang.Long albumId, java.util.Collection photoIds, boolean album)
return photos_get(null/*subjId*/, albumId, photoIds);
| public org.w3c.dom.Document | photos_get(java.lang.Long subjId, java.util.Collection photoIds)
return photos_get(subjId, null/*albumId*/, photoIds);
| public org.w3c.dom.Document | photos_get(java.lang.Long subjId, java.lang.Long albumId)
return photos_get(subjId, albumId, null/*photoIds*/);
| public org.w3c.dom.Document | photos_get(java.util.Collection photoIds)
return photos_get(null/*subjId*/, null/*albumId*/, photoIds);
| public org.w3c.dom.Document | photos_get(java.lang.Long albumId, boolean album)
return photos_get(null/*subjId*/, albumId, null/*photoIds*/);
| public org.w3c.dom.Document | photos_get(java.lang.Long subjId)
return photos_get(subjId, null/*albumId*/, null/*photoIds*/);
| public org.w3c.dom.Document | photos_getAlbums(java.lang.Long userId, java.util.Collection albumIds)Retrieves album metadata. Pass a user id and/or a list of album ids to specify the albums
to be retrieved (at least one must be provided)
boolean hasUserId = null != userId && userId != 0;
boolean hasAlbumIds = null != albumIds && !albumIds.isEmpty();
assert (hasUserId || hasAlbumIds); // one of the two must be provided
if (hasUserId)
return (hasAlbumIds) ?
this.callMethod(FacebookMethod.PHOTOS_GET_ALBUMS, new Pair<String, CharSequence>("uid",
Long.toString(userId)),
new Pair<String, CharSequence>("aids", delimit(albumIds))) :
this.callMethod(FacebookMethod.PHOTOS_GET_ALBUMS,
new Pair<String, CharSequence>("uid", Long.toString(userId)));
else
return this.callMethod(FacebookMethod.PHOTOS_GET_ALBUMS,
new Pair<String, CharSequence>("aids", delimit(albumIds)));
| public org.w3c.dom.Document | photos_getAlbums(java.lang.Long userId)
return photos_getAlbums(userId, null /*albumIds*/);
| public org.w3c.dom.Document | photos_getAlbums(java.util.Collection albumIds)
return photos_getAlbums(null /*userId*/, albumIds);
| public org.w3c.dom.Document | photos_getByAlbum(java.lang.Long albumId, java.util.Collection photoIds)Used to retrieve photo objects using the search parameters (one or more of the
parameters must be provided).
return photos_get(null /*subjId*/, albumId, photoIds);
| public org.w3c.dom.Document | photos_getByAlbum(java.lang.Long albumId)Used to retrieve photo objects using the search parameters (one or more of the
parameters must be provided).
return photos_get(null /*subjId*/, albumId, null /*photoIds*/);
| public org.w3c.dom.Document | photos_getTags(java.util.Collection photoIds)Retrieves the tags for the given set of photos.
return this.callMethod(FacebookMethod.PHOTOS_GET_TAGS,
new Pair<String, CharSequence>("pids", delimit(photoIds)));
| public org.w3c.dom.Document | photos_upload(java.io.File photo)
return /* caption */ /* albumId */photos_upload(photo, null, null);
| public org.w3c.dom.Document | photos_upload(java.io.File photo, java.lang.String caption)
return /* albumId */photos_upload(photo, caption, null);
| public org.w3c.dom.Document | photos_upload(java.io.File photo, java.lang.Long albumId)
return /* caption */photos_upload(photo, null, albumId);
| public org.w3c.dom.Document | photos_upload(java.io.File photo, java.lang.String caption, java.lang.Long albumId)
ArrayList<Pair<String, CharSequence>> params =
new ArrayList<Pair<String, CharSequence>>(FacebookMethod.PHOTOS_UPLOAD.numParams());
assert (photo.exists() && photo.canRead());
this._uploadFile = photo;
if (null != albumId)
params.add(new Pair<String, CharSequence>("aid", Long.toString(albumId)));
if (null != caption)
params.add(new Pair<String, CharSequence>("caption", caption));
return callMethod(FacebookMethod.PHOTOS_UPLOAD, params);
| public java.io.InputStream | postFileRequest(java.lang.String methodName, java.util.Map params)
assert (null != _uploadFile);
try {
BufferedInputStream bufin = new BufferedInputStream(new FileInputStream(_uploadFile));
String boundary = Long.toString(System.currentTimeMillis(), 16);
URLConnection con = SERVER_URL.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
con.setRequestProperty("MIME-version", "1.0");
DataOutputStream out = new DataOutputStream(con.getOutputStream());
for (Map.Entry<String, CharSequence> entry: params.entrySet()) {
out.writeBytes(PREF + boundary + CRLF);
out.writeBytes("Content-disposition: form-data; name=\"" + entry.getKey() + "\"");
out.writeBytes(CRLF + CRLF);
out.writeBytes(entry.getValue().toString());
out.writeBytes(CRLF);
}
out.writeBytes(PREF + boundary + CRLF);
out.writeBytes("Content-disposition: form-data; filename=\"" + _uploadFile.getName() + "\"" +
CRLF);
out.writeBytes("Content-Type: image/jpeg" + CRLF);
// out.writeBytes("Content-Transfer-Encoding: binary" + CRLF); // not necessary
// Write the file
out.writeBytes(CRLF);
byte b[] = new byte[UPLOAD_BUFFER_SIZE];
int byteCounter = 0;
int i;
while (-1 != (i = bufin.read(b))) {
byteCounter += i;
out.write(b, 0, i);
}
out.writeBytes(CRLF + PREF + boundary + PREF + CRLF);
out.flush();
out.close();
InputStream is = con.getInputStream();
return is;
}
catch (Exception e) {
System.err.println("caught exception: " + e);
e.printStackTrace();
return null;
}
| private java.io.InputStream | postRequest(java.lang.CharSequence method, java.util.Map params, boolean doHttps, boolean doEncode)
CharSequence buffer = (null == params) ? "" : delimit(params.entrySet(), "&", "=", doEncode);
URL serverUrl = (doHttps) ? HTTPS_SERVER_URL : _serverUrl;
if (isDebug() && DEBUG) {
System.out.println(method);
System.out.println(" POST: ");
System.out.println(serverUrl.toString());
System.out.println("/");
System.out.println(buffer);
}
HttpURLConnection conn = (HttpURLConnection) serverUrl.openConnection();
try {
conn.setRequestMethod("POST");
}
catch (ProtocolException ex) {
System.err.println("huh?");
ex.printStackTrace();
}
conn.setDoOutput(true);
conn.connect();
conn.getOutputStream().write(buffer.toString().getBytes());
return conn.getInputStream();
| public static void | printDom(org.w3c.dom.Node n, java.lang.String prefix)Prints out the DOM tree.
String outString = prefix;
if (n.getNodeType() == Node.TEXT_NODE) {
outString += "'" + n.getTextContent().trim() + "'";
}
else {
outString += n.getNodeName();
}
if (DEBUG) {
System.out.println(outString);
}
NodeList children = n.getChildNodes();
int length = children.getLength();
for (int i = 0; i < length; i++) {
FacebookRestClient.printDom(children.item(i), prefix + " ");
}
| public org.w3c.dom.Document | profile_getFBML(java.lang.Long userId)Gets the FBML for a user's profile, including the content for both the profile box
and the profile actions.
return this.callMethod(FacebookMethod.PROFILE_GET_FBML,
new Pair<String, CharSequence>("uid", Long.toString(userId)));
| public boolean | profile_setFBML(java.lang.CharSequence fbmlMarkup, java.lang.Long userId)Sets the FBML for a user's profile, including the content for both the profile box
and the profile actions.
return extractBoolean(this.callMethod(FacebookMethod.PROFILE_SET_FBML,
new Pair<String, CharSequence>("uid", Long.toString(userId)),
new Pair<String, CharSequence>("markup", fbmlMarkup)));
| private java.lang.String | reconstructValue(java.lang.String input)
if ((input == null) || ("".equals(input))) {
return null;
}
if (input.charAt(0) == '_") {
return input.substring(1);
}
return input;
| public void | setDebug(boolean isDebug)Set debugging on for this instance only.
_debug = isDebug;
| public static void | setDebugAll(boolean isDebug)Set global debugging on.
FacebookRestClient.DEBUG = isDebug;
| public void | setIsDesktop(boolean isDesktop)Enable/disable desktop mode.
this._isDesktop = isDesktop;
| public boolean | sms_canSend()Check to see if the application is permitted to send SMS messages to the current application user.
return sms_canSend(this.users_getLoggedInUser());
| public boolean | sms_canSend(java.lang.Long userId)Check to see if the application is permitted to send SMS messages to the specified user.
this.callMethod(FacebookMethod.SMS_CAN_SEND, new Pair<String, CharSequence>("uid", userId.toString()));
return this.rawResponse.contains(">0<"); //a status code of "0" indicates that the app can send messages
| public java.lang.Integer | sms_send(java.lang.String message, java.lang.Integer smsSessionId, boolean makeNewSession)Send an SMS message to the current application user.
return sms_send(this.users_getLoggedInUser(), message, smsSessionId, makeNewSession);
| public java.lang.Integer | sms_send(java.lang.Long userId, java.lang.String message, java.lang.Integer smsSessionId, boolean makeNewSession)Send an SMS message to the specified user.
Collection<Pair<String, CharSequence>> params = new ArrayList<Pair<String, CharSequence>>();
params.add(new Pair<String, CharSequence>("uid", userId.toString()));
params.add(new Pair<String, CharSequence>("message", message));
if (smsSessionId != null) {
params.add(new Pair<String, CharSequence>("session_id", smsSessionId.toString()));
}
if (makeNewSession) {
params.add(new Pair<String, CharSequence>("req_session", "true"));
}
this.callMethod(FacebookMethod.SMS_SEND, params);
//XXX: needs testing to make sure it's correct (Facebook always gives me a code 270 permissions error no matter what I do)
Integer response = null;
if ((this.rawResponse.indexOf("</sms") != -1) && (makeNewSession)) {
String result = this.rawResponse.substring(0, this.rawResponse.indexOf("</sms"));
result = result.substring(result.lastIndexOf(">") + 1);
response = Integer.parseInt(result);
}
return response;
| public void | sms_sendMessage(java.lang.Long userId, java.lang.CharSequence message)Sends a message via SMS to the user identified by userId .
The SMS extended permission is required for success.
this.callMethod(FacebookMethod.SMS_SEND_MESSAGE,
new Pair<String, CharSequence>("uid", userId.toString()),
new Pair<String, CharSequence>("message", message),
new Pair<String, CharSequence>("req_session", "0"));
| public int | sms_sendMessageWithSession(java.lang.Long userId, java.lang.CharSequence message)Sends a message via SMS to the user identified by userId , with
the expectation that the user will reply. The SMS extended permission is required for success.
The returned mobile session ID can be stored and used in {@link #sms_sendResponse} when
the user replies.
return extractInt(this.callMethod(FacebookMethod.SMS_SEND_MESSAGE,
new Pair<String, CharSequence>("uid", userId.toString()),
new Pair<String, CharSequence>("message", message),
new Pair<String, CharSequence>("req_session", "1")));
| public void | sms_sendResponse(java.lang.Integer userId, java.lang.CharSequence response, java.lang.Integer mobileSessionId)Sends a message via SMS to the user identified by userId in response
to a user query associated with mobileSessionId .
this.callMethod(FacebookMethod.SMS_SEND_MESSAGE,
new Pair<String, CharSequence>("uid", userId.toString()),
new Pair<String, CharSequence>("message", response),
new Pair<String, CharSequence>("session_id", mobileSessionId.toString()));
| private java.lang.String | stringify(java.util.List input)
if ((input == null) || (input.isEmpty())) {
return null;
}
String result = "";
for (Object elem : input) {
if (! "".equals(result)) {
result += ",";
}
result += elem.toString();
}
return result;
| private static void | stripEmptyTextNodes(org.w3c.dom.Node n)Hack...since DOM reads newlines as textnodes we want to strip out those
nodes to make it easier to use the tree.
NodeList children = n.getChildNodes();
int length = children.getLength();
for (int i = 0; i < length; i++) {
Node c = children.item(i);
if (!c.hasChildNodes() && c.getNodeType() == Node.TEXT_NODE &&
c.getTextContent().trim().length() == 0) {
n.removeChild(c);
i--;
length--;
children = n.getChildNodes();
}
else {
stripEmptyTextNodes(c);
}
}
| protected boolean | templatizedFeedHandler(com.facebook.api.FacebookMethod method, java.lang.String titleTemplate, java.lang.String titleData, java.lang.String bodyTemplate, java.lang.String bodyData, java.lang.String bodyGeneral, java.util.Collection pictures, java.lang.String targetIds)
assert (pictures == null || pictures.size() <= 4);
long actorId = this.users_getLoggedInUser();
ArrayList<Pair<String, CharSequence>> params = new ArrayList<Pair<String, CharSequence>>(method.numParams());
//these are always required parameters
params.add(new Pair<String, CharSequence>("actor_id", Long.toString(actorId)));
params.add(new Pair<String, CharSequence>("title_template", titleTemplate));
//these are optional parameters
if (titleData != null) {
params.add(new Pair<String, CharSequence>("title_data", titleData));
}
if (bodyTemplate != null) {
params.add(new Pair<String, CharSequence>("body_template", bodyTemplate));
if (bodyData != null) {
params.add(new Pair<String, CharSequence>("body_data", bodyData));
}
}
if (bodyGeneral != null) {
params.add(new Pair<String, CharSequence>("body_general", bodyGeneral));
}
if (pictures != null) {
int count = 1;
for (IPair picture : pictures) {
params.add(new Pair<String, CharSequence>("image_" + count, picture.getFirst().toString()));
if (picture.getSecond() != null) {
params.add(new Pair<String, CharSequence>("image_" + count + "_link", picture.getSecond().toString()));
}
count++;
}
}
if (targetIds != null) {
params.add(new Pair<String, CharSequence>("target_ids", targetIds));
}
this.callMethod(method, params);
return this.rawResponse.contains(">1<"); //a code of '1' indicates success
| public boolean | users_clearStatus()Clears the logged-in user's Facebook status.
Requires the status_update extended permission.
return this.users_setStatus(null, true);
| public org.w3c.dom.Document | users_getInfo(java.util.Collection userIds, java.util.EnumSet fields)Retrieves the requested info fields for the requested set of users.
// assertions test for invalid params
assert (userIds != null);
assert (fields != null);
assert (!fields.isEmpty());
return this.callMethod(FacebookMethod.USERS_GET_INFO,
new Pair<String, CharSequence>("uids", delimit(userIds)),
new Pair<String, CharSequence>("fields", delimit(fields)));
| public org.w3c.dom.Document | users_getInfo(java.util.Collection userIds, java.util.Set fields)Retrieves the requested info fields for the requested set of users.
// assertions test for invalid params
assert (userIds != null);
assert (fields != null);
assert (!fields.isEmpty());
return this.callMethod(FacebookMethod.USERS_GET_INFO,
new Pair<String, CharSequence>("uids", delimit(userIds)),
new Pair<String, CharSequence>("fields", delimit(fields)));
| public long | users_getLoggedInUser()Retrieves the user ID of the user logged in to this API session
Document d = this.callMethod(FacebookMethod.USERS_GET_LOGGED_IN_USER);
return Long.parseLong(d.getFirstChild().getTextContent());
| public boolean | users_hasAppPermission(java.lang.CharSequence permission)
this.callMethod(FacebookMethod.USERS_HAS_PERMISSION, new Pair<String, CharSequence>("ext_perm", permission));
return this.rawResponse.contains(">1<"); //a code of '1' is sent back to indicate that the user has the request permission
| public boolean | users_hasAppPermission(com.facebook.api.Permission perm)Check to see if the user has granted the app a specific external permission. In order to be granted a
permission, an application must direct the user to a URL of the form:
http://www.facebook.com/authorize.php?api_key=[YOUR_API_KEY]&v=1.0&ext_perm=[PERMISSION NAME]
this.callMethod(FacebookMethod.USERS_HAS_PERMISSION, new Pair<String, CharSequence>("ext_perm", perm.getName()));
return this.rawResponse.contains(">1<"); //a code of '1' is sent back to indicate that the user has the request permission
| public boolean | users_isAppAdded()Retrieves an indicator of whether the logged-in user has installed the
application associated with the _apiKey.
return extractBoolean(this.callMethod(FacebookMethod.USERS_IS_APP_ADDED));
| public boolean | users_setStatus(java.lang.String status)
return this.users_setStatus(status, false);
| public boolean | users_setStatus(java.lang.String newStatus, boolean clear)Set the user's profile status message. This requires that the user has granted the application the
'status_update' permission, otherwise the call will return an error. You can use 'users_hasAppPermission'
to check to see if the user has granted your app the abbility to update their status.
Collection<Pair<String, CharSequence>> params = new ArrayList<Pair<String, CharSequence>>();
if (newStatus != null) {
params.add(new Pair<String, CharSequence>("status", newStatus));
}
if (clear) {
params.add(new Pair<String, CharSequence>("clear", "true"));
}
this.callMethod(FacebookMethod.USERS_SET_STATUS, params);
return this.rawResponse.contains(">1<"); //a code of '1' is sent back to indicate that the request was successful, any other response indicates error
|
|