Showing posts with label json. Show all posts
Showing posts with label json. Show all posts

Monday, February 27, 2012

Neo4J with Scala Play! 2.0 on Heroku (Part 8) :: Scala template+Arbor.js to browse Neo4J via Play 2.0


Note

This post is a continuation of this post, which is the seventh part of a blog suite that aims the use of Neo4j and Play2.0 together on Heroku.

Viewing Neo4J Model Object in Play2.0

Goal

In this post, I'll talk about some functionalities that Play2.0 offers to create web application/site.

The main goal will be to have html views that enable us to create User, Group and link them, but not only, we'll use arbor.js to view what's being created or linked in Neo4J as a... graph of course.

Basically, it will consist into one html page, containing several forms for creating model instance (or link) through AJAX call on Json controllers.

So let's begin by explaining how to define a querying and persisting controllers using Play 2.0 Form.

Controllers

In that case, we'll take basic needs for our use case, that is, to retrieve the users list stored in Neo4J or create a new group.

Get Users

Briefly, Play 2.0 as the notion of controllers to handle server request, such controllers are bound to urls using a route configuration.

So what we have to do here is to create a controller, let's say Users, with a handler named j_all for list of users rendered in Json.

Using what we've discussed in previous posts, such controller and definition are rather simple, check this out:

As we can see, we have simple call the Model persistence utility object to retrieve all defined User in Neo4J. Which we are rendering directly in Json thanks to their Formatter. And finally, we stream the result in the http response.
Mmmh, simple no ? Here we did:

  1. send a Json request to Neo4J requesting all nodes that are linked to the root using the kind users (found using the User's ClassManifest)
  2. retrieve the Json response from Neo4J and un-marshall them in a List[User] (using the User Formatter)
  3. re-render them into the expected Model Json Format (again using the Fomatter)
  4. generate the String representation
  5. append it in the response body
  6. define the content type as being Json
In one single line.

To test it, roughly, just use this url http://localhost:9000/users.json. This will return a Json encoded response.

Create Group

Now, we want to add the possibility to create a new group remotely. For that, we'll create a controller Groups which defines a create handler.

This handler expects to receive a group name. After what, it creates the group instance and persist it in Neo4J.

To recover such request parameter (in a POST since we are creating something and changing the server state), we use a Play 2.0 construction play.api.data.Form that offers a lot of helpers to parse the body into a map of values (can be embedded).

In the following example, the goup name is extracted form the request's body (url encoded) as a nonEmptyText mapped as name. This is a helper mapping for extracting String that cannot be empty.

As we can see, the Form can be directly rendered in the Model instance by giving an apply and unapply functions after the mapping definition.

Javascript Routing

Using static urls are cool... no ok, let's try to use what some calls Web 2.0, you know Ajax.

The problem comes when you have to deal with Urls within Ajax calls. How to keep track of your urls changes for instances.

Pretty hard, so let's forget about hard coded urls in your javascript and use a routes file that can be downloaded client side. This routes file contains all your controllers' url mapping that you want to be exposed in javascript (if I can say).

How it works is simple:
  1. Use Routes.javascriptRouter to define a javascript object and the controllers to be remoted
  2. For each of them, you must use the following object controllers.routes.javascript..
  3. This object is created at compile time when defining the controller in the route conf file
  4. defines a handler (in the Application controller f.i.) that return the result of the javascriptRouter as being javascript file
  5. route this new controller to what you want (like /js/routes)
Having done that, you are now ready to use the created object in the javascript part.

If we take the controller controllers.Users.j_one (returns a User base on its given id), we'll have in our javascript access to a js function playRoutes.controllers.Users.j_one(id) that can takes an id.

By using this js function, you'll have in return a js object that defines at least two useful properties:
  • url: the formatted url for the controller (having compiled the parameter in the url)
  • ajax(c): a jquery (by default) ajax function that takes a payload object, but already defines the url and the method.
So far so good, but to use all of these stuffs, let's see in a coffeescript (thanks Play 2.0) example:

In the previous example, I wrote the ajax call my-self using jQuery... so I could have simply use the ajax property. But nevermind, I love sometime to be control freak.

C'est chic! No?

Arbor.js

For browsing our model graph, I've used arbor.js as the rendering framework, because it's the best one for graph... that's it. 
Since my intent here isn't to explain it, I'll leave you alone with that part. But I recommend you to browse its site here.

So what I did is simply using Users as nodes, all linked to a central root node. Clicking one them will show you their inter-relationships.

I've also added a select box that helps you showing all users in a chosen group.

Taking that the next post will be on how to deploy the whole stuff on Heroku. I don't have at this time any instance in the wild, but if you wish you can clone (and fork) my repo on github for this posts' suite.

But here is a preview of what has been achieved.
Fun but not so cute  -> I'm not a designer... :'(


Next post, the last, will talk about how to deploy this whole thing onto the Heroku PaaS.

Saturday, February 25, 2012

Neo4J with Scala Play! 2.0 on Heroku (Part 7) :: DSM+DAO+Neo4J+Play


Note

This post is a continuation of this post, which is the sixth part of a blog suite that aims the use of Neo4j and Play2.0 together on Heroku.

Using Neo4J in Play 2.0... and simple DAO

What I'll intent to show is a way to use a Domain Specific Model, persisted in a Neo4J back end service. For such DSM, we'll have an abstract magic Model class that defines generic DAO operations.

For simplicity, we'll try to link each category of classes to the root/entry node. For instance, all the Users will be bound to the entry node by a reference of kind user.

Model

I'll choose the very common use case, that is, Users and Groups. Here is its shape:
  • A User has a first name
  • A Group has a name
  • A User can be in several Groups
  • A Group can contain several Users
  • A User can know several Users
Let's keep the classes definition aside for a few, and stick to the persistence service.

Graph Service

The Graph Service is an abstraction of what is needed for a Graph Persistence Layer. It is bound to a generic type that defines the model implementation and defines traversal and persistence operations of graph's nodes.

Graph Service for Neo4J

Let's update now, the service that has been used in the previous post, for Neo4J persistence, in order to have it able to deal with model instance.

Let's start with the saveNode operation to see what is needed in the model and elsewhere.

In this Gist above, I've enlighted some points that must be found around the Model construction. (A) and (C) are composing a Json Format (as SJson propose), (B) is more related to model abstraction.

(C) has a special need when used with Dispatch, we could have a Dispatch Handler that can do both action parsing/unmarshalling and direct use in a continuation.

Model

Now, we are at the right point to talk the Model, since we've met almost all its requirement. So let's build a Magic Model class that can be extended by all concrete model classes.
Skeleton
That's the easy part, we just define the id property that is an id (part of the Rest Url in Neo4J).
Formatter
Ok, this part is simple too in this abstract Model definition because, a Format implementation must be part of the concrete DSM classes. That is, User that extends Model must define a Format[User] instance, and put it in the implicit context.
So, at this stage we have Model and User like this:

Class -- Relation's kind : F-Bounded
As we saw in the saveNode method needs to associate the concrete class to a relation kind. But what I wanted is to have a save method in Model, that implies that we cannot (at first glance) give the saveNode the information needed, that is the concrete class.

For that, we'll use a F-Bounded type for Model, that way we'll be able to give the saveNode method what is the really class... Mmmh ok, let me show you: But that's not sufficient, the saveNode method will need to use such available ClassManifest to find the relation it must create.

I choose a very common and easy solution, which is having a function in the Model companion that helps in registering classes against relation kind.

Model Dispatch Handler

Now we'll discuss something I find really useful and easy in Dispatch, create a Handler that can handle a Json response from Neo4J into a Model instance.
For that, we have already defined in previous post a way to handle json response into Play's JsValue.

Now, what we need is to use the implicit formatter of all model concrete classes to create instances. And it'll be the way to reach the goal, except that a problem comes from the Json response of Neo4J: the data is not present at the Json root, but is the value of the data property.
So it breaks our Format if we use it directly.

That's why the above definition of the Handler takes an extra parameter which is the conversion between JsValue to JsValue, that is to say, a function that goes directly to the data definition.

saveNode

Finally, let's gather all our work in a simple implementation of a generic saveNode function: As we can see, it's very easy to handle Neo4J response as DSO and use them directly in the continuation method of the Handler.

Usage

having all pieces in places (check out the related Git repo here). We can now really simply create a User and retrieve it updated with its id, or even get it from the database using its id.

In the next Post, we'll create some Play template for viewing such data, but create them also.

Tuesday, February 21, 2012

Neo4J with Scala Play! 2.0 on Heroku (Part 6) :: Dispatch+Play 2.0

Note

This post is a continuation of this post, which is the fifth part of a blog suite that aims the use of Neo4j and Play2.0 together on Heroku.

Using Neo4J in Play 2.0

In this post, we'll create a Dispatch Handler that handles Neo4J Rest Json calls in Play's Json object.
Having this in our hands, we'll be able to create a really simple service for dispatching Neo4J operations and use them in Play's views.

I've compiled the Play app on github, fork me.

NB: we'll use Dispatch but in case you wish to, you could use the Play's WS feature that might help you a lot (check this out).

Declare Dispatch deps

First of all, we have to update our Play app with the Dispatch dependency. For that, we have to update the sbt configuration file in order to add the related line.

Now, that we have updated the project, let update the application by reloading the configuration (if you're already in sbt console) and rebuild our IDEA project.


Play's Json Handler

Our goal is to use the Neo4J Rest Api that returns responses Json encoded.
So here, I'll show how we could have such response directly unmarshalled in Json object. In further posts, we'll use such handling feature to get Model instances directly (which is far more interesting).

What is necessary for that is to create a piece of code that is capable to take a subject and convert it to a JsValue. And since we love functional programming, let us have this method taking a continuation that accepts a JsValue.
In this listing, we see that we use the text parser to consume the response payload, then we ask the Play's Json parse function do its job.
Finally, we use the continuation applied to the parsed result.

Neo4J Service

Let's gather some utility urls to retrieve node, relations. In other words, urls for common usages. This service is left simple for further enhancements (next post). We see that most functions are there to create urls based on ids, but there is also the root one that directly fetches the entry node.

A Controller To Rule Them All

For the sake of this basic usage of our Handler with Neo4J, here are some examples of such requests. (full controller here).
As we can see, all we had to do is to create the correct url by using id, or Neo4J path conventions, then using the Handler operator ( >! ... how it's Play, no ?!), we have the facility to use directly JsValue instance to consume the result.
Okay, it's repetitive and the Json traversal is not shared. Let's us put this aside until the next post.
And before going ahead, I've created a pretty simple and naive view and url mapping. So check the sources on github, play it and tests the /rest et al. urls.

Next post: Enhance the handler and service to manage Domain Object.

Sunday, February 19, 2012

Neo4J with Scala Play! 2.0 on Heroku (Part 4) :: Play 2.0/Json

Note

This post is a continuation of this post, which is the thrid part of a blog suite that aims the use of Neo4j and Play2.0 together on Heroku.

Play2.0 - Scala - Json

I'm about to write a quick wrap up, of some Play20's wiki entries and stackoverflow that were all related to Json in Play2.0.
For that, I'll take some usage examples, but also present the underlying libraries (Jerkson) and the used paradigm, SJson.

Scope

Giving that the wiki pages are really clean and self-explaining, I'm not gonna enter deeply in how Json must be used with Play 2.0 albeit I'll give some prerequesites in order to help you understand how I'll use the Neo4J REST API.

play.api.libs.json

This package contains everything you'll need in order to work with Json in Play 2.0.
It defines important structure like JsObject, JsArray and even some like JsUndefined.
They usage is very easy since they are based on classical scala's Map and List of JsValue(parent type).
Here is an example of creating a JsArray and iterating items. To test it in a REPL, I recommend you to enter the Play console by using play in your repo and the console in sbt (to have all libraries loaded).

For arrays, it's quite easy (maybe wrapping could be annoying but a little of pimping can resolve that).
The Jerkson library powerful comes with JsObject usages. It has defined a very clean DSL for querying Json. Here is an example for querying a property or catch a descendant property.

play.api.libs.json.{Format, Reads, Writes}

Until now, you saw that Json is usable with Play. But, I guess that you hope more than that, since this framework is here to ease the work.
And you're right.
Play is coming with a SJson flavor for serialization and deserialization of DSO.
Three traits come in the game.

Reads

Reads defines a simple method reads:
Having a Reads defined for a type T, we can now extract such instance from Json.
With the object Reads that defines an implicit Reads instance for most common types like Option, String, Short ...

Writes

Writes, like Reads, is very simple and defines a simple method writes:
Obviously, its purpose is to convert a value of type T into its Json representation and is the inverse function reads.
A Writes object is defined too with conversion to common types.

Format

This trait is there to put the pieces together
With the help of this trait, we can now have a serializer of custom domain object from/to Json.
A good practice is to define such Format into the companion object of your DSO, so that it will come in the scope at once when using it.
Here is an example:
Let's see how to use this Format easily to go back and forth from DSO instances.

play.api.libs.json.Json._

This object is an handy one, that defines four convenient methods. Two are here to play with String and JsValue. The other are to play with types and JsValue.
Back to our simple DSO class, we can now do this:

Enhancement

In order to have more control on effects of your serialization, I would recommend you to consider the Scalaz library's Validation construct.
Indeed, it will help you having more relevant information and all at once if you reads is wrong.
Here is a talk about this (but not in Play).

In the next post, we'll talk about the Dispatch library. See it here