Disable Your Caps Lock Key

November 14th, 2008

If you are a fat-fingered programmer like me, and frequently hit the Caps Lock key when you mean to hit the Tab key, it’s helpful to just disable the Caps Lock key.
Does anyone actually use it intentionally?

For X11 (Linux and some Mac apps if you have X installed), add this to your .bashrc file (or equivalent for whatever shell you’re using):

xmodmap -e “remove lock = Caps_Lock”

For non-X11 Mac apps, try this.

For Windows, take a look here.

Qabili Pilau

November 1st, 2008

I found this middle-eastern (Afghani) recipe at
http://www.acrossboundaries.ca/ps_adult_skills_kitchen.html#qabilipilau

It’s apparently also known as Kabuli Palau, Qabili Palau, Kabuli Pulao….in essence, it’s a rice dish (Pilau) from Kabul.

It’s become a favorite of mine, so I thought I’d share it here:

cooking time: 1.5 hours, serves 4
Ingredients:
2 cups basmati rice
1/4 cup vegetable oil
1 1/2 pound lamb on the bone or 1 chicken, cut in 1-inch pieces
3 cups water
2 large carrots, cut into matchstick size pieces
1 cup raisins (golden sultanas are recommended)
1 teaspoon cumin
1 teaspoon cinnamon
1/4 teaspoon saffron (optional)
1 teaspoon salt
1 medium onion, diced
1 teaspoon white sugar

How to make Qabili Pilau:
1) On medium heat, brown the onions in oil, then add meat
and brown the meat slightly, stir constantly.

2) Add water, salt, cinnamon, and cumin.

3) Cover and simmer on low heat for about 1 hour.
Remove the meat from the juice, set juice aside

4) Saute carrots and sugar in oil until lightly browned,
then remove from oil. Lightly fry the raisins in oil.

5) Boil the meat juice, then add rice. Turn heat to low,
cover, and cook until the rice is tender (15-20 min.)

6) Mix everything together and place in a large oven-proof
bowl. Bake at 350 for half an hour to an hour

7) To serve, place on platter with the raisins and carrots
showing on top.

Apache / Tomcat Integration - Serving The Root Context

October 26th, 2008

About a year ago, I set up a web hosting reseller account with WestHost (http://westhost.com).
I’ve been pretty happy with them (this site is hosted there), but up until now, I haven’t pushed the limits much.

Today, I tried to set up a new virtual site with Tomcat serving the root context.
I’ve never tried to configure this before, but have become accustomed to either deploying my root application either as webapps/ROOT.war or deploying my expanded app in webapps/ROOT

I did this, and it didn’t work.
I did an on-line chat with WestHost tech support, and the nice person at the other end of the chat informed me that what I wanted to do was not possible. I thought about it for a moment, and decided that I’d be better off solving this on my own.

After a little “googling”, and some minor trial-and-error, I came up with a 4-step solution:
1. Put your java web application (expanded .war file) in /var/tomcat5/ROOT

2. Edit /etc/httpd/conf.d/jk.conf, and add the following:
#Root mounts
JkMount /* ajp13w
JkMount /servlet/* ajp13w

3.Edit /etc/http/conf/httpd.conf: find the line that begins with DirectoryIndex
It lists all of the allowable “start page” names. Add index.jsp to the front of the list.

4. Go to /var/www/html and rename index.html to something else, like index.html.orig
This is so that this index.html doesn’t override index.jsp in your app, if you’re using that.

5. Go to your control panel and restart the server.

Poor Pedagogy

October 17th, 2008

If you don’t like reading rants, stop reading now. This is definitely a rant.

I used to wonder where bad programmers get some of their idiotic ideas.
Some of them are just too involved or fly too much in the face of common-sense for the average code-monkey to come up with them on their own. Surely, someone is dispensing this cr*p as good advice.

Eventually, I started seeing the cr*p peddlers everywhere. Now I know.

The latest example that I saw was an article on TechRepublic, titled “10 JSP Tag Libraries No Programmer Should Be Without“.  It’s from 2007, but I just saw it today.

Several of the tag libraries that the article recommends are fine, but several are just bad ideas.

For instance, the article recommends the Mailer taglib from tha Jakarta-Taglib project.
It’s from Apache, so it must be good stuff, right?

Also recommended in the article is the JDBFforms taglib.

What’s wrong with these?

Well, the last time that I checked, JSPs were a display technology. You know, the “V” in MVC.
When did sending email and accessing a database become things that are proper to implement in the view tier?

Ok, so now I know where bad programmers get their “good” ideas. Places like TechRepublic and Apache, apparently.

Scripting Yakuake

August 22nd, 2008

Yakuake has become an integral part of my desktop over the years. It’s a drop-down terminal emulator, reminiscent of the old Quake console. It supports multiple tabs. When doing software development, this comes in very handy.

At the moment, I have it running with 4 tabs - one running tomcat with the app that I’m working on, with logging to the console, one with a CAS server, one running an ssh tunnel into the CVS server, and one with a shell for general-purpose use. All at the touch of the F-12 key. Great stuff.

This morning, I was feeling even more lazy than usual, and got to wondering whether I could script Yakuake to open those four tabs, and run the requisite commands in them, from a shell script.

As with most things in Linux, if you can imagine it, it’s probably possible, and if it’s truly useful, there’s a good chance that someone else has already done it.

It turns out that Yakuake supports DCOP, the KDE Desktop COmmunications Protocol (Yakuake is a KDE app, but I run it in GNOME, and it works fine).

With Yakuake’s DCOP interface, you can open new tabs, run commands in them, switch tabs, etc.
These, and some other commands are documented in a few places (including some references on the Yakuake home page), but many of the commands are not. To browse the full interface, you can use the ‘kdcop’ program.

Here’s some of the things that you can do with this:

* Add a new session (a new tab, with a new terminal):

     dcop yakuake DCOPInterface slotAddSession

* Change the caption on the tab of the current session:

  dcop yakuake DCOPInterface slotRenameSession \
   `dcop yakuake DCOPInterface selectedSession` "tomcat"

* Run a command in the current session:

dcop yakuake DCOPInterface slotRunCommandInSession \
  `dcop yakuake DCOPInterface selectedSession` "~/tomcat/bin/startup.sh"

* Select a specific tab:

dcop yakuake DCOPInterface slotSelectTabPosition 0

I understand that in the latest versions, Yakuake has switched over from DCOP to DBUS.
That’ll be another new adventure…..in the meantime, enjoy being lazy!

Spring Security Database Schema

August 19th, 2008

If your’e using JDBC Authentication with Spring Security, it’s pretty easy to find the database schema required for the “default” JdbcDaoImpl.

JdbcDaoImpl is pretty basic, though. It doesn’t support the concept of true role-based security.
It only has ‘users’ and ‘authorities’. Sure, you can call a role and ‘authority’, and manage all of your security based entirely on roles. But that’s pretty brittle. A bit too coarse-grained for my taste.

Spring Security does support permissions based on roles. In this situation, roles are known as ‘groups’, and permissions are ‘authorities’. This lets you have, say, a “Users” group with “read” permission for something, and an “Admin” group with “read” and “write” permissions. Then, if you later find that your roles are too lumpy, you can refactor your roles in the database, without touching your code. The trick is to do all security checks in the code based on permissions, not roles.

If you decide to go this route, it can be difficult to find the required database schema.
Of course, you can find it via trial-and-error (I did). To (hopefully) save others a little time, though, here it is (in MySQL dialect):

CREATE TABLE `users` (
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`enabled` tinyint(1) NOT NULL,
PRIMARY KEY  (`username`)
);

CREATE TABLE `groups` (
`id` int(11) NOT NULL default ‘0′,
`group_name` varchar(255) default NULL,
PRIMARY KEY  (`id`)
);

CREATE TABLE `group_members` (
`group_id` int(11) NOT NULL default ‘0′,
`username` varchar(255) default NULL,
PRIMARY KEY  (`group_id`, `username`)
);

CREATE TABLE `group_authorities` (
`group_id` int(11) NOT NULL default ‘0′,
`authority` varchar(255) NOT NULL default ”,
PRIMARY KEY  (`group_id`,`authority`)
) ;

Secure Login with Spring Security 2.0

August 18th, 2008

If you are reading this, then I’m sure that you know that with the latest release, Spring’s Acegi Security has been renamed  Spring Security.

Much has changed. Setting up Spring Security for most applications now involves a drastically reduced amount of configuration xml, mostly thanks to the <http auto-config=’true’> tag, which automatically sets up the most commonly used options.

Most of the examples that I was able to find on the web for custom form-login, even for Acegi, showed the login form posting the login credentials in the clear, via http. Not very secure….

The solution seemed pretty simple - add channel security for the login page, like so:

<intercept-url
pattern=”/login**”
access=”IS_AUTHENTICATED_ANONYMOUSLY”
requires-channel=”https”
/>

This did indeed make the login page switch to https. Unfortunately, it also made my login fail with a “Bad Credentials” message.

Many hours later, after trying all sorts of combinations, and combing the web for a clue, I determined that, not surprisingly, Spring Security was not broken, it was something that I had misconfigured.

Turns out that I had added a catch-all intercept-url, requiring http for anything not matching a url pattern that I had explicitly configured for https. The gotcha was that the login form posts to /j_spring_security_check - which was getting switched to http by the catch-all. Doh!

So, the solution was to explicitly configure /j_spring_security_check for https.

My resulting configuration is:

<http auto-config=’true’>
<form-login
login-page=”/login.jsp”
authentication-failure-url=”/login.jsp?login_error=1″
default-target-url=”/admin/user.htm”
/>

<port-mappings>
<port-mapping http=”8080″ https=”8443″/>
</port-mappings>

<intercept-url
pattern=”/login**”
access=”IS_AUTHENTICATED_ANONYMOUSLY”
requires-channel=”https”
/>

<intercept-url
pattern=”/j_spring_security_check”
access=”IS_AUTHENTICATED_ANONYMOUSLY”
requires-channel=”https”
/>

<intercept-url
pattern=”/admin/index.htm”
access=”ROLE_USER”
requires-channel=”https”
/>

<intercept-url
pattern=”/admin/user.htm”
access=”ROLE_USER”
requires-channel=”https”
/>

<intercept-url
pattern=”/admin/**”
access=”ROLE_ADMIN”
requires-channel=”https”
/>

<intercept-url
pattern=”/**”
access=”IS_AUTHENTICATED_ANONYMOUSLY”
requires-channel=”http”
/>

</http>

And now everything works properly. Doh! Indeed.

If you’ve read this far, I hope that this saves you a few hours.

Subversion 1.5.1 on Ubuntu 8.04 Hardy Heron

August 16th, 2008

I mostly use the excellent subclipse plug-in for Eclipse, and rarely use the command-line svn client.

I tried to use the command-line client today with a project that had been checked out of subversion using subclipse, and found that the latest version of the svn client that installs by default on Hardy (1.4.6) doesn’t work properly with those files. I got the message “This client is too old to work with working copy ‘.’; please get a newer Subversion client”

After some rummaging around the inter-web, I found these instructions for installing the latest svn (1.5.1) : http://www.cylindric.net/blog/2008/07/29/installing-subversion-15-on-ubuntu-804

It definitely solved the problem,  Thanks, whoever you are!

Some Java Annotations Considered Harmful

June 15th, 2008

In Java, annotations are currently all the rage.

Personally, I think that not all annotations are created equal. Some are quite useful, while others make no sense to me at all. It seems that annotations are a golden hammer, and everything is a nail lately.

Annotations such as those for JUnit make a lot of sense - like @Test - straightforward, useful, and no undue coupling - this is a JUnit annotation, being used in a JUnit test. The Junit test is, and always will be just that - a JUnit test. All is well with the world.

Consider persistence annotations, though, such as those for Hibernate and/or JPA.
To me, these are counter-productive. The whole idea behind Hibernate and JPA is to add persistence to POJOs - “Plain Old Java Objects”. But once you add persistence annotations to a POJO, it ceases to be a POJO!

There are actually two coupling issues here:

1. The POJO cannot be compiled without the library that provides the annotation. This is not an issue for a JUnit test, as it will only ever be used with JUnit. But why would I want to inextricably tie a POJO domain object to Hibernate or JPA? Suppose, for instance, that I want to use the POJO with GWT, or package it into a jar file, and give it to someone who wants to consume it from a web service. In the latter case, this would require the consumer to have the Hibernate/JPA jar files and their dependencies. In the former case…well, it’s just not possible.

2. With persistence annotations in a (formerly) POJO domain object, if I want to change some aspect of the database schema, like perhaps changing a table name or a column name, I would have to change and recompile the Java code as well. It seems to me that this is the definition of “tight coupling”, and a bad idea.

So, I prefer to steer clear of annotations like this, keep my Hibernate persistence details in hbm.xml files, and keep my POJOs as POJOs. Fortunately, even with Spring integration of Hibernate, this is easy to do.

Hierarchical SQL Queries and Hibernate

June 15th, 2008

As I mentioned in an earlier post, I’m working (slowly) on a web app for my municipality’s Office of Emergency Management. The app is meant to keep track of “first responders” - people who will respond in an emergency situation. This includes the local volunteer fire departments, rescue squad, OEM members, city public works employees, etc. This means that the app is going to have to keep track of hierarchies of people. For the sake of simplicity, let’s call this “departments” and “employees”, even though most folks are volunteers.

The interesting problem to solve here is hierarchical SQL queries. Let’s say someone has the role of Department Admin for the top-level “Fire Department”. Lambertville has several fire departments, which all ultimately are overseen by the city-wide Fire Chief. The Fire Chief may want to see the record of all of the Fire Department staff, city-wide. So, we’d need to be able to query the database for all “employees” in the “Fire Department” department, and all departments that are sub-departments of the “Fire Department” department.

If you search the web, you’ll find all sorts of schemes for solving this problem, including vendor-specific sql extensions in various databases, such as SQL Server’s “Common Table Expression” and Oracle’s “START WITH and CONNECT BY”. But, as usual, I’m looking for a vendor-neutral solution.

Several web sites promote the “adjacency model”, where each row stores a reference to it’s parent.
I found the sql queries required with this model to be more trouble than it’s worth.

I came up with an easier model, which I later discovered was thought of by other folks too. The folks at sqlteam.com call this a ‘lineage model’ - seems like a good name, so I’ll use that. I think that my approach goes a little further than theirs, so read on…

The basic idea is to store the entire lineage of each row, rather than just it’s parent id.
So, if we have a three-department hierarchy, A -> B -> C, with primary keys 1, 2, and 3 respectively, C’s ‘lineage’ is ‘1|2′. The sqlteam example uses this for sorting purposes, but it is also useful for selecting particular parts of the hierarchy. For example, if I want to see dept A and all of it’s sub-departments, I can use the following sql:

select * from dept where id = 1 or lineage like ‘%1%’;

If I want to see just direct sub-departments of dept A, I can use:

select * from dept where lineage = ‘1′;

The observant reader will notice that this extended use of the lineage model will only work properly with fixed-width keys. You wouldn’t want the ‘like ‘%1%’ where-clause above to match a row with, say, and id of ‘12′. But how to produce fixed-width keys?

I’m using Hibernate in this project, so the obvious answer was to write a new IdentityGenerator subclass. I wrote FixedWidthStringIdGenerator, based on Hibernate’s existing IncrementGenerator.

FixedWidthStringIdGenerator generates ids in the same way as IncrementGenerator, but then base-36 encodes the value (producing digits in the range [0-9][a-z]), and then left-pads the result with zeroes to produce a fixed-width string. When configured to produce ints, the width is 6 chars. Longs produce 13 chars.

This worked out so well that I submitted a patch to the Hibernate project. This is my first-ever contribution to an open-source project. Here’s hoping that they accept it.

Just in case the patch is not accepted, and you’re interested in using it, you can download it here.

Happy Hibernating!