Download Groovy Scripting Language - Department of Computer Engineering

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CMPE 473-Internet Programming
GROOVY SCRIPTING
LANGUAGE
Presented by
Seçkin ULUĞ
Canan Çelik
Groovy Scripting Language




Groovy is an object-oriented programming language for the Java
Platform as an alternative to the Java programming language. It can
be viewed as a scripting language for the Java Platform, as it has
features similar to those Python, Ruby, Perl, and Smalltalk.
Groovy uses a Java-like curly bracket syntax which is dynamically
compiled to JVM bytecodes and that works seamlessly with other
Java code and libraries.
Groovy is currently undergoing standardization via the Java
Community Process under JSR-241. In some contexts, the name
JSR 241 is used as an alternate identifier for the Groovy language.
Groovy 1.0 was released on January 2, 2007. Groovy 1.1 is
currently in beta and supports Java 5 annotations and static imports.

According to the brainchild of superstar
developers James Strachan and Bob McWhirter,
Groovy is an agile development language that is
based entirely on the Java programming APIs.

Groovy is currently in the beginning phase of
its Java Specification Request, which was
approved in late March of 2004. Groovy is also
the scripting language that some claim will
forever change the way that Java platform is
viewed and utilized.
Basic Properties of Groovy

Groovy is an agile dynamic language for the Java Platform

Builds upon the strengths of Java but has additional power

Makes modern programming features
developers with almost-zero learning curve

Increases developer productivity by reducing structural code when
developing web, GUI, database or console applications

continuously integrates with all existing Java objects and
libraries

compiles straight to Java bytecode so you can use it anywhere you
can use Java
available
to
Java
Why Another Language
Groovy isn't the only scripting language that is compliant with the
JRE. Python, Ruby, and Smalltalk are just three examples of
scripting languages that have been successfully ported to the Java
platform. This begs the question: Why another language? After all,
many of us already combine our Java code with Jython or JRuby for
faster application development; why should we learn another
language?
The answer is that “you don't have to learn a new language to
code with Groovy”. Groovy differentiates itself from the other JREcompliant scripting languages with its syntax and reuse of standard
Java libraries. Whereas Jython and JRuby share the look and feel of
their ancestors (Python and Ruby, respectively), Groovy feels like
the Java language with far fewer restrictions. Groovy employs the
features and libraries Java developers are most familiar with.
Agile Development
The fundamental tenets of agile development are that code should
be well suited to a wide range of tasks and applicable in a variety of
ways. Groovy lives up to these tenets by





Making developers free from compilation
Permiting dynamic types
Making easy syntactical constructs
Allowing its scripts to be used inside normal Java applications
Providing a shell interpreter
These features make Groovy a remarkably easy language to learn
and use, whether you're a seasoned Java developer or newcomer to
the Java platform.
Compilation
Like many scripting languages, Groovy saves
compilation for runtime. This means that Groovy scripts
are interpreted when they are run, much like JavaScript
is interpreted by the browser when a Web page is
viewed.
Runtime evaluation comes at a cost in terms of
execution speed, which could rule out the use of
scripting languages in performance intensive projects,
but compilation-free coding offers tremendous
advantages when it comes to the build-and-run cycle.
Runtime compilation makes Groovy an ideal platform
for rapid prototyping, building various utilities, and
testing frameworks.
Getting started..







Groovy requires Java, (1.4 or greater is required).
Groovy can be downloaded from
http://dist.codehaus.org/groovy/distributions/
Add a new System variable with the name GROOVY_HOME and
the value of the directory groovy was installed in.
Run groovyConsole.bat by double clicking on the icon in the bin
directory of the Groovy distribution.
Type in the groovy console or your groovy file the magical sentence:
println "Hello, World!“
Groovy files can be run (actually compile and then run) by typing
groovy file_name.groovy from the command line also Groovy
console can be copiled by simply pressing CTRL+R .
As expected, result is: Hello, World!
Running Groovy Files
Running the script Emailer.groovyin Groovy is as easy
as typing groovy Emailer.groovy on a command line.
If the same Java file (Emailer.java) wanted to be run an
extra command: javac Emailer.java, followed by java
Emailer should be written. This might seem trivial, you
can easily imagine the advantage of runtime compilation
in a larger context of application development.
 Groovy also permits scripts to drop a main method in
order to statically run an associated application.

Groovy does not require the explicit typing of formal languages such as C++
and the Java language.
Java static typing:
String myStr="Hello World";
Groovy dynamic typing:
myStr="Hello World"
As it can be seen there is no need to declare the variable type. There is
also no need to use a semicolon after the declaration in Groovy.
Polymorphism in Groovy
Another concept getting a new meaning in groovy is polymorphism. One can have all the power
of polymorphism without inheritance with dynamic typing.
class Song{
length
name
}
class Book{
name
author
}
def doSomething(thing){
println "going to do something with a thing named = " + thing.name
}
Above are two Groovy classes, ‘Song’ and ‘Book’. Both classes contain a name property. The
method ‘doSomething’ takes a ‘thing’ and attempts to print the object's ‘name’ property. Since
‘doSomething’ method does not define a type for its input parameter, any object will work so long
as the object contains a name property. Both instances of Song and Book can be used as input for
‘doSomething’ like:
mySong = new Song(length:90, name:"Burning Down the House")
myBook = new Book(name:"One Duck Stuck", author:"Phyllis Root")
 doSomething(mySong)
Burning Down the House
 anotherSomething = doSomethinganotherSomething(myBook)
One Duck Stuck
Variables
 x = 1 println x
1
 x = new java.util.Date()
println xTue Dec 01 20:20:59 EET 2007
x = false println x
false
x = "Hi" println x
Hi
Any String assignment can contain the pattern ${variablename},
and the value of the named variable will be interpolated into the
String:
 i=42
println “Hello ${i}”
Hello 42
Lists
myList = [1776, -1, 33, 99, 0, 9763]
println myList[0]
1776
println myList.size()
6
aList = ['python', 'ruby', 'groovy'] println
aList[-3]
python
Maps
scores=["Brett":100, "Pete":"Did not finish",
“Andrew":86.87934]
It should be noted that each of the values stored in the map is of a
different type.
println scores["Pete"]
Did not finish
println scores.Pete
Did not finish
Map.each method:
printMapClosure = { key, value -> println key + "=" + value }
["first" : "1", "second" : "2", "third" : 3"].each(printMapClosure)
second=2
third=3
first=1
Conditional Execution
amPM =
Calendar.getInstance().get(Calendar.AM_PM)
if (amPM == Calendar.AM){ println("Good morning")
}
else{
println("Good evening")
}
Good evening
Iterators
str = "uncle man“
for (ch in str){ println ch }
u
n
c
l
e
m
a
n
Closures
One of the most interesting syntax extension Groovy provides beyond standard
Java is what are called closures. This term has been overloaded in a lot of places in
computer science, but for now just similar to inner classes. One difference is that
variables can be passed in or out; Groovy closures do not constitute a "lexical
scope" the way an inner class does. Below example indicates how to break a String
into a List and print it one word per line, both the "long way" and using closures.
Without closures:
x = "When in the course of human events ...".tokenize()
for (val in x) println val
With closures, default parameter name:
"When in the course of human events ...".tokenize().each{
println it
}
 square = { it * it } [ 1, 2, 3, 4 ].collect(square)
[ 1, 4, 9, 16 ]
Closures (2)
class Dog{
action
train(){
action.call()
}
}
sit = { println "Sit, Sit! Sit! Good dog"}
down = { println "Down! DOWN!" }
myDog = new Dog(action:sit) myDog.train()
Sit, Sit! Sit! Good dog
mollie = new Dog(action:down) mollie.train()
Down! DOWN!
[1, 2, 3].each {
val = it
val += val
println val}
2
4
6
Dealing with Files
Groovy's java.io.File class has a newReader method that returns a BufferedReader (and newPrintWriter(), which
returns a PrintWriter). java.io.File also has eachLine, which opens the file and reads each line.
 myFileName = "C:\\temp.txt"
myFile = new File(myFileName)
printFileLine = { println "File line: " + it }
myFile.eachLine( printFileLine )
File line: first line
File line: second line
File line: third line
filename="C:\\temp.txt";
chars=0; lines=0; words=0;
new java.io.File(filename).eachLine {
chars+=it.length() + 1
words+=it.tokenize().size();
lines++;
}
println "\t${lines}\t${words}\t${chars}\t${filename}"
3 6
34
C:\temp.txt
Java.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class javaVersion{
public static void main(String[] args) throws IOException {
int chars=0, lines=0, words=0;
String filename=args[0];
BufferedReader r = new BufferedReader(new FileReader(filename));
String it;
while ((it = r.readLine()) != null) {
chars+=it.length() + 1;
words+=new StringTokenizer(it).countTokens();
lines++;
}
System.out.println("\t" + lines + "\t" + words +
"\t" + chars + "\t" + filename);
}
}
Groovy.groovy
filename="C:\\temp.txt";
chars=0; lines=0; words=0;
new java.io.File(filename).eachLine {
chars+=it.length() + 1
words+=it.tokenize().size();
lines++;
}
println "\t${lines}\t${words}\t${chars}\t${filename}"
Groovy inside the Java
-
-
-
Easy to embed groovy scripts in java
applications
Object oriented approach of groovy
language
Three ways to use a groovy script inside a
java application
-
Adopting GroovyShell to evaluate groovy expressions
Dynamic loading and using Groovy classes
Using the GroovyScriptEngine to run groovy scripts
GroovyShell Approach
Uses GroovyShell to execute and evaluate
groovy scripts
 Follow the steps below:

Include groovy libraries in your classpath
 Set binding object for passing the parameters
to methods
 Use evaluate method of shell to run the script

GroovyShell Approach(Example)
TestGS.java
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
public class TestGS {
public static void main(String[] args) {
Binding binding = new Binding();
binding.setVariable( “foobar”, new Integer(2) );
GroovyShell shell = new GroovyShell( binding );
shell.evaluate(
“println ‘Hello Class!’;” +
“calendar =
Calendar.getInstance().get(Calendar.AM_PM);” +
“(calendar == Calendar.AM) ?
println(\”Good morning\”) : println(\”Good evening\”);” +
“println ‘foobar is ‘ + foobar;”
);
}
}
Dynamic Loading Approach
Uses GroovyClassLoader to dynamically
create and load your groovy classes
 No binding objects required
 Follow the steps below:

Include groovy libraries in your classpath
 Create groovy class script
 Use GroovyClassLoader to parse the script
and create the class

GroovyShell Approach(Example)

First create your groovy class script( i.e
GSquare.groovy ) and then the test code(
i.e TestGCL.java )
GSquare.groovy
class Gsquare
{
public int square( int a )
{
return a * a
}
}
GroovyShell Approach(Ex. Cont’d)
TestGCL.java
package pkgGroovyClassLoader;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import java.io.File;
import java.io.IOException;
import org.codehaus.groovy.control.CompilationFailedException;
public class TestGCL {
public static void main(String[] args) throws
CompilationFailedException, IOException, InstantiationException,
IllegalAccessException {
GroovyClassLoader loader = new GroovyClassLoader();
Class groovyClass = loader.parseClass( new
File(“Gsquare.groovy”) );
GroovyObject groovyObject = (GroovyObject)
groovyClass.newInstance(); // create an instance
// set parameters and call a method
Object arg = new Integer( 3 );
Object answer = groovyObject.invokeMethod(“square”, arg);
System.out.println( answer.toString() );
}
}
Dynamic Loading Approach(2)
Alernatively in dynamic class loading
approach interfaces can be utilized
 Again no binding objects required
 Follow the steps below:

Include groovy libraries in your classpath
 Create groovy class script
 Use GroovyClassLoader to parse the script
and create the class

GroovyShell Approach(Example)

In addtion to your class script you should
implement an interface to it in java (i.e
MyInterface.java)
IGSquare.groovy
MyInterface.java
public interface MyInterface {
public int square( int a );
}
class IGsquare implements
MyInterface
{
public int square( int a )
{
return a * a
}
}
GroovyShell Approach(Ex. Cont’d)
ITestGCL.java
package pkgGroovyClassLoader;
import groovy.lang.GroovyClassLoader;
import java.io.File;
import java.io.IOException;
import org.codehaus.groovy.control.CompilationFailedException;
public class ITestGCL {
public static void main(String[] args) throws
CompilationFailedException, IOException, InstantiationException,
IllegalAccessException {
GroovyClassLoader loader = new GroovyClassLoader();
Class groovyClass = loader.parseClass( new
File(“IGSquare.groovy”) );
MyInterface myObject = (MyInterface)
groovyClass.newInstance();
int answer = myObject.square( 3 );
System.out.println( answer );
}
}
GroovyScripEngine Approach
Uses GroovyScriptEngine to run groovy
scripts
 Follow the steps below:

Include groovy libraries in your classpath
 Set binding object for passing the parameters
to methods
 Define a root that stores your scripts
embedded
 Use run method of secript engine to run the
script

GroovyShell Approach(Example)

Very similar to shell instead this time you
run scripts in .groovy files
GHello.groovy
output = “Hello, ${input}!”
foobar = 2
Key Points:


Binding keeps values assigned in these scripts
Tracing of modification of scripts inside the root defined
and updating the other dependent scripts accordingly
GroovyShell Approach(Ex. Cont’d)
TestGSE.java
package pkgGroovyScriptEngine;
import java.io.IOException;
import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;
import groovy.util.ResourceException;
import groovy.util.ScriptException;
public class TestGSE {
public static void main(String[] args) throws
CompilationFailedException, IOException, InstantiationException,
IllegalAccessException {
String[] roots = new String[] { “./” };
GroovyScriptEngine gse = new GroovyScriptEngine(roots);
Binding binding = new Binding();
binding.setVariable(“input”, “Class”);
gse.run(“Ghello.groovy”, binding);
System.out.println(binding.getVariable(“output”));
System.out.println( “foobar is “ +
binding.getVariable(“foobar”));
}
}
Groovy Markup

Support for various markup languages
such as:
XML
 HTML
 SAX
 W3C DOM
 Ants
 Swing UI

XML-Tree Generation


Manages XML-Tree generation
MarkupBuilder() method is used
data = [ 'Seçkin': [ 'eBay':7, 'GittiGidiyor':5 ], 'Canan': [ 'eBay':9, 'GittiGidiyor':4 ] ]
xml = new groovy.xml.MarkupBuilder()
xml.people() {
for ( entry in data ) {
person( name: entry.key ) {
for ( e_shop in entry.value ) {
online_shop(){
name( e_shop.key )
rating( e_shop.value )
}
}
}
}
}
XML-Tree Generation Result
<people>
<person name='Seçkin'>
<online_shop>
<name>eBay</name>
<rating>7</rating>
</online_shop>
<online_shop>
<name>GittiGidiyor</name>
<rating>5</rating>
</online_shop>
</person>
<person name='Canan'>
<online_shop>
<name>eBay</name>
<rating>9</rating>
</online_shop>
<online_shop>
<name>GittiGidiyor</name>
<rating>4</rating>
</online_shop>
</person>
</people>
Advantages
 General
syntactical
simplicity
 Ease of use of
closures and
iterators
XML-Tree Parsing
xml = """<people>
<person name='Seçkin'>
<online_shop>
<name>eBay</name>
<rating>7</rating>
</online_shop>
<online_shop>
<name>GittiGidiyor</name>
<rating>5</rating>
</online_shop>
</person>
<person name='Canan'>
<online_shop>
<name>eBay</name>
<rating>9</rating>
</online_shop>
</person>
</people>"""
people = new
groovy.util.XmlParser().parseText( xml )
people.person['@name']
Similar to Java
 Uses XMLParser()
method
 Advantage:
- Much easier to
implement compared
to Java

GroovySQL

Ease of JDBC programming with power of closures and
iterators
A simple code that prints the people’s names in the
database:
import groovy.sql.Sql
import java.sql.DriverManager;
sql =
Sql.newInstance("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=temp
db", "sa", "sa", "com.microsoft.jdbc.sqlserver.SQLServerDriver" );
sql.eachRow("select * from GroovySQL", { println it.id + " -- ${it.firstName}
${it.lastName} --"} );
Web Development
Groovylet
Groovylet is basically the counterpart of a
Servlet in Java
 Alternative to servlet
 Same with Servlet as programming
capabilities are considered
 Syntactically simple and easy( groovy )

Using Groovylet

Setting system variables and environment
Place the archives groovy.jar and asm.jar into
the WEB-INF/lib directory and configure the
buildpath
 Insert the following tags to WEB-INF/web.xml
file <servlet>

<servlet-name>Groovy</servlet-name>
<servlet-class>groovy.servlet.GroovyServlet</servletclass>
</servlet>
<servlet-mapping>
<servlet-name>Groovy</servlet-name>
<url-pattern>*.groovy</url-pattern>
</servlet-mapping>
Groovylet (Example)

Create a simple HTML file that takes
username and password from user and do
from action "Login.groovy”
Login.html
<html>
<head><title>Login</title></head>
<body>
<h3>Enter your credentials</h3>
<form action="Login.groovy" method=POST>
Username: <input type=text name=username size=20>
Password: <input type=text name=password size=20>
</form></body></html>
Groovylet (Ex. Cont.’d)
Login.groovy
def username= request.getParameter("username")
def password= request.getParameter("password")
if (username == "java" && password == "developer") {
response.sendRedirect("home.jsp")
session = request.getSession(true);
session.setAttribute("name", username)
}
else {
println """
<h1>Login Invalid</h1>
<p>Your IP has been logged > ${request.remoteHost}</p>
"""
paramMap = request.getParameterMap()
println "<p>You Submitted:</p>"
for (entry in paramMap) {
println "${entry.key} = ${entry.value}<br/>"
}
}
Conclusion


Groovy scripting language is in progress. If you are
accustomed to use other languages a lot, it is possible
for you to find one more language unnecessary but
Groovy seems to be a language in competition with our
favorite languages and have the potential to take place
of them.
In the meantime, Groovy has a lot going for it. It nicely
blends some of the most useful features of Ruby,
Python, and Smalltalk, while conserving core syntax
based on the Java language. For developers familiar
with the Java platform, Groovy provides a simpler
alternative with almost no ramp-up time. For developers
new to the Java platform, it may act as an easy entry
point to the more extensive syntax and requirements of
the Java language.
References
groovy.codehaus.org/
 http://www.onjava.com/pub/a/onjava/2004/
09/29/groovy.html
 http://www.indicthreads.com/articles/1131/
groovy_grails_getting_started_guide.html
