Friday, March 1, 2013

Increase quality and productivity with the Jersey Test Framework

With the Jersey test framework developers can increase the quality of their software as well as their productivity without leaving the comfort of their favorite IDE.

The framework spins up an embedded servlet container that is configured to load the restful resources specified by the developer. In addition, the SpringServlet can be used to wire in the necessary beans if Spring is being used.

And, this is really super simple. The key is to extend the JerseyTest class and override the configure() method. In the configure() method you supply the same information that you would normally provide in your web.xml.

Line 5 : specify the package that contains the Jersey resource(s) you want to test
Line 6 : provide the name and location of the Spring context file (if using Spring)
Line 7 : turn on the JSON to POJO mapping feature if you want to use that

public class MyResourceWebServiceTest extends JerseyTest {

    @Override
    protected AppDescriptor configure() {
        return new WebAppDescriptor.Builder("com.mycompany.services")
            .contextParam("contextConfigLocation", "classpath:**/testContext.xml")
            .initParam("com.sun.jersey.api.json.POJOMappingFeature", "true")
            .servletClass(SpringServlet.class)
            .contextListenerClass(ContextLoaderListener.class)
            .requestListenerClass(RequestContextListener.class)
            .build();
    } // configure()
Once your test class is configured to spin up the embedded web container with your resources now it's time to write your tests. Again, the Jersey test framework makes it so easy even a caveman can do it.

On line 3 below we simply access a WebResource object and provide the relative URI to the resource we are interested in. This URI should match the @Path mappings in your Jersey resource definition.

Once the WebResource is defined simply use it to build and execute the HTTP request for the desired HTTP method, in this case GET, as shown on line 6. That's it. All that's left to do is the standard JUnit stuff to validate the response.
    @Test
    public void someTest() {
        WebResource webResource = resource().path("/some/resource/17");
        ClientResponse response =  webResource
            .accept(MediaType.APPLICATION_JSON)
            .get(ClientResponse.class);

        assertEquals(200, response.getStatus());

        try {
            JSONObject obj = new JSONObject(response.getEntity(String.class));
            assertEquals("widget", obj.get("type"));
        } catch (JSONException e) {
            fail(e.getMessage());
        }
    } // someTest()

Now, push a button or hit a key or two to kick off your JUnit test suite and watch your Jersey web services and tests fly.  If you need to make a change it only takes a minute or two to modify your code and run the tests again.

One piece of advice - create a test specific Spring context file targeting the exact REST resources you want to test and, if your resources eventually end up accessing some datasource (most would), consider injecting mock data access objects into your Spring beans so you can easily control the data that your resource would have access to, thus easily facilitating your testing (and development) and making your tests repeatable.

See this post if you want to learn how to easily create hyperlinks in your Jersey REST services.

Wednesday, February 27, 2013

How to return a Location header from a Jersey REST service

If you're following the Resource Oriented architectural style (ROA) for REST you're often interested in building and returning hyperlinks to your resources in your web service responses.

In the case of an HTTP CREATE, in addition to returning an HTTP 201 response code, you're also going to want to return a hyperlink to the newly created resource in the Location header of the response.

The Jersey JSR 311 implementation makes this a trivial task.  The first step, as you can see in line 2 below, is to inject a UriInfo class member using the Jersey @Context annotation.  Jersey recognizes a number of different resources that can be injected into your service classes via the @Context annotation.  In this case we're interested in information about the URI of our web service.

Once you've completed the work of creating your new resource (whatever that happens to be) and you're ready to formulate a response it's a simple matter to create the hyperlink and place it in the Location header of the response.  The key is to get the absolute URI to this current service as we're doing in line 21 below.  And assuming your URI convention is to tack the ID on to the URI for the CREATE service (as it probably should be in REST) simply append the ID to the absolute URI and use the Jersey Response builder to complete your response.

The hyperlink we just created should look something like http://mydomain/services/resource/1234 and map over to the GET-mapped service shown below starting on line 34.

    @Context
    private UriInfo _uriInfo;
  
    @Path("/resource")
    @POST
    public Response createResource(String data) {
        Response response = null;

        try {
            // convert data to model object
            Model model = someConversionMethod(data);
            // save model object
            _businessManager.saveModel(model);

            // formulate the response
            response = Response.status(201)
                .header(
                    "Location",
                    String.format(
                        "%s/%s",
                        _uriInfo.getAbsolutePath().toString(),
                        model.getId()
                    )
                )
                .entity(model.getId())
                .build();
        } catch (Exception e) {
            response = Response.status(500).entity(e.getMessage()).build();
        }

        return response;
    } // createResource()

    @Path("/resource/{id}")
    @GET
    public Response getResource(@PathParam("id") String id) {
        ... 
See this post if you want to learn how to easily test your Jersey REST services.

Sunday, November 18, 2012

UML Class Diagram Relationships, Aggregation, Composition

There are five key relationships between classes in a UML class diagram : dependency, aggregation, composition, inheritance and realization. These five relationships are depicted in the following diagram:

UML Class Relationships
The above relationships are read as follows:
  • Dependency : class A uses class B
  • Aggregation : class A has a class B
  • Composition : class A owns a class B
  • Inheritance : class B is a Class A  (or class A is extended by class B)
  • Realization : class B realizes Class A (or class A is realized by class B)
What I hope to show here is how these relationships would manifest themselves in Java so we can better understand what these relationships mean and how/when to use each one.

Dependency is represented when a reference to one class is passed in as a method parameter to another class. For example, an instance of class B is passed in to a method of class A:  
public class A {

    public void doSomething(B b) {

Now, if class A stored the reference to class B for later use we would have a different relationship called Aggregation. A more common and more obvious example of Aggregation would be via setter injection:
public class A {

    private B _b;

    public void setB(B b) { _b = b; }

Aggregation is the weaker form of object containment (one object contains other objects). The stronger form is called Composition. In Composition the containing object is responsible for the creation and life cycle of the contained object. Following are a few examples of Composition. First, via member initialization:
public class A {

    private B _b = new B();

Second, via constructor initialization:

public class A {

    private B _b;

    public A() {
        _b = new B();
    } // default constructor

Third, via lazy init:

public class A {

    private B _b;

    public B getB() {
        if (null == _b) {
            _b = new B();
        }
        return _b;
    } // getB()

Inheritance is a fairly straightforward relationship to depict in Java:

public class A {

    ...

} // class A

public class B extends A {

    ....

} // class B


Realization is also straighforward in Java and deals with implementing an interface:

public interface A {

    ...

} // interface A

public class B implements A {

    ...

} // class B

Tuesday, October 9, 2012

ActiveMQ Producer Flow Control Send Timeout

ActiveMQ has a feature called Producer Flow Control that throttles back message producers when it detects that broker resources are running low.  In fact, it will block threads sending messages until resources become available.

You can configure the broker to timeout the message send so that it does not block when producer flow control is in effect, but this is a global setting and you cannot configure it per queue.

However, the ActiveMQConnection class has a setSendTimeout() method, but it is not exposed via the JMS connection interface.  There are a couple of ways to handle this.

First, you could simply cast your connection object to an ActiveMQConnection and then call the setSendTimeout method directly.  This works fine if you know for sure your implementation is ActiveMQ and you have access to the ActiveMQ libraries at compile time (in other words, you don't mind having this dependency in your messaging client).

try {
    // Create a ConnectionFactory
    ActiveMQConnectionFactory connectionFactory
        = new ActiveMQConnectionFactory("tcp://localhost:61616");

    QueueConnection connection = connectionFactory.createQueueConnection();
    ((ActiveMQConnection)connection).setSendTimeout(5000);
    ...

A second way to handle this would be to use Java reflection to dynamically invoke the setSendTimeout() method if it is available, like so:

try {
    ...

    QueueConnection connection = connectionFactory.createQueueConnection();

    try {
        Method setSendTimeout = connection.getClass().getMethod(
            "setSendTimeout",
            int.class
        );
        if (null != setSendTimeout) {
            setSendTimeout.invoke(connection, 5000);
        }
    } catch (Exception e) {
        System.out.println("could not invoke the setSendTimeoutMethod"); 
    }
    ...

With this approach, you can configure send timeouts per connection and you can be somewhat JMS provider agnostic in your client. Keep in mind that if you use a container to provide your JMS connection factory the connections you get back may not be ActiveMQ connections, but rather proxy objects that wrap an ActiveMQ connection.

Friday, September 28, 2012

Project Management, Agile and the Replacement Refs

An article I read this morning mentioned that now that the regular NFL refs are back on the job the referees have faded into the background and the game itself has taken center stage again.  Relative calm and order have been restored and fans, players and coaches can focus on the product (football) and not the administration of it.

I got to thinking about it and I realized how much that applied to project management on agile projects (I'm referring to organizations, like mine, that are project management centric, rooted in waterfall methodologies, and trying to implement scrum in a move toward agile).

Traditional project management on agile projects, where the focus is primarily on schedules, timelines, budgets, status meetings, resources, timekeeping, etc. etc. is akin to replacement refs in a professional football game - the management of the project is too visible and steals center stage.

So, bring back the regular refs and restore the integrity of agile by making the product itself the center of attention, surrounded by the team member collaborations and customer interactions that comprise the real game of agile and let project management quietly fade into the background where it can unobtrusively maintain calm and order.

Disclaimer: I think the replacement refs were put in a tough position where limited training, high expectations and the speed of the game made their ability to succeed a tough proposition from the very outset. I think the same can be said of traditional project managers on agile projects.

Friday, August 31, 2012

slf4j5 - Java logging even faster

In my previous posting where I introduced slf4j5 I reported that, to my surprise, performance was better than when using slf4j by itself - probably due to the usage of the Java 5 String formatter.

Inspired by this I took a closer look at performance and ended up creating a dedicated thread in each logger for doing the actual logging work (i/o). This resulted in more than a 50% improvement over slf4j5 without the dedicated thread. This has the added benefit of providing for non-blocking logging in a multi-threaded environment.

Get the code here: http://code.google.com/p/slf4j5/

Tuesday, August 21, 2012

Introducing slf4j5 - logging, varargs, String.format, faster

I was recently investigating some of the Java logging frameworks out there and really like the flexibility/abstraction layer that slf4j provides and decided to give it a try with the logback logging implementation, which is apparently the successor to log4j.

I noticed that slf4j has its own formatter built into the logging api calls for assembling parameterized strings. However, what I didn't realize is that it only accepted a maximum of 2 parameters.  Bummer.  What happened to varargs?  Turns out slf4j doesn't support Java 5 yet and it didn't sound like it was going to anytime soon.

So, I wrote a simple Java 5 wrapper around slf4j and, except for the Java 5 string formatting, you use it just like you would slf4j.  You can find it here (I'm hoping the slf4j folks will take it on as a subproject - if so, I'll update the link):

http://code.google.com/p/slf4j5/

I figured since I was adding a small layer on top of slf4j that there would be a performance penalty.  It would stand to reason, but I wanted to know how much overhead I was adding to slf4j so I wrote some tests to measure it.   I was so surprised by the results that I ran the tests over and over and reviewed the code and tweaked the tests until I convinced myself what I was seeing was actually true - the slf4j5 wrapper was actually faster than using slf4j by itself (with logback, of course).

But, how could that be? My guess is that it's primarily due to the use of String.format() rather than the custom formatter used in slf4j.

Here were the results:
In addition, I also enhanced the context-awareness to automatically log the class, method and line from which the logging call originated.

On a similar note, using this auto-detection strategy, you don't need to specify a class or a name when obtaining your logger.  For example:

LoggerFactory.getLogger() will obtain a logger for the class wherein this statement is contained.

So, varargs, advanced formatting, faster performance, auto-context detection - several good reasons to take it out for a test drive.

I will be working on the wiki, but here's an example:

public class MyClass { 

    private final Logger _log = LoggerFactory.getLogger();

    public void doSomething(int param1, String param2, double param3) { 
        _log.debug(“entering, params = %d, %s, %8.2f”, param1, param2, param3);
        
        // some useful business logic here
      
        _log.debug(“leaving”);
    } // doSomething()

    ...

The above logging statements would result in something like the following in the log file:

2012-08-22 07:33:22.543 DEBUG [main] [MyClass.doSomething():6] entering, params = 100, hello, 500.00
2012-08-22 07:33:23.618 DEBUG [main] [MyClass.doSomething():10] leaving

Let me know how it goes.

Saturday, January 7, 2012

Tuesday, April 5, 2011

Network tune-up for Windows Home Server (WHS) performance

It's all about the cables

Although I've been very pleased with my Windows Home Server, one area that has been a little disappointing is performance - until today that is.

Recently I tried restoring a 120 GB backup onto a new hard drive.  Unfortunately, WHS reported that it was going to take upwards of 22 hours - yes HOURS - to complete.  I figured there was something wrong with that so I cancelled and proceeded to investigate.  I found some interesting things on Google that said do this or that but none of those suggestions seemed to work for me.

Since my router was only capable of 100 Mbps and since my WHS box has a Gigabit LAN port I figured I would try upgrading my router.  After setting up my new Netgear gigabit router I noticed that my WHS box was only connecting to the network at 10 Mbps.  That would certainly explain where the 22 hours to restore a 120 GB backup was coming from - 120 gigabytes at 10 megabits per second would take about that long to transfer across the network.  But I had a gigabit router and a gigabit LAN port - why was the WHS box only connecting at 10 Mbps?

Well, it turns out, it was the cable.  My network, which I built several years ago, was wired with CAT5 cable.  Apparently cabling has come a long way since then and I was unaware.  But, when I swapped out the CAT5 cable from my router to my WHS box with the shielded CAT6 cable that came with the new router my WHS box was now connecting to the network at the 1 Gbps speed.  Yeah!  And, the restore of that 120 GB backup now took less than 30 minutes to complete.  Wow, what a difference.

So, if you're having trouble with performance from your WHS check your LAN cables.

I would also like to mention that the Netgear N600 router I bought has an awesome feature that I was unaware of when I bought it as it doesn't seem to be described in the product literature.  There is a button on the front where you can turn off the wireless portion of the router - very cool since all of my connections are currently wired connections.

If you want to see how to restore a backup to new/different hardware see my post on 'Windows Home Server to the rescue'

Sunday, March 6, 2011

Agile Thoughts : Sprint Length

team maturity and work definition are key factors

There are many factors that can/should influence sprint length, such as delivery schedules, resource availability, customer requirements, need for feedback, etc., but two often overlooked and perhaps most important factors are team maturity and how well the requirements/work are defined.

If I were putting together a new team or implementing scrum/agile processes for the first time with an existing team I would lean towards shorter sprints, perhaps on the order of a week or two.  I believe this would allow a team to mature much more quickly as there are more opportunities to exercise the full sprint process and more opportunities to use feedback to more rapidly move toward becoming a high-performing team.
Another key factor affecting sprint length is how well the work to be performed is defined and understood.  This includes both the business and technical aspects.  If the requirements are vague or unclear or if the technologies to be used are new or not widely known by the team then it might be a good idea to shorten the sprints to flush out more detail and get more rapid feedback from the customer on whether the team is on or off course.  Likewise, shorter, more focused sprints might help the team determine whether technology or architecture choices were appropriate and correct as well as helping to minimize risk or wasted effort.

As you can see from the above chart, mature, high-performing teams with poorly defined requirements and new, immature teams with outstanding requirements are in virtually the same place - they both need shorter sprints, for different reasons of course, but shorter sprints none-the-less.

See also:  agile thoughts : backlog preparation

Saturday, March 5, 2011

Windows Home Server to the rescue

restoring a PC to new hardware

Several months ago I built a Windows Home Server box partly to back up the family's PCs - one of which is an aging Windows XP machine that I built seven or eight years ago.  As luck would have it the last remaining SCSI hard drive in that old XP box started to fail last week, corrupting the OS and causing the machine to fail to boot.

Since I had this new WHS box I figured I had nothing to lose so I decided to try my first restore.  It was dirt simple and it worked, for a day or two, until the OS was corrupted again.  I ended up swapping out my SCSI controller for a SATA controller, added a new SATA hard drive and performed a restore from WHS onto my new hardware.  It looked like it was going to work just fine - until the first reboot after the restore.  As most of you probably guessed, the backup image did not have the drivers for my new PCI SATA card and thus Windows failed to boot.

I tried numerous things and finally discovered the recipe that would let me successfully restore the backup for my old hardware onto my new hardware:

1.  Restore the PC from WHS onto the new hardware

2.  Boot from the Windows XP CD, pressing F6 at the right time to install the SATA drivers for the new hardware

3.  Choose to install Windows XP (do not enter the XP recovery console)

4.  When prompted, choose to 'Repair' the current installation

Windows will appear to be performing a fresh install (and to some extent it is), but all of your programs and data will be left intact.  If you goof up along the way and accidentally do a full reinstall instead of a repair don't fret, simply go back to step 1 and start over by restoring the PC from WHS again.

5.  Once the repair is complete reboot into the OS and run Windows Update to recover all the patches and updates that were lost by the repair (in my case Windows was set back to SP2 from SP3 since SP2 is the service pack level of my installation CD)

6.  I would advise performing a manual backup to WHS at this point

In hindsight it seems like a pretty simple process, and it is, but it did take some trial and error to figure out.  Needless to say I am very pleased with Windows Home Server and my decision to add a WHS box to my home network.

See my post on 'network tune-up for WHS' to find out how to make the above process much faster and smoother.

Saturday, February 26, 2011

Agile Thoughts : Backlog Preparation

Two hours can make a huge difference.

I've been working in an agile development shop using the Scrum methodology for over four years now and have a few thoughts on what works well, what doesn't work so well and some thoughts on how to improve the process. The first topic I would like to discuss is backlog preparation and where that fits/should fit into the sprint schedule. 

For those of you unfamiliar with Scrum/agile a 'sprint' is a short iteration, somewhere in the 2 to 4 week range (+- a week) that consists of work selection, planning, design, implementation/development, testing, presentation to the client and a team retrospective - usually fairly rigid and in that order.

The team works from the 'backlog' - a list of features or capabilities (called stories) that need to be researched, developed or integrated into the software.  This list is created and prioritized by the 'solution owner' in cooperation with the client/customer.  But since we are talking about agile, this list can be changed frequently based on customer feedback and changing priorities.

Usually, these stories start out as nothing more than simple one line statements or short paragraphs of the form 'as a user I need to be able to do X.'  At some point in this agile/scrum process these stories need to be flushed out in enough detail so that (a) the story can become actionable by the team and (b) the amount and type of effort required to complete the story can be estimated with some degree of accuracy.  In my experience this usually occurs at backlog selection (the kickoff meeting for the new sprint where work is selected).  This usually, without exception, leads to meetings that are long, frustrating, and less productive than they need to be.

Agile/scrum teams usually try to combat this by holding 'backlog grooming' meetings throughout the sprint to flush out some of the details of these future stories and make some preliminary design decisions.  This, however, has several shortcomings that I have seen time and again:  (1) it interrupts the flow/focus of the current sprint, (2) team members are distracted by the current sprint's work and don't fully focus/participate in the thought process for developing future stories and (3) the team many times invests time in preparing stories that they will never actually work or that change dramatically by the time they do.

I use to work in manufacturing and one of the key concepts was 'just in time' - you bring the materials, machinery, and manpower together at just the right time so that inventory isn't building up or so that people and machinery aren't sitting idly by.  It's a great concept and aptly applies to software development and agile processes.  In this context I believe there is one, and only one, place for backlog preparation and that is sometime between when the team has completed its work on the current sprint and prior to the next backlog selection meeting.

The purpose of these backlog preparation meetings is for the solution owner to present the team with the stories that are to be worked in the coming sprint, for the team to ask some initial questions, and for the team to then go off and do some initial brainstorming.  The result should be stories that have a clearer 'definition of done' with some initial high-level tasking from which reasonable estimates of effort can be made.  This meeting should be short, perhaps no more than an hour with the solution owner present and perhaps another hour for the team to brainstorm and come up with an initial tasking, estimates, additional questions for the solution owner and, if need be, alternative implementations/paths forward.

The benefits to this approach are that the team is constantly focused on the work they are to be performing at any given point in time, resources are more efficiently and effectively utilized, the actual backlog selection meeting is more productive, estimates are more accurate, teams are happier and more engaged, and sprints get started off on the right foot and have a higher probability of success.

Two hours spent in backlog preparation - at the right time - can make a huge difference.

See also:  agile thoughts : sprint length

Standalone ExtJS XTemplate classes

ExtJS XTemplates are awesome!  They provide an easy way to combine custom presentation markup with simple or complex data on the client.  Sometimes that markup needs to be more dynamic than simply plugging the data straight into the template.  But, the Ext folks already thought of that and allow you to add methods to your XTemplate definition.  This is great, but can lead to gangly template definitions with scoping issues.

In a recent situation at work we had a 400+ line template definition - only about 20 lines of that was the presentation template, the rest being methods to manipulate/interpret the data (beyond the conversions we had already applied to the data).  In our situation we needed to interpret the same piece of data in different ways depending on where we were in the template (context) as well as the type of view the user wanted to see.  For those of you familiar with XTemplates you will realize that the 400+ lines of template definition are in the constructor call to the XTemplate class - basically a huge constructor parameter.  Obviously it was time for some refactoring.

I have written numerous custom components in javascript, but never one extending the XTemplate, so I decided to try making our template a custom class that extended the ExtJS XTemplate.  Turns out it worked beautifully with very little modification to the original template (other than relocating it to its own file and doing some minor restructuring).  The template markup became part of the call to the super constructor in my new class' constructor and the methods became first class citizens of my new class (which ext accomplishes behind the scenes anyway in the original implementation).

As a result the client code using the template only needed a single line to create an instance of the template, the template is now reusable if needed, the code is cleaner all around, and the scope/context inside the template methods is more natural and easier to understand.

See also:  injecting extjs components via html templates

Monday, January 17, 2011

Injecting ExtJS components via an html template

Use Ajax to load an html page as a template for ExtJS and then plug ExtJS components into it.

Sometimes a web page layout may be too complicated or time-consuming to develop purely in ExtJS or perhaps you want to convert an existing html page to use ExtJS components. In either case there is a simple and straightforward way to inject ExtJS components into a complex html page. There are only a few simple steps needed to accomplish this:
  • create the html
  • fetch the html
  • load the html
  • plug in the ExtJS components
Here is a snippet from myPage.html. Notice the {idBase} included as part of the id. That is a template param that will be replaced when the ExtJS XTemplate is processed. The purpose of {idBase} is to help make sure that each div section has a unique ID and is not really germain to this article.
    
...
The following methods are from myScript.js. This method loads the html using an Ajax request:
     initStructure : function() {
         Ext.Ajax.request({
             url : 'myPage.html',
             disableCaching : false,
             method : 'GET',
             success : this.onStructureLoaded.createDelegate(this)
         });
     } // initStructure()
This success handler puts the html text into an ExtJS XTemplate and then loads that into the body of this component (an ExtJS panel or window):
     onStructureLoaded : function(response, options) {
         var template = new Ext.XTemplate(
             response.responseText
         });

         this.body.update(template.apply({
             idBase : this.id
         }));

         this.initMyButton();
     ...
     } // onStructureLoaded()
Once the html has been loaded into the DOM we can start plugging our ExtJS components into it:
     initMyButton : function() {
         new Ext.Button({
             applyTo : this.getCustomId('myButton'),
             text : 'My Button',
             handler : this.onMyButtonClick.createDelegate(this)
         });
     } // initMyButton()

     getCustomId : function(name) {
         return String.format('{0}_{1}', name, this.id);
     } // getCustomId()

Wednesday, January 12, 2011

Spring-loading and injecting external properties into beans

Let's say you have a Spring managed bean that contains some properties that you would like to externalize from your application, say perhaps in a JBoss 'conf' folder properties file.  Apparently you can do this via annotations in Spring 3, but it's also fairly straightforward in Spring 2.5:

From the context.xml file:

    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:my_app.properties"/>
        <property name="placeholderPrefix" value="$prop{"/>
    </bean>
 
    <bean id="someBeanWithProps" class="my.class.with.Props">
        <property name="myPropA" value="$prop{prop.file.entry.prop.A}"/>
        <property name="myPropB" value="$prop{prop.file.entry.prop.B}"/>
    </bean>

JBoss, JNDI and java:comp/env

On startup JBoss will process any xyz-service.xml files it finds in the deploy folder before it processes any war or ear files, etc.  One thing this could be useful for is to preload configuration values into JNDI, thus making them available to web applications when they start up.  It may sound simple but it consists of a non-obvious four step process:

1.  Create a JNDIBindingServiceMgr mbean in the xzy-service.xml file.

2.  In the WEB-INF/jboss-web.xml file map a resource-env-ref entry over to a JNDI value bound in step 1.

3.  In the WEB-INF/web.xml file create a resource-env-ref entry for each JNDI bound value.

4.  Access the JNDI value from somewhere, such as a servlet filter, using 'java:comp/env'

First, the xyz-service.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE server PUBLIC "-//JBoss//DTD MBean Service 4.0//EN"
    "http://www.jboss.org/j2ee/dtd/jboss-service_4_0.dtd">
<server>

    <mbean code="org.jboss.naming.JNDIBindingServiceMgr"
           name="netcds.cas.client:service=JNDIBindingServiceMgr">

        <attribute name="BindingsConfig" serialDataType="jbxb">

            <jndi:bindings
                xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
                xmlns:jndi="urn:jboss:jndi-binding-service:1.0"
                xs:schemaLocation="urn:jboss:jndi-binding-service:1.0 resource:jndi-binding-service_1_0.xsd">

                <jndi:binding name="my/jndi/property">
                    <jndi:value type="java.lang.Boolean">false</jndi:value>
                </jndi:binding>

            </jndi:bindings>
        </attribute>
        <depends>jboss:service=Naming</depends>
    </mbean>

</server>

Next, the resource-env-ref entry in the jboss-web.xml file:

    <resource-env-ref>
        <resource-env-ref-name>my/jndi/property</resource-env-ref-name>
        <jndi-name>my/jndi/property</jndi-name>
    </resource-env-ref>

And the associated web.xml entry:

    <resource-env-ref>
        <resource-env-ref-name>my/jndi/property</resource-env-ref-name>
        <resource-env-ref-type>java.lang.Boolean</resource-env-ref-type>
    </resource-env-ref>

Finally, accessing the JNDI value from a servlet filter:
      
    boolean result = false;
    try {
        InitialContext context = new InitialContext();
        result = (Boolean)context.lookup("java:comp/env/my/jndi/property");
    } catch (final NamingException e) {
        // log and/or sys out
    }

Thursday, December 16, 2010

No dynamic filters in servlet spec 2.4 you say?

I had a requirement recently to be able to dynamically control CAS security filters in a web application (default CAS security to off for development and allow it to be turned on by external configuration post-deployment).  Unfortunately, servlet spec 2.4 does not allow one to programatically add new servlet filters (at least that's the prevailing theory).  This is a feature added/being added to the servlet 3.0 API.

My friend Google said there were a number of others who wanted to do the same thing but they were being pointed to servlet 3.0.  Unfortunately, servlet 3.0 and J2EE 6 were not an option for me, so it was looking like a tough nut to crack.

Then it struck me, what if I created a generic, conditional servlet filter that took the name of the class of the real filter as an init param?  And, what if I passed in the condition that was to be evaluated to determine whether or not to create and/or invoke the real filter?  Then, in the conditional filter, I could examine the condition and, as necessary, dynamically create an instance of the wrapped filter class.

Turns out it worked like a charm.  Here's how.  First the filter definition in web.xml:

    CAS Authentication Filter
    my.org.security.servlet.ConditionalFilter
    
        condition
        cas/enabled
    
    
        wrapped-class
        
            org.jasig.cas.client.authentication.AuthenticationFilter
        
    


public class ConditionalFilter implements Filter {

    // instance of the actual filter being wrapped
    private Filter _wrappedFilter;

    // are we to ignore the wrapped filter?
    private boolean _ignore = true;

    public ConditionalFilter() {
    } // constructor

    public void init(FilterConfig filterConfig) throws ServletException {
        // the 'condition' init param tells us whether or not 
        // the wrapped filter is active
        _ignore = !checkCondition(filterConfig.getInitParameter("condition"));

        try {
            if (!_ignore) {
                // the wrapped filter is active so we create an instance 
                // of it and initialize it
                _wrappedFilter = getFilterInstance(
                    filterConfig.getInitParameter("wrapped-class")
                );
                _wrappedFilter.init(filterConfig);
            }
        } catch (Exception e) {
            throw new ServletException(e);
        }
    } // init()

    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain filterChain)
        throws IOException, ServletException {
        if (!_ignore) {
            // the wrapped filter is active so we let it do its work
            _wrappedFilter.doFilter(request, response, filterChain);
        } else {
            // wrapped filter is inactive so simply move on to the next filter
            filterChain.doFilter(request, response);
        }
    }  // doFilter()

    public void destroy() {
        if (_ignore) {
            _wrappedFilter.destroy();
        }
    }  // destroy()

    private Filter getFilterInstance(String className)
        throws ClassNotFoundException, InvalidClassException,
               InvocationTargetException, IllegalAccessException,
               InstantiationException, NoSuchMethodException {
        // try to create an instance of the wrapped filter 
        // with the given class name
        Class filterClass = Class.forName(className);
        java.lang.reflect.Constructor constructor = filterClass.getConstructor();
        Object filter = constructor.newInstance();

        if (!(filter instanceof Filter)) {
            throw new InvalidClassException(
                String.format("'%s' is not an instance of Filter", className)
            );
        }
        return (Filter)filter;
    } // getFilterInstance()

    /*
     * looks up the configured 'condition' via JNDI to determine 
     * whether or not the wrapped filter is active
     */
    private boolean checkCondition(String condition) {
        boolean result = false;

        try {
            InitialContext context = new InitialContext();
            String path = String.format("java:comp/env/%s", condition);
            result =(Boolean)context.lookup(path);
        } catch (final NamingException e) {
            System.out.println(
                "unable to load condition from JNDI"
            );
        }

        return result;
    } // checkCondition()

} // class ConditionalFilter

Friday, April 2, 2010

One Thumb Up for Pair Programming

Pair programming is one of the characteristics of extreme programming and is, frankly, something I have not been a particularly strong advocate of. The idea of two developers sitting side-by-side, sharing one keyboard and working the exact same problem seems terribly inneficient to me. However, there are two reasons why, for short periods of time, that it would be beneficial to engage in pair programming.

The first one would be for test driven development. For a particular functional area under development one developer would write the unit/integration tests and one would write the code. To me, this would be the most efficient use of pair programming.

The second reason why I think it would be beneficial to perform short stints of pair programming would be to gain insight into the work practices, processes and procedures of one's teammates. For me personally, I could see how my teammates work and glean some ideas on how I could be more productive and efficient. What tools do they use? How do they use them? Do they have any shortcuts or time-savers? Likewise, it would be an opportunity for me to help my teammates improve their efficiency by offering suggestions based on the things that I do that help me.

Tuesday, March 9, 2010

jboss plugin for auto-deploying artifact during build

This is VERY handy for automatically deploying your artifact/war after a maven build is completed. Simply add the mvn goal jboss:hard-deploy to your maven command.
<plugin>
   <groupId>org.codehaus.mojo</groupId>
   <artifactId>jboss-maven-plugin</artifactId>
   <version>1.4</version>
   <configuration>
      <jbossHome>${jboss.home}</jbossHome>
      <serverName>default</serverName>
      <fileName>target/my-app.war</fileName>
   </configuration>
</plugin>

Saturday, March 6, 2010

Tunneling PUT and DELETE from ExtJS to Jersey ReST

Here is how you can invoke AJAX POSTs in ExtJS that map to PUT and/or DELETE methods in your Jersey ReST services.

The first step is to configure Jersey to allow this:
<init-param>
    <param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
    <param-value>com.sun.jersey.api.container.filter.PostReplaceFilter</param-value>
</init-param>
The next step is to issue the AJAX request (in this case we're going to issue a POST but tell Jersey to invoke the PUT mapped method instead):
Ext.Ajax.request({
    headers : {
        'X-HTTP-Method-Override' : 'PUT'
    },
    method: 'POST',
    url: '/my-api/some-service',
    params: {
        name : someObj.name,
        date : someObj.date,
        amount : someObj.amount
    },
    success: this.onSaveSuccess.createDelegate(this),
    failure: this.onSaveFailure.createDelegate(this)
});