Saturday, July 04, 2026

Open Data plus Busy Claude = Nice Maps

Swiss topographic maps are famous for their beauty. Always wanted those for my biking tours. Recently I had a couple of hours to chat with Claude about this. Up he came with:
  • topovert turning the swisstopo vector map into an .img you can throw at your Garmin devices. Bit exploratory still. You'll have to install a bit of stuff - I think Claude put that into the readme.
  • A swisstopo BRouter overlay to do your bike tour planning
  • with the background of the pretty Landeskarte (or an aerial map).
Programming is becoming quite a different beast right now.

Tuesday, December 25, 2012

Globally configurable wiring alternatives in CDI

The problem

Among the shortcomings of CDI (1.0) as a general purpose DI container is the lack of what Spring 3.+ users know as profiles (not to mention Guice, which is much more expressive due to its Java EDSL approach). The CDI feature which looks closest at a first glance is the concept of alternatives, quickly turns out to be utterly useless: You can annotate your beans directly (or indirectly, via stereotypes) as @Alternatives and then choose among them for one bean-archive (read "jar") only by selecting them in the META-INF/beans.xml file.  So, there is no way to switch between wiring-profiles without repackaging (possibly all) the jars in the deployment-unit. CDI 1.1 improves very slightly on this by allowing a "global" selection in only one of the "beans.xml" which is still far below par.

The implementation-selector pattern

My currently favored work-around consists of the following steps
  • define an enumeration of profiles
  • define a qualifier annotation referring to one of those profiles
  • annotate service alternatives with the above profile-qualifier
  • define a producer selecting the appropriate profile programmatically, publishing it to "@Default" injection points.
In some more detail:

Profile enum and annotation

Let's start with the annotation: The Enum's slightly more interesting, because it sports a reference to an annotation literal which comes in handy later, when we select the right instance:

Annotate your service alternatives

Now we can annotate our service alternatives like
@InProfile(IN_MEMORY_DB) public class SampleSvcForInMemoryDb implements SampleSvc { ...

Define the implementation-selector

This is just a bean containing a producer method like this: Thanks to the @Any annotation, it gets all available instances injected. It then selects the appropriate one for the activeProfile, which is a member variable in this sample, but can, of course be any method-call. Unfortunately, CDI does not allow a useful generification of that pattern, as far as I could see. It's still inferior to what other frameworks offer, but if CDI is a set standard, it's usable.

Tuesday, April 10, 2012

Autocompletion support for Scala's combinator parsers

Recently, I came to revisit Scala a bit more in depth -- compared to the odd script or hack I did before. Now, things at work change a bit: some green-field stuff to be done, even calling for some kind of DSL -- ok, maybe not really calling, really loudly but close enough to warrant spending some quality playing-time with my favorite "next great programming language".
So I threw together some combinator parsers which was some fun in itself and most of it felt very good. Except there was no autocompletion. The envisioned DSL should, among other things, navigate a mildly complex domain model. But, in contrast to a generic expression language, typos in property-names should be caught at the syntax level, and possible completions should be displayed when the user types the start of a property (or a dot). What I wanted to do was something like the made-up example below:
Of course, in the real DSL, the properties would not be hardcoded but reflectively collected from the model. The missing key-feature here is the CompletingParser mix-in: It doesn't come with the standard Scala library and I didn't easily find a nice solution readymade. So, that looked like a good opportunity to take Scala's extensibility for a test-drive that's both, interesting and easily within a Scala-beginner's reach
The basic ideas are
  • override the Parser class' alternative combinator "|" to make it collect possible completions in the ParseResult instead of just returning a Failure
  • override the implicit factory method for string literals to produce an alternative literal parser which differentiates between an unexpected and a missing character
As it turns out, in the standard implementation, the | combinator just delegates to ParseResult's append method which normally discards all results but the successful one, or, failing that, returns the failure which consumed most of the input stream. So we just need to replace the Failure parse result with a version that's able to keep track of possible completions, rather smellily named MissingCompletionOrFailure. This plan led me to the following little trait:
Now a simple command-loop to take our work for an interactive test-drive looks like this:

Tuesday, March 27, 2012

Pleasant surprise: JUnit supports Design by Contract

I've long felt contract envy of languages like Eiffel supporting Design by Contract. Only recently, I stumbled over the (not so) recent addition of theories to JUnit. Once the object instances under test are separated from the test-code - now taking on the form of a logical implication, making the latter re-usable is the obvious next step. Ever been tired of writing tests for your value-object's equals and hashCode methods? Try this:
/**
 * Provides JUnit theories that check, whether an arbitrary class 
 * satisfies the Object interface contract regarding the methods 
 * equals and hashCode. Instances of the class(es) to be tested 
 * have to be provided in derived classes 
 * 
 * @author scm
 */
@RunWith(Theories.class)
public abstract class ObjectContractTheory {
    
    @DataPoint
    public static final Object INSTANCE_OF_UNRELATED_TYPE = new String();
    
    @Theory
    public void equality_is_symmetrical( Object o1, Object o2) {
        assumeThat( o1, equalTo( o2 ) );

        assertThat( o2, equalTo( o1 ) );
    }

    @Theory
    public void equality_implies_equal_hashCodes( Object o1, Object o2) {
        assumeThat( o2, notNullValue() );
        assumeThat( o1, equalTo( o2 ) );

        assertThat( o1.hashCode(), is( equalTo( o2.hashCode() ) ) );
    }
        
    @Theory
    public void identity_implies_equality( Object o1, Object o2 ) {
        assumeThat( o1, sameInstance( o2 ) );

        assertThat( o1, equalTo( o2 ) );
    }

    @Theory
    public void any_object_is_unequal_to_null( Object o1 ) {
        assumeThat( o1, notNullValue() );
        
        assertThat( o1, not(  equalTo( null ) ) );
    }

    @Theory
    public void unrelated_classes_are_not_equal( Object o1, Object o2 ) {
        assumeThat( o1, notNullValue() );
        assumeThat( o2, notNullValue() );
        assumeThat( o1,  not( instanceOf( o2.getClass() ) ) );
        assumeThat( o2,  not( instanceOf( o1.getClass() ) ) );
        
        assertThat( o1, not( equalTo( o2 ) ) );
    }


}


Then to make sure that Integer fulfills that part of the object contract, you would simply write:
public class ObjectContractTest extends ComparableContractTheory {    
    @DataPoints
    public static final Integer[] INTS = {1,2,3,4};
}
Which is hardly to much to ask, even if creating your really interesting objects were slightly more verbose.

Sunday, January 17, 2010

Generics Gotcha: Intransitive Inheritance from self-referential types

The setup


I was used to the assumption that type inheritance in Java is transitive, that is B extends A and C extends B implies that C is a subtype of A as well as of B. As long as A,B and C denote straight classes, this is true to the best of my knowledge. But as I, admittedly only recently, learned, once generic type expressions come into play it gets a bit more interesting:
Let's make A a self-referential generic type like
interface A<T extends A<T>>{T x();}

The problem


Suppose, we'd now want to introduce some parallel class hierarchy depending on our A,B,C hierarchy, like this
interface D<T extends A<T>> ...
class E implements D<B> ...
class F implements D<C> ...
. Now, the compiler complains about the definition of class F, claiming that C is not a valid substitute for the parameter T extends A<T> of type D. Now, this seems funny: Type B is allowed while type C which is derived from B is not allowed in the very same type expression with the same upper bound A. After some thinking, this makes actually sense. What's the purpose of having a self-referential type like A? Probably, to have some method or attribute which is defined using the type of intended subtypes (as "x" shown above). Now, for the first sub-type, B, the type parameter T would be bound to B itself and in x's implementation the return-type would naturally be B. The same would, of course, hold for any sub-type of B, i.e. also for C. That, in turn, means that C is not a legal direct implementation of A! C is not self-referential any more, because its inherited member x still returns a B.

A resolution


Once the real cause of the problem is clear, the solution is easy: The definition of D needs to be changed to allow A's type parameter to refer to an arbitrary super type of D's parameter
interface D<T extends A<? super T>>
Now, E and F compiles just fine as defined before.

Saturday, November 14, 2009

Spring AOP: Excessive startup time for "perTarget" advice

Well over 300,000 Class.forName calls during context-initialisation were the result of setting up a simple "perTarget" advice for a 400-something beans application. With the standard "per class" instantiation model, the overhead went back to "normal", returning the Hibernate SessionFactory to the top of the list of startup resource-consumers. From a quick look at the profiler output, AspectJ's Type-Worlds are re-built over and over again while evaluating pointcuts - funny.

Saturday, February 23, 2008

Powerbook survived HD-ectomy

My beloved "old" (3.5 years) powerbook (G4, 15", 1.5 GHz) started to make humming noises, especially when tilted. A couple of weeks later there were sudden hangups, it would only restart after given some cooling time.
That it finally survived my amateur-surgery - albeit somewhat battered - let me immediately regret my fancying a new macbook. Some notes:

  • I followed this guide

  • I did need to poke into the dvd-drive-slit. I found a corkscrew useful for that - Just don't apply too much force unless you actually love that slightly battered look ...

  • As replacement, I chose the Hitachi Travelstar 5K160, 5400rpm, 8MB, 2.5", 120GB, P-ATA. In Switzerland it can be had at 107 SFr (e.g. at digitec ). Subjectively it's slightly louder and noticably faster than the original.

  • When re-assembling, don't absent-mindedly put screws into the holes meant for DVI-plugs. You'll never get them back out. But, anyway, there are plenty of screws, and even with one lost in the plug-hole, it won't fall apart (I hope).

Monday, June 04, 2007

Tapestry Components in Scala

Recently, I became interested in Scala: Multiple inheritance, good support for functional programming, a nice syntax, to mention the greatest highlights.

As a first exercise, I tried to write some Tapestry-4 components in Scala to gain some real-world experience, and to see whether Tapestry's pretty extensive use of bytecode-generation would somehow break Scala's Java-compatibility. I was pretty pleased with the results:

The following is a trait to add authorisation support to arbitrary (form-)components. It controls whether to render the component into which it is mixed in and binds its disabled parameter.

package ch.marcus.components;

import org.apache.tapestry._

trait AccessControlled extends AbstractComponent {
object binding extends IBinding {
def getObject = Boolean.box(getIdPath.contains("readOnly")) // TODO: delegate to ac-service
def getObject(c: Class) = getObject
def getDescription = "AccessControl disabled-binding"
def setObject(o: Object) = {}
def isInvariant = false;
def getLocation = null;
}

override def finishLoad = {
setBinding("disabled", binding )
}

/**Derived components delegate to the desired renderComponent method here: */
def renderAccessControlled ( w: IMarkupWriter, c: IRequestCycle )

override def renderComponent( w: IMarkupWriter, c: IRequestCycle ) {
if ( ! getIdPath.contains("invisible") ) // TODO: delegate to ac-service
renderAccessControlled(w,c);
}
}


Here is how to derive an access-controlled version of the standard TextField component by inheriting from TextField and the trait we just defined:


package ch.marcus.components;

import org.apache.tapestry._
import org.apache.tapestry.form._

abstract class AuthorisedTextField extends TextField with AccessControlled {
//duplicate from scala.Object to make Tap's class-enhancer happy
@remote override def $tag(): Int = 0

override def renderAccessControlled( w:IMarkupWriter, c: IRequestCycle )
= super[TextField].renderComponent(w,c);

}

The only gotcha is the override of $tag which seems to be necessary due to a glitch in Tapestries class-enhancer. Oh, and for components with a specification(.jwc)-file this must be copied for the derived component. This is slightly annoying, but unnecessary for component that consequently use annotations (specless components).

This is how a Tapestry page looks like in Scala:

package ch.marcus.pages
import org.apache.tapestry.annotations._
import scala.reflect._

abstract class Home extends ScalaPage {
val text = "Hello, this is Scala."

@Persist
def getMbr : String
def setMbr( m:String )

def onSubmit = {
setMbr (getMbr + "x")
}
}

Note, how clean the code looks without all the syntactic noise you'd have to add in Java and how nice the Tapestry annotations (Persist) work with Scala.

Saturday, May 12, 2007

Clean and Flexible Authorisation for Tapestry Applications

Currently we'r working on an application that will be used by 4 different departments. And I can already anticipate people dropping in to casually remark someting like "Oh, by the way, we've hired this guy who needs Access to module X of the invoicing system, but of course he mustn't be allowed to press button Y, and he needs to be able to change the comment-field. And don't hurry, he'll not really need it until today afternoon."

Furthermore, the app is meant to be re-usable by subsidiaries in other countries. So putting conditionals in the view-templates (anyway bad) or cluttering component tags with disabled="ognl: admin || hasRole('blub')" kind of parameters was clearly no option.

The solution I liked best was to introduce an "@AuthorisedBlock" component which iterates over all form components it contains (in its tag-body), looks up the current users permissions (r, rw, neither) for them and, accordingly decides whether to render them enabled, disabled or not at all (see source-code at the end of this post).

The permission lookup is delegated to a simple rules engine. A rule is basically a triple (role, id-regular-expression, permission). The rules engine determines the rule with the longest pattern-match for the id-regexp - considering, of course, only rules which apply to the current user's roles.

So, in the template there's only the <span jwcid="@AuthorisedBlock"> tag enclosing the part of the template subject to authorisation checking. The actual authorisation rules can be put into a config file or into the database.

Of course, this pattern should be implementable using any web-framework with a notion of components. But Tapestry has a couple of nice features that make it particularly easy and straightforward to implement:

  • Tapestry's form-components implement a well-known, useful interface. Thus @AuthorisedBlock works with any of them without the need to build cumbersome wrappers around 3rd party library components just to support authorisation properly.

  • A component can easily control the rendering of its body, i.e. the components belonging to the child tags of its own.

  • A component takes part in the construction of a page's component trees in an oo-manner. This makes it easy to setup the binding for the disabled parameter.


In short, Tapestry makes it easy to write the rather frameworky parts of an application, because it has nicely coherent inner workings and it's very liberal in exposing these to the application programmer and letting him change them. At least, this is true for versions 3 and 4 of Tapestry. Version 5 may become a bit more secretive. I'm not sure, whether I'll actually like that. Of course, I see the intended win: A Tap 3/4 app's GUI code will typically depend quite heavily on the framework, even on parts that were perhaps never intended to be publicly (ab-)used. So, a framework update to a new major version will be hard. However, I don't think this is really harmful. After all: Your frontend code doesn't contain any business logic, right? So, when you really need to go for a major frontend framework update, what could be the reason for this need? You'll probably want to give your application a fairly complete overhaul of the whole GUI anyway and you want to do it in a new way using the new features of your new framework (-version). What's the big point in backwards compatibility then?


public abstract class AuthorisedBlock extends AbstractComponent {
@InjectObject("service:iis.web.AuthorisationSvc")
public abstract AuthorisationSvc getAuthSvc();

@Override
protected void renderComponent(IMarkupWriter writer, IRequestCycle cycle) {
renderBody(writer, cycle);
}

@Override
public void renderBody(IMarkupWriter writer, IRequestCycle cycle) {
for (int i = 0; i < _bodyCount; i++) {
IRender r = _body[i];
if ( r instanceof IFormComponent ) {
IFormComponent formComp = (IFormComponent) r;
AccessPermission permission
= getAuthSvc().permissionFor( formComp.getExtendedId() );
if ( permission == invisible )
continue;

}
cycle.getResponseBuilder().render(writer, r, cycle);
}
}

@Override
public void addBody(IRender r) {
super.addBody(r);
if ( r instanceof IFormComponent ) {
IFormComponent formComp = (IFormComponent) r;
formComp.setBinding("disabled",
new DisabledBinding(formComp.getExtendedId()) );
}
}

private class DisabledBinding implements IBinding {

private String extendedId;

public DisabledBinding(String extendedId) {
this.extendedId = extendedId;
}

public Location getLocation() {
return null;
}

public String getDescription() {
return toString();
}

public Object getObject() {
return getAuthSvc().permissionFor(extendedId) == readOnly;
}

public Object getObject(Class type) {
return getObject();
}

public boolean isInvariant() {
return false;
}

public void setObject(Object value) {
throw new UnsupportedOperationException(this+" is a read-only binding");
}

@Override
public String toString() {
return "sythetic disabled binding for " + extendedId+" to AuthorisedBlock";
}

}

}

Wednesday, April 25, 2007

Subversive beats Subclipse as SVN Plugin for Eclipse

I've switched from subclipse to subversive recently. The former used to annoy me by

  • its inability to handle directory moves/copies. I had to go and delete .svn dirs manually

  • The annoying need to do manual updates after each commit


Subversive mostly works in any of these cases. And when it doesn't want to keep track of me moving some directory around, it politely asks me to commit before continuing.

Thursday, March 08, 2007

Maven2: creating JavaDoc links behind a firewall

I just spent the better part of the morning trying to make javadoc links work. In short: configuring the proxy did not work - We have to cope with offline package-lists, not a big problem really. Of course, to configure the maven-javadoc-plugin to do this, reading the source was the quickest way to go. So put something like this in your pom.xml:

<reporting>
<plugins>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<configuration>
<linksource>true</linksource>
<offlineLinks>
<offlineLink>
<url>http://java.sun.com/j2se/1.5.0/docs/api/</url>
<location>T:/maven/apidoc-packagelists/jdk-1.5.0</location>
</offlineLink>
</offlineLinks>
<docfilessubdirs>true</docfilessubdirs>
<excludedocfilessubdir>CVS</excludedocfilessubdir>
</configuration>
</plugin>

The locations must be valid Java file paths, pointing to a locally accessible directory which contains the package-list file for the given url.

Thursday, February 15, 2007

XFire newbie gotcha: use the correct ServiceFactory

If you use the jaxb binding (the default with the Maven-plugin) to generate you client proxies, to actually use your service, you have to instantiate a org.codehaus.xfire.jaxb2.JaxbServiceFactory instead of an org.codehaus.xfire.service.binding.ObjectServiceFactory. Otherwise the parameter names (wsdl:part@name) will be replaced with "in0"-elements by XFire - and the server will complain about an unexpected element "in0".

Quality of Maven integration becomes decisive for OSS adoption - good bye Axis

Today I realised, how important it became for any open-source project to play nicely with the Maven repository and to get its dependencies right in its pom's .
When I had to whip up a web-service client yesterday, I started out trying Axis-2 since I knew the server impl was bases on Axis. Quickly I had to decide to either start debugging their maven-plugins dependencies (obviously wsdl4j was lost somhow), or to try something different (XFire). What I definitely not wanted was to clutter my build with Ant or, worse, CLI calls. I quickly tried XFire, its Maven plugin worked out of the box - even the library itself was a pleasant surprise (easy to use, nice Jaxb-bindings, clean generated code).

Sunday, February 11, 2007

New Version 1.0.2 of hivedoc-plugin for HiveMind /Maven2

Finally, I got around to enhancing the hivedoc-plugin with:

  • Support for sub-modules

  • Removal of empty columns in the module-summary table.

The new version 1.0.2 should be on the central repo as soon as MAVENUPLOAD-1377 is resolved.

Monday, January 08, 2007

Half a Year of Maven 2: An experience of the awkward kind

We're using Maven 2 now for all new projects. At the highest level I can summarize our experience as:
  1. The concepts behind Maven are sound and amazingly useful.
  2. The implementation is just about usable - no show-stoppers anymore, but lots and lots of little, annoying bugs and surprising gotchas
  3. The documentation is sloppy.
The really funny thing is, how point 1. still by far outweighs the shortcomings 2. and 3 when it comes to the question "Was it worth it, after all?".

So what made it useful, after all?
  • First of all, it gives your builds a uniformity and completeness (JavaDocs, HiveDocs, PMD, CPD, ...) that would be difficult to achieve otherwise without having a dedicated, organization-wide build-manager (as a real person:).
  • Secondly, it facilitates re-use by making doing the right things easier than the wrong ones. Having cleanly specified dependencies referring to specific binary versions of jars makes a bigger difference than you might think without trying. And being able to inherit a big part of your build-setup from an org-wide POM (the ant project descriptor) is a real killer feature. Together with archetypes this makes the overhead for starting a new library-module really negligable.
Enough praise. The downside is, there is still way enough room for maven-improvement wishes for the new year. Too many things just make - sorry - too sloppy an impression for a project which is purportedly backed by a professional org (Mergere). Some of the issues I remember are:
  • Docs: One of the benefits of Maven should be good consistent docs. Ever searched for reference docs on the site-descriptor site.xml? Google the mailing-lists. Wondering how to generate standard plugin-documentation? Don't bother with the docs. Just have a look at the POM's of existing modules. Looking for core API-docs? You'll find something like this
  • The SCM / release plugin claims to support DOS'ish CVS-pathes (D:\...) - in the report it works, but the release:prepare fails.
  • Special characters in the generated docs don't work. E.g. german locale.
  • Want to create a repo-bundle for a multi-module project? Doesn't work.
  • In a Mojo you can inject things into private fields - If a superclass happens to have a private field of the same name the injection fails silently.
So, after all, a great tool with a great amount of small issues to work on. Please, Maven guys, put some effort in finishing off the little bugs - and thanks for a useful tool.

Friday, January 05, 2007

New Version of hivedoc-plugin for HiveMind

Since some people seem to use it, I've updated my hivedoc-plugin to version 1.0.1 . Notable changes are:
  • Support for custom resource root directories
  • Backport to Java 1.4
  • proper plugin-docs
The new version should show up on the central Maven 2 repo soon. If you need it before that, here's the repo-bundle.

Tuesday, January 02, 2007

hivedoc-plugin generates Maven 2 docs for HiveMind descriptors

If you're using HiveMind and Maven 2, generating docs for your HiveMind descriptors is now really quick and simple.
Find the docs under http://marcus-schulte.ch/hivedoc-plugin/.

Friday, September 15, 2006

Honeycomb now comes with a Maven2 archetype for Tapestry/Hibernate based web-apps.

Version 0.3.3 of Honeycomb is released.
Honeycomb provides an easy integration for Tapestry and Hibernate. Its distinguishing key feature is session-per-conversation support.
The main changes in this release are:

  • re-structuring into 4 libraries replaced the templates for the Core/Webapp projects with maven archetypes. Maven users get started without manual downloads.
  • Fixed rollback on RedirectException.
  • Fixed possible concurrency issue in cross-request service-model
  • Fixed: Removed dangerous loophole allowing a conversation to survive a rollback triggered by an exception.
  • Cleaned up HiveMind descriptors and moved them into the lib-modules.
  • added a Watch component to the tap-lib (calls a listener when a property has changed in a submit)

Saturday, August 26, 2006

The Return of the Database - who needs more "middleware"?

Maybe it's just my organization's policy of giving its developers relatively free access to db's while, at the same time, putting lots of administrative hurdles and hurdle-like administrators between them and the app-server. But it's really amazing how little there is that you can't get done nicely with a sturdy db and a decent servlet-container (at most).
Example: For some time I thought a nice event-driven architecture I was planning would require some serious investment (of money and effort) into some sort of enterprisy message-bus, and, of course, then you'd have at least 2 transactional resources to keep synchronised, crying for some "serious" app-server... When I suddenly asked myself, why the hell one ta-resource, the database wasn't enough. And it is, I think. For small-scale integration tasks, where we can control the deployment of all involved systems, business components shared across applications and working on the same database will do just fine. For more difficult tasks requiring some more decoupling there's stuff like Oracle Advanced Queuing - which can be used as a JMS implementation backed, ultimately, by db-tables. Similar things should be easy to implement on any db.
And the best thing: only one ta-resource, only jdbc, no need for two-phase-commit, old Tomcat will do.

Monday, February 27, 2006

KickStart is now Honeycomb, release 0.3 out

Kickstart has moved from SourceForge to JavaForge, and it's changed its name to Honeycomb (alluding to the central role that HiveMind plays in it). Honeycomb integrates Tapestry with Hibernate for painless full-stack web-dev-support.
New features comprise

  • A hibernate DataSqueezer

  • Pluggable Audit-Trail via hibernate interceptor

  • Support for session per request pattern via simple config switch.