Multi tenant approach with Java 8 in a Play project.

In my current project, I had to implement a multi tenant approach. There is nothing new about this, I have to check if current user is the owner of some resource. And I have to do the same thing across other several actions. The best way to do this, is to build an Action composition and compose all actions with it. So, let’s say we have this route:

   /admin/users/update/:id

Now, when we try to access this resource, our interceptor will be invoked:

    @Override
    public Promise<SimpleResult> call(Context context) throws Throwable {
    	RoleType currentRole = CurrentUser.role();

    	Long currentLoggedUserId = CurrentUser.id();
    	Long clientParamId = //get parameter here;
    	for (RoleType roleType : rolesAllowed) {
    		if(roleType.acceptsRole(currentRole)
    		&& roleType.acceptsTenant(currentLoggedUserId,clientParamId)){
    			try {
    				return delegate.call(context);
    			} catch (Throwable e) {
    				throw new RuntimeException(e);
    			}
    		}
    	}
    	return Promise.<SimpleResult>pure(
    	  Controller.unauthorized("You are not allowed to see this page"));
    }

And now we have a problem. How do we extract the client id from the url? The first thing that I thought was: All parameters are in request data…

  Long clientParamId = Long.parseLong(context.request()
                     .queryString().get("clientId")[0]);

Unfortunately, Play does not provide this information anywhere :(, if you try to run this code, you will get a NPE. This probably happens because in Scala version you would not have this problem, in there you compose actions in a different way. Basically you can invoke the “call” method from your controller’s action, using the functional support provided by the language instead of using annotation. You can see more here(link). To solve my problem, I used the same approach. Let’s see:

    public static Result updateForm(final Long id) {
    	return new RoleAction(User.class, id, RoleType.ADMIN,RoleType.TENANT)
    			.call(new Function0<Result>() {
    				public Result apply() throws Throwable {
    					User user = JPA.em().find(User.class, id);
    					Form<User> filledForm = userForm.fill(user);
    					return ok(views.html.admin.users.update_form.render(filledForm));
    				}
    			});
    }

It is a little bit verbose, no doubts, but I needed to delivery this feature :). And now I can access all parameters that I need. Just to make the job less annoying, I’ve created a Eclipse template that allows me just write “roleAction” and the code template is generated automatically :).

The good thing about this approach is that, now with Java 8, we can change this implementation in order to use the new lambda support :). Play with Java8 is a lovely thing!

    return new RoleAction(User.class,id,RoleType.ADMIN,RoleType.TENANT)
   .call( () -> {
    	User user = JPA.em().find(User.class, id);
    	Form<User> filledForm = userForm.fill(user);
    	return ok(views.html.admin.users.update_form
    			.render(filledForm));
    });

What do you think? One nice thing here is that I didn’t need to change the original call method. When you have just one method in your interface, the new compiler understands this interface as a Functional Interface and allows you to pass lambda as a parameter. Java 8 support is enabled in Play 2.2.2 and Play 2.3.x!

Posted in Uncategorized | Leave a comment

One model, many validations

It is not unusual a application has more than one html form that should be bound with the same model. Think about this situation: you have a form to register a new user with just a few fields, like name, email and password. After that, you need this same user completes his registration with other fields.

This common situation puts you in a problem. How to partially apply a validation rule in the same model. Below we have the User class:

    package models;

    @Entity
    public class User {

    	private String id;

    	@Required
    	private String name;

    	@Required
    	private String email;

    	@Required
    	private String password;

    	@Valid
    	private Address address = new Address();

    	@Required
    	private String facebookId;

    	//getters and setters
    }

There are a lot of validations! In the first situation, you only need to validate three fields. Let’s see the code:

    public static Result create(){
    	Form<User> filledForm = newUserForm.bindFromRequest("name","email","password");
    	if(filledForm.hasErrors()){
    		return badRequest(views.html.new_user_form.render(filledForm));
    	}
    	User user = filledForm.get();
    	//Ebean.save(user);
    	return redirect(routes.UsersController.form());
    }

Here we allow only the name, email and password are linked to the model. I already commented this in other post. The problem is when we invoke hasErrors method. This method will return true, because our model has other validations. Here we can use a feature provided for Bean Validation that allow us to split validation in different groups.

    package groups;

    public interface ValidationGroups {

    	public interface SocialInformation {}
    	public interface UpdateInformation{}
    	public interface BasicInformation{}

    }

The nice thing about this is that Play’s validation follows Bean Validation spec. We can take advantage of this! We only need to pass the group when we create the Form object.

         private static Form<User> newUserForm = Form.form(User.class,ValidationGroups.BasicInformation.class);

That is it! You can have a lot of groups and use them in specific situations. You still can use multiple groups to perform a validation :).

    @Required(groups={ValidationGroups.BasicInformation.class,ValidationGroups.SocialInformation.class})
    private String email;
    @Required(groups={ValidationGroups.BasicInformation.class,ValidationGroups.SocialInformation.class})
    private String password;
    @Required(groups=ValidationGroups.SocialInformation.class)
    private String facebookId;

And now you pass a different group to form method.

    private static Form<User> newUserForm = Form.form(User.class,ValidationGroups.SocialInformation.class);

Name and email will be validated when a validation is performed with one group or another.

Another alternative, that I try to avoid, is to create a new class that represents your html form. You can use it to bind input values and after that, create your Model. This approach is better when you have a form that is not bound with any model. For example, a form to log in your user. In this case, you can use DynamicForm or a Class that represents login information.

If you have any doubt about PlayFramework, fell free to get in touch. My contact informations is here.

 

Posted in Uncategorized | Leave a comment

Playframework, how to protect against Mass Assignment

Form data handling is one of the most used feature in every MVC framework, in Play is not different. Documentation on website is very good, but leaves outside a couple of important situations. Let’s see a first case to better understanding about this feature.

Imagine a simple html form to register a user. Here is the user class and template which contains html form:

      public class User {

      	private String id;
      	private String email;
      	private String password;
      	private RoleType roleType = RoleType.CUSTOMER;

      	public void setRoleType(RoleType roleType) {
      		this.roleType = roleType;
      	}

      	public RoleType getRoleType() {
      		return roleType;
      	}

        //getters and setters for other fields
      }

Now we have to write a controller to handle the client submission. Here is an example:

    public class UsersController extends Controller{
	
    	private static Form<User> newUserForm = Form.form(User.class); 

    	public static Result form(){
    		return ok(views.html.new_user_form.render(newUserForm));
    	}
	
    	public static Result create(){
    		Form<User> filledForm = newUserForm.bindFromRequest();
    		if(filledForm.hasErrors()){
    			return badRequest(views.html.new_user_form.render(filledForm));
    		}
    		User user = filledForm.get();
    		Logger.info("RoleType {}",user.getRoleType());
    		Ebean.save(user);
    		return TODO;
    	}
    }

The problem is that we are believing that our user will simply fill the inputs in form and submit the information. What if an extra parameter appear in our Form object? For example, “user.roleType“. There are all kinds of user in this world, and maybe one of them likes to test your application trying to submit extra parameters, using chrome tools for example :).

editiing_html_chrome

When you invoke form.bindFromRequest().get, Play’s underlying binder will get all parameters and try to set in your User object. Every field that has a setter can be set with a form parameter. So the first solution would be drop setRoleType() method from your class. But in our case that is impossible, we need this setter there to allow admin changes roleTypes of other users.

One other solution is configure Form object to accept only some fields, and this feature is implemented already in Play Framework.

    public static Result create(){
    	Form<User> filledForm = newUserForm.bindFromRequest("email","password");
    	if(filledForm.hasErrors()){
    	    return badRequest(views.html.new_user_form.render(filledForm));
    	}
    	User user = filledForm.get();
    	Logger.info("RoleType {}",user.getRoleType());
    	Ebean.save(user);
    	return TODO;
    }

Usage of this technique is a nice way to protect your system against Mass Assignment attack. For instance, Github already suffered with this kind of attack. Stay connected, next week I will write how to handle different types of validations from the same model!

Posted in java, jvm, playframework, scala | Tagged , , | 1 Comment

Your Play project is Java and Scala, at the same time

In the moment of creation a Play application, we are obliged to choose between Java and Scala as the base of our code, which is good because you can prefer one or another. The problem with this choice is that the programmers, basically Java programmers, they think that is a final choice. It is not unusual see some doubts in Play’s user forum about how to do something in Java version which is already well know in Scala version. For example, how to implement Web Sockets.

Of course, if there is a Java way to accomplish the task, go ahead and use it but, if there is not a Java way or this way is worst than the Scala version, still go ahead and use Scala. This is the point of this post, Play is possibly the only framework thought to be used with Scala and Java together, and not separated. Another example, all view templates are written in Scala. You still have the router file :).

Let’s see some examples! The first one is if you need to receive a Option in your template. You can try to pass a Option from play.libs.F.Option to your template.

    @(maybeTag:JavaOption[Hashtag])

    @maybeTag.map { tag:Hashtag =>
          @tag
    }.getOrElse {
          tagless
    }

The problem is that template, that becomes a Scala class after compilation, does not have any conversion from play.libs.F.Option to scala.Option. So code showed above will not work. There is no problem at all, instead of pass Play’s wrapper as argument, you can create a new Scala Option and solve your problem.

    ok(views.html.index.render(scala.Option.apply(hashtag)));

Another situation. Sometimes you have a class that simply holds a value. For example, in one of my current projects, I have a class called ImportStat.

    public class ImportStat {

    	private Number count;
    	private PhotoStatus photoStatus;

    	public ImportStat(Number count, PhotoStatus photoStatus) {
    		super();
    		this.count = count;
    		this.photoStatus = photoStatus;
    	}

    	public Number getCount(){
    		return this.count;
    	}

    	public PhotoStatus photoStatus() {
    		return photoStatus;
    	}

    }

I need to print the count value to give some information about a task that is being done by some Actor in my system. One way to do this is:

    @for(stat <- stats) {
     	  @stat.photoStatus():@stat.getCount()
    }

But, with a minor change you can take advantage of Scala syntax sugar to return values of your objects. You can use the apply() method. So let’s change our class.

    public class ImportStat {

    	private Number count;
    	private PhotoStatus photoStatus;

    	public ImportStat(Number count, PhotoStatus photoStatus) {
    		super();
    		this.count = count;
    		this.photoStatus = photoStatus;
    	}

    	public Number apply(){
    		return this.count;
    	}

    	public PhotoStatus photoStatus() {
    		return photoStatus;
    	}

    }

Now, in your template, you can write something like this.

    @for(stat <- stats) {
     	  @stat.photoStatus():@stat()
    }

The last one is the better, at least for me. I needed to use SSE to push notifications to browser. I googled about it and found this link, there was not a Java version! So I kept looking for and I found this blog post, which showed to me that Scala version was already implemented and it is much better than Java way, even if you use the pull request that brings SSE to Java version. So, for this case, I preferred to write the controller in Scala. Let’s just take a look in how you can open a SSE connection.

    package controllers

    //imports

    object UpdatePhotosController extends Controller {

      val (chatOut, chatChannel) = Concurrent.broadcast[JsValue]

      def newPhotos() = Action {
        implicit req =>
          {
            Ok.feed(chatOut &> EventSource()).as("text/event-stream")
          }
      }
    }

Now, let’s look how you can push information through the channel. And we will make this from an Actor written in Java!

    public class UpdatePhotoPanelActor extends UntypedActor{

    	@Override
    	public void onReceive(Object message) throws Exception {
    		final String id = (String) message;
    		Photo photo;
    		try {
    			photo = JPA.withTransaction(new Function0() {

    				@Override
    				public Photo apply() throws Throwable {
    					return Photos.byId(id);
    				}
    			});
    		} catch (Throwable e) {
    			throw new Exception(e);
    		}

    		UpdatePhotosController.chatChannel()
    		    .push(PanelPhotosJson.toScalaJsValue(0,photo));
    	}

    }

That is it! Don’t be afraid to mix both languages. If you are in Java project, your code will be 90% in Java and just 10% in Scala, not a big problem. The important part of Play written in Scala is the core, to build real world application is not important which one you gonna pick :). Choose the option that better fits to your team.

Posted in java, plataforma java, playframework, scala | Leave a comment

Strategies for testing static calls in Play projects

Play forum is a place with a lot of healthy doubts. Other day, an interesting topic popped there: How to test static methods. So, let’s talk about a little bit about this subject.

For example, if you have this piece of code:

    public void save(final RecentPhotosURL photosURL,
    		final Function2<String, Integer, Void> callback) {
    	WSRequestHolder holder = WS.url(photosURL.getEndpoint());
    	photosURL.fill(holder);
    	Promise promise = holder.get();
    	promise.map(savePhotosFunction);
    }

How can you test it? You are using WS class and making a static call. Libs like Mockito, only can test instance methods. One way to workaround things here is the usage of a lib which instruments your code and is able to mock some static calls :). This powerful tool is PowerMock. So, to test your method you could use something like this.

    @RunWith(PowerMockRunner.class)
    @PrepareForTest({ WS.class })
    public class NewPhotosSaverTest {

    	@Test
    	public void shouldGetJsonResponseAndSaveIt() {
    		mockStatic(WS.class);
    		Mockito.when(WS.url(url).thenReturn(new MyRequestHolder(url));
    		new NewPhotosSaver(...).save(photosURL,callback)
    	}

    	static class MyRequestHolder extends WSRequestHolder{

    		public MyRequestHolder(String url) {
    			super(url);
    		}

    		public  Promise get(){...}

    	}

    }

Voilà, you can unit test a lot of methods that use static approach. This could be used to test legacy system too :). I have no doubts that use static methods are easier than use a lot of instance methods. The main reason is that you can invoke these methods from everywhere. But oops, this can be your big problem too :(.

Now, if someone has to add some logic in this method, there is a big chance that a new class with some static methods be created. The complexity of this method would be increased because it would be responsible for creating and using objects instead of just use them and, even worst, static calls can be made from every piece of your code. I am not sure if you have seen something like this, but imagine a code inside a template:

    for(photo       code here
    }

So you have to know really well your team before start using static methods everywhere. Another strategy can be used to prevent maintainability problems like this. Instead of using Play API’s directly, you could wrap some of them and force your code to instantiate some objects.

    public class ServiceRequester {
      private String endpoint;

      public ServiceRequester(String enpoint){
        ...
      }

      public Promise get(Map<String,String> params){
        WSRequestHolder holder = WS.url(endpoint);
    		Set<Entry<String, String>> entries = params.entrySet();
    		for (Entry<String, String> entry : entries) {
    			holder.setQueryParameter(entry.getKey(),entry.getValue());
    		}
    		return holder.get();

      }
    }

    //using this code

    public class NewPhotosSaver {
        public void save(final RecentPhotosURL photosURL,
        		final Function2<String, Integer, Void> callback) {
        	ServiceRequester requester = new ServiceRequester(photosURL.getEndpoint());
        	Promise promise = requester.get(photosURL.getParams());
        	promise.map(savePhotosFunction);
        }
    }

Now you can refactor a little more and receive these dependencies as constructor args.

    public class NewPhotosSaver {

        public NewPhotosSaver(ServiceRequester requester){
          ...
        }

        public void save(final RecentPhotosURL photosURL,
        		final Function2<String, Integer, Void> callback) {
        	Promise promise = requester.get(photosURL.getParams());
        	promise.map(savePhotosFunction);
        }
    }

It is easy to test now! Just mock this parameter and test your code without problems.

    @Test
    public void shouldGetJsonResponseAndSaveIt() {
      ServiceRequester requester = mock(ServiceRequester.class);
      when(requester.get(params)).thenReturn(somePromiseHere)
      new NewPhotosSaver(requester).save(photosURL,callback);
      //asserts here
    }

Now you have, at least, two options of approach to your code. You can use this same strategy with your DAO. Instead of create static methods that use JPA.em() or Ebean.something, create instance methods and pass DAO’s instances as arguments to other classes.

Of course you have to think about what kind of approach you prefer, it is possible to mix them too. Your tests send signals about your code, pay attention :). Thanks to Rafael Ponte who talked about this situation with me and inspired me to write this post :).

Posted in java, scala, playframework | Tagged , , , | 3 Comments

Take advantage of assets conventions in Play

It is usual when you are working with Play use this kind of code to refer public assets.

   <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/style.css")"/>
   <script src="@routes.Assets.at("javascripts/jquery-1.4.4.min.js")" type="text/javascript">
   <img src="@routes.Assets.at("images/someimage.png"/>

But, Why do you have to write the name of css, javascript and images folder all the time if they are the convention? When you are using a framework is important to take advantage of all things, in order to avoid silly mistakes, like write the wrong name of the folder. For example, at least to me, it would be better if we could write something like this:

   <link rel="stylesheet" href="@Css("bootstrap.min.css")">
   <script type="text/javascript" src="@Js("main.js")"></script>
   <img src="@Image("someimage.png"/>

To achieve this we just have to use the built in controller named Assets. Let’s see the implementation:

  package helpers

  import controllers.routes

  object AssetsHelper {

    object Css {
	  def apply(file:String) = routes.Assets.at("stylesheets/"+file)
    }

    object Js {
	  def apply(file:String) = routes.Assets.at("javascripts/"+file)
    }

    object Image {
	  def apply(file:String) = routes.Assets.at("images/"+file)
    }

}

Now, you just have to import this class to all templates. Change your build.sbt and add this line.

   templatesImport ++= Seq("helpers.AssetsHelper._")

If you want to keep update with a lot of Play tips, follow me here and in my twitter :). Also I have my book available in Leanpub, still only in Portuguese and ASAP in English.

Posted in Uncategorized | Tagged , , , | Leave a comment