Monday, 29 July 2013

No-Arguments Default Constructor and Nested Classes (Non-Static Inner Class, Local Class, Anonymous Class)

Last week, I was working with different type of nested classes and found an interesting fact (which I overlooked up-till now) regarding no-arguments default constructor in some of the nested classes.

Before, I illustrate the example, as a refresher, lets briefly look how many types of Nested Classes are supported in Java.

Types of Nested Classes supported in Java:

  1. Static Nested Class – a static class nested inside another class
  2. Non-Static Nested Class – also called Inner Class – a non static class nested inside another class. Besides that, there are two other, special kinds of Inner Classes:
    1. Local Class – a named Inner Class
    2. Anonymous Class – an un-named Inner Class

Consider following class, in which I tried to create all different sorts of test cases regarding nested classes. Although I don’t wanted to add any extra code to illustrate these cases, but in order to gain “access” to certain members, I had to open doors here and there, please ignore them.

/**
* No-Arguments Default Constructor and Nested Classes (Non-Static Inner Class, Local Class, Anonymous Class)
* http://codeoftheday.blogspot.com/2013/07/no-arguments-default-constructor-and.html
*/
package com.smhumayun.codeoftheday.NestedClassesExample;
interface AnInterface {}
public class TopLevelClass {
static class StaticClassInsideTopLevelClass {}
class NonStaticClassInsideTopLevelClass {}
AnInterface anonymousClassObj1 = new AnInterface() {};
static {
class ClassInsideStaticBlock {}
AnInterface anonymousClassObj2 = new AnInterface() {}; //anonymous class
/*Ignore*/ classInsideStaticBlock = ClassInsideStaticBlock.class;
/*Ignore*/ anonymousClassInsideStaticBlock = anonymousClassObj2.getClass();
}
static void staticMethod () {
class ClassInsideStaticMethod {}
AnInterface anonymousClassObj3 = new AnInterface() {}; //anonymous class
/*Ignore*/ classInsideStaticMethod = ClassInsideStaticMethod.class;
/*Ignore*/ anonymousClassInsideStaticMethod = anonymousClassObj3.getClass();
}
/*Ignore*/ static { staticMethod(); }
void nonStaticMethod () {
class ClassInsideNonStaticMethod {}
AnInterface anonymousClassObj4 = new AnInterface() {}; //anonymous class
/*Ignore*/ classInsideNonStaticMethod = ClassInsideNonStaticMethod.class;
/*Ignore*/ anonymousClassInsideNonStaticMethod = anonymousClassObj4.getClass();
}
/*Ignore*/ static { new TopLevelClass().nonStaticMethod(); }
/*Ignore*/ public static Class classInsideStaticBlock;
/*Ignore*/ public static Class anonymousClassInsideStaticBlock;
/*Ignore*/ public static Class classInsideStaticMethod;
/*Ignore*/ public static Class anonymousClassInsideStaticMethod;
/*Ignore*/ public static Class classInsideNonStaticMethod;
/*Ignore*/ public static Class anonymousClassInsideNonStaticMethod;
}

And then I create following Test Runner sort-of a class which basically access different nested test classes created inside the top level class above and to display their information for our analysis.

/**
* No-Arguments Default Constructor and Nested Classes (Non-Static Inner Class, Local Class, Anonymous Class)
* http://codeoftheday.blogspot.com/2013/07/no-arguments-default-constructor-and.html
*/
package com.smhumayun.codeoftheday.NestedClassesExample;
import java.lang.reflect.Constructor;
import static com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass.*;
public class Test {
public static void main(String[] args) {
displayClassInfo("Top Level Class", TopLevelClass.class);
displayClassInfo("Static Nested Class", StaticClassInsideTopLevelClass.class);
displayClassInfo("Inner Class or Non Static Nested Class", TopLevelClass.NonStaticClassInsideTopLevelClass.class);
displayClassInfo("Anonymous Class inside Top Level Class", new TopLevelClass().anonymousClassObj1.getClass());
displayClassInfo("Class inside static block", classInsideStaticBlock);
displayClassInfo("Anonymous Class inside static block", anonymousClassInsideStaticBlock);
displayClassInfo("Class inside static method", classInsideStaticMethod);
displayClassInfo("Anonymous Class inside static method", anonymousClassInsideStaticMethod);
displayClassInfo("Class inside non static method", classInsideNonStaticMethod);
displayClassInfo("Anonymous Class inside non static method", anonymousClassInsideNonStaticMethod);
}
static void displayClassInfo (String classInfo, Class clazz) {
StringBuilder sb = new StringBuilder("\n").append(classInfo)
.append("\n\t").append(clazz.getName()).append(" [ ")
.append(clazz.isMemberClass() ? "Member Class " : "")
.append(clazz.isLocalClass() ? "Local Class " : "")
.append(clazz.isAnonymousClass() ? "Anonymous Class " : "")
.append(clazz.isSynthetic() ? "Synthetic Class " : "")
.append("]")
.append(clazz.getDeclaringClass() != null ? "\n\tDeclared by class - " + clazz.getDeclaringClass().getSimpleName() : "")
.append(clazz.getEnclosingClass() != null ? "\n\tEnclosed in class - " + clazz.getEnclosingClass().getSimpleName() : "")
.append(clazz.getEnclosingConstructor() != null ? "\n\tEnclosed in constructor - " + clazz.getEnclosingConstructor().toGenericString() : "")
.append(clazz.getEnclosingMethod() != null ? "\n\tEnclosed in method - " + clazz.getEnclosingMethod().toGenericString() : "")
.append("\n\tConstructors:")
;
Constructor<?>[] constructors = clazz.getDeclaredConstructors();
for (Constructor<?> constructor : constructors) {
sb.append("\n\t\t").append(constructor.toGenericString());
}
System.out.println(sb);
}
}

When you run the Test class, following output will be displayed on your console:

# No-Arguments Default Constructor and Nested Classes (Non-Static Inner Class, Local Class, Anonymous Class)
# http://codeoftheday.blogspot.com/2013/07/no-arguments-default-constructor-and.html
Top Level Class
com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass [ ]
Constructors:
public com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass()
Static Nested Class
com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass$StaticClassInsideTopLevelClass [ Member Class ]
Declared by class - TopLevelClass
Enclosed in class - TopLevelClass
Constructors:
com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass$StaticClassInsideTopLevelClass()
Inner Class or Non Static Nested Class
com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass$NonStaticClassInsideTopLevelClass [ Member Class ]
Declared by class - TopLevelClass
Enclosed in class - TopLevelClass
Constructors:
com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass$NonStaticClassInsideTopLevelClass(com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass)
Anonymous Class inside Top Level Class
com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass$1 [ Anonymous Class ]
Enclosed in class - TopLevelClass
Constructors:
com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass$1(com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass)
Class inside static block
com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass$1ClassInsideStaticBlock [ Local Class ]
Enclosed in class - TopLevelClass
Constructors:
com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass$1ClassInsideStaticBlock()
Anonymous Class inside static block
com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass$2 [ Anonymous Class ]
Enclosed in class - TopLevelClass
Constructors:
com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass$2()
Class inside static method
com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass$1ClassInsideStaticMethod [ Local Class ]
Enclosed in class - TopLevelClass
Enclosed in method - static void com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass.staticMethod()
Constructors:
com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass$1ClassInsideStaticMethod()
Anonymous Class inside static method
com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass$3 [ Anonymous Class ]
Enclosed in class - TopLevelClass
Enclosed in method - static void com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass.staticMethod()
Constructors:
com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass$3()
Class inside non static method
com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass$1ClassInsideNonStaticMethod [ Local Class ]
Enclosed in class - TopLevelClass
Enclosed in method - void com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass.nonStaticMethod()
Constructors:
com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass$1ClassInsideNonStaticMethod(com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass)
Anonymous Class inside non static method
com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass$4 [ Anonymous Class ]
Enclosed in class - TopLevelClass
Enclosed in method - void com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass.nonStaticMethod()
Constructors:
com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass$4(com.smhumayun.codeoftheday.NestedClassesExample.TopLevelClass)

Note following interesting observations:

  1. All nested classes, regardless of their type mentioned above, are mechanically generated by the compiler and hence a “$” in their fully qualified names. [Java Language Specification 3.8]
  2. Among all nested classes, static nested class is the only one that “retains” its constructor’s original signatures in the original form. All the other nested classes “looses” their constructor’s original signatures.
  3. For all the nested classes, other than the static nested class, following is true:
    1. If your nested class has no constructors defined, then don’t expect the default no-argument constructor to be available in these classes.
    2. If you nested class has one or more constructors defined, then don’t expect them to “retain” their original constructor signatures after compilation or at runtime.
    3. Why? because, java compiler, when compiles these nested classes, it “adds” an additional parameter at the very first (0 – zero) index of ALL constructors of a nested class. This additional parameter is actually the enclosing object’s reference. [Java Language Specification 8.1.3]

Now, if you refer to your Java Bean definition:

JavaBeans are are classes that are (1) serializable, (2) have a 0-argument constructor, and (3) allow access to properties using getter and setter methods.

So, by definition, all your non-static inner classes, local classes and anonymous classes disqualifies as JavaBeans.

Thursday, 25 July 2013

Emulating Multiple Inheritance in Java using ‘Program To Interface’ Design Principle, Object Composition and Method Delegation

In this post I will demonstrate the use of ‘Program To Interface’ Design Principle and Object Composition, to emulate Multiple Inheritance in Java. For a refresher on these topics, there’s a very informative post on Artima Developer where Erich Gamma, co-author of the landmark book, Design Patterns, talks with Bill Venners about two design principles: program to an interface, not an implementation, and favor object composition over class inheritance.

For our example, consider different type of Employment Roles available in a typical Software Consulting Firm. To simplify things a bit, assume there are 4 roles; Developer, Tester, Architect and Project Manager. All of these are Employee(s) of the Software Consulting Form i.e. the employer.

Thinking in Object Oriented, you can easily depict that Employee is the Base or Parent Class and Developer, Tester, Architect and ProjectManager are Derived or Child Classes.

v1

/**
* Emulating Multiple Inheritance in Java using ‘Program To Interface’ Design Principle, Object Composition and Method Delegation
* http://codeoftheday.blogspot.com/2013/07/emulating-multiple-inheritance-in-java.html
*/
package smhumayun.codeoftheday.MultipleInheritanceExample;
public class Employee {...}
public class Architect extends Employee {...}
public class Developer extends Employee {...}
public class ProjectManager extends Employee {...}
public class Tester extends Employee {...}

This is the simple example of (Single) Inheritance in Java i.e. all the five classes are inheriting a single Parent Class. All the five? yes Employee is inheriting from Object class following the rules of Java Language Specification that if a class is not inherited from any other class then by default it will be inherited from the Object class.

Now, in real world, this happens quite often and specially in a Software Consulting Firm that a person can “perform” the roles of more than one types. For example, given the circumstances and the skill sets:

  • A senior technical-management resource can perform the roles of Project Manager, Architect and Developer.
  • A senior technical resource can perform the roles of Architect and Developer.
  • Project Manager, Architect and Developer can wear the cap of Tester anytime during the project lifecycle.
  • So on and so forth

To simplify, let us consider one of the above cases, where we wanted to have a new “role”, which we call “ADP” and this role has the responsibilities of Architect, Developer and Project Manager combined. See the picture below:

v1

/**
* Emulating Multiple Inheritance in Java using ‘Program To Interface’ Design Principle, Object Composition and Method Delegation
* http://codeoftheday.blogspot.com/2013/07/emulating-multiple-inheritance-in-java.html
*/
package smhumayun.codeoftheday.MultipleInheritanceExample;
public class ADP extends Architect {...}
//Multiple Inheritance not allowed:
//public class ADP extends Architect, Developer, ProjectManager {...}

The Software Design depicted above is what we want to achieve, but because multiple inheritance is not supported in Java, we will try “emulate” Multiple Inheritance to allow “ADP” to inherit from Architect, Developer and ProjectManager classes.

java interface classJava allows us to emulate the behavior of Multiple Inheritance through the use of Interfaces. Java Interfaces are a good way to separate the contract from its actual implementation and which ever the class “implements” the interface will enter into a binding contract to provide implementation of all the methods “declared” in that particular interface, otherwise declares itself as an “abstract” class – an incomplete, non instantiable class.

While a Class in Java can not “extends”/inherit from more than one Classes, it can “implements”/inherit more than one Interfaces. If we can split the contract (method declarations) from the actual implementation (method definitions) of all of our classes above, we would be in a good position to at-least inherit/implement contracts from multiple interfaces – this is also referred to as “Multiple Interface Inheritance”.

/**
* Emulating Multiple Inheritance in Java using ‘Program To Interface’ Design Principle, Object Composition and Method Delegation
* http://codeoftheday.blogspot.com/2013/07/emulating-multiple-inheritance-in-java.html
*/
package smhumayun.codeoftheday.MultipleInheritanceExample;
public interface Employee {
int getEmployeeId();
void setEmployeeId(int employeeId);
}
//-----------------------------------------------------------
package smhumayun.codeoftheday.MultipleInheritanceExample;
public class EmployeeImpl implements Employee {
private int employeeId;
@Override
public int getEmployeeId() {
return employeeId;
}
@Override
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
}

The Software Design depicted below now shows each of our classes are now split up into a set of Interface and a corresponding Implementation Class.

v3

Note that Interfaces alone, now form the same hierarchy as show in the first picture above. Similarly implementation Classes alone, form the same hierarchy as shown in the first picture above.

Now, let us make changes to our Software Design to accommodate the ADP Class introduced in second picture above.

v4

/**
* Emulating Multiple Inheritance in Java using ‘Program To Interface’ Design Principle, Object Composition and Method Delegation
* http://codeoftheday.blogspot.com/2013/07/emulating-multiple-inheritance-in-java.html
*/
package smhumayun.codeoftheday.MultipleInheritanceExample;
public interface ADP extends Employee, Architect, Developer, ProjectManager {
}
//----------------------------------------------------------------------------
package smhumayun.codeoftheday.MultipleInheritanceExample;
public class ADPImpl implements ADP {
@Override
public void design() { /*implementation?*/ }
@Override
public void develop() { /*implementation?*/ }
@Override
public void manage() { /*implementation?*/ }
@Override
public int getEmployeeId() { /*implementation?*/ return 0; }
@Override
public void setEmployeeId(int employeeId) { /*implementation?*/ }
}

Notice how ADP (now an Interface) “extends”/inherits from more than one Parent Interfaces (Emlpoyee, Architect, Developer & ProjectManager). This is very nice as far as Multiple Interface Inheritance is concerned. Our target Interface i.e. ADP now have the method declarations of all the four other Interfaces and following is possible as far ADP Interface alone is concern:

ADP refAdp;
...
refAdp.getEmploeeId();
refAdp.setEmployeeId(1);
refAdp.design();
refAdp.develop();
refAdp.manage();

The last unresolved issue now is the Multiple Implementation Inheritance i.e. support for a Class to inherit from more than one Classes. For that we will use Object Composition and Delegation principles of OOP.

Now, our ADPImpl class have to fulfill the contracts of 4 additional Interfaces (besides its very own ADP Interface) – Employee, Architect, Developer and ProjectManager. Note that all of the methods declared in each of the Interfaces have their matching implementation already available in corresponding Implementation classes. And, our intent here is to re-use that implementation rather copy-paste or duplicate the code. Once way to re-use implementation is to inherit the class that contains the required implementation, but java allows us to inherit implementations from only one class.

Question: Which one of these 4 classes (Employee, Architect, Developer, ProjectManager) is the best candidate for Implementation Inheritance for ADP class and why?

Answer: Employee class, because person with ADP role (or any other role) “is an” Employee first. A person who is not an Employee can not work as an Architect, Developer, ADP, etc..

So let us now extend/inherit our ADPImpl class from EmployeeImpl class.

v5

/**
* Emulating Multiple Inheritance in Java using ‘Program To Interface’ Design Principle, Object Composition and Method Delegation
* http://codeoftheday.blogspot.com/2013/07/emulating-multiple-inheritance-in-java.html
*/
package smhumayun.codeoftheday.MultipleInheritanceExample;
public class ADPImpl extends EmployeeImpl implements ADP {
@Override
public void design() { /*implementation?*/ }
@Override
public void develop() { /*implementation?*/ }
@Override
public void manage() { /*implementation?*/ }
}

One down! 3 more to go Smile

We have now exhaust the Implementation Inheritance option and can not use it any more for ADPImpl class, so lets move on to Object Composition.

Object composition is a tightly coupled form of association and it requires ownership of the composed object. So much that the Composed Object may not exists without the existence of Container Object, and if a Container object dies than the Composed object should be disposed off as well. This form of relationship is also called “has a” relationship.

{Do note that there’s another loosely coupled form of association available and is called “Aggregation”}

ADP “is an” Employee and ADP “has an” Architect role – make sense?

Look at the picture above, ADPImpl is still complaining us to provide the implementation for design(), develop() and manage() methods which are declared in Architect, Developer and ProjectManager Interfaces. We already have the implementation of these methods in implementation classes ArchitectImpl, DeveloperImpl and ProjectManagerImpl respectively.

We will now use the Object Composition and Method Delegation to try to re-use the implementations rather than copy-pasting or duplicating the logic/code.

v6

/**
* Emulating Multiple Inheritance in Java using ‘Program To Interface’ Design Principle, Object Composition and Method Delegation
* http://codeoftheday.blogspot.com/2013/07/emulating-multiple-inheritance-in-java.html
*/
package smhumayun.codeoftheday.MultipleInheritanceExample;
public class ADPImpl extends EmployeeImpl implements ADP {
private ArchitectImpl architectImplDelegate;
private DeveloperImpl developerImplDelegate;
private ProjectManagerImpl projectManagerImplDelegate;
@Override
public void design() { architectImplDelegate.design(); }
@Override
public void develop() { developerImplDelegate.develop(); }
@Override
public void manage() { projectManagerImplDelegate.manage(); }
}

DOWNLOAD COMPLETE SOURCE FROM HERE

UPDATE: I’ve published an open source project “Project MI+” which will helps you in (functionally) inherit from multiple classes, saving you from writing a lot of boiler late code. Importantly, it uses all of the above mentioned concepts to achieve that, plus a of couple more to come even closer.

Using Project MI+, you can re-write ADP interface as follows:

package smhumayun.codeoftheday.MultipleInheritanceExample;

@MISupport(parentClasses={EmployeeImpl.class, ArchitectImpl.class, DeveloperImpl.class, ProjectManagerImpl.class})
public interface ADP extends Employee, Architect, Developer, ProjectManager {
}

You won’t need ADPImpl now and can instantiate ADP objects using Project MI+’s factory as follows:

ADP adp = miFactory.newInstance(ADP.class);
adp.getEmployeeId();
adp.design();
adp.develop();
adp.manage();

Tuesday, 23 July 2013

Quick and Easy Integration of Google URL Shortener API in your Java Applications using Scribe-Java and GSon

This post is about a quick and easy integration of Google’s URL Shortener Service/API in your Java Applications using popular APIs like Scribe-Java and Google’s GSon.

The good part about this integration is that you don’t need to do additional steps to register your application with the Service APIs, because in this case, the Google’s URL Shortener Service can be accessed “anonymously”, with out having the need to register the application and performing the authentication and authorization steps.

google url shortener - goo.gl.com

First Download:

Create a new project in IDE of your choice and add above downloaded JAR files to your project’s build/class path.

GoogleUrlShortenerApiIntegrationUsingScribeExample.java:

/**
* Quick and Easy Integration of Google URL Shortener API in your Java Applications using Scribe-Java and GSon
* http://codeoftheday.blogspot.com/2013/07/quick-and-easy-integration-of-google.html
*/
package smhumayun.codeoftheday.google.urlshortener;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.GoogleApi;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;
import java.lang.reflect.Type;
import java.util.Map;
/**
* This class demonstrate quick and Easy Integration of Google URL Shortener API in your Java Applications
* using Scribe-Java and GSon APIs
*
* User: smhumayun
* Date: 7/23/13
* Time: 5:27 PM
*/
public class GoogleUrlShortenerApiIntegrationUsingScribeAndGsonExample {
/**
* Main Method
*
* @param args arguments
*/
public static void main(String[] args) {
//Instantiating the oAuth Service of Scribe-Java API
OAuthService oAuthService = new ServiceBuilder()
//Google Api Provider - Google's URL Shortener API is part of Google Platform APIs
.provider(GoogleApi.class)
/*
Using "anonymous" as API Key & Secret because Google's URL Shortener service
does not necessarily requires App identification and/or User Information Access
*/
.apiKey("anonymous")
.apiSecret("anonymous")
//OAuth 2.0 scope for the Google URL Shortener API
.scope("https://www.googleapis.com/auth/urlshortener")
//build it!
.build();
//Instantiating oAuth Request of type POST and with Google URL Shortener API End Point URL
OAuthRequest oAuthRequest = new OAuthRequest(Verb.POST, "https://www.googleapis.com/urlshortener/v1/url");
//set the content type header to application/json - this is the type of content you are sending as payload
oAuthRequest.addHeader("Content-Type", "application/json");
//Preparing JSON payload to send url to Google URL Shortener
String json = "{\"longUrl\": \"http://h1b-work-visa-usa.blogspot.com/\"}";
//add xml payload to request
oAuthRequest.addPayload(json);
//send the request
Response response = oAuthRequest.send();
//print the response from server
System.out.println("response.getBody() = " + response.getBody());
//determining the generic type of map
Type typeOfMap = new TypeToken<Map<String, String>>() {}.getType();
//desrialize json to map
Map<String, String> responseMap = new GsonBuilder().create().fromJson(response.getBody(), typeOfMap);
//print id which is actually the shortened url
System.out.println("Shortened URL = " + responseMap.get("id"));
}
}

Compile and Run the project. You will notice an output similar to the one below in your IDE’s console:

# Quick and Easy Integration of Google URL Shortener API in your Java Applications using Scribe-Java and GSon
# http://codeoftheday.blogspot.com/2013/07/quick-and-easy-integration-of-google.html
response.getBody() = {
"kind": "urlshortener#url",
"id": "http://goo.gl/ePeF0j",
"longUrl": "http://h1b-work-visa-usa.blogspot.com/"
}
Shortened URL = http://goo.gl/ePeF0j

Copy the Shortened URL, open a browser of your choice and paste the Shortened URL into the browser’s Address Bar and press ENTER. You will notice how Google’s URL Shortener Service resolves your Shortened URL to your original (longer) URL.

Shortened URL:

google url shortener - shortened url

Original Longer URL resolved by Goo.gl:

google url shortener - original longer url

DOWNLOAD COMPLETE SOURCE FROM HERE

Monday, 22 July 2013

Maven, Struts2 Annotations and Tiles Integration Example via Convention / Codebehind / Zero Config plugin using Eclipse IDE

In this example, I will demonstrate how you can use Struts2 Annotations and Conventions alone to avoid XML Configuration. I will also integrate Struts2 Tiles Plugin, because I’ve seen a number of people struggling when it comes to Tiles integration with Struts2 Annotation and Convention based projects. Do note that Struts2 Convention Plugin has replaced the older Codebehind plugin and Zero Config Plugin.

The Struts2 Convention Plugin provides the following features:

  • Action location by package naming conventions
  • Result (JSP, FreeMarker, etc) location by naming conventions
  • Class name to URL naming convention
  • Package name to namespace convention
  • SEO compliant URLs (i.e. my-action rather than MyAction)
  • Action name overrides using annotations
  • Interceptor overrides using annotations
  • Namespace overrides using annotations
  • XWork package overrides using annotations
  • Default action and result handling (i.e. /products will try com.example.actions.Products as well as com.example.actions.products.Index)

The Convention Plugin should require no configuration to use. Many of the conventions can be controlled using configuration properties and many of the classes can be extended or overridden.

Ok, let’s start then.

Open Eclipse IDE and create a new Maven project.

eclipse new other project

eclipse new maven project

eclipse new maven project - create a simple maven project (skip archetype selection)

eclipse new maven project - configure project

Note that I’ve selected the “war” Packaging above.

From the eclipse IDE’s Project Explorer, double click on “pom.xml” file. It is your project’s Maven POM file and it should look like:

<!--
Maven, Struts2 Annotations and Tiles Integration Example via Convention / Codebhind / Zero Config plugin using Eclipse IDE
http://codeoftheday.blogspot.com/2013/07/maven-struts2-annotations-and-tiles.html
-->
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>smhumayun.codeoftheday</groupId>
<artifactId>Struts2AnnotationAndTilesIntegrationExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>CodeOfTheDay.blogspot.com - Struts2 Annotation And Tiles Integration Example</name>
<description>http://codeoftheday.blogspot.com</description>
</project>

This is the bare bone maven pom file. Now, add following three dependencies to it:

  1. Struts2 Core
  2. Struts2 Convention Plugin
  3. Struts2 Tiles Plugin
<!--
Maven, Struts2 Annotations and Tiles Integration Example via Convention / Codebhind / Zero Config plugin using Eclipse IDE
http://codeoftheday.blogspot.com/2013/07/maven-struts2-annotations-and-tiles.html
-->
<dependencies>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.3.15.1</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-convention-plugin</artifactId>
<version>2.3.15.1</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-tiles-plugin</artifactId>
<version>2.3.15.1</version>
</dependency>
</dependencies>

maven directory structure

Now,

Create a package structure as you like. However, make sure the immediate parent package that contains your Struts2 Actions should be named either of the following (refer to directory structure image above):

  • action
  • actions
  • struts
  • struts2

Why? because by “Convention”, Struts2 will “scan” for Action(s) in package(s) that “exactly” matches the names mentioned above. Yes, you can do all sorts of overriding and customizations, but you have to do that using XML Configuration (file called Struts.xml), which we want to avoid in our example. So, we will stick to the “Conventions” Smile

Create a new Action class. Make sure you follow these “Conventions”:

  • Your Action class must suffix with “Action”
    • For example: MyAction, ListOfAction, DownloadAction, etc..
  • OR, your class must implements “com.opensymphony.xwork2.Action” interface

(refer to directory structure image above) I prefer first one because in that case I’m less coupled with the Struts2 API. Lesser the “invasion” by a framework, the better!

Also, for the very same reason, and to demonstrate the plain POJO integration concept by Struts2, I avoid extending my Action class with any of the Struts2 support classes (i.e. com.opensymphony.xwork2.ActionSupport).

/**
* Maven, Struts2 Annotations and Tiles Integration Example via Convention / Codebhind / Zero Config plugin using Eclipse IDE
* http://codeoftheday.blogspot.com/2013/07/maven-struts2-annotations-and-tiles.html
*/
package smhumayun.codeoftheday.struts2_annotations_and_tiles_integration_example.actions;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
public class MainAction {
private String serverTime;
private static int totalVisits;
@Action(value="/showTime", results={@Result(name="success", location="showTime.tiles", type="tiles")})
public String showServerTime ()
{
serverTime = SimpleDateFormat.getDateTimeInstance().format(new Date(System.currentTimeMillis()));
System.out.println("serverTime = " + serverTime);
return "success";
}
@Action(value="/showVisits", results={@Result(name="success", location="showVisits.tiles", type="tiles")})
public String showTotalVisits ()
{
System.out.println("totalVisits = " + ++totalVisits);
return "success";
}
public String getServerTime() {
return serverTime;
}
public void setServerTime(String serverTime) {
this.serverTime = serverTime;
}
public int getTotalVisits() {
return totalVisits;
}
public void setTotalVisits(int totalVisits) {
MainAction.totalVisits = totalVisits;
}
}

Two important things to notice in the class above are:

  • @Result (…, type=”tiles”) – This is to instruct Struts2 that the result is of “Tiles” type and to enable or configure that type you will have to create a minimal Struts XML Configuration file called struts.xml, because this particular configuration can not be done using Struts2 Annotations:
    <!--
    Maven, Struts2 Annotations and Tiles Integration Example via Convention / Codebhind / Zero Config plugin using Eclipse IDE
    http://codeoftheday.blogspot.com/2013/07/maven-struts2-annotations-and-tiles.html
    -->
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
    <struts>
    <constant name="struts.convention.default.parent.package" value="codeoftheday.blogspot.com"/>
    <package name="codeoftheday.blogspot.com" extends="struts-default">
    <result-types>
    <result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
    </result-types>
    </package>
    </struts>
  • @Result (…, location=”your-tile-definition-name”) – The location refers to one of the tiles defined in your tiles definition file.

Create (if not already created) a web.xml, Java Web Application Deployment Descriptor, under /src/main/webapp/WEB-INF/ and add following to it:

  1. Struts2 Standard Filer Mapping
  2. Tiles Configuration
  3. Tiles Listener
<!--
Maven, Struts2 Annotations and Tiles Integration Example via Convention / Codebhind / Zero Config plugin using Eclipse IDE
http://codeoftheday.blogspot.com/2013/07/maven-struts2-annotations-and-tiles.html
-->
<!-- Struts2 Standard Filer -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Tiles Configuration -->
<context-param>
<param-name>org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG</param-name>
<param-value>/WEB-INF/tiles.xml</param-value>
</context-param>
<!-- Tiles Listener -->
<listener>
<listener-class>org.apache.struts2.tiles.StrutsTilesListener</listener-class>
</listener>

Create your tiles definition file and define all tiles definition:

<!--
Maven, Struts2 Annotations and Tiles Integration Example via Convention / Codebhind / Zero Config plugin using Eclipse IDE
http://codeoftheday.blogspot.com/2013/07/maven-struts2-annotations-and-tiles.html
-->
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
<definition name="baseLayout" template="/WEB-INF/content/tiles/BaseLayout.jsp">
<put-attribute name="title" value="" />
<put-attribute name="header" value="/WEB-INF/content/tiles/Header.jsp" />
<put-attribute name="body" value="" />
<put-attribute name="footer" value="/WEB-INF/content/tiles/Footer.jsp" />
</definition>
<definition name="showTime.tiles" extends="baseLayout">
<put-attribute name="title" value="Server Time" />
<put-attribute name="body" value="/WEB-INF/content/DisplayServerTime.jsp" />
</definition>
<definition name="showVisits.tiles" extends="baseLayout">
<put-attribute name="title" value="Total Visits" />
<put-attribute name="body" value="/WEB-INF/content/DisplayTotalVisits.jsp" />
</definition>
</tiles-definitions>

Create following JSP files:

BaseLayout.jsp:

<!--
Maven, Struts2 Annotations and Tiles Integration Example via Convention / Codebhind / Zero Config plugin using Eclipse IDE
http://codeoftheday.blogspot.com/2013/07/maven-struts2-annotations-and-tiles.html
-->
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Struts2 Annotations and Tiles Integration Example - <tiles:insertAttribute name="title" ignore="true" /></title>
</head>
<body>
<tiles:insertAttribute name="header" />
<tiles:insertAttribute name="body" />
<tiles:insertAttribute name="footer" />
</body>
</html>

Header.jsp:

<!--
Maven, Struts2 Annotations and Tiles Integration Example via Convention / Codebhind / Zero Config plugin using Eclipse IDE
http://codeoftheday.blogspot.com/2013/07/maven-struts2-annotations-and-tiles.html
-->
<center>
<h1>
Struts2 Annotations and Tiles Integration Example
<br><br>
<br><br>

Footer.jsp:

DisplayServerTime.jsp:

<!--
Maven, Struts2 Annotations and Tiles Integration Example via Convention / Codebhind / Zero Config plugin using Eclipse IDE
http://codeoftheday.blogspot.com/2013/07/maven-struts2-annotations-and-tiles.html
-->
Server Time
<br><br>
${serverTime}

DisplayTotalVisits.jsp:

<!--
Maven, Struts2 Annotations and Tiles Integration Example via Convention / Codebhind / Zero Config plugin using Eclipse IDE
http://codeoftheday.blogspot.com/2013/07/maven-struts2-annotations-and-tiles.html
-->
Total Visits
<br><br>
${totalVisits}

Finally, deploy the application on any Java Web Application Server, open your browser and go to URLs:

DOWNLOAD COMPLETE SOURCE CODE FROM HERE

Saturday, 20 July 2013

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.

/**
* How to post a Tweet in Java using Twitter REST API and Twitter4J Library
* http://codeoftheday.blogspot.com/2013/07/how-to-post-tweet-in-java-using-twitter.html
*/
package smhumayun.codeoftheday.twitter;
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
"H-1B Transfer Jobs | Java Developer | Harrison, NY | 2 Years" +
" - http://h1b-work-visa-usa.blogspot.com/2013/07/h-1b-transfer-jobs-java-developer_19.html");
//attach any media, if you want to
statusUpdate.setMedia(
//title of media
"http://h1b-work-visa-usa.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://codeoftheday.blogspot.com" rel="nofollow">SMH's Integration App</a>
status.getText() = H-1B Transfer Jobs | 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://h1b-work-visa-usa.blogspot.com/2013/07/h-1b-transfer-jobs-java-developer_19.html', displayURL='h1b-work-visa-usa.blogspot.com/2013/07/h-1b-t…'}]
status.getUserMentionEntities() = []

Also, notice a tweet similar to this one on your Twitter Timeline:

tweet using twitter rest api twitter4j java

Thursday, 18 July 2013

Programmatically Posting to LinkedIn Groups via LinkedIn REST API and using Scribe-Java OAuth Library

In this post, I will demonstrate how you can post to LinkedIn Groups programmatically via LinkedIn REST API and using Scribe-Java OAuth Library.

To start with, you need to have an active LinkedIn account. Plus, you need to create a new LinkedIn Developer Application from LinkedIn Developer Site. If you want help on this, please refer to my previous post in which I demonstrate how you can create a new LinkedIn Developer Application, set different Scope(s) and how you can get following:

  1. API Key
  2. API Secret
  3. OAuth Token
  4. OAuth Secret

Do note that, for this example, you need to have 'rw_groups' scope because it is required to retrieve and post group discussions as authenticated user. So make sure you have checked the relevant box against ‘rw_groups’.

A LinkedIn Group Post contains following elements:

  1. Post Title
  2. Post Summary
  3. Content URL
  4. Content Image URL
  5. Content Title
  6. Content Description

programmatically posting on linkedin groups

Here’s the code and inline explanation of what it does:

/**
* Code Of The Day - Programmatically Posting to LinkedIn Groups via LinkedIn REST API and using Scribe-Java OAuth Library
* http://codeoftheday.blogspot.com/2013/07/programmatically-posting-to-linkedin.html
*/
package smhumayun.codeoftheday.linkedin.group;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.LinkedInApi;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;
/**
* This class demonstrate how you can Post Content to LinkedIn Groups using Scribe-Java OAuth API
*
* User: smhumayun
* Date: 7/18/13
* Time: 7:03 PM
*/
public class PostToLinkedInGroupExample {
private static OAuthService oAuthService;
/**
* Main Method
*
* @param args arguments
*/
public static void main(String[] args) {
//Instantiating the oAuth Service of Scribe-Java API
oAuthService = new ServiceBuilder()
//LinkedIn Provider with Scopes support
.provider(LinkedInApi.withScopes(
//'rw_groups' is to retrieve and post group discussions as authenticated user
"rw_groups"
))
//API Key
.apiKey("XXXXXXXXXXXX")
//API Secret
.apiSecret("XXXXXXXXXXXXXXXX")
//build it!
.build();
//Instantiating oAuth Request of type POST and with LinkedIn Group Discussion Post - REST API End Point URL
OAuthRequest postGroupDiscussionRequest = new OAuthRequest(Verb.POST, "http://api.linkedin.com/v1/groups/5046253/posts");
//Preparing XML payload to Share Content on LinkedIn Group
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n" +
"<post>\n" +
"<title>" +
//title of the post
"New Job Post!" +
"</title>\n" +
"<summary>" +
//summary of the post
"A new job post has been shared recently by Syed Muhammad Humayun on H-1B Work Visa USA" +
"</summary>\n" +
"<content>\n" +
"<submitted-url>" +
//url of the content
"http://h1b-work-visa-usa.blogspot.com/2013/07/h-1b-transfer-jobs-java-tech-lead-il.html" +
"</submitted-url>\n" +
"<submitted-image-url>" +
//image url of the content (if any)
"http://lh4.ggpht.com/-X2DLlJm6hyg/Uec5z_tRxxI/AAAAAAAAEP8/E3gVAGKIYPs/h-1b%252520transfer%252520green%252520card%252520processing%252520jobs%25255B4%25255D.png?imgmax=800" +
"</submitted-image-url>\n" +
"<title>" +
//title of the content
"H-1B Transfer Jobs - Java Tech Lead - IL - (Sponsor Green Card)" +
"</title>\n" +
"<description>" +
//description of the content
"Provides application development and support to partner in the planning, delivery and/or support of business processes utilizing information technology and business practices for strategic business units. Work is of medium to high complexity and moderate to high in risk. Has expanded contact with responsibility to varied and multiple departments and functional operations, and actively participates in strategic business relationships. Serves as a key team member which may include being on multiple teams and/or team lead. Participates in the review and formation of processes. May plan work and schedules for others for project related work. Impact of decision-making is medium to high risk and impact. Serves as a consultant or expert and actively shares knowledge across workgroups. Applies information analyses to optimize the integration of major strategic business processes. Designs and implements complex changes impacting several processes with minimal direction. Primarily performs as an individual contributor, but may supervise a small work team (6 or fewer members). Duties: Lead the Identification, analysis and selection of complex information technology and business practices to support strategic business process/plans. Participates as required to design, develop, test and integrate applications of high complexity. Lead in the implementation of information technology and business processes of high complexity. Supports, evaluates, and continuously improves information technology and business processes to maintain alignment with business plans of medium-high complexity and medium-high risk. Leads the development and may manage a project plan and schedule for a given functional area. Acquires solid foundation of project management. Engages in expanded contact with varied and multiple departments and functional operations; actively participating in strategic business relationships and/or issues." +
"</description>\n" +
"</content>\n" +
"</post>\n";
//set the content type header to text/xml - this is the type of content you are sending as payload
postGroupDiscussionRequest.addHeader("Content-Type", "text/xml");
//add xml payload to request
postGroupDiscussionRequest.addPayload(xml);
//sign oAuth request
signOAuthRequest(postGroupDiscussionRequest);
//send the request
Response response = postGroupDiscussionRequest.send();
//print the response from server
System.out.println("response.getBody() = " + response.getBody());
System.out.println("response.getMessage() = " + response.getMessage());
System.out.println("response.getCode() = " + response.getCode());
System.out.println("response.getHeaders():");
for(String headerKey : response.getHeaders().keySet())
System.out.println("\t" + headerKey + " = " + response.getHeader(headerKey));
}
/**
* Sign given oAuthRequest with oAuth Service
*
* @param oAuthRequest oAuthRequest
*/
public static void signOAuthRequest (OAuthRequest oAuthRequest)
{
//sign your request with oAuth Service
oAuthService.signRequest(
new Token(
//OAuth Token
"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
//OAuth Token Secret
, "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
), oAuthRequest);
}
}

Once your program ran successfully, you will see a response on your console, similar to following:

# Code Of The Day - Programmatically Posting to LinkedIn Groups via LinkedIn REST API and using Scribe-Java OAuth Library
# http://codeoftheday.blogspot.com/2013/07/programmatically-posting-to-linkedin.html
response.getBody() =
response.getMessage() = Created
response.getCode() = 201
response.getHeaders():
null = HTTP/1.1 201 Created
Date = Thu, 18 Jul 2013 18:46:12 GMT
Vary = Accept-Encoding
Content-Length = 0
Location = http://api.linkedin.com/v1/posts/g-5046253-S-259167773
x-li-request-id = 7R09I1AUHX
X-LI-R2-W-IC-2 = com.linkedin.container.dsc=1
Server = Apache-Coyote/1.1

Wednesday, 17 July 2013

Using LinkedIn REST API to Share Content Programmatically via Scribe-Java OAuth Library

In this post, I will demonstrate how you can use LinkedIn REST API to Share Content programmatically via Scribe-Java OAuth Library.

To start with, you need to have an active LinkedIn account. Plus, you need to create a new LinkedIn Developer Application from LinkedIn Developer Site. If you want help on this, please refer to my previous post in which I demonstrate how you can create a new LinkedIn Developer Application, set different Scope(s) and how you can get following:

  1. API Key
  2. API Secret
  3. OAuth Token
  4. OAuth Secret

Do note that, for this example, you need to have 'rw_nus' scope because it is required to retrieve and post updates to LinkedIn as authenticated user. So make sure you have checked the relevant box against ‘rw_nus’.

A LinkedIn Share contains following elements:

  1. Comment
  2. Content – Title
  3. Content – URL
  4. Content – Description
  5. Content – Image URL
  6. Visibility

linkedin share

However, if your application can't provide all the metadata, LinkedIn will attempt to fetch the missing content for you. So we will only provide following and rest will be handled by LinkedIn itself:

  1. Comment – against the content you want to share
    • For example: “H-1B Work Visa USA - Everything you need to know - Info, Tips, Guides, Stats, News, Updates, Recommendations, Community, Jobs and much more!”
  2. URL – of the content you want to share
  3. Visibility

Here’s the code and inline explanation of what it does:

/**
* Code Of The Day - Using LinkedIn REST API to Share Content Programmatically via Scribe-Java OAuth Library
* http://codeoftheday.blogspot.com/2013/07/using-linkedin-rest-api-to-share.html
*/
package smhumayun.codeoftheday.linkedin.share;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.LinkedInApi;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;
/**
* This class demonstrate how you can Share content via LinkedIn using Scribe-Java OAuth API
*
* User: smhumayun
* Date: 7/17/13
* Time: 5:03 PM
*/
public class ShareViaLinkedInExample {
/**
* Main Method
*
* @param args arguments
*/
public static void main(String[] args) {
//Instantiating the oAuth Service of Scribe-Java API
OAuthService oAuthService = new ServiceBuilder()
//LinkedIn Provider with Scopes support
.provider(LinkedInApi.withScopes(
//'rw_nus' is required to retrieve and post updates to LinkedIn as authenticated user
"rw_nus"
))
//API Key
.apiKey("XXXXXXXXXXXX")
//API Secret
.apiSecret("XXXXXXXXXXXXXXXX")
//build it!
.build();
//Instantiating oAuth Request of type POST and with LinkedIn Share REST API End Point URL
OAuthRequest oAuthRequest = new OAuthRequest(Verb.POST, "http://api.linkedin.com/v1/people/~/shares");
//Preparing XML payload to Share Content via LinkedIn
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n" +
"<share> \n" +
" <comment>" +
//comments against the content you want to share
"H-1B Work Visa USA - Everything you need to know - Info, Tips, Guides, Stats, News, Updates, Recommendations, Community, Jobs and much more!" +
"</comment> \n" +
" <content> \n" +
" <submitted-url>" +
//URL of the content you want to share
"http://h1b-work-visa-usa.blogspot.com" +
"</submitted-url> \n" +
" </content> \n" +
" <visibility> \n" +
" <code>anyone</code> \n" +
" </visibility> \n" +
"</share>\n";
//add xml payload to request
oAuthRequest.addPayload(xml);
//sign your request with oAuth Service
oAuthService.signRequest(
new Token(
//OAuth Token
"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
//OAuth Token Secret
, "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
), oAuthRequest);
//set the content type header to text/xml - this is the type of content you are sending as payload
oAuthRequest.addHeader("Content-Type", "text/xml");
//send the request
Response response = oAuthRequest.send();
//print the response from server
System.out.println("response.getBody() = " + response.getBody());
}
}

Once your program ran successfully, you will see a response on your console, similar to following:

<!--
Code Of The Day - Using LinkedIn REST API to Share Content Programmatically via Scribe-Java OAuth Library
http://codeoftheday.blogspot.com/2013/07/using-linkedin-rest-api-to-share.html
-->
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<update>
<update-key>UNIU-XXXXXXXX-XXXXXXXXXXXXXXXXXXX-SHARE</update-key>
<update-url>http://www.linkedin.com/updates?discuss=&amp;scope=XXXXXXXX&amp;stype=M&amp;topic=XXXXXXXXXXXXXXXXXXX&amp;type=U&amp;a=7OVt</update-url>
</update>

You can use the update key to request the XML or JSON representation of the newly created share. This can be achieved by making a GET call to http://www.linkedin-ei.com/v1/people/~/network/updates/key={update_key} (setting {update_key} to the value you received in the previous response)

Alternatively, you can choose to to use the update url to redirect the user to the newly created share. This URL serves as a direct link to the posted share on LinkedIn.com so they can view the share in the browser.

Monday, 15 July 2013

Consuming LinkedIn REST based Web Services using Scribe OAuth Java Library / API

In this post, I will demonstrate how you can consume/call LinkedIn’s REST based Web Services using a popular and easy to use OAuth Java library called Scribe. As an example, we will call LinkedIn’s Group API to fetch the number of members registered in that group.

Register a new LinkedIn Application

{ If you don’t have a LinkedIn account yet, you should create one now }

First you need to register a new application with LinkedIn to receive an API Key. This unique key helps LinkedIn to identify your application lets you make API calls.

Log into your LinkedIn Developer Account

Click on “+ Add New Application” button

Fill out the form – you need to fill following mandatory fields:

  • Application Name = My First Test App
  • Description = My First Test App
  • Website URL = {URL where your people should go to learn about your application.} – Note you can create a free Java Cloud Hosting Account as shown in my previous post
  • Application Use = For this example, you can select “Groups and Collaboration”
  • Live Status = Development (You can change it to “Live” once you have done your testing and want to go live)
  • Developer Contact Email = Your email address
  • Phone = Your contact number
  • OAuth User Agreement – Default Scope
    • r_basicprofile
    • rw_groups
  • Agreement Language = Browser Local Setting

linkedin developer new application

Once you fill the form and click on “Save” button, you will be provided with an API Key, Secret Key, OAuth User Token and OAuth User Secret. DO NOT SHARE THESE WITH ANY ONE ELSE.

linkedin oauth api key token

Create a new Java Web Application that will consume LinkedIn REST based Web Services

You will be amazed to see how Scribe made it easy to do OAuth and finally call the web service:

OAuthService oAuthService = new ServiceBuilder()
.provider(LinkedInApi.class)
.apiKey(apiKey)
.apiSecret(apiSecret)
.build();
OAuthRequest oAuthRequest = new OAuthRequest(Verb.GET, url);
oAuthService.signRequest(new Token(token, tokenSecret), oAuthRequest);
Response response = oAuthRequest.send();

I externalized the secret keys, token and other information like URL, duration etc. so it becomes easy to change the configuration of your application with out re-compile the application all again. In the init() life cycle method of HttpServlet, I loaded all those externalized variables:

@Override
public void init(ServletConfig config) throws ServletException {
this.apiKey = config.getServletContext().getInitParameter("apiKey");
this.apiSecret = config.getServletContext().getInitParameter("apiSecret");
this.token = config.getServletContext().getInitParameter("token");
this.tokenSecret = config.getServletContext().getInitParameter("tokenSecret");
this.url = config.getServletContext().getInitParameter("url");
try
{
durationInMillis = Integer.parseInt(config.getServletContext().getInitParameter("durationInMillis"));
}
catch(Exception e)
{
durationInMillis = 60 * 1000;
}
this.numMembersPrefix = config.getServletContext().getInitParameter("numMembersPrefix");
this.numMembersPostfix = config.getServletContext().getInitParameter("numMembersPostfix");
this.namePrefix = config.getServletContext().getInitParameter("namePrefix");
this.namePostfix = config.getServletContext().getInitParameter("namePostfix");
}

Here,

  • apiKey, apiSecret, token and tokenSecret are the ones you generated above.
  • url is the LinkedIn Group REST API’s URL (we will replace the {{gid}} with actual Group Id in our servlet)
    • http://api.linkedin.com/v1/groups/{{gid}}:(num-members,name)
  • durationInMillis is the time to cache the member count value. During that time any calls to this servlet will serve the client with cached value instead of making a call to LinkedIn Group REST API. Once that time is passed and comes a new client request, the servlet will attempt to fetch the value from LinkedIn Group REST API and update its cache. {durationInMillis defaults to 60 x 1000ms = 1 minute}
  • numMembersPrefix, numMembersPostfix, namePrefix and namePostfix will be used to extract the LinkedIn Group Name and Member Count from the REST API Response XML.

In the doGet() life cycle method of HttpServlet, notice that this servlet expects a request parameter ‘gid’ i.e. LinkedIn Group Id, from the client and if not found, it sets the content to ‘INV’ i.e. Invalid Group Id.

long gid;
try
{
gid = Long.parseLong(req.getParameter("gid"));
}
catch(Exception e)
{
gid = 0;
}
if(gid <= 0)
{
content = "INV";
logMsg("Invalid gid : " + req.getParameter("gid"));
}

If we received a valid ‘gid’, then we first check it in our cache which is a simple HashMap<Long, GroupInfo>:

GroupInfo groupInfo = groups.get(gid);
if(groupInfo == null)
groupInfo = new GroupInfo(gid);
if(groupInfo.getLastChecked() <= 0 || System.currentTimeMillis() - groupInfo.getLastChecked() > durationInMillis )

If we didn’t found an associated GroupInfo object in our cache, we create a new one. And then we check if it’s a first request coming for this ‘gid’ or the time passed since the last request against this ‘gid’ is greater than the configured ‘durationInMillis’ then:

OAuthService oAuthService = new ServiceBuilder()
.provider(LinkedInApi.class)
.apiKey(apiKey)
.apiSecret(apiSecret)
.build();
OAuthRequest oAuthRequest = new OAuthRequest(Verb.GET, url.replace("{{gid}}", "" + groupInfo.getId()));
oAuthService.signRequest(new Token(token, tokenSecret), oAuthRequest);
Response response = oAuthRequest.send();
groupInfo.setLastChecked(System.currentTimeMillis());
content = response.getBody();
groupInfo.setName(content.substring(content.indexOf(namePrefix) + namePrefix.length() + 1, content.indexOf(namePostfix)));
String mc = content.substring(content.indexOf(numMembersPrefix) + numMembersPrefix.length() + 1, content.indexOf(numMembersPostfix));
try
{
groupInfo.setMemberCount(Long.parseLong(mc));
logMsg(groupInfo.getId() + " - " + groupInfo.getName() + " - " + groupInfo.getMemberCount() + " members");
content = "" + groupInfo.getMemberCount();
groups.put(groupInfo.getId(), groupInfo);
}
catch(Exception e)
{
logMsg("ERROR >>> " + groupInfo.getId() + " - " + groupInfo.getName() + " | mc {" + mc + "} | " + e.toString());
e.printStackTrace(System.out);
}

Make a call to LinkedIn Group REST API

Save the time to GroupInfo’s lastChecked – so we knew when did we last fetched the Group Information from LinkedIn.

Extract the name and memberCount from the response xml and set them in GroupInfo object.

Also, set the extracted memberCount to content, to be returned to the client.

Save the updated (or newly created) GroupInfo object in cache.

Else, if the time passed since the last request against this ‘gid’ is less than the configured ‘durationInMillis’ then:

else
{
content = "" + groupInfo.getMemberCount();
logMsg(groupInfo.getId() + " - " + groupInfo.getName() + " - " + groupInfo.getMemberCount() + " members (cached)");
}

Simply return the member count value from the cache.

Click here to view this servlet live in action - http://smhumayun.ap01.aws.af.cm/ligmcs?gid=5046253

If you remember my last post about a FREE LinkedIn Group Member Count Widget for Blogger, Wordpress, Drupal, Joomla, Magento, Moodle, Typo, Alfresco, Windows Live, Blogspot, SharePoint, etc.., this widget service uses very similar code like the one I’ve demonstrated above.

You can see the production version of the same being used here.

DOWNLOAD COMPLETE SOURCE CODE FROM HERE

MemberCountServlet.java:

/*
* Consuming LinkedIn REST based Web Services using Scribe OAuth Java Library / API
* http://codeoftheday.blogspot.com/2013/07/consuming-linkedin-rest-based-web.html
*/
package smhumayun.codeoftheday.linkedin.group;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.LinkedInApi;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;
/**
* Main Servlet exposed as a service which will be used by client(s) in order
* to determine number of group members registered in a particular LinkedIn Group
*
* @author smhumayun
*/
public class MemberCountServlet extends HttpServlet {
private String apiKey;
private String apiSecret;
private String token;
private String tokenSecret;
private String url;
private String numMembersPrefix;
private String numMembersPostfix;
private String namePrefix;
private String namePostfix;
private long durationInMillis;
private HashMap<Long, GroupInfo> groups = new HashMap<Long, GroupInfo>();
private SimpleDateFormat df = (SimpleDateFormat) SimpleDateFormat.getDateTimeInstance();
@Override
public void init(ServletConfig config) throws ServletException {
this.apiKey = config.getServletContext().getInitParameter("apiKey");
this.apiSecret = config.getServletContext().getInitParameter("apiSecret");
this.token = config.getServletContext().getInitParameter("token");
this.tokenSecret = config.getServletContext().getInitParameter("tokenSecret");
this.url = config.getServletContext().getInitParameter("url");
try
{
durationInMillis = Integer.parseInt(config.getServletContext().getInitParameter("durationInMillis"));
}
catch(Exception e)
{
durationInMillis = 60 * 1000;
}
this.numMembersPrefix = config.getServletContext().getInitParameter("numMembersPrefix");
this.numMembersPostfix = config.getServletContext().getInitParameter("numMembersPostfix");
this.namePrefix = config.getServletContext().getInitParameter("namePrefix");
this.namePostfix = config.getServletContext().getInitParameter("namePostfix");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
String content;
try
{
long gid;
try
{
gid = Long.parseLong(req.getParameter("gid"));
}
catch(Exception e)
{
gid = 0;
}
if(gid <= 0)
{
content = "INV";
logMsg("Invalid gid : " + req.getParameter("gid"));
}
else
{
GroupInfo groupInfo = groups.get(gid);
if(groupInfo == null)
groupInfo = new GroupInfo(gid);
if(groupInfo.getLastChecked() <= 0 || System.currentTimeMillis() - groupInfo.getLastChecked() > durationInMillis )
{
OAuthService oAuthService = new ServiceBuilder()
.provider(LinkedInApi.class)
.apiKey(apiKey)
.apiSecret(apiSecret)
.build();
OAuthRequest oAuthRequest = new OAuthRequest(Verb.GET, url.replace("{{gid}}", "" + groupInfo.getId()));
oAuthService.signRequest(new Token(token, tokenSecret), oAuthRequest);
Response response = oAuthRequest.send();
groupInfo.setLastChecked(System.currentTimeMillis());
content = response.getBody();
groupInfo.setName(content.substring(content.indexOf(namePrefix) + namePrefix.length() + 1, content.indexOf(namePostfix)));
String mc = content.substring(content.indexOf(numMembersPrefix) + numMembersPrefix.length() + 1, content.indexOf(numMembersPostfix));
try
{
groupInfo.setMemberCount(Long.parseLong(mc));
logMsg(groupInfo.getId() + " - " + groupInfo.getName() + " - " + groupInfo.getMemberCount() + " members");
content = "" + groupInfo.getMemberCount();
groups.put(groupInfo.getId(), groupInfo);
}
catch(Exception e)
{
logMsg("ERROR >>> " + groupInfo.getId() + " - " + groupInfo.getName() + " | mc {" + mc + "} | " + e.toString());
e.printStackTrace(System.out);
}
}
else
{
content = "" + groupInfo.getMemberCount();
logMsg(groupInfo.getId() + " - " + groupInfo.getName() + " - " + groupInfo.getMemberCount() + " members (cached)");
}
}
}
catch(Exception e)
{
content = "ERR";
e.printStackTrace(System.out);
}
resp.setContentType("text/plain");
resp.setContentLength(content.length());
PrintWriter out = resp.getWriter();
out.print(content);
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
private void logMsg (String msg)
{
System.out.println(df.format(new Date(System.currentTimeMillis())) + " | " + msg);
}
}

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>LinkedIn Group Members Count Service by smhumayun@gmail.com</display-name>
<context-param>
<param-name>apiKey</param-name>
<param-value>XXXXXXXXXXXX</param-value>
</context-param>
<context-param>
<param-name>apiSecret</param-name>
<param-value>XXXXXXXXXXXXXXXX</param-value>
</context-param>
<context-param>
<param-name>token</param-name>
<param-value>XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX</param-value>
</context-param>
<context-param>
<param-name>tokenSecret</param-name>
<param-value>XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX</param-value>
</context-param>
<context-param>
<param-name>url</param-name>
<param-value>http://api.linkedin.com/v1/groups/{{gid}}:(num-members,name)</param-value>
</context-param>
<context-param>
<param-name>durationInMillis</param-name>
<param-value>300000</param-value>
</context-param>
<context-param>
<param-name>numMembersPrefix</param-name>
<param-value><![CDATA[<num-members]]></param-value>
</context-param>
<context-param>
<param-name>numMembersPostfix</param-name>
<param-value><![CDATA[</num-members]]></param-value>
</context-param>
<context-param>
<param-name>namePrefix</param-name>
<param-value><![CDATA[<name]]></param-value>
</context-param>
<context-param>
<param-name>namePostfix</param-name>
<param-value><![CDATA[</name]]></param-value>
</context-param>
<servlet>
<servlet-name>ligmcs</servlet-name>
<servlet-class>smhumayun.codeoftheday.linkedin.group.MemberCountServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ligmcs</servlet-name>
<url-pattern>/ligmcs</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

Friday, 12 July 2013

XStream - One of the best Java and XML Framework around

xstreamXStream is for sure one of the best Java and XML frameworks around. It offers great ease of use, simplistic approach and fun to work with.

From the authors “XStream is a simple library to serialize objects to XML and back again.”

Let me show you how simple it is:

String xml = xstream.toXML(domainObject);

That’s it! Smile

Consider a simple domain object class:

/**
* XStream - One of the best Java and XML Framework around
* http://codeoftheday.blogspot.com/2013/07/xstream-one-of-best-java-and-xml.html
*/
package smhumayun.codeoftheday.XStreamExample;
import java.util.Date;
/**
* User domain object as an example
*
* User: smhumayun
* Date: 7/12/13
* Time: 7:53 PM
*/
public class User {
private int id;
private String name;
private Date joiningDate;
public User() {
}
public User(int id, String name, Date joiningDate) {
this.id = id;
this.name = name;
this.joiningDate = joiningDate;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getJoiningDate() {
return joiningDate;
}
public void setJoiningDate(Date joiningDate) {
this.joiningDate = joiningDate;
}
}
view raw User.java hosted with ❤ by GitHub

In order to convert or serialize that domain object to xml, all you have to do is following:

/**
* XStream - One of the best Java and XML Framework around
* http://codeoftheday.blogspot.com/2013/07/xstream-one-of-best-java-and-xml.html
*/
package smhumayun.codeoftheday.XStreamExample;
import com.thoughtworks.xstream.XStream;
import java.util.Date;
/**
* Main Example class
*
* User: smhumayun
* Date: 7/12/13
* Time: 7:53 PM
*/
public class MainXStreamExample {
public static void main(String[] args) {
//Instantiate XStream
XStream xstream = new XStream();
//Instantiate and initialize any domain object of yours
User user = new User(1, "Syed Muhammad Humayun", new Date(System.currentTimeMillis()));
//Convert your domain object to XML instantly with a single statement call!
System.out.println(xstream.toXML(user));
}
}

The output of the above program is:

<smhumayun.codeoftheday.XStreamExample.User>
<id>1</id>
<name>Syed Muhammad Humayun</name>
<joiningDate>2013-07-12 23:45:34.83 UTC</joiningDate>
</smhumayun.codeoftheday.XStreamExample.User>
view raw User.xml hosted with ❤ by GitHub

What if, you want to convert or deserialize the xml back to java object?

DomainObject domainObject = (DomainObject) xstream.fromXML(xml);

Some of the cool features of XStream includes:

  • Ease of use. A high level facade is supplied that simplifies common use cases.
  • No mappings required. Most objects can be serialized without need for specifying mappings.
  • Performance. Speed and low memory footprint are a crucial part of the design, making it suitable for large object graphs or systems with high message throughput.
  • Clean XML. No information is duplicated that can be obtained via reflection. This results in XML that is easier to read for humans and more compact than native Java serialization.
  • Requires no modifications to objects. Serializes internal fields, including private and final. Supports non-public and inner classes. Classes are not required to have default constructor.
  • Full object graph support. Duplicate references encountered in the object-model will be maintained. Supports circular references.
  • Integrates with other XML APIs. By implementing an interface, XStream can serialize directly to/from any tree structure (not just XML).
  • Customizable conversion strategies. Strategies can be registered allowing customization of how particular types are represented as XML.
  • Error messages. When an exception occurs due to malformed XML, detailed diagnostics are provided to help isolate and fix the problem.
  • Alternative output format. The modular design allows other output formats. XStream ships currently with JSON support and morphing.

Thursday, 11 July 2013

FREE LinkedIn Group Member Count Widget for Blogger, Wordpress, Drupal, Joomla, Magento, Moodle, Typo, Alfresco, Windows Live, Blogspot, SharePoint, etc..

While LinkedIn and other third parties offers numerous widgets and plugins, there’s one that is often requested by those who owns or manages or participates in one or more LinkedIn Groups.

LinkedIn Groups provide a place for professionals in the same industry or with similar interests to share content, find answers, post and view jobs, make business contacts, and establish themselves as industry experts.

In order to promote your LinkedIn Group, the only option you have is to add a “static” link of your group on your blog, CMS or website. But, that’s unlike how LinkedIn’s own or other Social Platforms widgets, badges, plugins offer “dynamic” linking that also displays useful information that shows how effective your community is and what’s the strength of your community.

Consider following examples:

LinkedIn Share Plugin – shows number of shares
linkedin share plugin

LinkedIn Recommend Button – shows number of recommendations
linkedin recommend button

Twitter Tweet Button – shows number of tweets
twitter tweet button

Facebook Share Button – shows number of shares
facebook share like button

Above examples, shows how these “dynamic” info links are more appealing and effective when it comes to end-user experience and ultimately online marketing.

On the other hand, LinkedIn provides a rich API to do a number of interesting things with the data trove you have in the form of your LinkedIn Profile, Connections, Jobs, Companies, Groups etc.. However, these kind of integrations require a certain amount of development skills and expertise and there’s no solution for those who didn’t have that and just wanted to have easy to integrate buttons, widgets, etc. just like those shown above.

Good news! I’ve developed an online tool that would allow you to generate LinkedIn Group Members Count button/widget easily, without any requirements of development skills or expertise. Its simple and quick to generate as many buttons as you like and its FREE!!!

All you need to generate free widget for your group is:

  1. Your LinkedIn Group Id – for example “5046253”
  2. Title of the Widget – for example “Join our LinkedIn Group”

How to find Group Id of your LinkedIn Group?

Go to the home page of a group you like

how to find linkedin group id

Right click on the Logo of the group and if you have:

  • Internet Explorer – then select “Copy Shortcut”
  • Firefox – then select “Copy Link Location”
  • Chrome – then select “Copy Link Address”

Paste the copied URL onto some plain/text editor. It will look like:

http://www.linkedin.com/groups?home=&gid=5046253&trk=anet_ug_hm

Notice the group id highlighted in yellow above. Copy the numeric number right after from “&gid=” and up-till very next “&”. This is your LinkedIn Group Id.

GO AHEAD AND CREATE FREE LINKEDIN GROUP MEMBER COUNT WIDGETS NOW!

CLICK TO VIEW LIVE DEMO

Wednesday, 10 July 2013

Deploying Java Web Application on AppFog’s FREE Cloud Hosting Account in Seconds!

What is AppFog?

If you don’t have an account with AppFog yet, you can create one from here – easiest signup process. You will have an active account in seconds!

appfog free cloud hosting account signup

Sign into your AppFog account and from top menu click on “Create App” or from bottom click on “New App”

appfog home page

Choose an application type:

appfog - new app - step one - choose an application

Choose infrastructure type:

appfog - new app - step two - choose an infrastructure

Go to Apps details page and Download Source Code:

appfog - app - details

Unzip source code at a location on your local machine.

{ If you have not installed Ruby and “af” RubyGem, install it now – How to Install Ruby and “af” RubyGem }

Start Command Prompt with Ruby:

appfog - run af command line tool

appfog - af - command line utility

Run login command : ‘af login’

‘cd’ to your project directory

Run update command to synchronize your remote project with your local one.

appfog - af - update

All your local files will be packaged and uploaded to your remote cloud space.

appfog - af - update 2

Go to your AppFog’s App Page and Click on ‘View Live Site’:

appfog - app - view live site

appfog - live site

AppFog’s FREE Quality Cloud Hosting – Supports Java, Grails, Spring, MySQL, PostgresSQL, Node, PHP, Drupal, WordPress, Python, Django, Ruby On Rails

 

af-logo

Launch your first app in minutes!

This is what AppFog claims and to let you verify their claim, they are offering a free quality cloud hosting account which comes up with the following jewels:

AppFog’s FREE account details:
Unlimited apps within 2GB RAM
  • Up to 8 service instances
  • 100MB storage per MySQL or PostgreSQL instance
  • 10MB RAM & 6 concurrent connections for Redis, MongoDB, and RabbitMQ instances
  • 5GB data transfer per month
  • 100 requests per second
  • Community-based support
  • Apps limited to *.af.cm domains

Besides their free offering, the pricing of other packages are very reasonable too. You can check all pricing details here.

AppFog’s Cloud supports following:

  1. Java
  2. Spring Framework
  3. Grails
  4. Ruby On Rails
  5. PHP
  6. Python
  7. Node
  8. MySQL
  9. PostgreSQL
  10. MongoDB
  11. ClearDB
  12. Drupal
  13. WordPress
  14. Django
  15. Redis
  16. RabbitMQ
  17. Etc..

Sunday, 7 July 2013

Setting Up Your Custom IPN Listener on Paypal

You can make your Custom IPN Listener known to PayPal by specifying the listener’s URL in following two ways:

  1. Setting Up IPN Notifications on Paypal
  2. Dynamically Setting the IPN Notification URL via Paypal Button’s HTML Variable

Setting Up IPN Notifications on Paypal

After you log into your Paypal Account, follow these instructions to set up your IPN Listener:

  1. Click ‘Profile’ on the ‘My Account’ tab
  2. Click ‘Instant Payment Notification Preferences’ in the Selling Preferences column
  3. Click ‘Choose IPN Settings’ to specify your listener’s URL and activate the listener.
    The following screen appears:
    edit-instant-payment-notification-ip
  4. Specify the URL for your listener in the ‘Notification URL’ field
  5. Click ‘Receive IPN messages (Enabled)’ to enable your listener
  6. Click Save
    The following screen appears:
    instant-payment-notification-ipn5

Dynamically Setting the IPN Notification URL via Paypal Button’s HTML Variable

In this case, PayPal sends the IPN message to the listener specified in the notification URL for a specific button or API operation instead of the listener specified in your Profile.

To specify a notification URL for a Paypal Button, specify your IPN Listener’s URL in the ‘notify_url’ HTML form variable of that Paypal Button’s HTML Code.

<!--
Paypal Button and Instant Payment Notification (IPN) Integration with Java
http://codeoftheday.blogspot.com/2013/07/paypal-button-and-instant-payment_6.html
-->
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="XXXXXXXXXXXXX">
<input type="hidden" name="return" value="http://www.yourdomain.com/orderComplete.do">
<input name="notify_url" value="http://www.yourdomain.com/your_ipn_listener.do" type="hidden">
<input type="image" src="https://www.paypalobjects.com/en_US/GB/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal ? The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>

Testing Your Custom IPN Listener for Paypal Instant Payment Notification (IPN) via Paypal’s IPN Simulator

You can test your custom IPN Listener by:

  1. logging into your Paypal Developer account.
  2. Select ‘Applications’ from tab menu
  3. Then select ‘IPN Simulator’ from left panel menu.
  4. Enter your IPN Handler URL
  5. Select Transaction Type:

ipn simulator_thumb[6]

Once you select the Transaction Type, the page will refresh with more form values relevant to your selected Transaction Type. Majority of the ‘Test Data’ is already filled. However, you can change any values you like to test.

Click on the Send IPN button to simulate the transaction, which will result in one or more IPN notifications being sent to your IPN Handler URL depending upon the Transaction Type.

send ipn_thumb[5]

Saturday, 6 July 2013

Paypal Button and Instant Payment Notification (IPN) Integration with Java

Integration with Payment Gateways is one of the most common integration in business applications. In this post, I will demonstrate how you can integrate your Java (Servlet/JSP/Struts/Spring/etc.) applications with Paypal using Paypal Button and Instant Payment Notification (IPN).

For those who hate to read long documentation, I’ve tried to capture “minimum” reading material here from Paypal website that is required to understand Paypal IPN Protocal and Architecture; and which is a pre-requisite for our example below.

Besides that, you should also setup following (if not done already):

  1. Create Paypal Account
  2. Activate Paypal Developer Account by signing in with your Paypal Account credentials
  3. Create Paypal Payment Button

    create paypal payment button

‘IpnHandler.java’

/**
* Paypal Button and Instant Payment Notification (IPN) Integration with Java
* http://codeoftheday.blogspot.com/2013/07/paypal-button-and-instant-payment_6.html
*/
package smhumayun.codeoftheday.PaypalIpnExample;
import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Paypal IPN Notification Handler Class
*
* User: smhumayun
* Date: 7/6/13
* Time: 5:48 PM
*/
public class IpnHandler
{
private Logger logger;
private IpnConfig ipnConfig;
private IpnInfoService ipnInfoService;
/**
* This method handles the Paypal IPN Notification as follows:
* 1. Read all posted request parameters
* 2. Prepare 'notify-validate' command with exactly the same parameters
* 3. Post above command to Paypal IPN URL {@link IpnConfig#ipnUrl}
* 4. Read response from Paypal
* 5. Capture Paypal IPN information
* 6. Validate captured Paypal IPN Information
* 6.1. Check that paymentStatus=Completed
* 6.2. Check that txnId has not been previously processed
* 6.3. Check that receiverEmail matches with configured {@link IpnConfig#receiverEmail}
* 6.4. Check that paymentAmount matches with configured {@link IpnConfig#paymentAmount}
* 6.5. Check that paymentCurrency matches with configured {@link IpnConfig#paymentCurrency}
* 7. In case of any failed validation checks, throw {@link IpnException}
* 8. If all is well, return {@link IpnInfo} to the caller for further business logic execution
*
* @param request {@link HttpServletRequest}
* @return {@link IpnInfo}
* @throws IpnException
*/
public IpnInfo handleIpn (HttpServletRequest request) throws IpnException {
logger.info("inside ipn");
IpnInfo ipnInfo = new IpnInfo();
try
{
//1. Read all posted request parameters
String requestParams = this.getAllRequestParams(request);
logger.info(requestParams);
//2. Prepare 'notify-validate' command with exactly the same parameters
Enumeration en = request.getParameterNames();
StringBuilder cmd = new StringBuilder("cmd=_notify-validate");
String paramName;
String paramValue;
while (en.hasMoreElements()) {
paramName = (String) en.nextElement();
paramValue = request.getParameter(paramName);
cmd.append("&").append(paramName).append("=")
.append(URLEncoder.encode(paramValue, request.getParameter("charset")));
}
//3. Post above command to Paypal IPN URL {@link IpnConfig#ipnUrl}
URL u = new URL(this.getIpnConfig().getIpnUrl());
HttpsURLConnection uc = (HttpsURLConnection) u.openConnection();
uc.setDoOutput(true);
uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
uc.setRequestProperty("Host", "www.paypal.com");
PrintWriter pw = new PrintWriter(uc.getOutputStream());
pw.println(cmd.toString());
pw.close();
//4. Read response from Paypal
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String res = in.readLine();
in.close();
//5. Capture Paypal IPN information
ipnInfo.setLogTime(System.currentTimeMillis());
ipnInfo.setItemName(request.getParameter("item_name"));
ipnInfo.setItemNumber(request.getParameter("item_number"));
ipnInfo.setPaymentStatus(request.getParameter("payment_status"));
ipnInfo.setPaymentAmount(request.getParameter("mc_gross"));
ipnInfo.setPaymentCurrency(request.getParameter("mc_currency"));
ipnInfo.setTxnId(request.getParameter("txn_id"));
ipnInfo.setReceiverEmail(request.getParameter("receiver_email"));
ipnInfo.setPayerEmail(request.getParameter("payer_email"));
ipnInfo.setResponse(res);
ipnInfo.setRequestParams(requestParams);
//6. Validate captured Paypal IPN Information
if (res.equals("VERIFIED")) {
//6.1. Check that paymentStatus=Completed
if(ipnInfo.getPaymentStatus() == null || !ipnInfo.getPaymentStatus().equalsIgnoreCase("COMPLETED"))
ipnInfo.setError("payment_status IS NOT COMPLETED {" + ipnInfo.getPaymentStatus() + "}");
//6.2. Check that txnId has not been previously processed
IpnInfo oldIpnInfo = this.getIpnInfoService().getIpnInfo(ipnInfo.getTxnId());
if(oldIpnInfo != null)
ipnInfo.setError("txn_id is already processed {old ipn_info " + oldIpnInfo);
//6.3. Check that receiverEmail matches with configured {@link IpnConfig#receiverEmail}
if(!ipnInfo.getReceiverEmail().equalsIgnoreCase(this.getIpnConfig().getReceiverEmail()))
ipnInfo.setError("receiver_email " + ipnInfo.getReceiverEmail()
+ " does not match with configured ipn email " + this.getIpnConfig().getReceiverEmail());
//6.4. Check that paymentAmount matches with configured {@link IpnConfig#paymentAmount}
if(Double.parseDouble(ipnInfo.getPaymentAmount()) != Double.parseDouble(this.getIpnConfig().getPaymentAmount()))
ipnInfo.setError("payment amount mc_gross " + ipnInfo.getPaymentAmount()
+ " does not match with configured ipn amount " + this.getIpnConfig().getPaymentAmount());
//6.5. Check that paymentCurrency matches with configured {@link IpnConfig#paymentCurrency}
if(!ipnInfo.getPaymentCurrency().equalsIgnoreCase(this.getIpnConfig().getPaymentCurrency()))
ipnInfo.setError("payment currency mc_currency " + ipnInfo.getPaymentCurrency()
+ " does not match with configured ipn currency " + this.getIpnConfig().getPaymentCurrency());
}
else
ipnInfo.setError("Inavlid response {" + res + "} expecting {VERIFIED}");
logger.info("ipnInfo = " + ipnInfo);
this.getIpnInfoService().log(ipnInfo);
//7. In case of any failed validation checks, throw {@link IpnException}
if(ipnInfo.getError() != null)
throw new IpnException(ipnInfo.getError());
}
catch(Exception e)
{
if(e instanceof IpnException)
throw (IpnException) e;
logger.log(Level.SEVERE, e.toString(), e);
throw new IpnException(e.toString());
}
//8. If all is well, return {@link IpnInfo} to the caller for further business logic execution
return ipnInfo;
}
/**
* Utility method to extract all request parameters and their values from request object
*
* @param request {@link HttpServletRequest}
* @return all request parameters in the form:
* param-name 1
* param-value
* param-name 2
* param-value
* param-value (in case of multiple values)
*/
private String getAllRequestParams(HttpServletRequest request)
{
Map map = request.getParameterMap();
StringBuilder sb = new StringBuilder("\nREQUEST PARAMETERS\n");
for (Iterator it = map.keySet().iterator(); it.hasNext();)
{
String pn = (String)it.next();
sb.append(pn).append("\n");
String[] pvs = (String[]) map.get(pn);
for (int i = 0; i < pvs.length; i++) {
String pv = pvs[i];
sb.append("\t").append(pv).append("\n");
}
}
return sb.toString();
}
public Logger getLogger() {
return logger;
}
public void setLogger(Logger logger) {
this.logger = logger;
}
public IpnConfig getIpnConfig() {
return ipnConfig;
}
public void setIpnConfig(IpnConfig ipnConfig) {
this.ipnConfig = ipnConfig;
}
public IpnInfoService getIpnInfoService() {
return ipnInfoService;
}
public void setIpnInfoService(IpnInfoService ipnInfoService) {
this.ipnInfoService = ipnInfoService;
}
}
view raw IpnHandler.java hosted with ❤ by GitHub

As for ‘IpnConfig.java’:

  1. ‘ipnUrl’ should be:
    1. For Production/Live - https://www.paypal.com/cgi-bin/webscr
    2. For Sandbox/Testing - https://www.sandbox.paypal.com/cgi-bin/webscr
  2. ‘receiverEmail’ should be the Paypal Account Email
  3. ‘paymentAmount’ should be the ‘Price’ you setup while defining Paypal Button above.
  4. ‘paymentCurrency’ should be the ‘Currency’ you mention while defining the Paypal Button above.

Now,

COMPLETE SOURCE CODE IS AVAILABLE HERE TO DOWNLOAD