Java Reflection & Constructor Varargs

I had a spot of trouble getting reflection to work with a Vararg constructor. Without being entirely sure, I think this is because Generics are implemented by type erasure whereby the type information is only available at compile time. At runtime i.e. when the Reflection API is invoked, the type information has been erased by the compiler. It looks as though this is the case to ensure legacy backwards compatibility.

Anyway, the trick with the code below was to double-wrap the constructor argument array ‘y’ in another Object array ‘z’, which isn’t clear at compile-time. This avoids an IllegalArgumentException: wrong number of arguments exception.

public A1C0(final List<RoomStream>... occupancyLevels) {
    // constructor
}
public static void main(String[] args) throws Exception {
    final List<RoomStream> a = new ArrayList<RoomStream>();
    final List<RoomStream> b = new ArrayList<RoomStream>();
    final Class[] x = {List[].class};
    final List[] y = {a, b, d, e};
    final Object[] z = {y};
    final Constructor c = getClass().getConstructor(x);
    final Object o = c.newInstance(z);
    System.out.println(o);
}

Tags:

Author:     Thursday, November 12th, 2009 Code No Comments

Agile Culture

I’ve read a couple of posts recently which I thought I would pass on as I thought most helpful.

Mark Schumann discusses some of the problems an Agile team might face in terms of external pressures.

And Jeff Patton explains why thinking of Agile as a culture and not just a process explains the resistance and difficulty in teaching and learning the approach within an organisation.

Both impressed me so much I even commented which means they must have struck a chord!

And they’ve both got cartoons on them which is cool ;o)

Tags: ,

Author:     Friday, October 23rd, 2009 Agile No Comments

Agile Evolution

Charles Darwin: “It is not the strongest of the species that survive, nor the most intelligent, but the one most responsive to change.”

Author:     Tuesday, September 8th, 2009 Code No Comments

Agile Hype?

There is now a lot of “hype” around the Agile development methodology, possibly because it’s producing better results than traditional approaches, or perhaps it just makes people’s working lives more interesting and challenging?

Either way, I read an agile101 post suggesting that ‘doing’ agile is a sign of incompetence which put my hackles up as you might expect, given that I’m a keen advocate. But the article makes an extremely pertinent point which I’d like to stress – that Agile is only something you are going to ‘become’ with plenty of practice. Picking up a book is a good place to start but that’s all it is… Agile development is an intuitive mindset, not a bunch of rules you can follow and hope to immediately be good at.

It also struck me that as Agile has gathered pace there are now many different ways of wrapping lots of processes and metrics, management techniques and so on around the basic concepts. In my opinion this in many ways detracts from the fundamentals that are ultimately going to help you deliver, and feel these demands can actually make a team less agile as the post suggests.

Here’s my mantra, if I can call it that, which I try and religiously stick to whilst leading Agile software development teams:

  • Focus, focus, focus – if it doesn’t make the boat go faster then save it for another day.
  • Refactor, refactor, refactor – even the smartest and most experienced developers rarely get it bang-on first time around, especially given that priorities and requirements are often less than stable.
  • Challenge the business sponsor and requirements – often I’ve found that requirements are over-complicated for the problem at hand. Get to the root of the issue, understand it, and then propose simpler alternatives which actually address the real issue.
  • Aim for the best in every single line of code and development practice if you can – look after all the little things and the big things will take care of themselves!

Sure, there are many tips and suggestions that can help you and your team to a place where you are able to “move light, travel fast” but as a Technical Lead or Architect (as opposed to Project Manager, say) I think it’s more important to get an intuitive “feel” for what’s a true value-add.

Although you’ll probably have to compromise at times on some of the points mentioned above, they’ve been great cornerstones for me when I feel there are too many demands on my time from what I consider to be less important techniques or deliverables.

Tags: ,

Author:     Tuesday, August 25th, 2009 Agile, Code, Development, Management No Comments

Incompetent Managers

Whether you have any pretensions of becoming a “Manager” or otherwise, the following post will probably be widely recognised by many in senior positions, and hopefully will be helpful to either those that aren’t or want to be. I doubt that the points mentioned are restricted to just the Technology industry.

I’m currently classified as a “Manager” in that I have leadership responsibilities, though prefer to roll my sleeves up and make sure I am contributing significantly towards results, as well as guiding those around me to help them make the correct decisions. I guess I prefer the term “Leader” and the connotations that brings with all the differences between the two titles.

Author:     Wednesday, August 5th, 2009 Management No Comments

Hibernate’s @FilterJoinTable

Couldn’t find a completely articulate example or full documentation of how to add a filter to a Hibernate Many-to-Many collection association mapping, so thought I’d would post a complete example here.

It’s possible to apply the filter to the target entity table which is reasonably well documented, or at least you can have an educated guess, but also to the association table of the Many-to-Many relationship where the docs were a little less clear.

I have the following relational association table:

CREATE TABLE departure_point_resort_association (
  departure_point_id      VARCHAR(36) NOT NULL,
  resort_id               VARCHAR(36) NOT NULL,
  site_id                 ENUM('30', '31'...) NOT NULL,
  PRIMARY KEY (departure_point_id, resort_id),
  CONSTRAINT assoc_departure_point_fk FOREIGN KEY (departure_point_id)
    REFERENCES departure_point (id),
  CONSTRAINT assoc_resort_fk FOREIGN KEY (resort_id) REFERENCES resort (id)
);

which is mapping a ski resort to potential departure points or airports. There was no real requirement to persist an actual SITE table (which would be entirely static data) and to map to it’s foreign key value, so instead am using a simple MySQL ENUM column above, and wanted to apply a filter at the application level to the collection of Resorts based on this site_id.

@Entity @Table
@FilterDef(name = "siteFilter", parameters = {
    @ParamDef(name = "siteId", type = "string")
})
public final class Resort extends BasePersistentObject {
    @ManyToMany(fetch = FetchType.EAGER)
    @FilterJoinTable(name = "siteFilter", condition = "site_id = :siteId")
    @JoinTable(name = "DEPARTURE_POINT_RESORT_ASSOCIATION",
            joinColumns = {
                    @JoinColumn(name = "RESORT_ID")
            },
            inverseJoinColumns = {
                    @JoinColumn(name = "DEPARTURE_POINT_ID")
            }
    )
    private Set departurePoints;

Then it’s simply a case of enabling the filter in the client (DAO or whatever your framework dictates):

session.enableFilter("siteFilter").setParameter("siteId",  String.valueOf(siteId));

Tags:

Author:     Tuesday, July 28th, 2009 Code, Database, Hibernate No Comments

Programming for grown-ups

I sent an article by Ted Dziuba of The Register around to my development team earlier this morning. As well as some well-deserved shots at Microsoft, it contained a rather acidic commentary (not like him) on the merits of the PHP programming language. Or rather lack of.

One of my colleagues replied with the following:

http://www.codexon.com/posts/php-53-adds-goto

Author:     Monday, July 20th, 2009 Code No Comments

Hibernate StatelessSession with Transactional Annotation

I have a bi-directional collection mapping in Java which I thought was causing me problems when persisting using Hibernate’s StatelessSession API.

However, it looks as though the issue was being caused by the fact I was using the @Transactional annotation instead. The API states:

“Operations performed via a stateless session bypass Hibernate’s event model and interceptors.”

I didn’t pick up on the importance of the above statement as it’s not particularly clear at first glance, but it looks as though using Annotations via AOP just isn’t supported when streaming directly to the database using the StatelessSession.

Commenting out the annotation and using a programmatic Transaction instead corrected the problem:

//    @Transactional
public List<Package> insertAvailability(final List<Package> packages) {
    final StatelessSession session = sessionFactory.openStatelessSession();
    final Transaction tx = session.beginTransaction();

    session.insert(aPackage);
    // insert collections manually etc...

    tx.commit();
    session.close();

    return packages;
}

Tags:

Author:     Monday, July 20th, 2009 Code, Database, Development 2 Comments

Tomcat ROOT.war deployment

If you wish to avoid having to deploy a web application explicitly named as ROOT.war – so that you use the default context URL “/” without having to resort to web server URL rewrites – it’s possible to do this and still maintain your application war files original name.

I thought it was worth writing about our approach to this as the Tomcat documentation isn’t particularly clear on how to achieve this.

As some background information, I work for a large FTSE100 company where a team other than the Development Team are responsible for the deployment of the application, and handing them a file called ROOT.war is a little unclear and could potentially lead to misunderstandings.

It’s possible to have the application context file point to a .war file outside of the Tomcat/webapps directory. Tomcat will then explode your war file, whatever it’s name, into the Tomcat/webapps/ROOT directory. Tomcat infers from the name of the context file that web application should be deployed as the default, accessible as root context “/”, without any need for web server URL rewrites.

<Context docBase="/<external_build_dir>/<application_name>.war" />

where <external_build_dir> can be any directory outside of Tomcat, for example your application build directory, and <application_name> can be the proper full name of your application.

If you are using Apache Ant deployment scripts, you can also make good use of a couple of features to automate this whilst maintaining naming clarity. We have a simple application context file <application_name>.xml:

<Context docBase="@DEPLOY_FILE@" />

and the associated application deployment script copies this file to the Tomcat conf directory, renaming it as ROOT.xml as so:

<copy file="${ant.project.name}.xml" tofile="${tomcat}/conf/Catalina/localhost/ROOT.xml">
  <filterset>
    <filter token="DEPLOY_FILE" value="${project.name}.war"/>
  </filterset>
</copy>

As you can see it’s also using Ant’s filter task with a token to express the location of the application war file, pointing back at the build directory.

Of course, you can still use an Apache HTTP web server RewriteRule to serve your application from “/”, but this would apply to every request served:

RewriteRule /<application_name>/(.*) /$1

BOOTNOTE: Thanks to pid-2 for pointing out my initial mistake in this post.

There’s no need to set the path attribute of the context xml file, in fact Tomcat specifically states that you should not do this. The fact that you have a context file called ROOT.xml is enough for Tomcat to infer that you wish to deploy the web application as the root “/”.

Tags: , ,

Author:     Saturday, March 21st, 2009 Tomcat 2 Comments

Primary Keys vs GUIDs

Just thought I would post some code having read Savvy Duck’s comments about the above. Although the project I refer to below was greenfield and didn’t require any kind of database migration, I never encountered any of the performance problems mentioned in some of the related articles.

We were using an Oracle 10g database however, and I’ll report an update if I see any issues with my latest project which is on MySQL and seems to have a bit of a history in this department. But it really was never an issue in any way that we recognized.

The likelihood of a primary key clash was calculated as 1 in 2.27 x 10exp32 for every one million records.

Anyway, the code. We were mapping to Java using Hibernate (avoiding the primary key problem mentioned here) like so:

public abstract class BasePersistentObject implements Serializable
{
    // will be overrriden with data read from database
    @Id
    private String id = UUID.createUUID();
}

I can provide the above UUID code if anyone wants to have a play with this implementation.

Instead of using the standard auto-increment Sequence then, the primary key was implemented with the following function:

/**
 * Returns a UID string.
 *
 * This is string based on a randomly generated bit sequence just like in the app server.
 */
CREATE OR REPLACE FUNCTION f_get_uid RETURN VARCHAR2 IS
BEGIN
	RETURN UTL_RAW.CAST_TO_VARCHAR2(
	           UTL_RAW.TRANSLATE( DBMS_CRYPTO.RANDOMBYTES(24),
	                              uid_util.uid_from_set,
	                              uid_util.uid_to_set ) );
END;
/

-- defines two constants used by f_get_uid() to generate UID strings;
CREATE OR REPLACE PACKAGE uid_util
IS
	uid_from_set CONSTANT RAW(256) := UTL_RAW.XRANGE(hextoraw('00'), hextoraw('FF'));
	uid_to_set   CONSTANT RAW(256) := UTL_RAW.CONCAT(
		UTL_RAW.CONCAT(
			UTL_RAW.XRANGE(UTL_RAW.CAST_TO_RAW('A'), UTL_RAW.CAST_TO_RAW('Z')),
			UTL_RAW.XRANGE(UTL_RAW.CAST_TO_RAW('a'), UTL_RAW.CAST_TO_RAW('z')),
			UTL_RAW.XRANGE(UTL_RAW.CAST_TO_RAW('0'), UTL_RAW.CAST_TO_RAW('9')),
			UTL_RAW.CAST_TO_RAW('-'),
			UTL_RAW.CAST_TO_RAW('_')
		),
		UTL_RAW.CONCAT(
			UTL_RAW.XRANGE(UTL_RAW.CAST_TO_RAW('A'), UTL_RAW.CAST_TO_RAW('Z')),
			UTL_RAW.XRANGE(UTL_RAW.CAST_TO_RAW('a'), UTL_RAW.CAST_TO_RAW('z')),
			UTL_RAW.XRANGE(UTL_RAW.CAST_TO_RAW('0'), UTL_RAW.CAST_TO_RAW('9')),
			UTL_RAW.CAST_TO_RAW('-'),
			UTL_RAW.CAST_TO_RAW('_')
		),
		UTL_RAW.CONCAT(
			UTL_RAW.XRANGE(UTL_RAW.CAST_TO_RAW('A'), UTL_RAW.CAST_TO_RAW('Z')),
			UTL_RAW.XRANGE(UTL_RAW.CAST_TO_RAW('a'), UTL_RAW.CAST_TO_RAW('z')),
			UTL_RAW.XRANGE(UTL_RAW.CAST_TO_RAW('0'), UTL_RAW.CAST_TO_RAW('9')),
			UTL_RAW.CAST_TO_RAW('-'),
			UTL_RAW.CAST_TO_RAW('_')
		),
		UTL_RAW.CONCAT(
			UTL_RAW.XRANGE(UTL_RAW.CAST_TO_RAW('A'), UTL_RAW.CAST_TO_RAW('Z')),
			UTL_RAW.XRANGE(UTL_RAW.CAST_TO_RAW('a'), UTL_RAW.CAST_TO_RAW('z')),
			UTL_RAW.XRANGE(UTL_RAW.CAST_TO_RAW('0'), UTL_RAW.CAST_TO_RAW('9')),
			UTL_RAW.CAST_TO_RAW('-'),
			UTL_RAW.CAST_TO_RAW('_')
		)
	);
END;
/
Author:     Sunday, March 1st, 2009 Database 1 Comment

Agile CTO