Category Archives: Uncategorized

Using scaffolding with REST in grails

You are developing an app and using Grails as its backend, now days REST is the new buzzword and you’ll probably want to create a REST api via Grails. Fortunately, Grails support REST api out of the box (version 2.3 and above), but what happens if you want to support scaffolding + REST api in the same controller.

Well, it seems that Grails supports it, although not in the most elegant way, by using content negotiation.
You have an ability to tell Grails in what format you want your response either by supplying a suffix to the request (.json) or by specifying it in the header. Either way it gives you the following ability:

  1. Define a regular Grails controller.
    class FamilyController {
     static scaffold = true
    }
    
  2. When calling the controller you can add a suffix to you call
    http://localhost:8080/app/family/index.json
  3. You should be able to get back results as json, same applies to xml.
  4. As you can see the default content being served is html so you can also access the scaffolding page.

The annoying part here is the fact that you cannot access your resource in a “by the book” manner, .e.g. you need to use an action like show, edit/${id} to access your resource and you can not do it directly via family/1

Advertisements

Leave a comment

Filed under Uncategorized

ConcurrentModificationException when using unmodifiableCollection

Learning something new everyday.

One of the best ways to avoid data manipulation problems in concurrent environments is to use read only data sets, one of the best way way to create a read only collection in Java is to use unmodifiableCollection method, however this method is not as innocent as you may think.

Behind the scenes unmodifiable collections are just a stub that redirect all methods to the original collections, except for methods that actually change the collection like add etc, in which case it throws an exception.

Test yourself, what happens when trying to iterate over an unmodifiable collection, when in a different thread new elements are added to the original collection… ConcurrentModificationException .

The best way to avoid it is to actually create a copy, e.g. new LinkedList(…)

To sum it up:

  1. Use unmodifiable collections whenever you want to make sure that in an external usage of the collection nothing will be modified, for example use it as a return value for your methods.
  2. Use different mechanisms in case of a multi-threaded environment, for example creating a real copy.

Leave a comment

Filed under API, Uncategorized

Android 101

Gave a lecture today on Android development for ILTechTalks, mainly first steps.

Talked about the following topics:

  1. Prerequisites
  2. Activities
  3. Widgets and layouts
  4. Saving content
  5. Publishing to the market

You can download the presentation and related code from here. You are more than welcomed to use this content under the creative common license.

Leave a comment

Filed under Uncategorized

Which is less expensive: Amazon or self-hosted? The start-up angle

I read today a wonderful article about AWS (iaas) vs self hosted solution , the pros and cons money wise.

Couple of points regarding the discussion that relates directly to startups:

  1. The author recommends for spiky/unknown/unproven loads to stay with the public cloud,later in the comments he adds: “ …let’s the the situation of an early-stage business. While I’ve referred to “spiky” loads, there’s another way to say that which is “variable”, “unknown” or “unproven” loads which describes the situation that a startup usually finds itself in. In those cases, the fact that you cannot forecast very well is the reason why it’s unlikely you’ll save money by self-hosting…because you’re very unlikely to buy the right amount of capacity.
  2. He is talking here mainly about infrastructure as a service (iaas), one major point that I think he overlooked here is that many startups don’t want to deal with the provisioning and machine preparations (you still have to do that under iaas), we want to be lean and quick to market, I would prefer to pay more money for platform as a service (paas like app engine) and deal with writing the actual business logic.
  3. Disaster recovery is also important, the ability to spread your machine across several geographical areas is costly.
  4. No matter how you’ll look at it, there is a good chance that as a startup you’ll use cloud api for your business, there are so many services today that cuts down your dev time and are only available as public api on the cloud. A good example might be google analytics. So you can’t really escape it.

3 Comments

Filed under Uncategorized

Best place to bootstrap a startup

The university

Where I live every couple of weeks a new entrepreneurship hub is opening its gates, promising a quiet place, free wifi, free coffee and best of all a place where you’ll keep your creative juices flowing, hey, after all being in an environment that drives innovation forward got to be a good place.

But as we all know for startups everything comes down to money (sorry, that’s the harsh reality), these places cost couple of bucks that can be spent wisely in different places (pizza for example), so the university sounds like a perfect place… it’s free.

I know, I know, many would prefer to be ran over by a bus then to go back to the university, but it’s a simple common sense, you have free wifi (in most universities where I live), cheap coffee and food (after all these are students, probably in worse condition than me) , white boards, desks and above all the wonderful feeling of innovations and cutting edge that universities has.

So why not ?

Leave a comment

Filed under Uncategorized

Using any Java paas solution for the time being locks you down

After reading this paas comparison and some others about various paas solutions currently on the market I want to clarify an important point regarding portability of AWS based applications (CloudBees and Beanstalk).

If your application uses a standard rational database and a standard ec2 instance then you are fine and your application is probably highly portable, however the moment you want to use features like nosql, blob/static storage and messaging then you have to use proprietary api.

  • CloudBees in case of nosql DB has support for MongoDB and couchDB via external support, however Beanstalk has a proprietary nosql db called simpleDB.
  • In case of static storage both platforms support S3 which has its own api.
  • and in case of messaging you have sqs which again has its own api.

Any java paas solution today locks you down somehow, I do agree that the lack of full Java EE/SE stack on app engine is worse than the above mentioned, but it’s important to remember that all paas solutions require some kind of proprietary api.

1 Comment

Filed under Uncategorized

Real time Facebook notification from app engine

It’s hard  to find a good example for Facebook authentication on app engine using java.

I’ll try to do the following:

  1. Explain the general flow for achieving  Real time notification on app engine.
  2. Show some code snippets for implementing the above flow.

General Flow + Code

Step 1

Use the callback mechanism of Facebook to start the authentication process.
http://www.facebook.com/dialog/oauth?client_id=<client_id&gt; &display=touch&scope=offline_access,read_stream&redirect_uri=<callback_url>

I’m calling to this URL from a mobile app,therefore I use display=touch, in addition pay attention that I’m asking from the user to grant me offline access, I’m assuming that I’ll update the user long after the authentication token will expire.

Step 2

I’ve prepared a callback get method on my app engine. Facebook calls my callback url passing to it a code. The code means the user granted me permissions.

Map<String, String[]> parameters = req.getParameterMap();
if (parameters.containsKey("code")) {
...
facebookAuthCode = ... // Get 'code' value

Pay attention that the code is not the access token (which is the holly grail), the access token will allow us to act on behalf of the user.

You need to call another url with the code you extracted, the response will be the access token.

String facebookAuthUrl = String.format("https://graph.facebook.com/oauth/access_token?client_id=%s&redirect_uri=%s&client_secret=%s&code=%s",
							Constants.FACEBOOK_APP_CODE, reconstructedURL,
							Constants.FACEBOOK_APP_SECRET, facebookAuthCode);
URL localUrl = new URL(facebookAuthUrl);
URLConnection conn = localUrl.openConnection();
conn.setDoOutput(false);
BufferedReader rd = null;
try {
	// Get the response
	rd = new BufferedReader(
	new InputStreamReader(conn.getInputStream()));
...

The easiest way to build a valid callback url is to use the request object.

URL baseURL = new URL(req.getScheme(), req.getServerName(),req.getRequestURI());

Now we register for real time notification.

Step 3

We need to post our data to Facebook with the appropriate parameters. They should include:

  • object – To which object in the social graph we want to listen to.
  • fields – Special fields that make up the object.
  • callback_url – Call this URL with post. In our case it is baseURL we used above.
  • verify_token – A token that will be sent back during hub mode.
  • access_token – built from facebook_app_code|facebook_app_secret . You should get these two values from your Facebook account. Pay attention to ‘|’.
// Use String builder instead of just regular string.
String data = URLEncoder.encode("object", "UTF-8") + "="
				+ URLEncoder.encode("user", "UTF-8");
data += "&" + URLEncoder.encode("fields", "UTF-8") + "="
				+ URLEncoder.encode("home", "UTF-8");
// Send real time updates to this URL.
data += "&" + URLEncoder.encode("callback_url", "UTF-8") + "="
				+ URLEncoder.encode(reconstructedURL.toString(), "UTF-8");
// A token used to verify that it is actually me who is running the
// verification process.
data += "&" + URLEncoder.encode("verify_token", "UTF-8") + "="
				+ URLEncoder.encode(Constants.FACEBOOK_VERIFY_TOKEN, "UTF-8");
data += "&" + URLEncoder.encode("access_token", "UTF-8") + "="
				+ Constants.FACEBOOK_APP_CODE + "|"
				+ Constants.FACEBOOK_APP_SECRET;
// Subscribe by doing a post.
URL url = new URL(String.format(
				"https://graph.facebook.com/%s/subscriptions?access_token=%s",
				Constants.FACEBOOK_APP_CODE, accessToken));

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

wr.write(data);
wr.flush();
...
wr.close();</pre>

Almost done here the final stage is the hub mode.

Step 4

Facebook is using hub mode to do a final verification of the process. You will receive back a verification token that you sent during your registration process (step 3), you will have to make sure it is equal to what you sent and then response with a challenge string that Facebook sent.

String verifyToken = (String) parameters.get("hub.verify_token")[0];
if (verifyToken.equals(Constants.FACEBOOK_VERIFY_TOKEN)) {
	log.info("hub.mode test is valid");
	resp.setContentType("text/plain");
	resp.getWriter().print(req.getParameter("hub.challenge"));
}

That’s it you are done you are now registered.

4 Comments

Filed under Uncategorized