Tag Archives: Groovy

install Groovy in RedHat as4

官方网是这样写的:
1,first, Download a binary distribution of Groovy and unpack it into some file on your local file system
2,set your GROOVY_HOME environment variable to the directory you unpacked the distribution
3,add GROOVY_HOME/bin to your PATH environment variable
4,set your JAVA_HOME environment variable to point to your JDK. On OS X this is /Library/Java/Home, on other unixes its often /usr/java etc. If you’ve already installed tools like Ant or Maven you’ve probably already done this step.

但会出现错误:
# groovysh
java.lang.NoClassDefFoundError: org/objectweb/asm/ClassVisitor
        at groovy.lang.GroovySystem.<clinit>(GroovySystem.java:27)
        at org.codehaus.groovy.runtime.Invoker.<init>(Invoker.java:38)
        at org.codehaus.groovy.runtime.InvokerHelper.<clinit>(InvokerHelper.java:44)
        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeNewN(ScriptBytecodeAdapter.java:225)
        at org.codehaus.groovy.tools.shell.Main.<clinit>(Main.groovy:34)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:101)
        at org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:130)


解决办法:
#vi /etc/profile

加入GROOVY_HOME
export GROOVY_HOME=”/home1/software/groovy-1.5.0/”

修改CLASSPATH
export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar:”/home1/lib/”:$GROOVY_HOME/lib/ant-1.7.0.jar:$GROOVY_HOME/lib/asm-2.2.jar:$GROOVY_HOME/lib/bsf-2.4.0.jar:$GROOVY_HOME/lib/jline-0.9.93.jar:$GROOVY_HOME/lib/mx4j-3.0.2.jar:$GROOVY_HOME/lib/ant-junit-1.7.0.jar:$GROOVY_HOME/lib/asm-analysis-2.2.jar:$GROOVY_HOME/lib/commons-cli-1.0.jar:$GROOVY_HOME/lib/jsp-api-2.0.jar:$GROOVY_HOME/lib/servlet-api-2.4.jar:$GROOVY_HOME/lib/ant-launcher-1.7.0.jar:$GROOVY_HOME/lib/asm-tree-2.2.jar:$GROOVY_HOME/lib/commons-logging-1.1.jar:$GROOVY_HOME/lib/junit-3.8.2.jar:$GROOVY_HOME/lib/xpp3_min-1.1.3.4.O.jar:$GROOVY_HOME/lib/antlr-2.7.6.jar:$GROOVY_HOME/lib/asm-util-2.2.jar:$GROOVY_HOME/lib/groovy-1.5.0.jar:$GROOVY_HOME/lib/mockobjects-core-0.09.jar:$GROOVY_HOME/lib/xstream-1.2.2.jar

Your First Groovy



Your First Groovy



//hello.groovy
println “hello, world”

for (arg in this.args ) {

println “Argument:” + arg;

}

// this is a comment

/* a block comment, commenting out an alternative to above:

this.args.each{ arg -> println “hello, ${arg}”}

*/

To run it from command line



groovy hello.groovy MyName yourName HisName


Overview


Groovy classes compile down to Java bytecode and so there’s a 1-1 mapping between a Groovy class and a Java class.

Indeed each Groovy class can be used inside normal Java code – since it is a Java class too.


Probably the easiest way to get groovy is to try working with collections. In Groovy List (java.util.List) and Map (java.util.Map) are both first class objects in the syntax. So to create a List of objects you can do the following…



def list = [1, 2, ‘hello’, new java.util.Date()]

assert list.size() == 4

assert list.get(2) == ‘hello’

assert list[2] == ‘hello’

Notice that everything is an object (or that auto-boxing takes place when working with numbers). To create maps…



def map = [‘name’:’James’, ‘location’:’London’]

assert map.size() == 2

assert map.get(‘name’) == ‘James’

assert map[‘name’] == ‘James’

Iterating over collections is easy…



def list = [1, 2, 3]

for (i in list) { println i }

Once you have some collections you can then use some of the new collection helper methods or try working with closures…



Working with closures


Closures are similar to Java’s inner classes, except they are a single method which is invokable, with arbitrary parameters. A closure can have as many parameters as you wish…



def closure = { param -> println(“hello ${param}”) }

closure.call(“world!”)

closure = { greeting, name -> println(greeting + name) }

closure.call(“hello “, “world!”)


If no parameter(s) is(are) specified before -> symbol then a default named parameter, called ‘it’ can be used. e.g.



def closure = { println “hello “ + it }

closure.call(“world!”)

Using closures allows us to process collections (arrays, maps, strings, files, SQL connections and so forth) in a clean way. e.g



[1, 2, 3].each ({ item -> print “${item}-“ })

[“k1”:“v1”, “k2”:“v2”].each {key, value -> println key + “=” + value}

Note: If a given closure is the last parameter of a method, its definition can reside outside of the parentheses. Thus the following code is valid:



def fun(int i, Closure c) {

c.call(i)

}

// put Closure out of ()

[1, 2, 3].each() { item -> print “${item}-“ } // 1-2-3-

fun(123) { i -> println i } // 123

// omit ()



[1, 2, 3].each ({ item -> print “${item}-“ }) // 1-2-3-



// omit enclosing ()
[1, 2, 3].each { item -> print “${item}-“ } // 1-2-3-

// normal
[1, 2, 3].each(({ item -> print “${item}-“ })) // 1-2-3-

// using the fun function to do the same thing
[1,2,3].each {fun(it,{item -> print “${item}-“})} // 1-2-3-

def closure = { i -> println i}

//[1, 2, 3].each() closure // error. closure has been previously defined

Here are a number of helper methods available on collections & strings…



each


iterate via a closure



[1, 2, 3].each { item -> print “${item}-“ }


collect


collect the return value of calling a closure on each item in a collection



def value = [1, 2, 3].collect { it * 2 }

assert value == [2, 4, 6]


find


finds first item matching closure predicate



def value = [1, 2, 3].find { it > 1 }

assert value == 2


findAll


finds all items matching closure predicate



def value = [1, 2, 3].findAll { it > 1 }

assert value == [2, 3]


inject


allows you to pass a value into the first iteration and then pass the result of that iteration into the next iteration and so on. This is ideal for counting and other forms of processing



def value = [1, 2, 3].inject(‘counting: ‘) { str, item -> str + item }

assert value == “counting: 123”

value = [1, 2, 3].inject(0) { count, item -> count + item }

assert value == 6


In addition there’s 2 new methods for doing boolean logic on some collection…



every


returns true if all items match the closure predicate



def value = [1, 2, 3].every { it < 5 }

assert value

value = [1, 2, 3].every { item -> item < 3 }

assert ! value



any


returns true if any item match the closure predicate



def value = [1, 2, 3].any { it > 2 }

assert value

value = [1, 2, 3].any { item -> item > 3 }

assert value == false


Other helper methods include:



max / min


returns the max/min values of the collection – for Comparable objects



value = [9, 4, 2, 10, 5].max()

assert value == 10

value = [9, 4, 2, 10, 5].min()

assert value == 2

value = [‘x’, ‘y’, ‘a’, ‘z’].min()

assert value == ‘a’


join


concatenates the values of the collection together with a string value



def value = [1, 2, 3].join(‘-‘)

assert value == ‘1-2-3’