Get H2 Database Version String

For retrieving the server version of a H2 database you connect to use

SELECT H2VERSION() FROM DUAL

which returns something like 1.3.174

Recently needed this for preventing an application being started with a specific version of H2 (which contained a specific bug), and the only reference on google was this issue entry

Posted in Software | Leave a comment

Grails ClassCastException com.sun.proxy.$Proxy cannot be cast to org.springframework.orm.hibernate3.HibernateCallback

When launching a Grails app, you sometimes get a java.lang.ClassCastException: com.sun.proxy.$Proxy28 cannot be cast to org.springframework.orm.hibernate3.HibernateCallback

Just clear the .slcache directory.

On windows, that’s %userdir%\.grails\.slcache
On *x, it’s something along ~/.grails/2.0.4/.slcache/

Unfortunately, that happens up to several times a week. But if you just delete the folder, it’s fixed (until next time …).
The problem seems to occur more often when switching between different Grails apps in IntelliJ Idea.

Posted in Software | 1 Comment

Make Grails Application Readonly

For a customer project there was the requirement to make certain parts of the application readonly depending on the state of a central domain object, which I’ll call Lock. Long story short:

  • an implementation of AbstractPersistenceEventListener intercepts persistence events and throws a custom exception if changes are forbidden
  • because the event listener is not able to access database state (because it’s triggered halfway through hibernate doing its saving), the necessary data is preloaded in a request filter
  • a custom exception page for the specific exception displays a user-friendly message using information delivered by the exception object

The main part is the src/groovy/LockCheckPersistenceListener.groovy that intercepts persistence events.
There’s one catch – it only kicks in on domain object operations. If you’re using executeUpdate statements, you’ll have to check these in a different way (if there’s not many of them, perform checks at the individual places).

/**
 * For details, see http://grails.org/doc/latest/guide/GORM.html#eventsAutoTimestamping
 */
class LockCheckPersistenceListener extends AbstractPersistenceEventListener  {
 
    public LockCheckPersistenceListener(final Datastore datastore) {
        super(datastore)
    }
    @Override
    protected void onPersistenceEvent(final AbstractPersistenceEvent event) {
        if (!(event.entityObject instanceof Lock)) {
            switch(event.eventType) {
                case EventType.PreInsert:
                case EventType.PreUpdate:
                case EventType.PreDelete:
                    performReadonlyCheck();
                break;
            }
        }
    }
 
    private performReadonlyCheck() {
        //you'd better not perform database access where - you'll get Hibernate's StaleObjectException and
        //'org.hibernate.AssertionFailure null id in XYZ' when accessing the database in any way
        def lock = RequestContextHolder.currentRequestAttributes().getAttribute("activeLock", RequestAttributes.SCOPE_REQUEST);
        if (lock.islocked) {
            throw new LockException("lock.locked")
        }
    }
 
    @Override
    public boolean supportsEventType(Class

The persistence listener needs to be registered in Bootstrap.groovy’s init closure as follows

grailsApplication.mainContext.eventTriggeringInterceptor.datastores.each { k, datastore ->
            grailsApplication.mainContext.addApplicationListener new LockCheckPersistenceListener(datastore)
        }

Within the PersistenceListener, database access is not advisable as it leads to various Hibernate exception. Because the information about the lock needs to be retrieved database nevertheless, the relevant domain object is pre-loaded in a Grails filter that stores the object in request scope for later use.

The filter goes to grails-app/conf/lock/LockFilters.groovy

class LockFilters {
    def filters = {
        all(controller:'*', action:'*') {
            before = {
                //Store the active lock for later use (needed by LockCheckPersistenceListener which can't perform db access from within a hibernate listener
                RequestContextHolder.currentRequestAttributes().setAttribute("activeLock", Lock.findByLocked(true), RequestAttributes.SCOPE_REQUEST)
            }
        }
    }
}

In UrlMappings.groovy, you register a custom exception page for your exception so you can display an appropriate message.

"500"(controller: 'lock', action: 'lockedException', exception: LockException)

The controller action for the exception page is trivial (an empty closure).
The only noteworthy part of the custom exception gsp page is the retrieval of the exception, where in this case, the custom exception has a reason property that is used for a i18n message key.

(...snip..)
<h3>${message(code: request.exception.cause.reason)}</h3>
(...snip...)

This way, you get a neat page that is shown whenever a user tries to change anything while he isn’t allowed to.

Posted in Software | Leave a comment

Single Tomcat 7 Webapp with Apache2 with Ajp Connector

As I had to some pages to get this information together, here’s to to set up a single tomcat webapp as the root of an apache server (on Debian, but should work similarly on other systems).
Assuming you’re configuring the server for the domain abc123.com

Setup your tomcat whereever you like. Per default, it already has the necessary AJP connector configured on port 8009.

In order for your webapp to be the root webapp, delete the existing ROOT directory, and rename your war file to ROOT.war and put it in the webapps directory, then start Tomcat. That’s it for Tomcat.

For the Apache configuration (being root), go to /etc/apache2/sites-available, create a file named abc123.com (yes, .com not .conf. But abc123.com.conf might work too) and put the following in it

<VirtualHost *:80>
    ServerName abc123.com
    ServerAlias *.abc123.com
    ProxyPreserveHost on
    ProxyRequests     off
    ProxyPass / ajp://localhost:8009/
    ProxyPassReverse / ajp://localhost:8009/
</VirtualHost>

and run

a2ensite abc123.com
a2enmod proxy_ajp
service apache2 restart

After this, you webapp should be available at abc123.com

Posted in Software | Leave a comment

Upload Files to S3 with s3cmd in Shell Script

For uploading a defined set of files to S3 using s3cmd, you can use the below shell script.

In our case, there’s two additional options (you might find useful as well)

  • -P sets the permissions to publicly readable
  • –add-header=Cache-Control:max-age=604800 sets the Cache-Control metadata (i.e. the file will be cached for 1 week), but you can use other metadata as well

for f in *.png
do
        s3cmd -P --add-header=Cache-Control:max-age=604800 put $f s3://yourbucket/yourpath/$f
done

For syncing an entire directory, there’s the sync option

s3cmd sync yourfolder s3://yourbucket/yourpath

To see if the files are were uploaded, respectively get the total number/count of files in a bucket

s3cmd ls s3://yourbucket/yourpath/
s3cmd ls s3://yourbucket/yourpath/ | wc -l

Posted in Software | Leave a comment