Monday, 14 October 2013

JetBrains IntelliJ IDEA > Features > Code/Context Highlighting and Code Folding

No one have ever understood the problems and challenges faced by Developers, better than JetBrains. The day, I was introduced to this amazingly genius IDE, back in 2004, I fell for it. And, with every passing day, or should I say every passing release, JetBrains keep on raising the bar to a level where no one can possibly reach it.

So impressed with this IDE, I though about writing each of those intelligent features that saves me from a lot of stress and waste of time and efforts. But, honestly, every time I failed to figure out where to start and which ones to blog first. So, now, just 2 minutes ago, while I was coding Bootstrap prototype interface for one of the projects that I’m working on, I was amazed to see how intelligently it is aiding and assisting me to do my work efficiently with as least stress as possible.

The Bootstrap prototype file I’m working on is a Plain HTML file, and there are around ~300 lines of code. See the snapshot below, shows how efficiently IntelliJ IDEA has highlighted the area where I’m working at:

JetBrains IntelliJ IDEA IDE (Click to open enlarge image in a new window)

  1. Notice breadcrumbs at the top of editor window
  2. Notice a thin stripe at the left hand side buffer of editor window
  3. Notice the highlighted line of code within the editor where my caret is
  4. Notice the highlighted tags hierarchy within the editor
  5. And finally notice, how all of the above are synced with beautiful colors to track each item of current context individually

Wow!

Well, that’s not all. This file you are looking at is a ~300 line file, notice how I saved my self from additional stress of looking at un-related code, by (6) folding/collapsing literally any part of the code I wished to.

Genius! isn’t it?

And finally Winking smile, for those who are thinking that I’ve spent a fortune to have that jewel under my belt, have a look at this:

JetBrains IntelliJ IDEA Community Edition

Happy Coding Smile

Saturday, 5 October 2013

Apache Maven Tips: Add/Append Copyright and License Header to your Project’s Source Code Artifacts using Maven License Plugin

apache-mavenEvery project requires proper copyrights and license information header to be added/appended at the top of each of the project’s source code artifacts. There is a very useful plugin for Apache Maven, called Maven License Plugin that helps you easily add/append such copyrights and license information.

First create a copyrights and license header file, for example:

${project}

Copyright (c) ${year}, ${founder}

This project includes software developed by ${founder}
${website}

Licensed under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at:

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.

Note the highlighted “parameters” enclosed within special notation “${ }”. We will define the values for these parameters when we will configure Maven License Plugin in our project’s POM file, as show below:

<plugin>
    <groupId>com.mycila.maven-license-plugin</groupId>
    <artifactId>maven-license-plugin</artifactId>
    <version>1.10.b1</version>
    <configuration>
        <header>src/license/LicenseHeader.txt</header>
        <properties>
            <project>${project.name}</project>
            <founder>${project.organization.name}</founder>
            <year>${project.inceptionYear}</year>
            <website>${founder-website}</website>

        </properties>
        <includes>
            <include>src/main/java/**</include>
            <include>src/test/java/**</include>

        </includes>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>format</goal>
            </goals>
            <phase>process-sources</phase>
        </execution>
    </executions>
    <dependencies>
        <dependency>
            <groupId>com.mycila</groupId>
            <artifactId>licenses</artifactId>
            <version>1</version>
        </dependency>
    </dependencies>
</plugin>

  1. Under the configuration tag, notice the <header/> element where we’ve mentioned the path to our copyrights and license header file.
  2. Similarly, the <properties/> element under <header/> is the place where you can define parameters and their values to be replaced by the parameter place holders as show in the header file above.
  3. The <includes/> element is the place where you can configure which files should the plugin attempt to add/append the copyright and license information. You can use wild cards as shown above.

Following is an example of Source Code file after processed by Maven License Plugin:

Thursday, 3 October 2013

Apache Maven Tips: Customizing Maven Site generation via Site Descriptor (Site.xml), Maven Site Plugin and Velocity Template

apache-mavenThere are two kind of customizations you can do with Maven Site generation:

(1) Configuring the Site Descriptor (Simple) – This is a higher level customization, where you can change or configure certain sections/areas of the site layout including the navigation/menu. Read more on Maven website.

(2) Custom Velocity Template (Complex) – This is a low level customization, where you have full control over the generated html content. However it is more complex than the first one because you need to have an understanding of Apache Velocity templating language.

To begin with, add Maven Site Plugin configuration under the <build/> tag of your POM:

<plugin>
    <artifactId>maven-site-plugin</artifactId>
    <version>3.3</version>
    <configuration>
        <templateFile>${basedir}/src/site/maven-site-template.vm</templateFile>
    </configuration>

</plugin>

Recommended way to develop/design a custom maven site template, is to start with the default template provided by maven itself, and then change it to your desired layout.

Tuesday, 1 October 2013

Apache Maven Tips: How to add/include or remove/exclude files as Resources and Test Resources

apache-mavenApache Maven’s Standard Directory Layout contains specific folders for application wide Resources and TestResources, they are:

src/main/resources
src/test/resources

What if you want to add or include more files as Resources or TestResources? a typical example is the use of standard README, LICENSE and NOTICE files, which by convention should reside at the very root of the project, like this:

./README
./LICENSE
./NOTICE
./src/...

In such situations, you can add or include files by adding a configuration similar to the following, under the <build/> section of your POM:

<build>
    <resources>
        <resource>
            <directory>${project.basedir}</directory>
            <includes>
                <include>README*</include>
                <include>LICENSE*</include>
                <include>NOTICE*</include>
            </includes>
        </resource>
    </resources>
    <testResources>
        <testResource>
            <directory>${project.basedir}</directory>
            <includes>
                <include>README*</include>
                <include>LICENSE*</include>
                <include>NOTICE*</include>
            </includes>
        </testResource>
    </testResources>

Similarly, you can remove or exclude files by adding a configuration similar to the following, under the <build/> section of your POM:

<build>
    <resources>
        <resource>
            <directory>${project.basedir}/src/main/resources</directory>
            <excludes>
                <exclude>SomeFile.toExclude</exclude>
            </excludes>
        </resource>
    </resources>
    <testResources>
        <testResource>
            <directory>${project.basedir}/src/test/resources</directory>
            <excludes>
                <exclude>SomeFile.toExclude</exclude>
            </excludes>
        </testResource>
    </testResources>

Wednesday, 25 September 2013

How to Flag a Post or a Discussion in a LinkedIn Group as a Promotion or a Job using Scribe and Java

As a sequel to my earlier post, Programmatically Posting to LinkedIn Groups via LinkedIn REST API and using Scribe-Java OAuth Library, in this post I will demonstrate how you can Flag a Post or a Discussion in a LinkedIn Group as a Promotion or a Job using Scribe and Java.

Flag Post or Discussion in LinkedIn Group as Promotion or Job

Consider the output of our example program in my previous post:

Notice the following header and its value:

Location = http://api.linkedin.com/v1/posts/g-5046253-S-259167773

This URL contains the post id of the published post and it is the very last part of the URL “g-5046253-S-259167773”.

So, what we will do now is the extend the same program/example and will try to extract the “Location” header value and then extract the “post-id” from that value:

//http://api.linkedin.com/v1/posts/g-5046253-S-276447044
String preUrl = "http://api.linkedin.com/v1/posts/";
String url = response.getHeader("Location").substring(preUrl.length());
url = preUrl + url + "/category/code";

Once you have the target URL, you can now proceed with the HTTP PUT request, using the url as a LinkedIn REST API end point.

OAuthRequest request = new OAuthRequest(Verb.PUT, url);
request.addHeader("Content-Type", "text/xml");

Now, if you want to Flag your Post or Discussion as a Promotion, you should add following XML stanza as the pay load to this request:

request.addPayload("<code>promotion</code>");

OR, if you want to Flag your Post or Discussion as a Job, you should add following XML stanza as the pay load to this request:

request.addPayload("<code>job</code>");

And, finally send the request to LinkedIn REST API server:

signOAuthRequest(request);
response = request.send();

When you run this updated program, you will see an output similar to the following on your console:

The Code 204 is fine, in our case as it complains about “No Content”. Your Post or Discussion on a LinkedIn Group has been Flagged as a Promotion or a Job.

Tuesday, 24 September 2013

Share a Post on Facebook Page using Scribe and Java

As a second Part of my earlier post, I will now demonstrate how you can Share a Post on a Facebook Page using Scribe and Java.

The pre-requisites/setup is the same as mentioned in the first part. i.e.

  • Create a Facebook App and get App ID & App Secret
  • Initialize Scribe’s OAuthService using above information
  • Get Short Lived Access Tokens and then exchange it a Long Lived Access Token – Note that these tokens are the Facebook App’s Tokens

    Token accessToken;

    //facebook app's short-lived access token
    //accessToken = getFbAppShortLivedAccessToken(oAuthService);
    //accessToken = new Token("CAAF3yH4PHBkBAO4mTp8sgngVkNgQxAebc1xt4O64qeOqlzxiI7vyJpM8Ml7VAIKROHPJB5IgDEgi0ShfWIkrnuMirmEm0UjuYFSrRlaURj9YWEWWKLrBQN5vrjFkid4JPMMYsewEcODKe73dp3LYA2JeHld8ZAJc1EkLZCr3HNdYLprSJF", "");

    //facebook app's long-lived access token
    //accessToken = getFbAppLongLivedAccessToken(oAuthService, accessToken);
    accessToken = new Token("CAAF3yH4PHBkBAKUwtBB5SAEreaLN2uVDRI48Q5LhAEHn2kUKaCyDcUO1y8ZBobqFccBx7QDdIWDd4gKJcQpZCYMAIy7P5KIKRBrvzuliJpjUJW18QUU3ijk4NMqROZAPmmrHqf24PufYNK9R26vRn9X7suDtuSze3eKvh5zSrZADZAkZCZARHan9ZAyWZBZBKvhWUZD", "");

  • You will also have to get the Short and Long Lived Access Tokens for the Facebook Page, on to which you want to share a post

    Token pageAccessToken;

    //facebook page's short-lived access token
    //pageAccessToken = getFbPageShortLivedAccessToken(oAuthService, accessToken);
    //pageAccessToken = new Token("CAAF3yH4PHBkBAMzY4Tyi5nyzhckF2DZC0V3ZBWjd5orLwZCw2Xv6lZBhCxsB29HCwPKdF8iMPgqmdurK9ZB2vmL7wPHlrWxagZA329QZBrnwkswZAMPZCDTvL5xcfCAvmZCTQXe6kS5ZAbUIELd1TeqB0pbjmkYh6w6kTNxtvRCSnAtDWOLMeP7qvpPMFXP21JFzToZD", "");

    //facebook page's long-lived access token
    //pageAccessToken = getFbPageLongLivedAccessToken(oAuthService, pageAccessToken);
    pageAccessToken = new Token("CAAF3yH4PHBkBAOSP9vZA0ZA876psVlRIfl1kQ4wdZBRm6M2nCx6Ru9eurBGzcx1zfLtBDZC2EFnGSNWuukwLpmgVHil57oXiZBLYRoWl0h8DcE8XSpAGvcxOumJrZBHZAEEFjZA1jrDVZCJu8ZBLZBQUqwKll0Ngy4EZCiglCYGSTj9NbOkuyX8S6vQl", "");

Finally:

OAuthRequest request = new OAuthRequest(Verb.POST, "https://graph.facebook.com/" + FB_PAGE_NAME + "/feed");
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
String message = "test message - " + sdf.format(new Date());
request.addBodyParameter("message", message);
String link = "
http://codeoftheday.blogspot.com/";
request.addBodyParameter("link", link);
request.addBodyParameter(ACCESS_TOKEN, pageAccessToken.getToken());
oAuthService.signRequest(accessToken, request);
Response response = request.send();

Note that we have used accessToken, Facebook App’s Access Token, to sign the request as usual. And, we are passing the pageAccessToken, Facebook Page’s Access Token, as a parameter of our request. This will ensure the Facebook Page Impersonation, such that the Facebook Page’s name and icon will be displayed as the Sharer. If you don’t pass pageAccessToken as a parameter than the Facebook App’s name and icon will be displayed as the Sharer.

Thursday, 12 September 2013

Share Post on Facebook Wall or Timeline using Scribe and Java

In this post, I will demonstrate how you can share post on your Facebook Wall or Timeline using Scribe OAuth API and Java.

As a pre-requisite, log into your Facebook account and go to Facebook Developer Apps section. If this is the first time you will have to register (no forms to fill, just a click of a button; more of a permission grant).

Create a new app, just fill the “Basic” information.

new facebook app

Once you click on “Save Changes”, your new app will be created and a unique “App ID” and “App Secret” will be assigned to your app. YOU SHOULD NOT SHARE THIS WITH ANY ONE and KEEP IT SAFE AND SECURE.

Besides, you will need these (ID & Secret) to make calls to Facebook servers via Graph API.

private static String FB_APP_KEY = "012345678901234";
private static String FB_APP_SECRET = "0123456789abcdef0123456789abcdef";

First thing to do is to initialize Scribe’s OAuthService, so that we can sign our requests to be sent to Facebook servers.

new ServiceBuilder()
        .provider(FacebookApi.class)
        .apiKey(FB_APP_KEY)
        .apiSecret(FB_APP_SECRET)
        .callback("
http://www.smhumayun.com/”)
        .build();

The call back URL used above is the same which we provided as a “Site URL” during our Facebook App creation. With one very important difference, the trailing forward slash “/”. No matter, if you have provided that trailing forward slash in your app’s “Site URL” or not, you MUST always append a forward slash “/” in your callback code. This might seems insane to you, but trust me, a lot of developers have banged their heads against the wall for this minor detail Smile

Next you’ll have to fetch the Short-Lived Access Token (typically expires in an hour or two).

String authorizationUrl = oAuthService.getAuthorizationUrl(null);
System.out.println(authorizationUrl);
System.out.println("And paste the authorization code here");
System.out.print(">>");
Verifier verifier = new Verifier(new Scanner(System.in).nextLine());
fbAppShortLivedAccessToken = oAuthService.getAccessToken(null, verifier);

The above code will print an Authorzation URL on console, you should copy that URL and open it in a browser and it will redirect to the same “callback” URL (we used above). The redirected URL will contain a ‘code’ query string parameter, copy the value of ‘code’ param and paste it on the console.

If this is a one time test, than you are good with Short-Lived Access Token, but if you want to make it part of a program, you need to exchange it with a Long-Lived Access Token (typically expires in 60 days).

OAuthRequest request = new OAuthRequest(Verb.GET
        , "
https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token"
        + "&client_id=" + FB_APP_KEY + "&client_secret=" + FB_APP_SECRET
        + "&fb_exchange_token=" + fbAppShortLivedAccessToken.getToken());
oAuthService.signRequest(fbAppShortLivedAccessToken, request);
Response response = request.send();

In order to get the Long-Lived Access Token, you have to send the Short-Lived Access Token to Facebook server with an exchange token request with “grant_type” as “fb_exchange_token”. Note, we use the same Short-Lived Access Token to sign this request.

As response to this request, you will get the Long-Lived Access Token, which you can safe/persist and re-use thereafter.

Finally:

OAuthRequest request = new OAuthRequest(Verb.POST, "https://graph.facebook.com/me/feed");
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
String message = "test message - " + sdf.format(new Date());
request.addBodyParameter("message", message);
String link = "
http://codeoftheday.blogspot.com/”;
request.addBodyParameter("link", link);
oAuthService.signRequest(accessToken, request);

You will create a new request to post a ‘message’ and a ‘link’ to your Facebook Wall or Timeline.

If all goes well, and the message/link were posted successfully, you will receive an “id” of the newly created post.

Tuesday, 10 September 2013

Making Java’s Multiple Interface Inheritance more “adaptable”

If there's one feature that I like about Multiple Inheritance, that would be "adaptability". When a child is inherited from multiple parent, child will automatically "adapts" to all the changes made in all the parents, from then and onwards. No explicit changes in child is required, in order to keep it "compatible" or "in-sync" with the parents.

How is it different in Java? in Java, the concept of Multiple Inheritance is further split up into Multiple Interface Inheritance and Multiple Implementation Inheritance specifically. Java supports the former and relinquish the later.

Consider a typical example of TypeC inheriting from TypeA and TypeB. In Java, the closest you can come to Multiple Implementation Inheritance (functionally) is as follows:

public interface TypeA { 
void methodA();
}
public interface TypeB { 
void methodB();
}
//multiple interface inheritance
public interface TypeC extends TypeA, TypeB {
void methodA();
}

public class TypeAImpl implements TypeA {

@override
public void methodA() {
System.out.println("method A");
}
}

public class TypeBImpl implements TypeB {
@override
public void methodB() {
System.out.println("method B");
}
}

public class TypeCImpl implements TypeC (

//object composition
private TypeAImpl delegateAImpl;
private TypeBImpl delegateBImpl;

@override
public void methodA() {
//method delegation
delegateAImpl.methodA();
}
@override
public void methodB() {


//method delegation
delegateBImpl.methodB();
}
@override
public void methodC() {
System.out.println("method C");
}
}

 


Problem? lack of "adaptability"


In our example above, we try to emulate Multiple Implementation Inheritance as closely as possible using:


  • Multiple Interface Inheritance
  • Object Composition
  • Method Delegation

However, contrary to the Multiple Implementation Inheritance, the child still, will not "adapts" to any of the following changes made to the parents. Even worst, these changes will break the child:


  • Add a new method - if we declare a new methodA2 in TypeA and define its implementation in TypeAImpl. TypeC will instantly adapts to the change in TypeA due to multiple interface inheritance. And, because TypeCImpl implements TypeC, it will also adapts to the newly declared methodA2 in TypeA. And so, TypeCImpl will break instantly because it either needs (a). the implementation of methodA2 to be defined OR (b). to change its type from a concrete class to an abstract class.
  • Update the signature of an existing method - if we change signature of methodB in TypeB from "void methodB()" to "void methodB(int b)" and similarly change its implementation in TypeBImpl. TypeC will instantly adapts to the change in TypeB due to multiple interface inheritance. And, because TypeCImpl implements TypeC, it will also adapts to the recently changed methodB in TypeB. And so, TypeCImpl will break instantly because it either needs (a). the implementation of "void methodB(int b)" to be defined OR (b). to change its type from a concrete class to an abstract class. Also, note that the methodB implementation in TypeCImpl will now start complaining about the erroneous code "delegateBImpl.methodB()" because such a method does not exists in TypeBImpl any more.
  • Remove an existing method - if we remove methodB declaration in TypeB and implementation in TypeBImpl. TypeC will instantly adapts to the change in TypeB due to multiple interface inheritance. And, because TypeCImpl implements TypeC, it will also adapts to the recent removal of methodB in TypeB and TypeBImpl. And so, TypeCImpl will break instantly because the methodB implementation in TypeCImpl will now start complaining about the erroneous code "delegateBImpl.methodB()" because such a method does not exists in TypeBImpl any more.

All of the changes above require mandatory changes in child as well and this sucks big time! any change to any one of the parent components, will "force" a ripple effect of mandatory changes to all of the child components down the hierarchy and if you don't do that, it'll break them apart.

Let me raise the bar a little more, assume if, TypeA and TypeB belongs to publicly published APIs, ApiTypeA-1.0.jar and ApiTypeB-1.0.jar. And then one or more of the changes mentioned above is made to those APIs in their next releases, ApiTypeA-2.0.jar and ApiTypeB-2.0.jar respectively. Now, if you don't want the changes, that's fine, you can keep pointing to the older version 1.0 of the dependencies and there won't be any issues. But, most likely in a real world scenario, at some point you need the upgrade to newer versions of the dependencies. But, you can not do that, until and unless you have the necessary resources to make appropriate changes in your code otherwise it will break your code.

Think of those cases specifically, where only additions are being made to relatively newer component(s) in order to add more functionality to make them feature rich. Additional methods/features, with out any changes or removals to existing ones, should not have any impact, the transition should be seamless, but this is not the case as shown above.

So, to make Multiple Interface Inheritance more "adaptable" and to bring it (functionally) one step closer to Multiple Implementation Inheritance with out the negatives of the later, becomes the motivation of Project MI+.

Friday, 6 September 2013

Project MI+ | Multiple Inheritance in Java like never before!

 

project mi  logo

Project MI+ add multiple inheritance support to your java classes, so they can (functionally) "extend" (read inherit) from multiple parent classes.

Project MI+ is an open source project published under Apache Public License version 2.0.

Suppose we want to inherit our Child class from two parent classes: (1) ParentOne and (2) ParentTwo.

public class ParentOne {
public void parentOneMethod() {
System.out.println("parent one method");
}
}

public class ParentTwo {
public void parentTwoMethod() {
System.out.println("parent two method");
}
}

First we will 'extract' interfaces from the parent classes mentioned above. [Project MI+ promotes the use of classic design principle 'Program to Interface']

public interface ParentOne {
void parentOneMethod();
}

public interface ParentTwo {
public void parentTwoMethod();
}

public class ParentOneImpl implements ParentOne {
public void parentOneMethod() {
System.out.println("parent one method");
}
}

public class ParentTwoImpl implements ParentTwo {
public void parentTwoMethod() {
System.out.println("parent two method");
}
}

Now we can simply:


  1. Create a Child interface,
  2. Extend it from parent interfaces,
  3. Add "Multiple Inheritance Support" by annotating the Child interface with MISupport (JavaDoc | Source Code) annotation.
import com.smhumayun.mi_plus.MISupport;

@MISupport(parentClasses = {ParentOneImpl.class, ParentTwoImpl.class})
public interface Child extends ParentOne, ParentTwo {
}

For multiple inheritance to work, you should always create new instances of MISupport (JavaDoc | Source Code) annotated classes (only) via MIFactory (JavaDoc | Source Code) instead of directly instantiating them using java's new keyword and a constructor.

import com.smhumayun.mi_plus.MIFactory;

...
MIFactory miFactory = new MIFactory();
Child child = miFactory.newInstance(Child.class);
child.parentOneMethod();
child.parentTwoMethod();
...

The child now refers to an object which (functionally) inherits methods from all the parent classes.

Click here to read more about Project MI+

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.

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.

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

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

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

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”.

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

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

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

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:

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

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:

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 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).

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:
  • @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

Create your tiles definition file and define all tiles definition:

Create following JSP files:

BaseLayout.jsp:

Header.jsp:

Footer.jsp:

DisplayServerTime.jsp:

DisplayTotalVisits.jsp:

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.

Once you run the above example, you will notice an output similar to this one on your console:

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:

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