Thursday, 26 August 2010

Maven, Spring, Hibernate & JPA skeleton project

Today I read that Spring-JPA is the 'dream team' for POJO development. So I thought I'd see what all the hype is about. Here is a skeleton Maven project using Spring, JPA implemented with Hibernate and backed with an embedded Derby database.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.adrianwalker.maven.skeleton.spring.jpa</groupId>
  <artifactId>maven-spring-jpa-skeleton</artifactId>
  <version>0.1.0</version>
  <name>Maven Spring JPA Skeleton</name>

  <description>
    Skeleton project for using Spring, Hibernate and Derby 
    database accessed through JPA.
 
    Usage: mvn clean install
  </description>

  <url>http://www.adrianwalker.org</url>

  <organization>
    <name>adrianwalker.org</name>
    <url>http://www.adrianwalker.org</url>
  </organization>

  <developers>
    <developer>
      <name>Adrian Walker</name>
      <email>ady.walker@gmail.com</email>
      <organization>adrianwalker.org</organization>
      <organizationUrl>http://www.adrianwalker.org</organizationUrl>
    </developer>
  </developers>

  <repositories>
    <repository>
      <id>java.net</id>
      <url>http://download.java.net/maven/2</url>
    </repository>
    
    <repository>
      <id>java.net - legacy</id>
      <url>http://download.java.net/maven/1</url>
      <layout>legacy</layout>
    </repository>    
  </repositories>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>javax.persistence</groupId>
      <artifactId>persistence-api</artifactId>
      <version>1.0</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring</artifactId>
      <version>2.5.6</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>2.5.6</version>
    </dependency>

    <dependency>
      <groupId>org.apache.derby</groupId>
      <artifactId>derby</artifactId>
      <version>10.6.1.0</version>
    </dependency>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate</artifactId>
      <version>3.2.1.ga</version>
    </dependency>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>3.2.1.ga</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.4</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

Spring Configuration

context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">

  <bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.apache.derby.jdbc.EmbeddedDriver" />
    <property name="url"
      value="jdbc:derby:target/database/message;create=true" />
    <property name="username" value="app" />
    <property name="password" value="app" />
  </bean>

  <bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <property name="jpaVendorAdapter">
      <bean
        class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        <property name="databasePlatform" value="org.hibernate.dialect.DerbyDialect" />
      </bean>
    </property>
    <property name="jpaProperties">
      <props>
        <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
      </props>
    </property>
  </bean>

  <bean name="jpaMessageDao"
    class="org.adrianwalker.maven.skeleton.spring.jpa.JpaMessageDao">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
  </bean>
  
  <bean name="messageJpaController"
    class="org.adrianwalker.maven.skeleton.spring.jpa.MessageJpaController">
  </bean>  

  <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
    <property name="dataSource" ref="dataSource" />
  </bean>

</beans>

Persistence Configuration

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xsi:schemaLocation="
    http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
    
  <persistence-unit name="messagePersistenceUnit" transaction-type="RESOURCE_LOCAL">
    <class>org.adrianwalker.maven.skeleton.spring.jpa.MessageEntity</class>
  </persistence-unit>
</persistence>

JPA Entity

A very simple entity which has an id and some message text.

MessageEntity.java

package org.adrianwalker.maven.skeleton.spring.jpa;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;

@Entity
@NamedQueries({
  @NamedQuery(
    name="MessageEntity.find",
    query = "SELECT m FROM MessageEntity m"),
  @NamedQuery(
      name = "MessageEntity.count", 
      query = "SELECT COUNT(m) FROM MessageEntity m")
})
public class MessageEntity implements Serializable {

  private static final long serialVersionUID = 1L;
 
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private long id;

  private String text;

  public MessageEntity() {
  }

  public MessageEntity(final String text) {
    this.text = text;
  }

  public long getId() {
    return id;
  }

  public void setId(final long id) {
    this.id = id;
  }

  public String getText() {
    return text;
  }

  public void setText(final String text) {
    this.text = text;
  }

  @Override
  public String toString() {
    return "MessageEntity [id=" + id + ", text=" + text + "]";
  }
}

Spring DAO vs JPA Controller

Spring provides a JpaDaoSupport class for extension, but this couples your DAO objects to the Spring framework, and you have to do some pretty ugly stuff to execute your named queries:

JpaMessageDao.java

package org.adrianwalker.maven.skeleton.spring.jpa;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.support.JpaDaoSupport;

public final class JpaMessageDao extends JpaDaoSupport {

  public long count() {
    return (Long) getJpaTemplate().execute(new JpaCallback() {

      public Object doInJpa(final EntityManager em) throws PersistenceException {
        Query q = em.createNamedQuery("MessageEntity.count");
        return q.getSingleResult();
      }
    });
  }

  public void create(final MessageEntity message) {
    getJpaTemplate().persist(message);
  }

  public MessageEntity read(final long id) {
    return getJpaTemplate().find(MessageEntity.class, id);
  }

  @SuppressWarnings("unchecked")
  public List<MessageEntity> read(final int firstResult, final int maxResults) {
    return (List<MessageEntity>) getJpaTemplate().execute(new JpaCallback() {

      public Object doInJpa(final EntityManager em) throws PersistenceException {
        Query q = em.createNamedQuery("MessageEntity.find");
        q.setFirstResult(firstResult);
        q.setMaxResults(maxResults);
        return q.getResultList();
      }
    });
  }

  public MessageEntity update(final MessageEntity message) {
    return getJpaTemplate().merge(message);
  }

  public void delete(final MessageEntity message) {
    getJpaTemplate().remove(message);
  }
}

A much neater alternative is to use a JPA style controller which gives you direct access to the EntityManager. The @PersistenceContext annotation is understood by Spring and your entity manager is injected into the controller class.

MessageJpaController.java

package org.adrianwalker.maven.skeleton.spring.jpa;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.PersistenceContext;

public class MessageJpaController {

  @PersistenceContext(unitName = "messagePersistenceUnit")
  private EntityManager em;

  public long count() {
    Query q = em.createNamedQuery("MessageEntity.count");
    return (Long) q.getSingleResult();
  }

  public void create(MessageEntity messageEntity) {
    em.persist(messageEntity);
  }

  public MessageEntity read(final long id) {
    return em.find(MessageEntity.class, id);
  }

  @SuppressWarnings("unchecked")
  public List<MessageEntity> read(int firstResult, int maxResults) {
    Query q = em.createNamedQuery("MessageEntity.find");
    q.setFirstResult(firstResult);
    q.setMaxResults(maxResults);
    return q.getResultList();
  }

  public MessageEntity update(MessageEntity messageEntity) {
    return em.merge(messageEntity);
  }

  public void delete(final MessageEntity message) {
    em.remove(message);
  }
}

Usage & Tests

And finally here are some JUnit 4 tests for both the DAO and Controller.

MessageTest.java

package org.adrianwalker.maven.skeleton.spring.jpa;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:context.xml" })
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
@Transactional
public final class MessageTest {

  @Autowired
  private MessageJpaController messageJpaController;
  
  @Autowired
  private JpaMessageDao jpaMessageDao;
   
  @Test
  public void daoCreate() throws Exception {
    
    for (int i = 1; i <= 10; i++) {
      jpaMessageDao.create(new MessageEntity(String.format("Message %s", i)));
    }

    assertEquals(10, jpaMessageDao.count());
  }

  @Test
  public void daoRead() throws Exception {
    List<MessageEntity> messages = jpaMessageDao.read(1, 2);
    assertNotNull(messages);
    assertEquals(2, messages.size());
  }  
  
  @Test
  public void daoUpdate() throws Exception {
    
    MessageEntity message = jpaMessageDao.read(1);

    assertNotNull(message);
    assertEquals("Message 1", message.getText());

    message.setText("Message X");
    message = jpaMessageDao.update(message);

    message = jpaMessageDao.read(1);
    assertEquals("Message X", message.getText());
  }

  @Test
  public void daoDelete() throws Exception {
    long beforeCount = jpaMessageDao.count();
    assertTrue(beforeCount == 10);

    for (int i = 1; i <= 10; i++) {
      MessageEntity message = jpaMessageDao.read(i);
      jpaMessageDao.delete(message);
    }

    long afterCount = jpaMessageDao.count();
    assertTrue(afterCount == 0);
  }
  
  @Test
  public void controllerCreate() throws Exception {    

    for (int i = 11; i <= 20; i++) {
      messageJpaController.create(new MessageEntity(String.format("Message %s", i)));
    }

    assertEquals(10, messageJpaController.count());
  }

  @Test
  public void controllerRead() throws Exception {
    List<MessageEntity> messages = messageJpaController.read(1, 2);
    
    assertNotNull(messages);
    assertEquals(2, messages.size());
  }    
  
  @Test
  public void controllerUpdate() throws Exception {
    MessageEntity message = messageJpaController.read(11);

    assertNotNull(message);
    assertEquals("Message 11", message.getText());

    message.setText("Message X");
    message = messageJpaController.update(message);

    message = messageJpaController.read(11);
    assertEquals("Message X", message.getText());
  }

  @Test
  public void controllerDelete() throws Exception {
    long beforeCount = messageJpaController.count();
    assertTrue(beforeCount == 10);

    for (int i = 11; i <= 20; i++) {
      MessageEntity message = messageJpaController.read(i);
      messageJpaController.delete(message);
    }

    long afterCount = messageJpaController.count();
    assertTrue(afterCount == 0);
  }  
}

Don't Believe The Hype

So basically, for me anyway, using Spring in conjunction with JPA gives you nothing above and beyond using JPA directly. By the the time you decide not to bother with JpaDaoSupport, all that has been achieved is moving connection properties form persistence.xml to context.xml, which just creates more Spring configuration XML clutter.

Spring recognising the @PersistenceContext is a nice touch for testing, but using constructor/setter injection to inject an EntityManager into a JPA controller class is no big deal if you don't want to use spring.

Source Code

Wednesday, 18 August 2010

Using Ordnance Survey OpenData Street View Rasters With GeoServer

Getting the data

The Ordnance Survey OpenData can be downloaded or ordered on DVD from here. I thought I'd order the lot on DVD since its free and it would save my bandwidth and time burning gigs of data to disc.

The data comes on EcoDisc DVDs, packaged in cardboard sleeves:

For this post I'll only be using data on disc 1/6 and 3/6 on the OS Street View discs.

Getting GeoServer

GeoServer stable release can be downloaded here. I punted for the binary download format, because I want to run GeoServer on Linux. After unzipping and starting GeoServer, you should be able to browse to http://localhost:8080/geoserver/web/ and log in using the default username/password:

admin/geoserver

Using the Street View Rasters

First we need to decide what set of tiles we want to use. I only want maps for York and the surrounding area, so using the grid map:

I can see I only want to use the SE data.

Disc 3 of the OS Street View set contains the tif image files I want, located in the directory:

data/se
The files need to be coppied to a location in GeoServers data directory tree. I coppied the images to:
geoserver-2.0.2/data_dir/data/OpenData/StreetView/se

The image files aren't GeoTIFFs, so need geo-referencing data not contained in the image file. This information is held on the disc 1 of the OS Street View set, in the directory:

data/georeferencing files/TFW
We only need the files which start with se, and these need to be copied along side the images in the data directory:
geoserver-2.0.2/data_dir/data/OpenData/StreetView/se
We also need to make sure that the file extension of the tfw is lower cased, using a Linux shell:
rename .TFW .tfw *.TFW
We should now have a directory containing .tif image files and .tfw world files. Each of the tif/tfw pairs needs a file containing projection information before it can be loaded into GeoServer. The files aren't supplied with the raster data, but they are simple to create. The name of the file must match the name of the tif/tfw, and each of the files must contain the same data:

PROJCS["OSGB 1936 / British National Grid", GEOGCS["OSGB 1936", DATUM["OSGB_1936", SPHEROID["Airy 1830",6377563.396,299.3249646, AUTHORITY["EPSG","7001"]], AUTHORITY["EPSG","6277"]], PRIMEM["Greenwich",0, AUTHORITY["EPSG","8901"]], UNIT["degree",0.01745329251994328, AUTHORITY["EPSG","9122"]], AUTHORITY["EPSG","4277"]], UNIT["metre",1, AUTHORITY["EPSG","9001"]], PROJECTION["Transverse_Mercator"], PARAMETER["latitude_of_origin",49], PARAMETER["central_meridian",-2], PARAMETER["scale_factor",0.9996012717], PARAMETER["false_easting",400000], PARAMETER["false_northing",-100000], AUTHORITY["EPSG","27700"], AXIS["Easting",EAST], AXIS["Northing",NORTH]]

You can create the files by hand, or running the following Python script in the directory containing the .tif files will do it for you:

import glob

content = 'PROJCS["OSGB 1936 / British National Grid", GEOGCS["OSGB 1936", DATUM["OSGB_1936", SPHEROID["Airy 1830",6377563.396,299.3249646, AUTHORITY["EPSG","7001"]], AUTHORITY["EPSG","6277"]], PRIMEM["Greenwich",0, AUTHORITY["EPSG","8901"]], UNIT["degree",0.01745329251994328, AUTHORITY["EPSG","9122"]], AUTHORITY["EPSG","4277"]], UNIT["metre",1, AUTHORITY["EPSG","9001"]], PROJECTION["Transverse_Mercator"], PARAMETER["latitude_of_origin",49], PARAMETER["central_meridian",-2], PARAMETER["scale_factor",0.9996012717], PARAMETER["false_easting",400000], PARAMETER["false_northing",-100000], AUTHORITY["EPSG","27700"], AXIS["Easting",EAST], AXIS["Northing",NORTH]]'

tifs = glob.glob('*.tif')

for tif in tifs:
  prj = tif.split('.')[0] + '.prj'
  file = open(prj,'w')
  file.writelines(content)
  file.close()


If you have a data directory with files that look a bit like this, then you're ready to load them into GeoServer:

  1. Load GeoServer up in a browser http://localhost:8080/geoserver/web/ and login. Click the 'Workspaces' link in the 'Data' section of the left hand navigation bar. Now click the 'Add new workspace' link.

  2. Name the workspace OpenData and give it the URI https://www.ordnancesurvey.co.uk/, and click save.

  3. Click the 'Stores' link in the 'Data' section of the left hand navigation bar. Now click the 'Add new Store' link. Under the 'Raster Data Sources' heading, click the 'ImageMosaic' link.

  4. Select the OpenData workspace, name the data source OS Street View SE and point the URL connection parameter to the data directory:
    file:data/OpenData/StreetView/se
    and then click save.

  5. You should be forwarded to the 'New Layer chooser page', click the 'Publish' link next to the 'se' layer in the table.

  6. About halfway down the page there should be inputs for 'Native SRS' and 'Declared SRS', make sure they both contain:
    EPSG:27700
    and click the 'Compute from data' and 'Compute from native bounds' links.

  7. Finally click save.

If all went well you should be able to use GeoServers 'Layer Preview' built in OpenLayers client to view the map:

Source Code

Friday, 13 August 2010

ColdFusion Is Dead (To Me)

So as from today I never have to program any ColdFusion again, it feels pretty good. ColdFusion just doesn't knock my frock off, it never did, and it probably never will.

This isn't one of those ColdFusion is dead, or ColdFusion sucks rants, those things aren't really my call, and besides, I can't be bothered to deal with ColdTard butthurt on my blog.

A Helmet

All I really know is that programming in CF made me feel a lot like this picture, and you secretly know it makes you feel like this too:

Saturday, 26 June 2010

GlassFish Security Review

GlassFish is Sun Microsystems open source application server. It is a competitor to Jboss AS and Apache Geronimo in the open source arena, and is my app server of choice.

Packt Publishing requested that I review one of their latest titles on the subject of GlassFish: GlassFish Security by Masoud Kalali, available to buy from Packt's web site.

I first took a look at GlassFish around 2007 whilst investigating EJB 3.0 and container managed persistence using JPA. Since then GlassFish has been my favourite platform for building web applications and web services, backed by EJB and JPA, sometimes taking advantage of GlassFish's load balancing and clustering features and excellent integration with other open source projects.

GlassFish Security has been a worth while read, adding to my awareness and knowledge of Java EE security best practices. I will definitely be applying the information presented in the book to current projects and future system design and development work.

GlassFish Security covers a very wide range of security topics, some of which will be applicable to web applications deployed on any JEE application server, whilst others are GlassFish and even host operating system specific.

The book doesn't just focus on programmatic security, making use of security APIs, annotations and XML configuration, but takes more of a complete systems view. OS and network security constraints, as well as enterprise wide system architecture considerations are explored.

The book is targeted at developers and system administrators, who have a sound footing working with JEE application servers, EJB development and have a working knowledge of Linux. To fully take advantage of this book you should know your way around the latest versions of GlassFish and probably NetBeans, have a Debian or Ubuntu install available, and have a keen interest in designing systems with security built in from the start.

The title of the book could quite easily have been GlassFish Security with OpenDS and OpenSSO, as they feature heavily in the later chapters. If your project has no need to interact with an LDAP server, or your organisation has no strategy for a single sign on solution or identity federation management, then these chapters may not be useful to you.

The book starts out from first principals with an overview of Java EE architecture and application modularisation and deployment. It's a slow start for an audience with experience of developing enterprise Java applications, but it establishes common terminology and is a good starting point to introduce fundamental security topics from.

The pace quickly picks up, security concepts such as authentication and authorisation, programmatic EJB security, XML configuration vs annotations, and roles, principals and groups are explained and demonstrated.

Covered next are the default security realms available to GlassFish and how to implementing custom realms and authentication methods.

A source code download for this and subsequent chapters is provided, although currently the source code for chapter two seems to be a duplicate of chapter three. Also, the book states that the build and deployment system used for the source is Maven, which it isn't. The source comes with standard NetBeans project files which use Ant for build and deployment.

Chapter three is probably the most useful for developers starting out with EJB development and web application security, and where the first real bit of programming starts. The chapter guides us through the end-to-end development and deployment of a JEE web application. The code uses a JPA persistence layer for accessing a MySQL database, a servlet containing some business logic and a simple JSP front end. Security constraints are are applied to the application, with authentication and authorisation done via interaction with a file security realm.

Some Linux administration knowledge is required for the next chapter concerned with locking down security on the host operating system and Java virtual machine. The examples given are intended for Debian based Linux distributions and consist of configuring user, file system, disk quota, network interface and port restrictions. JVM and GlassFish policy file configuration are explored, as well as a discussion on the advantages of enabling default auditing modules.

Naturally following on from the previous chapter, chapter five is concerned with configuring the GlassFish server itself, both from the command line and the admin interface. Restricting the IP addresses authorised to access network listeners and isolating applications using virtual servers are covered.

From chapter six onwards the book takes more of an architectural approach to security considerations.

This chapter describes to us the hierarchical nature of security data, and why it might not be best stored in a relational database, and instead in a directory service. OpenDS, an open source LDAP server is introduced, and its installation, administration, configuration and integration with our applications are explored.

Chapters seven, eight and nine, the remainder of the book, revolve around another open source project OpenSSO. OpenSSO is a single sign on solution which integrates seamlessly with GlassFish. Useful topics from chapter seven include using RESTful calls to the OpenSSO API to authenticate and authorise users.

Chapter eight introduces SSO Agents and filters configured in an applications web.xml to intercept calls and apply security measures. OpenSSO allows for very fine grained access controls which require no changes to application code and can be managed all from one place, very useful stuff that I'd like to take advantage of in future systems.

Finally, chapter nine builds on how to use OpenSSO in conjunction with a Web Services Agent to secure a simple SOAP web service deployed on GlassFish.

Overall this is a good book, covering a much wider range of security aspects than I expected. It gives you a great starting point on a breadth of topics but doesn't get to cover them in great depth.

As a developer I would have liked to see more advanced examples for chapters one to five, really getting to the nitty gritty of some real world examples. Maybe some advice on good practice when faced with tough design choices, how to avoid common pitfalls, security patterns and anti-patterns; the sort off stuff above and beyond what you might get from online GlassFish tutorials and Javadoc.

OpenSSO probably deserves a book in its own right, and although I have no immediate application for the information in the chapters that feature it, I'm glad I read them and now have a basic understanding to build on in the future. GlassFish Security benefits form these inclusions and they help it to be the comprehensive introduction to security that it is.

I was disappointed that source code printed in the book and available for download occasionally contained errors and wasn't supplied with Maven build scripts. These things slightly reduce the quality of an otherwise well written and well structured book.

I will definitely be implementing some of the information presented in this book in future Enterprise Java projects; I'll always consider the pros and cons of using a directory server before storing user credentials in relational tables; and GlassFish Security will be my first reference when considering system security design and implementation.

Downloads From Packt

Source

Here is some of the Packt example code repackaged as Maven projects.

Errata

Here are some errors I found in the printed code and xml configuration. Check the Packt support page for a complete listing.

  • Page 22 - missing closing XML tag </web-resource-name>.
  • Page 32 - missing double quotes and comma for @DeclareRoles annotation parameters.
  • Page 50 - missing single quotes around manager on second sql insert statement.
  • Page 85 - empty, unused method proccessRequest in Converter servlet.
  • Page 237 - stringEcho method annotation should be @WebMethod.

Wednesday, 21 April 2010

map, foldr & foldl higher-order functions in Java

Here are my implementations of some higher-order functions in java, foldl, foldr, map and others.

Functionals.java

package org.adrianwalker.functional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public final class Functionals {

  private static final String EMPTY_STRING = "";
  private static final List EMPTY_LIST = Collections.EMPTY_LIST;

  private Functionals() {
  }

  public static <T1, T2> T2 foldr(final Function<T1, T2> f, final T2 b, final List<T1> lst) {
    if (lst.isEmpty()) {
      return b;
    }

    return f.call(head(lst), foldr(f, b, tail(lst)));
  }

  public static <T1, T2> T2 foldl(final Function<T1, T2> f, final T2 b, final List<T1> lst) {
    if (lst.isEmpty()) {
      return b;
    }

    return foldl(f, f.call(head(lst), b), tail(lst));
  }

  public static <T1, T2> List<T2> map(final Function<T1, T2> f, final List<T1> lst) {
    return foldr(new Function<T1, List<T2>>() {

      @Override
      public List<T2> call(final T1 t1, final List<T2> t2) {
        return cons(f.call(t1), t2);
      }
    }, (List<T2>) EMPTY_LIST, lst);
  }

  public static <T1> List<T1> cons(final T1 x, final List<T1> xs) {
    List<T1> lst = newList(xs.size() + 1);
    lst.add(0, x);
    lst.addAll(1, xs);
    return Collections.unmodifiableList(lst);
  }

  public static <T1> T1 head(final List<T1> lst) {
    return lst.get(0);
  }

  public static <T1> List<T1> tail(final List<T1> lst) {
    List<T1> xs = newList(lst.size() - 1);
    xs.addAll(0, lst.subList(1, lst.size()));
    return Collections.unmodifiableList(xs);
  }

  public static List<Character> explode(final String string) {
    if (string.isEmpty()) {
      return (List<Character>) EMPTY_LIST;
    }

    return cons(string.charAt(0), explode(string.substring(1)));
  }

  public static String implode(final List<Character> lst) {
    return foldl(new Function<Character, String>() {

      @Override
      public String call(final Character t1, final String t2) {
        return t2 + t1;
      }
    }, EMPTY_STRING, lst);
  }

  public static <T1> List<T1> rev(final List<T1> lst) {
    return foldl(new Function<T1, List<T1>>() {

      @Override
      public List<T1> call(final T1 t1, final List<T1> t2) {
        return cons(t1, t2);
      }
    }, (List<T1>) EMPTY_LIST, lst);
  }

  private static <E> List<E> newList(final int initialCapacity) {
    return new ArrayList<E>(initialCapacity);
  }
}

Example Usage

Summing a list of integers using foldr.

List<Integer> input = Arrays.asList(new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10});

Integer output = Functionals.foldr(new Function<Integer, Integer>() {

  @Override
  public Integer call(final Integer t1, final Integer t2) {
    return t1 + t2;
  }
}, 0, input);

System.out.println(String.format("Sum: %s", output));

Source Code

Download the source and see the unit tests for other examples of usage.

Monday, 12 April 2010

ColdFusion Head First Design Patterns: Decorator

Continuing in this design patterns series taken from Head First Design Patterns, is a ColdFusion implementation of the Decorator Pattern.

Abstract Beverage

Beverage.cfc

<cfcomponent output="false">

  <cfset VARIABLES.description = "Unknown Beverage">
  
  <cffunction access="public" returntype="string" name="getDescription">
    <cfreturn VARIABLES.description>
  </cffunction>

  <cffunction access="public" returntype="numeric" name="cost" >    
  </cffunction>

</cfcomponent>

Abstract Decorator

CondimentDecorator.cfc

<cfcomponent extends="Beverage" output="false">
  
  <cffunction access="public" returntype="string" name="getDescription">
  </cffunction>
  
</cfcomponent>

Concrete Beverages

HouseBlend.cfc

<cfcomponent extends="Beverage" output="false">

  <cffunction access="public" name="init" returntype="HouseBlend">
    <cfset VARIABLES.description = "House Blend Coffee">
    
    <cfreturn THIS>
  </cffunction>  

  <cffunction access="public" returntype="numeric" name="cost" >
    <cfreturn 0.89>    
  </cffunction>  

</cfcomponent>

Espresso.cfc

<cfcomponent extends="Beverage">

  <cffunction access="public" name="init" returntype="Espresso">
    <cfset VARIABLES.description = "Espresso">
    
    <cfreturn THIS>
  </cffunction>

  <cffunction access="public" returntype="numeric" name="cost" >
    <cfreturn 1.99>    
  </cffunction>
  
</cfcomponent>

Concrete Decorators

Mocha.cfc

<cfcomponent extends="CondimentDecorator">

  <cffunction access="public" name="init" returntype="Mocha">
    <cfargument type="Beverage" name="beverage">
    
    <cfset VARIABLES.beverage = ARGUMENTS.beverage>
    
    <cfreturn THIS>
  </cffunction>

  <cffunction access="public" returntype="string" name="getDescription">
    <cfreturn VARIABLES.beverage.getDescription() & ", Mocha">
  </cffunction>

  <cffunction access="public" returntype="numeric" name="cost" >
    <cfreturn 0.20 + VARIABLES.beverage.cost()>
  </cffunction>

</cfcomponent>

Test Page

StarbuzzCoffee.cfm

<cfset beverage = createObject("component", "Espresso").init()>

<cfset beverage2 = createObject("component", "HouseBlend").init()>
<cfset beverage2 = createObject("component", "Mocha").init(beverage2)>
<cfset beverage2 = createObject("component", "Mocha").init(beverage2)>

<cfoutput>
  #beverage.getDescription()# $#beverage.cost()#
  <br />
  #beverage2.getDescription()# $#beverage2.cost()#
</cfoutput>

Source Code

Thursday, 8 April 2010

ColdFusion Builder Crack

ColdFusion Builder has been my weapon of choice for writing CFML since it has been in beta and free. Now it's at version 1.0.0, and Adobe has decided to charge $299 for it, I think I'll be going back to CFEclipse.

Shouldn't Adobe be trying to build it's user base by giving CFBuilder away for free? Even Microsoft has got in on the act with it's Express tools.

I also find it quite a poor show that Adobe has taken an Open Source project, Eclipse, added very little to it, re-branded it and is trying to charge the CF developer community, who are inexplicably loyal to Adobe, $299 a pop for it.

So just for shits and giggles here is how you might crack CFBuilder to continue using it for free.

You will need:-

  1. ColdFusion Builder Trial
  2. JD-GUI Java Decompiler
  3. 7-Zip

If you installed CFBuilder in the default location, the class files we need to modify are in:

C:\Program Files\Adobe\Adobe ColdFusion Builder\plugins\com.adobe.ide.coldfusion.common_1.0.0.271911.jar

Start the decompiler and open the above JAR file. The class we need to edit is:

com.adobe.ide.coldfusion.common.util.TestUtil.class

Navigate to the TestUtil class, the JD decompiler produces the following code:

TestUtil.java

package com.adobe.ide.coldfusion.common.util;

import com.adobe.ide.amt.Activator;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Timer;
import java.util.TimerTask;
import org.eclipse.core.runtime.Platform;
import org.eclipse.swt.widgets.Display;

public class TestUtil
{
  private Calendar _expDate = null;
  private Calendar _installDate = null;
  private int _evalDays = 30;
  private boolean _expired = false;
  private File _hiddenFile = null;
  private static final long MAGIC = -889275714L;
  private String _code = null;
  private boolean isBeta = true;
  private static final TestUtil instance = new TestUtil();
  private boolean isCheckDone = false;
  private boolean isValidLicense = false;
  private static final Object lockObject = new Object();
  private boolean cfbStartupPluginLoaded = false;

  public static final Object getLockObject() {
    return lockObject;
  }

  public static TestUtil getInstance() {
    return instance;
  }

  private TestUtil()
  {
    Timer timer = new Timer();

    TimerHelper timerTask = new TimerHelper(null);

    timer.schedule(timerTask, 150000L);

    this._expDate = Calendar.getInstance();
    this._expDate.set(2010, 2, 30);
    checkExpired();
  }

  static Long encodeDate(long time) {
    return Long.valueOf(0xCAFEBABE ^ (time >>> 32 | time << 32));
  }

  private void setCode() {
    Calendar now = Calendar.getInstance();
    this._code = encodeDate(now.getTime().getTime()).toString();
  }

  private void checkExpired() {
    if (!this.isBeta) {
      this._expired = false;
      return;
    }

    setHiddenFile();
    if (!hiddenFileExists()) {
      createFileIfNeeded();
    }

    setHiddenProps();
    if (!checkHiddenFile())
      this._expired = true;
  }

  private void createFileIfNeeded()
  {
    Process p = null;
    setCode();
    try {
      PrintWriter out = new PrintWriter(
        new BufferedWriter(new OutputStreamWriter(new FileOutputStream(this._hiddenFile))));
      out.println(this._code);
      out.close();
      if (!File.separator.equalsIgnoreCase("\\")) {
        break label99;
      }

      String command = "attrib +H " + this._hiddenFile.getPath();
      p = Runtime.getRuntime().exec(command);
      label99: p.waitFor();
    }
    catch (Exception localException) {
    }
    finally {
      if (p != null)
        p.destroy();
    }
  }

  private int getDaysDiffFromHiddenFile()
  {
    int _installYear = this._installDate.get(1);
    int _expYear = this._expDate.get(1);
    int yearDiff = _expYear - _installYear;

    return this._expDate.get(6) - 
      this._installDate.get(6) + 365 * yearDiff;
  }

  private void emptyHiddenFile() {
    Process p = null;
    try {
      this._hiddenFile.delete();
      this._hiddenFile.createNewFile();
      if (!File.separator.equalsIgnoreCase("\\")) {
        break label66;
      }

      String command = "attrib +H " + this._hiddenFile.getPath();
      p = Runtime.getRuntime().exec(command);
      label66: p.waitFor();
    }
    catch (Exception localException) {
    }
    finally {
      if (p != null)
        p.destroy();
    }
  }

  private boolean checkHiddenFile()
  {
    this._installDate = Calendar.getInstance();
    if (!isEmpty(this._code)) {
      this._installDate.setTime(decodeDate(Long.parseLong(this._code)));
      this._evalDays = getDaysDiffFromHiddenFile();
      if (getEvalDaysLeftForBeta() <= 0L) {
        this._expired = true;
      }

      return true;
    }
    return false;
  }

  private void checkSystemDate() {
    this._evalDays = getDaysDiffFromBeta();
    if (this._evalDays <= 0)
      this._expired = true;
  }

  private boolean hiddenFileExists()
  {
    return this._hiddenFile.exists();
  }

  private boolean isEmpty(String s)
  {
    return (s == null) || (s.length() == 0);
  }

  static final Date decodeDate(long code) {
    Date d = null;
    if (code != 0L) {
      code = 0xCAFEBABE ^ code;
      long time = code << 32 | code >>> 32;
      d = new Date(time);
    }
    return d;
  }

  private void setHiddenProps() {
    try {
      BufferedReader br = new BufferedReader(new FileReader(this._hiddenFile));
      String line = br.readLine();

      if (!isEmpty(line)) {
        this._code = line;
      }
      br.close();
    }
    catch (Exception localException) {
    }
  }

  private void setHiddenFile() {
    if (File.separator.equalsIgnoreCase("\\"))
    {
      String _hiddenfilename = getSystemDrive() + "\\.tolb3755.bin";
      this._hiddenFile = new File(_hiddenfilename);
    } else {
      String _hiddenfilename = getUnixHome() + "/.tolb3755.bin";
      this._hiddenFile = new File(_hiddenfilename);
    }
  }

  private String getEnv(String envvar)
  {
    Map variables = System.getenv();
    String value = "";
    for (Map.Entry entry : variables.entrySet()) {
      String name = (String)entry.getKey();
      value = (String)entry.getValue();
      if (name.equalsIgnoreCase(envvar.toUpperCase())) {
        break;
      }
    }
    return value;
  }

  private String getUnixHome()
  {
    return getEnv("HOME");
  }

  private String getSystemDrive() {
    return getEnv("SYSTEMDRIVE");
  }

  private int getDaysDiffFromBeta()
  {
    Calendar now = Calendar.getInstance();
    now.setTime(new Date());
    int _nowYear = now.get(1);

    int _expYear = this._expDate.get(1);

    int yearDiff = _expYear - _nowYear;

    int daysLeft = this._expDate.get(6) - 
      now.get(6) + 365 * yearDiff;
    return daysLeft;
  }

  public long getEvalDaysLeftForBeta()
  {
    int daysLeft = getDaysDiffFromBeta();
    if (daysLeft < 0)
      daysLeft = 0;
    return daysLeft;
  }

  public boolean isExpired() {
    return this._expired;
  }

  public boolean isValidAtStartup()
  {
    return isValidHelper(true);
  }

  public boolean isValid() {
    return isValidHelper(false);
  }

  public boolean isValidHelper(boolean calledFromStartup) {
    synchronized (getLockObject()) {
      if (this.isCheckDone) {
        return this.isValidLicense;
      }
    }
    return validate(calledFromStartup);
  }

  private boolean validate(boolean calledFromStartup)
  {
    if (!calledFromStartup)
    {
      return true;
    }

    synchronized (getLockObject())
    {
      try {
        if (this.isCheckDone)
          break label56;
        this.cfbStartupPluginLoaded = true;
        Activator.AMT_Initialize();
        int iProductActionIndicator = Activator.AMT_ObtainLicense(
          "ColdFusionBuilder_Base", 1, 0);
        label56: if (iProductActionIndicator > 1)
          this.isValidLicense = false;
        else {
          this.isValidLicense = true;
        }

      }
      catch (Throwable localThrowable)
      {
        this.isValidLicense = false;
      } finally {
        this.isCheckDone = true;
      }

      return this.isValidLicense;
    }
  }

  private class TimerHelper extends TimerTask
  {
    private TimerHelper()
    {
    }

    public void run()
    {
      try
      {
        if (TestUtil.this.cfbStartupPluginLoaded) {
          break label58;
        }
        Runnable task = new Runnable()
        {
          public void run()
          {
            TestUtil.this.isValidHelper(true);
          }
        };
        if (Platform.getOS().equalsIgnoreCase("macosx"))
        {
          Display.getDefault().syncExec(task);
        }
        else
        {
          Display display1 = new Display();
          display1.syncExec(task);
          label58: display1.dispose();
        }

      }
      catch (Throwable localThrowable)
      {
      }
      finally
      {
        TestUtil.this.isCheckDone = true;
      }
    }
  }
}

What we want to do is remove any validation logic and always return values indicating the the license is valid. After a bit of editing, your new TestUtil.java should look something like:

TestUtil.java

package com.adobe.ide.coldfusion.common.util;

import java.util.Date;

public class TestUtil {
  private static final TestUtil instance = new TestUtil();
  private static final Object lockObject = new Object();

  public static final Object getLockObject() {
    return lockObject;
  }

  public static TestUtil getInstance() {
    return instance;
  }

  private TestUtil() {
  }

  static Long encodeDate(long time) {
    return Long.valueOf(0xCAFEBABE ^ (time >>> 32 | time << 32));
  }

  static final Date decodeDate(long code) {
    Date d = null;
    if (code != 0L) {
      code = 0xCAFEBABE ^ code;
      long time = code << 32 | code >>> 32;
      d = new Date(time);
    }
    return d;
  }

  public long getEvalDaysLeftForBeta() {
    return 1;
  }

  public boolean isExpired() {
    return false;
  }

  public boolean isValidAtStartup() {
    return true;
  }

  public boolean isValid() {
    return true;
  }

  public boolean isValidHelper(boolean calledFromStartup) {
    return true;
  }
}

Recompile this class, and using 7-Zip, replace the old class in:

C:\Program Files\Adobe\Adobe ColdFusion Builder\plugins\com.adobe.ide.coldfusion.common_1.0.0.271911.jar

with the one you just compiled.

Now just start ColdFusion Builder and the registration screen should not appear.

As always with this type of thing, I won't be held responsible for anyone actually doing this, it's naughty and you might get a telling off, so don't do it. Either pay for CFBuilder or go download CFEclipse for free.