Wednesday, October 12, 2011

Using properties from Grails script

If you have custom Grails script and need to access property file from it, I found that easiest way to do it is to use Ant. There is complete example how to access file and to use variables:
ant.property(file:'user.properties')
ant.scp(file:'target/app.war', todir:"${ant.project.properties.login}:${ant.project.properties.password}@server:/home/tomcat/", trust:true)

Sudo without password prompt

Remote scripts often do something that requires root rights, common approach is to use sudo. But by default it interactively prompts for password, which is not easy thing if you execute commands automatically. Fortunately, it can be easily configured not to do it. All that is needed to do is to update /etc/sudoers, and change something like this:
testuser    ALL=(ALL) ALL
to something like this:
testuser    ALL=(ALL) NOPASSWD: ALL

Quartz error: Parameter index out of range

Recently, I had to configure Quartz in cluster. Most common approach to do it is to use database, there is a lot of tutorials and examples, but whatever I was using I bumped into this exception:
2011-10-12 10:44:44,861 [main] ERROR context.GrailsContextLoader  - Error executing bootstraps: org.quartz.JobPersistenceException: Couldn't store trigger 'mySimpleTrigger' for 'TestUpdaterJob' job:Parameter index out of range (2 > number of parameters, which is 1). [See nested exception: java.sql.SQLException: Parameter index out of range (2 > number of parameters, which is 1).]
org.codehaus.groovy.runtime.InvokerInvocationException: org.quartz.JobPersistenceException: Couldn't store trigger 'mySimpleTrigger' for 'TestUpdaterJob' job:Parameter index out of range (2 > number of parameters, which is 1). [See nested exception: java.sql.SQLException: Parameter index out of range (2 > number of parameters, which is 1).]
    at org.grails.tomcat.TomcatServer.start(TomcatServer.groovy:212)
    at grails.web.container.EmbeddableServer$start.call(Unknown Source)
    at _GrailsRun_groovy$_run_closure5_closure12.doCall(_GrailsRun_groovy:158)
    at _GrailsRun_groovy$_run_closure5_closure12.doCall(_GrailsRun_groovy)
    at _GrailsSettings_groovy$_run_closure10.doCall(_GrailsSettings_groovy:280)
    at _GrailsSettings_groovy$_run_closure10.call(_GrailsSettings_groovy)
    at _GrailsRun_groovy$_run_closure5.doCall(_GrailsRun_groovy:149)
    at _GrailsRun_groovy$_run_closure5.call(_GrailsRun_groovy)
    at _GrailsRun_groovy.runInline(_GrailsRun_groovy:116)
    at _GrailsRun_groovy.this$4$runInline(_GrailsRun_groovy)
    at _GrailsRun_groovy$_run_closure1.doCall(_GrailsRun_groovy:59)
    at RunApp$_run_closure1.doCall(RunApp.groovy:33)
    at gant.Gant$_dispatch_closure5.doCall(Gant.groovy:381)
    at gant.Gant$_dispatch_closure7.doCall(Gant.groovy:415)
    at gant.Gant$_dispatch_closure7.doCall(Gant.groovy)
    at gant.Gant.withBuildListeners(Gant.groovy:427)
    at gant.Gant.this$2$withBuildListeners(Gant.groovy)
    at gant.Gant$this$2$withBuildListeners.callCurrent(Unknown Source)
    at gant.Gant.dispatch(Gant.groovy:415)
    at gant.Gant.this$2$dispatch(Gant.groovy)
    at gant.Gant.invokeMethod(Gant.groovy)
    at gant.Gant.executeTargets(Gant.groovy:590)
    at gant.Gant.executeTargets(Gant.groovy:589)
Caused by: org.quartz.JobPersistenceException: Couldn't store trigger 'mySimpleTrigger' for 'TestUpdaterJob' job:Parameter index out of range (2 > number of parameters, which is 1). [See nested exception: java.sql.SQLException: Parameter index out of range (2 > number of parameters, which is 1).]
    at org.quartz.impl.jdbcjobstore.JobStoreSupport.storeTrigger(JobStoreSupport.java:1245)
    at org.quartz.impl.jdbcjobstore.JobStoreSupport$5.execute(JobStoreSupport.java:1151)
    at org.quartz.impl.jdbcjobstore.JobStoreSupport$40.execute(JobStoreSupport.java:3691)
    at org.quartz.impl.jdbcjobstore.JobStoreCMT.executeInLock(JobStoreCMT.java:242)
    at org.quartz.impl.jdbcjobstore.JobStoreSupport.executeInLock(JobStoreSupport.java:3687)
    at org.quartz.impl.jdbcjobstore.JobStoreSupport.storeTrigger(JobStoreSupport.java:1147)
    at org.quartz.core.QuartzScheduler.scheduleJob(QuartzScheduler.java:849)
    at org.quartz.impl.StdScheduler.scheduleJob(StdScheduler.java:254)
    at org.quartz.Scheduler$scheduleJob.call(Unknown Source)
    at QuartzGrailsPlugin$_closure5_closure24.doCall(QuartzGrailsPlugin.groovy:229)
    at QuartzGrailsPlugin$_closure5.doCall(QuartzGrailsPlugin.groovy:224)
    at QuartzGrailsPlugin.invokeMethod(QuartzGrailsPlugin.groovy)
    at QuartzGrailsPlugin$_closure3_closure21.doCall(QuartzGrailsPlugin.groovy:175)
    at QuartzGrailsPlugin$_closure3.doCall(QuartzGrailsPlugin.groovy:173)
    ... 23 more
Caused by: java.sql.SQLException: Parameter index out of range (2 > number of parameters, which is 1).
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
    at com.mysql.jdbc.PreparedStatement.checkBounds(PreparedStatement.java:3729)
    at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3713)
    at com.mysql.jdbc.PreparedStatement.setString(PreparedStatement.java:4553)
    at com.mysql.jdbc.BlobFromLocator.length(BlobFromLocator.java:333)
    at org.quartz.impl.jdbcjobstore.StdJDBCDelegate.getObjectFromBlob(StdJDBCDelegate.java:3463)
    at org.quartz.impl.jdbcjobstore.StdJDBCDelegate.selectJobDetail(StdJDBCDelegate.java:904)
    at org.quartz.impl.jdbcjobstore.JobStoreSupport.storeTrigger(JobStoreSupport.java:1201)
    ... 36 more

Google does not have a lot of information about it and I had to dig Quartz sources to investigate it, but finally I found that problem is emulateLocators=true on my database URL. I use this parameter for Lucene clustering so it seems there is conflict between them, so it is not possible to use common data source. Otherwise, it fixes this exception easily.

Wednesday, October 5, 2011

Calling stored procedure from JdbcTemplate

I am using JdbcTemplate to make database queries, like:
List<Map<String,Object>> rows = jdbcTemplate.queryForList("select * from rows");
Recently I had to replace SQL selects with stored procedures, but after doing so, I had exception:
java.sql.SQLException: The SQL statement must not contain a procedure call or parameter markers.
        at net.sourceforge.jtds.jdbc.JtdsStatement.executeQuery(JtdsStatement.java:1297)
        at com.mchange.v2.c3p0.impl.NewProxyStatement.executeQuery(NewProxyStatement.java:35)
        at org.springframework.jdbc.core.JdbcTemplate$1QueryStatementCallback.doInStatement(JdbcTemplate.java:440)
        at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:395)
        at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:455)
        at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:463)
        at org.springframework.jdbc.core.JdbcTemplate.queryForList(JdbcTemplate.java:494)
As I found out finally, when queryForList is called without parameters it cann't call stored procedures, so to do it you just need to add empty parameter list:
List<Map<String,Object>> tables = jdbcTemplate.queryForList("{call getRows() }", new Object[] {});

Tuesday, September 20, 2011

Running ant task in maven

Sometimes you have some task that you just need to execute: without attaching to build phase, or any process - just run. Unfortunately maven is not very flexible about it. Fortunately, it is still possible. To do it, you need use antrun plugin with custom profile. For example, like this:

<profiles>
  <profile>
     <id>deploy</id>
     <build>
        <plugins>
          <plugin>
            <artifactId>maven-antrun-plugin</artifactId>
            <version>1.3</version>
            <configuration>
              <tasks>
                <property file="user.properties" prefix="user"/>
                <scp file="target/target.war" todir="${user.login}:${user.password}@${user.server}:/home/user/" trust="true"/>
                <sshexec host="${user.server}" username="${user.login}" password="${user.password}" command="sudo ./redeploy.sh" trust="true" />
              </tasks>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.apache.ant</groupId>
                    <artifactId>ant-jsch</artifactId>
                    <version>1.7.1</version>
                </dependency>
                <dependency>
                    <groupId>com.jcraft</groupId>
                    <artifactId>jsch</artifactId>
                    <version>0.1.42</version>
                </dependency>
            </dependencies>
          </plugin>
        </plugins>
     </build>
  </profile>
...

</profiles>

Later, you can run this script like:


mvn antrun:run -Pdeploy

Of course you can have different scripts in several profiles.

This approach even has advantages over having separate Ant's build.xml - you don't need to have separate Ant installation, or for instance, with example above, you don't need to download jsch plugin separately - it is all done by Maven.

Friday, September 16, 2011

Java web application monitoring tool

I was looking for production monitoring tool recently. I didn't have any specific requirements, just to have some understanding about load and bottlenecks. Finally, after some googling I found one very interesting option JavaMelody.

This tool takes risky, but very interesting approach, proxies JDBC calls, loads as web filter, advisor for Spring, etc. Additionally, it watches usual VM stuff, like JMX. As result it has a lot of very detailed and deep statistics, like sql queries time, page load times, and so on. Also it provides a lot of graphics and tables, to watch, generally looks nice and advanced. Of course with this approach it looks quite dangerous, but seems like this is already mature tool and I would like to try to use it in my projects.

Also, it has very nice and simple integration with Grails. Just install Grails-melody plugin, and you have your statistics under URL <hostname:port/app-ctx>/monitoring. This is regular application URL, so you can easily configure access rights and login in your application.

Thursday, September 1, 2011

Hibernate "not-found" in Grails

Often when you delete object from db instead of just marking it as deleted, there is nasty exception that this object is referenced by someone else.
2011-09-01 15:18:38,953 [http-8080-1] ERROR errors.GrailsExceptionResolver  - Exception occurred when processing request: [GET] xxx
Stacktrace follows:
org.codehaus.groovy.grails.web.pages.exceptions.GroovyPagesException: Error processing GroovyPageView: Error executing tag <g:form>: Error executing tag <sec:ifAllGranted>: Error evaluating expression [xxx.yyy?.id] on line [70]: No row with the given identifier exists: [xxx#21244] at xxx.gsp:71 at xxx.gsp:102
    at java.lang.Thread.run(Thread.java:662)
Caused by: org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException: Error executing tag <g:form>: Error executing tag <sec:ifAllGranted>: Error evaluating expression [xxx.yyy?.id] on line [70]: No row with the given identifier exists: [yyy#21244] at xxx.gsp:71 at xxx.gsp:102
    ... 1 more
Caused by: org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException: Error executing tag <sec:ifAllGranted>: Error evaluating expression [xxx.yyy?.id] on line [70]: No row with the given identifier exists: [xxx#21244] at xxx.gsp:71
    ... 4 more
Caused by: org.codehaus.groovy.grails.web.pages.exceptions.GroovyPagesException: Error evaluating expression [xxx.yyy?.id] on line [70]: No row with the given identifier exists: [xxx#21244]
    at grails.plugins.springsecurity.SecurityTagLib$_closure1.doCall(SecurityTagLib.groovy:60)
    ... 7 more
Caused by: org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [xxx#21244]
    ... 10 more
In Hibernate there is nice not-found="ignore" for such cases. In Grails/GORM there is similar option which is not documented for some reason. Just add ignoreNotFound to domain objects mapping section and that is it. For example:
class Log {
  User user

  static mapping = {
    user ignoreNotFound : true 
  }

}