Integrating Groovy

Total Page:16

File Type:pdf, Size:1020Kb

Integrating Groovy Integrating Groovy We build too many walls and not enough bridges. —Isaac Newton 360 Getting ready to integrate 361 One of the biggest advantages of Groovy (even one of the reasons for its inception) is the fact it integrates natively with Java because both languages run on the same platform. It is important to understand what makes Groovy such an attractive option when you need to embed a scripting language in your application. First of all, from a corporate perspective, it makes sense to build on the same platform that most of your projects are already running on. This protects the investment in skills, experience, and technology, mitigating risk and thus costs. Where Java isn’t a perfect fit as a language, Groovy’s expressiveness, brevity, and power features may be more appropriate. Conversely, when Groovy falls short because of the inevitable trade-off between agility and speed, performance- critical code can be replaced with raw Java. These balancing decisions can be made early or late with few repercussions due to the close links between the two languages. Groovy provides you with a transparent integration mechanism that permits a one-to-one mix-and-match of Java and Groovy classes. This is not always the case with other scripting solutions, some of which just provide wrap- pers or proxies that break the object hierarchy contract. This chapter will show you how to integrate Groovy with Java in various ways. First we’ll examine three facilities provided by Groovy: GroovyShell, Groovy- ScriptEngine, and GroovyClassLoader. We will then consider the scripting sup- port provided by the Spring framework and Java 6, code-named Mustang. You will see that by integrating Groovy and Java, you can leverage the vast libraries of available Java classes and also enjoy the benefits of the extremely agile dynamic capabilities Groovy provides. All this can be done with seamless integra- tion of the two languages. 11.1 Getting ready to integrate The interplay between Groovy and Java means that it is easy to make them coop- erate in various ways. The most obvious way is to make Groovy code call into Java code, either using one of the command-line tools to load and run Groovy scripts directly, or using groovyc to compile Groovy into normal Java class files. This assumes that all the code is known before the application needs to be compiled. It doesn’t allow for any just-in-time provision of code, whether that’s through users entering expressions as they might into a graphing calculator or developers pro- viding replacement scripts for just the bits of code that require frequent changes within a live system. As an idea of how widely used this kind of facility can be, consider Visual Basic (VB). We’re not in the business of judging its pros and cons, but it would be hard to 362 CHAPTER 11 Integrating Groovy deny that VB is popular and has been for a long time. Although many developers write whole applications in VB from scratch, far more use the capability of various products to embed pieces of VB code in order to customize behavior in ways the original developers may never have even considered. Now consider allowing that kind of flexibility in your application. Instead of hearing people talking about writing VB in Microsoft Office, imagine those same people talking about writing Groovy in your application. Imagine them using your product in ways you never contemplated—making it more and more valu- able for them. Before seeing how this can be done, we should step back and think about why we would need to integrate Groovy in a Java application, the situations in which it’s useful to do so, and the dependencies we need to set up before we get started. 11.1.1 Integrating appropriately No-one can tell you what your application needs are or what is going to be suit- able for your particular situation. You must look carefully at your requirements and consider whether you will benefit from integrating Groovy at all. We can’t make that decision for you—but we hope we can give a few ideas to guide you. First, it’s worth explicitly acknowledging that not all applications benefit from integrating a scripting language such as Groovy. We can go as far as saying that most don’t need that. If you’re writing an e-Commerce web site, a multimedia player, or an FTP client, chances are that you won’t need a scripting language. But now, suppose you were building an advanced word processor, a spreadsheet appli- cation, or a complex risk-calculation module for an even more complicated bank software suite that had to evolve quickly to follow the rapid changes of the market, legislation, or new business rules. These applications might need an extension point where end users can customize them to suit their needs. Figure 11.1 shows one example of where you could integrate Groovy. Figure 11.1 One example of an integration solution. Groovy code is entered by the user in the user interface layer and then executed in the business layer. Getting ready to integrate 363 For instance, the banking application might require the definition of business rules in a script that could be defined at runtime without requiring a new and tedious development/test/qualification phase, reducing the time to market and increasing the responsiveness to changes in financial practices. Another example could be an office suite of applications offering a macro system to create reusable functions that could be invoked with a keystroke. It becomes obvious that a dichot- omy of the software world differentiates monolithic applications, which don’t need to evolve over time and have a fixed functional scope, from more fluid applications whose logic can be extended or modified during their lifespan to accommodate context changes. Before considering using Groovy in your application, you need to analyze whether you need to customize it, and see whether you want to customize, extend, or amend the logic, and not just simple parameters. If parameterization will ful- fill your needs, you may be better off with classic configuration mechanisms such as an administration web interface through a set of web services; or, for more advanced monitoring and action management, you may also consider exposing JMX1 MBeans. Sometimes, even if the logic has to change, if the choice is between a small and well-defined set of business rules that are known to begin with, you can also embed all those rules within the application and decide through param- eterization which one is to be used. Once you have examined your needs and come to the conclusion that a scripting environment is what your application requires, this chapter should provide you with all the information you need to make your application extendable at runtime with logic written in Groovy.2 In the following sections, you’ll learn how to use the GroovyShell class to eval- uate simple expressions and scripts, as well as the GroovyClassLoader for further loading of Groovy classes. In addition to the techniques provided by Groovy for integrating your scripts in Java, you’ll discover alternatives for leveraging the Spring framework and the scripting API within the upcoming Java 6 release. 11.1.2 Setting up dependencies In order to use Groovy within your project, you will need to set it up to use the Groovy libraries. This section covers the dependencies required for Groovy inte- gration. The fact that it’s so short should be a source of comfort—there’s little 1 Find more information at http://java.sun.com/products/JavaManagement/. 2 Of course, we don’t wish to discourage you from reading the chapter even if you don’t have any inte- gration needs right now. Gaining knowledge is a worthy pursuit in and of itself. 364 CHAPTER 11 Integrating Groovy work to do to get up and running. However, problems can sometimes crop up during integration that you wouldn’t see if you were using Groovy by itself. We will discuss these potential issues and how to resolve them. The Groovy distribution comes with a directory containing all the core librar- ies that form the Groovy runtime. The minimum for embedding Groovy consists of the three jar files listed in table 11.1. Table 11.1 The minimal jar files required for integrating Groovy File Purpose groovy-1.0.jar Groovy core library antlr-2.7.5.jar Grammar parser and generator asm-2.2.jar Bytecode toolkit used to generate classes But these three dependencies may sometimes conflict with the other libraries your project uses. In particular, if you are using Hibernate and/or Spring, which both use ASM for generating proxies, you will not be able to use Groovy unless the version of Hibernate or Spring you are using requires the same version of ASM. However, there is a solution to this problem. The Groovy distribution also comes with a specific Groovy jar file that embeds the dependencies in their own pack- ages. This library is often called the embeddable jar file, because you can embed it beside any other library without any conflict. You will find this jar file in the direc- tory named embeddable of your Groovy installation: groovy-all-1.0.jar. Remember that if your project depends on ASM or Antlr, you can use this “magic” jar file to solve your versioning issues between Groovy and your other dependencies. Also, keep in mind that your project will have to run under a JRE 1.4 or above, which is a requirement for Groovy.
Recommended publications
  • Introduction to Clojure
    Seminar on Languages for Scientific Computing Aachen, 6 Feb 2014 Navid Abbaszadeh [email protected] Overview • Trends • Introduction Aachen 2014 • / Paradigms, Data Structures, Syntax 02 / Navid Abbaszadeh Navid • 06 Compilation & Execution • Concurrency Model • Reference Types • Performance • Clojure & Scientific Computing Seminar on Languages for for onLanguages Seminar • Pros & Cons Clojure Computing,Scientific • Conclusion • References 2 • Demo How Hot is the Topic? • Clojure Google Group • ~8800 members Aachen • Active Community 2014 / 02 / 06 Abbaszadeh Navid Seminar on Languages for for onLanguages Seminar Scientific Computing, Clojure Computing,Scientific • Matching Job Positions • How often it is Googled 3 • Still Educational Introduction • Appeared in 2007 under Eclipse Public License • Rich Hickey created the language because “… I needed a Lisp, for Aachen 2014 functional programming, symbiotic with an established platform / 02 and designed for concurrency, and I couldn’t find one.” / 06 Abbaszadeh Navid • General Purpose: can be used wherever Java is used • Hosted on JVM • Core in Java & Clojure • Current Version: 1.5.1, bin + source + docs < 5MB • No Installation for onLanguages Seminar • java -cp clojure.jar clojure.main /path/to/myscript.clj arg1 arg2 … Clojure Computing,Scientific • Other implementations: • Clojure-py (Python) • ClojureCLR (.Net) • Rouge (Ruby) 4 • ClojureScript (JS) Paradigms • Lisp • S-Expressions Aachen • a notation for nested list composed of tree-structured data 2014 / 02 • (x1 x2 x3)
    [Show full text]
  • Introduction to Software Engineering
    Introduction to Software Engineering Edited by R.P. Lano (Version 0.1) Table of Contents Introduction to Software Engineering..................................................................................................1 Introduction........................................................................................................................................13 Preface...........................................................................................................................................13 Introduction....................................................................................................................................13 History...........................................................................................................................................14 References......................................................................................................................................15 Software Engineer..........................................................................................................................15 Overview........................................................................................................................................15 Education.......................................................................................................................................16 Profession.......................................................................................................................................17 Debates within
    [Show full text]
  • Space Details
    Space Details Key: GROOVY Name: Groovy Description: Documentation and web site of the Groovy scripting language for the JVM. Creator (Creation Date): bob (Apr 15, 2004) Last Modifier (Mod. Date): glaforge (Apr 12, 2005) Available Pages • Home • Advanced Usage Guide • Ant Task Troubleshooting • BuilderSupport • Compiling Groovy • Compiling With Maven2 • Design Patterns with Groovy • Abstract Factory Pattern • Adapter Pattern • Bouncer Pattern • Chain of Responsibility Pattern • Composite Pattern • Decorator Pattern • Delegation Pattern • Flyweight Pattern • Iterator Pattern • Loan my Resource Pattern • Null Object Pattern • Pimp my Library Pattern • Proxy Pattern • Singleton Pattern • State Pattern • Strategy Pattern • Template Method Pattern • Visitor Pattern • Dynamic language beans in Spring • Embedding Groovy • Influencing class loading at runtime • Make a builder • Mixed Java and Groovy Applications • Optimising Groovy bytecodes with Soot Document generated by Confluence on Dec 07, 2007 12:38 Page 1 • Refactoring with Groovy • Introduce Assertion • Replace Inheritance with Delegation • Security • Writing Domain-Specific Languages • Articles • Community and Support • Contributing • Mailing Lists • Related Projects • User Groups • Cookbook Examples • Accessing SQLServer using groovy • Alternate Spring-Groovy-Integration • Batch Image Manipulation • command line groovy doc or methods lookup • Compute distance from Google Earth Path (in .kml file) • Convert SQL Result To XML • Embedded Derby DB examples • Embedding a Groovy Console in
    [Show full text]
  • Configuring Java-Based Web Application Development Environment for an Academic Setting
    J.T. Yao, V.V. Raghvan, G.Y. Wang (Eds.): WSS'04, pp. 111-118, 2004. Configuring Java-Based Web Application Development Environment for an Academic Setting Ritesh Mehra, Satya K Gandham, Zonghuan Wu, Vijay V.Raghavan Center for Advanced Computer Studies, University of Louisiana, Lafayette {rxm3304, skg7478, zwu, raghavan}@cacs.louisiana.edu Abstract In this section, we review some of emerging Java technologies like EJB, Struts, JSF and Tiles in context In this paper, we analyze the characteristics and of their relevance to academic community. We also constraints of a typical academic environment for web discuss the relevance of extreme programming to application development. A set of Java-based web academic community. To start with, we review technologies and tools are introduced and reviewed for academic preferences for open source software, personal such an environment. The motivation behind this work is preferences of student and faculty and some of the to provide comprehensive resource for university faculty common project requirements. members and students about emerging technologies and available tools to facilitate rapid development of web 2.1 Preference for Open Source Software applications. Universities usually have preference for open source software solutions. This is evident from the recent 1. Introduction resolution approved by University of Buffalo, State University of New York stating that direct, unmediated In this paper we present a comprehensive view of and unfettered access to information is fundamental and available resources in terms of technologies and tools essential to scholarly inquiry, academic dialog, research, for building Java based web application environment in advancement of research methods and academic academic settings.
    [Show full text]
  • The Scripted Debugging of Java Program Via the Java Platform Debug Architecture
    The Scripted Debugging of Java Program via the Java Platform Debug Architecture Rory Taylor September 2017 Dissertation submitted in partial fulfilment for the degree of Master of Science in Information Technology Computing Science and Mathematics University of Stirling Abstract Typically, developer debugging their code must utilise one of two approaches. Either simple diagnostic statements are added into the program code itself and the program is exe- cuted normally, generating an output of requested variable values to compare with those expected, or the programmer utilises an ‘interactive’ debugger program. These programs run in real-time and retain control over the target program’s execution, pausing it at specified points to allow the user to examine the current state of the target and to iterate individually through the code they have written to locate faults. For large scale programs, however, this is a labour-intensive process that can take up significant time, and requires the user parses through the wealth of information produced from the debugger to target those values that they are interested in. The diagnostic approach requires that these lines of code must be re- moved after debugging is complete, risking the introduction of new errors. This project represents an attempt to create a functioning debugger specifically targeting the Java language, which would operate autonomously from the programmer using it. It would attempt to combine the targeted and unobtrusive nature of the ‘diagnostic’ approach to debugging, reducing the output to only those specifically requested by the programmer, with the real-time execution of an interactive debugger. This would also retain the advantages of the interactive debuggers in not requiring any of the original code to be edited.
    [Show full text]
  • A Pedagogic Programming Environment for Java That Scales to Production Programming
    RICE UNIVERSITY A Pedagogic Programming Environment for Java that Scales to Production Programming by Charles S. Reis A Thesis Submitted in Partial Fulfillment of the Requirements for the Degree Master of Science Approved, Thesis Committee: Robert Cartwright, Chair Professor of Computer Science Peter Druschel Professor of Computer Science Walid Taha Assistant Professor of Computer Science Houston, Texas April, 2003 A Pedagogic Programming Environment for Java that Scales to Production Programming Charles S. Reis Abstract This thesis describes extensions to the DrJava development environment that make it suitable for production programming. DrJava is an effective tool for teaching introductory programming skills in Java, and its simplicity is a desirable characteristic for projects of any size. To better support the development of large projects in DrJava, a carefully selected suite of features has been added to the environment. To facilitate interoperation with professional development environments, a plug-in supporting the DrJava interface has been written for the Eclipse environment. As a result of this work, DrJava has become an appropriate tool for teaching production programming skills in an academic environment, without sacrificing its original goals. Acknowledgments I would like to thank my adviser, Robert \Corky" Cartwright, whose passionate views on software development have greatly influenced me as a programmer and as a project manager. His leadership and feedback have been essential to DrJava's success. I am very fortunate to have worked with Eric Allen, for his insight, discipline, and continuous encouragement. I would also like to thank Brian Stoler, whose lead I have followed and whose guidance and continued contributions have been immensely beneficial.
    [Show full text]
  • Programming Clojure.Pdf
    Of the new crop of languages appearing on the Java Virtual Machine, Clojure might be the most compelling. Because of its time-honored roots in Lisp, compelling new features, and clever ways of mixing these features with existing Java libraries, it will expand the way you think about writing code. Stu has written a masterwork, making both new and old concepts blend together into an accessible and thought- provoking tour of this elegant language. Read the first chapter, and you will be hooked. David Bock Principal, CodeSherpas, Inc. Stuart has charted the smoothest path yet to Clojure fluency with this well-organized and easy-to-read book. He has a knack for creating simple and effective examples that demonstrate the language’s unique features and how they fit together. Chris Houser A primary Clojure contributor and clojure-contrib lib author Not only a great reference for an exciting new language, this book establishes Clojure as a serious tool for working programmers. Stuart Sierra Author of several clojure-contrib libraries, including the test-is testing framework Stu is passionate about finding better ways to develop software, and Programming Clojure shows it. This book shows rather than tells how and why Clojure can help you and, because of its tight integration with the Java platform, how you can leverage your investment in existing infrastructure and numerous Java APIs. I found the book extremely easy to read, with some of the most unique and interesting code examples in any technical book I’ve read. Scott Leberknight Chief architect, Near Infinity Corp. As someone following Clojure’s development closely before Program- ming Clojure was available, I was very impressed with how much I learned by reading it.
    [Show full text]