Call facebook graphrequest multiple times - facebook

i'm developpig an app in which i need to call the fb graphrequest multiple times , but those calls needs to be one after the other, the first one will get me the user friends, and the other calls will be done in a loop (for each friend ) get the "likes" that that friend made, now with the code that i made, the first one gives me the friends but the second one (the loop instruction) won't work, i guess it has somehing to do with the async calls but i don't know how to make them serial calls, here's my code :
GraphRequest request = GraphRequest.newMyFriendsRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONArrayCallback() {
#Override
public void onCompleted(JSONArray array, GraphResponse response) {
JSONObject jsonArray = response.getJSONObject();
try {
length = jsonArray.getJSONArray("data").length();
for (int i = 0; i < length; i++) {
AlertDialog a = new AlertDialog.Builder(liste_peronalisee.this).create();
a.setTitle("Erreur");
id[i] = jsonArray.getJSONArray("data").getJSONObject(i).getString("id");
a.setMessage(id[i]);
a.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
request.executeAsync();
for(int i=0;i<id.length;i++)
request = GraphRequest.newGraphPathRequest(
AccessToken.getCurrentAccessToken(),
"/".concat(id[i]).concat("/likes"),
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
JSONObject jsonArray = response.getJSONObject();
try {
length = jsonArray.getJSONArray("data").length();
for (int i = 0; i < length; i++) {
AlertDialog a = new AlertDialog.Builder(liste_peronalisee.this).create();
a.setTitle("Erreur");
id[i] = jsonArray.getJSONArray("data").getJSONObject(i).getString("name");
a.setMessage(id[i]);
a.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
request.executeAsync();
i need a quick answer, thanks in advance

Related

Streaming REST API

We are currently using SpringBoot to implement REST services where the response is sent in the form of JSON. I am exploring the ways to "stream" the response.
Could somebody please suggest different ways/approaches to stream the response.
Regards,
Rohit
Below is the code snippet to stream data from a rest endpoint.
#RequestMapping(value = "/streams", method = RequestMethod.GET)
public StreamingResponseBody getStreamingResponse () {
return new StreamingResponseBody() {
#Override
public void writeTo (OutputStream out) throws IOException {
for (int i = 0; i < 1000; i++) {
out.write((Integer.toString(i) + " - ")
.getBytes());
out.flush();
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
}

Spring MVC bulk message using MimeMessagePreparator

I'm trying to send bulk emails using Spring MVC. Here is my code:
if(customerClients != null){
int count = 0;
boolean sent = false;
List<MimeMessagePreparator> preparators = new ArrayList<MimeMessagePreparator>();
for (BulkEmail client : customerClients) {
if(customerID==-1)
customerID = client.getCustomerID();
CustomerAccount customerAccount = service.getCustomerAccount(client.getCustomerID());
if (instantMessage.isEmailChecked() && customerAccount.getBalance()>0) {
try{
final String receiverID = client.getEmail();
instantMessage.setIpersonOrGroupValue(receiverID);
preparators.add(new MimeMessagePreparator()
{
public void prepare(MimeMessage mimeMessage) throws Exception
{
final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
message.setSubject(instantMessage.getSubject());
message.setTo(receiverID);
message.setFrom(from);
message.setText(instantMessage.getMessage(), true);
}
});
sent = false;
}
catch(Exception ex){
ex.printStackTrace();
}
}
++count;
if(count%100==0){
springMail.send(preparators);
preparators = new ArrayList<MimeMessagePreparator>();
sent = true;
}
}
if(!sent)
springMail.send(preparators);
Here is the code that uses JavaMailSender for sending the preparators:
public void send(List<MimeMessagePreparator> preparatorsList) {
MimeMessagePreparator[] preparators = preparatorsList.toArray(new MimeMessagePreparator[preparatorsList.size()]);
mailSender.send(preparators);
}
The problem with this code is it takes around 1 second per email address. This means 300 emails in 5 minutes.
I want to know if this is normal or there is something I can do to improve.
Thanks

I get the following error: "message": "Malformed access token

I have an app in facebook and I am trying to obtain long term token,
for that I call the following link:
https://graph.facebook.com/oauth/authorize?client_id=xxxxxx&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Faccesstokforfacebook%2Ffbaccess&scope=read_stream,read_insights,user_religion_politics,user_relationship_details,user_hometown,user_location,user_likes,user_activities,user_interests,user_education_history,user_work_history,user_website,user_groups,user_events,user_photos,user_videos,user_about_me,user_status,user_games_activity,user_tagged_places,user_actions.books,user_actions.video,user_actions.news
and the return url is a servlet with following codes:
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String accessCode = request.getParameter("code");
System.out.println("dddd "+accessCode);
//print SUCCESS if code is found
/*if (accessCode!=null){*/
out.print("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\"http://www.w3.org/TR/html4/strict.dtd\"><html><head><title>Facebook Access Granted</title></head><body>");
out.print("<p>SUCCESS!</p><p>"+accessCode+"</p></body></html>");
and this servlet receives the very long code like this:
AQCY244eMOhxEVu3e6UEIl-qK974wTh-p0Il1ZdG9VEAYl5GdrjxxxxxxxxxxxxxxxxxxxxxxxxxxxxxQcJeUmeXFU56cbWbmXJdLQvEyIT7JWCxxu6tChkr9oCL1DVYxxv4v-j4Y_vaWGD7dYcxxxxxxxxxxxxxxxxxxTvZPHLU-tU5ySHrQrVgpo_i8minM73cyWxxxxxxxxxxxxxxdZvnrIhQXQ-B_3LAFzDcWe2NbCW7WSgmQ-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxMkJ55M0wHHbLmL4D-g_wLIwhpz4W_8Hz0h7v_ZL
Now when I use this token to get the all info for a page I get an error:
this is a link that I use:
https://graph.facebook.com/v2.0/khalatbari.hooman/feed?access_token=THE ABOVE CODE
and the error is:
Now I think the code that I get is not access token but I have no idea how to use this code to get access token!!!
can anyone help
Finally found solution for Facebook SDK 4.6.0 to getting limited comment's list for feed :
1> Calling commentInfo() firstly Inside Activity's oncreate()
:
private boolean isLoadMoreCalled;
commentInfo("", "true");
2> Putting load more method also there like:
listViewCommentList.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
Log.d("scrollState", ""+scrollState);
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int last_visible_in_screen = firstVisibleItem + visibleItemCount;
if(last_visible_in_screen == totalItemCount && isLoadMoreCalled) {
Toast.makeText(getApplicationContext(), "Loading more Items 10", Toast.LENGTH_SHORT).show();
commentInfo(nextFeedUrl, "false");
isLoadMoreCalled = false;
}
}
});
3> create commentInfo() of outside onCreate() :
public void commentInfo (String fields, final String isFirst) {
/** Festival Feed Comments Details #Facebook */
Bundle params = new Bundle();
params.putString("fields", "message,created_time,from");
params.putString("limit", "10");
if(isFirst.equals("false")) {
params.putString("after", fields);
}
showProgressBar();
/* make the API call */
//refreshCurrentAccessTokenAsync();
System.out.println("Acees Token Comment>>>"+ AccessToken.getCurrentAccessToken());
new GraphRequest(AccessToken.getCurrentAccessToken(), "/"+ feedId +"/comments", params, HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
System.out.println("Festival feed Comments response::" + String.valueOf(response.getJSONObject()));
try {
JSONObject jObjResponse = new JSONObject(String.valueOf(response.getJSONObject()));
JSONObject jObjPaging = jObjResponse.getJSONObject("paging");
JSONObject jObjCursor = jObjPaging.getJSONObject("cursors");
nextFeedUrl = "";
nextFeedUrl = jObjCursor.getString("after");
System.out.println("nextFeedUrl>>"+ nextFeedUrl);
JSONArray jArrayData = jObjResponse.getJSONArray("data");
for(int i = 0; i< jArrayData.length(); i++) {
Getting comments info & store into Data-Structure(Array-List)
}
if(isFirst.equals("true")) {
fbFeedCommentAdapter = new FbFeedCommentAdapter();
listViewCommentList.setAdapter(fbFeedCommentAdapter);
}
else {
fbFeedCommentAdapter.notifyDataSetChanged();
}
if(!jObjPaging.has("next")) {
isLoadMoreCalled = false;
}
else {
isLoadMoreCalled = true;
}
dismissProgressBar();
}
catch (Exception e) {
e.printStackTrace();
dismissProgressBar();
}
}
}
).executeAsync();
}
Here,
fbFeedCommentAdapter -> BaseAdapter
listViewCommentList -> Listview
Also refer How to use the Facebook Graph Api Cursor-based Pagination

GWT-RPC method returns empty list on success

I am creating a webpage having CellTable.I need to feed this table with data from hbase table.
I have written a method to retrieve data from hbase table and tested it.
But when I call that method as GWT asynchronous RPC method then rpc call succeeds but it returns nothing.In my case it returns empty list.The alert box show list's size as 0.
Following is the related code.
Please help.
greetingService.getDeviceIDData(new AsyncCallback<List<DeviceDriverBean>>(){
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
System.out.println("RPC Call failed");
Window.alert("Data : RPC call failed");
}
public void onSuccess(List<DeviceDriverBean> result) {
//on success do something
Window.alert("Data : RPC call successful");
//deviceDataList.addAll(result);
Window.alert("Result size: " +result.size());
// Add a text column to show the driver name.
TextColumn<DeviceDriverBean> nameColumn = new TextColumn<DeviceDriverBean>() {
#Override
public String getValue(DeviceDriverBean object) {
Window.alert(object.getName());
return object.getName();
}
};
table.addColumn(nameColumn, "Name");
// Add a text column to show the device id
TextColumn<DeviceDriverBean> deviceidColumn = new TextColumn<DeviceDriverBean>() {
#Override
public String getValue(DeviceDriverBean object) {
return object.getDeviceId();
}
};
table.addColumn(deviceidColumn, "Device ID");
table.setRowCount(result.size(), true);
// more code here to add columns in celltable
// Push the data into the widget.
table.setRowData(0, result);
SimplePager pager = new SimplePager();
pager.setDisplay(table);
VerticalPanel vp = new VerticalPanel();
vp.add(table);
vp.add(pager);
// Add it to the root panel.
RootPanel.get("datagridContainer").add(vp);
}
});
Code to retrieve data from hbase (server side code)
public List<DeviceDriverBean> getDeviceIDData()
throws IllegalArgumentException {
List<DeviceDriverBean> deviceidList = new ArrayList<DeviceDriverBean>();
// Escape data from the client to avoid cross-site script
// vulnerabilities.
/*
* input = escapeHtml(input); userAgent = escapeHtml(userAgent);
*
* return "Hello, " + input + "!<br><br>I am running " + serverInfo +
* ".<br><br>It looks like you are using:<br>" + userAgent;
*/
try {
Configuration config = HbaseConnectionSingleton.getInstance()
.HbaseConnect();
HTable testTable = new HTable(config, "driver_details");
byte[] family = Bytes.toBytes("details");
Scan scan = new Scan();
int cnt = 0;
ResultScanner rs = testTable.getScanner(scan);
for (Result r = rs.next(); r != null; r = rs.next()) {
DeviceDriverBean deviceDriverBean = new DeviceDriverBean();
byte[] rowid = r.getRow(); // Category, Date, Sentiment
NavigableMap<byte[], byte[]> map = r.getFamilyMap(family);
Iterator<Entry<byte[], byte[]>> itrt = map.entrySet()
.iterator();
deviceDriverBean.setDeviceId(Bytes.toString(rowid));
while (itrt.hasNext()) {
Entry<byte[], byte[]> entry = itrt.next();
//cnt++;
//System.out.println("Count : " + cnt);
byte[] qual = entry.getKey();
byte[] val = entry.getValue();
if (Bytes.toString(qual).equalsIgnoreCase("account_number")) {
deviceDriverBean.setAccountNo(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("make")) {
deviceDriverBean.setMake(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("model")) {
deviceDriverBean.setModel(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("driver_name")) {
deviceDriverBean.setName(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("premium")) {
deviceDriverBean.setPremium(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("year")) {
deviceDriverBean.setYear(Bytes.toString(val));
} else {
System.out.println("No match found");
}
/*
* System.out.println(Bytes.toString(rowid) + " " +
* Bytes.toString(qual) + " " + Bytes.toString(val));
*/
}
deviceidList.add(deviceDriverBean);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// System.out.println("Message: "+e.getMessage());
e.printStackTrace();
}
return deviceidList;
}
Could this be lazy fetching on the server side by hbase. This means if you return the list hbase won't get a trigger to actually read the list and you will simple get an empty list. I don't know a correct solution, in the past I've seen a similar problem on GAE. This could by solved by simply asking the size of the list just before returning it to the client.
I don't have the exact answer, but I have an advise. In similar situation I put my own trace to check every step in my program.
On the server side before return put : System.out.println("size of table="+deviceidList.size());
You can put this trace in the loop for deviceidList;

How I count all the number of records in a RecordStore

I have a LWUIT app that should display the number of records in a LWUIT list.
To get all the records I use a method called getRecordData() that returns all records as a String array, it works fine.
But how do I count the number of these records?
import java.util.*;
import com.sun.lwuit.events.*;
import javax.microedition.midlet.*;
import com.sun.lwuit.*;
import com.sun.lwuit.plaf.*;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms .*;
public class number_of_records extends MIDlet {
private RecordStore recordStore;
// Refresh2( ) method for getting the time now
public String Refresh2()
{
java.util.Calendar calendar = java.util.Calendar.getInstance();
Date myDate = new Date();
calendar.setTime(myDate);
StringBuffer time = new StringBuffer();
time.append(calendar.get(java.util.Calendar.HOUR_OF_DAY)).append(':');
time.append(calendar.get(java.util.Calendar.MINUTE)) ;
// time.append(calendar.get(java.util.Calendar.SECOND));
String tt = time.toString();
return tt;
}
// return all records of recordStore RecordStore
public String [] getRecordData( )
{
String[] str = null;
int counter = 0;
try
{
RecordEnumeration enumeration = recordStore.enumerateRecords(null, null, false);
str = new String[recordStore.getNumRecords()];
while(enumeration.hasNextElement())
{
try
{
str[counter] = (new String(enumeration.nextRecord()));
counter ++;
}
catch(javax.microedition.rms.RecordStoreException e)
{
}
}
}
catch(javax.microedition.rms.RecordStoreNotOpenException e)
{
}
catch(java.lang.NullPointerException n)
{
}
return str;
}
public void startApp()
{
com.sun.lwuit.Display.init(this);
final Button addition = new Button("add a goal");
final com.sun.lwuit.TextField tf = new com.sun.lwuit.TextField();
final com.sun.lwuit.List mylist = new com.sun.lwuit.List();
final Button All = new Button("All Goals");
final com.sun.lwuit.Form ff = new com.sun.lwuit.Form();
final com.sun.lwuit.Form g = new com.sun.lwuit.Form();
ff.getStyle().setBgColor(0X99CCFF);
All.getStyle().setBgColor(0X0066CC);
Style g_style5 = g.getSelectedStyle() ;
g.addComponent(tf);
g.addComponent(addition);
addition.getStyle().setBgColor(0X0066CC);
g.addComponent(All);
g.getStyle().setBgColor(0X99CCFF);
addition.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//
String s =tf.getText();
if( s!=null && s.length() > 0)
{
try
{
// Store the time in the String k
String k = Refresh2();
// The record and the time stored in KK String
String kk =tf.getText()+"-"+k;
// Add an item (the kk String) to mylist List.
mylist.addItem(kk);
byte bytestream[] = kk.getBytes() ;
// Add a record to recordStore.
int i = recordStore.addRecord(bytestream, 0, bytestream.length);
}
catch(Exception ex) { }
// Inform the User that he added the a record.
Dialog validDialog = new Dialog(" ");
Style Dialogstyle = validDialog.getSelectedStyle() ;
validDialog.setScrollable(false);
validDialog.getDialogStyle().setBgColor(0x0066CC);
validDialog.setTimeout(1000); // set timeout milliseconds
TextArea textArea = new TextArea("...."); //pass the alert text here
textArea.setFocusable(false);
textArea.setText("A goal has been added"+"" );
validDialog.addComponent(textArea);
validDialog.show(0, 10, 10, 10, true);
}
// Information to user that he/she didn’t add a record
else if((s==null || s.length()<= 0))
{
Dialog validDialo = new Dialog(" ");
validDialo.setScrollable(false);
validDialo.getDialogStyle().setBgColor(0x0066CC);
validDialo.setTimeout(5000); // set timeout milliseconds
TextArea textArea = new TextArea("...."); //pass the alert text here
textArea.setFocusable(false);
textArea.setText("please enter scorer name or number");
validDialo.addComponent(textArea);
validDialo.show(50, 50, 50, 50, true);
}
}
});
/*Action here for displaying all records of recordStore RecordStore in a new form */
All.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try
{
recordStore = RecordStore.openRecordStore("My Record Store", true);
}
catch(Exception ex) {}
try
{
com.sun.lwuit.Label l = new com.sun.lwuit.Label(" Team Goals") ;
ff.addComponent(l);
// Store the records of recordStore in string array
String [] record= getRecordData();
int j1;
String valueToBeInserted2="";
int k=getRecordData().length;
for( j1=0;j1< getRecordData().length;j1++)
{
valueToBeInserted2=valueToBeInserted2 + " " + record[j1];
if(j1==getRecordData().length)
{
mylist.addItem(record[j1]);
int m = getRecordData().length;
// Counting the number of records
String goals =""+getRecordData().length;
/* I tried to use for…loop to count them by length of the recordStore and render it.
This list also should display the number of records on the form.
But it didn’t !!!
*/
mylist.addItem(goals);
}
}
ff.addComponent(mylist);
}
catch(java.lang.IllegalArgumentException e)
{
}
finally
{
ff.show();
}
}
}
);
g.show();
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional) {
}
}
I Wrote this code but it gives NullPointerException at recordStore.enumerateRecords (null, null,true);
So I think the problem here.
please help.
myButton.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvet av)
{
try
{
RecordEnumeration enumeration = recordStore.enumerateRecords (null, null,true);
int o =recordStore.getNumRecords () ;
}
catch(Exception e)
{
}
}
});
what you need is enumeration.numRecords(); i reckon recordStore.getNumRecords() should work also, since this is what you are using the populate the array, you could even use the length of the array itself. These options are all in the code, it would be better to explore a bit more and also check the documentation to resolve trivial problems.
you could use the length of the array or set a RecordListener to your recordstore and increase a counter when added a record to recordstore.
here is the solution of my problem , I do a for loop to get the number of
elements of the array.
the counter should be the length of array
count.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent av)
{
try
{
recordStore = RecordStore.openRecordStore("recordStore", true);
}
catch(Exception e)
{ }
try
{
RecordEnumeration enumeration = recordStore.enumerateRecords (null, null,true);
}
catch(Exception e)
{
}
String record[] = getRecordData();
int j;
j = record.length-1;
Dialog validDialog = new Dialog(" ");
Style Dialogstyle = validDialog.getSelectedStyle() ;
validDialog.setScrollable(false);
validDialog.getDialogStyle().setBgColor(0x0066CC);
validDialog.setTimeout(1000); // set timeout milliseconds
TextArea textArea = new TextArea("....");
textArea.setFocusable(false);
textArea.setText("Number Counted"+j );
validDialog.addComponent(textArea);
validDialog.show(0, 10, 10, 10, true);
}});