### Jetty Groovlets Programmatic Setup
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-servlet/src/spec/doc/servlet-userguide.adoc
Example of setting up Groovlets programmatically using Jetty. This demonstrates how to integrate GroovyServlet with a Jetty server instance.
```groovy
import groovy.servlet.GroovyServlet
import org.eclipse.jetty.server.Server
```
--------------------------------
### Setup Event Handler
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/_type-checking-extensions.adoc
Handles the 'setup' event, which is called after the type checker finishes initialization. Used for extension setup.
```groovy
def setup() {
// Perform setup of your extension
}
```
--------------------------------
### Install Groovy using SDKMAN!
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/core-getting-started.adoc
Use SDKMAN! to easily install Groovy on Bash platforms. Ensure you have SDKMAN! installed and initialized before running the install command.
```shell
$ curl -s "https://get.sdkman.io" | bash
```
```shell
$ source "$HOME/.sdkman/bin/sdkman-init.sh"
```
```shell
$ sdk install groovy
```
```shell
$ groovy -version
```
--------------------------------
### GINQ Multiplication Table Example
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
A GINQ example demonstrating how to generate a multiplication table. This example is tagged for inclusion.
```groovy
include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_examples_01,indent=0]
```
--------------------------------
### GINQ Window Function Examples
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
Demonstrates various window functions in GINQ.
```groovy
def result07 = sql.eachRow( """
SELECT
name,
score,
ROW_NUMBER() OVER (PARTITION BY name ORDER BY score DESC)
FROM
Score
""" )
```
```groovy
def result08 = sql.eachRow( """
SELECT
name,
score,
RANK() OVER (PARTITION BY name ORDER BY score DESC)
FROM
Score
""" )
```
```groovy
def result01 = sql.eachRow( """
SELECT
name,
score,
DENSE_RANK() OVER (PARTITION BY name ORDER BY score DESC)
FROM
Score
""" )
```
```groovy
def result03 = sql.eachRow( """
SELECT
name,
score,
ROW_NUMBER() OVER (PARTITION BY name ORDER BY score DESC)
FROM
Score
""" )
```
```groovy
def result05 = sql.eachRow( """
SELECT
name,
score,
LAG(score, 1, 0) OVER (PARTITION BY name ORDER BY score DESC)
FROM
Score
""" )
```
```groovy
def result06 = sql.eachRow( """
SELECT
name,
score,
LEAD(score, 1, 0) OVER (PARTITION BY name ORDER BY score DESC)
FROM
Score
""" )
```
```groovy
def result20 = sql.eachRow( """
SELECT
name,
score,
FIRST_VALUE(score) OVER (PARTITION BY name ORDER BY score DESC ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
FROM
Score
""" )
```
```groovy
def result21 = sql.eachRow( """
SELECT
name,
score,
FIRST_VALUE(score) OVER (PARTITION BY name ORDER BY score DESC)
FROM
Score
""" )
```
```groovy
def result09 = sql.eachRow( """
SELECT
name,
score,
FIRST_VALUE(score) OVER (PARTITION BY name ORDER BY score DESC)
FROM
Score
""" )
```
```groovy
def result10 = sql.eachRow( """
SELECT
name,
score,
LAST_VALUE(score) OVER (PARTITION BY name ORDER BY score DESC)
FROM
Score
""" )
```
```groovy
def result13 = sql.eachRow( """
SELECT
name,
score,
NTH_VALUE(score, 2) OVER (PARTITION BY name ORDER BY score DESC)
FROM
Score
""" )
```
```groovy
def result16 = sql.eachRow( """
SELECT
name,
score,
NTILE(2) OVER (PARTITION BY name ORDER BY score DESC)
FROM
Score
""" )
```
```groovy
def result17 = sql.eachRow( """
SELECT
name,
score,
PERCENT_RANK() OVER (PARTITION BY name ORDER BY score DESC)
FROM
Score
""" )
```
```groovy
def result18 = sql.eachRow( """
SELECT
name,
score,
CUME_DIST() OVER (PARTITION BY name ORDER BY score DESC)
FROM
Score
""" )
```
```groovy
def result19 = sql.eachRow( """
SELECT
name,
score,
ROW_NUMBER() OVER (PARTITION BY name ORDER BY score DESC)
FROM
Score
""" )
```
```groovy
def result12 = sql.eachRow( """
SELECT
name,
score,
ROW_NUMBER() OVER (PARTITION BY name ORDER BY score DESC)
FROM
Score
""" )
```
```groovy
def result14 = sql.eachRow( """
SELECT
name,
score,
ROW_NUMBER() OVER (PARTITION BY name ORDER BY score DESC)
FROM
Score
""" )
```
```groovy
def result15 = sql.eachRow( """
SELECT
name,
score,
ROW_NUMBER() OVER (PARTITION BY name ORDER BY score DESC)
FROM
Score
""" )
```
```groovy
def result11 = sql.eachRow( """
SELECT
name,
score,
ROW_NUMBER() OVER (PARTITION BY name ORDER BY score DESC)
FROM
Score
""" )
```
```groovy
def result40 = sql.eachRow( """
SELECT
name,
score,
ROW_NUMBER() OVER (PARTITION BY name ORDER BY score DESC)
FROM
Score
""" )
```
--------------------------------
### HTML Login Example using Form POST
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-http-builder/src/spec/doc/http-builder.adoc
Combines form submission with HTML parsing to automate a login process. This example demonstrates sending credentials and checking the response.
```groovy
def client = HttpBuilder.http('https://example.com/')
client.form('/login', [username: 'user', password: 'password']) {
assert status == 200
// Check for successful login indicator in HTML
assert html.body().text().contains('Welcome, user!')
}
```
--------------------------------
### Hash Join Example 1
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
An example of a hash join in GINQ.
```sql
include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_joining_07,indent=0]
```
--------------------------------
### Hash Join Example 3
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
A third example of a hash join in GINQ.
```sql
include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_joining_09,indent=0]
```
--------------------------------
### Hash Join Example 2
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
Another example of a hash join in GINQ.
```sql
include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_joining_08,indent=0]
```
--------------------------------
### Setup for Server-Side Template Rendering (Java)
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-templates/src/spec/doc/_markup-template-engine.adoc
Provides the necessary Java setup for rendering templates on the server side, including creating a template configuration and the template engine instance.
```java
include::../test/MarkupTemplateEngineSpecTest.groovy[tags=rendering_setup,indent=0]
```
--------------------------------
### Spock Specification Example
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/core-testing-guide.adoc
A basic Spock specification demonstrating a feature method with setup, when, and then blocks for testing a Stack class.
```groovy
class StackSpec extends Specification {
def "adding an element leads to size increase"() { // <1>
setup: "a new stack instance is created" // <2>
def stack = new Stack()
when: // <3>
stack.push 42
then: // <4>
stack.size() == 1
}
}
```
--------------------------------
### Array Data Source Example
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
Demonstrates using an array as a data source in GINQ.
```sql
include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_datasource_02,indent=0]
```
--------------------------------
### Stream Data Source Example
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
Demonstrates using a stream as a data source in GINQ.
```sql
include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_datasource_01,indent=0]
```
--------------------------------
### Basic Groovy Ant Task Example
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ant/src/spec/doc/groovy-ant-task.adoc
A simple 'Hello World' example using the Groovy Ant task. This demonstrates the most basic usage.
```xml
println "Hello World"
```
--------------------------------
### Inner Join Example
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
An example of an inner join in GINQ.
```sql
include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_joining_01,indent=0]
```
--------------------------------
### JmxBuilder.bean() Syntax Example
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-jmx/src/spec/doc/jmx.adoc
This is a comprehensive syntax example for the JmxBuilder.bean() node, illustrating various descriptors for MBean configuration.
```groovy
jmx.export {
bean(
target:bean instance,
name:ObjectName,
desc:"...",
attributes:"*",
attributes:[]
attributes:[ "AttrubuteName1","AttributeName2",...,"AttributeName_n" ]
attributes:[
"AttributeName": "*",
"AttributeName":[
desc:"...",
defaultValue:value,
writable:true|false,
editable:true|false,
onChange:{event-> // event handler}
]
],
constructors:"*",
constructors:[
"Constructor Name":[],
"Constructor Name":[ "ParamType1","ParamType2,...,ParamType_n" ],
"Constructor Name":[
desc:"...",
params:[
"ParamType1": "*",
"ParamType2":[desc:"...", name:"..."],...,
"ParamType_n":[desc:"...", name:"..."]
]
]
],
operations:"*",
operations:[ "OperationName1", "OperationName2",...,"OperationNameN" ],
operations:[
"OperationName1": "*",
"OperationName2":[ "type1","type2,"type3" ]
"OperationName3":[
desc:"...",
params:[
"ParamType1": "*"
"ParamType2":[desc:"...", name:"..."],...,
"ParamType_n":[desc:"...", name:"..."]
],
onInvoked:{event-> JmxBuilder.send(event:"", to:"")}
]
],
listeners:[
"ListenerName1":[event: "...", from:ObjectName, call:{event->}],
"ListenerName2":[event: "...", from:ObjectName, call:&methodPointer]
]
)
}
```
--------------------------------
### AutoClone Equivalent Example
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/core-metaprogramming.adoc
Shows an equivalent implementation of the @AutoClone example without the AST transformation.
```groovy
include::../test/CloningASTTransformsTest.groovy[tags=example_autoclone_equiv,indent=0]
```
--------------------------------
### GINQ Grouping Example 06
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
A GINQ grouping example.
```sql
include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_grouping_06,indent=0]
```
--------------------------------
### GINQ Grouping Example 07
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
A GINQ grouping example.
```sql
include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_grouping_07,indent=0]
```
--------------------------------
### AutoClone Example
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/core-metaprogramming.adoc
Demonstrates the basic usage of the @AutoClone AST transformation.
```groovy
include::../test/CloningASTTransformsTest.groovy[tags=example_autoclone,indent=0]
```
--------------------------------
### FileTreeBuilder Example
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/core-domain-specific-languages.adoc
Creates a directory structure using FileTreeBuilder, specifying directories and files.
```groovy
new FileTreeBuilder('src').invokeMethod('dir', [
'main': {
dir 'groovy', {
file 'Foo.groovy'
}
},
'test': {
dir 'groovy', {
file 'FooTest.groovy'
}
}
])
```
--------------------------------
### Flow Typing Example (Footer)
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/core-domain-specific-languages.adoc
Completes the flow typing example, showing how @DelegatesTo helps IDEs and type checkers.
```groovy
Greeter greeter = new Greeter()
exec {
sayHello()
}
```
--------------------------------
### Robot Script Example
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/_type-checking-extensions.adoc
A basic Groovy script demonstrating the use of a 'robot' object.
```groovy
def robot = new Robot()
robot.move(10)
robot.turn(90)
```
--------------------------------
### GINQ Aggregation Function Examples
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
Demonstrates various aggregation functions in GINQ.
```groovy
def result22 = sql.eachRow( """
SELECT
name,
MIN(score) OVER (PARTITION BY name)
FROM
Score
""" )
```
```groovy
def result23 = sql.eachRow( """
SELECT
name,
MAX(score) OVER (PARTITION BY name)
FROM
Score
""" )
```
```groovy
def result26 = sql.eachRow( """
SELECT
name,
COUNT(score) OVER (PARTITION BY name)
FROM
Score
""" )
```
```groovy
def result27 = sql.eachRow( """
SELECT
name,
SUM(score) OVER (PARTITION BY name)
FROM
Score
""" )
```
```groovy
def result28 = sql.eachRow( """
SELECT
name,
AVG(score) OVER (PARTITION BY name)
FROM
Score
""" )
```
```groovy
def result33 = sql.eachRow( """
SELECT
name,
MEDIAN(score) OVER (PARTITION BY name)
FROM
Score
""" )
```
```groovy
def result31 = sql.eachRow( """
SELECT
name,
STDEV(score) OVER (PARTITION BY name)
FROM
Score
""" )
```
```groovy
def result32 = sql.eachRow( """
SELECT
name,
STDEVP(score) OVER (PARTITION BY name)
FROM
Score
""" )
```
```groovy
def result29 = sql.eachRow( """
SELECT
name,
VAR(score) OVER (PARTITION BY name)
FROM
Score
""" )
```
```groovy
def result30 = sql.eachRow( """
SELECT
name,
VARP(score) OVER (PARTITION BY name)
FROM
Score
""" )
```
```groovy
def result35 = sql.eachRow( """
SELECT
name,
AGG(score, 'MIN') OVER (PARTITION BY name)
FROM
Score
""" )
```
```groovy
def result36 = sql.eachRow( """
SELECT
name,
AGG(score, 'MAX') OVER (PARTITION BY name)
FROM
Score
""" )
```
```groovy
def result37 = sql.eachRow( """
SELECT
name,
AGG(score, 'SUM') OVER (PARTITION BY name)
FROM
Score
""" )
```
```groovy
def result38 = sql.eachRow( """
SELECT
name,
AGG(score, 'AVG') OVER (PARTITION BY name)
FROM
Score
""" )
```
```groovy
def result42 = sql.eachRow( """
SELECT
name,
AGG(score, 'COUNT') OVER (PARTITION BY name)
FROM
Score
""" )
```
--------------------------------
### Get Help for a Command in Groovy Shell
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-groovysh/src/spec/doc/groovysh.adoc
Use the /help command followed by the command name to get detailed usage information. This example shows how to get help for the /help command itself.
```groovysh
groovy> /help /help
help - command help
Usage: help [TOPIC...]
-? --help Displays command help
--groups Commands are grouped by registries
-i --info List commands with a short command info
```
--------------------------------
### Displaying the Start of a File with /head
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-groovysh/src/spec/doc/groovysh.adoc
Example of using the /head command to display the first few lines of a file.
```jshell
groovy> /head -n2 fruit.txt
apple
banana
```
--------------------------------
### Groovy AST Transformation: @WithLogging Example
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/core-metaprogramming.adoc
Demonstrates a simple local AST transformation to add logging messages at the start and end of method invocations. This example showcases a naive approach to aspect-oriented programming in Groovy.
```groovy
import org.codehaus.groovy.transform.ASTTransformation
import org.codehaus.groovy.ast.*
import org.codehaus.groovy.ast.expr.MethodCallExpr
import org.codehaus.groovy.ast.stmt.BlockStmt
import org.codehaus.groovy.ast.stmt.ExpressionStatement
import org.codehaus.groovy.control.SourceUnit
@interface WithLogging {}
class WithLoggingASTTransformation implements ASTTransformation {
@Override
void visit(ASTTransformationCode ast, SourceUnit sourceUnit) {
ast.methods.each {
if (it.code != null) {
def logStart = new MethodCallExpr(new MethodCallExpr(null, "println", new ConstantExpression("Entering method: ${it.name}")),
"println", new ConstantExpression("Exiting method: ${it.name}"))
it.code.statements.add(0, new ExpressionStatement(logStart))
}
}
}
}
```
--------------------------------
### Groovy DSL Creation with Maps and Closures (Example 1)
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/core-domain-specific-languages.adoc
Illustrates a basic strategy for creating a DSL in Groovy using maps and Closures.
```groovy
def builder = [
"key1": [
"subkey1": "value1",
"subkey2": "value2"
],
"key2": [
"subkey3": "value3"
]
]
def result = builder.key1.subkey1
assert result == "value1"
```
--------------------------------
### GINQ Result Set Data Source Example
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
Demonstrates using a GINQ result set as a data source.
```groovy
include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_datasource_04,indent=0]
```
--------------------------------
### Groovy Octal Literal Example
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/_working-with-numbers.adoc
Demonstrates the declaration of an octal literal in Groovy, which starts with a '0' followed by octal digits.
```groovy
def o = 012
```
--------------------------------
### Basic vbox Usage
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-swing/src/spec/doc/_swing-builder-widgets.adoc
Demonstrates the fundamental creation of a vbox component using the Swing Builder. No specific setup is required beyond having the Swing Builder available.
```groovy
swing.vbox()
```
--------------------------------
### For Loop Invariant Example
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-contracts/src/spec/doc/contracts-userguide.adoc
Illustrates how to apply a loop invariant to a for loop using the @Invariant annotation. The condition must hold at the start of each iteration.
```groovy
include::../test/ContractsTest.groovy[tags=loop_invariant_for_example,indent=0]
```
--------------------------------
### Intercept Groovy Property Get
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/core-metaprogramming.adoc
Override getProperty to intercept read access to properties. This example forwards requests to the getter for all properties except 'field3'.
```groovy
def getProperty(String property) {
if (property == 'field3') {
return super.getProperty(property)
}
return "Intercepted property: $property"
}
```
--------------------------------
### Groovy Valid Identifiers
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/core-syntax.adoc
Examples of valid identifiers (variable names) in Groovy, adhering to rules that allow letters, dollar signs, and underscores at the start, followed by letters, numbers, or Unicode characters.
```groovy
def _myVar = 1
def $myVar = 2
def myVar = 3
def myVarÀ = 4
def myVarÖ = 5
def myVarØ = 6
def myVarö = 7
def myVarø = 8
def myVar = 9
def myVar = 10
```
--------------------------------
### SQL Sorting with GINQ
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
Demonstrates basic sorting in GINQ, equivalent to SQL ORDER BY.
```sql
select * from T order by name
```
```sql
select * from T order by name asc
```
```sql
select * from T order by name desc
```
--------------------------------
### Groovy Shell /keymap Command Example
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-groovysh/src/spec/doc/groovysh.adoc
Illustrates the output of the /keymap command, showing key bindings for widgets like tailtip-toggle and autosuggest-toggle.
```shell
groovy> /keymap
...
"^["s tailtip-toggle
"^["v autosuggest-toggle
...
```
--------------------------------
### SQL Pagination with GINQ
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
Illustrates pagination using the limit clause in GINQ, specifying offset and size, or just size.
```sql
select * from T limit 10, 5
```
```sql
select * from T limit 5
```
--------------------------------
### Install Groovy using MacPorts
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/core-getting-started.adoc
If you are using macOS and have MacPorts installed, you can install Groovy with a simple command.
```shell
sudo port install groovy
```
--------------------------------
### Install Module with Grape CLI
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/grape.adoc
Use the `grape install` command to install a specified Groovy module or Maven artifact into the local Grape cache. If a version is not provided, the most recent version will be installed.
```bash
grape install [-hv] [] []
```
--------------------------------
### Install Groovy using Homebrew
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/core-getting-started.adoc
For macOS users with Homebrew installed, Groovy can be installed using the brew command.
```shell
brew install groovy
```
--------------------------------
### Write and Print File Size (Groovy)
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/_design-pattern-loan-my-resource.adoc
Demonstrates writing to a file and then printing its size using Groovy's built-in file handling, which implicitly uses the Loan my Resource pattern.
```groovy
def file = new File("test.txt")
file.withWriter {
it.writeLine("Hello world!")
}
println "File size: ${file.length()}"
```
--------------------------------
### Build Runnable Local Installation
Source: https://github.com/apache/groovy/blob/master/README.adoc
Generate a runnable local installation of Groovy with your changes applied. The installation will be located under subprojects/groovy-binary/build/install.
```bash
./gradlew :groovy-binary:installGroovy
```
--------------------------------
### SQL Logging Output with Batching
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-sql/src/spec/doc/sql-userguide.adoc
Example output demonstrating the detailed SQL statements logged when batching is enabled, showing how data is grouped and executed.
```text
INFO org.codehaus.groovy.sql.GroovySql - Executing batch of 100 statements
INFO org.codehaus.groovy.sql.GroovySql - INSERT INTO USERS (firstname, lastname) VALUES ('John', 'Doe')
INFO org.codehaus.groovy.sql.GroovySql - INSERT INTO USERS (firstname, lastname) VALUES ('Jane', 'Smith')
...
```
--------------------------------
### GINQ Grouping Example 03
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
A GINQ grouping example.
```sql
include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_grouping_03,indent=0]
```
--------------------------------
### Equivalent Code for Releasing Resources (Immediate Optional)
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
This code is equivalent to the previous example, showing that the `immediate` parameter is optional when releasing resources and waiting for tasks.
```groovy
include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_tips_10,indent=0]
```
--------------------------------
### GINQ Grouping Example 15
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
A GINQ grouping example.
```sql
include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_grouping_15,indent=0]
```
--------------------------------
### Build Documentation
Source: https://github.com/apache/groovy/blob/master/README.adoc
Compile the Groovy Language Documentation using this command.
```bash
./gradlew asciidoc
```
--------------------------------
### GINQ Grouping Example 14
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
A GINQ grouping example.
```sql
include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_grouping_14,indent=0]
```
--------------------------------
### Basic Groovy Servlet Server Setup
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-servlet/src/spec/doc/servlet-userguide.adoc
Sets up an embedded Jetty server to handle Groovy scripts. Ensure the base resource path is correctly configured.
```groovy
import org.eclipse.jetty.ee9.servlet.ServletContextHandler
var server = new Server(8080)
var handler = new ServletContextHandler(server, '/', ServletContextHandler.SESSIONS)
handler.baseResourceAsString = 'path_to_servlet_base'
handler.addServlet(GroovyServlet, '*.groovy')
server.start()
server.join()
```
--------------------------------
### Build and Run Unit Tests
Source: https://github.com/apache/groovy/blob/master/README.adoc
Execute this command to build the project and run all unit tests.
```bash
./gradlew test
```
--------------------------------
### GINQ Grouping Example 12
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
A GINQ grouping example.
```sql
include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_grouping_12,indent=0]
```
--------------------------------
### GINQ Grouping Example 11
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
A GINQ grouping example.
```sql
include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_grouping_11,indent=0]
```
--------------------------------
### Creating a Stored Procedure with Input and Output Parameters
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-sql/src/spec/doc/sql-userguide.adoc
Example of creating a stored procedure with both input and output parameters.
```groovy
def sql = Sql.newInstance(url, user, password, driver)
sql.execute '''
CREATE PROCEDURE concat_name(IN firstname VARCHAR(100), IN lastname VARCHAR(100), OUT fullname VARCHAR(200))
SET fullname = firstname || ' ' || lastname
'''
```
--------------------------------
### Basic Compiler Configuration Setup
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/core-domain-specific-languages.adoc
This code demonstrates the basic structure for creating and configuring a Groovy compiler configuration, including adding compilation customizers and using it with GroovyShell.
```groovy
import org.codehaus.groovy.control.CompilerConfiguration
// create a configuration
def config = new CompilerConfiguration()
// tweak the configuration
config.addCompilationCustomizers(...)
// run your script
def shell = new GroovyShell(config)
shell.evaluate(script)
```
--------------------------------
### GINQ Grouping Example 04
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
A GINQ grouping example.
```sql
include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_grouping_04,indent=0]
```
--------------------------------
### Use a Configuration Script
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/tools-groovy.adoc
Provide a configuration script using the `--configscript` option for advanced compiler configuration.
```bash
groovy --configscript config/config.groovy src/Person.groovy
```
--------------------------------
### GINQ Grouping Example 05
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
A GINQ grouping example.
```sql
include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_grouping_05,indent=0]
```
--------------------------------
### Geb Browser Initialization and Navigation
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/core-testing-guide.adoc
Demonstrates initializing a Geb Browser instance with a Firefox driver and base URL, then navigating to a specific page and interacting with elements.
```groovy
import geb.Browser
import org.openqa.selenium.firefox.FirefoxDriver
def browser = new Browser(driver: new FirefoxDriver(), baseUrl: 'http://myhost:8080/myapp') // <1>
browser.drive {
go "/login" // <2>
$("#username").text = 'John' // <3>
```
--------------------------------
### Groovy Command Chain Examples
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/core-domain-specific-languages.adoc
Illustrates various forms of Groovy's command chain syntax, including chaining with arguments, closures, and named arguments.
```groovy
def result = "hello" world "groovy"
assert result == "hello".world("groovy")
```
```groovy
def result = "hello" world("groovy", "cool")
assert result == "hello".world("groovy", "cool")
```
```groovy
def result = "hello" world { "groovy" }
assert result == "hello".world { "groovy" }
```
```groovy
def result = "hello" world(arg1: "groovy", arg2: "cool") { "closure" }
assert result == "hello".world(arg1: "groovy", arg2: "cool") { "closure" }
```
```groovy
def result = "hello" world
assert result == "hello".world()
```
--------------------------------
### Instantiating JmxBuilder
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-jmx/src/spec/doc/jmx.adoc
Shows the basic setup for using JmxBuilder, a Groovy DSL for the JMX API. Ensure the JmxBuilder jar is on the classpath.
```groovy
include::../test/JmxTest.groovy[tags=instantiating_jmxbuilder,indent=0]
```
--------------------------------
### Right Outer Join Example
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
An example of a right outer join in GINQ.
```sql
include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_joining_05,indent=0]
```
--------------------------------
### Launch Jetty Server with @Grab
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/grape.adoc
Demonstrates launching a Jetty server to serve Groovy templates using @Grab annotations for dependencies. Grape will download and cache Jetty and its dependencies.
```groovy
@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)
```
--------------------------------
### Left Outer Join Example
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
An example of a left outer join in GINQ.
```sql
include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_joining_04,indent=0]
```
--------------------------------
### Collaborator Classes Example
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/core-testing-guide.adoc
Defines example collaborator classes used in mocking scenarios.
```groovy
class Collaborator {
def doSomething() { "did something" }
}
class AnotherCollaborator {
def doSomethingElse(String msg) { "did something else with: ${msg}" }
}
```
--------------------------------
### Abstract Factory Usage (Groovy)
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/_design-pattern-abstract-factory.adoc
Demonstrates how to use the abstract factory to create and start a game. The first line configures which family of concrete game classes will be used.
```groovy
def gameFactory = new TwoUpGameFactory()
// def gameFactory = new GuessingGameFactory()
GameFactory.factory = gameFactory
def game = GameFactory.factory.createGame()
game.start()
```
--------------------------------
### Inner Join Example with Alias
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc
An example of an inner join with table aliases in GINQ.
```sql
include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_joining_02,indent=0]
```
--------------------------------
### AutoExternalize Equivalent Example
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/core-metaprogramming.adoc
Presents the equivalent implementation of the @AutoExternalize example without the AST transformation.
```groovy
include::../test/CloningASTTransformsTest.groovy[tags=example_autoext_equiv,indent=0]
```
--------------------------------
### Basic glue Usage
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-swing/src/spec/doc/_swing-builder-widgets.adoc
Demonstrates the basic usage of the glue widget.
```groovy
swing.glue()
```
--------------------------------
### Format String Checker Introduction Example
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-typecheckers/src/spec/doc/typecheckers.adoc
An introductory example for the FormatStringChecker, demonstrating the creation of a formatted string with multiple terms using format specifiers like %f, %X, and %B. This example checks the correctness of the format string and arguments.
```groovy
include::../test/FormatStringCheckerTest.groovy[tags=intro_example,indent=0]
```
--------------------------------
### Configuring a List of Elements (Usage)
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/core-domain-specific-languages.adoc
Demonstrates how to call the configureList method with a closure.
```groovy
def list = [1, 2, 3]
configureList(list) {
// delegate is the element of the list
println "Element: " + it
}
```
--------------------------------
### Groovy List Creation and Heterogeneous Types
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/core-syntax.adoc
Demonstrates creating a Groovy list and shows how it can contain elements of different data types.
```groovy
def list = [1, "hello", true]
assert list.size() == 3
assert list[0] == 1
assert list[1] == "hello"
assert list[2] == true
```
--------------------------------
### Groovy Class Instantiation
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/core-object-orientation.adoc
Demonstrates how to instantiate a Groovy class using the 'new' keyword. This is similar to Java but benefits from Groovy's concise syntax.
```groovy
def person = new Person()
person.name = "World"
println person.greet()
```
--------------------------------
### User Code for @TimedInterrupt Fibonacci Example
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/core-metaprogramming.adoc
An example of a potentially long-running user script (Fibonacci calculation) that can be managed by the @TimedInterrupt transformation.
```groovy
include::../test/SaferScriptingASTTransformsTest.groovy[tags=timedinterrupt_fib,indent=0]
```
--------------------------------
### GroovyScriptEngine Initialization and Execution
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/guide-integrating.adoc
Initializes a GroovyScriptEngine to manage scripts from a directory and executes a script that returns a Greeter instance.
```groovy
def engine = new GroovyScriptEngine('src/test-resources/reloading')
def greeter = engine.run('source1.groovy', null)
greeter.sayHello()
```
--------------------------------
### List Installed Modules with Grape CLI
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/grape.adoc
Use the `grape list` command to display all locally installed modules and their versions within the Grape cache.
```bash
grape list
```
--------------------------------
### Using a Stored Procedure with Input and Output Parameters
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-sql/src/spec/doc/sql-userguide.adoc
Example of calling a stored procedure with input and output parameters, specifying the output type.
```groovy
def sql = Sql.newInstance(url, user, password, driver)
def result = sql.call("call concat_name(?, ?, ?)", ["John", "Smith", Sql.VARCHAR])
println result
```
--------------------------------
### Type Checking Regex Example
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-typecheckers/src/spec/doc/typecheckers.adoc
Demonstrates how to type check a regular expression example using the RegexChecker. This ensures that the regex is valid and will not fail at runtime.
```groovy
include::../test/RegexCheckerTest.groovy[tags=checked_example,indent=0]
```
--------------------------------
### More Involved SwingBuilder Example with Code Reuse
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-swing/src/spec/doc/_swing-builder.adoc
Shows a more complex SwingBuilder example that utilizes closures for code re-use, allowing for modular GUI construction.
```groovy
def frame = swing.Frame("More Involved Example") {
def panel = swing.Panel() {
label = swing.Label("A label")
button = swing.Button("Click Me") {
action {
println "Button clicked!"
}
}
}
pack()
visible true
}
```
--------------------------------
### Create and Update an Agent
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/core-concurrent-actors.adoc
Demonstrates creating an Agent with an initial value and updating it using send. Asserts the final value after all updates are processed.
```groovy
import groovy.concurrent.Agent
def counter = Agent.create(0)
counter.send { it + 1 }
counter.send { it + 1 }
counter.send { it + 1 }
assert await(counter.getAsync()) == 3
```
--------------------------------
### Basic popupMenu Usage
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-swing/src/spec/doc/_swing-builder-widgets.adoc
Demonstrates the basic instantiation of a JPopupMenu using the Swing Builder.
```groovy
swing.popupMenu()
```
--------------------------------
### Parallel Transformation Examples
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/core-parallel-collections.adoc
Provides examples of parallel transformation methods. `collectParallel` transforms each element, while `collectManyParallel` transforms and flattens the results into a single collection.
```groovy
def names = people.collectParallel { it.name }
def allTags = articles.collectManyParallel { it.tags }
```
--------------------------------
### Groovy Classes for Delegation Example
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/_design-pattern-delegation.adoc
These are the example classes used to demonstrate the delegation pattern. 'Person' is the class that will delegate, and 'Lender' is the object providing the methods.
```groovy
class Person {
String name
}
class Lender {
def borrowAmount() {
return 1000
}
def lendMoney() {
return "Money lent"
}
def getLoanDetails() {
return "Loan details"
}
}
```
--------------------------------
### Simple SwingBuilder Example
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-swing/src/spec/doc/_swing-builder.adoc
Demonstrates basic usage of SwingBuilder to create a simple GUI hierarchy. This approach is more concise than traditional Swing code.
```groovy
def frame = swing.Frame("Simple Example") {
label = swing.Label("Hello, SwingBuilder!")
pack()
visible true
}
```
--------------------------------
### Invalid Group Count Error Example
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-typecheckers/src/spec/doc/typecheckers.adoc
Demonstrates a compile-time error detected by RegexChecker when an invalid group count is used in a regex. This example shows how to trigger and identify such errors.
```groovy
include::../test/RegexCheckerTest.groovy[tags=invalid_group_count,indent=0]
```
```groovy
include::../test/RegexCheckerTest.groovy[tags=invalid_group_count_message,indent=0]
```
--------------------------------
### Groovy Monoid Introduction Example
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/_design-pattern-monoid.adoc
Illustrates the basic structure for integer sum, product, and string concatenation, highlighting similarities before refactoring.
```groovy
def sum = { nums ->
def total = 0
for (num in nums) {
total += num
}
total
}
def product = { nums ->
def total = 1
for (num in nums) {
total *= num
}
total
}
def concat = { strs ->
def result = ''
for (str in strs) {
result += str
}
result
}
```
--------------------------------
### Groovy Iterator Example
Source: https://github.com/apache/groovy/blob/master/src/spec/doc/_design-pattern-iterator.adoc
Demonstrates the use of the 'each' closure operator and 'for..in' loop for iterating over collections and maps. This example showcases iterating through numbers, months, and colors.
```groovy
def numbers = [1, 2, 3, 4]
def months = [May: 31, Mar: 31, Apr: 30]
def colors = [java.awt.Color.BLACK, java.awt.Color.WHITE]
numbers.each { println it }
months.each { key, value -> println "${key}=${value}" }
colors.each { println it }
```
--------------------------------
### Manually add a signing key to the keyring
Source: https://github.com/apache/groovy/blob/master/CONTRIBUTING.md
This command sequence demonstrates how to manually fetch a specific key from a keyserver and append it to the Gradle keyring. Use this only when necessary, as Gradle's export-keys is preferred.
```bash
gpg --keyserver hkps://keyserver.ubuntu.com --recv-keys
gpg --export --armor >> gradle/verification-keyring.keys
```
--------------------------------
### HTML Template Example
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-templates/src/spec/doc/_markup-template-engine.adoc
Demonstrates generating HTML code, including doctype, tags, and attributes, using the template engine.
```groovy
include::../test/MarkupTemplateEngineSpecTest.groovy[tags=example2_template,indent=0]
```
--------------------------------
### Unclosed Group Error Example
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-typecheckers/src/spec/doc/typecheckers.adoc
Shows a compile-time error detected by RegexChecker when a group in a regular expression is not properly closed. This example includes the problematic code and the corresponding error message.
```groovy
include::../test/RegexCheckerTest.groovy[tags=unclosed_group,indent=0]
```
```groovy
include::../test/RegexCheckerTest.groovy[tags=unclosed_group_message,indent=0]
```
--------------------------------
### Customizing Groovy Shell Documentation Paths
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-groovysh/src/spec/doc/groovysh.adoc
Example of configuring custom documentation paths in the ~/.groovy/groovysh_init.groovy file.
```groovy
CONSOLE_OPTIONS.docs.groovy='https://groovy-lang.org/documentation.html'
CONSOLE_OPTIONS.docs.'org/jline/.*'='https://www.javadoc.io/doc/org.jline/jline/latest/'
```
```jshell
groovy> /doc groovy
groovy> /doc org.jline.terminal.Terminal
```
--------------------------------
### Basic GET Request with Query Parameters
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-http-builder/src/spec/doc/http-builder.adoc
Demonstrates a basic GET request with query parameters encoded using RFC 3986 percent-encoding. Spaces in keys and values become %20.
```groovy
def client = HttpBuilder.http('https://example.com/')
client.query(page: 1, size: 10)
client.get('/api/items') {
assert status == 200
println text
}
```
--------------------------------
### Basic vstrut Usage
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-swing/src/spec/doc/_swing-builder-widgets.adoc
Demonstrates the most basic usage of the `vstrut` widget. No specific setup or imports are required beyond the SwingBuilder instance.
```groovy
swing.vstrut()
```
--------------------------------
### Connect to HSQLDB with DataSource
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-sql/src/spec/doc/sql-userguide.adoc
Connect to an HSQLDB database using an existing DataSource. This example uses the DataSource provided by the HSQLDB driver jar.
```groovy
def ds = new org.hsqldb.jdbc.JDBCDataSource()
ds.setDatabase('jdbc:hsqldb:mem:yourdb')
ds.setUser('sa')
ds.setPassword('_yourPassword_')
def db = new Sql(ds)
```
--------------------------------
### Valid Format String Example
Source: https://github.com/apache/groovy/blob/master/subprojects/groovy-typecheckers/src/spec/doc/typecheckers.adoc
Demonstrates correct usage of format string methods with type checking enabled. This example ensures that the format string and its arguments are compatible, preventing runtime errors.
```groovy
def name = "World"
def message = "Hello %s".format(name)
println message
```