Sunday, January 30, 2011

Learning jQuery in the Greasemonkey playground

If you want to learn jQuery, but are not sure how to go about it, then you should go check out Greasemonkey, which is a Firefox add-on. Basically, what it does is it allows you to provide Firefox with a javascript file and a url pattern, and it will run the javascript on the page every time you go to it.

Most people kind of scratch their heads at this, not quite realizing the power of a tool like that. It is cool in and of itself, because it allows you to tweak your favorite webpages any way you like, and once installed it is transparent.

Another really cool benefit of it, though, is it makes a great testbed for practicing your javascript skills. You don't have to have an entire website to practice with, because you can practice on any site out there.

For example, here is a very small Greasemonkey script.

// ==UserScript==
// @name           Google Test
// @namespace      gtest
// @description    A small test script that picks on google
// @include        http://www.google.com/
// ==/UserScript==

document.getElementsByName("btnI")[0].style.display = "none";

All this does is remove the I'm Feeling Lucky button on the Google homepage. Not a lot, but as you can see, there is not a lot of buildup, either - you can just jump right in to doing javascript manipulations against whatever page you want.

The top part of the above script is the script metadata - it tells Greasemonkey what to do with the script. The most important part there is the @include tag - this is the URL pattern on which this script will execute.

What is even better is that you can start to play with jQuery as well. There is one more gotcha with jQuery - you need to include it into your script. You do this with a relatively simple little bit of metadata. Here is the same script, this time using jQuery.

// ==UserScript==
// ==UserScript==
// @name           Google Test
// @namespace      gtest
// @description    A small test script that picks on google
// @include        http://www.google.com/
// @require       http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js
// ==/UserScript==

$("input[name=btnI]").hide();

Notice the @require metadata - that tells Greasemonkey to include that external javascript file into your script.

Alright, we have the scripts ready, but how do we start using this thing? There are just a few steps to get you going:
  1. Go to the Greasemonkey installation page, and install the add-on
  2. Grab the script text above, and save it onto your computer somewhere. Call it "googleTest.user.js". The ".user.js" part is convention when dealing with Greasemonkey scripts.
  3. With Firefox open and Greasemonkey installed, grab the googleTest file, and drag it onto Firefox. You should see a Greasemonkey pop up asking if you want to install. Tell it yes.
  4. Go to Google, and see that we have gotten rid of the I'm Feeling Lucky button.
All there is to it. Once you have the script installed, you do not have to go through the drag and drop process again. Simply go to Tools > Greasemonkey > Manage User Scripts... and select your script to edit. It should open the script in your favorite text editor, ready to edit away to your heart's content. As soon as you save the file, the script is updated in Firefox and ready to test out.

Another great tool that goes hand in hand with this process is Firebug. Most web developers probably already know and love Firebug, but just in case you are not familiar, it is another Firefox add-on that is incredibly useful for web development. It is particularly useful for writing Greasemonkey scripts, because you need to know what to edit with your javascript. For example, I used it to determine what element to grab to get rid of the I'm Feeling Lucky button on Google.

I have successfully used Greasemonkey to expand my own jQuery knowledge, and it was an effective and entertaining way of going about it. If you want to learn more about jQuery, I highly recommend this method. Good luck!

Saturday, January 29, 2011

A quick jQuery primer

I am sure that if you are a web developer, then at some point in your career you have had to deal with javascript. It also seems like more and more people are turning to jQuery. If you already use jQuery, this post is not for you. This is basically just a quick overview, mostly directed at people that are familiar with javascript, but have little to no jQuery experience.

So, to start things off, why use jQuery? Well, basically, jQuery is a javascript that works well. It simplifies a lot of the things in javascript, and makes things more intuitive. Just as a quick example, take the simple task of toggling visibility of a div on your page.

Take a simple page:
Toggle Div
This is some toggling text

Here is the code for toggling visibility in javascript:


Here is the code for toggling visibility in jQuery:


That was an 8 line reduction in code, not to mention a heck of a lot easier to understand.

The key to understanding most of jQuery is to look at it's selector technology. That is all the stuff inside the $() in the code snippet above. jQuery uses the $ as it's primary object - in fact, there are several things you can do just with $.whatever. With parens after the $, it means that it is searching for stuff.

The selector syntax is very similar, if not identical, to the CSS selector syntax. For example, if you do $("div"), that will return all of the divs on the page. Better yet, jQuery will take any operation you perform, and apply it to everything that is returned by the selector, so that $("div").toggle() would toggle the visibility of every single div on the page.

Just to cover some of the basics of the selector syntax, here is a quick and dirty list of some of the commonly used things:
  • "#" - used to reference a particular ID, such as $("#mydivid")
  • "." - used to reference a class name, such as $(".myclassname")
  • "," - used to concatenate selectors, such as $("#firstdiv, #seconddiv") to select both the div with the ID "firstdiv" and the div with the ID "seconddiv"
  • " " - used for hierarchy of selectors, such as $("#mydivid a") to select all links that are children of the div with the id "mydivid"
There is a very large list of functions that jQuery can call on things. Just a few of the commonly used ones:
  • val()/val("blah") - used to get or set the value of a form field
  • css("cssattr")/css("cssattr","attrval") - used to get or set any css attribute on the object
  • attr("attrname")/attr("attrname","attrval") - used to get or set any html attribute on the object
  • insertBefore(object)/insertAfter(object) - used to add new html objects to the page
  • parent()/children() - used to get the parent object or the children objects of the object
There are many many more things as well, far more than I could possibly get into here. I highly encourage you to check out the jQuery documentation for more information.

Friday, January 28, 2011

Creating Custom Struts2 Interceptors

Now we're into it. The meaty stuff. If you have not read my post on Struts2 Interceptors, I recommend you head over that way first. With me so far? Great, lets dig in.

So, why would you want to create your own interceptor? Granted, there are a whole bunch of provided interceptors. There are several that are provided but are not used in the default interceptor stack, that might be worth checking out. Things like the LoggingInterceptor (logs when you enter and leave an action) and the TimerInterceptor (tracks how long an Action take to execute) are wonderful tools that should be looked into. So, what is left?

Basically, if you ever find yourself adding code or wishing you could add code to each of your actions, you have a valid candidate for a custom interceptor.

The case study we are going to follow today is a problem I ran into a while back. I had a standard jsp header and footer that were included in every page of my site. I wanted to be able to turn on some debugging features in those pages whenever the struts.devMode constant was set to true. However, I couldn't find any way to check the struts.devMode constant from the jsp page. Could be that there is a way, but I couldn't find it. I did find that you could grab it from within your action class, and that you could set it to a member of your action class and access that from your jsp. Eck.

So I decided to make a custom interceptor. This interceptor would be responsible for getting the current value of the struts.devMode constant, and putting that on the Value Stack. In naming this interceptor, I went a step further, and called it GenerateConstants, figuring I could use this to inject any of the struts constants that I might need in the future. To kick things off, I started with the following code inside a file called GenerateConstants.java:

package mypackage.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class GenerateConstants extends AbstractInterceptor {
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        // Perform pre-action stuff here
        String result = invocation.invoke();
        // Perform post-action stuff here
        return result;
    }
}

Excellent, we have the base structure. Time to fill it out a little bit. First we add the devMode property, and have struts inject it for us.

package mypackage.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class GenerateConstants extends AbstractInterceptor {
    private String devMode;

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        // Perform pre-action stuff here
        String result = invocation.invoke();
        // Perform post-action stuff here
        return result;
    }

    @Inject("struts.devMode") 
    public void setDevMode(String devMode) {
        this.devMode = devMode;
    }
}

Finally, we push this value into the Value Stack

package my.package.name;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class GenerateConstants extends AbstractInterceptor {
    private String devMode;

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        // Perform pre-action stuff here
        if ( devMode != null )
        {
            invocation.getInvocationContext().put("devMode", devMode);
        }

        String result = invocation.invoke();
        // Perform post-action stuff here
        return result;
    }

    @Inject("struts.devMode") 
    public void setDevMode(String devMode) {
        this.devMode = devMode;
    }
}

That is the entire amount of interceptor code needed. There is still a little more work to be done, though. Now comes the fun part - hooking it up! Crack on open your struts.xml file, and we'll work on the plumbing.

First thing that you have to do is to declare the interceptor, so that struts is aware that it exists. Inside your struts.xml file, if it does not already exist, add the interceptors tag, and add your interceptor to it, like so:


    
        
            
        
        
    


Next we need to create a new interceptor stack to use the new interceptor. Remember the default stack we talked about before? We are going to add to that now.


    
        
            

            
                
                
            
        
        
    


So here we are using the "interceptor-stack" tag to define a new stack. The child tag "interceptor-ref" just points to either an interceptor or an interceptor stack that is already defined. So in this case, we are defining our new stack with "generateConstants" as the first interceptor, followed by the "defaultStack" interceptor stack, which is the default stack provided with struts.

Finally, we have one more step to carry out. Right now, we have our shiny new stack, but we still have not told anything to use it. In order to do that, we can either declare our stack inside each Action, or we can override the default stack for all actions. The first method can be useful if you have a stack that only needs to be executed on a handful of Actions. However, our interceptor should be used by all Actions, so we are going to update the default. To do that, all we need to do is add a single tag called "default-interceptor-ref", outside of the "interceptors" tag, like so:


    
        
            

            
                
                
            
        

        

        
    


That's all there is to it. A few XML tags and a little bit of code, and you have a new interceptor.

Thursday, January 27, 2011

Struts2 Interceptors

Interceptors are one of the most powerful, and yet seemingly least understood feature of Struts2. The Interceptor framework is basically the core of the Struts2 framework, and understanding how it works is the key to really unlocking the power of Struts2.

For any given web request, there is a series of Interceptors that get fired off before your Action class is called. Each Interceptor performs a specific job that is required for every action. Some of the core functionality of Struts2 lives in these Interceptors by default, such as populating the member variables of your action class, validating data and exception handling.

The Interceptors fire based off of what is known as the Interceptor Stack. The Stack is just an ordered list of Interceptors that need to be fired prior to entering the action. When you include the struts core library in your project, it includes a file called "struts-default.xml", which defines all of the core Interceptors and a default Interceptor Stack. Since these are set up by default, and they handle most use cases, most people do not really understand the Stack, because it "Just Works".

To understand how it works, you just need to look at what happens when struts receives a new request. It starts things off by creating an object called the ActionInvocation, and calling a method called "invoke" on that object. During the first trigger, invoke looks at the configured Stack, gets the first Interceptor configured, and fires that Interceptor's "intercept" method.

Inside "intercept" is where the Interceptor performs whatever tasks it needs to get done. For example, there is an Interceptor available for use called the LoggingInterceptor. Inside of this Interceptor's "intercept" method, the first thing that it does is log out an "Entering" message.

After performing any necessary operations, the interceptor then calls ActionInvocation.invoke again. Bear in mind the call stack we have going so far:
    ActionInvocation.invoke()
        Interceptor1.intercept()
            ActionInvocation.invoke()

Back inside invoke, the ActionInvocation class has kept track of what Interceptors it has already fired. In this case, it has made note of the fact that Interceptor1 has already been called. It looks again at the Stack, and finds the Interceptor configured to fire after Interceptor1, and calls that Interceptor's "intercept" method.

This continues on and on, until we reach the last interceptor. After the last interceptor performs whatever it needs to do, it again calls ActionInvocation.invoke. ActionInvocation now recognizes that all of the Interceptors have been called, and proceed to call the Action class's execute method. So the final call stack looks something like this:
    ActionInvocation.invoke()
        Interceptor1.intercept()
            ActionInvocation.invoke()
                Interceptor2.intercept()
                    ActionInvocation.invoke()
                        .
                        .
                        .
                        InterceptorN.intercept()
                            ActionInvocation.invoke()
                                Action.execute()

This is now the part that most people are familiar with - the Action class. Your Action does what it needs to do, then returns a String value. Something like "success", "error", "input", etc. These return values end up determining what page gets displayed to the user.

This String that gets returned by your Action class - where does it go? If we look up at our call stack, we will see that it will return to ActionInvocation.invoke. Interesting. Here is the fun part - both ActionInvocation.invoke and all of the Interceptors "intercept" methods return Strings as well. In fact, they return your String.

So now we start to unwind back up the Stack. This is another very important part of the framework. Do you ever remember seeing those weird Struts2 pictures, that show all of the Interceptors being fired twice? Once before the Action, and once after? Like this one:


This call stack is how that works. The Interceptors do not actually get fired twice. They are fired once, but the Action call occurs inside of them. Back to the above mentioned LoggingInterceptor now. As I said, this Interceptor logs out an "Entering" message when it starts, then it fires "invoke". After "invoke" returns, though, this Interceptor is not done - it also logs a "Leaving" message afterward.

Here is the complete code necessary in order to log an entering and leaving message before and after every single one of your Action calls:
@Override
public String intercept(ActionInvocation invocation) throws Exception {
        logMessage(invocation, START_MESSAGE);
        String result = invocation.invoke();
        logMessage(invocation, FINISH_MESSAGE);
        return result;
}

That's it. Instead of log lines inserted at the top and bottom of every single Action class, this one little snippet set up as an Interceptor does all that work for you.

I wanted to go over how to do a custom interceptor, but I have already prattled quite a bit longer than I thought I would. Hopefully I have given you a bit better understanding on how Interceptors work, and gotten you hungry to learn how you can start writing your own. More posts will follow.

The Struts2 Framework

I'll admit, when I first started web development, I didn't like frameworks. I was a do-it-yourself kind of guy. I didn't want to have to deal with learning the ins and outs of someone else's code. Now that I have begun to use frameworks, though, I would never go back.

My current framework of choice is Struts 2. I have a lot of respect for this framework, and I feel like it does a lot for me in a really elegant way. You will probably hear me blather on about it quite a bit, as it is where I spend most of my time these days.

Struts 2 is an MVC framework, or a Model-View-Controller. MVC is a design pattern that is used to separate the parts of a web application into separate layers. A layer is an isolation of a type of code that keeps it independent of the implementation of the other layers.

The View is the part of the code that actually handles how the data is presented. In Struts 2, this is typically handled by jsp files.

The Controller is what hooks up the View with the Model. It is what controls where the flow goes, what view to display, what business logic to execute. It is kind of the brain of the operation. In Struts 2, the Action class acts as the Controller. Your Action class should not have any business logic in it directly. Rather, it should call into a Service layer that executes your business logic, then alter the flow of the View based off of what it returns.

The Model is the parts of the code that actually contain the business logic. I typically isolate this into a Service layer, which is called from the Action class.

The beauty of the MVC design pattern is that these layers are totally isolated from one another. If we want to start using freemarker templates instead of jsps, we could do that, and we wouldn't have to touch our Action class or Service layer. If we want to change our business logic, it should not affect our Action class or View layer.

There are other MVC frameworks out there. What makes Struts 2 stand out from the others? Well, to start with, it is the one that my employer wants me to use - always a good incentive. That being said, I personally still prefer Struts 2 to any of the other frameworks I have tried. My only other experience has been with Spring MVC, which seems to be a good solution as well, but made less sense to me than Struts 2 does.

Struts 2 has a lot of features, and I have barely begun to scratch the surface on all that it can do. More posts will come in the future that start talking about the Interceptor concept, the built in validation framework, and many of the other features that Struts 2 has to offer.

I leave you today with the thing that most developers always want to see in a new technology - the Hello World.

The following clips were taken from http://struts.apache.org/2.x/docs/hello-world.html.

The Action class:
package tutorial;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorld extends ActionSupport {

    public static final String MESSAGE = "Struts is up and running ...";

    public String execute() throws Exception {
        setMessage(MESSAGE);
        return SUCCESS;
    }

    private String message;

    public void setMessage(String message){
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

The struts.xml file:
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="tutorial" extends="struts-default">
        <action name="HelloWorld" class="tutorial.HelloWorld">
            <result>/HelloWorld.jsp</result>
        </action>
        <!-- Add your actions here -->
    </package>
</struts>

The JSP file:
<%@ taglib prefix="s" uri="/struts-tags" %>

<html>
    <head>
        <title>Hello World!</title>
    </head>
    <body>
        <h2><s:property value="message" /></h2>
    </body>
</html>

Wednesday, January 26, 2011

Unit Testing

Unit testing is one of my favorite time saving techniques. I am amazed at the number of people that I talk to that don't write unit tests, because it takes too long, or it feels like writing it twice, or a handful of other reasons that I have heard.

Plain and simple, if used right, unit tests can save you a whole bunch of time. It is one of those spend-a-little-to-save-a-lot techniques. I find this to be particularly true in web development.

I get rather sick of manually testing my stuff for a web application. Each little change is a complete chore. You have to
  1. Make the change
  2. Deploy the new app
  3. Possibly restart the web server
  4. If necessary, log in
  5. Navigate to the page in question
  6. Perform activity under examination (potentially a lot of clicks involved here)
  7. Evaluate the displayed results
Not only is this time consuming, but it is also incredibly prone to error conditions. What if something didn't deploy right? What if the web server is bugging out? Maybe the displaying of the results is incorrect. What if you hit the wrong link, or typed in the wrong value, or whatever. You get the idea.

Another one I see people do sometimes is that they will write little main() functions in their code, in order to test their functionality. Guess what - that is basically what a unit test is! Only now you are adding more code, and getting less support by your IDE.

Unit tests are basically just little code snippets that most modern IDEs know how to support natively. They can be automated, they can provide reports, and better yet, they can be rerun time and time again, at just a single click of a button.

Unit tests really are not all that scary, once you get into them. Here is an example of a very simple test that will always pass:

public class TestMyClass
{
     @Test
    public void testMyClass() {
        assertTrue(1 == 1); 
    }
}

Not too bad, right? This will always tell you, every time you run the tests, that 1 does in fact equal 1. Not all that helpful, but it is a start. So, let's go with a more real-world scenario:

public class TestMailService
{
     @Test
    public void testSetForwarding() {
        MailService mailService = new MailService();
        mailService.setForwarding("fromaddress@domain.com",
            "toAddress@domain.com");


        assertTrue(
            mailService.getForwardingAddress( "fromaddress@domain.com" ).
            equals( "toAddress@domain.com" ));

    }

}

So, this is a slightly meatier example that tests a mail service that sets up forwarding. With this little snippet in place, you can determine that your mail service library is successfully setting and retrieving the forwarding address correctly. If you or somebody else does something that breaks that functionality, you do not need to experience that through your web browser in order to become aware of the problem.

This is by no means an exhaustive study on unit tests. It really only scratches the surface. If you have not used them before, though, I highly recommend you look into it. Save yourself some time, and make your coding world just that much better.

About Me

I'm Dustin Wilhelmi, and I am a software developer team lead for the University of Kansas. I live locally here in Lawrence, KS, with my wife, my 3 year old baby girl, and a dog that barks like crazy at the growing grass.

I got my CS degree from Emporia State University, which has a very small but absolutely awesome Computer Science department. The size allowed me to have a good relationship with my teachers (yes, that's right, they actually knew who I was!) and meant I had a good close relationship with pretty much every CS student there. I was trained in C++, and in my professional career have worked fairly extensively in C# and in Java, which is my current language of choice.

Now that we have the basics out of the way, we can get on with the meat. Mostly I am creating this blog to keep a record of things that I stumble on - interesting solutions to problems, solid third-party libraries, whatever. I don't even know that anybody will ever read this, but it at the least gives me a good place to keep track of my stuff in an easily searchable fashion.

So that's it. Have fun, learn something, and feel free to comment or email any questions.