A good article about the garbage collector

Essential and very accurate article about JVM garbage collection by Alexey Ragozin:

http://aragozin.blogspot.com/2011/12/garbage-collection-in-hotspot-jvm.html

LinkedIn API, OAuth and Scribe

Hello everyone.
We know OAuth is a beautiful authentication service… in terms of concept. But when it comes to implementation, it’s a real pain in the ass. I found myself into fighting against it using Java to authenticate on LinkedIn, the popular reputation network. After a few minutes I was crying like a baby. It’s not impossible to do it by yourself, but the patience required is more than I could offer.

So I found out this library, named Scribe written by the brilliant software engineer Pablo Fernandez  that definitely helped a lot.
I copied and run his server side authentication example and worked like charm.

I’m taking his example for Twitter right from here site here (hope you don’t mind Pablo) https://github.com/fernandezpablo85/scribe-java/wiki/getting-started :

OAuthService service = new ServiceBuilder()
                           .provider(TwitterApi.class)
                           .apiKey("your_api_key")
                           .apiSecret("your_api_secret")
                           .build();
Token requestToken = service.getRequestToken();
String authUrl = service.getAuthorizationUrl(requestToken); Verifier v = new Verifier("verifier you got from the user");
Token accessToken = service.getAccessToken(requestToken, verifier); // the requestToken you had from step 2
OAuthRequest request = new OAuthRequest(Verb.GET, "http://api.twitter.com/1/account/verify_credentials.xml");
service.signRequest(accessToken, request); // the access token from step 4
Response response = request.send();
System.out.println(response.getBody());

And guess what, it worked like charm with LinkedIn also (just changing a few details you can find by yourself).

This is all beautiful… a pity what I had to implement was a client side authentication. The user authenticates on a LinkedIn popup, generates a cookie with an auth token in it that is then sent to our server that must use it run an exchange with the LinkedIn server to obtain a real access token… This is a very powerful authentication process, but implementing it is, again, a work of patience.

And again, reading through LinkedIn developers forums, Scribe shows up again, used like this:

OAuthRequest req = new OAuthRequest(Verb.POST, "https://api.linkedin.com/uas/oauth/accessToken");
req.addBodyParameter("xoauth_oauth2_access_token", jsnpToken);
Token token = new Token("","");
service.signRequest(token, req);
Response resp = req.send();
String body = resp.getBody();

where “jsnpToken” is the auth token passed through the cookie and “body” contains a string describing the real access token you’ll use to sign further requests.

Wasn’t that easy?

Thanks Pablo!

Java : Final oddity

Hey, I’m back.

I was captured in optimization facts lately and I ended up chasing the true advantages in using final stuff correctly (in Java of course). But much before I could state I have an opinion, I found myself trapped in a strange JVM… mystery.
What I wanted to understand is if the JVM can listen to our ‘hints’ to take the final stuff  and use it inline.
This topic has been subject of many talks, mostly because it’s hard for the JVM to determine whether a field won’t change at runtime or not. This could be obvious at first sight: final fields won’t change. But when reflections come into play, well… you’ll never know.
So can reflections change a final field? This is the question. And the answer is: WHO KNOWS? If you look at this document, you’ll notice it’s a long and painful story.

Since there’s nothing better than trying stuff yourself, I tried to discover it by doing a simple test program.

public class Malicious {
	public final int testField = 5;

	public static void main(String[] args) throws Exception{
		Malicious m = new Malicious();
		Field f = m.getClass().getField("testField");
		f.setAccessible(true);
		f.setInt(m, 7);
		System.out.println("f: "+f.getInt(m));
		System.out.println("m.testField: "+m.testField);
	}
}

Before I tell you the results, let me first say that I used:

- MacOSX 10.6.4
- 1.6.0_22
So you won’t get upset if you get different results on different environments.

RESULTS:
f: 7
m.testField: 5

Honestly, this makes no sense. No security exceptions, nothing, just different values. And of course, if I remove the final keyword, what I get is:
f: 7
m.testField: 7

I’m honestly happy to state that a final field cannot be modified via reflections. I’m less happy to say the behavior is not supported by a homogeneous communication because I only got a security exception when I tried to remove the setAccessible line.

Mad snippet of the day (too much power for a useless idea…)

Especially written for a servlet container… just guess what it does…

public <E>E toObject(HttpServletRequest request, Class<E> type)
                 throws InstantiationException, IllegalAccessException {
  E inst = type.newInstance();
  Method[] mets = inst.getClass().getDeclaredMethods();
  for(Method m : mets){
    if(m.getName().startsWith("set"))try{
       String varName = m.getName().
                           substring(m.getName().indexOf("set")+3);
       varName = Character.toLowerCase(varName.charAt(0))+
                                         varName.substring(1);
       String val = request.getParameter(varName);
       if(m.getParameterTypes()[0]==Integer.class)
           m.invoke(inst, Integer.valueOf(val));
       if(m.getParameterTypes()[0]==Boolean.class)
           m.invoke(inst, Boolean.valueOf(val));
       if(m.getParameterTypes()[0]==String.class)
           m.invoke(inst, val);
      }catch(Exception e){e.printStackTrace();continue;}
     }
   return inst;
}

Trick: Invoke methods with varargs

Two days ago I faced a strange situation:
Java: let’s say you have a main function (that, as you all know, accepts varargs arguments) and want to use it as a gateway for other main functions. You don’t want to specialize the gateway, so that it will work for any new subprogram your jar will have added. The gateway will receive, as first argument, the subprogram class name.
The first thing to do is easy:

 Class c = Class.forName(args[0]);

Next, we want a Method object for the “main” function:

Method mainMethod = c.getMethod("main",String[].class);

Next, we want to invoke the method but the thing shows up trickier than expected, because if you:

mainMethod.invoke(null, args); //NOT WORKING

Nope, nada. Why? Because the args you’re passing would be splitted in single arguments, that IS NOT what the function is expecting. In fact, “main” wants a “varargs”. That sounds like a nonsense, but varargs is in fact a little naive…
To workaround this:

Object o = args;
mainMethod.invoke(null, o); 
and there you go. This was not hard to solve, and thinking of it a little, it looks quite obvious, but the runtime error you get doing it the wrong way is a little too tricky, so I wanted to share this with you.
Peace
Follow

Get every new post delivered to your Inbox.