3.1. Annotation
One or more groovy.lang.Grab annotations can be added at any place that
annotations are accepted to tell the compiler that this code relies on
the specific library. This will have the effect of adding the library to
the classloader of the groovy compiler. This annotation is detected and
evaluated before any other resolution of classes in the script, so
imported classes can be properly resolved by a @Grab annotation.
import com.jidesoft.swing.JideSplitButton
@Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,2.3.0)')
public class TestClassAnnotation {
public static String testMethod () {
return JideSplitButton.class.name
}
}
An appropriate grab(…) call will be added to the static initializer
of the class of the containing class (or script class in the case of an
annotated script element).
3.2. Multiple Grape Annotations
In early versions of Groovy, if you wanted to use a Grab annotation multiple times
on the same node you had to use the @Grapes annotation, e.g.:
@Grapes([
@Grab(group='commons-primitives', module='commons-primitives', version='1.0'),
@Grab(group='org.ccil.cowan.tagsoup', module='tagsoup', version='0.9.7')])
class Example {
// ...
}
Otherwise you’d encounter the following error:
Cannot specify duplicate annotation on the same member
But in recent versions, @Grapes is purely optional.
Technical notes:
-
Originally, Groovy stored the Grab annotations for access at runtime and duplicates aren’t allowed in the bytecode. In current versions, @Grab has only SOURCE retention, so the multiple occurrences aren’t an issue.
-
Future versions of Grape may support using the Grapes annotation to provide a level of structuring, e.g. allowing a GrabExclude or GrabResolver annotation to apply to only a subset of the Grab annotations.
3.3. Method call
Typically a call to grab will occur early in the script or in class initialization. This is to ensure that the libraries are made available to the ClassLoader before the groovy code relies on the code. A couple of typical calls may appear as follows:
import groovy.grape.Grape
// random maven library
Grape.grab(group:'com.jidesoft', module:'jide-oss', version:'[2.2.0,)')
Grape.grab([group:'org.apache.ivy', module:'ivy', version:'2.0.0-beta1', conf:['default', 'optional']],
[group:'org.apache.ant', module:'ant', version:'1.7.0'])
-
Multiple calls to grab in the same context with the same parameters should be idempotent. However, if the same code is called with a different
ClassLoadercontext then resolution may be re-run. -
If the
argsmap passed into thegrabcall has an attributenoExceptionsthat evaluates true no exceptions will be thrown. -
grabrequires that aRootLoaderorGroovyClassLoaderbe specified or be in theClassLoaderchain of the calling class. By default failure to have such aClassLoaderavailable will result in module resolution and an exception being thrown-
The ClassLoader passed in via the
classLoader:argument and its parent classloaders. -
The ClassLoader of the object passed in as the
referenceObject:argument, and its parent classloaders. -
The ClassLoader of the class issuing the call to
grab
-
3.3.1. grab(HashMap) Parameters
-
group:- <String> - Which module group the module comes from. Translates directly to a Maven groupId. Any group matching/groovy(|\..|x|x\..)/is reserved and may have special meaning to the groovy endorsed modules. -
module:- <String> - The name of the module to load. Translated directly to a Maven artifactId. -
version:- <String> and possibly <Range> - The version of the module to use. Either a literal version `1.1-RC3' or an Ivy Range `[2.2.1,)' meaning 2.2.1 or any greater version). -
classifier:- <String> - The Maven classifier to resolve by. -
conf:- <String>, defaultdefault' - The configuration or scope of the module to download. The default conf is `default:which maps to the mavenruntimeandmasterscopes. -
force:- <boolean>, defaults true - Used to indicate that this revision must be used in case of conflicts, independently of -
conflicts manager
-
changing:- <boolean>, default false - Whether the artifact can change without its version designation changing. -
transitive:- <boolean>, default true - Whether to resolve other dependencies this module has or not.
There are two principal variants of grab, one with a single Map and
one with an arguments Map and multiple dependencies map. A call to the
single map grab is the same as calling grab with the same map passed in
twice, so grab arguments and dependencies can be mixed in the same map,
and grab can be called as a single method with named parameters.
There are synonyms for these parameters. Submitting more than one is a runtime exception.
-
group:,groupId:,organisation:,organization:,org: -
module:,artifactId:,artifact: -
version:,revision:,rev: -
conf:,scope:,configuration:
3.3.2. Arguments Map arguments
-
classLoader:- <GroovyClassLoader> or <RootClassLoader> - The ClassLoader to add resolved Jars to -
refObject:- <Object> - The closest parent ClassLoader for the object’s class will be treated as though it were passed in asclassLoader: -
validate:- <boolean>, default false - Should poms or ivy files be validated (true), or should we trust the cache (false). -
noExceptions:- <boolean>, default false - If ClassLoader resolution or repository querying fails, should we throw an exception (false) or fail silently (true).
3.4. Command Line Tool
Grape added a command line executable `grape' that allows for the inspection and management of the local grape cache.
grape install [-hv] <group> <module> [<version>] [<classifier>]
This installs the specified groovy module or maven artifact. If a version is specified that specific version will be installed, otherwise the most recent version will be used (as if `*' we passed in).
grape list
Lists locally installed modules (with their full maven name in the case of groovy modules) and versions.
grape resolve [-adhisv] (<groupId> <artifactId> <version>)+
This returns the file locations of the jars representing the artifacts for the specified module(s) and the respective transitive dependencies. You may optionally pass in -ant, -dos, or -shell to get the dependencies expressed in a format applicable for an ant script, windows batch file, or unix shell script respectively. -ivy may be passed to see the dependencies expressed in an ivy like format.
grape uninstall [-hv] <group> <module> <version>
This uninstalls a particular grape: it non-transitively removes the respective jar file from the grape cache.
3.5. Advanced configuration
3.5.1. Repository Directory
If you need to change the directory grape uses for downloading libraries you can specify the grape.root system property to change the default (which is ~/.groovy/grapes)
groovy -Dgrape.root=/repo/grapes yourscript.groovy
3.5.2. Customize Ivy settings
You can customize the ivy settings that Grape uses by creating a ~/.groovy/grapeConfig.xml file. If no such file exists, here are the default settings used by Grape.
For more information on how to customize these settings, please refer to the Ivy documentation.
3.6. More Examples
Using Apache Commons Collections:
// create and use a primitive array list
@Grab(group='commons-primitives', module='commons-primitives', version='1.0')
import org.apache.commons.collections.primitives.ArrayIntList
def createEmptyInts() { new ArrayIntList() }
def ints = createEmptyInts()
ints.add(0, 42)
assert ints.size() == 1
assert ints.get(0) == 42
Using TagSoup:
// find the PDF links of the Java specifications
@Grab(group='org.ccil.cowan.tagsoup', module='tagsoup', version='1.2.1')
def getHtml() {
def parser = new XmlParser(new org.ccil.cowan.tagsoup.Parser())
parser.parse("https://docs.oracle.com/javase/specs/")
}
html.body.'**'.a.@href.grep(~/.*\.pdf/).each{ println it }
Using Google Collections:
import com.google.common.collect.HashBiMap
@Grab(group='com.google.code.google-collections', module='google-collect', version='snapshot-20080530')
def getFruit() { [grape:'purple', lemon:'yellow', orange:'orange'] as HashBiMap }
assert fruit.lemon == 'yellow'
assert fruit.inverse().yellow == 'lemon'
Launching a Jetty server to serve Groovy templates:
@Grab('org.eclipse.jetty.aggregate:jetty-server:8.1.19.v20160209')
@Grab('org.eclipse.jetty.aggregate:jetty-servlet:8.1.19.v20160209')
@Grab('javax.servlet:javax.servlet-api:3.0.1')
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.servlet.ServletContextHandler
import groovy.servlet.TemplateServlet
def runServer(duration) {
def server = new Server(8080)
def context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS)
context.resourceBase = "."
context.addServlet(TemplateServlet, "*.gsp")
server.start()
sleep duration
server.stop()
}
runServer(10000)
Grape will download Jetty and its dependencies on first launch of this script, and cache them. We create a new Jetty Server on port 8080, then expose Groovy’s TemplateServlet at the root of the context — Groovy comes with its own powerful template engine mechanism. We start the server and let it run for a certain duration. Each time someone will hit http://localhost:8080/somepage.gsp, it will display the somepage.gsp template to the user — those template pages should be situated in the same directory as this server script.