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+