### Groovy Script Example Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/community-over-code-na-2023.adoc Demonstrates a simple Groovy script that prints 'Hello world!'. This example is compatible with JEP 445 scripting in Java. ```groovy def main() { println 'Hello world!' } ``` -------------------------------- ### Initial Diet Problem Setup Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/solving-simple-optimization-problems-with-groovy.adoc Defines the initial food items and solver configuration for a diet optimization problem. This setup is used to solve the problem with default solver settings. ```groovy def unsolved = new DietSolution(foods: [ new Food('Bread' , '🍞', 2.0, 4.0, 1.0, 15.0, 90), new Food('Milk' , '🥛', 3.5, 8.0, 5.0, 11.7, 120), new Food('Cheese', '🧀', 8.0, 7.0, 9.0, 0.4, 106), new Food('Potato', '🥔', 1.5, 1.3, 0.1, 22.6, 97), new Food('Fish' , '🐟', 11.0, 8.0, 7.0, 0.0, 130), new Food('Yogurt', '🍶', 1.0, 9.2, 1.0, 17.0, 180) ]) def config = new SolverConfig() .withSolutionClass(DietSolution) .withEntityClasses(Food) .withConstraintProviderClass(DietConstraintProvider) .withTerminationSpentLimit(Duration.ofSeconds(10)) def factory = SolverFactory.create(config) def solver = factory.buildSolver() println solver.solve(unsolved) ``` -------------------------------- ### SQL DSL Example in Groovy Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/wiki/GEP-3.adoc An example of how a DSL for SQL queries can be expressed in Groovy using current syntax. This demonstrates a practical application of Groovy's expressive power. ```Groovy sql.select( "column_name", from:"table_name", where:"column_name" ``` -------------------------------- ### Custom Window Gatherer Usage Examples Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-gatherers.adoc Demonstrates the usage of the custom `windowMultiple` gatherer with different step size configurations. ```groovy assert (1..8).stream().gather(windowMultiple(3)).toList() == [[1, 2, 3]] ``` ```groovy assert (1..8).stream().gather(windowMultiple(3, 2, 1)).toList() == [[1, 2, 3], [4, 5], [6]] ``` ```groovy assert (1..8).stream().gather(windowMultiple(3, -1)).toList() == [[1, 2, 3], [4, 5, 6, 7, 8]] ``` -------------------------------- ### Basic Micronaut LangChain4j Chat Example Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-ai.adoc A simple Micronaut application demonstrating a basic chat interaction using LangChain4j to get recommendations for Auckland. ```groovy @Singleton class AppRunner { @Inject HolidayAssistant assistant void run() { println assistant.activities('What are four good things to see while I am in Auckland?') } } @AiService interface HolidayAssistant { @SystemMessage(''' You are knowledgeable about places tourists might like to visit. Answer using New Zealand slang but keep it family friendly. ''') String activities(String userMessage) } try(var context = ApplicationContext.run()) { context.getBean(AppRunner).run() } ``` -------------------------------- ### Define variables for examples Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/exploring-gatherers4j.adoc These variables are used across multiple examples to provide consistent data sources. ```groovy var abc = 'A'..'C' var abcde = 'A'..'E' var nums = 1..3 ``` -------------------------------- ### Groovy DSL for financial and scheduling tasks Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/wiki/GEP-3.adoc Showcases various Groovy DSL examples for different domains, including financial transactions, scheduling, and blending colors. These examples demonstrate the flexibility of command expressions with named and non-named arguments, closures, and method chaining. ```groovy sell 100.shares of MSFT // sell(100.shares).of(MSFT) ``` ```groovy every 10.minutes, execute {} // already possible with current command expressions ``` ```groovy schedule executionOf { ... } every 10.minutes // scheduler(executionOf({})).every(10.minutes) ``` ```groovy blend red, green of acrylic // blend(red, gree).of(acrylic) ``` ```groovy select from: users where age > 32 and sex == 'male' // equivalent to select(from: users).where(age > 32).and(sex == 'male') // not that however for this example, it would be intersting // to transparently convert the boolean conditions into closure expressions! ``` ```groovy take mediumBowl combine soySauce, vinegar, chiliPowder, garlic place chicken in sauce turn once to coat marinate 30.minutes at roomTemperature ``` -------------------------------- ### Groovy println AST Template Example Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/wiki/GEP-4.adoc A concise example of generating a println AST in Groovy using AstBuilder and the proposed oxford bracket syntax for AST templating. ```groovy new AstBuilder().buildFromCode { println([ | message | ]) }[0] ``` -------------------------------- ### Package Change Example in Groovy Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-3-highlights.adoc Illustrates a package change for a utility class from groovy.util to groovy.xml. ```groovy groovy.util.XmlParser => groovy.xml.XmlParser groovy.util.XmlSlurper => groovy.xml.XmlSlurper groovy.util.GroovyTestCase => groovy.test.GroovyTestCase ``` -------------------------------- ### Commit Trailer Examples Source: https://github.com/apache/groovy-website/blob/asf-site/AGENTS.md Examples of commit trailers for attributing AI assistance. 'Assisted-by:' is the default for AI-assisted changes, while 'Generated-by:' is for AI-produced changes with minimal human modification. ```git Assisted-by: ``` ```git Generated-by: ``` -------------------------------- ### Java JMH Benchmark Setup Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-record-performance.adoc Sets up a static instance of a Java record for use in JMH benchmarks. ```java private static final JavaRecordLabel JAVA_RECORD_LABEL = new JavaRecordLabel(X0, X1, X2, X3, X4); ``` -------------------------------- ### Using the Inits Gatherer Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-gatherers.adoc Example of using the custom `inits` gatherer on a stream to obtain a list of all initial sublists, demonstrating its functionality. ```groovy assert search.stream().gather(inits()).toList() == [[], ['brown'], ['brown', 'fox']] ``` -------------------------------- ### Start Ignite Node, Populate Cache, and Run K-Means Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/whiskey-clustering-with-groovy-and.adoc Starts an Apache Ignite node with the specified configuration, prints the dimensions of the loaded data, and initiates the K-Means clustering process. ```groovy Ignition.start(cfg).withCloseable { ignite -> println ">>> Ignite grid started for data: ${data.size()} rows X ${data[0].size()} cols" ``` -------------------------------- ### Groovy Collection Take and Drop Examples Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-gatherers.adoc Shows how to use the 'take' and 'drop' methods to select a window of elements from a Groovy collection. ```groovy assert (1..8).take(3) == [1, 2, 3] // same as [0..2] assert (1..8).drop(2).take(3) == [3, 4, 5] // same as [2..4] ``` -------------------------------- ### Groovy Language Integrated Query (GQ) Example Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/community-over-code-na-2023.adoc Illustrates Groovy's Language Integrated Queries (GQ) feature, providing a SQL-like syntax for querying collections. This example groups fruits by their first character and lists them. ```groovy GQ { from fruit in ['Apple', 'Apricot', 'Banana', 'Cantaloupe'] groupby fruit[0] as firstChar select firstChar, list(fruit.toUpperCase()) as fruit_list } ``` -------------------------------- ### Example Usage of Dynamic Rover DSL Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/life-on-mars-units-of.adoc Demonstrates how to use the dynamic map-based DSL to control the rover's movement. ```groovy move right by 2.m at 5.cm/s ``` -------------------------------- ### Dafny Example: Multiply by Repeated Addition Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/loop-invariants.adoc A textbook Dafny example demonstrating multiplication using repeated addition, including preconditions, postconditions, and loop invariants. ```dafny method Multiply(m: int, n: int) returns (res: int) requires m >= 0 && n >= 0 ensures res == m * n { res := 0; var i := 0; while i < n invariant 0 <= i <= n invariant res == i * m { res := res + m; i := i + 1; } } ``` -------------------------------- ### Fluent API Example in Groovy with GEP-3 Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/wiki/GEP-3.adoc The Groovy equivalent of the Java fluent API example, utilizing extended command expressions for a more concise syntax. Parentheses and dots are omitted. ```Groovy Email.from "foo@example.com" to "bar@example.com" subject "hello" body "how are you?" ``` -------------------------------- ### Groovy Collection Indexing Examples Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-gatherers.adoc Demonstrates various ways to index and select elements from Groovy collections using ranges and specific indices. ```groovy assert (1..8)[0..2] == [1, 2, 3] // index by closed range assert (1..8)[3<..<6] == [5, 6] // index by open range assert (1..8)[0..2,3..4,5] == [1, 2, 3, 4, 5, 6] // index by multiple ranges assert (1..8)[0..2,3..-1] == 1..8 // ditto assert (1..8)[0,2,4,6] == [1,3,5,7] // select odd numbers assert (1..8)[1,3,5,7] == [2,4,6,8] // select even numbers ``` -------------------------------- ### Gatherers4J window gatherer examples Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/exploring-gatherers4j.adoc Demonstrates the usage of the `window` gatherer from Gatherers4J with different parameters for step size and remainder handling. ```groovy assert (1..5).stream().gather(Gatherers4j.window(3, 1, true)).toList() == [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5], [5]] assert (1..8).stream().gather(Gatherers4j.window(3, 2, true)).toList() == [[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8]] assert (1..8).stream().gather(Gatherers4j.window(3, 2, false)).toList() == [[1, 2, 3], [3, 4, 5], [5, 6, 7]] assert (1..8).stream().gather(Gatherers4j.window(3, 4, false)).toList() == [[1, 2, 3], [5, 6, 7]] assert (1..8).stream().gather(Gatherers4j.window(3, 3, true)).toList() == [[1, 2, 3], [4, 5, 6], [7, 8]] ``` -------------------------------- ### Starting the Actor System with GPars Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-pekko-gpars.adoc Sends initial 'SayHello' messages to the main actor to initiate the system's operation. ```groovy main << new SayHello('World') main << new SayHello('GPars') ``` -------------------------------- ### Groovy Functional Composition Example Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy6-functional.adoc Demonstrates functional composition of closures and method references in Groovy. ```groovy var trim = { String s -> s.trim() } var upper = String::toUpperCase var sizeSq = (String::size) >> { it ** 2 } var composed = sizeSq << (trim >> upper) assert composed(' foo bar ') == 49 ``` -------------------------------- ### Groovy Query Language (GQL) - Limit and Offset Example Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-gatherers.adoc Equivalent of `take` and `drop` combined, using `limit` with an offset in GQL. ```groovy assert GQL { from n in 1..8 limit 2, 3 select n } == [3, 4, 5] ``` -------------------------------- ### Groovy Legacy Date and Calendar Examples Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-dates-and-times-cheat.adoc Shows how to work with legacy Date and Calendar objects in Groovy for time representation and manipulation. ```groovy var breakfast = Date.parse('hh:mm', '07:30') var lunch = Calendar.instance.tap { clear() set(hourOfDay: 12, minute: 30) } assert lunch[HOUR_OF_DAY, MINUTE] == [12, 30] var dinner = lunch.clone().tap { it[HOUR_OF_DAY] += 7 } assert dinner == lunch.copyWith(hourOfDay: 19) assert dinner.format('hh:mm a') == '07:30 pm' assert dinner.format('k:mm') == '19:30' assert dinner.time.timeString == '7:30:00 pm' assert breakfast.before(lunch.time) // Java API assert lunch < dinner // Groovy shorthand ``` -------------------------------- ### Sliding Window Gatherer Usage Examples Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-gatherers.adoc Demonstrates the usage of the `windowSlidingByStep` gatherer with different step sizes and the `keepRemaining` flag. ```groovy assert (1..5).stream().gather(windowSlidingByStep(3, 1)).toList() == [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5], [5]] ``` ```groovy assert (1..8).stream().gather(windowSlidingByStep(3, 2)).toList() == [[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8]] ``` ```groovy assert (1..8).stream().gather(windowSlidingByStep(3, 2, false)).toList() == [[1, 2, 3], [3, 4, 5], [5, 6, 7]] ``` ```groovy assert (1..8).stream().gather(windowSlidingByStep(3, 4, false)).toList() == [[1, 2, 3], [5, 6, 7]] ``` ```groovy assert (1..8).stream().gather(windowSlidingByStep(3, 3)).toList() == [[1, 2, 3], [4, 5, 6], [7, 8]] ``` -------------------------------- ### Begin Neo4j Transaction Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-graph-databases.adoc Starts a Neo4j embedded database transaction. Ensure the managementService is set up prior to this. ```groovy // ... set up managementService ... var graphDb = managementService.database(DEFAULT_DATABASE_NAME) try (Transaction tx = graphDb.beginTx()) { // ... other Neo4j code below here ... } ``` -------------------------------- ### Java Stream Skip and Limit Examples Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-gatherers.adoc Illustrates how to achieve similar 'take' and 'drop' functionality using Java Streams with 'skip' and 'limit'. ```java assert (1..8).stream().limit(3).toList() == [1, 2, 3] assert (1..8).stream().skip(2).limit(3).toList() == [3, 4, 5] ``` -------------------------------- ### Groovy Starter Configuration - Load Libraries Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/wiki/GEP-9.adoc This configuration snippet shows how Groovy bootstraps its configuration by loading all JAR files from the lib directory. ```groovy # load required libraries load !{groovy.home}/lib/*.jar ``` -------------------------------- ### Graph Traversal Example Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-graph-databases.adoc Performs a graph traversal starting from a specific swim, following 'supersedes' edges to find related events. ```groovy println "Olympic records after ${swim1.properties().subMap(['at', 'event']).values().join(' ')}: " gremlin.gremlin(''' g.V().has('at', 'London 2012').repeat(__.in('supersedes')).emit().values('at', 'event') ''').execute().data().collate(2).each { a, e -> println "$a $e" } ``` -------------------------------- ### Fleet Ticker Server Example Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-mina-sshd.adoc This script demonstrates booting SSHD broker servers, building a fleet, and running an in-process socket client to process market data. It showcases the output of a typical run, including subscribed symbols, ticks, quotes, and unsubscribes. ```groovy sleep intervalMillis } } } void stop() { running.set(false) } } ``` -------------------------------- ### Groovy Inits and Tails for List Subsequences Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-gatherers.adoc Demonstrates Groovy's `inits` and `tails` functions, showing their output for a sequence of numbers. ```groovy assert (1..6).inits() == [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3], [1, 2], [1], []] assert (1..6).tails() == [[1, 2, 3, 4, 5, 6], [2, 3, 4, 5, 6], [3, 4, 5, 6], [4, 5, 6], [5, 6], [6], []] ``` -------------------------------- ### Neo4j Graph Traversal Example Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-graph-databases.adoc Demonstrates Neo4j's traversal API to find paths starting from a specific swim record, following 'supersedes' relationships. It prints information about the end node of each path. ```groovy var info = { s -> "$s.at $s.event" } println "Olympic records following ${info(swim1)}:" for (Path p in tx.traversalDescription() .breadthFirst() .relationships(supersedes) .evaluator(Evaluators.fromDepth(1)) .uniqueness(Uniqueness.NONE) .traverse(swim1)) { println p.endNode().with(info) } ``` -------------------------------- ### Simple Interface SAM Example Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/wiki/GEP-12.adoc An example of a simple interface that qualifies as a SAM type. ```groovy interface SAM { def foo() } ``` -------------------------------- ### Build Developer Site with Gradle Source: https://github.com/apache/groovy-website/blob/asf-site/AGENTS.md Use this command to build the developer-focused website. The output will be located in site-dev/build/site/. ```bash ./gradlew :site-dev:webzip ``` -------------------------------- ### Build User Site with Gradle Source: https://github.com/apache/groovy-website/blob/asf-site/AGENTS.md Use this command to build the user-facing website. The output will be located in site-user/build/site/. ```bash ./gradlew :site-user:webzip ``` -------------------------------- ### Method does not exist example Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/wiki/GEP-8.adoc This example demonstrates a typo in a method call, which static type checking will flag as an error. ```groovy def method() { ... } methode() // typo ``` -------------------------------- ### Assignment type checking example Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/wiki/GEP-8.adoc This example illustrates a forbidden assignment where a String is assigned to an integer variable, which STC will prevent. ```groovy int x = 2 x = 'String' ``` -------------------------------- ### Groovy Starter Configuration - Grab Module Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/wiki/GEP-9.adoc This configuration snippet demonstrates how to load a specific module, like groovy-sql, using the 'grab' directive with version information. ```groovy # load SQL component grab org.codehaus.groovy groovy-sql 1.9.0 ``` -------------------------------- ### Property does not exist example Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/wiki/GEP-8.adoc This example shows an attempt to assign a value to a non-existent property 'y' on an object of class A, which STC will detect. ```groovy class A { int x } A obj = new A() a.y = 2 ``` -------------------------------- ### Basic CliBuilder Usage Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-2-5-clibuilder-renewal.adoc Demonstrates basic CliBuilder setup for defining options and displaying usage help. Shows how to define headings and options, and then call usage(). ```groovy def cli = new groovy.cli.CliBuilder() cli.headerHeading("%nHeader heading:%n") cli.header("header 1", "header 2") cli.descriptionHeading("%nDescription heading:%n") description("description 1", "description 2") cli.optionListHeading("%nOPTIONS:%n") cli.footerHeading("%nFooter heading:%n") cli.footer("footer 1", "footer 2") cli.a(longOpt: 'aaa', 'a-arg') // (4) cli.b(longOpt: 'bbb', 'b-arg') cli.usage() ``` -------------------------------- ### Groovy Contract Annotation Example Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy6-functional.adoc Example of using contract annotations like `@Requires` for specifying preconditions, which can be checked by type-checking extensions. ```groovy @Requires ``` -------------------------------- ### Compile-time Regex Error Example Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-typecheckers.adoc This example shows a compile-time error generated by RegexChecker when an unmatched closing parenthesis is present in the regular expression. ```groovy [Static type checking] - Bad regex: Unmatched closing ')' ``` -------------------------------- ### GroovyFX Application Start Method Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/adventures-with-groovyfx.adoc Initializes the GroovyFX application stage, loads category images, and sets up the main UI layout using a GridPane with text fields, combo box, date picker, and table view. ```groovy start { stage(title: 'GroovyFX ToDo Demo', show: true, onCloseRequest: close) { urls.each { k, v -> images[k] = image(url: v, width: 24, height: 24) } scene { gridPane(hgap: 10, vgap: 10, padding: 20) { columnConstraints(minWidth: 80, halignment: 'right') columnConstraints(prefWidth: 250) label('Task:', row: 1, column: 0) task = textField(row: 1, column: 1, hgrow: 'always') label('Category:', row: 2, column: 0) category = comboBox(items: ToDoCategory.values().toList(), cellFactory: graphicLabelFactory, row: 2, column: 1) label('Date:', row: 3, column: 0) date = datePicker(row: 3, column: 1) table = tableView(items: items, row: 4, columnSpan: REMAINING, onMouseClicked: { var item = items[table.selectionModel.selectedIndex.value] task.text = item.task category.value = item.category ``` -------------------------------- ### Possible loss of precision (long to int) example Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/wiki/GEP-8.adoc This example demonstrates a potential loss of precision when assigning a long value to an int variable. STC will flag this. ```groovy long myLong = ... int myInt = myLong ``` -------------------------------- ### Initialize Helper Variables for Clustering Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/whiskey-clustering-with-groovy-and.adoc Sets up helper variables including feature names, a pretty-print formatter for doubles, an Euclidean distance metric, and a vectorizer for the K-Means algorithm. ```groovy var features = ['Body', 'Sweetness', 'Smoky', 'Medicinal', 'Tobacco', 'Honey', 'Spicy', 'Winey', 'Nutty', 'Malty', 'Fruity', 'Floral'] var pretty = this.&sprintf.curry('%.4f') var dist = new EuclideanDistance() var vectorizer = new DoubleArrayVectorizer().labeled(FIRST) ``` -------------------------------- ### Incompatible binary expressions example Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/wiki/GEP-8.adoc This example shows an incompatible binary expression where a String is added to an integer. STC checks if a compatible 'plus' method exists. ```groovy 1 + 'string' ``` -------------------------------- ### Broker Box Server Setup Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-mina-sshd.adoc Boots an SSHD server with a custom CommandFactory for handling quote requests. Uses sensible defaults for ciphers, MACs, and key-exchange algorithms. ```groovy SshServer.setUpDefaultServer() SimpleGeneratorHostKeyProvider() AcceptAllPasswordAuthenticator.INSTANCE new CommandFactory() { @Override Command createCommand(String line) { return new QuoteCommand(line) } } ``` -------------------------------- ### Use the Explicit Delegation Menu Class Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-delegation.adoc Demonstrates how to create and use the Menu class, adding items and asserting properties. ```groovy def vietnamese = new Menu().tap { add(new MenuItem('Phở', 7)) add(new MenuItem('Bánh Mì', 5)) } assert vietnamese[0].price == 7 assert vietnamese.size() == 2 assert vietnamese.findByPrice(7).name == 'Phở' ``` -------------------------------- ### Groovy Usage Example for Menu Class Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-delegation.adoc Demonstrates creating and populating Menu objects, then asserting list and date-related behaviors. This includes accessing items by index, checking for item non-overlap, and comparing dates. ```groovy def italianWednesday = new Menu(LocalDate.of(2024, 1, 24)).tap { add(new MenuItem('Spaghetti Bolognese', 10)) add(new MenuItem('Gnocchi di Patate', 11)) add(new MenuItem('Tiramisù', 9)) } def italianThursday = new Menu(LocalDate.of(2024, 1, 25)).tap { add(new MenuItem('Fettuccine al Pomodoro', 12)) add(new MenuItem('Pizza Margherita', 10)) add(new MenuItem('Pannacotta', 10)) } assert italianWednesday[0].price == 10 assert !italianWednesday.any{ italianThursday.contains(it) } assert italianWednesday.isBefore(italianThursday.dateDelegate) ``` -------------------------------- ### Query Swim Events Starting with 'Heat' Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-graph-databases.adoc Executes a Cypher-style query to find distinct 'at' locations for swims where the event starts with 'Heat'. Asserts the result. ```groovy assert run(''' MATCH (s:Swim) WHERE s.event STARTS WITH 'Heat' RETURN DISTINCT s.at AS at ''')*.get('at')*.asString().toSet() == ["London 2012", "Tokyo 2021"] as Set ``` -------------------------------- ### Explicit return type checking example Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/wiki/GEP-8.adoc This example shows a method declared to return an int, but it attempts to return a String. STC will flag this as an incompatible return type. ```groovy int method() { return 'String' // return type is not compatible } ``` -------------------------------- ### Before: Multiple Options for Aliases Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-2-5-clibuilder-renewal.adoc Illustrates the previous requirement to declare separate options for each alias, such as '-cp' and '-classpath'. ```groovy // before: split -cp, -classpath into two options def cli = new CliBuilder(usage: 'groovyConsole [options] [filename]') cli.classpath('Where to find the class files') cli.cp(longOpt: 'classpath', 'Aliases for "-classpath"') ``` -------------------------------- ### Array component type assignment example Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/wiki/GEP-8.adoc This example shows an attempt to assign an integer value to an element in a String array. STC will prevent this due to type incompatibility. ```groovy String[] arr = { '1', '2', '3' } arr[2] = 200 ``` -------------------------------- ### Awaiting Single from RxJava with Adapter Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-async-await.adoc This example demonstrates awaiting a `Single` from RxJava directly using the `await` keyword, assuming the `groovy-rxjava` adapter is available on the classpath. This simplifies asynchronous operations with RxJava types. ```groovy def result = await Single.just('hello') ``` -------------------------------- ### GraphQL Runtime Wiring and Schema Creation Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-graph-databases.adoc Sets up the GraphQL runtime by parsing the schema and defining DataFetchers for each query. It then builds an executable schema. ```groovy var generator = new SchemaGenerator() var types = getClass().getResourceAsStream("/schema.graphqls") .withReader { reader -> new SchemaParser().parse(reader) } var swimFetcher = { DataFetchingEnvironment env -> var name = env.arguments.name var at = env.arguments.at var event = env.arguments.event swims.find{ s -> s.who.name == name && s.at == at && s.event == event } } as DataFetcher var finalsFetcher = { DataFetchingEnvironment env -> swims.findAll{ s -> s.event == 'Final' && supersedes.any{ it[0] == s } } } as DataFetcher> var heatsFetcher = { DataFetchingEnvironment env -> swims.findAll{ s -> s.event.startsWith('Heat') && (supersedes[0][1] == s || supersedes.any{ it[0] == s }) } } as DataFetcher> var successFetcher = { DataFetchingEnvironment env -> var at = env.arguments.at swims.findAll{ s -> s.at == at } } as DataFetcher> var recordsFetcher = { DataFetchingEnvironment env -> supersedes.collect{it[0] } } as DataFetcher> var wiring = RuntimeWiring.newRuntimeWiring() .type("Query") { builder -> builder.dataFetcher("findSwim", swimFetcher) builder.dataFetcher("recordsInFinals", finalsFetcher) builder.dataFetcher("recordsInHeats", heatsFetcher) builder.dataFetcher("success", successFetcher) builder.dataFetcher("allRecords", recordsFetcher) }.build() var schema = generator.makeExecutableSchema(types, wiring) var graphQL = GraphQL.newGraphQL(schema).build() ``` -------------------------------- ### Possible loss of precision (int literal as long) example Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/wiki/GEP-8.adoc This example shows an integer literal with an 'L' suffix being assigned to an int. STC will not complain here as '2' can be represented as an int. ```groovy int myInt = 2L ``` -------------------------------- ### Java-style Array Initialization in Groovy Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-3-highlights.adoc Demonstrates initializing an array using Java's syntax within Groovy. ```groovy def primes = new int[] {2, 3, 5, 7, 11} ``` -------------------------------- ### Method return type check example Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/wiki/GEP-8.adoc This example demonstrates a mismatch between the declared return type of a method (String) and the type of the variable receiving the return value (int). STC enforces compatibility. ```groovy String method() { 'Hello' } int x = method() // return types don't match ``` -------------------------------- ### Groovy `val` type inference examples Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/wiki/GEP-16.adoc When statically type checking, `val` infers the type similarly to `final` or `final def`. This example demonstrates type inference for different initial values. ```groovy val x = 42 // final, type inferred as int val s = 'hello' // final, type inferred as String val list = [1,2,3] // final, type inferred as ArrayList ``` -------------------------------- ### Measuring Native Image Execution Speed Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/working-with-sql-databases-with.adoc This example demonstrates how to measure the execution time of a native image application using the 'time' command. It shows the real, user, and system time taken for the application to run. ```bash paulk@pop-os:/extra/projects/groovy-graalvm-h2$ time build/native/nativeCompile/H2Demo [aqua]##[ID:1, NAME:Lord Archimonde] [ID:2, NAME:Arthur] [ID:3, NAME:Gilbert] [ID:4, NAME:Grug]## real 0m0.027s user 0m0.010s sys 0m0.011s ``` -------------------------------- ### Groovy LocalTime Examples Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-dates-and-times-cheat.adoc Demonstrates creating, parsing, manipulating, and formatting LocalTime objects using Groovy's concise syntax and Java API. ```groovy var breakfast = LocalTime.of(7, 30) var lunch = LocalTime.parse('12:30') assert lunch == LocalTime.parse('12:30.00 pm', 'hh:mm.ss a') lunch.with { assert hour == 12 && minute == 30 } var dinner = lunch.plusHours(7) assert dinner == lunch.plus(7, ChronoUnit.HOURS) assert Duration.between(lunch, dinner).toHours() == 7 assert breakfast.isBefore(lunch) // Java API assert lunch < dinner // Groovy shorthand assert lunch in breakfast..dinner assert dinner.format('hh:mm a') == '07:30 pm' assert dinner.format('k:mm') == '19:30' assert dinner.format(FormatStyle.MEDIUM) == '7:30:00 pm' assert dinner.timeString == '19:30:00' ``` -------------------------------- ### Groovy: Collate with various step sizes and leftover handling Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-gatherers.adoc Presents multiple examples of the `collate` method with different window sizes, step sizes, and options for keeping or discarding remaining elements. ```groovy assert (1..5).collate(3, 1) == [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5], [5]] assert (1..8).collate(3, 2) == [[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8]] assert (1..8).collate(3, 2, false) == [[1, 2, 3], [3, 4, 5], [5, 6, 7]] assert (1..8).collate(3, 4, false) == [[1, 2, 3], [5, 6, 7]] assert (1..8).collate(3, 3) == [[1, 2, 3], [4, 5, 6], [7, 8]] // same as collate(3) ``` -------------------------------- ### GPars Message Definitions Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-pekko-gpars.adoc Defines the strongly typed message containers for the GPars actor example. ```groovy record Greet(String whom, Actor replyTo) { } record Greeted(String whom, Actor from) {} record SayHello(String name) { } ``` -------------------------------- ### Interactive Client with Netcat Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-mina.adoc Demonstrates how to interact with the TickerServer using the netcat command-line utility. Shows sample commands and expected server responses. ```shell $ nc localhost 9999 SUBSCRIBE AAPL,MSFT SUBSCRIBED AAPL SUBSCRIBED MSFT TICK AAPL 173.42 TICK MSFT 412.10 ... QUOTE GOOG,TSLA QUOTE GOOG 198.20 QUOTE TSLA 215.55 UNSUBSCRIBE AAPL UNSUBSCRIBED AAPL QUIT BYE ``` -------------------------------- ### Get List Init Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-list-processing-cheat-sheet.adoc Returns a new list containing all elements except the last one. ```groovy assert [1, 2, 3, 4].init() == [1, 2, 3] ``` -------------------------------- ### Get Tail of List Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-list-processing-cheat-sheet.adoc Returns a new list containing all elements except the first one. ```groovy assert [1, 2, 3, 4].tail() == [2, 3, 4] ``` -------------------------------- ### Configure Gradle Build for Groovy Project Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/netbeans.adoc Set up the Gradle build file with necessary plugins, repositories, and dependencies for a Groovy application using Commons Numbers Fraction. ```groovy plugins { id 'groovy' id 'application' } repositories { mavenCentral() } dependencies { implementation libs.groovy implementation libs.numbers.fraction } java { toolchain { languageVersion = JavaLanguageVersion.of(21) } } application { mainClass = 'App' } ``` -------------------------------- ### Groovy Query Language (GQL) - Sliding Window Equivalent Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-gatherers.adoc Demonstrates a sliding window implementation using GQL with lead window function. ```groovy assert GQL { from ns in ( from n in 1..8 select n, (lead(n) over(orderby n)), (lead(n, 2) over(orderby n)) ) limit 3 select ns }*.toList() == [[1, 2, 3], [2, 3, 4], [3, 4, 5]] ``` -------------------------------- ### Example of Map Destructuring with Renaming Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/wiki/GEP-20.adoc Demonstrates how to destructure a map and rename properties using a colon syntax. ```groovy def (name: fullName) = person ``` -------------------------------- ### Method Selection in Dynamic Groovy Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/wiki/GEP-10.adoc Demonstrates Groovy's runtime method selection, choosing the most specialized signature. ```Groovy void foo(String arg) { println 'String' } void foo(Object o) { println 'Object' } def o = 'The type of o at runtime is String' foo(o) ``` -------------------------------- ### Wayang Cluster Allocations Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/using-groovy-with-apache-wayang.adoc Example output showing the members allocated to each cluster when printing cluster allocations. ```text Cluster 0 (17 members): Ardbeg, Balblair, Bowmore, Bruichladdich, Caol Ila, Clynelish, GlenGarioch, GlenScotia, Highland Park, Isle of Jura, Lagavulin, Laphroig, Oban, OldPulteney, Springbank, Talisker, Teaninich Cluster 2 (9 members): Aberlour, Balmenach, Dailuaine, Dalmore, Glendronach, Glenfarclas, Macallan, Mortlach, RoyalLochnagar Cluster 3 (36 members): AnCnoc, ArranIsleOf, Auchentoshan, Aultmore, Benriach, Bladnoch, Bunnahabhain, Cardhu, Craigganmore, Dalwhinnie, Dufftown, GlenElgin, GlenGrant, GlenMoray, GlenSpey, Glenallachie, Glenfiddich, Glengoyne, Glenkinchie, Glenlossie, Glenmorangie, Inchgower, Linkwood, Loch Lomond, Mannochmore, Miltonduff, RoyalBrackla, Speyburn, Speyside, Strathmill, Tamdhu, Tamnavulin, Tobermory, Tomintoul, Tomore, Tullibardine Cluster 4 (24 members): Aberfeldy, Ardmore, Auchroisk, Belvenie, Ben Nevis, Benrinnes, Benromach, BlairAthol, Craigallechie, Deanston, Edradour, GlenDeveronMacduff, GlenKeith, GlenOrd, Glendullan, Glenlivet, Glenrothes, Glenturret, Knochando, Longmorn, OldFettercairn, Scapa, Strathisla, Tomatin ``` -------------------------------- ### Runtime NullPointerException example Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-null-checker.adoc Demonstrates a common runtime error where a null reference is dereferenced, leading to a NullPointerException. ```groovy String name = null println name.toUpperCase() // NullPointerException at runtime ``` -------------------------------- ### CliBuilder Usage with ANSI Colors Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-2-5-clibuilder-renewal.adoc Illustrates customizing usage help messages with ANSI colors and styles using picocli's markup. Shows how to apply styles to headers, synopsis, descriptions, and footers. ```groovy def cli = new groovy.cli.picocli.CliBuilder(name: 'myapp') cli.usageMessage.with { headerHeading("@|bold,red,underline Header heading|@:%n") header($/@|bold,green \ ___ _ _ ___ _ _ _ / __| (_) _ )_ _(_) |__| |___ _ _ | (__| | | _ \ || | | / _` / -_) '_| \___|_|_|___/\_,_|_|_\|, |___ _ _ |@/$) synopsisHeading("@|bold,underline Usage|@: ") descriptionHeading("%n@|bold,underline Description heading|@:%n") description("Description 1", "Description 2") // after the synopsis optionListHeading("%n@|bold,underline Options heading|@:%n") footerHeading("%n@|bold,underline Footer heading|@:%n") footer($/@|bold,blue \ ___ ___ ___ / __|_ _ ___ _____ ___ _ |_ ) | __| | (_ | '| _ \/ _ \ V / || | / / _|__ \ \___|_| \___/\___/\_/ \_, | /___(_)___/ |__/ |@/$) } cli.a('option a description') cli.b('option b description') cli.c(type: List, 'option c description') cli.usage() ``` -------------------------------- ### System Initialization and Message Sending Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy-pekko-gpars.adoc Initializes the Pekko actor system and sends initial messages to the HelloWorldMain actor. ```groovy var system = ActorSystem.create(HelloWorldMain.create(), 'hello') system.tell(new HelloWorldMain.SayHello('World')) system.tell(new HelloWorldMain.SayHello('Pekko')) ``` -------------------------------- ### Create Micronaut App with Kubernetes and PostgreSQL Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/community-over-code-na-2023.adoc Command-line instruction to create a new Micronaut application in Groovy, including features for Kubernetes and PostgreSQL integration. ```bash mn create-app \ --features kubernetes \ --features postgres \ --features jdbc-data \ --lang groovy collatz ``` -------------------------------- ### Get Groovy Version Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/wiki/GEP-9.adoc This code snippet shows how to retrieve the current Groovy runtime version as a string. ```groovy println GroovySystem.version ``` -------------------------------- ### AST Template Example (Alternative) Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/wiki/GEP-2.adoc An alternative approach considered for AST creation using templates, which allows for dynamic application of AST structures. This feature was not implemented due to added complexity and potential for confusion. ```Groovy def astTemplate = builder.buildAst ( "println $txt" ).head() def constant = builder.buildAst ( "To be, or not to be: that is the question" ).head() def methodCallExpression = astTemplate.apply(txt: constant) // method call expression not contains println "To be ... " ``` -------------------------------- ### Groovy TypeChecked Reductions Example Source: https://github.com/apache/groovy-website/blob/asf-site/site/src/site/blog/groovy6-functional.adoc Demonstrates parallel reductions with type-checked associative operations using injectParallel and sumParallel. ```groovy @TypeChecked(extensions = 'groovy.typecheckers.CombinerChecker') def reductions() { assert (1..100).toList().injectParallel(0, Sum.&add) == 5050 assert ['a', 'b', 'c'].sumParallel(Concat.&join) == 'abc' assert [3, 1, 4, 1, 5, 9, 2, 6].sumParallel(Largest.&max) == 9 // REJECTED at compile time — subtraction is not associative: // [1, 2, 3].injectParallel(0) { a, b -> a - b } } ```