List of Figures

Chapter 1. Why add Groovy to Java?

Figure 1.1. Groovy generates bytecodes for the Java Virtual Machine. Either compile them ahead of time or let the groovy command generate them from source.

Figure 1.2. Arrays and strings from a duck-typing point of view. Each is a collection with an append method. If that’s all we care about, they’re the same.

Chapter 2. Groovy by example

Figure 2.1. The Google Chart API “Hello, World” example

Figure 2.2. Apply collect to a map to convert it into a list, where each entry is transformed into a string.

Figure 2.3. The “Hello, World” Swing user interface, holding the image returned by Google Chart

Figure 2.4. Groovy Baseball is a web application that shows the results of MLB games on a given date.

Figure 2.5. Building Groovy Baseball, part 1—geocoding stadium data and saving in DB

Figure 2.6. Building Groovy Baseball, part 2—extracting box score data and creating output POGOs

Figure 2.7. Building Groovy Baseball, part 3—drive system and generate XML

Figure 2.8. Links to baseball games played on May 5, 2007

Chapter 3. Code-level integration

Figure 3.1. Guide to integration features. Groovy can be accessed with Java classes alone using the JSR 223 script engine. If you are willing to add some Groovy library classes to Java, the Eval, GroovyShell, and Binding classes make working with scripts easy. The best way to combine Groovy and Java is using classes for both languages.

Figure 3.2. Using the JSR 223 ScriptEngine to invoke a Groovy script. Java creates a ScriptEngineManager, which then yields a ScriptEngine. After supplying parameters to the engine, its eval method is invoked to execute a Groovy script.

Figure 3.3. The Groovy script for accessing the Google V2 geocoder

Figure 3.4. Java calls the me, x, xy, or xyz method in the Groovy Eval class to execute a script.

Figure 3.5. Java code sets variables in the Binding, which is used in the GroovyShell to execute Groovy code. The results are returned via the getVariable method in the Binding.

Figure 3.6. Mixing Java and Groovy classes. The Java app instantiates a Location and supplies it with street, city, and state values. It sends the new Location to the Groovy geocoder, whose fillInLatLng method supplies the latitude and longitude, which can then be retrieved by Java again.

Chapter 4. Using Groovy features in Java

Figure 4.1. Groovy features that can be added to Java classes

Figure 4.2. Groovy adds a map-based constructor to Java classes, regardless of what constructors are already included.

Figure 4.3. Groovy operators are implemented as methods, so if the Java class contains the right methods, Groovy scripts can use the associated operators on their instances.

Figure 4.4. Groovy adds convenience methods to classes in the Java standard library.

Figure 4.5. The @Delegate AST transformation exposes all methods in the delegates through the composite object. The transformation only works in Groovy classes, but the delegates themselves can be in Groovy, Java, or both.

Figure 4.6. The @Immutable AST transformation results in an immutable object that can be used in both Java and Groovy clients.

Figure 4.7. Using an XmlSlurper or XmlParser to populate an object from XML data

Figure 4.8. Generating an XML representation of an object using a groovy.xml.MarkupBuilder

Chapter 5. Build processes

Figure 5.1. Guide to technologies in this chapter. Java approaches are based on Ant or Maven. Groovy supplies Ant tasks for compilation and executing scripts. Gant is used by Grails but will eventually be replaced by Gradle. The AntBuilder class is useful and built into Gradle. There are two separate plugins available for Maven builds. Groovy Grapes make it easy to deliver code (normally scripts) to a client without compiling it first. Ultimately, though, the future belongs to Gradle.

Figure 5.2. Standard Maven project structure used for the application in this section. Compiled sources are in src/main/java, and tests reside in src/test/java.

Chapter 6. Testing Groovy and Java projects

Figure 6.1. Java tests in this chapter are from JUnit. The standard Groovy library includes a subclass of JUnit’s TestCase called GroovyTestCase, and its subclasses are useful as well. The Spock framework is a very popular alternative testing API that includes a JUnit test runner. Groovy makes it easy to create mock objects through library classes like Expando, MockFor, and StubFor.

Figure 6.2. The isPrime method has a bug, but the rest are fine.

Figure 6.3. A UML diagram of a simple banking system that uses a service, and a DAO implementation based on flat files. Dashed open arrows represent dependencies, solid open arrows are associations, and the dashed closed arrow indicates implementation.

Figure 6.4. The geocoder relies on an XmlSlurper instantiated locally to do its job. The goal is to modify its parse method to return the needed value, even though the slurper is a local variable in the test method.

Figure 6.5. Results of the Spock data-driven tests. The test with the @Unroll annotation is shown in the Eclipse output as “unrooted,” showing different output messages for each set of data.

Chapter 7. The Spring framework

Figure 7.1. Guide to the Spring technologies with Groovy. Spring manages POGOs as easily as POJOs, so the examples include Groovy implementations of both normal beans and aspects. Closure coercion is used to implement the RowMapper interface in a JdbcTemplate. Refreshable beans are Groovy source files that can be modified at runtime. Inline scripted beans are included inside XML configuration files. Grails provides a BeanBuilder class for configuring beans. Finally, Spock has a library that allows it to be used with Spring’s test context feature.

Figure 7.2. A simple account management application. Transactions are demarcated in the service layer. The persistence layer consists of a single DAO class that implements an interface and uses the Spring JdbcTemplate to access an embedded database.

Figure 7.3. The GroovyEvaluator is a refreshable bean. The source code is deployed, and Spring checks it for changes after each refresh interval. If it has changed, Spring reloads the bean.

Figure 7.4. Spring AOP in action. ChangeLogger is a Java aspect that logs a message before each set method. UpdateReporter does the same in Groovy but reports on existing values. The GroovyAspect is an inline scripted bean defined inside the configuration file.

Chapter 8. Database access

Figure 8.1. Java uses JDBC and JPA, with Hibernate being the most common JPA provider. Most NoSQL databases have a Java API that can be wrapped by Groovy; in this chapter GMongo is used to access MongoDB. GORM is a Groovy DSL on top of Spring and Hibernate. Finally, the groovy.sql.Sql class makes it easy to use raw SQL with a relational database.

Figure 8.2. Controllers contact transactional session EJBs, which acquire database data through entity EJBs. The data is copied to transfer objects and returned to the controller.

Figure 8.3. An entity relationship diagram for the generated database, given the domain classes listed in the text

Figure 8.4. New and deleted objects are transient. When they are saved they become persistent, and when the session closes they become detached. Knowing the state of an object is key to understanding how it works in Hibernate.

Figure 8.5. A portion of the vampire movies database, using the MonjaDB plugin for Eclipse

Chapter 9. RESTful web services

Figure 9.1. Server-side JAX-RS technologies in this chapter. JAX-RS 2.0 is annotation-based but includes builders for the responses. URIs are mapped to methods in resources, which are assigned using annotations. Resources are returned as representations using content negotiation from client headers.

Figure 9.2. Client-side REST technologies in this chapter. Unlike JAX-RS 1.x, version 2.0 includes client classes. Apache also has a common client, which is wrapped by Groovy in the HttpBuilder project. Finally, you can use standard Groovy classes to parse requests and build responses manually.

Figure 9.3. Hypermedia approaches in this chapter. Hypermedia in JAX-RS is done through transitional links in the HTTP headers, structural links in the message body, or customized responses using builders and slurpers.

Figure 9.4. Transitional links appear in the HTTP response headers, while structural links are part of the response objects. In each case the links can be used to access other resources from this one.

Chapter 10. Building and testing web applications

Figure 10.1. Guide to the technologies in this chapter. Spring provides mock objects for testing that are also used in Grails. Using plugins and some configuration, Gradle builds can do integration testing of web applications. The ServletCategory class makes session, request, and other objects easier to use. Groovlets are a quick way to build simple applications. Finally, the HTTPBuilder project provides a programmatic web client, and Grails applications use Groovy DSLs and elegant metaprogramming to combine Spring and Hibernate in a standard convention-over-configuration framework.

Figure 10.2. The GroovyDocs for ServletCategory. Each method is static and is added to the class listed in the first argument.

Figure 10.3. Servlet tests using Spring mocks. The Spring API provides mock classes for the request, response, and session, and captures outputs, forwards, and redirected URLs.

Figure 10.4. Web project layout. The integrationTest directories are discussed later in this chapter. The project has the standard Maven structure for a web application.

Figure 10.5. The layered design of every Java web application ever made. Presentation layer classes, including controllers, go through transactional services to access persistent data.

Figure 10.6. The Model-View-Controller (MVC) architecture, little changed since the days of Smalltalk. Views display model objects, which are created and configured by controllers.

Figure 10.7. Standard layout for all Grails applications. Adherence to convention over configuration makes it easy to find the various components, from controllers to services to domain classes to views.

Figure 10.8. Displaying the castles on a Google Map. The Castle domain classes have their latitude and longitude coordinates set by the GeocoderService. The Google Visualization plugin generates the proper JavaScript to add them to a Google Map.

Appendix A. Installing Groovy

Figure A.1. The Groovy console, which comes with the Groovy distribution. Remember to go under the View menu and select Auto Clear Output On Run to make the tool far more practical.

Appendix B. Groovy by feature

Figure B.1. Access any linear collection using an index from either end. The first element is at index 0. The last element is at index –1. You can also use subranges, as in mylist[-4..-2].

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.79.241