Java DSL for object-oriented type-safe CSS styling

I am looking for something like this Java-CSS-Library, to implement server-generated CSS stylesheets backed by a type-safe object-oriented model of CSS classes and rule sets.

This is part of my ongoing quest for the perfect “pure Java” web development framework that would allow me to

  • Focus on my strongest area of expertise: Elegant Java code
  • Use refactorings and other advanced Java tooling in Eclipse or IntelliJ Community Edition
  • Ignore the HTML/HTTP vs JVM objects impedance mismatch as much as possible

Sharing IntelliJ project configuration (.idea, *.iml) in version control

Me and my team do exactly what Christof Schablins describes in this blog post and what the Jetbrains folks recommend here: We use IntelliJ IDEA and share *.iml files (modules) and most files in .idea directory (project config) in the Version Control System (in our case CVS), including shared ant configs, shared run configs for Tomcat 6 and JUnit tests, shared project specific code inspection profile, shared data source definitions, etc.

Overall it works great. But we noticed a few things:

  • Needed an IntelliJ Path variable TOMCAT_HOME because devs have Tomcat installed in different places
  • Dialog “Do you want to add workspace.xml to CVS” keeps popping up (despite an entry in .cvsignore file within the .idea directory)
  • If devs have different sets of IntelliJ plugins enabled, each plugin adds its default code inspection rules to the shared profile (even if the project does not use them, e.g. Ruby stuff in a pure Java project). So developers have to be cautious not to check in those changes (or accept the bloat they cause)

So my question is: Have you come across these or similar issues and did you solve them?

Turn org.w3c.dom.NodeList into Iterable

I recently posted some reusable code that facilitates reverse iteration over a list in Java.

Here is another potentially useful Java method related to iteration, from my buddy Jordan Armstrong:

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
  /**
   * @param n An XML node list
   * @return A newly created Iterable for the given node list, allowing 
   *         iteration over the nodes in a for-each loop. The iteration 
   *         behavior is undefined if concurrent modification of the node list
   *         occurs.
   */
  public static Iterable<Node> iterable(final NodeList n) {
    return new Iterable<Node>() {

      @Override
      public Iterator<Node> iterator() {

        return new Iterator<Node>() {

          int index = 0;

          @Override
          public boolean hasNext() {
            return index < n.getLength();
          }

          @Override
          public Node next() {
            if (hasNext()) {
              return n.item(index++);
            } else {
              throw new NoSuchElementException();
            }  
          }

          @Override
          public void remove() {
            throw new UnsupportedOperationException();
          }
        };
      }
    };
  }

Union and intersection types in Java

Ceylon has union and intersection types at the heart of its type system. Ironically, there is something in Java resembling these powerful concepts, but only in specialized niche contexts and not as “first class citizens” of the type system:

  1. Something like intersection types can be used in generic type boundary declarations (since Java 1.5)
  2. Something like union types can be declared in try-catch blocks that use the multi-catch feature (since Java 1.7)

Interestingly, the Java language engineers used the & and | operators, just like Ceylon. But I have found no evidence so far that they are considering expanding these concepts to the Java type system in general or even let Java developers use them freely in all type declarations …

Update Oct/2012: At JavaOne, I asked Brian Goetz about this. He said that the Java Language team at Oracle has no intention to add additional support – beyond the niches mentioned above – for Union or Intersection types to Java in the foreseeable future.

Generic Apache Ant build.xml for webapps with JUnit tests

This post is about a build.xml file for Apache Ant that compiles, unit tests and packages a typical web application. The main build artifact is a timestamped WAR file.

Standardized directory layout

The build file assumes that your project uses the following directories:

  • src : Java sources and classpath resources
  • test : JUnit test sources and classpath resources
  • web : Web resources (JSP, HTML, CSS, etc.)
  • web/WEB-INF/lib : jars required by the web application at runtime
  • devlib/provided : jars provided by the web container at runtime
  • devlib/test : jars required for test compilation or execution

Transient build directories

The build will create these transient output directories for each stage of the build process. You should configure the version control of your project to ignore them.

  • build/classes : Compiled Java code and classpath resources (compile)
  • build/test-classes : Compiled JUnit tests (test-compile)
  • build/test-reports : JUnit test reports (test)
  • dist : WAR file (dist)

Run ant clean to delete them after you grabbed the WAR file.

The build.xml file

<project name="PROJECT_NAME" default="dist">

    <property name="classes" location="build/classes"/>
    <property name="test-classes" location="build/test-classes"/>
    <property name="test-reports" location="build/test-reports"/>

    <path id="classpath">
        <fileset dir="devlib/provided">
            <include name="*.jar"/>
        </fileset>
        <fileset dir="web/WEB-INF/lib">
            <include name="*.jar"/>
        </fileset>
    </path>

    <path id="test-classpath">
        <path refid="classpath"/>
        <pathelement location="${classes}"/>
        <pathelement location="${test-classes}"/>
        <fileset dir="devlib/test">
            <include name="*.jar"/>
        </fileset>
    </path>

    <target name="clean">
        <delete dir="dist"/>
        <delete dir="build"/>
    </target>

    <target name="compile">
        <mkdir dir="${classes}"/>
        <javac destdir="${classes}">
            <classpath refid="classpath"/>
            <src path="src"/>
            <src path="common/src"/>
        </javac>
        <copy todir="${classes}">
            <fileset dir="src" excludes="**/*.java"/>
        </copy>
    </target>

    <target name="test-compile" depends="compile">
        <mkdir dir="${test-classes}"/>
        <javac destdir="${test-classes}">
            <src path="common/test"/>
            <src path="test"/>
            <classpath refid="test-classpath"/>
        </javac>
    </target>

    <target name="test" depends="test-compile">
        <mkdir dir="${test-reports}"/>
        <junit printsummary="yes">
            <classpath refid="test-classpath"/>
            <formatter type="brief" usefile="false"/>
            <formatter type="xml"/>
            <batchtest todir="${test-reports}" failureproperty="failed"
                       errorproperty="failed">
                <fileset dir="${test-classes}" includes="**/*Test.class"/>
            </batchtest>
        </junit>
    </target>

    <tstamp>
        <format property="timestamp" pattern="yyyy-MM-dd_hh-mm"/>
    </tstamp>

    <target name="dist" depends="clean, compile, test">
        <mkdir dir="dist"/>
        <war destfile="dist/${ant.project.name}_${timestamp}.war"
             basedir="web"
             excludes="**/CVS">
            <classes dir="${classes}"/>
        </war>
    </target>

</project>

Iterate in reverse order over a list in Java

Sometimes we want to iterate in reverse order over a list in Java – without (re)sorting the list. Code example:

    for (T item : backwards(list)) {
        // do something
    }

Here is a backwards() method that does this for you (maybe put this code into a util class and use a static import):

    public static <T> Iterable<T> backwards(final List<T> list) {
        return new Iterable<T>() {
            @Override
            public Iterator<T> iterator() {
                return backwardsIterator(list);
            }
        };
    }

    private static <T> Iterator<T> backwardsIterator(List<T> list) {
        final ListIterator<T> iter = list.listIterator(list.size());
        return new Iterator<T>() {
            @Override
            public boolean hasNext() {
                return iter.hasPrevious();
            }

            @Override
            public T next() {
                return iter.previous();
            }

            @Override
            public void remove() {
                iter.remove();
            }
        };
    }

Maven integration (m2e) for Eclipse 3.7.x (Indigo)

Sonatype’s Maven integration for Eclipse (m2e) has been migrated to eclipse.org and is now available from the default update site for Indigo.

This means that you no longer have to add any Sonatype update sites as mentioned on the old (now outdated) m2eclipse site.

In particular, this also means that the old “m2e-extras” update site is obsolete for Eclipse 3.7.x and later. Things like WTP integration or Subclipse integration are now available as “m2e connectors” through Window – Preferences – Maven – Discovery.

All of this is very poorly (or not at all) documented on the new m2e home page and some people had problems with these changes.