Showing posts with label source code. Show all posts
Showing posts with label source code. Show all posts

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:

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.

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

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:

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:

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.

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

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:

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:

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:

web.xml:

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

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’

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