Showing posts with label Groovy. Show all posts
Showing posts with label Groovy. Show all posts

22.11.11

Groovy Goodness: Create Our Own Script Class | Javalobby

Groovy Goodness: Create Our Own Script Class | Javalobby

  • By default the script is evaluated with an instance of groovy.lang.Script class.
  • But we can extends this Script class and write our DSL allowed methods, which can then be used by the DSL script. 
  • We pass our own Script class to the GroovyShell with an CompilerConfiguration object. The CompilerConfiguration allows us to set a new base script class to be used.

22.7.10

Annotation usage with properties

Background

Groovy's property mechanism provides a short-hand which simplifies defining typical JavaBean-style classes. You simply define the property with no explicit visibility and it is replaced at the bytecode level by a private backing variable, a public setter and a public getter. To the Java world, all three parts are visible. In the Groovy world, conceptually it is OK to just think about the property - Groovy's property notation comes in to play so that using the setter or getter looks like using the property as if it was a field.

This works well but introduces a slight complication with annotations. When using the non-property approach, there are three places in the source code where an annotation may be added (the field, the setter and the getter). With the property approach (idiomatic Groovy) there is just one place available in the source to place an annotation.

Current Behaviour

Currently if an annotation is applied to a property, the compiler will attempt to apply the annotation to the field, the setter and the getter. If any of these fails (e.g. some annotations may apply only to methods or only to fields) the code won't compile.

PROPOSAL: Smarter annotation assignment

Use the java.lang.annotation.Target of any annotations to determine where the annotation will be included in the final class.

If the @Target of the used annotation marks the annotation as usable only on FIELD level, then the annotation will be attached to the generated field.

If the @Target of the used annotation marks the annotation as usable on METHOD level, then the annotation will be attached to the generated getter and setter.

If the @Target of the used annotation marks the annotation as usable on both FIELD and METHOD level, then the annotation will be attached to all the generated class elements.

Obviously, if multiple annotations are used, there is the possibility of the annotations being split across the generated class elements, e.g. I can use both a field and a method annotation. The field annotation will be attached to the field (and ignored for the getters and setters) while the method annotation will be attached just to the methods.

PROPOSAL: Additional annotation classification mechanism

Sometimes it is desirable to be more selective with annotation than is possible even with smarter annotation assignment, e.g. placing an annotation on just one of the setter or getter. Sometimes an annotation might be possible on both fields and methods but in a particular example we want to apply it to just one. To achieve this we need additional syntax to express how we want to classify an annotation.

One way to do this is to use a synthetic annotation as a prefix to the real annotation. A @Target annotation appears in Groovy code at the source level, but it is only synthetic. It has no real definition. It will be like a compiler flag only, and completely ignored in the output.

The @Target annotation allows the user to further refine where the compiler should attach an annotation. After it has been used by the compiler, it is completely discarded. The Groovy @Target annotation will further specify if an annotation will be attached to a FIELD, GETTER or SETTER, but will never contradict the Java @Target annotation. In case such a contradiction occurs the Groovy compiler must emit an error.

Last, but not least I should mention that there will be no naming conflict between the Java java.lang.annotation.Target annotation and the Groovy Target annotation (probably groovy.lang.annotation.Target), because they will be living in completely different context.

An example:

@Target([FIELD]) @AutoPopulate(defaultValue="bar")
@Target([GETTER]) @ManagedAttribute(currencyTimeLimit=15)
@Target([SETTER]) @ManagedAttribute(persistPolicy="OnUpdate")
int base = 10

As an alternative, we could come up with some other syntax to achieve the same result, e.g. here might be some other ways to write the above:

@[FIELD]AutoPopulate(defaultValue="bar")
@[GETTER]ManagedAttribute(currencyTimeLimit=15)
@[SETTER]ManagedAttribute(persistPolicy="OnUpdate")
int base = 10

Or this:

@AutoPopulate[FIELD](defaultValue="bar")
@ManagedAttribute[GETTER](currencyTimeLimit=15)
@ManagedAttribute[SETTER](persistPolicy="OnUpdate")
int base = 10

Or this (using a synthetic annotation parameter):

@AutoPopulate(groovyTarget='field', defaultValue="bar")
@ManagedAttribute(groovyTarget='getter', currencyTimeLimit=15)
@ManagedAttribute(groovyTarget='setter', persistPolicy="OnUpdate")
int base = 10
 
http://groovy.codehaus.org/Annotation+usage+with+properties

20.7.10

Annotations with Groovy

Introduction

Java 5 and above supports the use of annotations to include metadata within programs. Groovy 1.1 and above also supports such annotations.

Annotations are used to provide information to tools and libraries. They allow a declarative style of providing metadata information and allow it to be stored directly in the source code. Such information would need to otherwise be provided using non-declarative means or using external files. We won't discuss guidelines here for when it is appropriate to use annotations, just give you a quick run down of annotations in Groovy.

Annotations are defined much like Java class files but use the @interface keyword. As an example, here is how you could define aFeatureRequest Annotation in Java:

// Java
public @interface FeatureRequest {
String key();
String summary();
String assignee() default "[unassigned]";
String status() default "[open]";
String targetVersion() default "[unassigned]";
}

This annotation represents the kind of information you may have in an issue tracking tool. You could use this annotation in a Groovy file as follows:

@FeatureRequest(
key="GROOVY-9999",
summary="Support Graphical Annotations",
assignee="Pete",
status="Open",
targetVersion="5.0"
)
class SomeClassWhereFeatureCouldBeUsed {
// ...
}

Now if you had tools or libraries which understood this annotation, you could process this source file (or the resulting compiled class file) and perform operations based on this metadata.

As well as defining your own annotations, there are many existing tools, libraries and frameworks that make use of annotations. See some of the examples referred to at the end of this page. As just one example, here is how you could use annotations with Hibernate or JPA:

import javax.persistence.*

@Entity
@Table(name="staff")
class Staff implements Serializable {
@Id @GeneratedValue
Long id
String firstname
String lastname
String position
}

Example

As another example, consider this XStream example. XStream is a library for serializing Java (and Groovy) objects to XML (and back again if you want). Here is an example of how you could use it without annotations:

// require(groupId:'com.thoughtworks.xstream', artifactId:'xstream', version:'1.3')
import com.thoughtworks.xstream.*

class Staff {
String firstname, lastname, position
}

def xstream = new XStream()
xstream.classLoader = getClass().classLoader
def john = new Staff(firstname:'John',
lastname:'Connor',
position:'Resistance Leader')

println xstream.toXML(john)

This results in the following output:

<Staff>
<firstname>John</firstname>
<lastname>Connor</lastname>
<position>Resistance Leader</position>
</Staff>

Just as an aside, not related to annotations, here is how you could write the XML to a file:

new File("john.xml").withOutputStream { out ->
xstream.toXML(john, out)
}

And how you would read it back in:

// require(groupId:'com.thoughtworks.xstream', artifactId:'xstream', version:'1.3')
// require(groupId:'xpp3', artifactId:'xpp3_min', version:'1.1.4c')
import com.thoughtworks.xstream.*

class Staff {
String firstname, lastname, position
}

def xstream = new XStream()
def john
// now read back in
new File("john.xml").withInputStream { ins ->
john = xstream.fromXML(ins)
}

println john.dump()
// => <Staff@12d96f2 firstname=John lastname=Connor position=Resistance Leader>

Now, on to the annotations ...

XStream also allows you to have more control over the produced XML (in case you don't like its defaults). This can be done through API calls or with annotations. Here is how we can annotate our Groovy class with XStream annotations to alter the resulting XML:

// ...
import com.thoughtworks.xstream.annotations.*

@XStreamAlias("person")
class Associate {
@XStreamAsAttribute
@XStreamAlias('first-name')
String firstname

@XStreamAlias('surname')
String lastname

@XStreamOmitField
String position
}

msg = new Associate(firstname:'Sarah',
lastname:'Connor',
position:'Protector')
Annotations.configureAliases(stream, Associate)
println stream.toXML(msg)

When run, this produces the following output:

<person first-name="Sarah">
<surname>Connor</surname>
</person>

Differences to Java

Annotations may contain lists. When using such annotations with Groovy, remember to use the square bracket list notation supported by Groovy rather than the braces used by Java, i.e.:

// Java
@ManagedOperationParameters({
@ManagedOperationParameter(name="x", description="The first number"),
@ManagedOperationParameter(name="y", description="The second number")})

Would become:

// Groovy
@ManagedOperationParameters([
@ManagedOperationParameter(name="x", description="The first number"),
@ManagedOperationParameter(name="y", description="The second number")])

 


 


http://groovy.codehaus.org/Annotations+with+Groovy

16.7.10

Make My Java Program Supports Dynamic Language(5)

Groovy

  • Problem: Still Slow.

Groovy is my second though, and I am OK with it so far, although I have some performance concern with it. According to my testing, by primitive calculation Groovy, it is about 128 times slower than the native Java program. The difference is significant. However, due to my current use cases, I would probably use Groovy as a glue language to glue up some other Java implementation with programmatic flow control

  • ClassLoader Supports

I am very happy that Groovy provides ClassLoader supports. That means it support a transparent Class.forName().

  • Resource Loader

image

image

I am happy with the implementation. The Composite Design Pattern of Resource Loader gives me a good opportunity to build my own Resource Loader, so that I can search specific PATHs/JARs.

Scala

Scala is popular now a day. But it’s not design to embedded or into Java. http://www.scala-lang.org/node/6966 is a thread talking about Scala Scripting. And here is some except:

Here are two examples:

http://people.apache.org/~mduerig/scala4scripting/

You might probably want to watch his talk from the Scala Days as well.

Here's some code I wrote some time ago (in Java!) which uses Scala for
scripting (I'm not sure which version but definitely pre-2.8):

http://github.com/jrudolph/scolorz/blob/master/src/net/virtualvoid/graph...

Actually it is quite easy to use the Scala interpreter (beware Java
code following):

import scala.tools.nsc.Interpreter;
import scala.tools.nsc.Settings;

final Interpreter interpreter = new Interpreter(new Settings());
final Painter[] painter = new Painter[1];

interpreter.bind("painter", "Array[net.virtualvoid.graphics.Painter]", painter);
String code = "object aPainter extends net.virtualvoid.graphics.Painter{\n"
+ "def paint:Unit = {\n"
+ text.getText() + "\n}\n"
+ "}\n";

interpreter.interpret(code);
interpreter.interpret("painter(0) = aPainter;");

So I defined a Painter interface and bound an array of that variable
to receive the results. Code which I executed got wrapped by code
which implements the interface. After evaluating this, the result is
stored into the array and can be accessed afterwards.