Getting all wall posts and comments using RestFB - java

At first: I know there were some similar topics and I wrote some code according to them (as seeing below). I'm new in Facebook api so I'm a little bit lost :D
Anyway, my app has to get all wall posts and comments but I'm not able to get it all. Could anyone help me please? Here are my methods:
public static void getFacebookPosts(String url){
try{
LoggedFacebookClient client = new LoggedFacebookClient();
Page page = client.fetchObject(url, Page.class);
System.out.println(page.getName());
Connection<Post> pageFeed = client.fetchConnection(page.getId() + "/feed", Post.class);
//Getting posts:
for (List<Post> feed : pageFeed){
for (Post post : feed){
//PRINTING THE POST
getAllPostComments(post.getId(), client);
}
}
}catch(com.restfb.exception.FacebookOAuthException ex){
System.out.println("\n!!!!!!! Token Expired !!!!!!!!\n");
}
}
private static void getAllPostComments(String postId, DefaultFacebookClient client){
int currentCount = 0;
JsonObject jsonObject = client.fetchObject(postId + "/comments", JsonObject.class,
Parameter.with("summary", true), Parameter.with("limit", 1));
long commentsTotalCount = jsonObject.getJsonObject("summary").getLong("total_count");
System.out.println("\nComments:");
boolean pom = true;
while(pom == true){ //There should be "while(currentCount < commentsTotalCount)" but currentCount is always < then commentsTotalCount. That's the problem :)
pom = false;
Connection<Comment> comments = client.fetchConnection(postId + "/comments",
Comment.class, Parameter.with("limit", 50000), Parameter.with("offset", currentCount));
for(Comment komentar : comments.getData()){
pom = true;
currentCount++;
stazenychKomentu++;
String mess = komentar.getMessage().replaceAll("\n", " ").replaceAll("\r", " ");
System.out.println(" [" + currentCount + "]: " + komentar.getFrom().getName() + " ## " + mess);
}
}
celkemKomentu += commentsTotalCount;
System.out.println(currentCount + " / " + commentsTotalCount);
}
and here is the way I get the acces token:
public LoggedFacebookClient(){
super();
AccessToken accessToken = this.obtainAppAccessToken(API_KEY, APP_SECRET);
this.accessToken = accessToken.getAccessToken();
}
I would be very grateful if anyone could help me. Thanks a lot and sorry if my English isn't perfect.

If you want to get all posts you just need to make this:
while (pageFeed.hasNext()) {
pageFeed = facebookClient.fetchConnectionPage(pageFeed.getNextPageUrl(),Post.class);
}
Parameter.with("limit", xxx) work for less then 200 posts. And don't forget about long-live access token!
GET /oauth/access_token?
grant_type=fb_exchange_token&
client_id={app-id}&
client_secret={app-secret}&
fb_exchange_token={short-lived-token}
https://developers.facebook.com/docs/facebook-login/access-tokens#pagetokens

Related

Domain Restriction in BabelNet

I am trying to restrict the results of my BabelNet query to a specific (Babel)domain. To do that, I'm trying to find out a way to compare the synsets' domains with the domain I need (Geographical). However, I'm having trouble getting the right output, since although the 2 strings match, it still gives me the wrong output. I'm surely doing something wrong here, but I'm out of ideas.
After many trials, the following code was the one that gave me the nearest result to the desired output:
public class GeoRestrict {
public static void main(String[] args) throws IOException {
String file = "/path/to/file/testdata.txt";
BabelNet bn = BabelNet.getInstance();
BufferedReader br = new BufferedReader(new FileReader(file));
String word = null;
while ((word = br.readLine()) != null) {
BabelNetQuery query = new BabelNetQuery.Builder(word)
.build();
List<BabelSynset> wordSynset = bn.getSynsets(query);
for (BabelSynset synset : wordSynset) {
BabelSynsetID id = synset.getID();
System.out.println("\n" + "Synset ID for " + word.toUpperCase() + " is: " + id);
HashMap<Domain, Double> domains = synset.getDomains();
Set<Domain> keys = domains.keySet();
String keyString = domains.keySet().toString();
List<String> categories = synset.getDomains().keySet().stream()
.map(domain -> ((BabelDomain) domain).getDomainString())
.collect(Collectors.toList());
for (String category : categories) {
if(keyString.equals(category)) {
System.out.println("The word " + word + " has the domain " + category);
} else {
System.out.println("Nada! " + category);
}
}
}
}
br.close();
}
}
The output looks like this:
Synset ID for TURIN is: bn:00077665n
Nada! Geography and places
Any ideas on how to solve this issue?
I found my own error. For the sake of completeness I'm posting it.
The BabelDomain needs to be declared and specified (before the while-loop), like this:
BabelDomain domain = BabelDomain.GEOGRAPHY_AND_PLACES;

Discord JDA EmbedMessage Profile Link

Currently I'm making a rather simple logging bot for Discord. All it does is send an EmbedMessage to any #log channel in the server.
This little bit of messy code:
#Override
public void onMessageReceived(MessageReceivedEvent e) {
Message message = e.getMessage();
User author = e.getAuthor();
MessageChannel channel = e.getChannel();
if (channel.getName().equalsIgnoreCase("log") && !author.isBot()) {
message.delete().queue();
} else {
EmbedBuilder eBuilder = new EmbedBuilder();
String aMention = "#" + author.getName() + "#" + author.getDiscriminator();
eBuilder.setAuthor(aMention, null, author.getEffectiveAvatarUrl());
eBuilder.setColor(Color.GRAY);
eBuilder.setFooter("#" + channel.getName(), null);
eBuilder.appendDescription(message.getContentDisplay());
MessageEmbed embed = eBuilder.build();
for (MessageChannel mc : e.getGuild().getTextChannels()) {
if (mc.getName().equalsIgnoreCase("log") && !author.isBot()) {
mc.sendMessage(embed).queue();
}
}
}
}
is the setup for logging non-bot chatting. Currently, it doesn't seem to setup a direct profile link to the user talking, in the line String aMention = "#" + author.getName() + "#" + author.getDiscriminator();. I tried searching for a specific method that gets a profile link, but currently I am not able to find it.
If you want to mention a member, just use:
Member yourMember = e.getMember();
String mention = yourMember.getAsMention();
// ...your code

403 : Daily Limit for Unauthenticated Use Exceeded youtube api v3 java

I Know this question has been asked multiple times, but I couldn't find one working for me.
Basically I am trying to get a youtube video basic info which I get the proper result for that but then when I trigger to get the comments of that video the error pops out saying:
There was a service error: 403 : Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.
My code:
public String getyoutubeitemfull_details(String URI) throws SQLException, IOException{
try {
YouTube youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("APP_ID").build();
String apiKey = "API Key";
YouTube.Videos.List listVideosRequest = youtube.videos().list("statistics");
listVideosRequest.setId("qUvPzjSWMSM");
listVideosRequest.setKey(apiKey);
VideoListResponse listResponse = listVideosRequest.execute();
Video video = listResponse.getItems().get(0);
BigInteger viewCount = video.getStatistics().getViewCount();
BigInteger Likes = video.getStatistics().getLikeCount();
BigInteger DisLikes = video.getStatistics().getDislikeCount();
BigInteger Comments = video.getStatistics().getCommentCount();
System.out.println("[View Count] " + viewCount);
System.out.println("[Likes] " + Likes);
System.out.println("[Dislikes] " + DisLikes);
System.out.println("[Comments] " + Comments);
CommentThreadListResponse videoCommentsListResponse = youtube.commentThreads()
.list("snippet").setVideoId("qUvPzjSWMSM").setMaxResults(50l).setTextFormat("plainText").execute();
List<CommentThread> videoComments = videoCommentsListResponse.getItems();
for (CommentThread videoComment : videoComments) {
CommentSnippet snippet = videoComment.getSnippet().getTopLevelComment().getSnippet();
System.out.println(" - Author: " + snippet.getAuthorDisplayName());
System.out.println(" - Comment: " + snippet.getTextDisplay());
System.out.println("\n-------------------------------------------------------------\n");
}
} catch (GoogleJsonResponseException e) {
System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
} catch (IOException e) {
System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
FYI: So much of question that I have been through so far talk about adding listVideosRequest.setKey(apiKey); which I have it done. I also Have enable OAuth 2.0 enabled in my google console.
Thanks to #DalmTo for throwing to its direction.
Basically Api Key doesn't have priviledges to retrieve comments and things like that. for deep priviledges I had to use Oauth, which basically is being created the same was as API Key but in Oauth you receive a client_secrets.json file containing: client secret, client ID and etc...
Then you call that in you code.
Note: Their is verious ways of calling you client_secrets.json file but it depends on your need.
My way: Reader clientSecretReader = new InputStreamReader(
new FileInputStream("/home/Downloads/src/client_secrets.json"));

I KEEP GETTING ERROR_WRONG_LABEL on Brother Printer QL-710W

I have been trying to get my android code to print to a new Brother Printer but
I keep getting ERROR_WRONG_LABEL.
I also get the information:
D/Brother Print SDK: no such enum object for the id: -1
This is my code:
public void printLabel() {
Printer myPrinter = new Printer();
PrinterInfo myPrinterInfo = new PrinterInfo();
try {
myPrinterInfo.printerModel = PrinterInfo.Model.QL_710W;
myPrinterInfo.ipAddress = "12.1.3.45";//not real ip
myPrinterInfo.macAddress = "";
myPrinterInfo.port = PrinterInfo.Port.NET;
myPrinterInfo.paperSize = PrinterInfo.PaperSize.A7;
myPrinterInfo.printMode=PrinterInfo.PrintMode.FIT_TO_PAGE;
myPrinterInfo.numberOfCopies = 1;
LabelInfo mLabelInfo = new LabelInfo();
mLabelInfo.labelNameIndex = 5;
mLabelInfo.isAutoCut = true;
mLabelInfo.isEndCut = true;
mLabelInfo.isHalfCut = false;
mLabelInfo.isSpecialTape = false;
myPrinter.setPrinterInfo(myPrinterInfo);
myPrinter.setLabelInfo(mLabelInfo);
//File downloadFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Log.i("HEYYYY", "startCommunication = " + myPrinter.startCommunication());
Bitmap map = BitmapFactory.decodeResource(getResources(), R.drawable.ic_action_overflow);
PrinterStatus printerStatus = myPrinter.printImage(map);
Log.i("HEYYYY", "errorCode-11 = " + printerStatus.errorCode);
Log.i("HEYYYY", "labelWidth = " + myPrinter.getLabelParam().labelWidth);
Log.i("HEYYYY", "paperWidth = " + myPrinter.getLabelParam().paperWidth);
Log.i("HEYYYY", "labelNameIndex " + mLabelInfo.labelNameIndex);
Log.i("HEYYYY", "printers " + myPrinter.getNetPrinters("QL-710W"));
Log.i("Label-id", myPrinter.getPrinterStatus().labelId + "");
myPrinter.endCommunication();
} catch(Exception e){
e.printStackTrace();
}
}
Whenever I put the mac address which I got from the printer page, the error code changes to
ERROR_NOT_MATCH_ADDRESS.
But without it(setting it to an empty string or commenting it out), it changes to
ERROR_WRONG_LABEL.
What is wrong with this code, please?
UPDATE:
I inserted the correct mac id and now the error code is
ERROR_WRONG_LABEL
what do I do?
After reading through the manual that came with it, I discovered that the ERROR_WRONG_LABEL code occurs due to wrong labelNameIndex or wrong paperSize.
I set the labelNameIndex value to 15 and, voila it worked.
I feel anyone facing this problems should try out various values for the labelNameIndex.
Thanks.

Using facebook graph API 2.5 for batch request in Java

I was using facebook FQL query to fetch sharecount for multiple URLS using this code without needing any access token.
https://graph.facebook.com/fql?q=";
"SELECT url, total_count,share_count FROM link_stat WHERE url in (";
private void callFB(List validUrlList,Map> dataMap,long timeStamp,Double calibrationFactor){
try {
StringBuilder urlString = new StringBuilder();
System.out.println("List Size " + validUrlList.size());
for (int i = 0; i < (validUrlList.size() - 1); i++) {
urlString.append("\"" + validUrlList.get(i) + "\",");
}
urlString.append("\""
+ validUrlList.get(validUrlList.size() - 1) + "\"");
String out = getConnection(fbURL+URLEncoder.encode(
queryPrefix
+ urlString.toString() + ")", "utf-8"));
dataMap = getSocialPopularity(validUrlList.toArray(), dataMap);
getJSON(out, dataMap, timeStamp,calibrationFactor);
} catch (Exception e) {
e.printStackTrace();
}
}
But as now Facebook has depreciated it i am planning to use
https://graph.facebook.com/v2.5/?ids=http://timesofindia.indiatimes.com/life-style/relationships/soul-curry/An-NRI-bride-who-was-tortured-to-hell/articleshow/50012721.cms&access_token=abc
But i could not find any code to make batch request in the same also i am using pageaccesstoken so what could be the rate limit for same.
Could you please help me to find teh batch request using java for this new version.
You will always be subject to rate limiting... If you're using the /?ids= endpoint, there's already a "batch" functionality built-in.
See
https://developers.facebook.com/docs/graph-api/using-graph-api/v2.5#multirequests
https://developers.facebook.com/docs/graph-api/advanced/rate-limiting

Categories