How do I write Facebook apps in Java? - java

I have looked in vain for a good example or starting point to write a java based facebook application... I was hoping that someone here would know of one. As well, I hear that facebook will no longer support their java API is this true and if yes does that mean that we should no longer use java to write facebook apps??

There's a community project which is intended to keep the Facebook Java API up to date, using the old official Facebook code as a starting point.
You can find it here along with a Getting Started guide and a few bits of sample code.

Facebook stopped supporting the official Java API on 5 May 2008 according to their developer wiki.
In no way does that mean you shouldn't use Java any more to write FB apps. There are several alternative Java approaches outlined on the wiki.
You might also want to check this project out; however, it only came out a few days ago so YMMV.

I write an example using facebook java api
It use FacebookXmlRestClient in order to make client request and print
all user infos
http://programmaremobile.blogspot.com/2009/01/facebook-java-apieng.html

BatchFB provides a modern Java API that lets you easily optimize your Facebook calls down to a minimum set:
http://code.google.com/p/batchfb/
Here's the example taken from the main page of what you can effectively do in a single FB request:
/** You write your own Jackson user mapping for the pieces you care about */
public class User {
long uid;
#JsonProperty("first_name") String firstName;
String pic_square;
String timezone;
}
Batcher batcher = new FacebookBatcher(accessToken);
Later<User> me = batcher.graph("me", User.class);
Later<User> mark = batcher.graph("markzuckerberg", User.class);
Later<List<User>> myFriends = batcher.query(
"SELECT uid, first_name, pic_square FROM user WHERE uid IN" +
"(SELECT uid2 FROM friend WHERE uid1 = " + myId + ")", User.class);
Later<User> bob = batcher.queryFirst("SELECT timezone FROM user WHERE uid = " + bobsId, User.class);
PagedLater<Post> feed = batcher.paged("me/feed", Post.class);
// No calls to Facebook have been made yet. The following get() will execute the
// whole batch as a single Facebook call.
String timezone = bob.get().timezone;
// You can just get simple values forcing immediate execution of the batch at any time.
User ivan = batcher.graph("ivan", User.class).get();

You might want to try Spring Social. It might be limited in terms of Facebook features, but lets you also connect to Twitter, LinkedIn, TripIt, GitHub, and Gowalla.
The other side of things is that as Facebook adds features some of the old API's might break, so using a simpler pure FB api (that you can update when things don't work) might be a good idea.

This tutorial will literally step you through everything you need to do: http://ocpsoft.org/opensource/creating-a-facebook-app-setup-and-tool-installation/
It comes in 3 parts. The other 2 are linked from there.

Related

Azure App Configuration Feature Management

I am looking for a solution using Maven and Java (Not Spring) where I can upload all my Key and labels and flag value by Json to deploy.
When I configure my project in Jenkins it should apply all the values which are changed.
Kindly provide me some directions, I tried lot with less material on this topic
I managed to workout the solution. Basically following this Microsoft Azure Link
, but not completely solved my problem by this link though. Below is the Code Snippet which solved my problem. Code is not testable or productionable , this is just for reference.
public void process() {
String value = "{\"id\": \"test\", \"description\": \"Sample Feature\",\"enabled\": false,\"conditions\": { \"client_filters\": []}}";
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
ConfigurationClient configurationClient = new ConfigurationClientBuilder()
.connectionString(END_POINT)
.buildClient();
final ConfigurationSetting configurationSetting = new ConfigurationSetting();
configurationSetting.setKey(format(".appconfig.abc/%s", "abc"));
configurationSetting.setLabel("lable");
configurationSetting.setContentType("application/vnd.microsoft.appconfig.ff+json;charset=utf-8");
configurationSetting.setValue(value);
configurationClient.addConfigurationSettingWithResponse(configurationSetting, NONE)
}
Key points here is ".appconfig.abc" , At this point of time we don't have direct call to Feature Management , but we can add Key and labels to configuration as I said in the code snippet but with the Key as ".appconfig.abc" which you can get this info from portal. And the value should be a Json object, how we make this Json is upto you really.
Overall so much of information around the sites but none of them are connected in Java world for Azure. May be helpful to any one.
End Point , one can get from the Configuration Access Keys.

Is it possible to get Direct Messages from Twitter by a specific user using the Twitter4j library?

I'm using the Twitter4j library to develop a proyect that works with Twitter, one of the things what I need is to get the Direct messages, I'm using the following code:
try{
List<DirectMessage> loStatusList = loTwitter.getDirectMessages();
for (DirectMessage loStatus : loStatusList) {
System.out.println(loStatus.getId() + ",#" + loStatus.getSenderScreenName() + "," + loStatus.getText() + "|");
}
}
catch(Exception e)
It works fine, but what the code returns is a list of the most recent messages in general. What I want is to get those direct messages using some kind of filter that allows finding them by a user that I indicate.
For example, I need to see the DM only from user #TwitterUser.
Is this posible with this library?
All kinds of suggestions are accepted, even if I should use another library I would be grateful if you let me know.
It looks like the actual Twitter API doesn't support a direct filter on that API, by username anyway. (See Twitter API doc: GET direct_messages.)
Which means, you'd have to make multiple calls to the API with pagination enabled, and cache the responses into a list.
Here is an example of pagination wtih Twitter4J getDirectMessages().
In that example, use the existing:
List<DirectMessage> messages;
But inside the loop, do:
messages.addAll(twitter.getDirectMessages(paging));
Note: you only would have to do this once. And in fact, you should persist these to a durable local cache like Redis or something. Because once you have the last message id, you can ask the Twitter API to only return "messages since id" with the since_id param.
Anyway, then on the client side you'd just do your filtering with the usual means in Java. For example:
// Joe is on twitter as #joe
private static final String AT_JOE = "Joe";
// Java 8 Lambda to filter by screen name
List<DirectMessage> messagesFromJoe = messages.stream()
.filter(message -> message.getSenderScreenName().equals(AT_JOE))
.collect(Collectors.toList());
Above, getSenderScreenName() was discovered by reading the Twitter4J API doc for DirectMessage.

How to fetch the Facebook comment replies using graph API?

I am using the Facebook graph API to get the posts and the comments, and it's all working fine. Now I want to use the API to get the replies of a particular comment. How can I do that? I’m using the following code to get the comments:
cmmntObj = facebookClient.fetchObject(postID + "/comments", JsonObject.class,
Parameter.with("limit", limitOfRecords),
Parameter.with(Since_Until[k], date_SinceLast[k].toString()),
Parameter.with("Date_Format", "U"));
The following code works well and fetches the comments. I would appreciate if somebody can help me in getting the replies also.
I parsed the Comments JSON and built another query around it but it doesn’t work.
This is the query to fetch the tweets:
String getCmmntID = new String();
getCmmntID = cmmntObj.getJsonArray("data").getJsonObject(0).getString("id");// .getString("id");
cmmntReplies = facebookClient.fetchObject(
postID + "/comments?filter=stream&fields=parent.fields(" + getCmmntID + ")",
JsonObject.class, Parameter.with("limit", limitOfRecords),
Parameter.with(Since_Until[k], date_SinceLast[k].toString()),
Parameter.with("Date_Format", "U"));
How do I get the replies to these?
It is possible to get the comments edge for your comments, and then to get the comments edge of those comments, ad-infinitum. This becomes a matter of you deciding how many levels of comments you want to code into your application. I'm not sure if there is a finite number of levels of comments that Facebook would allow, you'll have to experiment with that. However, here is what you would want to add:
Parameter.with("fields", "message,comments{comments,message}")
That will get you three levels of comments (the main comments and two levels of replies).

I am coding in Android Studio, and I need to fetch and display a specific line of data from a specific webpage

I am very new to coding in Java/Android Studio. I have everything setup that I have been able to figure out thus far. I have a button, and I need to put code inside of the button click event that will fetch information from a website, convert it to a string and display it. I figured I would have to use the html source code in order to do this, so I have installed Jsoup html parser. All of the help with Jsoup I have found only leads me up to getting the HTML into a "Document". And I am not sure if that is the best way to accomplish what I need. Can anyone tell me what code to use to fetch the html code from the website, and then do a search through the html looking for a specific match, and convert that match to a string. Or can anyone tell me if there is a better way to do this. I only need to grab one piece of information and display it.
Here is the piece of html code that contains the value I want:
writeBidRow('Wheat',-60,false,false,false,0.5,'01/15/2015','02/26/2015','All',' ',' ',60,'even','c=2246&l=3519&d=G15',quotes['KEH15'], 0-0);
I need to grab and display whatever value represents the quotes['KEH15'], in that html code.
Thank you in advance for your help.
Keith
Grabbing raw HTML is an extremely tedious way to access information from the web, bad practice, and difficult to maintain in the case that wherever you are fetching the info from changes their HTML.
I don't know your specific situation and what the data is that you are fetching, but if there is another way for you to fetch that data via an API, use that instead.
Since you say you are pretty new to Android and Java, let me explain something I wish had been explained to me very early on (although I am mostly self taught).
The way people access information across the Internet is traditionally through HTML and JavaScript (which is interpreted by your browser like Chrome or Firefox to look pretty), which are transferred over the internet using the protocol called HTTP. This is a great way for humans to communicate with computers that are far away, and the average person probably doesn't realize that there is more to the internet than this--your browser and the websites you can go to.
Although there are multiple methods, for the purpose of what I think you're looking for, applications communicate over the internet a slightly different way:
When an android application asks a server for some information, rather than returning HTML and JavaScript which is intended for human consumption, the server will (traditionally) return what's called JSON (or sometimes XML, which is very similar). JSON is a very simple way to get information about an object, and put it into a form that is readable easily by both humans (developers) and computers, and can be transmitted over the internet easily. For example, let's say you ask a server for some kind of "Video" object for an app that plays video, it may give you something like this:
{
"name": "Gangnam Style",
"metadata": {
"url": "https://www.youtube.com/watch?v=9bZkp7q19f0",
"views": 2000000000,
"ageRestricted": false,
"likes": 43434
"dislikes":124
},
"comments": [
{
"username": "John",
"comment": "10/10 would watch again"
},
{
"username": "Jane",
"number": "12/10 with rice"
}
]
}
That is very readable by us humans, but also by computers! We know the name is "Gangnam Style", the link of the video, etc.
A super helpful way to interact with JSON in Java and Android is Google's GSON library, which lets you cast a Java object as JSON or parse a JSON object to a Java object.
To get this information in the first place, you have to make a network call to an API, Application Programming Interface. Just a fancy term for communication between a server and a client. One very cool, free, and easy to understand API that I will use for this example is the OMDB API, which just spits back information about movies from IMDB. So how do you talk to the API? Well luckily they've got some nice documentation, which says that to get information on a movie we need to use some parameters in the url, like perhaps
http://www.omdbapi.com/?t=Interstellar
They want a title with the parameter "t". We could put a year, or return type, but this should be good to understand the basics. If you go to that URL in your browser, it spits back lots of information about Interstellar in JSON form. That stuff we were talking about! So how would you get this information from your Android application?
Well, you could use Android's built in HttpUrlConnection classes and research for a few hours on why your calls aren't working. But doesn't essentially every app now use networking? Why reinvent the wheel when virtually every valuable app out there has probably done this work before? Perhaps we can find some code online to do this work for us.
Or even better, a library! In particular, an open source library developed by Square, retrofit. There are multiple libraries like it (go ahead and research that out, it's best to find the best fit for your project), but the idea is they do all the hard work for you like low level network programming. Following their guides, you can reduce a lot of code work into just a few lines. So for our OMDB API example, we can set up our network calls like this:
//OMDB API
public ApiClient{
//an instance of this client object
private static OmdbApiInterface sOmdbApiInterface;
//if the omdbApiInterface object has been instantiated, return it, but if not, build it then return it.
public static OmdbApiInterface getOmdbApiClient() {
if (sOmdbApiInterface == null) {
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://www.omdbapi.com")
.build();
sOmdbApiInterface = restAdapter.create(OmdbApiInterface.class);
}
return sOmdbApiInterface;
}
public interface OmdbApiInterface {
#GET("/")
void getInfo(#Query("t") String title, Callback<JsonObject> callback);
}
}
After you have researched and understand what's going on up there using their documentation, we can now use this class that we have set up anywhere in your application to call the API:
//you could get a user input string and pass it in as movieName
ApiClient.getOmdbApiClient().getInfo(movieName, new Callback<List<MovieInfo>>() {
//the nice thing here is that RetroFit deals with the JSON for you, so you can just get information right here from the JSON object
#Override
public void success(JsonObject movies, Response response) {
Log.i("TAG","Movie name is " + movies.getString("Title");
}
#Override
public void failure(RetrofitError error) {
Log.e("TAG", error.getMessage());
}
});
Now you've made an API call to get info from across the web! Congratulations! Now do what you want with the data. In this case we used Omdb but you can use anything that has this method of communication. For your purposes, I don't know exactly what data you are trying to get, but if it's possible, try to find a public API or something where you can get it using a method similar to this.
Let me know if you've got any questions.
Cheers!
As #caleb-allen said, if an API is available to you, it's better to use that.
However, I'm assuming that the web page is all you have to work with.
There are many libraries that can be used on Android to get the content of a URL.
Choices range from using the bare-bones HTTPUrlConnection to slightly higher-level HTTPClient to using robust libraries like Retrofit. I personally recommend Retrofit. Whatever you do, make sure that your HTTP access is asynchronous, and not done on the UI thread. Retrofit will handle this for you by default.
For parsing the results, I've had good results in the past using the open-source HTMLCleaner library - see http://htmlcleaner.sourceforge.net
Similar to JSoup, it takes a possibly-badly-formed HTML document and creates a valid XML document from it.
Once you have a valid XML document, you can use HTMLCleaner's implementation of the XML DOM to parse the document to find what you need.
Here, for example, is a method that I use to parse the names of 'projects' from a <table> element on a web page where projects are links within the table:
private List<Project> parseProjects(String html) throws Exception {
List<Project> parsedProjects = new ArrayList<Project>();
HtmlCleaner pageParser = new HtmlCleaner();
TagNode node = pageParser.clean(html);
String xpath = "//table[#class='listtable']".toString();
Object[] tables = node.evaluateXPath(xpath);
TagNode tableNode;
if(tables.length > 1) {
tableNode = (TagNode) tables[0];
} else {
throw new Exception("projects table not found in html");
}
TagNode[] projectLinks = tableNode.getElementsByName("a", true);
for(int i = 0; i < projectLinks.length; i++) {
TagNode link = projectLinks[i];
String projectName = link.getText().toString();
String href = link.getAttributeByName("href");
String projectIdString = href.split("=")[1];
int projectId = Integer.parseInt(projectIdString);
Project project = new Project(projectId, projectName);
parsedProjects.add(project);
}
return parsedProjects;
}
If you have permission to edit the webpage to add hyper link to specified line of that page you can use this way
First add code for head of line that you want to go there in your page
head your text if wanna
Then in your apk app on control click code enter
This.mwebview.loadurl("https:#######.com.html#target")
in left side of # enter your address of webpage and then #target in this example that your id is target.
Excuse me if my english lang. isn't good

get all issues stored in jira

hi i want to get all issues stored in jira from java using jql or any othere way.
i try to use this code:
for(String name:getProjectsNames()){
String jqlRequest = "project = \""+name+"\"";
SearchResult result = restClient.getSearchClient().searchJql(
jqlRequest, 10000,0, pm);
final Iterable<BasicIssue> issues = result.getIssues();
for (BasicIssue is : issues) {
Issue issue = restClient.getIssueClient().getIssue(is.getKey(), pm);
...........
}
it give me the result but it take a very long time.
is there a query or a rest API URL or any other way that give me all issues?
please help me
The JIRA REST API will give you all the info from each issue at a rate of a few issues/second. The Inquisitor add-on at https://marketplace.atlassian.com/plugins/com.citrix.jira.inquisitor will give you thousands of issues per second but only the standard JIRA fields.
There is one other way. There is one table in JIRA database named "dbo.jiraissue". If you have access to that database then you can fetch all the ids of all issues. After fetching this data you can send this REST request "**localhost/rest/api/2/issue/issue_id" and get JSON response. Of course you have to write some code for this but this is one way I know to get all issues.

Categories

Resources