With the success we had with EQATEC Analytics at RemoteX I started looking around for something similar, but for JavaScript. I didn’t find anything that satisfied my needs.

Thus I created my own error collecting and analysis tool, and named it JS-Analytics.

You use it similar to how you use Google Analytics, you add a few given script tags to your website and JS-Analytics will try to collect any unhandled JavaScript error that occurs, and send information about it back to JS-Analytics website.

JS-Analytics uses a combination of window events to collect errors. These events aren’t available on all browsers so JS-Analytics will use JQuery to provide cross browser support. This means that cross browser support is only available for JQuery code.

For more information about how it works I recommend this page.

Right now this JS-Analytics provides just some basic analysis. But I felt that it was better to announce it and hopefully get some feedback on it, than to carry on without any feedback.

I read a blog post at Three Rivers Institute that lead me to the following presentation.

The presentation is about startups and search engine optimization. How to drive visitors to your website.

Dharmesh discusses how to adapt your webpage to generate visitors, also promoting his hubspot seo grader.

Now this got me thinking of a project I’ve been working on. It’s a highly dynamic JavaScript based page, hosted on Google AppEngine. (currently not in a state I’d like to show it off since its still lacking the basic features).

The page is being designed with a few ideas in mind:

  • All dynamic data i served to the page through REST
  • All static pages are served with long expiration, most content is static
  • The main page never reloads, instead JavaScript does AJAX to update the content
  • The JavaScript is designed using SOLID design principles
  • The JavaScript is tested
  • Back and forwards buttons still work
  • Marketing Content is served using Google Sites, to reduce bandwidth but especially to shorten roundtrips when working with Marketing material

Now the idea here is to give a similar feeling as to what GMail feels like. A common trend, in web application development I think. However, after watching the presentation the following thought occurred to me. The GMail application needs to be found by search-engines.

Google has a signup page with content that is searchable, but the main JavaScript client is not designed to be found by Search Engines.

I want my page to be found by search engines, and this means that there are a few of the basic Ideas behind the page that I need to reconsider. Especially the following:

  • The main page never reloads, instead JavaScript does AJAX to update the content
    • Meaning that the page looks “empty” to search engine crawlers since all content is loaded using JavaScript
  • Marketing Content is served using Google Sites, to reduce bandwidth but especially to shorten roundtrips when working with Marketing material
    • Right now this is implemented using IFrames, which probably cause trouble for search-engines (yeah yeah, I know frames suck especially IFrames… but there were some cross site issues I didn’t want to fix right now),
  • I need some of my content pages to be searchable, but not the AJAX-driven application in it self. So now I have to rethink some of my decisions which were made from a pure coding view-point, to adapt to marketing viewpoints (and search engine algorithms so its not all bad).

I found a new tool for testing web-applications in IE today. It’s called IETester, and it allows me to test IE versions 5.5 to 8 in the same application. Which is great, since my Vista machine only runs 8 normally.

I use it to verify my Grails application in IE6. Tonight I managed to create a unit test capturing the issue I was experiencing in IE6, using IETester and QUnit, so now I know where to take off tomorrow.

However it isn’t that stable, I’m running it on a 64-bit machine which might add some extra strain on the application. But for me it needed to be re-started or crashed a few times while I was isolating the bug I am working on.

Im doing something not supported. I’m serving html files through my Grails web-app running Jetty. Simply I have some static pages that will not change. I want them served uncompiled. I use the resources-first plugin to help out with serving these html files.

The files are documentation, responses if you wish, for the user. I load them using Ajax to provide standard responses for some actions. The problem is that the responses are in Swedish. Jetty only serves them in ISO-8859-1, which is its standard configuration. According to this.

The issue I have is that I can’t change it. I can’t set a system variable to change the default encoding to UTF-8, not without having to do some programming. As  a result, the easiest way for me to handle this issue is to change my HTML files to GSP files. This forces me to serve them through the Grails stack and thus demands somewhat more resources from my poor server.

I tried to see if I could configure the Jetty-server to use UTF-8 as a default encoding, but alas according to this documentation I can only change it for the URI and not the content, and the URI is already set to UTF-8.

If anyone finds out how to serve HTML through the same server as Grails but with the correct encoding let me know. Right now I have a work around that will work for the next 6 months.

Update: Apparently, hosting just HTML files with utf-8 encoding set on the file, works in the production environment. Thank you Mor.ph.

So I have my Grails environment setup. The point is to build a REST-service that will work as a back end to a highly dynamic JavaScript page. I chose Grails, since it builds on Hibernate and Spring.

Two frameworks Id like to examine for the purpose of seeing the differences between Castle and nHibernate in the .Net world.

Building domain-classes and having the represented as XML is straight forward in Grails, but I need to take care of the login scenario. If you’d like to know more about building REST web services with Grails, I recommend reading the Mastering Grails: RESTful Grails article. Login seems like a good place to start, to ensure that my domain-controllers can dictate login as I develop the domain.

Now Grails.org has a list of tutorials, one of them, focusing on Login. It’s a good beginners tutorial showing how to use interceptors to execute user verification before showing the actual view requested. For my scenario however it has a few problems. Lets use the tutorial as a start of point.

The problems I have with the solution is with the following code:

def checkUser() {
  if(!session.user) {
    // i.e. user not logged in
    redirect(controller:'user',action:'login')
    return false
  }
}

For my scenario this has one problem, in two places. Its stateful. First of it always directs the user to the same place, of course it can be different per controller. I need it to simple say access denied.

def checkUser() {
  if(!session.user) {
    // i.e. user not logged in
    response.sendError(401)
    return false
  }
}

The above code is changed to instead of redirecting the user, it simply sets the response code to Access Denied. Now there’s just one issue left, the session code.

I don’t want to use session, as it requires my server to remember each session, preferably I want the client to remember the state.

Another issue is that I want to use Mor.ph AppSpace, if I pay for the most basic of subscriptions at Mor.ph I get two Cube, i.e. two servers with a load balancers in front. As a result I can’t be sure that the same server will service the same client all the time.

If we instead choose to check for the logged in user using the authorization header. The state is always provided by the client, instead of keeping the state on the server.

def checkUser() {
  if(!UserController.checkAuthorization(request, response)) {
    // i.e. user not logged in
    response.sendError(401)
    return false
  }
  return true
}

I let the UserController do the checking of the user, using a static method. This will let me keep the authorization code in the same place I handle users to begin with. It also allows me to change the authorization method later by changing the code in the checkAuthorization method. We could use Dependency Injection here to inject a real instance of the UserController, or even better an object with the sole responsibility to check user access. However DI is out of scope for this post.

You can implement any way of checking the user login you want. If you want a simple solution and stick with the HTTP standard you could use Basic auth. Here is a good explaination of how to implement Basic auth for Grails. Another way is too use a cookie to hold authorization information.

For this example were just sending username:password in the authorization header. My final implementation will be Basic Auth with the password hashed to a checksum. The point of the hash is to never send plain-text password across the net.

Here is the checkAuthorization method in the UserController for this example.

static boolean checkAuthorization(HttpServletRequest request, HttpServletResponse response) {
  def authString = request.getHeader('Authorization')

  if (!authString) {
    return false;
  }

  def credentials = authString.split(':')
  if( credentials.length != 2 || credentials[0] == null || credentials[0] == "" || credentials[1] == "" || credentials[1] == null)
    return false;

  def user = User.findByEmailAndPassword(credentials[0], credentials[1])

  if (user) {
    return true;
  }
  return false;
}

Now we can create some JQuery based JavaScript code to handle login.

function RestClient() {
    var self = this;
    var auth;

    function ShowLoginUI(afterLoginCallback) {
        var dialog = document.createElement('div');
        $(dialog).html("<table><tr><td>Email</td><td><input id='email' type='text'/></td></tr><tr><td>Password</td><td><input id='pass' type='password'/></td></tr></table>");
        $(dialog).dialog({ buttons: {"Login": function() {
            auth = $(this).find("#email").val() + ":" + $(this).find("#pass").val();
            afterLoginCallback();
            $(this).dialog("close");
        }, "Cancel":function() {
            $(this).dialog("close");
        }}, modal:true});
    }

    this.Get = function(url) {
        var data = null;

        data = $.ajax({
            url : url,
            method : 'GET',
            beforeSend : function(req) {
                req.setRequestHeader('Authorization', auth);
            }, cache : true,
            error: function(request, textStatus, error) {
                if (request.status == 401) {
                    ShowLoginUI(function() {
                        data = self.Get(url);
                    });
                }
            }});

        return data;
    };
}

The above code does Ajax Get-calls to the specified address. If the call failed due to Access Denied, it shows a login form and tries to execute the Ajax request again. The class remembers the authorization string, so as long as the user uses the same RestClient-object the state is maintained at the client side. Ill leave instructions on how to wire up Grails with JQuery to someone else.

Here is a simple usage example:

var a = new RestClient();
$("#test").click(function() {
  var data = a.Get("plant/create");
  $(document).append(data);
});

Good luck writing scalable login scenarios using Ajax instead of page reloads.