I just spent the last hour banging my head on my desk trying to get any kind of date type (whether java.util.Date or a simple timestamp) from the current time and a timezone identifier (something along the lines of Etc/GMT+12). You'd think this is an easy task. Obviously the GregorianCalendar takes a timezone as a constructor argument, so it really should be.

It is until you've called getTime() on the calendar object and wonder why you're still getting your local time. And on further inspection you realize that GregorianCalendar doesn't even care about the timezone object you've just given it. Only setting it through setTimeZone() makes it recognize that you actually want it to use a different timezone for date and time calculation.

This should work now, right? Of course it should, but getTime() and getTimeMillis() still returns the local time and doesn't mind that you don't want it to. Only if you use a date formatter like SimpleDateFormat will Java remotely start to understand what you really want. But it stays awefully quiet about the fact that then you can't get a simple timestamp anymore.

There's an article on ONJava with more detail on this.

And there I thought timezone handling in Rails would be complicated.

Tags: java, links, rails, ruby

One thing that's nice about Rails is the separation of test, development and production environment right from the beginning. I'm currently working on a Java project with Spring and found myself using MySQL for most of the development and testing and Oracle in production. Using Hibernate that's not a big problem (most of the time that is, unless you're bitten in the ass by another weird Oracle JDBC driver bug), but I don't want to change all the properties for every deployment.

There's a neat trick to achieve a similar functionality using Spring. As you do in Rails you basically put all the properties that are different in every environments into separate files, e.g.

project-test.properties
project-development.properties
project-production.properties

First thing that comes to mind is the specification of the database connection properties and Hibernate specifics.

jdbc.url=jdbc:mysql://localhost/my_database_test
jdbc.user=scott
jdbc.password=tiger
jdbc.driver=com.mysql.jdbc.Driver
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

I also put in web service configurations so that I can use different configurations or even mock services during development.

Now let's have a look at the Spring configuration. The important part is the configuration of a PropertyPlaceHolderConfigurer. Basically, that's the class that is responsible for resolving the properties which I'll use in the XML configuration later on.

<bean id="propertyConfigurer" 
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="systemPropertiesMode" value="1"/>
  <property name="locations">
    <list>
      <value>classpath:project-production.properties</value>
      <value>classpath:project-development.properties</value>
      <value>classpath:project-test.properties</value>
    </list>
  </property>
  <property name="ignoreResourceNotFound" value="true"/>
</bean>

This will read read all the properties from the listed properties files. The rule is that the properties in the last file win, so development overwrites production, and test overwrites development. One thing to mention is the property ignoreResourceNotFound which defaults to false. That way the configurer throws an exception when he can't find one of the properties files. I set it to true so that I can just remove the test file for the development environment and the development file for the production environment.

You can put these files in your JAR file, or into WEB-INF/classes. My setup puts the project-test.properties into my test/ folder so that it's not even included in the deployment. For a production deployment I just remove the development file during the build and I'm good to go.

What you can now do in your configuration is this

<bean id="dataSource"
      class="org.apache.commons.dbcp.BasicDataSource"
      destroy-method="close">
  <property name="driverClassName" value="${jdbc.driver}"/>
  <property name="url" value="${jdbc.url}"/>
  <property name="username" value="${jdbc.user}"/>
  <property name="password" value="${jdbc.password}"/>
</bean>

<bean id="sessionFactory">
<bean id="sessionFactory"
      class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="dataSource" ref="dataSource"/>
  <property name="hibernateProperties">
    <props>
      <prop key="hibernate.dialect">${hibernate.dialect}</prop>
    </props>
  </property>
</bean>

These properties can also be used to configure bean references. For testing and development I use a mocked web service implementation which I can switch through the property

web.service=mockedWebService

If I have defined a bean with the id mockedWebService I can now safely use a property to reference it.

<bean id="someService"
      class="some.Class">
  <property name="webService" ref="${web.service}"/>
</bean>

You can even specify properties files based on system properties:

<bean id="propertyConfigurer" 
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="systemPropertiesMode" value="1"/>
  <property name="locations">
    <list>
      <value>classpath:project-${environment}.properties</value>
      <value>classpath:project-${user.name}</value>
    </list>
  </property>
  <property name="ignoreResourceNotFound" value="true"/>
</bean>

If you add the property environment to the startup command of whatever you're using you can specify the environment during startup, or use an approach based on the login user's name.

While not a perfect solution I found it to be a lot easier to work with than editing Spring configuration by hand or having a separate XML configuration for the different stages.

Tags: java

All I wanted was to store images in the database through Hibernate. It all look so easy. Add a byte array property, add it as a binary type to the Hibernate mapping and off you go. So far so good. I'm developing with MySQL where everything worked the way it's supposed to. Image data goes into the database and comes out when required, no problem.

Enter Oracle. The first fetching of data from the database worked like a charm, but the second brought up a nice ORA error. ORA-17027: Stream has already been closed. Good stuff. Digging through the result on Google it seems that I'm not the only one having this problem. The Hibernate gang is quick enough to point out that the error lies with the Oracle JDBC driver. The problem is that a the default type for byte arrays with the OracleDialect is long raw. When a query is fired with a stream column (e.g. long raw) in the field list it has to be read last, or else the stream will be closed once the next column is read.

One suggestion was to put the corresponding column to the end of the mapping file, but that didn't work at all for me. Another one was to use a different JDBC driver. All that didn't work for me, but there had to be a way.

According to Hanson Char the solution is to use a blob to store the byte array. Since you can't just set the type of the property to blob and be done with it, he offers a simple solution: add blob handling to your model. I tried it and it works. The thing I didn't like about it was to have all that stuff from the JDBC packages in my model, so I tried to put it into a UserType. It does work to a certain extent, but since you don't have direct access to the session in it I couldn't implement everything Hibernate's own BlobType does. Respecting the hibernate.jdbc.usestreamsfor_binary is probably the most important thing.

So I just derived a combination of Hanson's Code and Hibernate's BlobType wrapped it into a ByteBlobType. It uses most of the BlobType implementation and only wraps the conversion between byte array and blob.

Just before I was done I had a look what kinds of subclasses of UserType lurks around in my project. It didn't really surprise me, but of course Spring offers a type to do just that, but Spring-style. Doh! It's called BlobByteArrayType. Though it can be used as a normal Hibernate type, it needs an additional property set in your session factory provided by Spring's LocalSessionFactoryBean, a LobHandler. That's a no-brainer though and can be done quite easily:

 <bean id="sessionFactory"
      class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
   .....
   <property name="lobHandler" ref="defaultLobHandler"/>
 </bean>

 <bean id="defaultLobHandler" 
       class="org.springframework.jdbc.support.lob.DefaultLobHandler"
       lazy-init="true"/>

That should work for most databases, of course not with all versions of Oracle. For the latter you're better off using the OracleLobHandler. The default handler works with Oracle 10g to a certain extent which I can confirm, but apparently not all of it. If you're not using Spring, then the above ByteBlobType might be an option for you.

Tags: java, oracle

I'm currently working with a proprietary framework. Which is not bad per se. Compared to others I've worked with it's a nice framework to work with. It uses Spring heavily which is a plus and makes working with it quite flexible.

All that said there's one thing that bugs me about it, and that bugs me about Java in general. The overuse of final. Not for constants, mind you, but for methods and classes.

Why on earth would someone want to impose this restriction on developers? And by someone I don't especially mean the framework creator, but also the Java creators. Is it really worth it sacrificing flexibility and extensibility to ensure that nobody overwrites your methods or extends your classes to customize them? Do they really think that people are that stupid that they can't decide for themselves what to do with a framework? It's just beyond me. What are classes, inheritance and all that object-oriented mumbo jumbo for anyway.

If something is so important that it shouldn't be overwritten, then please, document it. Don't leave the developer asking why he has to go and reimplement everything himself just to have a certain part of your framework's functionality available to him.

Today's NetNewsWire tab sweep:

  • DataMapper - Competition for ActiveRecord - Not available at the moment, cached on the Googles.
    Looks like a nice alternative to ActiveRecord, especially for standalone environments without Rails. Being able to put queries, especially simpler ones, in Ruby code is quite appealing.

  • The Great Ruby Shoot-Out
    Antonio Cangiano compared the current Ruby implementations. JRuby, Ruby 1.9 and Rubinius look awesome, at least by the numbers.

  • Upcoming Changes to the JavaScript Language
    I'm still not sure if I'm gonna like what's coming. JavaScript is on the way to turning into a full-blown and statically typed object-oriented language, but with all its pros and cons. It looks a lot like C++, and if that's no a little bit scary, I don't know what is.

  • Google Chart API
    Now that's a really useful API. Put in your data via HTTP request and get back chart images. Awesome.

  • SVNMate
    A TextMate plugin to integrate Subversion, taking the integration further than the Subversion bundle.

  • Rak
    grep in Ruby, ignores .svn and CVS directories. Accepts regular expression in Ruby syntax, and can execute Ruby code on the results.

  • The Evolution of Java
    Right on.

On a side node, Rails 2.0 has been released. I recommend checking out the PeepCode book on Rails 2.0 to check what's new and what's old.

Update: Ryan Daigle (author of aforementioned book) also has a nice collection on a lot of the changes and new features in Rails 2.0.

For a current gig I had to set up a Java web project from scratch. The set-up isn't that unusual: * Spring 1.2 (yes, it's rather old, but the project uses a portlet framework which used to work with Spring 1.1, and I don't want to make the big jump just yet, the upgrade to Spring 1.2 went just fine though) * Hibernate 3.2 (hence the upgrade to Spring 1.2) * Tomcat 4.1.38 (again, the framework, and it's a very stable version)

What amazed me was the time I needed to set up the project and to get the first code running, including access to the database, mapping a simple class, deployment, deployment descriptors, the whole bunch. Although I used the skeleton of an existing project in a tidied-up version it took me a day until I had all the pieces together, including a 27 MB download just to get the MySQL JDBC connector (whose JAR file is smaller than 500 kB by the way). Granted, it's been a while since I set up my last project, but half a year isn't that long, so I'm not a total newbie at these things.

Here are the basic steps: * Set up a project * Collect the libraries - Downloads from several locations * Create a build file - I had one already from the existing project which just needed some cleaning up. It's an Ant file. "You could just use Maven" i hear you say. Yes I could, but therefore I'd have to get to know Maven which would cost even more time. * Create a Spring configuration - Again I could base this on the existing one, Hibernate needed some polishing * Write mapping files * Create deployment descriptors * Start writing code * Create the database * Deploy the project * Run Tomcat

Now, compare that to this: * gem install rails --include-depdencies * rails my_app * Create the database * Edit database.yml * Write a migration * Write code * Run script/server - No deployment descriptors needed

I didn't have to leave the command line once to do all these things. And if I need new libraries, gem install or script/plugin install are my friends.

It took me almost a day to get everything up and running in the Java project. It usually takes me five minutes to crank out the first features with Rails.

I'm left wondering why things ever got so complicated in the Java world. Things get even worse and more complicated if I'd want to set up a test environment. Are these things so much part of Java web development now that nobody's bothered by complicated set-ups or do people have their own project skeletons which include everything needed similar to the skeleton that Rails generates?

Tags: java, rails

Since I've started freelancing I worked less and less in a Java environment. Which is quite a good thing for me, since I get to do what I enjoy. I worked in a J2EE environment for three years. Though I never got to feel the pain of using entity beans, I still started loathing it over time. It just felt too heavy-weight. Testing is a pain, deployment takes ages, and it just can get frustrating what with all the waiting and the complexity involved.

I'm not going to discuss the pros and cons of J2EE here. It has its setting and that won't change for a while. There are some things that can make Java if not worthwhile, then at least a little bit fun. One of them is the Spring Framework which I've been using on several projects now, and which impresses me every time.

The other one is IntelliJ IDEA. I wrote about my switch from Eclipse a while ago. I'm still not looking back. I'm currently using IDEA 7.0 Milestone 2, and the integration of Spring and Hibernate impresses me every time I run across a new neat feature or just use it. It's been well worth its money till now.

There are some downsides though. I only have to look at my memory meter to see them. IDEA easily takes up 400 MB real memory. Throw in Tomcat (though a lightweight joy compared to JBoss) with another 150, maybe Oracle running on Parallels and it's not fun anymore. Swapping galore. Thanks to Hibernate I can work with MySQL most of the time, otherwise it would be a pain. It's a little shocking to see that 2 GB of memory are almost not enough for Java development on the Mac anymore.

Memory usage is most likely the reason why I'm still not very fond of using a full-blown IDE to develop with Rails. TextMate is still my number one choice, and I don't see that changing soon. Though I have yet to try out the Ruby and Rails plug-in for IDEA>