Yes. It’s 1:26 am, and I’m working on stuff. Really, I’d like to be in bed. Asleep. And I’d like to stay there for three days.
But alas, instead, if you are having problems with dropdown JavaScript menus appearing BEHIND a Flash object, try adding this to the parameters you’re passing to the Flash object:
wmode="transparent"
Or if you’re using SWFObject, you can do something like this instead:
var so = new SWFObject("crappy.swf", "crappy_swf", "100%", "100%", "9", "#ffffff");
so.addParam("wmode", "transparent");
so.write("flash");
Maybe that will save you some headaches. It saved me some.
UPDATE
Apparently it might be better to use
wmode="opaque"
Apparently it’s less CPU intensive, and it seems to do the same job (that’s how it worked for me, anyway). I believe the differences are as follows:
Opaque makes Flash behave like any other page element, allowing you to easily float content over it using JavaScript and DHTML.
Transparent makes the page background underneath the Flash video appear through any transparent areas of the Flash video.
Just wanted to throw up a post saying that I got my Buffalo WHR-G125 flashed with version 1.17-ND of the Tomato Firmware. The whole tftp bit was necessary, but it turns out it’s not nearly as scary as I thought it might be.
The filename for the firmware I flashed was Tomato_1_17_ND.7z. You’ll wanna make sure you get the “ND” version (New Drivers) if you’re flashing a WHR-G125.
A couple weeks ago I ran into some horrible issues with Oracle and activerecord-jdbc. Inserts were failing with an “invalid column index” error.
It turns out this was reported as JRUBY-2018 and resolved, but there wasn’t a release of activerecord-jdbc that contained the fix.
Being impatient like I am, I grabbed the head from svn and built it myself. So if you ever find you need to build yourself an activerecord-jdbc gem from subversion, here you go:
First make sure you have hoe installed.
jruby -S gem install hoe
Grab the source from svn.
svn co http://jruby-extras.rubyforge.org/svn/trunk/activerecord-jdbc
Build the .gem
jruby -S rake packageInstall the generated .gem file.
jruby -S gem install activerecord-jdbc-adapter-[version].gemMAKE SURE YOU UNINSTALL YOUR PREVIOUS VERSION
The chances that you’ll have to do this are very slim. Nick Sieger is usually super-on-top of making sure things are up and working the way they should be, but just in case.
Joel Spolsky recently made some comments about TripIt, which I immediately tested, and was blown away.
This would have been infinitely useful during my past 2 years of globe-trotting.
If you travel a lot (at all?) and are tired of making up stupid itineraries in Word or Notepad or whatever, then this web app is for you.
$ du -shdanbookpro:~ daniel$ du -sh
53G .Very good then. Carry on.
Update
If you’re looking for a real good time, give this a try (thanks Nick):du -chs ~/*This will give you a list of each file/directory and the amount of disk space used by each. In my case something like this:
danbookpro:~ daniel$ du -chs ~/*
58M /Users/daniel/Bin
853M /Users/daniel/Desktop
1.3G /Users/daniel/Documents
1.1M /Users/daniel/Droplets
10G /Users/daniel/Library
25M /Users/daniel/Movies
7.2G /Users/daniel/Music
26G /Users/daniel/Pictures
1.5G /Users/daniel/Public
112K /Users/daniel/Sites
6.2G /Users/daniel/Work
53G total
danbookpro:~ daniel$
In the process of setting up my new dev machine, I decided I was going to try using MacPorts to install all of the dev-type-software instead of installing into /usr/local.
James Duncan Davidson has a great overview article (that needs no further explaining from myself), titled Sandboxing Rails With MacPorts. Another similar article can be found here.
My problem is that I work on a lot of projects that use ImageMagick / RMagick, and that’s not discussed here.
No worries, I’ll install ‘em and give it a go:
sudo port intall ImageMagick
sudo gem install rmagickCRAP! I don’t know what happens for you, but ImageMagick installs perfectly for me, and then RMagick craps out and dies something like this:
/opt/local/lib/ruby/gems/1.8/gems/rmagick-1.15.9/./lib/rvg/misc.rb:321:in `get_type_metrics':
unable to read font `(null)' (Magick::ImageMagickError)
from /opt/local/lib/ruby/gems/1.8/gems/rmagick-1.15.9/./lib/rvg/misc.rb:321:in `render'
from /opt/local/lib/ruby/gems/1.8/gems/rmagick-1.15.9/./lib/rvg/misc.rb:696:in `text'Now, for the solution I am going to give all credit to Jakob Skjerning, because I found the solution on his site after doing some Googling.
Do this instead:
sudo port install ImageMagick
sudo port install rb-rmagickDone. Works. Thank goodness.
I went out and picked up a new MacBook Pro yesterday, after the display issue on my wife’s iMac got so bad that finally the machine has become unusable. We’re gonna do a little swap – she’ll take my MacBook, I get the MBP, and the iMac is going to get thrown off a bridge or something.
What I wanted to comment about here is Apple’s Migration Assistant – which absolutely and undisputedly rocks my little world.
After pondering the long hours I was in for getting all my apps reinstalled, settings, passwords, serial numbers for apps, bla bla bla up and copied and running onto the new Mac – Nick pointed me to the Migration Assistant (which I’m not sure I even really knew about) and off I went. Plugged in my male-to-male FireWire cable into both machines, and booted the MacBook into Target Disk Mode (hold down ‘T’ while powering up until the FireWire symbol displays on the screen). The Migration Assistant asked me what users I wanted, if I wanted the Applications as well, and blammo. I went into the hot tub for a while, and when I got back I had my user, files, documents, library, settings, applications und alles.
So far there are only two apps that didn’t come over seamlessly, and those would be Parallels and Mozy (which, if you haven’t tried, is the best backup software I’ve ever laid my hands on), both of which I needed to reinstall, but after a bit of fiddling are working fine again. All told this thing saved me hours, and I’m sure I’ll use it again on my next Mac purchase.
A few days ago I ran a sudo gem update and unwittingly got a Capistrano 2.0.0 upgrade that broke my ability to deploy a bunch of existing Rails apps.
cap deploy
the task `deploy' does not existHmm. That sucks. Nick to the rescue. Here’s the culprit:
gem list | egrep -v "^( |$)"
...
...
capistrano (2.0.0, 1.4.1, 1.4.0)
...
...Needed to uninstall all the Capistrano gem versions, and install the last working one (apparently 2.0.0 is not backwards compatible with 1.4.1 – which I didn’t know until today).
Here we go:
sudo gem uninstall capistrano -v 2.0.0
sudo gem uninstall capistrano -v 1.4.1
sudo gem uninstall capistrano -v 1.4.0Say Yes when it asks you to uninstall the cap and capify binaries.
Now let’s install 1.4.1 again:
sudo gem install capistrano -v 1.4.1Yay! It works! Time to fix those deploy scripts… when I have time.
I wrote this article for IBM developerWorks a while back, but never ended up blogging about it. So at any rate, here it is: Ruby on Rails and XML – for better or for worse.
It’s been a long time since the last time I installed and used Ubuntu, but with another shiny newish version out, 6.10 or whatever it is, I wanted to give it another go. Of course, I’m afraid of hard disk crashes (as should you be), so the first thing I do is set up a software RAID. I’ll go with a RAID-1 (Mirror) so we’re protected in the event that one of the disks decides to up and die.
The last time I did this was for Ubuntu 5.10 (don’t ask me what nifty nickname that version had) – but it looks like a few things (not many) have changed. In 6.10 (AKA Edgy Eft) the Disks Manager is gone, but you can still use the Device Manager to figure out what disks you want to use to create your RAID. I still have two of these 160GB SATA Seagate drives that I’ll use for the sake of this example. Here’s a screen shot of the Device Manager, I’ve browsed to the first of the disks I’m planning on using, and you can see that it’s /dev/sda (screenshot, top right).
This screenshot also shows that my drives contain the Backup volume – I’m nuking this volume to create this RAID.
Now we open up the terminal, and get going. My drives are /dev/sda and /dev/sdb, so the first step is to use cfdisk to partition them:
daniel@ubuntu:~$ sudo cfdisk /dev/sda
daniel@ubuntu:~$ sudo cfdisk /dev/sdb
Running cfdisk opens a cursor based application that you need to use to create the partitions. I deleted all existing partitions, and then created a Primary partition that took up the entire disk. Then I set the Type to FD which is Linux Raid Autodetect.
Next we load the RAID module for RAID-1 (Mirror):
daniel@ubuntu:~$ sudo modprobe raid1After this, I opened up Device Manager again to see what the partitions had been called that we created on our disks. One of my partitions is /dev/sda1 and the other is /dev/sdb2. You can check out the screen shot below to see what I was looking at:
You can also notice from this screen that the Backup volume has indeed been nuked, and now we simply have Volume (linux_raid_member).
The next thing I want to do is run mdadm, but in my install of Ubuntu 6.10 it doesn’t exist, so we’ll install it:
daniel@ubuntu:~$ sudo apt-get install mdadmThat will spit out a bunch of stuff and eventually you should get the message:
* Starting RAID monitoring service mdadm —monitor [ ok ]Alright, now let’s run mdadm to create the RAID:
daniel@ubuntu:~$ sudo mdadm —create
/dev/md0 —level=1 —raid-devices=2 /dev/sda1 /dev/sdb1For me, I was prompted to confirm that I wanted to continue to create the array, because it looked like my disks were already a part of an array. I just pressed ‘y’ and carried on.
At this point, the RAID is being constructed, it’s not yet completed, even though you’ve been dumped back to the terminal. We can view the progress of the resyncing like so:
daniel@ubuntu:~$ sudo cat /proc/mdstat
Personalities : [raid1]md0 : active raid1 sdb1[1] sda1[0]
156288256 blocks [2/2] [UU]
[>....................] resync = 2.4%
(3886336/156288256) finish=52.6min speed=48201K/secunused devices: <none>
daniel@ubuntu:~$
So in 52.6 minutes we should be good to go. Now is your queue to grab me a Caramel Macchiato from Starbucks…Triple Grande, please.
Once the RAID is finished doing the resync, we need to create a file system on that bad boy. I’m going to use ext3, but you can go ahead and use whatever strikes your fancy.
daniel@ubuntu:~$ sudo mkfs.ext3 /dev/md0And voila! Once that’s finished, we should have a nice shiny file system that’s all RAIDified. Before we can actually do anything with it, we first need to mount it. I’m going to mount mine at /backup, but again, you can mount it however or wherever you see fit.
daniel@ubuntu:~$ sudo mkdir /backup
daniel@ubuntu:~$ sudo mount /dev/md0 /backup
Now with any luck, we should have 160GB of RAID goodness mounted at /backup, let’s check to see what we’ve got:
daniel@ubuntu:~$ df -k /dev/md0I would love to paste the result of the above command here, but the stupid terminal is not copying my selected text to the clipboard, but trust me when I say it tells us we have a nice ~160GB file system mounted at /backup.
Since we don’t want to have to remount the file system every time we reboot, we can add an entry to /etc/fstab to get it to mount at boot. As I’ve mentioned before, I’m not a Linux ninja by any stretch of the imagination, but if you read the man page for fstab and take a look at what’s in your current file, I’m confident you’ll easily be able to get it to mount the way you’d like. For me, I basically copied the line from my boot disk and changed /dev/hdc to /dev/md0 and also changed the last column (pass) from 1 to 2.
/dev/md0 /backup ext3 defaults,errors=remount-ro 0 2There you are, a newly updated entry on how to set up a nice software RAID in Edgy Eft (Ubuntu 6.10). Enjoy.
If we ever meet, I will buy you a beer, or wine, or whatever you want.
You are forever in my gratitude for how much time you save me thanks to this and this.
For the uninformed: If you need to install Ruby/Rails/Mongrel/RMagick/etc. on Mac OS X, and you don’t want to have to figure it out yourself, or think, then follow the above links.
Coding in Ruby is like using a Mac. If you’re not used to it, you spend quite some time looking for an obtuse way to do something, only to come to a “one line of code” solution about 2 hours later.
For me, I wanted to deserialize a YAML serialized ActiveRecord::Base subclass. Looking at the YAMLrdoc, it appeared that I could register a custom type via YAML::add_domain_type – but I wanted to Google around a bit just to see if anyone had already solved this <ahem>YAML deserialization problem</ahem>, to find me some sample code.
I learned nothing via Google, so I turned to the handy rails console (may it live forever) for a quick test, and I ended up with something like this:
monkey:~/Work/[client]/trunk daniel$ ruby script/console
Loading development_daniel environment.
>>
>> class BlaTest
>> attr_accessor :bla
>> end
=> nil
>> b = BlaTest.new
=> #<BlaTest:0x3718164>
>> b.bla = "Yay Test"
=> "Yay Test"
>> c = YAML::load( b.to_yaml )
=> #<BlaTest:0x37138bc @bla="Yay Test">
>> c.class
=> BlaTest
>> c.bla
=> "Yay Test"
So basically, we’ve created a new class with a single property, instantiated an instance of the class, set the property, and then we’ve called YAML::load for the YAML representation of our created instance. The result of YAML::load we’ve assigned to c.
To my surprise (astonishment?), I didn’t even need to register my custom type at all. As you can see, the resulting instance c is of type BlaClass with the appropriate value for the bla property.
One line of code. Beautiful.
I found this new (to me) Ruby tidbit in a comment on a two year old blog post here.
Basically, in Ruby, you can initialize a new Hash so that any time you reference a given value, keyed by a given key, if that value is previously nil, it assigns a default value.
In “gooder” English, it basically just lets you assign a “default” value for items in a Hash.
Why is this useful? Well, let’s say for example that you are iterating over some array, building up a hash as you go. Maybe the key you are using for the hash is derived from a certain property of each of the objects in your array.
We have an ArrayList of Product objects. Product has a “getCategory()” method, and we want to build up a HashMap whereby the key is the product category, and the value is an ArrayList of all Products that fall into a given category.
Map<String,List<Product>> map = new HashMap<String, List<Product>>();
for (Product product : products){
if ( map.get( product.getCategory() ) == null ){
map.put( product.getCategory(), new ArrayList<Product>() );
}
map.get( product.getCategory() ).add( product );
}
I still can’t get over how downright ugly Java code looks now if you want to get it to compile without warnings, thanks to generics. Just. Yuck.
We have an Array of Product objects. Product has an attr_accessor for category. We want to build up a Hash object in the same manner as we did for the Java example above.
map = Hash.new { |h,k| h[k] = [] }
products.each { |product| map[product.category] << product }You’ll note that I don’t have to do any check for null (or nil) because the initializer passed to Hash basically says “Any time someone grabs something from the hash, if it’s null, initialize it with a new Array”.
As odd as it sounds, when you’re playing bachelor for the weekend while your wifey is chillaxing in Indonesia, you find a lot of strange things to do to amuse yourself.
I’ve talked before about a neat little piece that someone discovered over on the Strongspace forums about getting Subversion repositories working over there. I’ve been using this method a lot lately, and typing all the commands gets tedious. The long and the short of it is that you need to create the repository locally first, and then copy it up to your Strongspace account before you can do the checkout over svn+ssh.
As I was writing this little piece, I figured I might as well also say something about how I really love the Vibrant Ink TextMate theme that I originally discovered while reading Chu Yeow’s blog

Quite nice I think. And droplets you ask? Well, I was going through the NLMA (Neat Little Mac Apps podcast) history – and came across Photodrop – which looks incredibly useful. That triggered in my brain some memory that Transmit was actually supposed to do droplets in the latest version, and sure enough it does. So now I have a nice little Transmit droplet that lets me upload files (like this ruby app and the image above) with simple drag and drop onto this droplet mini-app thinger.
As for this ruby Strongspace Subversion app, you can grab it here
Usage is dead easy:
ruby svn.rb [strongspace_username] [repository_name]
You’ll be prompted with your password a couple times. Make sure you’re aware of what this app actually does before you run it – or you could find yourself short some files!
Just found a piece of gold on the Strongspace forums with a little tip on how to use your Strongspace storage for svn+ssh subversion access.
A quick test and I’ve got two new subversion repositories up and running beautifully. Pretty excited about this.
I’ve been using FastMail for email for quite some time now (4 years?). The service is always up, has IMAP access, is fast, and has loads of great features.
I was having a bit of trouble getting the IMAP stuff set up to work properly with Mail.app until I found a couple nice little articles to help get it set up correctly.
MacDevCenter has one here along with one that I found later on the FastMail wiki.
At any rate, it all works now, and exactly the way one would want and expect. If you haven’t tried FastMail and you’re looking for a great email provider, try them out, give them some money, you won’t regret it.
Disclaimer – I’m not affiliated with FastMail in any way whatsoever, and don’t get any kickbacks from recommending them.
Since the layout that I found and used for this TextPattern install seemed a bit (ok, a lot) flaky, I finally managed to find some time to dig up a different 3 column CSS layout, and mod it up a bit.
Things feel a little bit more like I’d like them to at this point, but the fonts look like absolute crap in Internet Explorer. Also IE doesn’t seem to deal with really long lines of pre-formatted text as well as Firefox does (no surprise, really).
Also managed to finally get some stats up and running. I used to use AWStats a long time ago, but now I’m using it again. Found a great tutorial on how to get AWStats set up on TextDrive here. Sometimes it’s nice to just follow a tutorial, instead of having to think for yourself, especially when you’re really sleepy.
Take a peak in this file:
/etc/ssh/sshd_config
and change the port number to whatever seems reasonable to you (and probably a port that’s not currently in use is a good idea).
After that, restart sshd:
/etc/init.d/ssh restart
You should now be able to log in using the new port number.
Note: There is an updated version of this article for Ubuntu 6.10 here
Wanting to finally put these stupid SATA disks to good use, I managed to get them thrown into a RAID-1 configuration on my happy Ubuntu install.
Just thought I’d share how I did it, and the resources I used. Standard disclaimer applies: If you follow these instructions, and you lose all your data, or the world explodes, or the sky starts falling, or you die, I’m not liable.
Here are the resources I used.
Go to Disks Manager to figure out the Devices that you want to actually make into a RAID, for me that was /dev/sda and /dev/sdb. These are 2×160GB Seagate SATA disks attached to a Promise FastTrak 378 controller on an Asus A8V Deluxe motherboard.
So now you need to create the partitions that you want to use as a RAID.
daniel@ubuntu:~$ sudo cfdisk /dev/sda
daniel@ubuntu:~$ sudo cfdisk /dev/sdb
I made mine Primary Partitions (not sure if this is good, bad, or if it matters at all), and you NEED to make the filesystems of type Linux Raid Autodetect (FD).
After that, i loaded the RAID module for RAID-1 (Mirror) because that’s the type of RAID I wanted to build:
daniel@ubuntu:~$ sudo modprobe raid1
After this, I restarted the Disks Manager to see what the partitions had been called on my disks. I selected the disk on the left, and took a look at the partition tab on the right, noticing that one of my disk partitions was /dev/sda1 and the other was /dev/sdb1.
Now we can run mdadm:
daniel@ubuntu:~$ sudo mdadm —create /dev/md0 —level=1 —raid-devices=2 /dev/sda1 /dev/sdb1
Now let’s take a look at the status of the disks as they are rebuilding the RAID:
daniel@ubuntu:~$ sudo cat /proc/mdstat
Personalities : [raid1]
md0 : active raid1 sdb1[1] sda1[0]
156288256 blocks [2/2] [UU]
[>....................] resync = 0.9% (1459904/156288256) finish=54.7min speed=47093K/sec
unused devices:
daniel@ubuntu:~$
So, 54.7 minutes left for the disks to finish the sync [start twiddling thumbs].
You can get some information about the partition by going like so:
daniel@ubuntu:~$ sudo mdadm —misc —detail /dev/md0
So, once it finished, let’s make a file system. I’m going to use ext3, but you go ahead and use whatever you like, so we go:
daniel@ubuntu:~$ sudo mkfs.ext3 /dev/md0
And once it finished, we should (technically) have a nice pretty file system. But now we have to mount it. I want to mount mine in a /backup directory, because I’m going to be using this RAID for backups.
So here we go:
daniel@ubuntu:~$ sudo mkdir /backup
daniel@ubuntu:~$ sudo mount /dev/md0 /backup
Now, technically, we should have nearly 160GB of yummy RAID1 love available to us in the /backup directory. Let’s run df and see what it tells us:
daniel@ubuntu:/backup$ df -k
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/hda2 35064712 5173932 28109576 16% /
tmpfs 1026508 0 1026508 0% /dev/shm
tmpfs 1026508 13536 1012972 2% /lib/modules/2.6.12-10-amd64-generic/volatile
/dev/sdc1 199093056 136388704 62704352 69% /media/EXTERNAL
/dev/md0 153834788 131228 145889148 1% /backup
Excellent, /dev/md0 is mounted at /backup, and we’ve got lots of backup space.
In order to get this thing to mount each time we boot, we’ll want to put it into our /etc/fstab file. Let’s do that now.
I added a line like this to my /etc/fstab:
/dev/md0 /backup ext3 defaults,errors=remount-ro 0 2
I’m not a super-linux-ninja, but I was able to figure out what I wanted to do here by reading the man page for fstab, and by looking at the other entries in the file. So run “man fstab” and then you can edit the fstab file (by using something like “sudo vi /etc/fstab” once you’re feeling like you’re comfortable with what to add there).
Ok, that’s going to be the last entry for a while, I’m heading to New Zealand tomorrow, and won’t be back for three weeks. I also haven’t rebooted my machine yet to see if that /etc/fstab change worked, so lets hope I didn’t mess something up.
Also maybe called OpenSessionInView, or more specifically: “that hibernate stuff so that lazy loading doesn’t die in your views when you’re using Spring”, or a bunch of other things.
I’ve jumped headlong back into the Java world and am mucking with Java 5 annotations at at long last, only because I really wanted to play with Hibernate Annotations. I think that the only reason I’ve stayed away from Hibernate for so long (as in, years) is because of the arrogance of certain Hibernate / JBossian types (names not need be mentioned, you know who I’m talking about). But alas, I’ve come to the point where I don’t really care about their arrogance anymore, I just want to be more productive. I could try the TopLink community edition associated with the GlassFish project instead, but that’ll have to wait.
But back to the whole point of this post. I was having a pain in the neck of a time dealing with getting my Hibernate objects to Lazy Load in views and unit tests – because using the HibernateTemplate in Spring (depending on how you set up your transactions, etc.) basically closes the Hibernate session before your view or your unit tests get a chance to access and analyze the data, leaving you with nothing but big fat Lazy Loading Exceptions.
What you want to do if you’re having these kinds of problems is take a look at org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor (or there is a Filter alternative that you can toss in your web.xml).
This should get you started at least:
<bean id="openSessionInView" class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
<property name="sessionFactory"><ref bean="sessionFactory"/></property>
</bean>
Then you need to tell your URL handler mapping to be intercepted:
<bean id="urlMappings" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref bean="openSessionInView"/>
</list>
</property>
<property name="mappings">
<props>
<prop key="/public/**/*">publicController</prop>
<prop key="/login">loginController</prop>
...
</props>
</property>
</bean>
Now – there is a different strategy for getting the session to remain open in unit tests (I’m using TestNG, but maybe you’re using JUnit, either way it doesn’t matter). I was able to find a great blog entry courtesy of Karl Baum about how to get that set up here.
It’s been a really long time since I’ve blogged anything, I’ve been so busy working, coding and doing, um, ‘stuff’. Hopefully this is the start of my foray back into more regular entries.
...and (why || how) they can be your friend.
Useless Preamble
As previously mentioned, I’ve been using Spring a whole lot in the ‘latest project’, and in addition am using Acegi Security to provide authentication and authorization services.
Scenario
Now that all that is out of the way, I, like most other people who write webapps, wanted a way to display the currently logged in users information on the screen for them. You know, username, maybe a “Hello, $USERNAME! Thanks for coming out!” type nonsense. So in Acegi, the code used to get the currently logged in user looks like this:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Once you’ve got the Authentication object, you need to get the Principal, which will at last be castable into whatever your User object implementation happens to be. So basically for me, I had a getUser() method that looks like this:
protected User getUser(){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if ( auth != null && auth.getPrincipal() instanceof User ){
return (User) auth.getPrincipal();
} else {
return null;
}
The Problem
Now, this is all well and good, and in Spring, chances are you want to add this code to a Controller implementation somewhere. But which Controller? I’ve got a ton of them. I thought of extracting it to some superclass, but based on the Spring controller hierarchy, whereby sometimes you might extend AbstractController, or SimpleFormController, or implement the Controller interface directly, it didn’t seem like this was going to cut the cake, so to speak. We don’t have multiple inheritance in Java (duh!), so I couldn’t do that, and I certainly didn’t feel like putting the code in some separate bean that I would have to inject into every single one of my controllers. Oh what to do?
The Solution
Enter interceptors. Oh how we love thee (when they’re the appropriate tool for the job).
So, an interceptor basically does exactly what it says it does. It “intercepts” method calls to an object. For all the details, go read something about AOP, this is just going to be an example in somewhat plain English.
In my particular case, I wanted to “intercept” all calls to the handleRequest(...) methods of the org.springframework.web.servlet.mvc.Controller interface (which all Spring controllers implement). If I could do that, then any time a method was intercepted, I could simply call my neat little getUser() method and dump the user into the current HttpServletRequest as an attribute. Spot on!1
So um, how the heck to we actually do it? Ok, first of all, let’s write the actual interceptor class. This is the class that we want to be automagically called any time the handleRequest(...) method of a Controller is executed (I’ve gotten rid of comments and imports).
public class AddUserToModelInterceptor implements MethodInterceptor { public Object invoke( MethodInvocation methodInvocation ) throws Throwable {
ModelAndView model = (ModelAndView) methodInvocation.proceed();
if ( model != null && getUser() != null ){
model.addObject( "user", getUser() );
}
return model;
} protected User getUser(){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if ( auth != null && auth.getPrincipal() instanceof User ){
return (User) auth.getPrincipal();
} else {
return null;
}
}
}
Note that the fully qualified class name (in case you’re curious) of MethodInterceptor is org.aopalliance.intercept.MethodInterceptor
Great, so we have an interceptor, now what? Lets go define some beans!
<bean id="addUserToModelInterceptor"
class="com.example.AddUserToModelInterceptor"/> <bean id="controllerClassFilter" class="com.example.ControllerClassFilter"/> <bean id="controllerPointCutAdvisor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
<property name="classFilter" ref="controllerClassFilter"/>
<property name="advice" ref="addUserToModelInterceptor"/>
<property name="mappedName" value="handleRequest"/>
</bean> <bean id="autoProxyCreator" class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>
Alright, the first bean definition is just an instance of the AddUserToModelInterceptor that we just finished showing in the above example. After that, we have a class filter (which we’ll look at in a second). Thirdly there is the bean controllerPointCutAdvisors. Joins, Pointcuts and Advice are fancy AOP terminology that you should really read about, but I won’t cover here. We pass three simple properties to this bean. The first is just the class filter, the second is the “Advice” which is a reference to our interceptor bean, and lastly, we pass “mappedName” – which is simply the method name that we would like to intercept calls to, in our case, “handleRequest”. Lastly, we define a proxy creator bean, which in this case is an instance of Spring’s DefaultAdvisorAutoProxyCreator. Basically, what this bean does is once all of the bean definitions have been loaded, it scours all loaded beans applying advice to matching pointcuts. In our case, it will apply our “addUserToModelInterceptor” advice to all bean instances that match our “classFilter” that have the method name “handleRequest”.
Briefly, the class filter is just a dead simple interface that Spring offers. In essence, we don’t want our advice to be applied to any classes that ‘accidentally’ define a method called handleRequest. We only want the advice applied to classes that implement Spring’s Controller interface. So here is what our ControllerClassFilter looks like:
public class ControllerClassFilter implements ClassFilter {
public boolean matches( Class aClass ) {
return Controller.class.isAssignableFrom( aClass );
}
}
Fewf! Something easy to end off with!
I hope that this has managed to help shed a little light on how interceptors can be useful, and hopefully some of it actually made sense.
UPDATE: 1-Feb-2008 – This has changed as of Mac OS X 10.5 Leopard
For pre-Mac OS X 10.5, open a terminal and run:
sudo lookupd -flushcacheFor Mac OS X 10.5:
sudo dscacheutil -flushcacheThat should do it. You’ll need to type in your administrator password.
I have found the most fabulous set of free icons for use in web/desktop applications.
Check out this collection created and provided by Mark James.
This will let you know how to determine free disk space on a *nix box (Linux, FreeBSD, Mac OS X, Solaris, etc.) The man page for df says this:
df - report filesystem disk space usage
When I type df -k on one of my Linux machines, it tells me how much free space (in Kilobytes) I have on each of my mounted filesystems. Here is the output:
[daniel@localhost daniel]$ df -k
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/hda2 76541056 31788324 40864604 44% /
/dev/hda1 101089 9272 86598 10% /boot
none 188248 0 188248 0% /dev/shm
This tells me that I have about 56% free space on my main /dev/hda2 partition, which is mounted at /. This translates into roughly 40864604 Kilobytes, or 40GB.
Your output will vary depending on the number of filesystems you have, and where they are.
I ran into a fabulous (and open source!) database tool the other day for interacting with various databases via JDBC.
It’s called Execute Query and the web site is here: http://executequery.org/.
It has a ton of features I’m sure I haven’t even used yet, but it reverse engineered my schema into an ERD for me, which made me smile.
This page will describe a couple of ways in which you can get Linux (specifically RedHat) to start certain applications (any application really) at boot time. Some of the common apps that people may want to configure to start automatically are Apache, MySQL, Tomcat, JBoss, Zope, xinetd, etc. Most versions of RedHat should come with this handy tool called chkconfig
You may find that it is not in your path by default (eg: on my linux box, chkconfig is in /sbin, but I did not have /sbin in my path by default. So I added /sbin to my path first, in order to gain access to chkconfig easily on the commandline, without having to type /sbin/chkconfig. The first thing you might want to try is something like the following:
netfs 0:off 1:off 2:off 3:on 4:on 5:on 6:off
network 0:off 1:off 2:on 3:on 4:on 5:on 6:off
iptables 0:off 1:off 2:on 3:on 4:on 5:on 6:off
sshd 0:off 1:off 2:on 3:on 4:on 5:on 6:off
nfs 0:off 1:off 2:off 3:off 4:off 5:off 6:off
sendmail 0:off 1:off 2:on 3:on 4:on 5:on 6:off
crond 0:off 1:off 2:on 3:on 4:on 5:on 6:off
httpd 0:off 1:off 2:off 3:off 4:off 5:off 6:off
xinetd 0:off 1:off 2:off 3:on 4:on 5:on 6:off
xinetd based services:
chargen-udp: off
rsync: off
chargen: off
daytime-udp: off
daytime: off
echo-udp: off
echo: off
services: off
servers: off
time-udp: off
time: off
cups-lpd: off
sgi_fam: on
ktalk: off
cvspserver: on
The output above is a partial output of the command
chkconfig —listWhat the output is basically telling you is which apps that have startup scripts in /etc/init.d are configured to be in an on/off state at which run level. In my example, I want to configure my linux machine to have httpd (which is Apache) start on boot, so the command I want to type to get this to happen is:
chkconfig httpd onThis will ensure that my service httpd from /etc/init.d is in a started state at (by default) run levels 2, 3, 4, and 5 (for all intents and purposes, these run levels indicate a “normal” machine state, describing what all of the run levels mean is much beyond the scope of this document). Now if I reboot my machine, I will notice that httpd was started automatically at boot.
How to write a Trust Manager that will allow you to make an HttpsURLConnection to any host, without requiring valid certs, etc.
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType ) {
}
public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType ) {
}
}
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance( "SSL" );
sc.init( null, trustAllCerts, new java.security.SecureRandom() );
HttpsURLConnection.setDefaultSSLSocketFactory( sc.getSocketFactory() );
}
catch ( Exception e ) {
//We can not recover from this exception.
e.printStackTrace();
}
HttpsURLConnection urlc = (HttpsURLConnection) new URL( url ).openConnection();
This page describes how to create a symbolic link in linux
For example, I want to create a symbolic link in my /usr/local directory called mysql that symbolically links to /usr/local/mysql-standard-4.0.18-pc-linux-i686
Here is what I do:
shell> cd /usr/local
shell> ln -s /usr/local/mysql-standard-4.0.18-pc-linux-i686 mysql
shell> ls -l mysql
shell> lrwxrwxrwx 1 mysql mysql 46 May 30 13:59 mysql -> /usr/local/mysql-standard-4.0.18-pc-linux-i686
The last two commands are just to demonstrate that the link was created. Do a directory listing with ls -l mysql and then you can see that now there is a link mysql that points to the directory /usr/local/mysql-standard-4.0.18-pc-linux-i686.
Recently I’ve been working on a web-app that uses some .png files with transparency in them. Internet Explorer totally screws up the transparency and renders it grey.
There’s a great fix for it here:
http://homepage.ntlworld.com/bobosola/pnghowto.htm
Rumor has it this will go away in Internet Explorer 7, which will be released with Vista probably in 2027 later this year.
The absolute best ftp and sftp client I have found for Windows (and again, by “best” – I usually mean that it’s free, and works fantastic) is FileZilla.
FileZilla is an open source project over at SourceForge, and you can take a look at it here:
On most (any?) Linux or Unix system, you should be able to check which operating system it is running by using:
[root@humandoing root]# uname
Linux
This of course can be great when used in a shell script and you need to perform different actions depending on the operating system that the script is being executed on.
Or if you want the kernel version
[root@humandoing root]# uname -r
2.4.27rimu1-3um
If you want to get really crazy:
[root@humandoing root]# uname -a
Linux humandoing.net 2.4.27rimu1-3um #1 Thu Sep 9 02:48:08 UTC 2004 i686 i686 i386 GNU/Linux