Archive

Posts Tagged ‘Groovy’

A little bit of housework – MOPping up

December 31, 2016 Leave a comment

in doing some basics you keep relearning some stuff so here’s a quick recap on Groovy MOP.

Each groovy class has a metaClass, who’s default class is groovy.lang.MetaClassImpl.  If you set a property on the metaClass groovy changes this to be ExpandoMetaClass.  Normally calls to methods on your class are normally redirected to the metaClass to call the methods on your class using the invokeMethod call on the metaClass

Using the metaClass of your class you can lookup the methods on your class  like this

class MyIntercepted {

    def myMethods () {
        println "methods fom meta class"
        int total = 0
        def list = this.getMetaClass().getMethods().each {total++; println "$it.name"}
        println "total methods found : $total \n"
        list
    }

    def myMetaMethods () {
        println "list of meta methods from meta class"
        int total = 0
        def list = this.getMetaClass().getMetaMethods().each {total++; println "$it.name"}
        println "total of metaMethods found : $total \n"
        list
    }

    //has higher priority than invokeMethod
    /*def methodMissing (String name, args) {
        println "missing method: method $name ($args) was called by methodMissing"
    }*/

    //will be called if no method can be matched
    def invokeMethod (String name, args) {
        println "metaclass is of type " + this.getMetaClass().getClass()
        println "method $name ($args) was called intercepted by invokeMethod"
    }
}

// and use it 
MyIntercepted mi = new MyIntercepted()

mi.myMethods()       //class method exists
mi.myMetaMethods()   //class method exists
mi.smoke()           //class method doesn't exist 

 

calling myMethods() lists out the basic class methods found via the metaClass including those of GroovyObject, and my two class methods.

calling the myMetaMethods() will list out the broader list of metaMethods that Groovy embellishes each class with with via the GDK, which includes the “println” method.

if you implement def invokeMethod (String name, args), as shown (and you have to put the String type to name to get right dynamic dispatch), then when you call the nonexistent smoke(), method then Groovy calls the invokeMethod call where you can see the trace wriiten to your console.

if you uncomment the def methodMissing() this has higher priority and so this methodMissing() is called when the mi.smoke() method is called.

if you change your class to implement the marker interface GroovyInterceptable like this, then groovy intercepts all calls on the class and directs them to the invokeMethod call, including metaMethods such as println. Because of this you can’t use println as this is intercepted as wll and go into stackoverflow loop. you have to use the System.out.println to get trace output.

class MyIntercepted implements GroovyInterceptable {

    def myMethods () {
        println "methods from meta class"
        int total = 0
        def list = this.getMetaClass().getMethods().each {total++; println "$it.name"}
        println "total methods found : $total \n"
        list
    }

    def myMetaMethods () {
        println "list of meta methods fom meta class"
        int total = 0
        def list = this.getMetaClass().getMetaMethods().each {total++; println "$it.name"}
        println "total of metaMethods found : $total \n"
        list
    }

    //has higher priority than invokeMethod
    def methodMissing (String name, args) {
        println "missing method: method $name ($args) was called by methodMissing"
    }

    //will be called if no method can be matched
    def invokeMethod (String name, args) {
        System.out.println "method $name ($args) was called intercepted by invokeMethod"
    }
}

So how do call method if you have intercepted all the calls? You lookup the method and if it exists you can use the method.invoke(this, args) on it

    //will be called if no method can be matched
    def invokeMethod (String name, args) {
        //System.out.println "metaclass is of type " + this.getMetaClass().getClass()
        System.out.println "method $name ($args) was called intercepted by invokeMethod"
        MyIntercepted.metaClass.invokeMethod(this, 'println', "invoked println from metaClass.invokeMethod ")
        MetaMethod method = MyIntercepted.metaClass.getMetaMethod("hello")
        if (method) {
            System.out.println "looked up hello metamethod and tried to call it "
            method.invoke(this, "\tmethod.invoke: invoked hello metamethod")
            method.invokeMethod('println', "\tmethod.invokeMethod: invoked println directly from a meta method")
        }
    }

however you have to be careful like with println as this will again go into stack overflow

if you override the invokeMethod on the metaClass like this

MyIntercepted mi = new MyIntercepted()
mi.metaClass.invokeMethod = {String name, args -> System.out.println "used overriden metaClass invokeMethod"}

it has lower priority than a class method of same the name implemented in the class. whereas if you have a methodMissing on a class and one on the metaClass, the resolution path uses the metaClass implementation first!

Advertisements
Categories: Groovy Tags: ,

Quick note on groovy testing a spock

February 29, 2016 Leave a comment

Been getting to grips with gradle, groovy and spock, on a little project and couldnt figure out how to get the GroovyTestCase power assertions available to spock tests.

So eventually found it you have to add the following import

import static groovy.test.GroovyAssert.*
import static org.assertj.core.api.Assertions.*

this enables you to use the the groovy power asserts (shouldfail, assertFalse, etc ), the other is a fluent assertion library that has some interesting features – you need to update your compile dependencies to include ‘org.assertj:assertj-core:3.0.0’

I have not played with the Hamcrest matchers at this point but probably worth a look as these with Spock too

If you want Gradle to find and run your tests i’ve found its easiest to end your class file nameTest.groovy then you can run single shot tests for example like this

gradle -Dtest.single=DynamicRuleSpecification test

which will run the DynamicRuleSpecificationTest.groovy in your ‘src/test/groovy’ folder

Happy testing

Categories: gradle, Groovy, Testing Tags: ,

silly problems with Spring @Value ‘${}’ with IoC injection

February 23, 2016 Leave a comment

hit some basic problems with Spring injection today worth noting for others

I was trying out @Value injection today in spring and hit some basic issues

1. when you use @Value in groovy and spring – despite the fact that you might want to use a ${} expression, you cant wrap this in “” which you might expect. The Groovy compiler gets in a huff and declares the the value is not a String (technically its a GString in groovy).

to make this work in groovy you have write something like (note single ”)

@Value ('${jmx.rmi.host}')

This is counter intuitive if you are used to the normal “” Gstring interpolation in Groovy. To make it work with “” you have to try

@Value ("${jmx.rmi.host}".toString())

or just use the ” as previously shown.

2. second issue: if injecting values from application.properties in root of your classpath , then note that the properties values in that file default to string, so `x.y.z=”hi”` will return a string including the quotes, which is not what you expect. just leave the strings unadorned to inject correctly.

3. then, if you use param injection alone like this

void setHost ( @Value ('${jmx.rmi.host}') String host)

then you get a null injection (not sure why). To fix this, either

a) move the

@Value ('${jmx.rmi.host}'

to method level, or

b) use @autowired at method level and leave the

@Value ('${jmx.rmi.host}')

at parameter level as well,  to get the injection to occur.

It’s these small nuances that take so much time, hopefully someone else will benefit and save a couple of hours.

4. Lastly, you can lookup properties using the Spring Environment like this. Just use the @Autowired on method or constructor, and do the lookup /type conversion using the env.getRequiredProperty call like this

@Component
class Props {

    private Map props = [:]
    boolean jmxEnabled
    String host

    @Autowired  //test inject the env
    Props (Environment env) {
        jmxEnabled = env.getRequiredProperty("org.softwood.jmx", Boolean.class)
        props[jmxEnabled]=jmxEnabled


    }

    //format either use Autowired for method and @value on param
    // or just @value as method injection will work
    @Autowired
    void setHost ( @Value ('${jmx.rmi.host}') String host)  {

        assert host
        println "set host by injection"
        this.host = host
        props[host] = host
    }

}

GPARS Actors and sleeping barber example

November 27, 2014 Leave a comment

started to look at the GPARS library and how to apply this into my programms – found an earlier example from Hamlet D’arcy, but it was out of date relative to latest GPARs constructs, and scheduling work at particular times

So i’ve had a go at relaunching it in new clothes. In order to simulate the waiting room i’ve used blocking queue of fixed size. Adding a customer will block when the waiting room is full – until someone (the barber takes one as his next customer)like this by sending a message to the actor

     barber << check client  //message to actor

in the second approach i've used the timer service to repeatedly schedule a message to a second barber ( not an actor ) which runs the action takes a client and reschedules itself for next ask

def barber2 = Executors.newScheduledThreadPool(1)
barber2.scheduleAtFixedRate({
	     println 'Barber2: Next customer please!'
		 Customer customer = waitingRoom.take()
		 println "${customer.name} gets a haircut at ${new Date().format('H:m:s')}" }
 as Runnable, 0, 5, TimeUnit.SECONDS)

the complete groovy script solution looks like this

package com.softwood.script

import groovy.transform.Immutable
import groovyx.gpars.group.DefaultPGroup

import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit


// create waiting room can't hold more than 12!  array queue of customers
def waitingRoom = new ArrayBlockingQueue(12)

/**
 * ArrayBlockingQueue filled with customers that need a haircut. 
 * And the barber is an executor service with a scheduled task to 
 * give haircuts. The number of threads in the scheduled thread 
 * pool is 1 because there's only one barber. The barber takes 
 * customers from the waiting room and cuts their hair once every 
 * 15 minutes. The call to waitingRoom.take() is blocking... if 
 * there is a customer ready then he is serviced immediately, and 
 * if one is not, then the call blocks until someone is available. 
 * Once thing to note... the waitingRoom has a size of 12... if a 
 * 13th customer is added then the calling code will either block 
 * until there is enough room or throw an exception. There is an 
 * API to do either case.
 */
final def group = new DefaultPGroup ()

//event driven actor model 
final def barberShop = group.reactor {message ->
	switch (message) {
		case Enter :
			println "${message.customer.name} enters and is waiting for a haircut"
			//add customer from message to the waiting room 
			waitingRoom.add (message.customer)
			break
		
		case "quit":
			println "called quit on barbershop - now new customers can come in"
			terminate()
			break
		
	}
}

// message to post on barberShop
@Immutable
class Enter {
	Customer customer
}

//customer for barbershop
@Immutable
class Customer {
	String name
}

//create a single barber - thread pool size of 1
final DefaultPGroup barberGroup = new DefaultPGroup (1)


println "barber opening shop"
//this model auto starts the barber
final barber = barberGroup.actor {
	loop {
		react {
			println "barber> asked to -> $it"
			println "barber> Next Customer Please!"
			Customer customer = waitingRoom.take()  //blocking call on waiting room
			println "barber> ${customer.name} gets a haircut at ${new Date().format('H:m:s')}"
		}
	}
}

def barber2 = Executors.newScheduledThreadPool(1)
barber2.scheduleAtFixedRate({
	     println 'Barber2: Next customer please!'
		 Customer customer = waitingRoom.take()
		 println "${customer.name} gets a haircut at ${new Date().format('H:m:s')}" }
 as Runnable, 0, 5, TimeUnit.SECONDS)


//add some customers to waiting room 
barberShop << new Enter(customer: new Customer(name: 'Jerry'))
barberShop << new Enter(customer: new Customer(name: 'Phil'))
barberShop << new Enter(customer: new Customer(name: 'Bob'))
barberShop << new Enter(customer: new Customer(name: 'Ron'))
barberShop << "quit"

//send 'message' to first barber 
barber << "check client  "

//barber.stop()
barber.join (20, TimeUnit.SECONDS)
println "customers in queue ${waitingRoom.size()}"
println "barber closing shop"

i’ve used @ immutable to construct a a thread safe message with thread safe ‘customer’ to pass to the waiting room

Categories: GPARS, Groovy Tags: , , ,

Using Spring with no xml config …

October 21, 2013 Leave a comment

As usual i was just on the way to fixing something else and thought it worth while just documenting a couple of things to know about using spring and groovy.

Spring 3+ now has good support for beans either with traditional xml configuration files (which has the benefit of being independent of the code, and so useful for third party software you may have but little code control over) and more latterly for annotation driven config from code – which if your writing /maintaining code can be more pleasant to work with than lots of angle brackets

so quickie introduction to using noXml anywhere context build – here goes

i’ve built this as a gradle project to handle the dependency management (I am working with Groovy so this makes a lot of sense) but you could do this with maven, our just add the jars to your build path.

I’m using Springsource IDE – but you can install gradle support into ordinary eclipse also

once you have the gradle project support enabled from the eclipse market place and (either use embedded gradle – or download your own install) you should be ready to go

I created a new gradle project using the wizard – kept it simple and just used simple gradle project structure

in the build.gradle file in the root of the project edit the file to include some additional dependencies and apply the groovy plugin, and added a src/main.groovy source directory to the standard gradle project.

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'groovy'

sourceCompatibility = 1.5
version = '1.0'
jar {
    manifest {
        attributes 'Implementation-Title': 'Gradle Quickstart', 'Implementation-Version': version
    }
}

//project variables
ext {
	spring_version = "3.1.4.RELEASE"
}

repositories {
    mavenCentral()
}

dependencies {
	compile 	'org.codehaus.groovy:groovy-all:2.1.+'
        compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
        testCompile group: 'junit', name: 'junit', version: '4.+'
	compile 	"org.springframework:spring-core:${spring_version}"
	compile 	"org.springframework:spring-beans:${spring_version}"
	compile 	"org.springframework:spring-context:${spring_version}"
	compile 	"org.springframework:spring-aspects:${spring_version}"
	compile 	"org.aspectj:aspectjrt:1.6.10"
	compile 	"org.aspectj:aspectjweaver:1.6.10"
	compile 	"cglib:cglib:2.2"
}

test {
    systemProperties 'property': 'value'
}

uploadArchives {
    repositories {
       flatDir {
           dirs 'repos'
       }
    }
}

couple of things to note: you have to have cglib in the dependency list, and groovy (if you are using groovy) and as i want to try spring DI outside of the context – i’ve included the aspectj necessities

then what you need to do is provide an entry point (I could use a groovy script here – but i have just used a class with a static main instead as you would for a java like app)

package com.softwood

import org.springframework.context.annotation.AnnotationConfigApplicationContext

class Sampler {
	
	static void main (String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(/*BeanConfig.class*/)
                //could add dynamically like this - but I didn't,  I just used the scan()
                //ctx.register (BeanConfig.class)
		ctx.scan ("com.softwood")
		ctx.refresh ()
		
		WillsBean wb = ctx.getBean("willsBean")
		assert wb != null
		println "willsBean : " + wb.type

		WillsBean pwb = ctx.getBean("privateBean")
		WillsBean pwb2 = ctx.getBean("privateBean")
		println "privateBean with type $pwb.type and int : " + pwb.i + " dump: " + pwb.dump()
		println "privateBean with type $pwb.type and int : " + pwb2.i + " dump: " + pwb2.dump()

	}

}

so pretty simple to start with – i’ve created a Sampler class which creates a new AnnotationConfigApplicationContext() – you can pass the list of @Configuration classes into the constructor (as shown in commented out params), or call the register() action on the context to register these at runtime (commented out), and lastly call the refresh() to reload the context.

what i’ve done here however is set a context-scan starting from com.softwood and below looking for annotated files (@Configuration, @Component, @Service etc ) and call refresh(). This loads the @Configuration class BeansConfig and its beans (and WillsBean as its annotated with @Component) into the context.

So then you provide the basic @Configuration annotated class, and define the @Beans within that you expect to be handled within the context. In this example i’ve declared WillsBean with @Component (but you needn’t do that) which adds the default bean as willsBean using the default constructor as a singleton.

in the BeanConfig class i declare two @Bean instances; publicBean (singleton) and privateBean (which is prototype scoped – a new instance every time is returned) (note it didn’t like the private bean as being decalred private – i had to make it public to work)

@Configuration
class BeanConfig {
	static int i
	
	@Bean 
	WillsBean publicBean () {
		return new WillsBean ("willsPublicBean")
	}
	
	@Bean @Scope ("prototype")
	WillsBean  privateBean () {
		return new WillsBean ("willsPrivateBean", i++)
	}
}

@Component
class WillsBean  {
	
	String type 
	int i 

	WillsBean () {
		this.type = "singletonComponent"
		this.i = -1
	}

	WillsBean (String type) {
		this.type = type
		this.i = -1
	}
	
	WillsBean (String type, int i) {
		this.type = type
		this.i = i 
	}
}

This all works as expected when you run it.

Equally you can expand the example and add say a DISource and DITarget class, where the DITarget has an @Autowired Field dependency on a a DISource which will be fulfilled when you get the diTarget bean from the context like this

class BeanConfig {
       ....
	@Bean 
	DISource diSource () {
		return new DISource()
	}

	@Bean 
	DITarget diTarget () {
		return new DITarget ()  //trigger autowired injection on field 
	}
} //end BeanConfig

//DI source class 
class DISource {
	String name = "DI source for injection "
}

//DI dependent class 
class DITarget {
	@Autowired DISource diSource
}

you trigger the DI injection from the Sampler.main() like this

		DITarget target = ctx.getBean("diTarget")
		println "injected DISource into DItarget and set as : " + target?.diSource?.name

The rest of the annotation examples can be gleaned from the user guide documentation when is pretty good.

Categories: Groovy, Spring Tags: , ,

Trials and tribulations with groovy AST transforms…

February 25, 2013 Leave a comment

Fell into this somewhat by accident – and its end up consuming a lot of play time to figure some of the stuff out – Information on what todo and how can be a little sparse, and it can be a bit of a bother to work with and get working – however its a useful to know exists when you need it.  However its not for the faint hearted.

What triggered this was my exploration of a Griffen transform @PropertyListener that you can add to @Bindable.  When i tired to import that transform into a SWT/grails/groovy project – it would not work as outlined.

so I went back to basics and tried to build it up from first principles.  I’ve tried to document what i went through in the process, from simple marker interfaces – through to those that take parameters that inform the transformation externally

Essentially what i think I found was that the example outlined in the griffen project – I couldn’t get to work at all and i ended passing either a closure as the property listener – or a String name of a field in your class that is a closure to make this work at all

I’ve attached a PDF of the tutorial and steps to go through, so i hope someone else finds it useful

So i now have a working transformation that seems to keep eclipse happy and doesn’t fail the IDE when applied to your class.  Its not ‘case hardened, and i’m still adding stuff to the ASTUtils library but ive attached the working zip file to have a peek at also

trials and tribulations in AST transformations v1.0

Actually wordpress free wont let me post a zip – so y’ll need to contact me for copy of the zip of the project

 

 

 

 

 

 

 

 

 

 

Categories: AST, Groovy Tags: , , ,
%d bloggers like this: