Groovy - Java's scripting language
Bymark Volkmann, Partner Object Computing, Inc. (OCI)
Translation: Raxy
Introduction
Groovy is an open source scripting language implemented with Java and is closely related to it. It requires JDK 1.4. Groovy adds many Ruby and Python scripting language to Java. Groovy features Dynamic Typing, Closure (Closures) Easy Object Navigation and a more simple Lists and MAPS syntax. All these features and other features will be described in detail in this article.
Here is the words on the Groovy webpage. "Groovy is designed to deactivate the transaction on the Java platform in a streamlined way, and bring powerful features similar to Python Ruby to Java."
The Groovy script can use any Java class. They can be compiled into a Java bytecode (ie .class file) and can be referenced by any normal Java class .Groovy compiler, Groovyc, you can compile the Groovy script file and Java source file, however Some grams (such as internal category) are not supported.
In theory, you can write a complete application with Groovy, which has a similar performance of the same Java application. This is a different, Python, Perl, and Beanshell, which is Groovy and other scripting languages. Make Groovy now run better than Java. One of the slow reasons is that the generated bytecode uses the mapping to invoke the constructor and the private / protection method. This issue will be resolved in later versions.
Groovy is created by James StraChan and Bob McWhirter. James also participates in many other open source projects, including Jelly, Dom4j, Jaxen, BetWixt and Maven. Bob is Jaxen and Drools (an open source-oriented Java rule engine) The founder.
This article does not involve all the characteristics of Groovy, but only involves most of them. It assumes that you have enough understanding of Java's syntax and compare the syntax of Java and Groovy.
If we can reach an agreement on what kind of grammar in a good programming language, then we don't need so many languages. Such a large number of programming languages will be excluded, obviously we don't agree. (Based on the Number of Programming Languages Out There, We Obviously Don't agree.) After reading this article, you may think that Java's syntax is already available and thinks of Groovy's syntax is not a taste. If your conclusion is like this, I encourage You study Pat Niemeyer's Beanshell is at http://www.beanshell.org/. It is closer to the standard Java syntax. On the other hand, if you like the short syntax of Groovy, then Groovy!
Download and install Groovy
Use the following steps to download Groovy.
1. Visit http://groovy.codehaus.org/.
2. Click on "Download" in the top of the top navigation bar.
3. Click the "this site" link.
4. Select a version download.
The latest version can be downloaded in CVS. Description of the operation steps can be found here.
To install Groovy, use the following steps.
1. Unzip the downloaded file.
2. Set the environment variable groovy_home to the decompressed directory.
3. Add $ Groovy_Home / Bin (Unix) or% Groovy_Home% / BIN (Windows) to the environment variable Path.
Run Groovy
There are four ways to run the Groovy script. In these ways, the script will be parsed, converted into Java source code and compile into Java bytecode (bytecode). Interacting shell
Command Groovysh launched an interactive shell where you can enter a Groovy statement. Enter some statements, press Enter to the ENTER key at each statement. The statement is not evaluated or executed until you enter the execute command .
Interactive Swing Console
The GroovyConsole command will start a Swing window. Enter the Groovy statement in the lower half of the window. Select Run to run them in the ActionS menu. The output content is displayed in the upper half of the window. You can open and save the script file in the File menu.
Run script file
A Groovy script file (file extension is .Groovy) can run using the command groovy script-name.groovy.
Run compilation script
Using the command groovyc script-name.groovy, a Groovy script file can be compiled as a Java .class file. If a loose statement is used in the script file (Loose Statements), a .class file will contain a main method, so It can run Java Script-name like a Java application. The content of the main method will be mentioned later. ClassPath must contain the Groovy * .jar and the ASM * .jar file in the Groovy Lib directory.
There is a custom Ant task to complete this task! This class is org.codehaus.groovy.ant.groovyc.
Some grammar details
The following is the crucial difference between Java and Groovy syntax. Other we will talk about it later.
· Its goal is to support all legitimate Java syntax, but this goal has not yet reached.
· The semicolon ending each line of statement is available.
· The parentheses next to the method of the method are also available unless otherwise no parameters or non-brackets. However, parentheses in the constructor are required. Some people prefer to use circles Brackets. This article tends to omit it in the case of allowing.
· "Return" statement can also be possible at some point. When a method is to return the value, if the last statement before the brace (the brace end of the method), then it will value it As a return value. After Groovy may change to the value calculated to return the list of the last executed statement.
· Groovy attributes and methods are public (public), rather than protected, which is protected in Java. We will discuss Groovy Beans later.
· Java.lang, Groovy.lang and Groovy.UTIL class are automatically imported.
Dynamic type (Dynamic Typing)
Types are available for variables, attributes, methods / closing packages (Method / Closure Parameters), and method return types. They all determine the type when assigning them. Different types will be behind Used. Any type can be used, even the basic type (through Autoboxing). When needed, the conversion between many types will occur automatically, such as the conversion between these types: string (String ), Basic types (such as INT) and types of wrapper classes (such as Integer). We can also add different basic types to the same array (Collectes).
Added Methods
Groovy adds many methods to standard Java classes such as Java.lang.Object and Java.lang.String. You can find those additions to http://groovy.codehaus.org/groovy-jdk.html. Other we will Talk DUMP
This operation returns a string Toyota Model = CAMRY>. Print and Println These two static methods print the value of the TOString method of the object. For example, Print Car or Println Car. Invokemethod This operation uses the REFLECTION to implement dynamic method calls. The syntax format is Object.InvokeMethod (Method-name, argument-array). The following example prints a value 4. s = 'abcabc' // a java.lang.string Method = 'indexof' Args = ['b', 2] Println S.InvokeMethod (Method, Args) Groovy string Strings can also use double quotes. You can use single quotes. When using double quotes, you can include embedded values. The syntax format containing the inlay is $ {expression} and Ruby language. Just It uses $ and Ruby to use #. Use the double quotation string contains at least one embedded value, then it is an object of the Groovy.lang.gstring class. Other strings are java.lang.String Objects of class. Gstrings will be enforced to java.lang.String when needed. Javadoc to the Groovy class such as grovy.lang.gstring can be found at http://groovy.codehaus.org/apidocs/. The embedded value is very helpful for implementing the toString method. For example, String toString () {"$ {name} IS $ {age} years old."} Multi-line strings can be created in three ways. The following example is equivalent. The last example uses the way known as "here-doc". After three less than numbers, it is the specified separator string. The value of the string includes all characters between the severity string, "EOS" (meaning "End of String" string means that the end of the end of the "end of string" is a normal separator, and other splitors can also be used. . s = "this string Spans three / "lines /" And Contains Two newlines. " s = "" "this String Spans Three "Lines" And Contains Two newlines. "" "" s = <<< EOS This string Spans Three "Lines" And Contains Two newlines. EOS Note: The last line of characters in the previous code snippet is not saved in the string. The following methods are added to the java.lang.string class. Contains This operation determines whether a given substring is included in a string. 'Groovy'.contains (' oo ') returns true. count This operation statistics appears in a given string. 'Groovy Tool'.count (' oo ') Returns 5.Tokenize This operation uses a given separator to divide the string (token) and return token. The specified separator parameter is optional. The default interval is space. 'Apple ^ banana ^ grape '.Tokenize ('^') Returns ['Apple', 'Banana', 'Grape']. minus This operation removes the first part of the string to give the stator string. 'Groovy Tool' - 'oo' Returns 'Grvy Tool'. Multiply This action repeats the number of times a given string. 'Groovy' * 3 Returns 'GroovyGroovyGroovy'. Regular expression (regex) First, let's review the support of J2SE 1.4 on the regular expression. So let's take a look at how Groovy is implemented. In J2SE 1.4, classes in the java.util.Regex package support regular expressions. Mode (Pattern) object represents a compiled Regex. They are created using pattern.Compile ("Pattern"). This class Javadoc description The syntax of the regular expression. The Matcher object saves a pattern that matches a string. They are created using pattern.matcher ("text"). To determine if the text is desirable to match, we use matcher.matches () / Must have corresponding to it in the mode. Groovy has three ways to support regular expressions. ~ "Pattern" Creates a mode object and is equivalent to pattern.Compile ("pattern"). "TEXT" = ~ "pattern" creates a Matcher object and is equivalent to Pattern.Compile "pattern"). Matcher ("text"). "text" == ~ "patter" - Returns a Boolean value, equivalent to pattern.Compile ("pattern"). matcher ("text"). matches (). Multi-way can see Mode and Matcher's Javadoc. E.g, Pattern = "// D {5}" // matches Zip Codes (5 digits) TEXT = "63304" // a zip code Println text == ~ pattern // Prints "true" m = text = ~ pattern Println Matches () // Prints "True" // The next line requires a literal string for the pattern. // a variable can't used. P = ~ "// D {5}" m = p.matcher (text) Println Matches () // Prints "True" Groovy script Groovy's script file is usually named ".groovy" is the suffix. They can contain (in any order) loose statements, definitions that are associated with the class, and class definitions. E.g, // These is. Println 'Loose Statement'myMethod' Mark ', 19 Println New Myclass (A1: 'Running', A2: 26.2) // this is a method definition That // is not associated with a class. DEF MYMETHOD (P1, P2) { Println "MyMethod: P1 = $ {P1}, P2 = $ {P2}" } // this is a definition of a class there // Has Two Properties and One Method. Class myclass { A1; A2 String toString () {"myclass: a1 = $ {a1}, A2 = $ {a2}} } The definition of methods and classes does not need to be placed before they are used. The loose method is compiled into a static method in the corresponding class in the basic file associated with the class. For example, a loose method called Foo in bar.groovy script. Compiled a static method called FOO in class bar. Loose speech sentences are collected from the RUN method, and the method is called by compilation. When Groovyc is used to be cheaper, the generated class has a RUN method that contains all loose statements and a Main method to call the RUN method. Current scripts cannot reference the code in other scripts unless they are compiled and introduced. This will be improved soon. Operator overload Groovy supports a part of the operator operator overload. Each operator corresponds to a specific method. As long as you implement these methods in your class, you can use the corresponding operator to call these methods to operate. Method can be heavy It comes to operate different types of parameters. Compare operator A == b corresponds to a.equals (b) a! = B corresponds to! a.Equals (b) a === b corresponds to a == BA <=> b in Java corresponds to A.Compareto (b) a> B Corresponding A.Compareto (B)> 0 A> = B corresponds to a.compareto (b)> = 0 A
0 a <= b corresponds to a.compareto (b) <= 0 The comparison operator can handle the NULL value and does not generate nullpointerexception. NULL is considered to be smaller than any value. Note that in Groovy == operator is used to determine if the two objects have the same value and === operator is used to determine if they are the same object in memory. The CompareTo method returns an int value, and if a B returns a value greater than 0, returns 0 if A is equal to B. Other operators A B corresponds to A.Plus (b) A - B corresponds A.Minus (b) a * b corresponds to A.Multiply (b) A / B corresponds to A.DIVIDE (B) A And corresponds to A. Increment b) A-- AND --A corresponds to A.Decrement (b) A [b] corresponds to A.Get (b) a [b] = C corresponds to A.PUT (B, C) Groovy closure A closure is a code snippet that can be used. Each closure is compiled into a class that inherits the Groovy.lang.closure class. This class has a Call method, and we can pass the parameters and call this closure. They can access and modify variables within the range created in the closure (the change in Scope When the closure is created.) The variable created in the closure can also be Quote. Closures can be saved in variables and is passed as parameters to the method. This is very useful in some List, Map, and String methods, we will mention later. Defining the syntax format of the closure is {Comma-Separated-parameter-list | statements} E.g, Closure = {BILL, TIPPERCENTAGE | BILL * TIPPERCENTAGE / 100} Tip = Closure.call (25.19, 15) Tip = Closure (25.19, 15) / / with the previous line is equivalent The number of parameters that pass the error generate incorrectClosureArgumentException. Keyword IT is used to have only one parameter closure. The parameter list can be omitted and use IT representative parameters in the statement. For example, the closure below is equivalent. {x | println x} {PrintLn it} The following is an example of a method, which uses a list and a closure as a parameter. It is written as a "loose method", but it can also be written into a method of a class. Method Traversed this list, on the list Each item calls the closure. It uses a project that returns True using a closure to generate a new list and return to the new list. Note that the Find and FindAll methods provided by Groovy can replace it. DEF LIST MyFind (List List, Closure Closure) { List newlist = [] For (Team in List) { IF (Closure.call Team) Newlist.add Team } Newlist } Here is an example of using this method. Class Team {name; Wins; losses} Teams = [] Teams.add New Team (Name: 'Rams', Wins: 12, Losses: 4) Teams.add New Team (Name: 'Raiders', Wins: 4, Losses: 12) Teams.add New Team (Name: 'Packers', Wins: 10, Losses: 6) Teams.add New Team (Name: '49ers', Wins: 7, Losses: 9) WinningTeams = myfind (teams) {it.wins> it.losses} Winningteams.each {println it.name} There is no need to write a method like MyFind because there is already a FindAll method in the list class. Use it like this, WinningTeams = Teams.Findall {it.wins> it.losses} Groovy beans Here is an example of a Groovy bean. Class car { String make String model } This class declares two attributes without any method. However, many things are completed in the background. Class, attributes, and methods are public (public and protected) properties will become private domains. However, their public / protected GET and SET will be automatically generated. (Public and protected "result in private fields for which public / protected get and set methods are automatically generated) These can be overloaded to provide custom behavior. The GET and SET methods are not generated for explicitly declared privacy properties. The above Groovy code is equivalent to the following Java code. Public class car { PRIVATE STRING MAKE; PRIVATE STRING Model Public string getmake () { Return Make; } Public string getModel () { Return model; } Public void setmake (string make) { THIS.MAKE = Make; } Public void setmodel (String model) { THIS.MODEL = Model; } } The class generated by the Groovy Beans inherits the Java.Lang.Object class and implements the Groovy.lang.GroovyObject class. It adds to getProperty, setProperty, GetMetaClass, setmetaclass, and invokeMethod. Groovy.lang.MetaClass class Allow to add during runtime method. Groovy Beans can create a famous parameter. For example, the following code calls the non-parameter constructor of the CAR class and then calls the SET method for each independent property. mycar = new car (make: ' Toyota ', Model:' Camry ') Groovy Lists Groovy Lists is an instance of the Java.util.ArrayList class. They can be created using a comma-separated value table inside the square brackets. For example, Cars = [new car (make: 'Honda', Model: 'odyssey'), New car (Make: ' Toyota ', Model:' Camry ']]]] Println Cars [1] // Refers to Camry For (car in Cars) {println car} // calls car's TSTRING method Class car { Make; Model String toString () {"car: make = $ {opportel = $ {model}} } In order to determine the location of the List of the List of the List, we use negative indexes. Empty LISTS can be created with []. For example, Cars = [] There are two ways to add an element. Cars.Add Car CARS << Car List You can create it using an array call array.tolist () method. Array can also be created using the list to call the list.toArray () method. Groovy also added some ways to java.util.list. count This operation calculates how many elements in the LIST are equal to the given object. [1, 2, 3, 1] .count (1) returns 2. Immutable This operation uses the static method of the Java.util.Collections class UnmodifiableList to create a copy of the unwarable copy. For example, list = [1, 2, 3] .immutable () List.add 4 // throws java.lang.unsupportedOperationException exception INTERSECT This operation creates a list of two common elements containing two given LISTs. [1, 4, 3, 4] .intersect ([2, 4, 6]) returns [2, 4]. Join This operation uses a given string to connect to the value of the component's TOString. For example, it inserts a '^' separator in the middle of all string elements of the List. ['One', 'Two', 'Three'] .join ('^') Returns "One ^ Two ^ Three". Sort This action sorts the List element and creates a new list. Sort can be accepted as a parameter with java.util.comParetor or closure. Fruits = ['Kiwi', 'strawberry', 'grape', 'banana'] // The next line returns [Banana, Grape, Kiwi, Strawberry]. sortedfruits = fruits.sort () // The next line returns [Kiwi, Grape, Banana, Strawberry]. sortedfruits = Fruits.Sort {L, R | Return L.Length () <=> R.Length ()} The last Sort method call above is an example of the closure as a method parameter. There are many ways to do this in Groovy. Groovy Beans can be easily sorted to multi-attributes. Assume that there is a Player Bean with attribute Name, AGE, and Score. You can sort this BEAN's List Players first based on the AGE and sort based on Score. Players.Sort {[it.age, it.score]} Min / max These two operations identify minimal or largest List elements or string characters. They can accept Java.util.comParetor or closures as parameters. For example, they find out the smallest and largest numbers in a list. [5, 9, 1, 6] .min () Returns 1. [5, 9, 1, 6] .max () Returns 9. Reverse This operation reverses (inward) List's position or character of the character in the character string. [1, 2, 3] .reverse () returns [3, 2, 1]. Groovy Heavy loaded with the Plus and Minus operators to operate the Java.util.List object. Plus This operation creates a collection of two LISTs and deletes duplicate elements. [1, 2, 3] [2, 3, 4] return [1, 2, 3, 2, 3, 4]. minus This operation deletes all the elements that appear in the first LIST. [1, 2, 3, 4] - [2, 4, 6] return [1, 3]. When List elements Not Primitives, compare them using the Equals method. Groovy Maps Groovy's MAPS is an example of a Java.util.hashmap class. They can create a keytical List that is separated by a comma-separated keyword / value of square brackets. The keyword is separated from the colon. For example, Players = ['Baseball': 'Albert Pujols', 'golf': 'Tiger Woods'] Println Players ['golf'] // Print Tiger Woods Println Players.golf // Print Tiger Woods For (Player in Players) { Println "$ {Player.Value} Plays $ {Player.Key}" } / / The previous cycle is the same effect. Players.each {Player | Println "$ {Player.Value} Plays $ {Player.Key}" } Empty MAP can be created using [:]. For example, Players = [:] Groovy Switch Any objects can be used in the Groovy Switch statement, including classes, list, range, and pattern. CASE statements are compared using the ISCase method. The overloaded version of a lot of ISCase methods is provided. Unless is overloaded for a specific type, ISCase uses Equals. Method. When a CASE is followed by a class name, ISCase uses instanceof. Iscase method is overloaded in your class. Below is an example of the Switch statement on different types of value operation. Switch (x) { Case 'Mark': Println "Got My Name" Break Case 3..7: Println 'Got A Number in The Range 3 To 7 Inclusive' Break Case ['MoE', 'Larry', 'Curly']: Println 'Got A Stooge Name' Break Case java.util.date: Println 'Got A Date Object' Break Case ~ "// d {5}": Println 'Got A Zip Code' Break DEFAULT: Println "Got Unexpected Value $ {x}" } Groovy Ranges Use ".." and "..." operators to create Range. Below is some examples. 3..7 Create a Range from 3 to 73 ... 7 Create a Range from 3 to 6 "a" .. "d" creates a RANGE from "A" to "D" "a" ... "d" Create a Range from "a" to "c" Range is an object inherited from a Java.util.AbstractList class and implements a grang.range interface. A Range is an unmodified list. Range interface adds a GetFrom and a GetTo method to get the lower bound and the upper bound value. The RANGE interface provides two implementations. When the range limit is an integer value. It uses groovy.lang.IndRange. It adds a Contains method to determine if a value is in the range. When the range limit is used, use Groovy.lang. It also has a Contains method, but it is only useful when it is only used as a scope restricted object. Ranges is very useful in the loop. See the example below. Groovy looping Here is six ways to cycle a range. for For (i in 1..1000) {println i} While i = 1 While (i <= 1000) {println i; i } Each (1..1000). Each {println it} Times 1000.Times {PrintLn it} // Cycle value from 0 to 999 Upto 1.upto (1000) {println it} STEP 1.Step (1001, 1) {println it} // The value from 1 to 1000 is loop; // stopping one before the parameter valuelist / map / string method accepts a closure as a parameter Some LIST, MAP and STRING methods are accepted as parameters. Each This operation is used to traverse the character in the collection or a string in the string. It provides another selection to use java.util.Iiterator, you can get a simpler code. For example, print a list of a list [5 , 9, 1, 6] .each {x | Println x} or [5, 9, 1, 6]. Each {println it} Collect This operation is used to convert a collection or string into a new collection or string. For example, double each number in the list and create a new listdoupla = [5, 9, 1, 6] .COLLECT {x | x * 2} assigns Doubles to [10, 18, 2, 12]. Find This operation is used to find the first conformance set element or string character. For example, find the first number of LIST larger than 5 [5, 9, 1, 6] .find {x | x> 5} Returns 9. FINDALL This operation is used to find all qualified set elements or string characters. For example, find all the numbers in LIST [5, 9, 1, 6] .findall {x | x> 5} return [9, 6] . EVERY This operation is used to determine if each character of each element or a string is conforming to a given condition. For example, it is determined whether all numbers in the list are less than 7 [5, 9, 1, 6] .every {x | x <7} Returns false. Any This operation is used to determine if there is a set of elements or characters in a collection that conforms to a given condition. For example, it is determined whether there is less than 7 in the LIST [5, 9, 1, 6]. An {x | x <7 Returns True. inject This operation is used to pass the value to the first traversal and then pass the value of each traverse to the next time. For example, seeking 5 steps (using an uncommon way) Factorial = [2, 3, 4, 5] .INJECT (1) { PrevResult, X | PrevResult * x } This closure is performed four times. 1) 1 * 2 2) 2 * 3 3) 6 * 4 4) 24 * 5 It returns 120. File I / O Read the line in the file (two options) The omittion number (...) in the following code paradigm represents the omitted code. File = new file ('myfile.txt') File.eachline {println it} LINELIST = file.readlines () Read the byte in the file (two options) File = new file ('myfile.txt') File.eachbyte {println it} Bytelist = file.readbytes () Read files in the directory DIR = New file ('Directory-Path') Dir.eachfile {file |. Read files and close resources These methods read files through a Reader or InputStream and ensure that the resource will be closed regardless of whether there is an exception. File.withReader {reader |. Reader.withreader {reader |. InputStream.withStream {is |. Write files and close resources These methods write files through a Writer or OutputStream and ensure that the resource will be closed regardless of whether there is an exception. File.withWriter {Writer |. File.withprintwriter {pw |. File.withoutputStream {OS |... Writer.withwriter {writer |........ '<<' operator Add to string S = 'foo' s = s << 'bar' Add to a StringBuffer SB = New StringBuffer ('foo') SB << 'bar' Add to LIST Colors = ['Red', 'Green'] Colors << 'Blue' The end of the data stream w = new file ('myfile.txt'). NewWriter () W << 'foo' << 'bar' w.close () Object navigation The relationship between objects (Graphs) can be expressed by the syntax using a syntax (".") Operator similar to XPath. To avoid NullPointRexception exceptions, use operators "->" instead ".", Class team { String name Person Coach Players = [] } Class Person { String name } P = New Person (Name: 'Mike Martz') T = New Team (Name: 'Rams', Coach: P) // Next line print and team.getcoach (). GetName () the same content. Println "Coach = $ {T.coach.Name}" T = New Team (Name: 'Blues') // The next line returns empty, // Will not throw a NullPointerexception exception. Println "Coach = $ {T-> Coach-> Name}" // The next line throws the NullPointRexception exception. Println "Coach = $ {T.coach.Name}" Groovy Reflection Suppose you want to get a class object through an object. Use someobject.getClass () in Java. In Groovy, use somebject.class to complete. Suppose you want to get a class object through a class name. Use someClass.class or class.Forname ("pkg.someclass") in Java and Groovy. Print the list of all methods for Groovy GString, Gstring.class.methods.each {it.name} Print a list of all methods in java interface java.util.list, Java.util.list.class.methods.each {it.name} Capture does not implement You can write a class to capture the method that is not implemented. For example, o = new catchcall () // The next line prints "Unknown Method Mark Called with [19]". Println O. FOO ("Mark", 19) Class catchcall { InvokeMethod (String Name, Object Args) { Try { Return Metaclass.InvokeMethod (this, name, args) } catch (missingMethodeXception e) {// can be inserted here // Handle special logic for specific methods and parameters. Return "Unknown Method $ {Name} Called with $ {args}" } } } Groovy Markup Groovy's Markup uses the InvokeMethod method to capture the non-existent methods just mentioned and convert them to "NODES"). The parameters of the method are viewed as the attribute of the node. After the closure after the method It is a more and more effects including the content of the node. · Building a generic, data tree (NodeBuilder) · Build a DOM tree (DOMBUILDER) · Firing SAX Events (SAXBUILDER) · Create a string of HTML or XML (MarkupBuilder) · Execute Ant Task (ANTBUILDER) · Create a Swing user interface (SWINGBUILDER) Alternatively, custom Builders can be created by inheriting the Groovy.util.Buildersupport class. Generate HTML Here is an example of generating HTML using MarkupBuilder. Import groovy.xml.markupbuilder MB = New MarkupBuilder () Mb.html () { HEAD () { "" this is my title. ") } Body () { p ("this is my paragraph.") } } Println MB This code generates the following HTML file.
hEAD>
this is my paragraph. p>
body>
html>
Generate XML
Here is an example of using MarkupBuilder to generate an XML.
Import groovy.xml.markupbuilder;
MB = New MarkupBuilder ()
Mb.autos () {
Auto (Year: 2001, Color: 'Blue') {
Make ('
Toyota
')
Model ('CAMRY')
}
}
Println MB
This code generates the following XML file.
Toyota
make>
auto>
autos>
Groovy SQL
Groovy makes JDBC easier. Groovy.sql.sql class provides a simple way to run a query (query) and columns in the RESULTSET. In the following example, MusicCollection is the name of a database (in this case , Already registered as an ODBC data source), Artists is the name of a table in the database, and Name is the column name in the table.
Import groovy.sql.sql
DBURL = 'JDBC: ODBC: Musiccollection'
JDBCDRIVER = 'Sun.jdbc.odbc.jdbcodbcdriver'sql = SQL.NEWINSTANCE (DBURL, JDBCDRIVER)
SQL.Eachrow ('Select * from artists') {
Println it.name
}
Groovlets
Groovlets can replace servlets or JSP. It provides the following implicit variables.
· OUT - equivalent to httpservletResponse.getwriter () method
· Request - equivalent to HTTPSERVLETREQUEST
· Session - equivalent to httpsession
Below is a Groovlet example. It can be saved as a file called SimpleGrovlet.groovy. It uses "Here-Doc" to generate an HTML file.
Out.println <<< EOS
hEAD>
Today is $ {new java.util.date ()}. p>
body>
html>
EOS
GroovyServlet compiles the Groovlet and provides cache acceleration (cache) until their content changes. After the Groovlet changes, the GroovyServlet will automatically recompile the Groovlet. GroovyServlet must be registered in Web.xml.
Below is an example of the web.xml file to simply demonstrate the part of the registered GroovyServlet.
XML Version = "1.0"?>
Public "- // Sun microsystems, Inc.//dtd Web Application 2.3 // en"
"http://java.sun.com/dtd/web-app_2_3.dtd">
servlet>
servlet-maping>
web-app>
Groovlets can be deployed with Ant. Basic steps are
1. Create a WAR with the following below.
o The top of the Groovlet source file (* .groovy)
o Web.xml in the o Web-INF folder
o Groovy * .jar and asm * .jar files in the web-inf / lib folder
2. Deploy this WAR in a servlet engine such as Tomcat.
Here is the ANT construction file for this matter.
Build.properties
Build.dir = build
Src.dir = SRC
# Directory That Contains Groovlets
Groovy.dir = $ {src.dir} / groovy # Directory That Contains Web.xml
Web.dir = $ {src.dir} / web
# Path to War That Will Be Product
War.file = $ {build.dir} / $ {ant.project.name} .war
# Where the war shop be deployed
WebApps.dir = $ {env.tomcat_home} / webapps
# Jars That Must Be in the War
ask.jar = $ {env.groovy_HOME} / lib / asm-
1.4.1
.jar
Groovy.jar = $ {env.groovy_HOME} /lib/groovy-1.0-beta-4-snapshot.jar
Build.xml
target>
Description = "Creates War File"> war> target> Description = "Deploys War File"> target> provject> After this Groovlet example is deployed, you can make it displayed in your browser http: // localhost: 8080 / groovlexample / simplegrovlet.groovy. GrooowTexample is the name of the web application. SimpleGroovlet.groovy It is the name of the Groovlet. This is the URL-Pattern specified by the groovyservlet in the web.xml file. Issues Groovy is not perfect. Browse about Groovy articles, please visit http://groovy.codehaus.org/ and click on the Issue Tracker connection. Below is some published articles and its number. · Primitive parameters to methods and closeness parameters to methods and closures am Tsupported YET (128 & 133). · Arrays of primities Aren't supported yet (119). · Static Primitive Fields Aren't Supported YET (153). · CHAINED ASSIGNMENT (x = y = 19) ISN't Supported YET (57). · * Imports aren't supported yet (84). • Compiler Doesn't catch calls to non-eviistent methods on staticly typed parameters (170). · NESTED CLASSES AREN'T Supported YET (69). to sum up We have quickly browsed some grammar and characteristics of Groovy. These Java-based shortcuts let you have done more work? Are you found more fun in your work? Your code makes it easier to understand or more Is it difficult? I hope to see your feedback. Give me email: mark@ociweb.com. You can also share your feedback here in the Groovy mailing list. bibliography Groovy Home Page - http://groovy.codehaus.org/