Categories
Uncategorized

Removing CAPS LOCK on OS X

This has been bugging me for a while, but I’ve just gotten around to doing anything about it. I hate the caps lock key. I never use it and I’m always triggering it by accident. Thankfully, it’s fairly simple to disable. First go into System Preferences and choose “Keyboard & Mouse”.

System Preferences: Keyboard & Mouse

Now on the “Keyboard” tab, there’s a button in the bottom left that I’d managed to miss entirely, “modifier keys”:

System Preferences: Keyboard

This pops up a little dialog pane that lets you choose the behaviour of the caps lock key.

System Preferences: Modifier Keys

I chose control, as it’s not entirely useless. In fact, on my macbook, it’s a damned sight more useful than the hobbled control key which has been displaced by an “Fn” button.

Categories
Uncategorized

NetBeans 6.5

Today NetBeans 6.5 got released. Congratulations, guys! I’m primarily an Eclipse user1, but I keep hearing about NetBeans through the Java Posse and heck, I even subscribe to the NetBeans podcast to try and keep an eye on what’s up. Every time a new release comes out, I give it a whirl.

So this time, now I’m looking at 6.5. And it’s really nice on a lot of fronts. Most of the improvements in 6.5 aren’t directly relevant to me — they’re related to scripting languages I don’t use. What I’m particularly interested in is the core Java SE support. And NetBeans is really very good. It’s just not quite as good as Eclipse. Or (more likely) I can’t figure out a way to make it do what I want.

There are a couple of things I do all the time in Eclipse. First, ⌘-T, which shows type hierarchies. But that’s putting it simply. If you pop it over a class, it shows the subtype hierarchy. Press it again and it shows the supertype hierarchy. What’s neat is that if you do it over a method, it greys out those classes that don’t have an implementation of that method.

⌘-T in Eclipse

But what makes it particularly useful is that it doesn’t pop up a proper window, just a little floater (I have no idea what it’s really meant to be called). As soon as you click somewhere, it disappears. This makes it incredibly fast to navigate code.

As far as I can see, the closest that NetBeans has is “File Hierarchy” on ^⇧F12. But this pops up a big old clunky dialog box.

That’s one more thing about NetBeans — the key bindings are weird. And I speak as a long time emacs user. Now I’ll learn them (as it’s annoying to carry my customisations everywhere). But they conflict badly with a lot of Mac keyboards, because they’re extremely function-key heavy, and the mac likes to take over the function keys for itself.

The other Eclipse feature I use the whole damn time is “assign to local variable”. Yes, you can curse me for being damned lazy. But, I want to be able to type new PhoneImpl("01273", "123456"); then hit a key and get it assigned to a variable. In Eclipse, that’s ⌘-T L. I couldn’t find a way to do it in NetBeans. The compiler knows what type it’s going to be. Why should I have to remember? Otherwise I’d be back in Emacs.

There are a couple of missing refactorings I use a lot: “Extract to local variable” and “inline local variable”. Both are easily replaced with cut’n’paste 90% of the time.

One particular feature that Eclipse and NetBeans both share is terrible defaults for exceptions. Here’s Eclipse’s default:

  try {
      new URI("http://example.com/");
  } catch (URISyntaxException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
  }

And here’s NetBeans.

  try {
      new URI("http://example.com/");
  } catch (URISyntaxException ex) {
      Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
  }

Both of these are fundamentally broken, and going to catch out dozens of unwitting programmers who don’t know any better. Yes, you can change the defaults, but most people don’t.

Anyway I don’t want you to think that I’m totally down on NetBeans. The new release maintains what I first saw in 6.1: a very fast, full featured IDE. It’s dead easy to get going, and there is loads of documentation. I find the project view to be much more useful and better organised than the eclipse view of the same.

NetBeans Project View

I suspect that most of the problems I’ve been having are down to the fact I’ve been using Eclipse for 3 years, and NetBeans for a few hours at best.

One thing I did like very much is that there’s builtin Maven support. I downloaded the Java SE installation2, went to the plugins window and selected “maven”. About a minute later I had a working installation. And I can create new projects with archetypes really simply. And it’s dead simple to add new libraries as needed (I’m guessing it uses the nexus indexer to look stuff up). The only missing thing is the dependency viewer, but I can always run dependency:tree and dependency:analyze manually.

Funnily enough, where I think NetBeans really wins is the dynamic languages support. I’ve been following Tor’s blog for a little while and I’m incredibly impressed with what has been achieved in the Ruby support. For developing Ruby code, I head straight for NetBeans. Most of the issues I’ve outlined above are really specific to statically typed languages. For dynamic languages like Ruby (and now PHP and Python), what NetBeans gives you is a big win over the standard text editor.

Heck, the JavaScript support is pretty decent too. The first thing I did today was open up jslint4java and jump into fulljslint.java. That’s some pretty scary code. But NetBeans handled it with no issues at all. And it even pointed out a warning that’s easy to overlook (a duplicate hash key).

So, the big question is — am I going to use NetBeans? For any Ruby stuff, there’s no question. For Java stuff, I’m going to give it a try. After spending enough time with it to write this, I’ve already figured out enough stuff to use it a bit more successfully.

1 Apart from Emacs, Vim and TextMate. ☺

2 I didn’t like the look of the Java EE version — I don’t really need 3 application servers bundled, do I?

Categories
Uncategorized

The best subversion client

The best subversion client I’ve used to date? git. It’s so script-friendly! This morning somebody asked me for a complete history of a project in CSV format. Using my nicely cloned repository, it was a simple matter of giving the correct format to git log.

  ⇒ git log --pretty='format:%h,%ai,%an,%s' | head -5
  f584913,2008-09-26 21:58:02 +0000,Dominic Mitchell,Pull out a base class for OptionInstances.
  803a32a,2008-09-26 21:57:38 +0000,Dominic Mitchell,Organise imports.
  1cb0132,2008-09-26 21:57:17 +0000,Dominic Mitchell,Switch from a Set of OptionInstance to a Map from Option to OptionInstance.
  a0c1efd,2008-09-26 21:56:56 +0000,Dominic Mitchell,Introduce OptionInstance.
  a211ae3,2008-09-26 21:55:59 +0000,Dominic Mitchell,Use standard idiom for emptying a Set

I love how git embodies the Unix toolkit approach.

Categories
Uncategorized

Time Zones, done better

A few days ago, I signed up to HuffDuffer (love the logo, BTW). However, once I’d registered, my profile page said Huffduffing since November 1st, 2008. Which was a little weird, as when I did this it was October 31st.

So I filed a bug report and Jeremy quickly spotted the problem: the server was running in Australia, so was using an Australian timezone. That’s about 11 hours ahead, which would put my signup in to the next day. His fix was simple: force huffduffer to use GMT (see datetime configuration in the PHP manual). This isn’t a 100% correct solution, but it’s definitely the least bad approach.

But it set me wondering: can we do better? The key thing is that something somewhere has to know what time zone you’re in. That thing happens to be your browser. JavaScript Date objects have a getTimezoneOffset() method which return the minutes difference between you and GMT.

  alert(new Date().getTimezoneOffset());

Right now, when I try it, it returns zero because I’m in british winter time, which just happens to be the same as GMT. If I was in Australia, it’d return 660 (11 hours).

So we know the time on the server, and we know how far away from GMT we are. So how do we get JavaScript to format the date correctly?

Obviously, the first step is to pass the time to the browser as GMT. The normal approach to this is to use the Unix time format (number of seconds since midnight 1970). In PHP, look at gmmktime(). Perl uses gmtime(). And JavaScript has a constructor which takes milliseconds.

  new Date(0); // Thu Jan 01 1970 01:00:00 GMT+0100 (BST)

Ooops. That’s an hour ahead. But it’s actually misleading: the internal representation (the milliseconds we are passing in) doesn’t have a timezone, it’s only applied when you turn it into a human readable form. You can demonstrate this by using rhino on the command line to fool Javascript in to thinking it’s in different time zones1.

First, let’s try it in my time zone:

  % java -jar js.jar -e "print(new Date(0))"
  Thu Jan 01 1970 00:00:00 GMT-0000 (GMT)

Now let’s pretend we’re in Australia:

  % TZ=Australia/Melbourne java -jar js.jar -e 'print(new Date(0))'
  Thu Jan 01 1970 10:00:00 GMT+1000 (EST)

Which makes things really easy for us: get the server to pass the unix time, create a new Date object from it and then rewrite the textual object based on the contents.

So, if you start out with some HTML like this:

  

At the third stroke, it will be 2008-10-31 14:00:00.

Note that we include the default (GMT) time in order to degrade gracefully.

Then you can use some JavaScript like this to automatically adjust it to the time zone of the browser.

    $("span.datetime").each(function () {
        if (!this.hasAttribute('unixtime')) {
            return;
        }
        var unixtime = this.getAttribute('unixtime');
        // Convert seconds to milliseconds
        var date = new Date(unixtime * 1000);
        $(this).text(format_date(date));
    });

I’m relying on jquery a little bit in there in order to focus on the problem, not the DOM. You can download the full source if needed (tzadjust.zip).

This is such a teeny-tiny thing overall, but it’s part of the polish to help make your site great.

1 You can change the timezone of any command this way in Unix. I have alias nydate='TZ=America/New_York date' in my shell profile so I can quickly see what the time in New York is.

Categories
Uncategorized

Jasypt++

Once again, jasypt (“Java Simplified Encryption”) makes me smile.

Java comes with a comprehensive set of encryption utilities: JCE. I had to do some decryption the other day and ended up with this code.

public class Decryptor {
    private static final String ALGORITHM = "PBEWithMD5AndDES";

    private final Base64 base64 = new Base64();
    private final Cipher cipher;

    public Decryptor(String password) {
        try {
            cipher = Cipher.getInstance(ALGORITHM);

            // Just generate an empty salt as we don't want to use one.
            byte[] salt = new byte[cipher.getBlockSize()];
            Arrays.fill(salt, (byte) 0);

            // Set up the cipher.
            PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
            SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
            SecretKey key = factory.generateSecret(pbeKeySpec);
            PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, 1000);
            cipher.init(Cipher.DECRYPT_MODE, key, parameterSpec);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchPaddingException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeySpecException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (InvalidAlgorithmParameterException e) {
            throw new RuntimeException(e);
        }
    }

    public String decrypt(String cipherText) {
        try {
            // cipherText is base64, so will always be ASCII.
            byte[] cipherBytes = base64.decode(cipherText.getBytes("US-ASCII"));
            byte[] decryptedMessage = cipher.doFinal(cipherBytes);
            // Assume encrypted text is UTF-8.
            return new String(decryptedMessage, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IllegalBlockSizeException e) {
            throw new RuntimeException(e);
        } catch (BadPaddingException e) {
            throw new RuntimeException(e);
        }
    }
}

This does also include conversion from base64 using Apache commons-codec, but it’s a lot of code. Even though I’ve tried to make things simpler (attempting to not use a salt [and I am aware of the consequences]), there’s still a lot of baggage.

Which is why I’m so grateful to have found jasypt. Essentially, all the above code is wrapped up for you in a nice little API. The above comes down to:

  SimplePBEConfig config = new SimplePBEConfig();
  config.setPassword(password);
  config.setSaltGenerator(new ZeroSaltGenerator());
  StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
  encryptor.decrypt(cipherText);

So why did I have to write the code in the first place? Well, we need to get a 3rd party to implement it, and I can’t enforce dependencies upon them. But the difference in the amount of code is shocking.