Avdi Grim has begun a thought-provoking series surrounding the idea of sustainable software development – specifically targeting Ruby as an example.
With some of the recent discussion surrounding “monkey patching” in Ruby, I think that the timing seems about right, for some serious thought to be given about the long-term effects of maintaining Ruby-based code-bases, should prolific “monkey patching” continue to be used haphazardly by many of the libraries, plugins, gems and other code that makes (sometimes critical?) modifications to the underlying core language classes.
Nick Sieger has crafted a thoughtful response to Avdi, which includes the quote:
[Monkey patching is] still a basic part of the Ruby programming culture, like it or not.
While Nick is totally correct, and Ruby does give you the power to shoot, maim and otherwise pillage and murder yourself in a bazillion different ways – that doesn’t take away the fact that it is still an incredibly powerful, elegant and syntactically beautiful programming language.
At the risk of sounding like a trite broken record (for the 485,000 time), I think that once again it boils down to using and choosing the right tools for the job. If the consequences of Ruby’s dynamism (among whatever other consequences) outweigh the positive benefits that a Ruby solution provides – then choose a different tool.
You can complain about the verbosity of a language like Java all you want (heck, I know I do at times), but I come back to Java sometimes after working with Ruby for a few months, and I’m all of a sudden thankful for strict, static typing, always knowing what I’m gonna get.
What continues to irk me are the folks who seem completely hell-bent that their way is the only One True Way™.
I was in a job interview the other day (company name shall be kept confidential) at a place that does extensive software development in many languages including Java, C, C++, Perl and PHP (at the very least). Near the end of the interview, we were discussing different languages, and I mentioned how sometimes I really enjoy the dynamic typing facet of Ruby, as opposed to the statically typed facet of Java. At this statement, one of the interviewers piped up to tell me that the fact that I enjoyed dynamic typing at times was “the most brain-dead thing” he’d ever heard anyone say.
It seems so strange to me, to be on the receiving end of an insult like that, coming from a company that performs extensive development in PHP (which is not only dynamically typed, but also weakly typed, as opposed to Ruby which is strictly typed).
At any rate, all of that comes to some sort of summary that everyone should already know by now:
I’ve just been doing some reading up on some various Java documentation – and came across the list of new language features in Java 5 (yeah – I know, we’re at 6 now).
At any rate, I came across this gem about static imports, copied verbatim from Sun’s online documentation:
So when should you use static import? Very sparingly! Only use it when you’d otherwise be tempted to declare local copies of constants, or to abuse inheritance (the Constant Interface Antipattern). In other words, use it when you require frequent access to static members from one or two classes.
So that begs the question, why bother adding static imports as a core language feature at all, if the documentation basically says (in PR Speak to English, with apologies to John Gruber):
We have wicked awesome new language features including static imports! But FOR THE LOVE OF ALL THINGS GOOD, DON’T USE STATIC IMPORTS, IT WILL TURN YOUR CODE TO SLOPPY CRAP!
Thanks, Sun. Next time, add some language features that we have your blessing to actually utilize.
Note to Sun: I like closures, and if you build them into the language, try doing it using syntax that doesn’t suck (I’m looking at you, generics).
A new article I wrote recently has been published at last. Since even looking at JSF makes me want to die, I think this little AjaxTags is a nice Ajax library for those of you still using JSP.
I’ve started on Wicket this week, which thus far is really impressing me.
Sorry I haven’t been blogging, I’ve been way to freakin’ busy.
I’ve been really busy, so it’s taken some sweet time, but at long last I’ve been able to upgrade to SimpleLog 2.0 which Garrett Murray managed to push out the door. I redid all the colors, background, some of the fonts and the overall width of the content in my ongoing mantra to ‘mess with CSS’ more. The latest version also offers content and comment feeds, among other things, like a prettier admin interface.
DreamHost is continuing to aggravate me in new and special ways, none the least of which was deploying the new version of this site. I’ve got some space over at SliceHost that Nick has so nicely set up for us, but alas, I haven’t had the time or energy to get things moved over there yet.
I suppose deploying the new site isn’t a bad way to spend the afternoon after sampling a few pints with James at Pump Room Asia.
I’ve been meaning to comment as well about the relatively new and beautiful support for Ruby / Rails in both IntelliJ IDEA (screencasts here and here) and NetBeans (screencasts here and here, but I haven’t had time. It’ll have to wait for another day.
Don’t get me wrong, I love TextMate, but it ain’t no IDE.
Last night proved to be a great time, with a Java meetup here in Singapore once again brilliantly organized by Christopher Marsh-Bourdon. The event was held at Brewerkz and us Java geeks were on the receiving end of a great overview of the many facets of the Spring Framework from one Ben Alex, of Interface 21 and Acegi/Spring Security fame.
It was great to have a chance to chat with Ben a bit about Spring, open source companies, and different approaches that companies seem to take in building APIs and interacting with developers and users of said APIs.
My first experience with Spring was on a somewhat large personal project that I started working on about a year ago. Code that hasn’t seen the light of day in the real world, but has been a phenomenal learning experience as far as working with Spring, Acegi, as well as the Spring HibernateTemplate support, Spring MVC – and a bunch of other stuff that I just can’t remember.
If any of you out there have the attitude that I used to have, which was something like:
“Why do I need to use Spring, it’s just another framework, and all it does is manage other frameworks.”
I highly recommend that you download Spring right now, and use it. You won’t be disappointed. It’s worth the download and integration for the IoC and Dependency Injection alone.
My favorite podcast, hands down, is the JavaPosse. There’s nothing quite like sitting back with a cup of coffee and listening to Dick, Carl, Tor and Joe yammer about Java (and/or technology in general) – especially if they’ve been drinking.
A few months ago they launched a Google group in which I am an avid lurker, and very occasional poster. One of the more recent threads was surrounding third-party iPhone application development. I think that the winning comment in this thread was this one:
The simple question here is therefore “Is this phone of any further interest to the Java community/Java Posse?”.
He might as well have said:
If it’s in the world, and it has nothing to do with Java, we shouldn’t discuss it or have any interest, and said object might as well be used as toilet paper. If it’s not Java, it can kiss my bleeeeep.
Forget the fact that it’s a phone – and I could care less if it had anything to do with Java whatsoever. I don’t care if I can write or run 3rd party apps on my phone, or my iPod. I want a phone so I can (go figure) phone people. Of course, all the other iPhone stuff is awesome as well (calendaring, sms, voice mail, iPod, photos, videos, etc.). Why, for the love of all things good, would a community write off said device claiming it no longer deserves “any further interest [from] the Java community” – because it doesn’t have Java on it? Maybe the Java community should stop having interest in hard disks, or RAM, or digital cameras, or iPods for that matter – simply because they don’t allow for third party Java application development on them. I’m making a pact right now. I’m not going to purchase another stick of RAM until I can plug it into a USB port on my laptop, and write a third-party Java app for it that makes it light up, or sing, or something.
Unfortunately, this is the collective wisdom that (stereotypically speaking) the Java community now tends to bring to the table. Let us look at a fictitious (but not fictitious at the same time) example:
Jim: Hey there, have you played with Ruby at all?
Greg: Are you crazy, that stupid thing?
Jim: It’s got some really powerful syntax, and I can’t believe how fast you can prototype apps in it.
Greg: Nothing more than a stupid toy language.
Jim: Have you used it? Have you seen how powerful some of the APIs are?
Greg: No. I’m a Java developer.
Jim: Why don’t you just take a look, see what you think?
Greg: No. If it’s not Java, it’s stupid and useless.
Right. Thanks.
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”.
Apparently at least a few people think that the iPhone will be a hit:

| Ticker | Company | Phone |
| AAPL | Apple | iPhone |
| RIMM | Research In Motion | Blackberry |
| PALM | Palm | Treo |
I first saw a screenshot similar to this on a Flickr photo stream belonging to Dave Shea (a fellow Vancouverite, I might add). I jumped over to Google Finance to take a peak myself, and the picture says a thousand words. It’ll be interesting to see how things progress over the next 6 months, but in the mean-time I’ll admit I’m salivating over the pretty iPhone.
Lots of questions seem to be going around, especially with regards to Java support, and I found an interesting quote from Mr. Jobs hisself, surrounding Java support for the iPhone:
Java’s not worth building in. Nobody uses Java anymore. It’s this big heavyweight ball and chain.
-Steve Jobs
I found this quote via David Pogue’s Blog which was in turn a quote from an interview that John Markoff had with His Steveness.
I’m not sure if Steve has jumped on the Rails bandwagon (yah, that was supposed to be funny), or if he just has a hate on for Java in general. It’s also worth noting that up to date Java support on Mac OS X seems to be a bit lacking as well. In order to run Java 5, Mac OS X 10.4 was required, and now it’s sounding like in order to run Java 6, a mandatory update to Leopard (Mac OS X 10.5) will be required as well.
Charles Oliver Nutter (AKA “one of the JRuby guys” if you listen to the JavaPosse podcast) put up a post that has me salivating about the deployment of Rails apps on Java app servers that will be a part of our inevitable future.
Currently, my biggest gripe about Rails is deployment. To put it bluntly, Lighttpd is unstable, and Mongrel has a few weird quirks, FastCGI is dated, buggy and well, not very fast.
So at any rate, the very idea of deploying a Rails app on a “real” application server is very cool.
About a week ago I received an email from PayPal which contained the first donation I’ve ever received for JarIndexer. I immediately sent a thank you note to the donator, and received this response:
I really support people like you who share tools and things like that for the rest of us, especially when it removes pain. So, thanks for JarIndexer. It saved me so much time and it was very easy to use. So, keep up the good work.
That means a lot. JarIndexer is a super simple program, gets about 30-50 downloads a month, and was very easy to write, but I’m extremely pleased that it has been of use to someone, and managed to relieve a bit of pain.
I suppose this provides me an opportunity to say my thinks as well, to the open source community in general – and to all the folks out there who provide great software that make our lives easier as developers. I suppose I could specifically mention people like James Duncan Davidson (ANT), Rod Johnson (Spring), Gavin King (Hibernate), Yukihiro Matsumoto (Ruby), David Heinemeier Hansson (Rails), Thomas Fuchs (Scriptaculous) and Sam Stephenson (Prototype). In my day-to-day coding life, when thinking of people who freely give their software to the community – these guys have made me the happiest I’ve been in years.
It looks like it’s official. Sun has officially released Java under the GPL license. Wow that surprises me. The first place I noticed the news was on Charles Oliver Nutter’s blog (AKA – one of “the JRuby guys”).
I don’t have the same optimism as many do, that there will be a minimal amount of forking of the language. I think that every Tom, Dick and Jane is going to have a different idea of what Java ought to do, and the forking will begin like mad.
I might eat my hat yet, but until then, it’s gonna be chicken curry.
It is quite possible that Kathy Sierra writes what is the best blog on the Internet. The relentless shift from developer-focus to user-focus is something that is becoming more important pretty much on an hourly basis.
One thing that really got me thinking about this was the recent video of 37 Signals (Jason and David) that’s been making the rounds, you know, the Mac one.
Albeit the video is a bit on the glam side (maybe I’m only saying that because I don’t have their stunning good looks?). At any rate, one of the things that David says in the video is:
“We’re trying to affect both our peers in the industry and also customers out there, just raise their level of expectation…”
This seems to go along with the whole theme of Creating Passionate Users – but why I bring it up here is for the following reason (Warning: Gross Stereotype Ahead):
People who write apps in Ruby on Rails care about user experience. People who write Java apps don’t give a rip.
-me
(Ok – I’ll make an exception for JIRA). I can feel the flames flying this way already, but this has been more often than not what I have observed in the past year or so. It’s not that Rails provides some sort of Magickal Code that isn’t possible to provide in a Java-based application – it’s that Rails makes it easy for the developer to integrate those features. I mean, forgive me if you like Java Server Faces – but the last time I looked at that code – I ended up in a psychiatric ward for a month before deciding that I’ll just stick with JSP, thanks.
After our Singapore Ruby meetup a couple weeks back, I was chilling with Herry and Choon Keat over a bite to eat – and the primary things that we seemed to be constantly coming back to when discussing Java vs. Ruby were along the lines of:
Don’t get me wrong, I’m not saying that Ruby is now the de facto standard language and “you will be assimilated” all borg-style, I’m just saying that if it’s a feasible language to use for a given project, and Java is equally feasible – I’ll take Ruby in a heartbeat.
It’s about time that the end-users of software start raising their expectations, and time for developers to deliver software to their end-users that doesn’t suck. And one of the major driving forces of this in the past 12 months has been Ruby on Rails, along with some great JavaScript libraries like Prototype and Script.aculo.us. So thanks, guys.
I’ve been enjoying doing this for the sake of examining syntactical differences and standard API differences between Java and Ruby.
Let’s say that we have an object, call it Department. One of the methods in Department is an accessor to retrieve a department id.
Now let us say that we would like to iterate through an array of Department objects and build up a String along the way (we’ll call the String ‘out’), creating a comma-separated list of ID’s (this is a real-world problem, something that you probably have done a ton of times in one form or another).
In Java, I would probably do something like this:
Department[] deptArray = //Create an array with departments
StringBuffer out = new StringBuffer();
//Yes, I know I could use the 'new' for loop, but I need an index
for ( int index = 0; index < deptArray.length; index++ ){
Department d = deptArray[index];
out.append( d.getId() );
if ( index != deptArray.length - 1 ){
out.append( "," );
}
}
Of course, you might write a nice utility class, that can take an arbitrary array of some type of object, and you could pass into your utility method the name of the method you wish to execute on whatever the instance type your array contains, and you could end up with a method definition something like this:
public static String getDelimitedStringFromObjArray(
String methodName, String delimiter, Object[] objs );
But really, that’s not the point. The point is: “How much code does it take me to do Task N using the bare bones APIs provided to me by the language.”
In Ruby:
dept_array = //Create an array with departments
out = dept_array.collect! {|department| department.id }.join(',')
I’ve never even looked at JRuby. Ever.
So I started to look at it yesterday, after I read somewhere that Spring 2.0 is going to have some built-in dynamic language support. Now, don’t get me wrong, I really like Spring. Six months ago you couldn’t catch me saying enough good things about Spring and how wonderful IoC / dependency injection makes life. But I want to say for the record, that whoever thought it was a “good idea” to allow people to embed JRuby / Groovy code in Bean Definition Files (see here) should probably be kicked in the teeth. And if that’s how I feel about it, then I don’t even want to know what Allen Holub would have to say.
Mind you, he probably doesn’t like Spring at all anyways, since it’s all based on XML configuration – but you have to draw the line somewhere.
Friends don’t let friends start embedding chunks of code from random languages into XML files.
Admittedly, I’ve been spending a lot more time with Ruby these days then I have with Java. And in the meantime, it seems like everyone has started talking about this EE-JAY-BEE-THREE thing, and stuff like that.
Ok – well – admittedly, I’ve seen the new JPA stuff (Java Persistence API) and have used the Hibernate Annotations stuff on a few projects – and I read a ton of the EJB3 spec stuff since, at least when I was using Hibernate Annotations – the documentation was so abysmal that it forced me into the spec to figure out how to do some stuff.
At any rate, I’m a long time IntelliJ user, and frankly – every time I open up Eclipse I almost vomit. I tried it again today, and mostly, when it opens up, I stare at all the menus, and the way the whole thing seems like it was randomly assembled by a tornado, and after about 10 minutes, I shut the thing down and go make another cup of coffee.
Currently I’m downloading NetBeans to give that a try (not that I’m seriously considering switching IDE’s – it just seems to me that NetBeans and Eclipse are the two Java IDEs that get the most hype).
I’m a little dubious about whether NetBeans will be any good at all, especially when, on their Top 10 reasons to switch page, they can’t seem to come up with even one good reason. Let’s take a look at reason number nine for example:
9. It’s Cool
NetBeans is cool. You can add your favorite photo as a background using the substance plug-in. It also allows you to change the look and feel of the IDE completely.
Now, when did crap like “It’s Cool” – and the ability to set the background of your IDE to be your favorite photo of Auntie Margie become more important than stuff like “Increasing Developer Productivity”. Does anyone really care about the Netbeans Mobility Pack? Does anyone really care that the IDE has ANT support integrated? If it didn’t have ANT support integrated, no one who writes Java these days would probably even consider it to be a Java IDE. And how about actually being fast, instead of just claiming to be fast. And since when does “Best out-of-the-box experience” be a top-ten reason to switch – when every IDE can claim exactly the same thing. Why not get the developers to write the reasons to switch – and not the marketing team.
Do I sound like I’m ranting a lot these days? Sheesh.
I’ve jumped back into Ruby codin’ lately for a few personal projects and prototypes that I’ve been working on, and I just find, more and more – that one of the reasons why I love Ruby so much is that it really seems to have the developer in mind. Java seems very disinterested in the developer, and interested in, well, verbosity?
For example, I ran into a very simple situation where I have a Map (call it what you will, HashMap, Hashtable, Hash, whatever) that I needed to reverse – or invert. In essence, what I needed was a new Map whereby the keys became the values and the values became the keys.
Now, in Java (assuming I have the privilege of Java 5), I would do something like this:
HashMap inverse = new HashMap();
for ( Map.Entry me : existingMap.keySet() ){
inverse.put( me.getValue(), me.getKey() );
}
If I did not have the privilege of Java 5, it would look something like this:
HashMap inverse = new HashMap();
for ( Iterator i = existingMap.keySet().iterator(); i.hasNext(); ){
Map.Entry me = (Map.Entry) i.next();
inverse.put( me.getValue(), me.getKey() );
}
Let us contrast this with Ruby:
inverse = existingMap.invert
Now, excuse me while I got make a fresh cup of coffee with all the time I just saved.
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.
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.
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();