Posted on Apr 12, 2009

A year with Java

Last year at this time I took a Java programming class as a refresher as I hadn’t done much with Java since my days as an undergrad (and a few short programs in grad school). After primarily using Perl for the last 7 years, this was a big switch. The difficulty with Perl is that it’s a programming language for concenting adults. You can do almost anything any number of ways. The amount of time it takes to understand a block of Perl code is far greater than that of a block of a statically typed language like Java. This had been a huge issue for our company as we had tons of legacy code that followed no standard.

It is my firm belief that if you are going to develop a large codebase in Perl, you MUST use a fairly stringent coding standard. In my first week in my current role, I came across three separate “subroutines” that were over 2500 SLOC. One of the shorter subroutines had 200 SLOC and 32 regular expressions. 4 of these regular expressions were over 80 characters long. Dynamic subroutines are often used. Map statements that turn arrays into hashes are the norm. One library that I maintain is > 10000 SLOC and contains 7 comments. It has been my personal nightmare for more than a year and a half now.

Some of this has to do with simply not understanding best development practices regardless of language, other things (like not adding a comment for a 120 character regular expression) could have been avoided by the use of a coding standard. 80% of software development is maintenance, plan accordingly. One way to force yourself to do the right thing when writing code is to pretend the guy who is going to be asked to maintain it is completely psychotic and knows where you live.

In any event, I have found that using a stringent coding standard is far less important when using Java because:

  • it’s statically typed – I know what I’m going get back from any subroutine. I don’t have to worry about using Data::Dumper with die statements to figure out what complicated object I’m dealing with.
  • you can use a debugger – no more running the entire program and relying on print statements to figure out what’s going on. I can see the value of each variable and I can make changes on the fly and see the results. This is a huge timesaver.
  • frameworks – although there are a few frameworks for various paradymes in Perl, Java takes the cake here. It cuts down on development time by allowing developers to concentrate on the functionality of their application instead of the middleware that must accompany it. Using a framework (struts, spring, hibernate, etc) also makes it trivial for all developers to understand how a module works.

I can’t understate the huge amount of time our company has saved since switching to Java. “Estimated Time to Fix” is greatly reduced and more work is accomplished.

Posted on Nov 17, 2008

Generating xmlbeans from xml

This took me a while to figure out and I had to use many different sources so I figured I’d put the whole process here. The goal was to create xmlbeans for an API call that returned xml. I did not have an .xsd file to go by however, but xmlbeans comes with a couple of utilites that can be used to go from an instance of my API return to an xsd file, to xmlbeans. Here’s the process:

Generate an xsd file from your xml file using inst2xsd like so:

/opt/xmlbeans-2.4.0/bin/inst2xsd -outPrefix info.xsd info.xml

You should end up with a info0.xsd file. Take a look at this file to make sure the generic types look ok (string, short, float, etc). inst2xsd guesses at what they should be based on the content of the xml file but the xml file typically represents only one instance of the process.

Next, you can create the xmlbeans from the xsd file. To add a package name to the beans, you must create a file with an .xsdconfig extension in the same directory as your xsd file. Failing to do so will result in the default package name of ‘noNamespace’. The .xsdconfig file should look like this:

<xs:config xmlns:xs=”http://xml.apache.org/xmlbeans/2004/02/xbean/config”>
<!– Use the “namespace” element to map a namespace to the Java
package
name that should be generated. –>
<xs:namespace uri=”##any”>
<xs:package>com.bryandunn.project.mail</xs:package>
</xs:namespace>
</xs:config>

Next, run the xmlbeans utility scomp like so:

/opt/xmlbeans-2.4.0/bin/scomp -out info.jar info0.xsd info0.xsdconfig

This should result in an info.jar file with your xmlbeans which you can then reference like this:

import org.apache.xmlbeans.*;
import com.bryandunn.project.mail.*;
import java.io.*;

public class XMLBeanTest {

public static void main(String[] args) {

File xmlFile = new File("/home/bdunn/tmp/info.xml");

try {
    // Bind the instance to the generated XMLBeans types.
    MailClientDocument strDoc = MailClientDocument.Factory.parse(xmlFile);
    // Get and print pieces of the XML instance.
    MailClientType client = strDoc.getMailClient();
    MailingType mailing = client.getMailing();
    System.out.println(mailing.getConfigFile());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

Posted on Aug 26, 2008

Hibernate Bi-Directional Many-To-Many

This took me a few hours to figure out so I’m logging this here for my own sanity. If you have a bidirectional many-to-many mapping in Hibernate with a join table, the join table is only updated when the noninverse side of the mapping is inserted/updated. In the example below, the join table (pane_specs) is only updated when a spec is saved, not when a pane is saved:

Spec.java

@ManyToMany
@JoinTable(
name = “pane_specs”,
joinColumns = { @JoinColumn(name = “spec_id”) },
inverseJoinColumns = { @JoinColumn(name = “pane_id”) }
)
public List<Pane> getPanes() {

Pane.java

@ManyToMany(mappedBy = “panes”)
public List<Spec> getSpecs() {

Posted on May 16, 2008

Comparison of Java Framworks from a Java Noob

A coworker and I were tasked with rewriting an internal application to manage our company’s workflow. We both have a background in Perl and not much Java, making us the perfect candidates to prototype potential frameworks. The following is what we came up with based on our (few) requirements:

  • MVC framework
  • view layer must allow us to write html and css
  • must be flexible enough to extend to other upcoming projects

The final decision ended up being struts2, mainly due to it’s flexibility. Other frameworks seemed like they would allow us to develop more quickly, but we would have been stuck with them (custom tags, combined view/controller layers, etc). With struts and hibernate for the model layer, it seemed like we could quickly move to something else easily.

Servlets/JSP/JSTL

  • Pros:
    1. Not a lot of re-learning, everything can be done pretty much the same way as in CGI.
    2. We have (read: Roger has) JSP and JSTL books
  • Cons:
    1. Requires a couple little helper classes for working with Hibernate
    2. JSTL isn’t especially graceful
    3. Doesn’t look good on a job description or resume

Tapestry

(I tested 4.1, the current GA release. 5.0 is in beta testing, and probably will be released before long. There are already books out for 5, but not really any online tutorials.)

  • Home page: http://tapestry.apache.org/
  • Lots of tutorials: http://tapestry.apache.org/tapestry4.1/tutorials/index.html
  • Hibernate+Tapestry: http://www.hibernate.org/96.html
  • Pros:
    1. Allows you to write HTML with only a couple of additional non-standard attributes
    2. Very well documented and tutorial-ed.
    3. One “page specification” XML file (*.page) per page, instead of a single huge XML config file
    4. Coding is extremely simple, most of the complexity is in the page files.
  • Cons:
    1. Lots of different components (for page specification files) using a kind of non-standard language
    2. Notorious for changing API between major releases (i.e. 5.0).

Wicket

  • Home page: http://wicket.apache.org/
  • A dated tutorial: http://cwiki.apache.org/WICKET/newuserguide.html
  • Databinder, a Wicket+Hibernate linking library: http://databinder.net/site/show/overview
  • Pros:
    1. An Apache project, implying longevity or better integration going forward
    2. Lots of people think it represents the future of Java frameworks
    3. AJAX and jQuery integration built-in
  • Cons:
    1. Uses a very unique design pattern, a huge rethink from standard CGI or servlet coding.
    2. Tutorials and other information is a bit dated, making it hard to learn, especially with the unique design pattern. (This is even more true for Databinder)
    3. Lots of the HTML can/should/must be generated by code, instead of by hand.

Struts

  • Home page: http://struts.apache.org/
  • Tutorial: http://struts.apache.org/2.x/docs/hello-world.html
  • Pros:
    1. Fairly minimal. Struts does some things for you, but keeps the general Servlet/JSP structure more or less unchanged
    2. Integration with Hibernate is as simple as with Servlets/JSP
    3. Virtually ubiquitous
    4. eCommerce suite uses Struts, so we will have to know it anyhow
  • Cons:
    1. Eats babies
    2. Tastes like dirt

JSF (Java Server Faces)

GWT (Google Web Toolkit)

Echo

Posted on Mar 17, 2008

Random collection of notes from Sun Java course

These are some notes I scribbled down during Sun’s “Java Programming” class. Having programmed in Perl the last 7 years, this is what I wrote down as “noteworthy.”

  • Everything in Java is an object except primitive types
  • All objects are references in memory
  • A ‘foreach’ loop in java looks like this:

for (Car y: x) {

y.speed = 100;

}

  • Inherited objects always call the super classes constructor. The default is super() with no arguments. This can be overridden by placing a super(int i) as the FIRST EXECUTABLE STATEMENT in a subclass constructor.
  • All objects inherit from the base class ‘Object’.
  • obj instanceof class will return true or false based on whether obj is indeed an object of type class.
  • defining the toString method for object obj allows you to define what is printed when System.out.println(obj) is called.
  • The static keyword declares members that are associated with the class and not the class objects
  • The final keyword ensures a member can not be changed. This means that methods and classes that use final can not be overridden or extended.
  • The abstract keyword:
    • forces child classes to define a method.
    • classes with an abstract method must also be abstract.
    • abstract classes can not be instantiated directly (only via subclasses)
  • An interface is a class with only abstract methods
  • The implements class keyword is used for interfaces to enforce the rules of the interface. Unlike extends, implements can be used on more than one interface.
  • For handling exceptions, you can use try and catch blocks, or declare your method with a ‘throws‘ clause that sends the exception back to whatever called that method.