Is branching an OOP code-smell?

June 9, 2011 by

A code smell is a hint that something has gone wrong somewhere in your code. Use the smell to track down the problem

Kent Beck via http://c2.com/cgi/wiki?CodeSmell

I’ve developed a new code-smell sensitivity to “if.” In fact, branching in general triggers an alarm as I read through code (especially if I just typed it). 

Can something so fundamental to programming be a code smell? That gets me thinking that maybe it isn’t so fundamental to OOP.  In high academia, I was told that “structured programming” was the greatest formalism since the slicing of bread. There are 3 required pillars to structured programming:

  1. Sequence – A set of statements are executed in a certain order.
  2. Selection – Statements are executed conditionally.
  3. Iteration – A set of statements can be executed multiple times.

In light of declarative programming and OOP, all of these may be a code smell. For now, I’ll just tackle ‘selection’ and come back to the others as time permits.

Lest I wax too abstract, let’s start with some code (in pidgin java):

switch (pizza.crust) {
   case Pizza.CRUST_THICK:
      doughInOunces = 16 ;
      bakeTimeInMinutes = 13;
      break;
   case Pizza.CRUST_THIN:
      doughInOunces = 12;
      bakeTimeInMinutes = 8;
      break;
   case Pizza.CRUST_PAN;
   default:
      doughInOunces = 19;
      bakeTimeInMinutes = 18;
}

Here we have a selection, a choice if you will.  How much dough do we need and how long do we bake it? Well that depends on the thickness of the crust. Another way of saying that is that it depends on the type of pizza. That’s our first hint. First a detour through some smarter minds than mine.

I’m a big fan of the “Tell, don’t ask” principle and its close relative, “The Hollywood Principle.” Essentially, you don’t ask an object about its state and then act based on that state; you tell the object what you want it to do. In my example, the client code asks the pizza object about its state and makes a decision based on that state. That decision probably belongs near the state itself.

Here’s my proposed alternative (again in pidgin java):

class ThinCrust extends Pizza.Crust {
   int getDoughInOunces() { return 12; }
   int getBakeTimeInMinutes() { return 8; }
}
class ThickCrust extends Pizza.Crust {
   int getDoughInOunces() {return 16; }
   int getBakeTimeInMinutes() { return 13; }
}
class PanCrust extends Pizza.Crust {
   int getDoughInOunces() { return 19; }
   int getBakeTimeInMinutes() { return 18; }
}

And here’s the modified client code:

doughInOunces = pizza.crust.getDoughInOunces(); 
bakeTimeInMinutes = pizza.crust.getBakeTimeInMinutes(); 

Recall the ‘type’ hint. If you have a choice based on some type of something and you’re using a language with a type system (if not, I’d really like to hear about it), use that! In my modifications I created an inner type ‘Crust’ for the ‘Pizza’ type. Now the ‘selections’ are tucked into the types.

In the client code, I just tell the object of a certain (and probably unknown-at-compile-time) type to give me the data I need.

Okay, okay, I’m actually asking for data again. With more refactoring, my client code should actually just look like this:

pizza.bake()

The behavior that uses the values for baking time and amount of dough would still be needed, but only inside the pizza object. The pizza object itself would still want to get these values from its crust inner type, perhaps composed through an inversion of control (IoC) container like Spring.

Is there a case where one needs to perform selection instead of deferring the decision to a type? That is, what are the exceptions to my argument above?

What’s in YOUR work week?

April 6, 2011 by

“Time – got the time tick-tick-tickin’ in my head” – Joe Jackson

I need more time!

Let’s take a look at the average work week.  A handful of one hour meetings, maybe one large meeting, many smaller meetings.  By mid-week the calendar is almost full.  People are coming to your desk constantly asking for small adjustments/favors/tasks.  That time-saving-must-do project you had in mind, once again, received no time.  It’s the end of the week, you’re drained, and looking back you’re not sure what really happened.

You can read time management books, take a Covey course and recite all of the key phrases.  These are all good, and highly recommended.  But I’m going to fast forward to a different ending that’s not in the popular reading materials.  First let’s post a supposition:

Jim’s Axiom – Creativity does not exist without constraints.

You may be thinking “I can’t be creative WITH constraints!”  I respectfully say you are wrong.  Let’s go back to when you were younger.  You had a clean, unwrinkled, pristine sheet of paper (or an entire pad) and a pencil.  You looked down and… nothing.  “Mom, what should I draw?”

Did you see what just happened there?  Maybe you remember that, maybe you just heard your own child ask that very question.  There are no constraints.  You (or they) can draw anything, and you draw… nothing.  Where do you start?  What should you do?  If only you had a starting point you could go anywhere.  You need a constraint.

When the pressure is on, and you need to reach the goal line you do what it takes, you look for the opportunity, and you press forward and find a way.  Once there are constraints your creativity can take root and navigate through and bring you to success.

Jim’s Corollary – Creativity is the ability to solve a problem when there are constraints.

I need to find a way to the store and the main road is closed.  Creativity.
I need to buy groceries and I’m low on funds.  Creativity.
I need to get more done and I’m running out of time.  Creativity.

The Pony Express was infamous for delivering mail.  We could have grown that system and bought more horses.  When they weren’t fast enough we could have bred faster horses.  But the limitations were real, and no matter how much you did more of the same thing you couldn’t solve the pressing issue.  It doesn’t scale properly, and was not cost effective.  There had to be a better way.

This new way did not involve a horse.  It was the telegraph.  A completely different way of dealing with the issue.  Taking a broken system and spending more time doing it doesn’t get you the advance you’re really looking for.  The same is true during your work day.  If you take your current process and just add more time you do get more done.  But at what cost?  And what value are you really adding?

If you find yourself working 60+ hour weeks I’m going to challenge you.  Are you really only smart enough to just do more of the same to beat out your competition?  Is that how you sell yourself?  What happens when the next guy comes along and works 70 hours?  80?  They win?

But what about studies that state efficiency decreases as hours per week increases?  A quick search on Google yielded this: “The average efficiency for 50 hr, 60 hr, and 70 hr weeks was 0.92, 0.84, and 0.78, respectively.”  That means that at 70 hours per week you’re as efficient as actually working 55 hours.  You’ve heard the adage… why have you denied it?  Work smarter, not harder.

• Look at the work you’re doing and note the time spent.  What’s really eating your day?  What new process can you put in place to replace the old, inefficient model?  Focus on the important/non-urgent, and manage the important/urgent.  Avoid the non-important items!  Recommended reading:  First Things First by Steven Covey (Full disclosure: I’ve taken the Seven Habits course and love his style on time management, but I haven’t read this book yet.  Ironic I know.)

• The next step is to examine your processes.  Why and when you do what you do.  Keep your meetings focused and only invite those that should be there.  Set an agenda with a desired outcome, and once reached, end the meeting, even if it’s early!  Recommend reading: Death By Meeting by Patrick Lencioni.

• Are you trying to do it all on your own?  Who’s your model or mentor for that?  Look for strategic partnerships to accomplish more than you could do on your own.  Recommend reading:  Mentored By A Millionaire by Steven Scott.

As a young boy I heard a wealthy and successful man say something that has stuck with me.   I believe I’m finally starting to grasp the full intent, and I’ll leave it with you now:

“If you can’t do it in 40 hours a week, you’re doing it wrong.”

Implementing Modular Web Design: Part 2 – How?

March 29, 2011 by

Modular Web Design by Nathan Curtis and Web Anatomy: Interaction Design Frameworks that Work by Robert Hoekman Jr. and Jared Spool are great resources for UX developers. They focus on the theory, philosophy and process of designing modularly. Unfortunately, these books don’t go into any detail about how to actually implement, in code, a modular web design system in a web app. Some excerpts in Modular Web Design hint at what other companies have done, but there are no concrete steps to guide the process of implementation.

In this post I hope to outline a global strategy that is programming-language agnostic, easy for the end-user (in this case other developers) to implement, and hopefully elegant in its abstract design.

As a UX Engineer I approach code architecture the same way I approach a wireframe design. I start with what I want the end use case to look like and work my way back through the details. In this case my end users are my fellow developers and the goal for them is a super-easy implementation of reusable components that borders on the magical. Think jQuery’s “write less. do more.” motto on steroids.

I want developers to be able to write one line of code anywhere in the view tier of the web app and have that magically transformed into a fully functional component complete with CSS and JS wirings when the page is actually rendered by the server.

The end goal is one line code snippets that transform into HTML, CSS, and JS at runtime.

In order to achieve this, you need something in the request cycle that’s looking for these one-liners and triggering the component engine that renders the HTML, CSS, and JS to spring into action. Ideally this is some kind of string parser connected to your view composition engine, preferably pretty late in the composition cycle so the components will be one of the last things rendered by the server before the user sees the page.

The high level request diagram looks something like this:

Once the ability to detect snippets and return components in their place has been enabled, you can begin to break down the input and output processes further.

At some point in the input process the snippet that the output parser is scanning for will need to be broken down into arguments that can be passed to the component engine.  The syntax of the snippet will be discussed in a later post, but for now let’s assume that snippet is transformed into something the component engine can understand. We may also want to add rules at the input stage to check for things like component dependencies, or to ensure that there aren’t too many of one type of component on the page, (i.e. more than one site wide navigation component, probably not a good idea).

The component engine receives the appropriate arguments, works its magic, and returns HTML and paths to static assets. The HTML will need to be inserted in the same location that the snippet was previously. The static assets will require some more advanced routing.

Best practices are to have CSS references in the head and any static JS files referenced immediately before the closing body tag. There will need to be something at the output stage that can manage the creation and injection of the necessary <link> and <script> tags.

That’s pretty much it for the high-level overview. Obviously there’s more complexity that can be added like preventing the addition of duplicate JS and CSS files or combining those static assets into one file to lower the number of http requests, but that’s my vision for a basic implementation. A one line snippet becomes HTML, CSS, and JS all wired together. It’s modular, reusable, and wicked fast for implementation.

In my next post I’ll discuss the syntax of the invocation snippets. Specifically, strategies to prevent naming collisions, how to efficiently pass configuration parameters, and more. What are your thoughts on this high-level implementation? Would you do something different? Have you implemented something similar? If so, post a comment below.

Salesforce and Amazon SQS

March 8, 2011 by

A couple of us are working on a new project that involves Salesforce CRM. We recently came upon a few technical challenges related to our need to keep a subset of the data stored in the cloud in-sync with our internal application servers. These include:

  • Limited number of API calls we can make per 24 hour period. Salesforce charges a per-user license fee, and each license gives you a certain number of API calls. If our project scales as we expect it to, we could easily exceed the number of API calls.
  • Keeping development data in sync with our internal development server and test data with the test server.

We came up with two initial solutions:

  1. Have our internal systems poll the cloud for change.
  2. Have the cloud send a message to our systems informing us of a change.

The first approach requires a balancing act: how up-to-date does the information need to be on our side, vs. how many API calls we can make. If we poll every second, we would consume 86,400 calls per day – more than we will probably have allotted when we launch.  We also can’t consume 100% of our API calls on polls, as once we have detected that something needs to sync, we need to make calls to download the changed objects, and also need calls to periodically send data to the cloud as well.

The second approach seems to be the better one, as outbound messages don’t apply towards daily API limits. Also, we only anticipate the synced object types would only ever incur a few hundred changes per day, far fewer than the thousands of polling calls we would have to make. The problem then becomes how to implement the sync in a way that would work in our production ‘org’, our ‘sandbox’, and the ‘developer accounts’ that we developers are using. The way our web stack is structured, however, only allows for communication from third parties to see our production web environment. We could come up with our own way to queue messages in production intended for other levels, but we would need to be even more concerned about security and we would likely be duplicating something that the marketplace already provides.

It turns out someone does: Amazon.

I’ve been familiar with Amazon’s cloud computing offerings for some time now, just have never been able to utilize them with previous employers. Amazon has a service known as SQS, or Simple Queue Service, that “offers a reliable, highly scalable, hosted queue for storing messages as they travel between computers.”

With SQS you can:

  • Send up to 64KB of text per message
  • Persist messages for up to 14 days
  • Create unlimited queues (ie: one queue for each of our environments)
  • And a lot more

Furthermore, SQS is cheap: $0.01 per 10,000 requests (send and receive are considered separate), and about $0.1 per GB of transfer. Far cheaper than buying additional Salesforce licenses.

Salesforce has its own language known as Apex, which runs on their servers and has a syntax very similar to Java’s. SQS messages are fairly simple, with Query and SOAP based API’s available. The one complexity is the means of signing a message. SQS messages include HMAC signatures using a private key you establish with Amazon that prevents messages from being forged.

The SQS implementation is quite simple. An Apex Trigger exists on object that we need to sync.  That trigger enqueues a message containing the record type, the ID of the changed record, and a timestamp. This message goes to a SQS queue that corresponds to the environment (dev, test, prod, etc…).  A scheduled task on our end polls SQS every few seconds for changes.

How do you sign a message in Apex that conforms to SQS specs? Apex does have some good built in libraries, including a Crypto class that even has an AWS example in their documentation (though for a different service using a much simpler authentication scheme). Here is the solution I came up with:

<pre>public class AmazonSqsSender
{

	private String getCurrentDate() {
		return DateTime.now().formatGmt('yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\'');
	}

	public void sendMessage(String message) {
		//AmazonAws__c is a custom setting object that stores our keys, an Amazon Host, and a queue name
		//You can just put your keys, host and queue below as strings
		AmazonAws__c aws = AmazonAws__c.getOrgDefaults();

		String accessKey =aws.accessKey__c;
		String secretKey = aws.secretKey__c;
		String host = aws.host__c;
		String queue = aws.queue__c;

		Map<String,String> params = new Map<String,String>();

		params.put('AWSAccessKeyId',encode(accessKey));
		params.put('Action','SendMessage');
		params.put('MessageBody',encode(message));
		params.put('Timestamp',encode(getCurrentDate()));
		params.put('SignatureMethod','HmacSHA1');
		params.put('SignatureVersion','2');
		params.put('Version','2009-02-01');

		//The string to sign has to be sorted by keys
		List<String> sortedKeys = new List<String>();
		sortedKeys.addAll(params.keySet());
		sortedKeys.sort();

		String toSign = 'GET\n' + host +'\n'+queue+'\n';
		Integer p = 0;
		for (String key : sortedKeys) {
			String value = params.get(key);
			if (p > 0) {
				toSign += '&';
			}
			p++;
			toSign += key+'='+value;
		}
		params.put('Signature',getMac(toSign,secretKey));

		String url = 'https://'+ host+queue+'?';
		p = 0;
		for (String key : params.keySet()) {
			if (p > 0) {
				url += '&';
			}
			p++;
			url += key+'='+params.get(key);
		}

		HttpRequest req = new HttpRequest();
		req.setEndPoint(url);
		req.setMethod('GET');
		Http http = new Http();
		try {
			//System.debug('Signed string: ' + toSign);
			//System.debug('Url: ' + url);
			HttpResponse res = http.send(req);
			//System.debug('Status: ' + res.getStatus());
			//System.debug('Code  : ' + res.getStatusCode());
			//System.debug('Body  : ' + res.getBody());
		}
		catch (System.CalloutException e) {
			System.debug('ERROR: ' + e);
		}

	}
//Amazon wants + and * to be escaped, but not ~
	private String encode(String message){
		return EncodingUtil.urlEncode(message,'UTF-8').replace('+', '%20').replace('*', '%2A').replace('%7E','~');
	}

	private String getMac(String RequestString, String secretkey) {
		String algorithmName = 'hmacSHA1';
		Blob input = Blob.valueOf(RequestString);
		Blob key = Blob.valueOf(secretkey);
		Blob signing =Crypto.generateMac(algorithmName, input, key);
		return EncodingUtil.urlEncode(EncodingUtil.base64Encode(signing), 'UTF-8');
	}

	public static void sendTest() {
		AmazonSqsSender t = new AmazonSqsSender();
		t.sendMessage('Hello from Salesforce ' + Math.random());
	}
}

Using the System Log, it is possible to call AmazonSqsSender.sendTest() to send a random message. Some Java code was running on my workstation that proved messages were being sent.

For the time being, we are going to poll Salesforce directly to keep the overall complexity down, but at least we know that Amazon SQS is an option if we need it.

Brainteaser++, my first crack at Ruby

February 3, 2011 by

I got a new desk calendar with daily brain teasers. The advertised purpose is to give my mind a little exercise for a few minutes every morning. January 5th’s puzzle inspired me. What would be better than solving this puzzle? Writing a program to solve it for me! Even better, I’ll use a new language I’ve been meaning to pick up. Now we’re flexing the brain.

Here’s the puzzle:

In the table of letters, find the two ‘lines’ that contain the same set of letters. Lines can go horizontal, vertical, or diagonal and in any direction.

M P A F H E L
C G E H O A F
F A C M T L K
E B H F M C O
G H M L E O A
A L F O G K C
H C P T A G G

This definitely lends itself to a computerized, brute-force approach. ‘Line’ and ‘in any direction’ are misdirection.  Really we’re looking for two unordered sets that contain the same elements.

The approach

  1. Read the data from stdin line-by-line and build a collection of character arrays or strings including the columns and the two diagonals.
  2. Sort each string alphabetically. Then, I can use string comparison to see if two ‘sets’ contain the same elements.
  3. Iterate over the collection of strings, looking for two that match. It will have to be an ordered collection just so that I can output an indicator of which rows, columns, or diagonals matched.

Here’s my stab at it in Ruby.

class Puzzle

  def initialize
  	# table of characters from input
  	@char_table = []
  	# the horizontal, vertical, and diagonal lines from @char_table
  	@lines = {}
  end

  def main
    readPuzzle
    buildLines
    puts findMatch or "no matches found"
  end

  private

  def readPuzzle
    while line = gets
      lineAsArray = []
      line.chomp.each_char {|c| lineAsArray << c}
      @char_table << lineAsArray
    end
  end

  def buildLines
    counter = 0

    #horizontal lines
    @char_table.each { |line|
      @lines[ counter ] = line.sort.to_s
      counter += 1
    }

    #vertical lines
    #FIXME: assumes square 2D array; ought to validate that
    for i in 0..@char_table.length() - 1
      @lines[ counter ] = []
      for j in 0..@char_table[i].length() -1
        @lines[ counter ] << @char_table[j][i]
      end
      @lines[ counter ] = @lines[ counter ].sort.to_s
      counter += 1
    end

    #diagonal lines
    @lines[ counter ] = []
    @lines[ counter + 1 ] = []
    for i in 0..@char_table.length() -1
      @lines[ counter ] << @char_table[i][i]
      @lines[ counter + 1 ] << @char_table[i][@char_table.length - i - 1 ]
    end
    @lines[ counter ] = @lines[ counter ].sort.to_s
    @lines[ counter + 1 ] = @lines[ counter + 1 ].sort.to_s
  end

  def findMatch
    until @lines.length == 0
      key, val = @lines.shift
      @lines.each{ |key2,val2|
        if val==val2 then
          return "matches found at line #{key} and line #{key2}"
        end
      }
    end
  end
end

p = Puzzle.new
p.main

I really enjoyed the exercise.  The puzzle was supposed to take about 2 minutes.  This took hours (hey, it’s my first time with Ruby, cut me some slack). However, it can solve these puzzles in well under 2 minutes, so I think I still hit the mark.

My solution is not particularly Ruby-esque.  There’s a lot of explicit iteration with indices. That may just be the nature of trying to extract strings from a two-dimensional character table. Once I got past the data-loading, things seemed to get closer to the Ruby way.

What would you improve? (Especially to all you Ruby coders on the Web, how can I make this more Ruby-like?)

Implementing Modular Web Design: Part 1 – Why?

January 28, 2011 by

Having read Web Anatomy: Interaction Design Frameworks that Work by Robert Hoekman Jr. and Jared Spool and Modular Web Design by Nathan Curtis, I was super excited about the prospect of creating a component library for the developers here at Lampo. What’s so cool about component libraries? Let me tell you.

Imagine never having to hand-code a contact form ever again. Now I hear you, you’re saying “Kevin, I’m an awesome developer, I don’t hand-code contact forms, I’ve got code snippets, templates, and frameworks that allow me to quickly implement contact forms, why would I want a component library?” The problem with snippets, templates, and frameworks are three words that make every developer cringe: “copy and paste.”

Imagine working on a site that has 20+ contact forms all for different business modules within the company. Now imagine that you need to change something about all 20 of those forms. Now you’re saying, “But Kevin, CSS rocks my socks off, I reuse stylesheets like a champ!” To which I say, what if you need to alter the markup? What if you need to attach a bit of javascript to transform your contact forms for mobile devices? With copy and paste there’s just no global hook at the component level.

Another argument is for existing component libraries. Most of these are javascript based: jQuery UI, YUI, LivePipe etc. They’re great, but there’s still a good deal of configuration involved. You need to write the markup, create the js bindings between markup and the library, and then download a theme or write some CSS to make it all look pretty. The type of component library I’m talking about does all these things for you.

One line of code gets you markup, JS, and CSS. All wired up to work beautifully together and provide you with usability-tested, consistent, semantically-correct components to use throughout your web app. Plus you have the control to change and upgrade components on the fly and all users of your components will receive the updates. No need to do a search and replace (AKA search and destroy). It just happens.

Have I sold you yet? Do you want to build one of these? Does it sound as amazing as a triple rainbow unicorn?

Well it did to me. So how do you implement something like this? Hoekman and Spool’s book provided me with some great theory, but nothing code based. Curtis’s book does an awesome job of describing implementation for a design department (another benefit, another post), but also left me hanging when it came to coding.

So that’s where we begin. In the next post I’ll discuss how we approached the problem of actually implementing the Lampo component library lovingly known as “Gutenberg UX.”

That’s the origin story for our component library.  Have you implemented something similar or experienced any drawbacks implementing jQuery UI or another javascript component library?  Comment on this post and share your story with us!

Grails and Rabbits

January 12, 2011 by

Tim: There he is!
King Arthur: Where?
Tim: There!
King Arthur: What? Behind the rabbit?
Tim: It *is* the rabbit!
-Monty Python and the Holy Grail

This. Is. Ridiculous.

After SpringOne I was anxious to try Grails with RabbitMQ on my own.  I downloaded the complete bundle for Windows and set it up.  I’ve never run an Erlang application so I felt a bit funny, but it was simple and painless.  I set an environment variable for Erlang (ERLANG_HOME).  Then I just hard coded a ‘base’ directory for logging and whatnot in Rabbit (server.bat).  Yeah, I could have set another env var there too, but I was too anxious.

I started the server.bat file and had RabbitMQ running.  Though it was lonely.

Sir Bedevere: Well, now, uh, Lancelot, Galahad, and I, wait until nightfall, and then leap out of the rabbit, taking the French by surprise – not only by surprise, but totally unarmed!
-Monty Python and the Holy Grail

I jumped into STS and ran ‘install-plugin rabbitmq’
A simple config setting (Config.groovy):

rabbitmq {
   connectionfactory {
      username = 'guest'
      password = 'guest'
      hostname = 'localhost'
      consumers = 5
   }
   queues = {
      jimski()
   }
}

My Controller only needed to call:

rabbitSend 'jimski', msg

…and for fun I setup a Service to pull messages off the queue:

static rabbitQueue = "jimski"
void handleMessage(msg) {
   println "received message: $msg"
}

Voila! Messages taken in by the Controller make a call to rabbitSend and magically the Service sees them and pulls them out to display.  Crazy easy.  Crazy cool.

I’m going to keep at it.  Let me know your experiences with queuing.

Add Spring Security to ColdFusion

January 10, 2011 by

We are evaluating Spring Security as a part of our authentication and authorization platform. Since we have many ColdFusion apps, it was natural for us to see how it would work in tandem with ColdFusion. Fortunately, since ColdFusion is a Java web application, Spring Security fits right in.

In this post, I’ll show the basics of connecting Spring Security with ColdFusion. I’m not intending to teach how Spring Security works or other details of implementation. For more information, see the Spring Security Reference Documentation (also available as a PDF).

At a high level, you add Spring Security as a Servlet Filter that is setup to run before the ColdFusion servlet in the Java web application config file (web.xml). To make it as easy as possible to see how it works, I’ll show you how to to setup the Spring Security tutorial app. I’m starting with a new install of ColdFusion 9.0.1, installed as a J2EE app under Tomcat 6.0.29 (running on JDK 1.6.0.22, 64-bit on Windows XP Pro).

  1. Download Spring Security from here (using version 3.0.5, the latest as of this writing).
  2. Extract the zip file (spring-security-3.0.5.RELEASE.zip).
  3. Extract the tutorial WAR file located in
    spring-security-3.0.5.RELEASE/dist/spring-security-samples-tutorial-3.0.5.RELEASE.war
    to a local directory (I’ll call it <tutorial-war>).NOTE: If you’ve never run the Spring Security tutorial, you can just put the <tutorial-war> directory into the /webapps directory of your Tomcat app server and run it. Here is more info about Spring Security tutorial.
  4. Copy all of the .jar files from:
    <tutorial-war>/WEB-INF/lib
    into:
    <cf-app>/WEB-INF/lib
  5. Copy the file:
    <tutorial-war>/WEB-INF/classes/log4j.properties
    to:
    <cf-app>/WEB-INF/classes/log4j.properties
  6. Copy the file:
    <tutorial-war>/WEB-INF/applicationContext-security.xml
    to:
    <cf-app>/WEB-INF/applicationContext-security.xml
  7. Copy indicated lines from:
    <tutorial-war>/WEB-INF/web.xml
    to:
    <cf-app>/WEB-INF/web.xml 

    1. Under the line:
      <description>Adobe ColdFusion 9</description>
      (line 5 in my stock CF9 web.xml), insert the <context-param /> blocks from
      <tutorial-war>/WEB-INF/web.xml
      (NOTE: In the code below, I removed the first line in the first <context-param /> from the tutorial that said
      classpath:applicationContext-business.xml.):

      	<!-- INSERTED FOR SPRING SECURITY -->
      
          <!--
            - Location of the XML file that defines the root application context
            - Applied by ContextLoaderListener.
            -->
          <context-param>
              <param-name>contextConfigLocation</param-name>
              <param-value>
      			<!-- REMOVED classpath:applicationContext-business.xml -->
                  /WEB-INF/applicationContext-security.xml
              </param-value>
          </context-param>
      
          <context-param>
              <param-name>log4jConfigLocation</param-name>
              <param-value>/WEB-INF/classes/log4j.properties</param-value>
          </context-param>
      
          <context-param>
              <param-name>webAppRootKey</param-name>
              <param-value>tutorial.root</param-value>
          </context-param>
      
      	<!-- END INSERT FOR SPRING SECURITY -->
      
    2. Under the many <context-param /> blocks and before the <filter /> blocks (around line 64 in my stock CF9 web.xml), insert:
      	<!-- INSERTED FOR SPRING SECURITY -->
      
          <filter>
              <filter-name>springSecurityFilterChain</filter-name>
              <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
          </filter>
      
          <filter-mapping>
            <filter-name>springSecurityFilterChain</filter-name>
            <url-pattern>/*</url-pattern>
          </filter-mapping>
      
      	<!-- END INSERT FOR SPRING SECURITY -->
      
    3. Under the <filter-mapping /> blocks and before the <listener /> blocks (around line 167 in my stock CF9 web.xml), insert:
      	<!-- INSERTED FOR SPRING SECURITY -->
      
          <listener>
              <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
          </listener>
      
          <listener>
            <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
          </listener>
      
          <listener>
              <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
          </listener>
      
      	<!-- END INSERT FOR SPRING SECURITY -->
      
  8. Now, we have to adjust ColdFusion’s logging configuration so that Spring Security’s configuration and libraries are favored.
    1. Rename the file:
      <cfapp>/WEB-INF/cfusion/lib/commons-logging-1.1.1.jar
      to:
      <cfapp>/WEB-INF/cfusion/lib/commons-logging-1.1.1.jar.bak
    2. Rename the file:
      <cfapp>/WEB-INF/cfusion/lib/commons-logging-api-1.1.1.jar
      to:
      <cfapp>/WEB-INF/cfusion/lib/commons-logging-api-1.1.1.jar.bak
    3. Rename the file:
      <cfapp>/WEB-INF/cfform/jars/commons-logging.jar
      to:
      <cfapp>/WEB-INF/cfform/jars/commons-logging.jar.bak
    4. Rename the file:
      <cfapp>/WEB-INF/cfform/jars/commons-logging.properties
      to:
      <cfapp>/WEB-INF/cfform/jars/commons-logging.properties.bak
    5. Create the file:
      <cfapp>/WEB-INF/classes/commons-logging.properties
      , and insert the following into it:

      	org.apache.commons.logging.LogFactory=org.apache.commons.logging.impl.SLF4JLogFactory
      	org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger
      
  9. Extract the file security.tld from the META-INF directory of the file
    <cfapp>/WEB-INF/lib/spring-security-taglibs-3.0.5.RELEASE.jar
    and put it into the
    <cfapp>/WEB-INF/lib
  10. Edit the file:
    <cf-app>/WEB-INF/applicationContext-security.xml
    and comment out the <session-management /> block (around line 35), like so:

    	<!--
    	<session-management invalid-session-url="/timeout.jsp">
    		<concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
    	</session-management>
    	-->
    
  11. That should be all of the server-side configuration you need to make Spring Security work with ColdFusion. When you startup your app server, you should see a lot of Spring Security related output in your console, ending with:

    Root WebApplicationContext: initialization completed in  ms

    Since you can use JSP Tag Libraries in ColdFusion templates or CFCs, you can import Spring Security’s taglib and then easily restrict access to certain content or code using Spring Security’s access expressions. Here’s an example CFM file.

    <cfimport taglib="/WEB-INF/lib/security.tld" prefix="security">
    <html>
    <head>
    	<title>Spring Security on ColdFusion tester</title>
    </head>
    <body>
    	<h1>Spring Security on ColdFusion Test Application</h1>
    	<cfinclude template="/include/nav.cfm" />
    
    	<security:authorize access="isAuthenticated()">
    	<p>You can see this because you are authenticated.</p>
    	</security:authorize>
    
    	<security:authorize access="hasRole('ROLE_SUPERVISOR')">
    	<p>You can see this because you have supervisor permission.</p>
    	</security:authorize>
    
    </body>
    </html>
    

    That’s just the beginning — but a pretty strong beginning that opens up a whole new world of enterprise-class security.

Asynchronicity

December 21, 2010 by

“Daddy grips the wheel and stares alone into the distance.
He knows that something somewhere has to break” – The Police

I recently attended SpringOne 2GX and had a great time.  The folks behind Spring, Groovy, and Grails are fantastic.  Go find a NFJS event and be dazzled.  During one session I learned about RabbitMQ, a recent acquisition of SpringSource.  This is an impressive project done in only 12,000 lines of code!

I’m greatly intrigued by a message queuing system.  My only experience is as a gateway to a mainframe system.  Not exactly a keen architectural strategy as much as “that’s how you gotta do it.”  So I’ve seen something there, but have struggled to find a good use.

But I feel like I’ve found something!  We have many applications that have a common need to interface with an external system via SOAP.  This is an expensive operation and is currently handled synchronously.  Ah HA! Toss it behind a queue and make it asynchronous and regain some performance.  This call doesn’t need to have a response so the application doesn’t have to wait for the return!

Now throw in other ideas like an enterprise language-agnostic logging system, and step that up a bit with a destination for critical errors  to be stored for investigation and triage.  I think I now have a trifecta of ideas, and enough critical mass to justify revving up a new service!

What are your thoughts and experiences with asynchronicity?

Making Coldfusion sensitive to your (JSON) case

December 20, 2010 by

I inadvertently discovered that, contrary to popular belief and my own past experiences, ColdFusion can honor your variables’ case when using the built-in SerializeJSON.

First, the simple approach, which fails to produce most obvious results.

<cfscript>
 map = {};
 map.someNumber = 4;
 map.someString = "Hello JSON";
</cfscript>
<cfoutput>
 #SerializeJSON( map )#
<cfoutput>

This produces the following results. Notice that the keys (properties in JavaScript parlance) are UPPERCASED as though the serializer were shouting at you.

{"SOMENUMBER":4.0,"SOMESTRING":"Hello JSON"}

This becomes a problem when you deserialize the JSON in a case-sensitive context (i.e. JavaScript in a browser). It turns out this has little to do with the serialization and more to do with how ColdFusion creates struct keys from your (case-insensitive) code. We can help ColdFusion “do the right thing” by being more explicit with our keys.

Instead of creating a struct with variable names (which ColdFusion treats as case-insensitive), we’ll create struct keys with strings (which maintain their case.)

<cfscript>
 map = {};
 map[ "someNumber" ] = 4;
 map[ "someString" ] = "Hello JSON";
</cfscript>
<cfoutput>
 #SerializeJSON( map )#
</cfoutput>

This results in the following:

{"someNumber":4.0,"someString":"Hello JSON"}

Now we have no surprises when we consume this JSON in a browser. Our JavaScript object literals can use the same keys our CFML struct literals did.