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:

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:

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

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:

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:

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:

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

The output of the above program is:

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.

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’

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