Thursday, April 19, 2012

Groovy Eval slow performance

Groovy Eval is nice feature, unfortunately it does not have great performance. Recently, I had to calculate values on a bunch of objects and got quite dramatic performance issue. After quick investigation, I pinpointed problem to be with Eval, which can be summarized to:


def t = System.currentTimeMillis()
1000.times {
  Eval.x(44, 'x>3')
}
println (System.currentTimeMillis() - t)
7281
I tried to check if there is other solution that could do the same and I found that there is similar native Java function. In similar test I got:


import javax.script.ScriptEngine
import javax.script.ScriptEngineManager
import javax.script.SimpleBindings

def t = System.currentTimeMillis()
ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
1000.times {
  engine.eval('x>3', new SimpleBindings([x:44]))
}
println (System.currentTimeMillis() - t)
250

Obviously, it will not be absolutely the same in general and I assume Eval provides much more (and looks less ugly), but ScriptEngine is good enough for my case and it performs almost 30 times faster.

Tuesday, April 3, 2012

Accessing request parameters from UserDetailsService in Spring Security

If you need to use several properties to authenticate user with Spring Security, for example, by login and domain, there is no built-in way to do it. Even when you override UserDetailsService it only calls method with one username parameter.
Fortunately, there is easy way to access request context with Grails, so it is possible to extract any parameter you need, like:


import org.springframework.web.context.request.RequestContextHolder

class UserDetailsService implements GrailsUserDetailsService  {

  UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    def otherParameter = RequestContextHolder.requestAttributes.params.other
       ...
  }
}


Monday, April 2, 2012

Redis exception: Cannot use Jedis when in Multi.

Jedis newbie problem when adding transactions to Redis client application:


Cannot use Jedis when in Multi. Please use JedisTransaction instead.
redis.clients.jedis.exceptions.JedisDataException: Cannot use Jedis when in Multi. Please use JedisTransaction instead.
 at redis.clients.jedis.BinaryJedis.checkIsInMulti(BinaryJedis.java:1651)
 at redis.clients.jedis.Jedis.hmset(Jedis.java:724)
 at test.TestService.updateSomething(TestService.groovy:39)
 at test.TestService$_processBet_closure1.doCall(TestService.groovy:16)
 at grails.plugin.redis.RedisService.withRedis(RedisService.groovy:67)

Description of exception is absolutely correct though a little confusing. Problem is that you are trying to call methods on Redis connection object instead of Transaction object. So most probably you have something like:


  Jedis jedis = pool.getResource()
  jedis.watch('foo')
  ...
  def transaction = jedis.multi()
  jedis.set("foo", value.toString())
  def result = transaction.exec()


But instead, you should have something like:


  Jedis jedis = pool.getResource()
  jedis.watch('foo')
  ...
  def transaction = jedis.multi()
  transaction.set("foo", value.toString())
  def result = transaction.exec()


Friday, March 30, 2012

Code snippet for JMS queue reader

There is quick snippet how to read from ActiveMQ queue with Groovy:


import org.apache.activemq.pool.PooledConnectionFactory
import javax.jms.Connection
import javax.jms.Session
import org.apache.activemq.command.ActiveMQQueue
import javax.jms.MessageConsumer
import org.springframework.jms.listener.adapter.MessageListenerAdapter
import javax.jms.Message

  PooledConnectionFactory pooledConnectionFactory
  ActiveMQQueue testJmsQueue

  pooledConnectionFactory.start()
  Connection conn = pooledConnectionFactory.createConnection()
  Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE)
  MessageConsumer consumer = session.createConsumer(testJmsQueue)
  consumer.setMessageListener(new MessageListenerAdapter() {
    @Override
    void onMessage(Message message) {
      println message.getContentMap()
    }
  })
  conn.start()


Thursday, March 22, 2012

How to read IMAP email with Groovy

There is quick snippet how to read email from Google IMAP with Groovy:

@Grab(group='javax.mail', module='mail', version='1.4')

import javax.mail.*
import java.util.Properties

def session = Session.getDefaultInstance(new Properties(["mail.store.protocol":"imaps", "mail.imaps.host":"imap.gmail.com", "mail.imaps.port":"993"]),null)
def store = session.getStore("imaps")
store.connect('imap.gmail.com', 'test@gmail.com', 'pass')
def folder = store.getFolder("INBOX")
folder.open(Folder.READ_WRITE)
folder.messages.each { msg ->
  println msg.content
}


Friday, March 16, 2012

JavaScript unit testing in Grails

Recently I wanted to test some complicated JavaScript code and surprisingly there is no a lot of options to choose from in Grails. Fortunately, I was already using Geb and it is extremely easy in this case.
I decided to use QUnit testing framework and all that needs to be done in this case is to place few static files in JS, CSS and HTML folders, create Geb page for QUnit reports and Geb Spec for launching browser. For development everything can be done (and much faster) with QUnit alone. Geb is basically only needed to run tests from CI (Jenkins in my case).


There is my Geb Spec:

package my.test.specs

import spock.lang.Stepwise
import my.test.pages.QUnitPage

@Stepwise
class QUnitSpec extends GebScreenshotsSpec {

  def "run QUnit tests"() {
    when:
    to QUnitPage

    then:
    at QUnitPage
    failedCount == '0'
  }

}


Geb page:

package my.test.pages

import geb.Page

class QUnitPage extends Page {
  static url = "http://localhost:"+System.getProperty("server.port", "8080")+"/my-test/js/tests/qunit.html"

  static at = { $("#qunit-header") }

  static content = {
    failedCount(wait:true) {$('#qunit-testresult .failed').text()}
  }
}


qunit.html and all it's content is just plain QUnit framework.

Disadvantages are that reports are not persisted or summarized with other testing frameworks, but if you have screenshots in your Geb tests, it will provide some feedback. Another issue is if you are not using Geb, than this can be overkill to use it only for JS unit tests.
But in case you already have Geb this is super-simple and lightweight approach.