Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Develop a Facebook application with Eclipse Galileo

Create, debug, and deploy a restaurant search application

Suresh Krishna, Software Developer, Freelance Developer
Suresh Krishna has been a programmer since 2000 and has been working on the domain modeling, IDEs, and productivity tools. Inspired by the IDE evolution and developer productivity, he works primarily on the Eclipse plug-ins and RCP applications. Extreme Programming and Scrum are his favorites, along with evangelizing Eclipse to the user, developer, and corporate communities. He enjoys his free time writing blogs and product evaluations.

Summary:  This article is for any Eclipse developer who wants to learn how to use the mature Web Tools Platform release of Galileo to develop, debug, and deploy a restaurant-search Facebook application. Along the way, you will take advantage of various aspects of the Facebook Application API and the Facebook Connect API.

Date:  22 Dec 2009
Level:  Intermediate
Also available in:   Japanese  Portuguese

Activity:  87342 views
Comments:  

Eclipse Galileo

Eclipse Galileo is the annual release of Eclipse projects, which includes 33 projects. This release has 24 million lines of code from 380 committers from 44 organizations. The new features in the Galileo release reflect three important trends in the Eclipse community: expanding adoption of Eclipse in the enterprise, innovation of Eclipse modeling technology, and advancement of Eclipse runtime technology.

Getting started with Galileo

Before you begin developing your Facebook SimpleRestaurantSearch application, you need to download and install the Galileo package of Eclipse (see Resources). In this section, you'll learn how to set it up.

Downloading Galileo

The Galileo package represents the next incremental release for Eclipse, and as such, means a new installation of the Eclipse platform. As with all Eclipse releases, there are a number of packages to choose from, depending upon your development needs.

Download the Eclipse IDE for Java™ EE Developers version, as it has everything you need to develop and deploy a Facebook application. Choose the version for your operating system, select an appropriate mirror, and download it (see Resources). The file is quite large — close to 190 MB depending on your platform — so be patient.

The Eclipse Web site provides a comparison chart, shown in Figure 1.


Figure 1. Package comparison chart
Image showing Eclipse Web site comparison chart

When the download is complete, unzip the package where you want Eclipse to be installed, then double-click the Eclipse icon to run it. Select a workspace, and Eclipse will take you to the welcome page. From here, choose the Workbench icon (the arrow on the far right of the welcome screen shown in Figure 2).


Figure 2. Eclipse Welcome screen
Screenshot shows the Eclipse Welcome screen

Setting up Tomcat in Eclipse

Eclipse Galileo allows you to integrate variety of servers so that any Web applications can be developed, debugged, and deployed. For the current Facebook SimpleRestaurantSearch application, you would use Tomcat as the application server (see Resources). Download Tomcat to a local folder and extract it.

Switch to Eclipse and open the server view (see Figure 3).


Figure 3. Server view in Eclipse
Figure 3 shows the server view in Eclipse

Right-click on the server view and select New > Server menu option (see Figure 4).


Figure 4. New server menu option
Image shows the new server menu option

Define a new server by selecting the appropriate options. Select the Tomcat V6 Server option under Apache category. You can name the server as anything meaningful for the application like EclipseBook-Host, then click Next (see Figure 5).


Figure 5. Defining a new server
Figure 5 shows how to                     define a new server

In the next wizard window, enter the Tomcat installation directory, select the required JRE, then click Finish (see Figure 6).


Figure 6. Setting the installation directory
Screenshot showing how to set the installation directory

Once Tomcat is properly configured, the server appears in the server view. By default, the server port is set to 8080 (see Figure 7).


Figure 7. Server appears in the server view
Image shows that the server appears in the server view

Next, we'll set up the Dynamic Web Project so you can work with your application's Web interface from within Eclipse.

Setting up the Dynamic Web Project

Click on the Project Explorer, and right-click and select the Dynamic Web Project (see Figure 8).


Figure 8. Setting up the Dynamic Web Project
Image shows setting up the Dynamic Web Project

Give the project a name and set the target runtime to be the Tomcat Server name. Remember that you name the Tomcat Server as EclipseBook-Host. Click Finish to create the Web project configured to use the Tomcat server and default Web configuration (see Figure 9).


Figure 9. Creating the Web project
Screen showing how to create the Web project


Downloading and setting up the Facebook Java API

As of May 2008, Facebook has discontinued any support of its official Java client, directing users interested developing Facebook applications in Java technology to use one of the various third-party clients out there. One of the popular Facebook Java APIs is available on Google (see Resources). As such, the purpose of this project is now to maintain, support, and extend the abandoned code base to provide a high-quality, up-to-date version of the Facebook API client for Java developers (see Figure 10).


Figure 10. Facebook Java API
Figure 10 shows the Facebook Java API

Download the latest Java Facebook API (V3.0.0) into the local folder and extract the files (see Figure 11).


Figure 11. Downloading the latest Facebook Java API
Screen showing downloading of the latest  Facebook Java API

The Facebook Java API contains all the libraries related to the Facebook Application API and other dependent JARs (see Figure 12). See Download for the source code of our sample application. Note that the JAR files aren't included in that ZIP file, since you download them here with the Facebook Java API.


Figure 12. Libraries related to the Facebook Application API and other dependent JARs
Figure 12 shows the libraries related to the Facebook Application                     API and other dependent JARs

Copy all the Facebook Java Client JARs to the lib folder of the SimpleRestaurantSearch application. This will now enable the project to use the Facebook APIs (see Figure 13).


Figure 13. Copy all the Facebook Java Client JARs to lib folder
Image showing how to copy all the Facebook Java Client JARs to                     the lib folder


Creating a Facebook application

Almost everyone has a presence on Facebook, including Web developers, business managers, and social geeks. Creating applications on the Facebook platform that leverage the Facebook Application API opens a window of visibility for users of all stripes, whether they wish to advertise a product or service or simply share information with friends.

To create a Facebook application, you first need to obtain a Facebook Platform API key. Follow these steps to create an application with the Facebook Developer application.

Go to the Get Started site to get an overview of the steps for setting up the application (see Resources). Click on Developer App in the Helpful Links to go to your user profile and add this developer application. If you are not already logged in, a login screen will prompt you for login. Otherwise, the application asks for authorization and will add the application to your profile (see Figure 14).


Figure 14. Get Started
Figure 14 shows the Get Started site

The developer's home page contains the news, updates, and articles about the Facebook Platform API.

Enter a name for your application in the Application Name field (see Figure 15). If you have already created the icon and logo for your application, you can enter this information at this time in the same screen. Accept the developer terms of service, then click Save Changes.


Figure 15. Naming the application
Naming the application

In the next screen shown in Figure 16, important information is displayed. It is important to note the Application ID, API Key, and Secret Key for future application development.


Figure 16. Application ID, API Key, and Secret Key are displayed
Figure 16 shows that the Application ID, API Key, and Secret Key are displayed

Once you enter the required information and save the new application, an overview of the RestaurantSearch application information is displayed (see Figure 17).


Figure 17. Overview of application
Image shows overview of application

By now, you have created and registered an application named SimpleRestaurantSearch with Facebook. The next step creates a simple servlet and adds functionality to authenticate the Facebook API key. In the Project Explorer, go to the SimpleRestaurantSearch project, then create a servlet in the src folder. Name the servlet RestaurantSearch and enter the package name as com.devworks.facebook. Click Next to enter the servlet initialization parameters (see Figure 18).


Figure 18. Creating a simple servlet
Screen shows creating a simple servlet

In the next screen shown in Figure 19, enter the Initialization Parameters API_KEY and the value as the API key in our initial steps of Facebook application creation.


Figure 19. Entering the Initialization Parameters API_KEY
Figure 19 shows entering the Initialization Parameters API_KEY

On the next screen, enter the Initialization Parameters SECRET_KEY and the value as the secret key in our initial steps of Facebook application creation.

This is the time to use the API_KEY and SECRET_KEY to authenticate the Facebook application, and if the login is successful, print a simple Hello World message.

Listing 1 is the critical segment of the doGet method of our RestaurantSearch servlet.


Listing 1. doGet method

01   protected void doGet(HttpServletRequest request,
02     HttpServletResponse response) throws ServletException,IOException {
03 
04     String apiKey = getServletConfig().getInitParameter("API_KEY");
05     String secretKey = getServletConfig().getInitParameter("SECRET_KEY");
06     HttpSession session = request.getSession();
07     String sessionKey = (String) session
08         .getAttribute("restSearchAppSession");
09     String authToken = request.getParameter("auth_token");
10 
11     FacebookJsonRestClient client = null;
12 
13     if (sessionKey != null) {
14       client = new FacebookJsonRestClient(apiKey,
15           secretKey,
16           sessionKey);
17 
18     } else if (authToken != null) {
19       client = new FacebookJsonRestClient(apiKey, secretKey);
20       client.setIsDesktop(false);
21       try {
22         sessionKey = client.auth_getSession(authToken);
23         session.setAttribute("restSearchAppSession", sessionKey);
24       } catch (Exception e) {
25         e.printStackTrace();
26       }
27     } else {
28      response.sendRedirect("http://www.facebook.com/login.php?api_key="+apiKey);
29       return;
30     }
31     response.getWriter().println("HelloWorld");
32   }

Lines 4 and 5 get the initial parameters such as API_KEY and SECRET_KEY from servlet configuration.

Line 7 gets the session key from the session if it's already present, else it would be null.

Line 9 gets the authentication token from the request parameter. It could be null if the session is not authenticated.

If a sessionKey exists, Line 14 creates a FacebookJsonRestClient and needs the apiKey, secretKey, and sessionKey as constructor arguments (see Figure 20).


Figure 20. Creating a FacebookJsonRestClient
Image shows creating a FacebookJsonRestClient

If a sessionKey does not exist, create a FacebookJsonRestClient with only the apiKey and secretKey. On line 20, make sure to set the correct client mode.

It's important that your application is set to the correct mode. If it is set to "desktop mode is false," the Facebook server will understand when you try to pass a session secret.

In lines 22 and 23, create the sessionKey with the help of authentication token and set it to the session attribute restSearchAppSession.

If there is no sessionKey and no authentication token that implies that the user needs to log in to the Facebook and get a new session and auth key. Thus, the Line 28 redirects to Facebook login.

Finally, print Hello World on the output writer, as shown in line 31.

Once the RestaurantSearch application is complete, you can start the Tomcat server. Remember that in the initial steps of cresting the SimpleRestaurantSearch application, you have already associated this project with the Tomcat server EclipseBook-Host. From the server view, start Tomcat. This will start the Tomcat server in Eclipse and will deploy the application (see Figure 21).


Figure 21. Starting the Tomcat server in Eclipse and deploying the application
Screen shows starting the Tomcat server in Eclipse and deploying the application

Once the Tomcat server is started, browse to http://localhost:8080/SimpleRestaurantSearch/RestaurantSearch. This will take you to a Facebook developer page that informs you that the site is under construction and suggests you that the application Callback URL is not set. Click on the applications settings editor (see Figure 22).


Figure 22. The applications settings editor
Image shows the applications settings editor

In the application settings editor, go to the Canvas tab and enter the Canvas page URL (http://apps.facebook.com/devrestaurantsearch), Canvas Callback URL (http://localhost:8080/SimpleRestaurantSearch/RestaurantSearch), and Bookmark URL (http://apps.facebook.com/devrestaurantsearch). Save the settings (see Figure 23).


Figure 23. Application settings editor
Screen shows the application settings editor

Once the new settings are saved, the Application Overview page is displayed (see Figure 24).


Figure 24. Application Overview
Figure 24 shows the Application Overview page

The real power of Eclipse is the integrated Tomcat and hot deployment capability. You can simply restart the server now and see if the saved application properties are in effect (see Figure 25).


Figure 25. Restarting the server
Image shows restarting the server

Now when the server is restarted within Eclipse Galileo, the RestaurantSearch servlet will redirect you to the app login page (http://www.facebook.com/login.php?api_key=<API_KEY>). Once you enter your Facebook's e-mail ID and password, the servlet will write the response out.

From the Facebook application screen, it can be understood that the API_KEY is used to log in to the appropriate application. In this case, it is SimpleRestaurantSearch (see Figure 26).


Figure 26. Application login
Application login

Finally, the Facebook application is authenticated, and once the sessionKey and authKey are generated, Hello World is displayed on the screen (see Figure 27).


Figure 27. Hello World is displayed
Image shows that Hello World is displayed

Log off from Facebook and try to access the application on http://www.facebook.com/apps/application.php?id=144078916555. Facebook displays the application information, and you can access it by logging in (see Figure 28).


Figure 28. Login page
Screen shows the login page

In the next steps, you will use the Google Search API and integrate it into a simple JSP.


Integrate Google Search API into the Facebook application

The Google Ajax Search API lets you put Google Search in your Web pages with JavaScript. You can embed a simple dynamic search box and display search results in your own Web pages or use the results in innovative, programmatic ways. You do not need a key to use this API. Using a key in your application/site is completely optional. However, it is useful to have one.

Go to http://code.google.com/apis/ajaxsearch/signup.html and agree to the terms and conditions. Click on the Generate API Key (see Figure 29).


Figure 29. Generating the API key
Image shows generating                     the API key

Google generates API key and shows the URL for which this API is good. This Web page also provides examples to get started (see Figure 30).


Figure 30. Google-generated API key
Figure 30 displays the Google-generated API key

Copy the provided example code from the above Google Search to RestaurantSearch.jsp in the WebContent folder. Save the JSP and make sure to change the code in SimpleRestaurantSearch from writing the response Hello World to dispatch the request to the RestaurantSearch.jsp.

Change the code from response.getWriter().println("Hello World"); to request.getRequestDispatcher("RestaurantSearch.jsp").forward(request,response);.

The moment the JSP is saved, the entire project gets redeployed to the Tomcat server automatically. In the previous steps, you set the Canvas URL (http://apps.facebook.com/devrestaurantsearch) and also the Canvas Callback URL (http://localhost:8080/SimpleRestaurantSearch/RestaurantSearch) (see Figure 31).


Figure 31. Settings for the Canvas URL and the Canvas Callback URL
Screen shows the settings for the Canvas URL and the Canvas Callback URL

If you access the Canvas URL, and once you have successfully logged in, RestaurantSearch.jsp starts the RestaurantSearch application (see Figure 32).


Figure 32. Starting up the RestaurantSearch application
Image shows starting the RestaurantSearch application

The application bookmark is in the bottom left corner of the application toolbar. You can enter a search string for a restaurant search (see Figure 33).


Figure 33. Application bookmark in the application toolbar
AFigure 33 shows the application bookmark in the application toolbar

Change the default location in the Google Maps and set the default maps view to NORMAL View in RestaurantSearch.jsp (see Listing 2).


Listing 2. Changing the default location in Google Maps

// change the default location in the Google Maps
map.setCenter(new google.maps.LatLng(37.773,-122.417),13);

// set the Map to Normal view
map.setMapType(G_NORMAL_MAP);
map.removeMapType(G_HYBRID_MAP);
map.addMapType(G_NORMAL_MAP);

Save the JSP to hot-deploy and retest it to make sure that the location and map type are changed (see Figure 34). We have now chosen San Francisco as the default search location. Once this application is running in Facebook, when a user searches for a type of restaurant, he can add a ZIP code for the location, and the application will return mapped restaurant results in that location.


Figure 34. Redeploying and retesting the application
Screenshot shows redeploying and retesting the application

Now you can test further by navigating to your Facebook profile and searching for the SimpleRestaurantSearch application in the search box in the top right corner (see Figure 35).


Figure 35. Searching for the SimpleRestaurantSearch application from your Facebook profile
Screen shows searching for the SimpleRestaurantSearch application from your Facebook profile

Application Search will take you to the SimpleRestaurantSearch application (see Figure 36).


Figure 36. Application Search takes you to the SimpleRestaurantSearch application
Image shows that Application Search takes you to the SimpleRestaurantSearch application


Integrating the Facebook Connect API

Facebook Connect allows you to leverage Facebook for your own off-Facebook applications. You could use the Facebook connect API on your site and let your viewers share content on their own profiles.

You will need to create a cross-domain communication channel file called xd_receiver.htm and place it in a directory relative to the callback URL. You should create the xd_receiver.htm file in the directory from where you'll be serving your Connect Web pages (WebContent folder in our example). See Figure 37.


Figure 37. Creating and saving a cross-domain communication channel
Screen shows creating and saving a cross-domain communication channel

An example of a cross-domain channel file is shown in Listing 3. You can copy the following content and create the xd_receiver.htm in the WebContent folder. Without a cross-domain channel file, Facebook will not be able to communicate correctly with our application server (see Listing 3).


Listing 3. A cross-domain channel file

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/XdCommReceiver.js"
 mce_src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/XdCommReceiver.js" 
type="text/javascript"></script>
</body>
</html>

The quickest way to start using Facebook Connect on your server is to use the JavaScript API library. The two essential properties of connecting to the library are setting the correct document type and loading the JavaScript library at the end of your Web page, near the </body> tag. This code change can be done in the RestuarantSearch.jsp file (see Listing 4).


Listing 4. Using Facebook Connect on your server

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" 
xmlns:fb="http://www.facebook.com/2008/fbml">

<script type="text/javascript" 
src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php"
 mce_src="http://static.ak.connect.facebook.com/js/api_lib/
v0.4/FeatureLoader.js.php"> </script>

Listing 5 is a simple example of how to log a user into your Facebook Connect application and display his name and profile picture from Facebook.


Listing 5. Simple example of how to log a user into your Facebook Connect application

<script type="text/javascript"> 
function update_user_box() {
    var user_box = document.getElementById("user");

    user_box.innerHTML =
    "<span>"
    + "<fb:profile-pic uid='loggedinuser' facebook-logo='true'>
</fb:profile-pic>"
    + "Welcome, <fb:name uid='loggedinuser' useyou='false'></fb:name>"
    + "</span>";

    FB.XFBML.Host.parseDomTree();
}
</script>

<script type="text/javascript" src="http://static.ak.connect.facebook.com/js
/api_lib/v0.4/FeatureLoader.js.php"mce_src="http://static.ak.connect.facebook.com/js
/api_lib/v0.4/FeatureLoader.js.php"> 
</script>

<script type="text/javascript">
    var api_key = "Connect API_key here";
    var channel_path = "xd_receiver.htm"; 
    FB.init(api_key, channel_path, {"ifUserConnected": update_user_box});
</script>

To test this on your own server, you need to replace your API key in Listing 5, which is shown in Figure 38.


Figure 38. Replacing the API key
Image shows replacing the API key

Once you save the JSP, it gets hot-deployed, and you can start the RestaurantSearch application. Notice that you can see a button at the bottom of the search results (see Figure 39).


Figure 39. Button at the bottom of the search results
Figure shows the button at the bottom of the search results

If you are already logged into the Facebook session, clicking the Facebook Connect would log you into your profile. The idea is that the SimpleRestaurantSearch user would share his favorite restaurants and feedback on your own profile.

This example demonstrates the real power of the Facebook Connect API. Once the restaurant application is launched, connect to the Facebook Connect, and recommend restaurant on your profile. These restaurant recommendations can be viewed by other friends of yours.

Clicking on the Recommendation button would open a small wizard that would take in the comments and share it with friends (see Figure 40).


Figure 40. Opening a wizard for comments
Figure 40 shows opening a wizard for comments

You can test the Facebook application by going to your application developer profile and allowing it to be viewed by others (see Figure 41).


Figure 41. Sharing your information
Screen shows sharing your information


Summary

Eclipse Galileo has included a number of new and improved features, and you can leverage Galileo to develop great applications. This article uses the Eclipse Galileo J2EE edition that has the tools for Java developers creating Java EE and Web applications, including a Java IDE, tools for Java EE, JPA, JSF, Mylyn, and others.

With the Galileo J2EE edition, you imported the Facebook Java libraries, configured Tomcat as an internal server, added the functionality for Facebook authentication, added Google Search API, and added the Facebook Connect API to the SimpleRestaurantSearch application.

Integrated Tomcat enables you to develop, debug, test, and deploy the complete Facebook application code. You can take the full advantage of the Galileo release to develop a great Facebook application. With a Facebook ID, Facebook Developer Key, and Google Search API, you can use the attached code to test the RestaurantSearch application.



Download

DescriptionNameSizeDownload method
Restaurant Search source codeos-eclipse-facebookRestaurantSearch.zip18KBHTTP

Information about download methods


Resources

Learn

Get products and technologies

Discuss

  • The Eclipse Platform newsgroups should be your first stop to discuss questions regarding Eclipse. (Selecting this will launch your default Usenet news reader application and open eclipse.platform.)

  • The Eclipse newsgroups has many resources for people interested in using and extending Eclipse.

  • Participate in developerWorks blogs and get involved in the developerWorks community.

Related

You might also be interested in the following content from developerWorks

About the author

Suresh Krishna has been a programmer since 2000 and has been working on the domain modeling, IDEs, and productivity tools. Inspired by the IDE evolution and developer productivity, he works primarily on the Eclipse plug-ins and RCP applications. Extreme Programming and Scrum are his favorites, along with evangelizing Eclipse to the user, developer, and corporate communities. He enjoys his free time writing blogs and product evaluations.

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Open source
ArticleID=457247
ArticleTitle=Develop a Facebook application with Eclipse Galileo
publish-date=12222009
author1-email=suresh.madhuvarsu@gmail.com
author1-email-cc=