Friday, 13 November 2015

Functional programming for Java: getting started with Javaslang

Java is an old language and there are many new kids in the block who are challenging it on its own terrain (the JVM). However Java 8 arrived and brought a couple of interesting features. Those interesting features enabled the possibility of writing new amazing frameworks like the Spark web framework or Javaslang.

In this post we take a look at Javaslang which brings functional programming to Java.


Functional programming: what is that good for?


It seems that all the cool developers want to do some functional programming nowadays. As they wanted to use Object-oriented programming before. I personally think functional programming is great to tackle a certain set of problems, while other paradigms are better in other cases.

Thursday, 13 August 2015

Introducing Raven: An Elegant Build for Java

Rational


There's a first step that every single Java project has to go through: setting up a build system. And often before that, choosing a build system. There hasn't been much improvement in the Java world in this area for quite a while; Ant 1.1 was released in July 2000 and Maven was created in 2004.

his lack of innovation could seem strange: for non trivial projects (which most end up being after some time), writing build scripts can take a lot of time. Given that builds usually aren't shipped to users, the time spent on their maintenance can seem like time lost... but a sub-optimal build system will actually make you lose time. So down the road, the best build is the one that saves you the most time when writing, debugging, and maintaining your scripts.

Friday, 12 June 2015

How to Integrate Facebook and Twitter with Java Applications

In the modern era, web sites have become an integral part of any business—big and small. The presence of a business on the web is not necessarily enough to reach a global mass audience. Social media plays a significant role in reaching a wider audience as it has a cascading and concurrent effect. Social networking and media sites themselves are also interested in integration and communication with other web sites, exposing their APIs and allowing web sites to communicate and integrate with them. Facebook provides convenient APIs (known as Graph API) for this purpose. The Graph API is very powerful and flexible. It exposes all necessary features (known as interfaces) required for integration.

Facebook Application Model


Before going into the actual implementation, let’s understand the Facebook application model. Facebook opens its platform to developers using REST web services. As a developer, you are free to use the APIs of your choice to integrate Facebook features in your application. You are also free to use the technology of your choice. Facebook uses a proxy server model as a main integration point. The Facebook proxy server follows the following steps:
  • The web application will reside in your web/application server and you need to register the base URL in a Facebook account.
  • When the application is visited in Facebook, it will call the registered URL on the application server.
  • The application will call necessary Facebook APIs to get the relevant information.
  • Your application uses its own database data and Facebook data and render it
  • After this Facebook returns your application's output to the user

How to Get Facebook Libraries


Before we integrate Facebook with your Java application we need some third party libraries. These third party libraries will help you with integration and communication with Facebook (actually accessing Facebook application installed in their server). Different independent groups of Java and open source developers have made efficient Facebook libraries for integration purpose.

The following example will show the integration part:

Listing 1: Sample Java code for Facebook integration


package com.home.social;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import Facebook4j.Facebook;
import Facebook4j.FacebookException;
import Facebook4j.FacebookFactory;
import Facebook4j.Post;
import Facebook4j.ResponseList;
import Facebook4j.conf.Configuration;
import Facebook4j.conf.ConfigurationBuilder;

public class FacebookIntegration {

public static void main(String[] args) throws FacebookException {
// Create conf builder and set authorization and access keys
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setDebugEnabled(true);
configurationBuilder.setOAuthAppId("xxxx");
configurationBuilder.setOAuthAppSecret("xxxxx");
configurationBuilder.setOAuthAccessToken("xxxx");
configurationBuilder
.setOAuthPermissions("email, publish_stream, id, name, first_name, last_name, read_stream , generic");
configurationBuilder.setUseSSL(true);
configurationBuilder.setJSONStoreEnabled(true);

// Create configuration and get Facebook instance
Configuration configuration = configurationBuilder.build();
FacebookFactory ff = new FacebookFactory(configuration);
Facebook Facebook = ff.getInstance();

try {
// Set search string and get results
String searchPost = "MACDonaldsIndia";
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"dd_MM_yyyy_hh_mm");
String fileName = "D:\\FacebookConfigFolder\\File\\" + searchPost
+ "_" + simpleDateFormat.format(date) + ".txt";
String results = getFacebookPostes(Facebook, searchPost);
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(results);
bw.close();
System.out.println("Completed");
}
} catch (IOException e) {
e.printStackTrace();
}
}

// This method is used to get Facebook posts based on the search string set
// above
public static String getFacebookPostes(Facebook Facebook, String searchPost)
throws FacebookException {
String searchResult = "Item : " + searchPost + "\n";
StringBuffer searchMessage = new StringBuffer();
ResponseList<Post> results = Facebook.getPosts(searchPost);
for (Post post : results) {
System.out.println(post.getMessage());
searchMessage.append(post.getMessage() + "\n");
for (int j = 0; j < post.getComments().size(); j++) {
searchMessage.append(post.getComments().get(j).getFrom()
.getName()
+ ", ");
searchMessage.append(post.getComments().get(j).getMessage()
+ ", ");
searchMessage.append(post.getComments().get(j).getCreatedTime()
+ ", ");
searchMessage.append(post.getComments().get(j).getLikeCount()
+ "\n");
}
}
String feedString = getFacebookFeed(Facebook, searchPost);
searchResult = searchResult + searchMessage.toString();
searchResult = searchResult + feedString;
return searchResult;
}

// This method is used to get Facebook feeds based on the search string set
// above
public static String getFacebookFeed(Facebook Facebook, String searchPost)
throws FacebookException {
String searchResult = "";
StringBuffer searchMessage = new StringBuffer();
ResponseList<Post> results = Facebook.getFeed(searchPost);
for (Post post : results) {
System.out.println(post.getMessage());
searchMessage.append(post.getFrom().getName() + ", ");
searchMessage.append(post.getMessage() + ", ");
searchMessage.append(post.getCreatedTime() + "\n");
}
searchResult = searchResult + searchMessage.toString();
return searchResult;
}

// This method is used to create JSON object from data string
public static String stringToJson(String data) {
JsonConfig cfg = new JsonConfig();
try {
JSONObject jsonObject = JSONObject.fromObject(data, cfg);
System.out.println("JSON = " + jsonObject.toString());
} catch (Exception e) {
e.printStackTrace();
}
return "JSON Created";
}
}

Integration with Twitter


In order to integrate your application with Twitter, we need to use the library - Twitter4j. This is a well documented library that helps any Java developer to integrate his/her application with Twitter. As a developer you need to follow certain steps:
  • Send a request to Twitter asking for a token. This request should carry both a consumer key and a secret key.
  • Store the response received from Twitter.
  • Once the response is received, the authentication URL is extracted from the response.
  • The user then needs to be redirected to the authentication URL, so that he can sign in.
  • User signs in and gets a Personal Identification Number or PIN.
  • User then enters PIN in the application.
  • Once the PIN is entered the application should ask Twitter for a security token, providing consumer parameters as above as well as the previously stored request token and the PIN.
  • Once the token is received, every request going to Twitter should have this token along with the PIN

Listing 2: Sample Java code for Twitter integration


package com.home.social;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.List;

import Twitter4j.Query;
import Twitter4j.QueryResult;
import Twitter4j.Status;
import Twitter4j.Twitter;
import Twitter4j.TwitterFactory;
import Twitter4j.conf.ConfigurationBuilder;

public class TwitterIntegration {
public static void main(String[] args) throws Exception{
// Create configuration builder and set key, token etc
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("xxx");
        cb.setOAuthConsumerSecret("xxxx");
        cb.setOAuthAccessToken("xxxxx");
        cb.setOAuthAccessTokenSecret("xxxx");

// Create Twitter instance
Twitter Twitter = new TwitterFactory(cb.build()).getInstance();

// Create file writer and buffer writer
        FileWriter fstream = new FileWriter("Twitterstream.txt",true);
        BufferedWriter out = new BufferedWriter(fstream);

// Create Query object and set search string
Query query = new Query("");
query.setQuery("#USAirways");

// Get query result
QueryResult qr = Twitter.search(query);

// Get tweets and write in the file
while(qr.hasNext()){
qr.nextQuery();
List<Status> tweets = qr.getTweets();

for (Status t: tweets){
System.out.println(t.getId() + " - " + t.getCreatedAt() + ": " + t.getText());

out.write("\n"+t.getId()+",");
out.write("\t"+t.getText()+",");
out.write("\t"+t.getUser()+",");
}
}
try{
Thread.sleep(1000*60*15);
}catch(Exception e) {}
}
}

Friday, 10 April 2015

Determining File Types in Java

Programmatically determining the type of a file can be surprisingly tricky and there have been many content-based file identification approaches proposed and implemented. There are several implementations available in Java for detecting file types and most of them are largely or solely based on files’ extensions. This post looks at some of the most commonly available implementations of file type detection in Java.

Several approaches to identifying file types in Java are demonstrated in this post. Each approach is briefly described, illustrated with a code listing, and then associated with output that demonstrates how different common files are typed based on extensions. Some of the approaches are configurable, but all examples shown here use “default” mappings as provided out-of-the-box unless otherwise stated.

Tuesday, 17 March 2015

Create your own AOP in Java

Introduction


As you know AOP is one of the best features provided by Spring framework which provides utmost flexibility while achieving cross cutting concerns. Have you thought of how AOP works in Spring ? Sometimes this is the question asked in case of senior level technical interview. Sometimes this question becomes more significant when it comes to only core java. Recently one of my friend went to attend the interview and he faced an embarrassing question about how to use AOP only in core java without using Spring and related libraries. In this article I will provide you an outline about how to create your own AOP only in core java of course with certain limitations. This is not a comparative study between Spring AOP and Java AOP. However you can achieve AOP in java to certain extent using proper design patterns.