Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

How to Face Detection in Java using JJIL

A requirement came up on a recent project to automatically crop displayed profile images of people to just the "face" area for a thumbnail.

This seems like a job for a face detection algorithm. Searching for appropriate open-source Java implementations didn't yield too many results,
I was successful with JJIL - Jon's Java Imaging Library, which is open sourced under the LGPL licence.

JJIL is targeted at Java ME / Android platforms and doesn't have much documentation or a particularly intuitive API (not complaining, as clearly some stellar work has gone into it, kudos to Jon Webb, it's creator).

In the end I muddled through, detecting faces in an image in a standard Java project, but given it took me a while to get everything working, I thought I'd write a quick guide to help out others that are trying to achieve similar results.

Getting the Right JARs

First things first, I had trouble getting the published JAR files to work happily together. There seems to be some sort of version mismatch issue between the core and J2SE versions.

So I built my own copy - you can download it here - JJIL-visural-build-20110112.zip

This is a build of the current trunk JJIL code, and the Java SE additions (jjil-j2se).

This build is guaranteed to work with the code examples below.

Basic Process

I'm going to try to explain the basic process of detecting the faces in terms of input and output data.

The key file provided by JJIL for easy face (and other body part) detection is Gray8DetectHaarMultiScale.java

This operation is applied to an 8-bit greyscale input image, in combination with a pre-defined Haar Cascade profile. The profile determines which areas of the image are "detected". So you would want (for example) a profile to detect the frontal face features. JJIL provides several profiles out of the box.

The output image is a mask of the area of image where faces are detected (white) and the areas where no face was detected (black). This isn't tremendously useful, as we'd usually rather just have the rectangular areas in coordinate form - I'll address this later, after walking through the process.


  • Read an image from disk (.JPG, etc.)



  • Convert it into a jjil.core.Image
  • Generally we'll have an RGB image (colored image) and so need to convert it to 8-bit greyscale, which is what the Gray8DetectHaarMultiScale class requires.



  • Create a new instance of Gray8DetectHaarMultiScale with the Haar profile for detecting faces (or other body part if that's what you're looking for).
  • Apply Gray8DetectHaarMultiScale to our 8-bit grey image.
  • Retrieve result from Gray8DetectHaarMultiScale.



  • Resulting Haar mask for test image for face detection

The figure below shows, the source image, overlayed with the resulting mask, from step #6

So as you can see, the masks correctly identify the faces the two people in the image.

Here's a small Java class that demonstrates how to read an image and apply the process described above.

Note: all the code in the article can be downloaded as a full project at the end of the article.

The Code

package jjilexample;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import javax.imageio.ImageIO;
import jjil.algorithm.Gray8Rgb;
import jjil.algorithm.RgbAvgGray;
import jjil.core.Image;
import jjil.core.RgbImage;
import jjil.j2se.RgbImageJ2se;
import jjil.algorithm.Gray8DetectHaarMultiScale;
public class Main {
    public static void findFaces(BufferedImage bi, int minScale, int maxScale, File output) {
        try {
            // step #2 - convert BufferedImage to JJIL Image
            RgbImage im = RgbImageJ2se.toRgbImage(bi);
            // step #3 - convert image to greyscale 8-bits
            RgbAvgGray toGray = new RgbAvgGray();
            toGray.push(im);
            // step #4 - initialise face detector with correct Haar profile
            InputStream is  = Main.class.getResourceAsStream("/jjilexample/haar/HCSB.txt");
            Gray8DetectHaarMultiScale detectHaar = new Gray8DetectHaarMultiScale(is, minScale, maxScale);
            // step #5 - apply face detector to grayscale image
            detectHaar.push(toGray.getFront());
            // step #6 - retrieve resulting face detection mask
            Image i = detectHaar.getFront();
            // finally convert back to RGB image to write out to .jpg file
            Gray8Rgb g2rgb = new Gray8Rgb();
            g2rgb.push(i);
            RgbImageJ2se conv = new RgbImageJ2se();
            conv.toFile((RgbImage)g2rgb.getFront(), output.getCanonicalPath());
        } catch (Throwable e) {
            throw new IllegalStateException(e);
        }
    }
    public static void main(String[] args) throws Exception {
        // step #1 - read source image
        BufferedImage bi = ImageIO.read(Main.class.getResourceAsStream("test.jpg"));
        // onto following steps...
        findFaces(bi, 1, 40, new File("c:/Temp/result.jpg")); // change as needed
    }
}

Getting Face Rectangles Instead

It would be more useful in many cases, to get a collection of Rectangles, in coordinate form, instead of an image mask.

There is a version of DetectHaarMultiScale in the JJIL project SVN, which implements a "getRectangles" method to retrieve this data. Unfortunately the source is incompatible with the rest of the library in SVN, so it may be WIP or an abandoned version of the code.

To get around this, I created my own version of Gray8DetectHaarMultiScale, which you can download here - Gray8DetectHaarMultiScale

Here are the important changes below -

    public void push(Image image)  throws jjil.core.Error {
        pushAndReturn(image);
    }
    public List pushAndReturn(Image image) throws jjil.core.Error
    {
        List result = new ArrayList();
....
                    if (hcc.eval(imSub)) {
                        // Found something.
                        nxLastFound = imSub.getXOffset();
                        nyLastFound = imSub.getYOffset();
                        // assign Byte.MAX_VALUE to the feature area so we don't
                        // search it again
                        result.add(new Rect(nxLastFound*nScale, nyLastFound*nScale,
                                this.hcc.getWidth()*nScale,
                                this.hcc.getHeight()*nScale));
                        Gray8Rect gr = new Gray8Rect(nxLastFound,
                                nyLastFound,
                                this.hcc.getWidth(),
                                this.hcc.getHeight(),
                                Byte.MAX_VALUE);
                        gr.push(imMask);
                        imMask = (Gray8Image) gr.getFront();
                     }
....
        return result;
    }
So now we can call "pushAndReturn(...)" instead of just push() to apply the process to our image, and get a List back of the detected faces. Perfect!

Using this here is a version of the example code above which prints out the rectangles where faces were detected -
package jjilexample;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.util.List;
import javax.imageio.ImageIO;
import jjil.algorithm.Gray8Rgb;
import jjil.algorithm.RgbAvgGray;
import jjil.core.Image;
import jjil.core.Rect;
import jjil.core.RgbImage;
import jjil.j2se.RgbImageJ2se;
public class Main {
    public static void findFaces(BufferedImage bi, int minScale, int maxScale, File output) {
        try {
            InputStream is  = Main.class.getResourceAsStream("/jjilexample/haar/HCSB.txt");
            Gray8DetectHaarMultiScale detectHaar = new Gray8DetectHaarMultiScale(is, minScale, maxScale);
            RgbImage im = RgbImageJ2se.toRgbImage(bi);
            RgbAvgGray toGray = new RgbAvgGray();
            toGray.push(im);
            List results = detectHaar.pushAndReturn(toGray.getFront());
            System.out.println("Found "+results.size()+" faces");
            Image i = detectHaar.getFront();
            Gray8Rgb g2rgb = new Gray8Rgb();
            g2rgb.push(i);
            RgbImageJ2se conv = new RgbImageJ2se();
            conv.toFile((RgbImage)g2rgb.getFront(), output.getCanonicalPath());
        } catch (Throwable e) {
            throw new IllegalStateException(e);
        }
    }
    public static void main(String[] args) throws Exception {
        BufferedImage bi = ImageIO.read(Main.class.getResourceAsStream("test.jpg"));
        findFaces(bi, 1, 40, new File("c:/Temp/result.jpg")); // change as needed
    }
}

If you run this, you will note that it actually detects 3 faces in the image. This is common, as the way the Haar algorithm works, is by resizing the image to different scales and running a fixed size matrix over the image. It is possible for the same face to be detected at different scales and so you end up with rectangles within rectangles. It is a pretty trivial matter to remove these "extra" rectangles though by just checking if they are fully contained by another and ignoring them accordingly.

Download the Project

To save you some time, here's the full example as a Netbeans project that you can download and run, play with, etc. Have fun!
Read More

How to Use Dropbox Java API in Java

This Java tutorial is to demonstrate the Dropbox Java API which can be used to manage the files in a Dropbox account via Java code. This is fairly a simple Java API and easy to use.

Java-Dropbox-API

Dropbox

Do we need an introduction for Dropbox? If you are thinking about what is Dropbox, its a really popular application to store and edit documents from computer, mobile and tablet. Dropbox is one of the successful YCombinator start-ups and now worth in billions. We get 2GB free when we signup and additional storage can be purchased. This can be effectively used as a backup space. Dropbox innovated and set this domain on fire. Now we have Google Drive, Microsoft OneDrive and so many players into this business.

Dropbox Java API

Dropbox provides API for almost all popular programming platforms. API provides programmatic way to read and write to Dropbox. Java Dropbox API can be used to interact with Dropbox from our Java applications.

Dropbox Java API Example

Following example illustrates how to write a Java application to upload a file to Dropbox, create folder, check the size and other information.

  • Create Dropbox App
  • Create new Dropbox Platform app




We need to create an application in Dropbox. Login and go to the Dropbox Apps console.
  • Dropbox App Secret and Dropbox App Key


We need the Dropbox App secret and Dropbox App key to authorize with the Dropbox API. Grab them as shown below.

Dropbox API Authentication

As a prerequisite, we should create a Dropbox App and get the Drobox App Secret, App Key as detailed above. We should instantiate DbxAppInfo by passing the Dropbox App Secret and App key. Once instantiated, we can authorize using the web request using DbxWebAuthNoRedirect. We can get the authorize url and go to that URL and then allow access and get the auth code.

Allow Access


Get Access Code




Use the above access code in Java application to gain access to the Dropbox API.

public DbxClient authDropbox(String dropBoxAppKey, String dropBoxAppSecret)
throws IOException, DbxException {
DbxAppInfo dbxAppInfo = new DbxAppInfo(dropBoxAppKey, dropBoxAppSecret);
DbxRequestConfig dbxRequestConfig = new DbxRequestConfig(
"JavaDropboxTutorial/1.0", Locale.getDefault().toString());
DbxWebAuthNoRedirect dbxWebAuthNoRedirect = new DbxWebAuthNoRedirect(
dbxRequestConfig, dbxAppInfo);
String authorizeUrl = dbxWebAuthNoRedirect.start();
System.out.println("1. Authorize: Go to URL and click Allow : "
+ authorizeUrl);
System.out
.println("2. Auth Code: Copy authorization code and input here ");
String dropboxAuthCode = new BufferedReader(new InputStreamReader(
System.in)).readLine().trim();
DbxAuthFinish authFinish = dbxWebAuthNoRedirect.finish(dropboxAuthCode);
String authAccessToken = authFinish.accessToken;
dbxClient = new DbxClient(dbxRequestConfig, authAccessToken);
System.out.println("Dropbox Account Name: "
+ dbxClient.getAccountInfo().displayName);
return dbxClient;
}

Get Dropbox Size using Java

/* returns Dropbox size in GB */
public long getDropboxSize() throws DbxException {
long dropboxSize = 0;
DbxAccountInfo dbxAccountInfo = dbxClient.getAccountInfo();
// in GB :)
dropboxSize = dbxAccountInfo.quota.total / 1024 / 1024 / 1024;
return dropboxSize;
}
Upload file to Dropbox using Java
public void uploadToDropbox(String fileName) throws DbxException,
IOException {
File inputFile = new File(fileName);
FileInputStream fis = new FileInputStream(inputFile);
try {
DbxEntry.File uploadedFile = dbxClient.uploadFile("/" + fileName,
DbxWriteMode.add(), inputFile.length(), fis);
String sharedUrl = dbxClient.createShareableUrl("/" + fileName);
System.out.println("Uploaded: " + uploadedFile.toString() + " URL "
+ sharedUrl);
} finally {
fis.close();
}
}

Upload file to Dropbox using Java

public void uploadToDropbox(String fileName) throws DbxException,
IOException {
File inputFile = new File(fileName);
FileInputStream fis = new FileInputStream(inputFile);
try {
DbxEntry.File uploadedFile = dbxClient.uploadFile("/" + fileName,
DbxWriteMode.add(), inputFile.length(), fis);
String sharedUrl = dbxClient.createShareableUrl("/" + fileName);
System.out.println("Uploaded: " + uploadedFile.toString() + " URL "
+ sharedUrl);
} finally {
fis.close();
}
}

Create folder in Dropbox using Java

public void createFolder(String folderName) throws DbxException {
dbxClient.createFolder("/" + folderName);
}
List files in Dropbox using Java
public void listDropboxFolders(String folderPath) throws DbxException {
DbxEntry.WithChildren listing = dbxClient
.getMetadataWithChildren(folderPath);
System.out.println("Files List:");
for (DbxEntry child : listing.children) {
System.out.println(" " + child.name + ": " + child.toString());
}
}

Download file from Dropbox using Java

public void downloadFromDropbox(String fileName) throws DbxException,
IOException {
FileOutputStream outputStream = new FileOutputStream(fileName);
try {
DbxEntry.File downloadedFile = dbxClient.getFile("/" + fileName,
null, outputStream);
System.out.println("Metadata: " + downloadedFile.toString());
} finally {
outputStream.close();
}
}

Complete Java Dropbox API Example

package com.s2ptech.java.dropbox;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Locale;
import com.dropbox.core.DbxAccountInfo;
import com.dropbox.core.DbxAppInfo;
import com.dropbox.core.DbxAuthFinish;
import com.dropbox.core.DbxClient;
import com.dropbox.core.DbxEntry;
import com.dropbox.core.DbxException;
import com.dropbox.core.DbxRequestConfig;
import com.dropbox.core.DbxWebAuthNoRedirect;
import com.dropbox.core.DbxWriteMode;
public class JavaDropbox {
private static final String DROP_BOX_APP_KEY = "bxsicd65ljq0ymh";
private static final String DROP_BOX_APP_SECRET = "3t1lqvq1amaehb1";
DbxClient dbxClient;
public DbxClient authDropbox(String dropBoxAppKey, String dropBoxAppSecret)
throws IOException, DbxException {
DbxAppInfo dbxAppInfo = new DbxAppInfo(dropBoxAppKey, dropBoxAppSecret);
DbxRequestConfig dbxRequestConfig = new DbxRequestConfig(
"JavaDropboxTutorial/1.0", Locale.getDefault().toString());
DbxWebAuthNoRedirect dbxWebAuthNoRedirect = new DbxWebAuthNoRedirect(
dbxRequestConfig, dbxAppInfo);
String authorizeUrl = dbxWebAuthNoRedirect.start();
System.out.println("1. Authorize: Go to URL and click Allow : "
+ authorizeUrl);
System.out
.println("2. Auth Code: Copy authorization code and input here ");
String dropboxAuthCode = new BufferedReader(new InputStreamReader(
System.in)).readLine().trim();
DbxAuthFinish authFinish = dbxWebAuthNoRedirect.finish(dropboxAuthCode);
String authAccessToken = authFinish.accessToken;
dbxClient = new DbxClient(dbxRequestConfig, authAccessToken);
System.out.println("Dropbox Account Name: "
+ dbxClient.getAccountInfo().displayName);
return dbxClient;
}
/* returns Dropbox size in GB */
public long getDropboxSize() throws DbxException {
long dropboxSize = 0;
DbxAccountInfo dbxAccountInfo = dbxClient.getAccountInfo();
// in GB :)
dropboxSize = dbxAccountInfo.quota.total / 1024 / 1024 / 1024;
return dropboxSize;
}
public void uploadToDropbox(String fileName) throws DbxException,
IOException {
File inputFile = new File(fileName);
FileInputStream fis = new FileInputStream(inputFile);
try {
DbxEntry.File uploadedFile = dbxClient.uploadFile("/" + fileName,
DbxWriteMode.add(), inputFile.length(), fis);
String sharedUrl = dbxClient.createShareableUrl("/" + fileName);
System.out.println("Uploaded: " + uploadedFile.toString() + " URL "
+ sharedUrl);
} finally {
fis.close();
}
}
public void createFolder(String folderName) throws DbxException {
dbxClient.createFolder("/" + folderName);
}
public void listDropboxFolders(String folderPath) throws DbxException {
DbxEntry.WithChildren listing = dbxClient
.getMetadataWithChildren(folderPath);
System.out.println("Files List:");
for (DbxEntry child : listing.children) {
System.out.println(" " + child.name + ": " + child.toString());
}
}
public void downloadFromDropbox(String fileName) throws DbxException,
IOException {
FileOutputStream outputStream = new FileOutputStream(fileName);
try {
DbxEntry.File downloadedFile = dbxClient.getFile("/" + fileName,
null, outputStream);
System.out.println("Metadata: " + downloadedFile.toString());
} finally {
outputStream.close();
}
}
public static void main(String[] args) throws IOException, DbxException {
JavaDropbox javaDropbox = new JavaDropbox();
javaDropbox.authDropbox(DROP_BOX_APP_KEY, DROP_BOX_APP_SECRET);
System.out.println("Dropbox Size: " + javaDropbox.getDropboxSize()
+ " GB");
javaDropbox.uploadToDropbox("happy.png");
javaDropbox.createFolder("tutorial");
javaDropbox.listDropboxFolders("/");
javaDropbox.downloadFromDropbox("happy.png");
}
}

Dropbox API Example Output

1. Authorize: Go to URL and click Allow : https://www.dropbox.com/1/oauth2/authorize?locale=en_IN&client_id=bxsicd65ljq0ymh&response_type=code
2. Auth Code: Copy authorization code and input here
_-heFn6Qtl8AAAAAAAALAEtTxFPQPHNI-T0PufKYbv0
Dropbox Account Name: Joseph Kulandai R
Dropbox Size: 2 GB
Uploaded: File("/happy (4).png", iconName="page_white_picture", mightHaveThumbnail=true, numBytes=24670, humanSize="24.1 KB", lastModified="2014/12/07 13:02:12 UTC", clientMtime="2014/12/07 13:02:12 UTC", rev="82e10806e") URL https://www.dropbox.com/s/nq6ebu8mqbfr6pz/happy.png?dl=0
Files List:
happy (1).png: File("/happy (1).png", iconName="page_white_picture", mightHaveThumbnail=true, numBytes=24670, humanSize="24.1 KB", lastModified="2014/12/07 12:40:07 UTC", clientMtime="2014/12/07 12:40:07 UTC", rev="42e10806e")
happy (2).png: File("/happy (2).png", iconName="page_white_picture", mightHaveThumbnail=true, numBytes=24670, humanSize="24.1 KB", lastModified="2014/12/07 12:58:50 UTC", clientMtime="2014/12/07 12:58:50 UTC", rev="52e10806e")
happy (3).png: File("/happy (3).png", iconName="page_white_picture", mightHaveThumbnail=true, numBytes=24670, humanSize="24.1 KB", lastModified="2014/12/07 13:00:23 UTC", clientMtime="2014/12/07 13:00:24 UTC", rev="62e10806e")
happy (4).png: File("/happy (4).png", iconName="page_white_picture", mightHaveThumbnail=true, numBytes=24670, humanSize="24.1 KB", lastModified="2014/12/07 13:02:12 UTC", clientMtime="2014/12/07 13:02:12 UTC", rev="82e10806e")
happy.png: File("/happy.png", iconName="page_white_picture", mightHaveThumbnail=true, numBytes=24670, humanSize="24.1 KB", lastModified="2014/12/07 12:07:13 UTC", clientMtime="2014/12/07 12:07:14 UTC", rev="22e10806e")
tutorial: Folder("/tutorial", iconName="folder", mightHaveThumbnail=false)
Metadata: File("/happy.png", iconName="page_white_picture", mightHaveThumbnail=true, numBytes=24670, humanSize="24.1 KB", lastModified="2014/12/07 12:07:13 UTC", clientMtime="2014/12/07 12:07:14 UTC", rev="22e10806e")

Read More

Facebook Login with OAuth Authentication Using Java

This Java tutorial is to help implement authentication in Java using Facebook OAuth Login API. We will be using Java and a JSON parser API and other than that we will not use any third-party component. Facebook is not providing any sdk for Java client.

Apart from Spring Social I couldn’t find any reputable Java SDK for Facebook integration. With a Json parser we can handle everything ourselves. In this tutorial, we will see how to use Facebook to implement an authentication in a custom Java application and get Facebook profile data like name, email and gender.

Facebook Web Application


We need to create a web application in Facebook. After logging in to https://developers.facebook.com/ under Apps menu click “Create a New App


Create-Facebook-Application

Facebook Application Settings

We need to specify the application callback url in the FB settings. This will be used by the FB server on authentication to hand back control to our application.


Facebook-Application-Settings

There is a lot of discussion about how Facebook will directly call our “localhost” as it will not be visible to it. Facebook will never call the application URL directly. A request will be sent back as response to the client browser with the callback url. The browser does the request. A sequence diagram given below explains the flow of control in authentication using Facebook OAuth.

Facebook OAuth Authentication Sequence Flow




  • On access of an url or in welcome page the Facebook Login button is shown. The user will click the FB button to login into the Java web application. On click of that button a Facebook URL will be invoked.
  • Facebook will validate the application ID and then will redirect to its login page.
  • User will enter the FB login credentials and submit the form.
  • Facebook will validate the credentials and then redirect back to the browser with a request to forward to the redirect_url. Redirect_url is the URL in our application which will take care of further processing.
  • Browser will call the redirect url.
  • Redirect URL page will again call the Facebook to request for access_token.
  • Facebook on validation success will respond back with access_token.
  • Redirect URL page will again call the Facebook to request for user data by sending the access_token.
  • Facebook on validating the access_token will respond back with user data requested.
  • Redirect URL page will forward to a page showing user data in the client browser.
  • Facebook Login Page


Screen shot shown in the start of this tutorial is the login page in our application and following is the code.
<%@page import="com.s2ptech.java.social.facebook.FBConnection"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%
FBConnection fbConnection = new FBConnection();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Java Facebook Login</title>
</head>
<body style="text-align: center; margin: 0 auto;">
<div
style="margin: 0 auto; background-image: url(./img/fbloginbckgrnd.jpg); height: 360px; width: 610px;">
<a href="<%=fbConnection.getFBAuthUrl()%>"> <img
style="margin-top: 138px;" src="./img/facebookloginbutton.png" />
</a>
</div>
</body>
</html>

Application redirect URL


Following is the page the Facebook issues a redirect request to the browser.

package com.s2ptech.java.social.facebook;
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MainMenu extends HttpServlet {
private static final long serialVersionUID = 1L;
private String code="";
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException { code = req.getParameter("code");
if (code == null || code.equals("")) {
throw new RuntimeException(
"ERROR: Didn't get code parameter in callback.");
}
FBConnection fbConnection = new FBConnection();
String accessToken = fbConnection.getAccessToken(code);
FBGraph fbGraph = new FBGraph(accessToken);
String graph = fbGraph.getFBGraph();
Map<String, String> fbProfileData = fbGraph.getGraphData(graph);
ServletOutputStream out = res.getOutputStream();
out.println("<h1>Facebook Login using Java</h1>");
out.println("<h2>Application Main Menu</h2>");
out.println("<div>Welcome "+fbProfileData.get("first_name"));
out.println("<div>Your Email: "+fbProfileData.get("email"));
out.println("<div>You are "+fbProfileData.get("gender")); }
}

Facebook Get Access Token

package com.s2ptech.java.social.facebook;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
public class FBConnection {
public static final String FB_APP_ID = "234231262685378";
public static final String FB_APP_SECRET = "y2a73dede3n49uid13502f5ab8cdt390";
public static final String REDIRECT_URI = "http://localhost:8080/Facebook_Login/fbhome";
static String accessToken = "";
public String getFBAuthUrl() {
String fbLoginUrl = "";
try {
fbLoginUrl = "http://www.facebook.com/dialog/oauth?" + "client_id="
+ FBConnection.FB_APP_ID + "&redirect_uri="
+ URLEncoder.encode(FBConnection.REDIRECT_URI, "UTF-8")
+ "&scope=email";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return fbLoginUrl;
}
public String getFBGraphUrl(String code) {
String fbGraphUrl = "";
try {
fbGraphUrl = "https://graph.facebook.com/oauth/access_token?"
+ "client_id=" + FBConnection.FB_APP_ID + "&redirect_uri="
+ URLEncoder.encode(FBConnection.REDIRECT_URI, "UTF-8")
+ "&client_secret=" + FB_APP_SECRET + "&code=" + code;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return fbGraphUrl;
}
public String getAccessToken(String code) {
if ("".equals(accessToken)) {
URL fbGraphURL;
try {
fbGraphURL = new URL(getFBGraphUrl(code));
} catch (MalformedURLException e) {
e.printStackTrace();
throw new RuntimeException("Invalid code received " + e);
}
URLConnection fbConnection;
StringBuffer b = null;
try {
fbConnection = fbGraphURL.openConnection();
BufferedReader in;
in = new BufferedReader(new InputStreamReader(
fbConnection.getInputStream()));
String inputLine;
b = new StringBuffer();
while ((inputLine = in.readLine()) != null)
b.append(inputLine + "\n");
in.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("Unable to connect with Facebook "
+ e);
}
accessToken = b.toString();
if (accessToken.startsWith("{")) {
throw new RuntimeException("ERROR: Access Token Invalid: "
+ accessToken);
}
}
return accessToken;
}
}

Access Facebook Graph Profile Data

package com.s2ptech.java.social.facebook;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
public class FBGraph {
private String accessToken;
public FBGraph(String accessToken) {
this.accessToken = accessToken;
}
public String getFBGraph() {
String graph = null;
try {
String g = "https://graph.facebook.com/me?" + accessToken;
URL u = new URL(g);
URLConnection c = u.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
c.getInputStream()));
String inputLine;
StringBuffer b = new StringBuffer();
while ((inputLine = in.readLine()) != null)
b.append(inputLine + "\n");
in.close();
graph = b.toString();
System.out.println(graph);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("ERROR in getting FB graph data. " + e);
}
return graph;
}
public Map getGraphData(String fbGraph) {
Map fbProfile = new HashMap();
try {
JSONObject json = new JSONObject(fbGraph);
fbProfile.put("id", json.getString("id"));
fbProfile.put("first_name", json.getString("first_name"));
if (json.has("email"))
fbProfile.put("email", json.getString("email"));
if (json.has("gender"))
fbProfile.put("gender", json.getString("gender"));
} catch (JSONException e) {
e.printStackTrace();
throw new RuntimeException("ERROR in parsing FB graph data. " + e);
}
return fbProfile;
}
}

Facebook Authentication Success and Profile Data


Read More

How to post a Tweet in Java using Twitter REST API and Twitter4J Library

In this post, I will demonstrate how you can post a Tweet in Java  using the Twitter REST API and an open source third party twitter integration library in java called Twitter4J.
To start with you need to have an active Twitter account.


  • Log into Twitter Developer Site using your Twitter credentials.
  • Go to My Applications section and click on “Create a new application”.
  • Fill out the mandatory fields – Name, Description and Website. Accept the Terms. Fill Captcha and Submit.

twitter developer apps new application
  • Once your application is created successfully, you will be redirected to the My Applications page.
  • Click on the application you’ve just created.
  • Under the “Details” tab and “OAuth Settings”, you will find the “Consumer Key” and “Consumer Secret”. 


IMPORTANT – You should never share Consumer Key and Consumer Secret with any one.
twitter developer apps details oauth settings
  • For this example, you need a minimum of Read and Write “Access level”.
  • Click on the “Settings” tab and under “Application Type”, select the radio button option “Read and Write” or “Read, Write and Access direct messages”; which ever you like and click on the “Update this Twitter application’s settings” button at the bottom.
  • Now, go back to “Details” tab, notice that your newly set “Access level” is now reflected under the “OAuth Settings”.
  • Finally, generate your Access Token (if not already generated) by clicking the button at the bottom of “Details” tab. Do note that the “Access level” shown under the “Your access token” should match the one shown under “OAuth Settings”. Should you change your “Access level” anytime in future, you can re-generate your Access Token by clicking the button “Recreate my access token”.

So now you are all set for the coding part. You have:
  1. Consumer Key
  2. Consumer Secret
  3. Access Token
  4. Access Token Secret
For this particular example we will use Twitter REST API v1.1 and while, we can build up the necessary structure from scratch to do OAuth authentication, access token and making the raw RESTful calls all by ourselves, but we prefer to not to do this and would rather the principle of not re-inventing the wheel again. We will use a very good and easy to use Twitter Library written in Java to do the heavy lifting and save us a lot of precious time and effort.
Twitter4J is an unofficial Java library for the Twitter API. With Twitter4J, you can easily integrate your Java application with the Twitter service.
Twitter4J is:
  • 100% Pure Java - works on any Java Platform version 5 or later
  • Android platform and Google App Engine ready
  • Zero dependency : No additional jars required
  • Built-in OAuth support
  • Out-of-the-box gzip support
  • 100% Twitter API 1.1 compatible
Download Twitter4J from its official website. Unzip the downloaded folder at some location on your machine. For this example you only need the code JAR available in the lib folder.
import twitter4j.*;
import twitter4j.auth.AccessToken;   import java.io.IOException; import java.net.URL; import java.util.Arrays;   /** * This class demonstrate how you can post a Tweet in Java using the Twitter REST API and an open source third party * twitter integration library in java called Twitter4J * * User: smhumayun * Date: 7/20/13 * Time: 9:26 AM */public class TweetUsingTwitter4jExample {   public static void main(String[] args) throws IOException, TwitterException {   //Your Twitter App's Consumer Key String consumerKey = "XXXXXXXXXXXXXXXXXXXXX";   //Your Twitter App's Consumer Secret String consumerSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";   //Your Twitter Access Token String accessToken = "XXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";   //Your Twitter Access Token Secret String accessTokenSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";   //Instantiate a re-usable and thread-safe factory TwitterFactory twitterFactory = new TwitterFactory();   //Instantiate a new Twitter instance Twitter twitter = twitterFactory.getInstance();   //setup OAuth Consumer Credentials twitter.setOAuthConsumer(consumerKey, consumerSecret);   //setup OAuth Access Token twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));   //Instantiate and initialize a new twitter status update StatusUpdate statusUpdate = new StatusUpdate( //your tweet or status message "S2PTech | Java Developer | Harrison, NY | 2 Years" + " - http://s2ptech.blogspot.com/"); //attach any media, if you want to statusUpdate.setMedia( //title of media "http://s2ptech.blogspot.com/" , new URL("http://lh6.ggpht.com/-NiYLR6SkOmc/Uen_M8CpB7I/AAAAAAAAEQ8/tO7fufmK0Zg/h-1b%252520transfer%252520jobs%25255B4%25255D.png?imgmax=800").openStream());   //tweet or update status Status status = twitter.updateStatus(statusUpdate);   //response from twitter server System.out.println("status.toString() = " + status.toString()); System.out.println("status.getInReplyToScreenName() = " + status.getInReplyToScreenName()); System.out.println("status.getSource() = " + status.getSource()); System.out.println("status.getText() = " + status.getText()); System.out.println("status.getContributors() = " + Arrays.toString(status.getContributors())); System.out.println("status.getCreatedAt() = " + status.getCreatedAt()); System.out.println("status.getCurrentUserRetweetId() = " + status.getCurrentUserRetweetId()); System.out.println("status.getGeoLocation() = " + status.getGeoLocation()); System.out.println("status.getId() = " + status.getId()); System.out.println("status.getInReplyToStatusId() = " + status.getInReplyToStatusId()); System.out.println("status.getInReplyToUserId() = " + status.getInReplyToUserId()); System.out.println("status.getPlace() = " + status.getPlace()); System.out.println("status.getRetweetCount() = " + status.getRetweetCount()); System.out.println("status.getRetweetedStatus() = " + status.getRetweetedStatus()); System.out.println("status.getUser() = " + status.getUser()); System.out.println("status.getAccessLevel() = " + status.getAccessLevel()); System.out.println("status.getHashtagEntities() = " + Arrays.toString(status.getHashtagEntities())); System.out.println("status.getMediaEntities() = " + Arrays.toString(status.getMediaEntities())); if(status.getRateLimitStatus() != null) { System.out.println("status.getRateLimitStatus().getLimit() = " + status.getRateLimitStatus().getLimit()); System.out.println("status.getRateLimitStatus().getRemaining() = " + status.getRateLimitStatus().getRemaining()); System.out.println("status.getRateLimitStatus().getResetTimeInSeconds() = " + status.getRateLimitStatus().getResetTimeInSeconds()); System.out.println("status.getRateLimitStatus().getSecondsUntilReset() = " + status.getRateLimitStatus().getSecondsUntilReset()); System.out.println("status.getRateLimitStatus().getRemainingHits() = " + status.getRateLimitStatus().getRemainingHits()); } System.out.println("status.getURLEntities() = " + Arrays.toString(status.getURLEntities())); System.out.println("status.getUserMentionEntities() = " + Arrays.toString(status.getUserMentionEntities())); }   }
Once you run the above example, you will notice an output similar to this one on your console:
status.toString() = StatusJSONImpl{createdAt=Sat Jul 20 11:47:10 EDT 2013...} status.getInReplyToScreenName() = null status.getSource() = <a href="http://s2ptech.blogspot.com" rel="nofollow">SMH's Integration App</a> status.getText() = S2PTech | Java Developer | Harrison, NY | 2 Years - http://t.co/dYnQYMKBst http://t.co/y7RJyvaaqc status.getContributors() = [] status.getCreatedAt() = Sat Jul 20 11:47:10 EDT 2013 status.getCurrentUserRetweetId() = -1 status.getGeoLocation() = null status.getId() = XXXXXXXXXXXXXXXXXX status.getInReplyToStatusId() = -1 status.getInReplyToUserId() = -1 status.getPlace() = null status.getRetweetCount() = 0 status.getRetweetedStatus() = null status.getUser() = UserJSONImpl{id=XXXXXXXX, name='S M Humayun', screenName='smhumayun'...} status.getAccessLevel() = 3 status.getHashtagEntities() = [] status.getMediaEntities() = [MediaEntityJSONImpl{...}] status.getURLEntities() = [URLEntityJSONImpl{url='http://t.co/dYnQYMKBst', expandedURL='http://s2ptech.blogspot.com/', displayURL='s2ptech.blogspot.com/'}] status.getUserMentionEntities() = []
Read More

How to Shut down JBoss with the JMX Console

In order to shut down JBoss with the JMX Console:

1. Open the JMXConsole in your browser (for example: http://localhost:8080/jmx-console )


2. Navigate to the jboss.system:type=Server mbean (hint: you can probably just CTRL-F and enter type=Server in the dialog box)
3. Click on the jboss.system:type=Server


4. Scroll down to "Shutdown" and press invoke.


5. Say bye bye to JBoss

6. Ever think maybe you might want to SecureTheJmxConsole?

Read More