Showing posts with label GWT. Show all posts
Showing posts with label GWT. Show all posts

Sunday, July 17, 2011

GWT JSNI Reference

I've recently had to go through the GWT JSNI interface, and I found the documentation a little lacking.  While the official JSNI page has nice examples and clearly shows how things integrate, it leaves out some reference information that would be helpful.  My guess is that they didn't want to duplicate the JNI reference, but its still a little frustrating to have to look up the type codes in a separate area.  And the type codes aren't exactly intuitive, I mean, who would guess that 'Z' is the representation for boolean?

So, here is a little cheat sheet for those of you looking for the GWT JSNI type codes.  These are, of course, the same codes that can be found in the JNI reference.

Native Type Java Language Type Description Type signature
unsigned char jboolean unsigned 8 bits Z
signed char jbyte signed 8 bits B
unsigned short jchar unsigned 16 bits C
short jshort signed 16 bits S
long jint signed 32 bits I

long long

__int64
jlong signed 64 bits J
float jfloat 32 bits F
double jdouble 64 bits D

Table taken from Wikipedia, 5/7/2011


In addition to the primitive types, any object can be referenced using its fully qualified name like this:

LFully.Qualified.Name;

For example, to access a string, you use:  Ljava.lang.String;

To reference an array of the same type, prepend [ like this:

[Ljava.langString;

So that's my quick cheat sheet.  Here are a couple of additional references that help:

Coding Basics - Javascript Native Interface (JSNI) 

JDK 6 Java Native Interface-related APIs & Developer Guides

Saturday, February 5, 2011

GWT and SmartGWT - JNI and Unsatisfied Link Error

GWT uses the Java JNI mechanism in a really unique way.  JNI was originally intended to work with native code on the computer where you had your JDK, like C++.  I've had limited exposure to the JNI interface - I've only had to use it for a serial communication component.  Even then, I was using a library that relied on JNI, so I didn't generate the code, I just had to make sure the native library was on my classpath.

The Google Engineers applied this mechanism to Javascript, however.  If you want to write 'Native' Javascript in your GWT classes, its easy.  Just flag your method as native and put your javascript code, in comments, before your terminator.  Here's a sample from the Google Web site.


public static native void alert(String msg) /*-{
  $wnd.alert(msg);
}-*/;


Viola!  Instant native interface for your JavaScript CLIENT code.  That's right, just try running this method on the server.  While working on my current project, I ran into this issue accidently while trying to use a SmartGWT class.  I got a JNI error on the server because the VM couldn't find the native code.  Of course, there isn't any native code on the server.  In this case, the 'native' code is JavaScript.

I was trying to pass a SmartGWT ListGridRecord to the server so I could map it to a persistent bean.  Of course, once I saw the error, I followed the inheritance hierarchy for ListGridRecord all the way up the chain, and what did I find at the top?  JsObject.  Of course, I didn't even have to go that far.  After looking at the Record code, it relies on static methods in JSOHelper, which uses a lot of native JavaScript

In the end I had make transfer objects to use to send the data over GWT RPC. This was a good reminder, though, that while GWT looks like Java, what's being executed really isn't.

Sunday, January 30, 2011

SmartGWT and GWT RPC Integration

I am currently finishing my Capstone project for my MSE at Carroll University. While the application I am writing itself doesn't have a lot of twists in it, I decided to use this opportunity to experiment with some different technologies.  I'm using GWT, SmartGWT, and Hibernate in the application.  I've used Hibernate and GWT pretty extensively in my professional career, but the twists I've added for this development are to configure Hibernate using the JPA standard, and to use GWT Designer for mockups.  I've already posted about my experiences with GWT Designer.

I haven't really used SmartGWT before.  My experience has been with the ExtGWT library, which I loved.  I chose to use SmartGWT on this build because it is fully LGPL, while Ext is dual licensed.  While working with SmartGWT I've found some things that I was not expecting.

One of the selling points of SmartGWT is that it has built in support for 'Data Binding' with Tables and the like.  This is done through DataSource objects.  The problem is, the published DataSource implementations don't work with GWT RPC. And the DataSource base class has dozens of methods (Just take a look at the JavaDoc).  It really isn't clear how to define your own custom data source, or the work it will take to do so.  This was a sticking point for me because I really like the GWT RPC mechanism, and I had already come up with a nice security model, which I posted about here.

It took a while, but I finally found a post about integrating GWT RPC on the SmartClient Forums.  The post is a bit dated and says you need to compile from source, but that is not the case.  The version of SmartGWT I am using, 2.4 already has the clientCustom flag built in.  The developer who posted this also supplied 5 files, Including a GwtRpcDataSource abstract class, and a sample implementation.  The class comments well what you need to do to implement your datasource. With this setup, a new GWT data source can be defined by implementing 4 methods.  

I hope this post helps others find the solution much faster than I was able to.

Friday, December 31, 2010

GWT Designer

I am not a fan of WYSIWYG software.  Almost every experience I had with WYSIWYG tools had the same pattern:
  1. I implement some application using the tool because I am pressed for time.
  2. I get the initial project done very quickly.
  3. Someone requests a change.
  4. Because of the WYSIWYG generated code, I essentially have to rewrite the app.
Maybe I just didn't use the WYSIWYG right.  Obviously, a lot of people love them.  But they were always counter-productive for me.  In the end, they cost me more time than they saved.  So, you can imagine my feelings when I read about GWT Designer.  Here was a Drag and drop visual editor for GWT, complete with integration for SmartGWT and Ext GWT.  I was hesitant, to say the least.

But I also firmly believe that as a Software Engineer, you have to keep your mind open and constantly re-evaluate new tools.  So, I installed the GWT Designer plugin for Eclipse.  I used it for my capstone project, a CRUD application for running a sign installation company.  I was pleasantly surprised.  

Here are a few observations about the Editor:
  1. I was able to jump between code and the visual editor easily
  2. Changing my code by hand didn't break the visual editor 
  3. The code generated by the editor was easily readable and clean
Even though I started with the WYSIWYG, as I got a simple layout produced, I found myself easily translating into the code. It was a good experience.  The visual components I created were originally going to be mock ups, but they were so clean, I've transitioned them into the working code.  The application is not done yet, but its looking good - I've already been able to easily incorporate changes requested by my client.  

Now, here are the drawbacks I encountered:
  1. My 5 year old PC and laptop run the visual components a little slow. 
  2. The visual rendering isn't yet perfect.  While it was mostly reflective of the actual output, there were a few differences.
All in all, though, the drawbacks were more annoyances than restrictions.

If you use GWT, I recommend you try GWT Designer.

Friday, December 24, 2010

GWT Simple Security Configuration

For my capstone project in my MSE program at Carroll University, I am writing a GWT application. One of the requirements for this application is security. There are several posts on securing a GWT application on the Web already, but most of them are more heavy weight solutions that show you how to use Spring-AOP and Spring-security to secure your app.

For this project, I don't need anything that heavy-weight. Here is a little review of how I secured this application.

First, I wanted each service to have it's own access controls. More specifically, I want to be able to secure each method in each service. Second, I want to be able to support Role-based access. This way I can add users to roles to grant them the permissions they need. Finally, I don't have a real need to redefine role access in real-time. Given these constraints, I was able to put together a quick and easy solution to secure my application.

First, I decided that I wanted to be able to easily see in my code what the access control was. It seemed to me that Annotations would be an easy way to do this. Something like:

@Secure("ROLE_ADMINISTRATOR")

But I want to be able to specify multiple roles that can be configured to this action, so, multiple roles would look more like this:

@Secure({"ROLE_ADMINISTRATOR, ROLE_CONFIGURATION_MANAGER"})

So, the first thing I did was define the Annotation.


package com.archie.sma.server.util.security;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Secure {
  public String[] value();
}
  
AS you can see, annotations are annotated. This one says that this annotation applies to Methods, and it is kept at runtime.

Next I needed to apply the annotation to my services. This was quite easy. In my Service interface on the client, I used the annotation:

@Secure({"ROLE_ADMINISTRATOR", "ROLE_CONFIGURATION_MANAGER"})
public Object get(String id) throws Exception {
//Method implementation here...
}

Of course, I now need to tie these two together. Since I'm Using GWT, I decided to Extend the GWTServerServlet. By extending the servlet and over-riding the processCall and onAfterRequestDeserialized method, I am able to easily use a little bit of Reflection to get the annotation and determine if the user in Session has access to the method. This approach also requires me to extend my new security Servlet for all my secured classes. So its on the developer to ensure he is extending the class correctly. Here is the class:





public class SecureRemoteServiceServlet extends RemoteServiceServlet {

  private transient IDaoFactory daoFactory;

  @Override

  public void init(ServletConfig config) throws ServletException {

    super.init(config);

    daoFactory = new DaoFactory();

  }

  /**

   * 

   */

  private static final long serialVersionUID = 1000L;

  private static final String USER = "USER";

  private User user;

  @Override

  protected final void onAfterRequestDeserialized(RPCRequest rpcRequest) {

    Method method = rpcRequest.getMethod();

    Secure secure = method.getAnnotation(Secure.class);

    Boolean hasAccess = Boolean.FALSE;

    if (secure != null) {

      

      String[] roles = secure.value();

      HttpServletRequest request = getThreadLocalRequest();

      user = (User) request.getSession().getAttribute(USER);

      if (user != null) {

        List<Role> userRoles = user.getRoles();

        for (Role role : userRoles) {

          for (int i = 0; i < roles.length; i++) {

            if (role.toString().equals(roles[i])) {

              if(hasAccess != null) {

                hasAccess = Boolean.TRUE;

              }

            }

          }

        }

      }

    }

    if (!hasAccess){

      throw new RuntimeException("Not Authorized");

    }

  }

  /*

   * @Override public final String processCall(String payload) throws

   * SerializationException { if (!hasAccess) { throw new

   * UnexpectedException("Security Exception", new Exception(

   * "Not Authorized")); } return super.processCall(payload); }

   */



  public User getUser() {

    return user;

  }



  public void setUser(User user) {

    this.user = user;

  }



  public IDaoFactory getDaoFactory() {

    return daoFactory;

  }



  public void setDaoFactory(IDaoFactory daoFactory) {

    this.daoFactory = daoFactory;

  }

}


So that is my quick and dirty security implementation for my GWT app. This is not what you would call an enterprise solution, but it is a quick way to implement security for a little, self-contained application.