Adamovich / Fiandesio | Groovy 2 Cookbook | E-Book | www.sack.de
E-Book

E-Book, Englisch, 394 Seiten

Adamovich / Fiandesio Groovy 2 Cookbook

Java and Groovy go together like ham and eggs, and this book is a great opportunity to learn how to exploit Groovy 2 to the full. Packed with recipes, both intermediate and advanced, it's a great way to speed up and modernize your programming.
1. Auflage 2025
ISBN: 978-1-84951-937-3
Verlag: De Gruyter
Format: PDF
Kopierschutz: Adobe DRM (»Systemvoraussetzungen)

Java and Groovy go together like ham and eggs, and this book is a great opportunity to learn how to exploit Groovy 2 to the full. Packed with recipes, both intermediate and advanced, it's a great way to speed up and modernize your programming.

E-Book, Englisch, 394 Seiten

ISBN: 978-1-84951-937-3
Verlag: De Gruyter
Format: PDF
Kopierschutz: Adobe DRM (»Systemvoraussetzungen)



Get up to speed with Groovy, a language for the Java Virtual Machine (JVM) that integrates features of both object-oriented and functional programming. This book will show you the powerful features of Groovy 2 applied to real-world scenarios and how the dynamic nature of the language makes it very simple to tackle problems that would otherwise require hours or days of research and implementation.

Groovy 2 Cookbook contains a vast number of recipes covering many facets of today's programming landscape. From language-specific topics such as closures and metaprogramming, to more advanced applications of Groovy flexibility such as DSL and testing techniques, this book gives you quick solutions to everyday problems.

The recipes in this book start from the basics of installing Groovy and running your first scripts and continue with progressively more advanced examples that will help you to take advantage of the language's amazing features.

Packed with hundreds of tried-and-true Groovy recipes, Groovy 2 Cookbook includes code segments covering many specialized APIs to work with files and collections, manipulate XML, work with REST services and JSON, create asynchronous tasks, and more. But Groovy does more than just ease traditional Java development: it brings modern programming features to the Java platform like closures, duck-typing, and metaprogramming.

In this new book, you'll find code examples that you can use in your projects right away along with a discussion about how and why the solution works. Focusing on what's useful and tricky, Groovy 2 Cookbook offers a wealth of useful code for all Java and Groovy programmers, not just advanced practitioners.

Adamovich / Fiandesio Groovy 2 Cookbook jetzt bestellen!

Weitere Infos & Material


Embedding Groovy into Java


There are plenty of scripting languages available at the moment on the JVM. Some of them only offer expression language support for data binding and configuration needs, for example, MVEL (http://mvel.codehaus.org/) and SpEL (Spring Expression Language, http://www.springsource.org/documentation). Others provide a fully featured programming language. Examples of these are JRuby, Jython, Clojure, Jaskell, and of course, Groovy.

In this recipe, we will show you how to benefit from Groovy scripting from within your Java application.

Getting ready


To embed Groovy scripts into your Java code base, first of all, you need to add library to your class path. Or if you are using Java 7 and want to take advantage of the optimization, you should add instead (see also the recipe in Chapter 1, ).

These libraries are located inside the Groovy distribution archive under the folder. Another way to get those JAR files is from Maven Central Repository at http://search.maven.org/.

The artifact contains all the required classes to run Groovy code. It also includes dependencies such as Antlr, ASM, and Apache Commons inside the archive to be able to run Groovy with only single JAR on the class path. However, you shouldn't worry about class version conflicts if you use one of these libraries because all foreign classes are placed under special packages inside the library.

How to do it...


There are several ways in which a Groovy script can be invoked from your Java application, but the recommended one—and also the simplest—is using the class.

  1. Let's start by creating a new Java class named that has the following content:
    import groovy.lang.GroovyShell; import groovy.lang.Script; import java.io.File; import java.io.IOException; import org.codehaus.groovy.control.CompilationFailedException; public class CallGroovyUsingGroovyShell { public static void main(String[] args) throws CompilationFailedException,IOException { // Create shell object. GroovyShell shell = new GroovyShell(); double result = (Double) shell. evaluate("(4/3) * Math.PI * 6370 " + "// Earth volume in cubic killometeres "); System.out.println(result); } }

    The class instantiates a object and calls the method of the object by passing a containing Groovy code.

  2. Let's explore more methods of the class by adding the following Java code to the method:
    shell.evaluate("name = 'Andrew'"); shell.setVariable("name", "Andrew"); shell.evaluate("println \"My name is ${name}\""); shell.evaluate("name = name.toUpperCase()"); System.out.println(shell.getVariable("name")); System.out.println(shell.getProperty("name")); shell.evaluate("println 'Hello from shell!'"); System.out.println(shell.evaluate(" 1 + 2 "));
  3. In the same folder where the newly created Java class is located, place a Groovy script named , with the following content:
    def scriptName = 'external script' name = scriptName println "Hello from ${name} on ${currentDate}!" def getCurrentDate() { new Date().format('yyyy-MM-dd') }
  4. Let's continue by adding a new line to the method of our Java class:
    shell.evaluate(new File("script.groovy"));
  5. Now compile and run the class. The library must be located in the same folder as the Java and the Groovy file.

    On Linux/OS X:

    javac -cp groovy-all-2.1.6.jar CallGroovyUsingGroovyShell.java java -cp .:groovy-all-2.1.6.jar CallGroovyUsingGroovyShell

    On Windows:

    javac -cp groovy-all-2.1.6.jar CallGroovyUsingGroovyShell.java java -cp .;groovy-all-2.1.6.jar CallGroovyUsingGroovyShell

    The output should look as follows:

    6682.593603822243 My name is Andrew My name is Andrew ANDREW ANDREW Hello from shell! 3 Hello from external script on 2013-08-31!
  6. Let's add more examples to the class. Append the following lines to the method of the class:
    Script script = shell.parse(new File("script.groovy")); script.run(); System.out.println(script. invokeMethod("getCurrentDate", null)); System.out.println(script.getProperty("name")); // Calling internal script script = shell.parse("println 'Hello from internal script!'"); script.run(); script = shell.parse(new File("functions.groovy")); System.out.println(script.invokeMethod("year", null));
  7. Add one more Groovy file to the list of files for this recipe, named :
    def year() { Calendar.instance.get(Calendar.YEAR) } def month() { Calendar.instance.get(Calendar.MONTH) } def day() { Calendar.instance.get(Calendar.DAY_OF_MONTH) }
  8. Compile and run again; the additional output should look as follows:
    Hello from external script on 2013-08-31! 2013-08-31 external script Hello from internal script! 2013

How it works...


In the Java class example, the object is instantiated using the default constructor.

In step 1, the Groovy code passed to the method calculates the result of the simple arithmetical expression. No statement is used, but still the expression evaluates correctly. The reason is that in Groovy, the statement is optional, and an expression will always return the value of the last statement. The mathematical expression's result type is as we only operate with floating numbers; this is why we can safely cast it.

Furthermore, the expression refers to a constant defined in the class, without explicitly importing it. This is possible due to the fact that Groovy imports all classes automatically, just like Java.

There is also a comment at the end of the expression, which is safely ignored. Similar to Java, comments can appear anywhere in Groovy code.

The object supports defining global variables, which can be re-used by evaluated scripts, by using the method, as displayed in step 2.

The variable is set and then used inside a script evaluated later. The variable will be available to all the scripts executed throughout the lifetime of the object.

The variable's value can also be changed during script execution and retrieved later using the method.

In step 3, we can observe another useful feature of the integration of Groovy with Java; the possibility of executing external Groovy scripts from Java by passing a object to the method.

You can also create individual objects for repeated executions:

Script script = shell.parse(new File("HelloWorld2.groovy")); script.run(); // run first time script.run(); // run second time

In this case, the script code will be compiled by the method and the script execution will be faster than if we do repeated calls of the method.

Steps 6 and 7 show how you can also execute individual methods if they are defined by the code located in an external script. Once the script is successfully compiled, the can be used to call any function declared in the external script.

There's more...


If you are familiar with JSR-223, which provides the specification for the Java SE scripting API, you can also use it with Groovy. JSR-223 is recommended over the approach if you want to be able to switch to a different scripting language at any point. The next example shows how to get started with the scripting API:

import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class CallGroovyUsingJSR223 { public static void main(String[] args) throws ScriptException { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("groovy"); // Expression evalution. System.out .println(engine.eval("(4/3) * Math.PI * 6370 " +"// Earth volume in cubic killometeres ")); // Variable binding. engine.put("name", "Andrew"); engine.eval("println \"My name is ${name}\""); } }

The key to start using Groovy with JSR-233 is again to add the artifact to the classpath. Adding the jar will automatically bind the Groovy script engine into JVM, which can be retrieved by a call to as shown in the previous example. Please note that the JSR-233 specification is only available from Java 6.

Another way to dynamically embed Groovy into Java code is by defining the Groovy classes and parsing them with...


Adamovich Andrey :

Andrey Adamovich is a software craftsman with many years of experience in different lifecycle phases of software creation. He is passionate about defining good development practices, documenting and presenting architecture, the reuse of code and design patterns, the profiling and analysis of application performance, as well as extreme automation of development and operations activities. He is a longtime Groovy user and has a deep knowledge of the language internals. He uses Groovy in his day-to-day development job for simplifying the development process, which includes: code generation, super cool DSLs, and rapid prototyping. He has Master's degree in Computer Science from the Latvian State University.Fiandesio Luciano :

Luciano Fiandesio is a programmer, technology enthusiast, and entrepreneur living in Zurich, Switzerland. Luciano has been working for the last 18 years in 12 different countries as an architect and developer for large corporations and small start-ups: Nokia, European Central Bank, BNP Paribas, and Ericsson are among his clients. He loves coding and designing solutions that are both elegant and rock solid. When not busy learning the next big thing, he likes playing with his analog cameras and cooking Italian food. Two years ago, he started a consulting company focused on software factory automation, Aestas IT, where Groovy plays a big role. He holds a Master's degree in Literature and Philosophy from Rome University. Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable \u0001{mso-style-name:"Table Normal"; \u0001mso-tstyle-rowband-size:0; \u0001mso-tstyle-colband-size:0; \u0001mso-style-noshow:yes; \u0001mso-style-priority:99; \u0001mso-style-parent:""; \u0001mso-padding-alt:0in 5.4pt 0in 5.4pt; \u0001mso-para-margin-top:0in; \u0001mso-para-margin-right:0in; \u0001mso-para-margin-bottom:10.0pt; \u0001mso-para-margin-left:0in; \u0001line-height:115%; \u0001mso-pagination:widow-orphan; \u0001font-size:11.0pt; \u0001font-family:"Calibri","sans-serif"; \u0001mso-ascii-font-family:Calibri; \u0001mso-ascii-theme-font:minor-latin; \u0001mso-hansi-font-family:Calibri; \u0001mso-hansi-theme-font:minor-latin;} The authors have created support website for the book - http://groovy2cookbook.com



Ihre Fragen, Wünsche oder Anmerkungen
Vorname*
Nachname*
Ihre E-Mail-Adresse*
Kundennr.
Ihre Nachricht*
Lediglich mit * gekennzeichnete Felder sind Pflichtfelder.
Wenn Sie die im Kontaktformular eingegebenen Daten durch Klick auf den nachfolgenden Button übersenden, erklären Sie sich damit einverstanden, dass wir Ihr Angaben für die Beantwortung Ihrer Anfrage verwenden. Selbstverständlich werden Ihre Daten vertraulich behandelt und nicht an Dritte weitergegeben. Sie können der Verwendung Ihrer Daten jederzeit widersprechen. Das Datenhandling bei Sack Fachmedien erklären wir Ihnen in unserer Datenschutzerklärung.