Archive

Posts Tagged ‘maven’

Easy Java toString() methods using Apache commons-lang ToStringBuilder

May 21, 2010 2 comments

One of the disciplines I try to have while developing Java code is always overriding the default toString, equals, and hashCode methods. I have found that most of the modern IDE’s have a way to generate these methods. My IDE of choice, IntelliJ IDEA, does have this functionality but I find it’s implementations to be sub par. Here is an example of an IntelliJ generated toString method for a class…

@Override
public String toString() {
    return "Person{" +
        "name=" + name +
        ", age=" + age +
        '}';
}

My biggest problems with this implementation are:

  1. Hard-coded, static strings for class and field names makes the amazing refactoring features of IntelliJ less reliable.
  2. Not using StringBuilder makes this code harder to read and slightly more resource intensive.
  3. Only fields of this class can be used; all inherited fields, even protected ones, are not included.

This was just not good enough. I started to investigate if anyone had written some kind of library which could reflectively look at an Object and produce a complete (private and inherited fields included) and consistent toString representation. Sure enough, I discovered that one of the Apache Commons libraries provided exactly this functionality. The commons-lang project has a class called ToStringBuilder which has a static method on it that uses reflection to generate a string which contains a all of a classes fields. The string’s format is consistent and can be controlled by the ToStringStyle class which has several useful formats built-in and also lets to implement your own. You can now write any object’s toString method as follows:

@Override
public String toString() {
    return ToStringBuilder.reflectionToString(this);
}

If you are using maven as your project management tool, you can add the following dependency into your pom.xml file in order to be able to use the commons-lang library in your project.

<dependency>
  <groupId>commons-lang</groupId>
  <artifactId>commons-lang</artifactId>
  <version>2.5</version>
</dependency>

Normally I would try to avoid reflection in production code when possible due to it’s reported slower performance, however I find the only time I am actually using toString methods is usually in debugging or testing where speed is not my number one concern. If you don’t feel reflection is a good solution for you, the ToStringBuilder class does have several instance methods which follow the traditional ‘builder’ pattern which allows you to manually choose the fields which will be included in the string representation of your object. Here is example of that usage pattern:

public String toString() {
    return new ToStringBuilder(this).
        append("name", name).
        append("age", age).
        append("smoker", smoker).
        toString();
}

This usage does have some of the same problems as the original implementation like it requires the field identifiers to be static strings. This does however allow you to ensure a consistent format of the resulting string and it also has the ability to include the any super classes’ toString result using the appendSuper() method.

If you are using Eclipse or NetBeans, I understand there are very good plugins which can build very good toString representations but this functionality is unfortunately not enough for me to give up the refactoring support IntelliJ provides. The above solution would also help though if you have some developers on a team using different IDE; using a library to toString representations is better than IDE dependent tools since it maintains consistency between environments.

The ToStringBuilder class is just one of many useful utility classes provided by the commons-lang library and the commons-lang library is just one of the useful libraries provided by the Apache Commons project. Make sure to check it out anytime you find yourself writing some code and asking yourself “Hasn’t someone done this already?”

Advertisements

First Look at Vaadin

November 22, 2009 8 comments

I’ve had the chance over a recent weekend to have a first crack at a web framework called Vaadin.

I was originally browsing for news about the latest release of Google’s GWT framework when I stumbled on a reference to Vaadin, and decided to go take a look. What I found intrigued me, and I decided to take it for a test drive, as I was down sick for a couple of days with a laptop nearby…. My back became annoyed with me, but it was worth it, I think.

First Look
First off, the practicalities: Vaadin is open source, and with a reasonable license, the Apache License. The essential bits of Vaadin are contained in a single JAR, and it’s both Ant and Maven friendly right out of the box.

The next thing that struck me about Vaadin was the documentation. The first unusual thing about it’s documentation was the fact of it’s existence, as open source projects are downright notorious for poor documentation. Vaadin is a pleasant exception, with tons of examples, a well-organized API doc, in the usual JavaDoc format, and even the “Book of Vaadin”, an entire PDF book (also available in hardcopy) that takes you through Vaadin in enough detail to be immediately productive.

Given that surprisingly pleasant start, I dug deeper, creating a little app of my own.

Just the Java, Ma’am
The main thing that kept me interested in Vaadin once I started digging further was that it’s pure Java. Many frameworks talk about writing your UI work in Java, such as Wicket, but there’s still a corresponding template and some wiring that happens to put the code and the template together. Not so with Vaadin.

When they say “just Java”, they mean it – your entire UI layer is coded in Java, plain and simple. No templates, no tag libraries, no Javascript, no ‘nuthin. It’s reminiscent of the Echo framework, except in Vaadin’s case the Javascript library that your code automatically produces is Google’s GWT, instead of Echo’s own Core.JS library.

Unlike GWT, though, the Vaadin approach doesn’t bind you to any specific source code though, it’s just a binary jar you put on your classpath.

The only thing in my sample app, other than 2 Java files, was a web.xml and a css stylesheet, both of which were only a few lines long. And this was no “Hello, World”, either, but a rich AJAX webapp with a tree menu, fancy non-modal “fading” notifications, images, complex layouts, and a form with build-in validation. And it took maybe 4 hours of total work to produce – and that was from a standing start, as I’d never heard of Vaadin before last Thursday. Not bad, not bad at all.

I found I was able to get a very capable little webapp up and running with no need to invent my own components, even though I had trees and sliders and menus and other assorted goodies on the page. It worked in every browser I was able to try it in, which is certainly not the case for my own hand-rolled JavaScript most of the time 🙂

I haven’t yet tried creating my own custom components, but it certainly looks straightforward enough.

I did try linking to external resources, and included non-Vaadin pages in my app, with no difficulties, so it appears that Vaadin plays well with others, and can be introduced into an existing project that uses, for instance, a whack of JSP’s that one might want to obsolete.

Webapps
I think Vaadin warrants more exploration, and I intend to put it further through its paces in the next few weeks. It appears extremely well-suited to web applications, as opposed to websites with a tiny bit of dynamic stuff in them.

It offers an interesting alternative to some of the patterns I’ve seen for advanced dynamic webapp development so far.

One approach I’ve seen a lot is to divide the duties of creating an app into the “back end” services and the “UI”. Generally the UI is written in either JavaScript, or uses Flex or some other semi-proprietary approach. The “back end” stuff is frequently written to expose it’s services as REST, then the two are bolted together. The pain point here happens when the two meet, as it’s common and easy to have minor (or major!) misunderstandings between the two teams. This usually results in a lot of to-and-fro to work out the differences before the app comes all the way to life.

The other approach, more common on smaller or resource-strapped teams, is to have the same group responsible for both UI and back-end services. This reduces the thrash in the joints a bit, but doesn’t eliminate it, because the two technologies on the two sides of the app aren’t the same. You can’t test JavaScript the same way you write Java, for instance, and they’re two different languages – one of which (Java) has far better tooling support than the other. IDE support, for instance, is superb for Java, and spotty at best for JavaScript.

With Vaadin, both of these approaches become unnecessary, as its the same technology all the way through (at least, what you write is – technically it’s still using JavaScript, but because that’s generated, I don’t count it).

You get to use all of the tools you know and love for the back-end services to write the code for the UI, which you can then unit and functional test to your heart’s content.

The temptation to mix concerns between UI code and back-end service code must still be resisted, of course, but at least that code isn’t buried somewhere in the middle of a JSP page, ready to leap out and bite you later.

Because you’re using dynamic layouts, the app always fits properly on the screen without any extra work, addressing a pet peeve of mine, the “skinny” webapp, restraining itself to the least common denominator of screen size, thus rendering impotent my nice wide monitors.

Scala
Just because Vaadin is a Java library doesn’t restrict you to using Java to drive it, however. I made another little webapp where the whole UI was defined in Scala, calling the Vaadin APIs, and it worked like a charm. In some ways, Scala is an even better fit for Vaadin than straight Java, I suspect. I haven’t tried any other JVM compatible language, but I see no reason they wouldn’t work equally well.

Deployment and Development Cycle
As I was building the app with Maven, I added a couple of lines to my POM and was able to say “mvn jetty:run” to get my Vaadin app up and running on my local box in a few seconds. My development cycle was only a few seconds between compile and interactive tests, as I was experimenting with the trial-and-error method.

TDD would be not only possible, but easy in this situation.

I successfully deployed my little Vaadin app to ServiceMix, my OSGi container of choice, without a hitch.

Performance appeared excellent overall, although I haven’t formally tested it with a load-testing tool (yet).

Summary
So far, I’m impressed with Vaadin. I’m more impressed with any web framework I’ve worked with in a number of years, in fact. I’m sure there are some warts in there somewhere, but for the benefits it brings to the table, I suspect they’re easily worth it. I think the advantages to teams that already speak fluent Java is hard to overstate, and the productivity to produce good-looking and functioning webapps is quite remarkable.

Over the next few weeks I’ll push it a bit harder with a complex example application, and see how it stacks up against other web app technologies I’ve worked with in a more realistic scenario.

By: Mike Nash

Basic Hibernate @OneToOne @PrimaryKeyJoinColumn Example With Maven and MySQL

November 14, 2009 7 comments

Recently we had a story which involved improving one of our data models. The table for the model had grown quite wide and we wanted to improve normalization and performance. We wanted to move a few columns from our original table (Listing) to a new table with the primary key of the new table (ListingLocation) also being a foreign key to the primary key of the original table, our one-to-one relationship. I will try to detail how we accomplished this change using a simplified example. Source code is linked at the bottom of this post.

Here is the entity relationship diagram of the old, single table structure:
Old ER Diagram
And here is the entity relationship diagram of the new, two table structure:
New ER Diagram

As you can see, it is a very simple example of a very common relationship in the database. However, what we found when implementing this in Hibernate was not a simple as I had hoped.

To get started here is the SQL used to represent our new tables:

CREATE TABLE Listing
(
id BIGINT(20) NOT NULL AUTO_INCREMENT,
price DECIMAL(10,2),
PRIMARY KEY (id)
) TYPE = INNODB;


CREATE TABLE ListingLocation
(
listingID BIGINT(20) NOT NULL,
address VARCHAR(255),
PRIMARY KEY(listingID),
INDEX (listingID),
FOREIGN KEY (listingID) REFERENCES Listing (id)
) TYPE = INNODB;

I’ve used MySQL for this example because it is free and easy to setup. InnoDB table types have been because they allow foreign keys, which is crucial to this example.

Our old Listing entity was pretty basic; it looked something like this (imports & getters/setters excluded):

@Entity
@Table
public class Listing implements Serializable {
@Id
@GeneratedValue
private long id;
@Column(columnDefinition= "DECIMAL(10,2)")
private double price;
private String address;
...

In this case, creating a new instance of Listing and persisting it is very easy. When we split the entities, it becomes a little more complicated. Here is what our entities looked like after being split:

@Entity
@Table
public class Listing implements Serializable {
@Id
@GeneratedValue
private long id;
@Column(columnDefinition= "DECIMAL(10,2)")
private double price;
@OneToOne
@PrimaryKeyJoinColumn
private ListingLocation listingLocation;
...

and

@Entity
@Table
public class ListingLocation implements Serializable {
@Id
@Column(name = "listingID")
private Long id;
private String address;
...

The differences are not large, but there are a couple important points to note:

  • Adding ListingLocation to Listing with @OneToOne & @PrimaryKeyJoinColumn annotations tells Hibernate the Listing has a one-to-one mapping with ListingLocation by using the Primary Key as the join column.
  • Adding @Id & @Column(name = “listingID”) annotations to our id field in ListingLocation tells Hibernate that id is, well, an ID, but that column should not be called “id” in the DB, but “listingID” as that will help an observer see the relationship quickly without looking closely at the schema. Also, it is good to note that the @GeneratedValue is not on “id” in ListingLocation as it is in Listing as we want to specify exactly what goes in that field.

The biggest gripe I have with using the one-to-one relationship is that we can no longer save Listing only. Our REAL Listing entity is far more complex with several relationships, but this was the first one-to-one relationship with Hibernate. Previously we could do something like:

Listing listing = new Listing();
listing.setPrice(price);
listing.setAddress(address);
listing.setFoo(foo); // where foo is a @OneToMany annotated entity
...
session.save(listing);

Now, we must save Listing and ListingLocation separately like this:

ListingLocation listingLocation = new ListingLocation();
listingLocation.setAddress(address);
Listing listing = new Listing();
listing.setPrice(price);
listing.setListingLocation(listingLocation);
...
session.save(listing);
if (listing.getListingLocation() != null) {
listing.getListingLocation().setId(listing.getId());
session.save(listing.getListingLocation()); // save ListingLocation
}

I guess I’m just a bit spoiled, but I was hoping that this would bit more automatic, as it is with the one-to-many/many-to-one relationships.

I have written a small app that uses these two entities and inserts a row into each table, the link is available at the bottom of this post. The config (hibernate.cfg.xml) expects that you have MySQL running on 127.0.0.1 with a DB named ‘OneToOneDemo’ with a user named ‘root’ and a password of ‘password’; I have included the SQL (Setup-OneToOneDemo.sql) to setup the DB. Just extract the contents of the archive, navigate to the project directory, and from the command line/terminal run:

mvn clean compile exec:java -Dexec.mainClass=com.point2.onetoonedemo.App -e

You should see the following output:

@OneToOne @PrimaryKeyJoinColumn Hibernate Demo
----------------------------------------------
...
Hibernate:
insert into Listing (price) values (?)

Hibernate:
insert into ListingLocation (address, listingID) values (?, ?)
Saved listing ID: 1

Download Source Code (12 KB .ZIP)

If you have any questions, comments, or suggestions on how to do better accomplish one-to-one Hibernate mappings, I would love to hear about them. If you have any problems getting the code to compile and/or run, please let me know and I will make the necessary changes. Everything should just work, providing you modify the hibernate config or setup your DB. I had a difficult time finding complete and recent documentation on this subject so I hope this post and the maven project will help.

By: Damien Gabrielson

Maven with included Dependencies

September 4, 2009 1 comment

One of the most common, and, in my opinion, valid criticism’s of Apache Maven is the way it handles dependencies.

The default way of doing dependencies in Maven is for a build to look for dependency jars in one of a specified number of places. If you don’t specify a location, it will start with your local Maven repository, then a stock set of online repositories (such as ibiblio).

What this means is that you can quickly and easily add a dependency to your project by just listing it in the POM, and Maven will frequently just go get it for you as required. For dependencies that don’t change rapidly (which is generally a bad idea for entirely separate reasons), the local copy is always used, so after the first download you don’t go get the jar again unless it changes.

The downside of this (and hence the basis for the criticism) is that your local repository is considered a cache, and is not checked in to your source control system. Maven aficionados believe that source control should be for what the name implies: source, not jars (which are an artifact, not source code). This is good, except in situations where the local repository is removed (as it’s a cache, and not “backed up” by being in source control) and you want to rebuild your project. Normally, no problem: Maven will simply go back out into the wilds of the internet and get your jars for you again. Except when it can’t, which is where the problem starts.

Let’s say your project depends on foo-1.0.jar, for the sake of discussion. Foo-1.0.jar is found in a repository at http://baz.com. No problem. Two months from now, you come back and make a change to your project, and your local repo doesn’t have foo-1.0.jar in it. Maven goes to get it for you, but baz.com has gone offline. Oops. Now you can’t build your project at all. Worse, let’s say you *do* find foo-1.0.jar, but it’s been updated. Granted, this is a gross violation of the version scheme, but as baz.com is not under your control, it *can* happen – and Murphy was an optimist.

The first level of defense against this is to have a local jar proxy that *is* backed up, like Nexus. Nexus not only provides a safe haven for the exact versions of Jars you need to build your project, but also proxies new jars automatically, when set up correctly. That way, once you use that external dependency, it’s available on the local proxy immediately forever more, in precisely the correct version.

This solution is so good, that I always consider Nexus and Maven to be two parts of one solution – as you don’t really have reliable and repeatable builds without Nexus in the mix.

Another way to go, however, is perhaps even more straightforward, and might be appropriate if you have a limited number of “internal” binary dependencies – that is, binary dependencies that you generate within your organization between projects.

This is the option I want to describe in this blog, and it takes a form very similar to the old Ant style of having a “lib” directory in your project, and checking jars into source control.

You simply create a directory (called lib or whatever you wish, but “lib” might be more standard), and put your jar dependencies in it. Then you refer to each dependency in your pom.xml file with a special syntax, like so:


    <dependency>
      <groupId>mygroup</groupId>
      <artifactId>myjar</artifactId>
      <version>1.0.0</version>
      <scope>system</scope>
      <systemPath>${basedir}/src/main/
         resources/lib/myjar-1.0.0.jar</systemPath>
    </dependency>

Now the myjar-1.0.0.jar will be on my classpath during compilation, easy as that. I can then check in that nicely versioned jar file, and have a fully self-contained project, while at the same time being able to leverage the power of Maven and it’s rich ecosystem of plugins. If you’re using the shade plugin, this is an excellent way to create a self-contained executable jar file containing all of your necessary dependencies in one shot, rather than having to worry about classpaths at runtime.

In web applications, you can do even better. By placing the dependency in the correct spot in your source tree, you can have it automatically included in the finished .war file, while at the same time finding it in your classpath during compile time, like so:


    <dependency>
      <groupId>xstream</groupId>
      <artifactId>xstream</artifactId>
      <version>1.3.1</version>
      <scope>system</scope>
      <systemPath>${basedir}/src/main/
           webapp/WEB-INF/lib/xstream-1.3.1.jar
           </systemPath>
    </dependency>

This includes the xstream jar in my webapp. Every IDE that can digest a POM file (which include my 3 main ones, IntelliJ IDEA, Eclipse IDE and Netbeans) also automagically find the dependencies.

One minor constraint here is that you must use a *versioned* jar file – e.g. it must be named according to the artifact-version.jar pattern. I consider this a feature, not a limitation, as I’m a firm believer that all artifacts should be properly versioned, so I can tell what source code originally created them. Yes, I know that can be done internally, in a manifest or such, but I like to see the label on the outside of the box, so to speak.

As one colleague put it, now you can be assured of coming back to your project months or years later, even if you don’t have internet connectivity, and be able to build the darn thing again, without going off on a wild jar chase all over the internet.

This pattern can overcome a serious and legitimate objection to Maven, and might be appropriate in many situations. Give it a try, let me know what you think!

By: Mike Nash

Maven Projects In NetBeans 6.5 On OSX / Updating Maven On OSX

May 1, 2009 Comments off

Since my last post, Defaulting To JDK 1.6 In NetBeans 6.5 On OSX, has enjoyed some popularity I decided to keep running with the NetBeans 6.5/OS X theme. NetBeans is a great, free IDE that supports more types of projects than the average developer would likely ever need. One of the most useful project types that NetBeans supports is Maven projects. If you are new to Maven, here is an intro to peak your interest.

For developers who have been using Maven for a while, you likely will be creating your projects (.pom files specifically) from a text editor but this can be a little overwhelming for those new to Maven or those who would rather simply spend their time writing code instead. NetBeans 6.5 makes it incredibly easy to create a Maven project in a matter of seconds.

First, go to the “File” menu and choose “New Project”.
New Project
Under “Categories”, choose “Maven” and in”Projects”, choose “Maven Project” and click “Next”.
Choose Project
The “Archetype” window should open next, select “Maven Quickstart Archetype” and click “Next”.
Project Archetype
The “Name and Location” window will open allowing you to give specifics to your project. You can customize this as you see fit but for the purposes of this example I will leave the default settings. Click “Finish” and your project will start to build.
Project Name & Location
If you are running OS X 10.5.6, as I am, you will likely see the following error:

------------------------------------------------------------------------
[ERROR]BUILD ERROR
------------------------------------------------------------------------
Error resolving version for 'org.apache.maven.plugins:maven-archetype-plugin': Plugin requires Maven version 2.0.7
------------------------------------------------------------------------
For more information, run Maven with the -e switch

The reason for this is that OS X 10.5 shipped with Maven 2.0.6 pre-installed but Apple has never pushed any updates to it. According to the Apache archives, Maven 2.0.6 was released in April 2007 but it is kind of annoying that they didn’t realize that Maven projects would not work by default on OS X before they released NetBeans 6.5. Luckily, it is very easy to update Maven to the latest version if you don’t mind using the terminal and the sudo command.

  1. Download the zip with binaries for whichever Maven version you would like to install. At time of writing, the most recent version is 2.1.0, http://www.apache.org/dyn/closer.cgi/maven/binaries/apache-maven-2.1.0-bin.zip.
  2. Once the file is downloaded, you can extract the archive and you should end up with a directory named something like “apache-maven-2.1.0”. Open a Terminal window and cd /usr/share
  3. Let’s move the current Maven directory to a backup folder in case we ever want to revert. In the terminal you opened in the last step, type sudo mv maven maven-2.0.6. This will ask you for your password and then move the “maven” directory to a new directory called “maven-2.0.6”, assuming your user account has sufficient permissions.
  4. Now let’s put the new version in place so that NetBeans will start using it. To do so, we need to copy the directory we extracted from the zip file. Once again, in the Terminal window you have open, type sudo cp -R /Users/dgabrielson/Desktop/apache-maven-2.1.0 maven. Keep in mind that the path to the extracted “apache-maven-2.1.0” directory will have to be changed to the appropriate path on your system.
  5. Maven should now be upgraded! To confirm, in your Terminal window, type mvn -version and you should see some output like Apache Maven 2.1.0 (r755702; 2009-03-18 13:10:27-0600).

Now if you try to build again, you should get a successful build log ending with:

------------------------------------------------------------------------
BUILD SUCCESSFUL
------------------------------------------------------------------------

Enjoy your new Maven build and get coding!

By: Damien Gabrielson