Posts tagged with “java”

Introducing the Proton Template Engine (part 3)

Thursday, 29 January, 2009

Templates are usually made up of other templates, especially if you want to re-use page/document components. Proton supports an include function to embed one template inside another.

For example, a fragment of a template (include2.xhtml) containing 2 paragraphs of text…

<div>
    <p eid="para1">PARA 1 TEXT</p>
    <p eid="para2">PARA 2 TEXT</p>
</div>

…can be embedded in another template (include1.xhtml)…

<body>
    <h1 eid="title">PAGE TITLE GOES HERE</h1>

    <div eid="includedcontent">
    INCLUDED CONTENT GOES HERE
    </div>
</body>

…and then populated with data, using the following snippet of code:


tmp = self.templates['include1.xhtml']
tmp.setelement('title', 'Page Title')
tmp.include('includedcontent', 'include2.xhtml')
tmp.setelement('para1', 'First paragraph of text')
tmp.setelement('para2', 'Second paragraph of text')

 

On the ‘syntactic sugar front’, as an alternative to the more explicit repeat function (for repeating elements in the output), Proton supports setting lists of values rather than single-values. Consider the template:

<ul>
    <li rid="list-item" eid="list-item">LIST ITEMS</li>
</ul>

The list can be populated without having to explicitly call repeat, using the following code snippet:


lst = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g' ]
tmp.setelement('list-item', lst)

If your objects are decorated with properties (@property), then Proton also supports automatically setting the values in the page, using the convention of id followed by colon followed by property. For example, using the following template:

<dl>
    <dt>X Value</dt>
    <dd eid="prop:x">prop x here</dd>
    <dt>Y Value</dt>
    <dd eid="prop:y">prop y here</dd>
</dl>

A class Temp, with properties x and y can be set in the template, with the name prop and the values will be automatically populated.


class Temp(object):
    def __init__(self, x, y):
        self._x = x
        self._y = y

    @property
    def x(self):
        return self._x

    @property
    def y(self):
        return self._y

t = Temp('100', '500')
tmp.setelement('prop', t)

Scripting in Spring

Thursday, 1 November, 2007

Spring has a rather nice scripting framework that I haven’t paid much attention to, more from a lack of need than any real lack of interest.

One thing I recently noticed, is that there are only 3 supported scripting languages: Beanshell, Groovy and JRuby. Now Beanshell (for myself at least) was interesting about 4 or 5 years ago (maybe longer… since I can’t quite recall when it was first released), and I have little interest in Groovy (read “little interest” as “no interest”).

A bit of googling only uncovered a brief discussion about adding Jython support back in 2004 (I haven’t been able to find any code to go with that discussion), and Rhino-in-Spring which, as far as I can tell, is aimed at the web tier. Interesting that 2 of the most popular (IMO) scripting languages are rather conspicious by their absence from the core Spring distribution. Or if not absent, then certainly not very visible.

I’ve been looking for a reason to hack around with Spring extensions for a while, so this seemed like the opportune moment. Following one of the comments in that 2004 discussion, I started with cloning GroovyScriptFactory and a few other classes from the scripting package, and then hacked away the bits I didn’t want or need.

GenericScriptFactory is my abstract base class, and contains most of the code from GroovyScriptFactory. Subclass JythonScriptFactory is the workhorse for Jython scripting, while RhinoScriptFactory is obviously for Javascript code.

The cool part — I’ve implemented a NamespaceHandler for both, so bean configuration looks like this for Jython:

<script:jython id="test1" script-source="test.py"
               bean-name="mytest" return-type="test.TestInterface"
               interpreter="pythonInterpreter">
    <script:property name="test" value="jython prop from spring" />
</script:jython>

and for Javascript (Rhino):

<script:rhino id="test2" script-source="test.js"
              bean-name="mytest" return-type="test.TestInterface"
              scope="jsScope">
    <script:property name="test" value="javascript prop from spring" />
</script:rhino>

You’ll note that in both cases the attributes are passed to the factory, but properties are injected after the bean (in whatever language) has been created. A distinction which is rather useful when you think about it. This is the same as the other scripting languages already built-in to Spring.

You can see the full configuration file here, which includes setting up a PythonInterpreter for Jython, and a global scope for Rhino.

The sweet spot is, of course, this configuration:

<script:jython id="test3" script-source="test.py" bean-name="mytest" return-type="test.TestInterface" interpreter="pythonInterpreter">
    <script:property name="testInterface" ref="test2" />
</script:jython>

test2 is the object created by the Javascript code, and you’ll note that it’s being injected into the object created (in this case) by Jython code. The opposite works as well, meaning you can call Jython code from Javascript and Javascript code from Jython (well, at least through Spring injection). Exactly why you’d want to do this, I don’t know, but it’s a fun feature.

In either case, my classes implement a simple Java interface, meaning the beans created by both scripts are useable from Java as well — as you can see in the Test code:


public static final void main(String[] args) throws Exception {
    ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "beans.xml" });
    BeanFactory factory = (BeanFactory) context;

    TestInterface ti1 = (TestInterface) factory.getBean("test1");
    System.out.println("jython test: " + ti1.getTest());

    TestInterface ti2 = (TestInterface) factory.getBean("test2");
    System.out.println("rhino test: " + ti2.getTest());
}

Anyone interested can find the whole thing (very much a work in progress) in a Mercurial repository here.

A Few Glorious Months (Netbeans rant)

Wednesday, 19 September, 2007

UPDATE: it helps if you check the menu options properly… blushsmiley

I don’t tend to waste my time investigating all the nooks and crannies of an IDE (Integrated Development Environment, for the non-developer-types). I typically just use the basics. Some might say I’m wasting time by not using those features, but it works for me.

So when the Eclipse & IntelliJ users on the team opened a dialog box and jumped straight to a source file by typing the first few letters of the filename, I just shrugged and went back to navigating through the project tree…. that is, until someone pointed out that Netbeans had the exact same feature — “Go To File” (so obviously a little investigation of menu options wouldn’t have gone astray).

Then, lo and behold, I discovered shortly after, that Netbeans’ “Go To File” function actually did more than Eclipse (and was at least equivalent to Intelli). You could type the capital letters of the class and it would list the matching classes. For two glorious months (or so), I had a feature that was at least as good as my colleagues. The months of enduring taunts, because of my obscure choice in IDEs, faded from memory as I jumped from file to file with a flick of a few (less) fingers… at least, until the latest version of Eclipse arrived with that feature.

Now Netbeans 6 beta 1 has been released. I’ve been burnt in the past by NB early releases — but this is a brand-spanking-new beta. Spit-polished with the glean of months of development effort, since then. Gosling is talking about it. The general consensus elsewhere appears to be that it’s good.

And, after upgrading, it does look good. Not a huge amount of visible difference from NB5. A few burrs here and there have been filed off the sharp edges. There are some things I don’t find attractive, but it’s bearable. Integration with source control doesn’t seem to thrash the CPU, which is a major improvement.

But then… Alt+Shift+O

My most-used feature.

The only thing I could (until recently) hold above the Eclipse users on the team, and say confidently (and maturely), “Nyah nyah nyah nyah nyah”.

One thousand curses on the perpetrator, for violating the perfection of the Alt+Shift+O! Yes, they’ve indeed extended it to search all filenames instead of just classes, but at the same time they’ve rendered it unuseable. Not only is it slower, it is s…l……o………w……………e……………………r.

It is grindingly slow.

If the phrase that immediately pops to mind to describe the fastest thing you’ve ever seen is “blazingly fast”, then a snail would be described as “blazingly fast” by this feature. A tortoise would have the opportunity to perform a full circuit around my desk, and execute a perfect pirouette, before this abysmal piece of code decided that it should return some results.

Slowness I could’ve forgiven if they hadn’t removed the only thing that (until recently — and yes, I know I keep saying that) made me better than the Eclipsers. The feature-in-the-feature that made me as good as the Intellis. Searching, via the capital letters of a class.

MCGF would find MyCrazyGeneratorFactory.java and MyCrazyGeneratorFactoryImpl.java. WDMCHSLN would find WhyDoMyClassesHaveSuchLongNames.java. As it is, I now have to type My (then wait an inordinately long amount of time) to find all files starting with “My”. Carry on typing if I want to narrow the results. With a bit more waiting…

Netbeans 6.

The upgrade that is actually a downgrade.

Now I have to endure the snickers of both the IntelliJ AND the Eclipse users.

Sigh.

Footnote: Welcome back NB5.5.1!

The Worst Thing about Python

Saturday, 28 July, 2007

The worst thing about Python is that when you spend a lot of time working with other languages (in my case, Java), and you come back to work on a Python app, occasionally you forget that there’s usually a better way to do something. Case in point: creating a rather simplistic framework for initialising an application (db connections, messaging, etc), only to realise a few days later that none of your dynamic loading of initialisation scripts is necessary in the slightest, when a module’s __init__ provides as much of that capability as might be needed.

Sigh.

On a completely unrelated note, a special thanks to the various people who’ve recently linked to this site (specifically to the YAK page). I was never that bothered by an abysmally low technorati ranking, but now find myself absurdly pleased when I’ve climbed up by about half-a-million.

Well… I’m still in the 500,000s anyway, it’s an improvement. A-list? Can you say Z-list? ;-)

netbeans 6 hiccup

Tuesday, 12 June, 2007

…or at least I hope it’s a hiccup.

I downloaded the lastest daily of Netbeans 6, after a couple of exceptions in the m9 release I had been using began to get annoying. Not only is it extremely buggy compared to prior version (unusual for a Netbeans daily, in my experience), but it appears they have replaced the quite functional file dialog with an absolutely abysmal, in my honest opinion completely unuseable, dual mode dialog box.

Whatever possessed the development team to allow that abomination into the main trunk, let’s hope it is a temporary aberration and by the time NB6 goes final, saner minds have prevailed.

Top Ten Netbeans Niggles

Friday, 23 March, 2007

A few things I’m finding a minor annoyance in Netbeans at the moment…

1. Netbeans is not an island.

I’m the only one using Netbeans on our project. I’m the small deformed child, in the corner of the class, that none of the other kids wants to play with.
Our projects are all driven off ant build scripts, so the logical way to use NB (when everyone else is using Eclipse or Intelli) is a free-form project (i.e. “Java Project with Existing Ant Script”). Okay, that works fine, but when you want to compile a single file from within the IDE, the ant script ide-file-targets.xml is created — that’s still okay, I can hack so that the internal classpath in that file points at the classpath in our main build script. But what about code completion, and the other IDE tools that rely on knowing the classpath?
First, right-click on the Project, select Properties, then Java Sources Classpath, then reproduce the classpath you’ve already created in the build script….?

Hmmm. That’s a word that starts with A and rhymes with “pass”.

A related note: I hate the ant icon on freeform projects in NB6. Go back to the old one.

 

2. A Project is not an island.

If NetBeans is not an island, neither are the projects in it. If you hit Ctrl and move your mouse pointer over a class name you can jump to the implementation… but not if that class is defined in another project. There might be a way to do this — but it ain’t obvious.

 

3. Why can’t I turn off Editor Hints?

I don’t like them. I don’t need them. And if I do, I’ll ask. But the problem is, there’s no obvious option that says “Use Editor Hints” to turn them off, and I’ve been through the advanced options — a number of times.

Besides, checkstyle covers all the stuff we actually want to check for.

 

4. “Help” is rubbish.

Stick it in a proper browser, so I can at least hit CTRL+F and find something in the current page. Oh yeah, and my up and down arrows don’t work in the help window either. Might be a Linux issue. But maybe not.

 

5. Where’s “Jump to Resource”?

Alt+Shift+O opens a dialog to jump to a “type” (class/interface/etc), which is nice. But Eclipse will open any resource: Python scripts, build scripts, whatever. Gimme that instead.

 

6. Fix Imports doesn’t remember what I chose last time.

Chances are if I select commons LogFactory one time, I’m going to want to select it the next time. I do not want to select it from a drop-down menu every time.

 

7 Minimal installation wanted.

I want to specify a minimal installation. All non-essential modules switched off. Everything that doesn’t stop the IDE from falling over in a steaming heap. Code completion yes — built-in Tomcat, app server integration, HTTP monitor, J2EE blueprints, integration, etc, etc, etc… absolutely not. I’ll switch on the bits I want, thanks all the same. In fact, don’t even bother including them in the distribution. Download on demand.

 

8. Reformat

If you say reformat xml, surely it means fully reformat? Not just reformat a bit. Either that, or relabel the menu option to “Half-assed Reformat Code”.

 

Okay, so that’s only eight. But Top Ten rolls off the tongue better than Top Eight… :-D

hibernate and multiple databases

Tuesday, 13 March, 2007

We’ve had an app running on SQL Server and MySQL under Hibernate for over a year now — but I failed (rather miserably) getting Postgres running well with the same mapping files.

The main problem was that our mapping files use a native generator:


    <generator class="native" />

In SQL Server and MySQL this maps to an auto incrementing column, but in Postgres (I think) you end up with an int or bigint (depending upon your domain object data type), and a separate sequence (named hibernate_sequence), used to populate it.

Thus if you’re applying raw SQL statements outside of Hibernate’s control, you can’t use the same SQL across all 3 databases. In other words, assuming a table:


<hibernate-mapping>
    <class name="MyTableImpl" proxy="MyTable" table="mytable">
        <id name="dbId" column="id">
            <generator class="native" />
        </id>
        <property name="col1" column="col1" not-null="true" />
        <property name="col2" column="col2" not-null="true" />
    </class>
</hibernate-mapping>

The following sql statement…


    insert into mytable (col1, col2) values ('a', 'b')

…will work on SQL Server and MySQL (in these cases, the column “id” is created as an identity or auto_increment), but not on Postgres (the column is created as a basic int).

However, I’ve just found a workaround — not sure if it’s the recommended approach (I’ve seen a couple of other references describing other ways to accomplish the same result, but these involve changing the mapping files), but this way works for me.

The answer is to define your own Hibernate dialect, subclassing the default Postgres dialect:


import java.sql.Types;
import org.hibernate.Hibernate;
import org.hibernate.dialect.PostgreSQLDialect;
import org.hibernate.dialect.function.SQLFunctionTemplate;
import org.hibernate.id.IdentityGenerator;

public class CustomPostgresqlDialect extends PostgreSQLDialect {

    public CustomPostgresqlDialect() {
        super();

        // register some functions and column types in here
        ...
    }

    public Class getNativeIdentifierGeneratorClass() {
        return IdentityGenerator.class;
    }
}

This dialect returns an identity generator instead of a sequence generator, which means we don’t need to change our mappings across all 3 databases.

Result!

JAXB 2, not as intelligent as it thinks it is

Friday, 6 October, 2006

This is an excellent example of a developer getting carried away by his/her own cleverness:

When generating Java code from an XML Schema, in certain modes JAXB automagically converts words to plural where there may be more than one element. For example, the word Datum is automatically converted to Data, the word Item converted to Items.

This is an exceptionally bad idea for 2 reasons (off the top of my head):

1. Surely it makes more sense for the code to closely match the schema? Not arbitrarily deciding to fix your grammar for you.

2. It’s badly implemented. For example, if I have an abbreviated word ending with “f” it incorrectly converts to plural — “Itemref” becomes “Itemreves”. Garbage. What’s worse, is that I have an xsd:choice contain Items and Itemrefs, so the JAXB1 generated code contained the method “getItemOrItemRef” — JAXB2 in extensions mode creates the wonderful “getItemsAndItemreves” method.

What 1st university student on 6 months work experience came up with that brilliant plan?

But wait, it gets even worse. The jaxb documentation at dev.java.net is full of badly written (often unintelligible) ramblings, missing links, less-than-useless links to blog entries and unwritten faq entries (why bother writing the heading if you don’t have time to write the content, I ask you?).

It is, to put it politely, an absolute mess.

vaguely useful hack

Friday, 23 June, 2006

This is one of the more useful hacks I’ve thrown together lately. It’s a simple console application for accessing a hibernate domain (i.e. you can execute queries such as “from Blah where x = 1″), so you don’t have to deploy your application to test minor changes to hql statements.

It is, by no means, an endorsement of hibernate; rather a reflection on the fact that I can’t find any tools to access the domain which don’t require the use of Eclipse (<sarcasm-alert>because, of course, everyone uses eclipse</sarcasm-alert>).

In any case, the script needs to be executed with a classpath referencing the hibernate jars, jython jars, your domain classes, and anything else hibernate & jython might need to access — I run it from within ant, but it could quite easily be executed from a shellscript.

another wonderful example…

Friday, 12 May, 2006

If you’re using, or have used JSF, you’ll be aware that Javascript is generally a necessity. However, some JSF components do function with Javascript disabled… and so you’d kind-of hope that the basic HTML components will work fine with javascript switched off.

You’d be wrong.

Radio buttons don’t work in all cases, inside tables being the obvious example (solution: write your own radio component. Sigh), and my new personal favourite… feature… command links (rendering as hrefs) will work, but not if they’re inside a form.
We figure the evaluation processing gets to the form component, checks if the form has been submitted, and does not evaluate any of the child elements if it hasn’t been submitted. With javascript enabled, a click on a command link (href) effectively submits the form — with javascript disabled, the command link is a plain href, so the form is not submitted, hence the action on the link is no longer evaluated.

Which is another wonderful example of why spotty faced geeks barely past puberty shouldn’t be allowed to design & develop frameworks… [disclaimer: I have no idea whether the people behind JSF are spotty-faced, geeks, or barely past puberty, but it suits my view of the technology, so I'll persist with my stereotypical assumptions]. Let’s just ignore the last 10 or so years of web development and standardisation, shall we?