### Grails Version Output Source: https://grails.apache.org/docs/7.0.4/guide/gettingStarted.html Example output when verifying the Grails installation, showing the installed version. ```text Grails Version: 7.0.4 ``` -------------------------------- ### Integration Test with Setup Data (Not Rolled Back) Source: https://grails.apache.org/docs/7.0.4/guide/testing.html Demonstrates how data persisted in the setup() method is not rolled back by default. Manual cleanup is required if setup() persists data. ```groovy import grails.testing.mixin.integration.Integration import grails.gorm.transactions.* import spock.lang.* @Integration @Rollback class BookSpec extends Specification { void setup() { // Below line would persist and not roll back new Book(name: 'Grails in Action').save(flush: true) } void "test something"() { expect: Book.count() == 1 } } ``` -------------------------------- ### Asynchronous Rendering with AsyncContext Source: https://grails.apache.org/docs/7.0.4/guide/async.html Use the `startAsync` method to get an `AsyncContext` instance, then use its `start` method to perform asynchronous operations. Remember to call `complete()` to terminate the connection after rendering. ```groovy def ctx = startAsync() ctx.start { new Book(title:"The Stand").save() render template:"books", model:[books:Book.list()] ctx.complete() } ``` -------------------------------- ### Getting Help for Grails Commands Source: https://grails.apache.org/docs/7.0.4/guide/commandLine.html Use the 'help' command to list all available commands and get usage instructions. You can also get specific help for a command by appending its name. ```bash grails help ``` -------------------------------- ### Feature Configuration Example Source: https://grails.apache.org/docs/7.0.4/guide/profiles.html Example structure of a feature.yml file, including description, and commented-out sections for customizing versions and dependencies. ```yaml description: Description of the feature # customize versions here # dependencies: # - scope: compile # coords: "org.grails.plugins:myplugin2:1.0" ``` -------------------------------- ### Example Profile Configuration Source: https://grails.apache.org/docs/7.0.4/guide/profiles.html Customize profile dependencies and features using the `profile.yml` file. This example shows how to include default features, specify build plugins, exclude dependencies, and define custom dependencies. ```yaml features: defaults: - hibernate - asset-pipeline build: plugins: - org.apache.grails.gradle.grails-web excludes: - org.grails.grails-core dependencies: - scope: compile coords: "org.mycompany:myplugin:1.0.1" - scope: testCompile coords: org.spockframework:spock-core excludes: - group: org.codehaus.groovy module: groovy-all ``` -------------------------------- ### Accept Header Example from Firefox Source: https://grails.apache.org/docs/7.0.4/guide/theWebLayer.html An example of a detailed Accept header sent by Firefox, indicating preferred media types. ```text text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, \ text/plain;q=0.8, image/png, */*;q=0.5 ``` -------------------------------- ### Setting up URL Mappings Unit Test Source: https://grails.apache.org/docs/7.0.4/guide/testing.html Implement `UrlMappingsUnitTest` and mock necessary controllers in the `setup()` method to test URL mappings. Controllers can only be mocked after the request is available, typically in `setup()`. ```groovy import grails.testing.web.UrlMappingsUnitTest import spock.lang.Specification class UrlMappingsSpec extends Specification implements UrlMappingsUnitTest { void setup() { mockController(TestController) } ``` -------------------------------- ### Example Grails Command Invocations Source: https://grails.apache.org/docs/7.0.4/guide/commandLine.html Illustrates how to run an application in a specific environment and how to create a new Grails application. ```bash $ grails dev run-app ``` ```bash $ grails create-app books ``` -------------------------------- ### Quartz Grails Plugin Metadata Example Source: https://grails.apache.org/docs/7.0.4/guide/plugins.html An example demonstrating how to define metadata for a Grails plugin, including version support, author information, description, and issue tracking. ```groovy package quartz import grails.plugins.* import org.slf4j.LoggerFactory @grails.util.logging.Slf4j class QuartzGrailsPlugin extends Plugin { // the version or versions of Grails the plugin is designed for def grailsVersion = "3.0.0.BUILD-SNAPSHOT > *" // resources that are excluded from plugin packaging def pluginExcludes = [ "grails-app/views/error.gsp" ] def title = "Quartz" // Headline display name of the plugin def author = "Jeff Brown" def authorEmail = "zzz@yyy.com" def description = '''\ Adds Quartz job scheduling features ''' def profiles = ['web'] List loadAfter = ['hibernate3', 'hibernate4', 'hibernate5', 'services'] def documentation = "https://apache.github.io/grails-quartz/latest/" def license = "APACHE" def issueManagement = [ system: "Github Issues", url: "https://github.com/apache/grails-quartzissues" ] def developers = [ [ name: "Joe Dev", email: "joedev@gmail.com" ] ] def scm = [ url: "https://github.com/apache/grails-quartz" ] Closure doWithSpring()...... ``` -------------------------------- ### Grails Profile Directory Structure Example Source: https://grails.apache.org/docs/7.0.4/guide/profiles.html An example illustrating the typical directory structure of a Grails profile, including commands, features, skeleton, and templates. ```text /web commands/ create-controller.yml run-app.groovy ... features/ asset-pipeline/ skeleton feature.yml skeleton/ grails-app/ controllers/ ... build.gradle templates/ artifacts/ Controller.groovy profile.yml ``` -------------------------------- ### XML Request Body Binding Example Source: https://grails.apache.org/docs/7.0.4/guide/theWebLayer.html Example of sending an XML request body to bind to a command object. ```Shell $ curl -H "Content-Type: application/xml" -d 'Some Other Widget2112' localhost:8080/bodybind/demo/createWidget Name: Some Other Widget, Size: 2112 ``` -------------------------------- ### JSON View Output Example Source: https://grails.apache.org/docs/7.0.4/guide/theWebLayer.html The expected JSON output for the basic JSON view example. ```json {"message":{ "hello":"world"}} ``` -------------------------------- ### Install Grails with SDKMAN Source: https://grails.apache.org/docs/7.0.4/guide/gettingStarted.html Provides commands to install the latest version of Grails or a specific version using the SDKMAN package manager. ```bash $ sdk install grails ``` ```bash $ sdk install grails 7.0.4 ``` -------------------------------- ### Publish Plugin to Maven Local Source: https://grails.apache.org/docs/7.0.4/guide/plugins.html Execute the Gradle command to install the plugin into your local Maven cache. ```bash ./gradlew publishToMavenLocal ``` -------------------------------- ### Verify Grails Installation Source: https://grails.apache.org/docs/7.0.4/guide/gettingStarted.html Command to check if Grails has been installed correctly by displaying its version information. ```bash grails --version ``` -------------------------------- ### JSON Request Body Binding Example Source: https://grails.apache.org/docs/7.0.4/guide/theWebLayer.html Example of sending a JSON request body to bind to a command object. ```Shell $ curl -H "Content-Type: application/json" -d '{"name":"Some Widget","42"}'[size] localhost:8080/demo/createWidget Name: Some Widget, Size: 42 ``` -------------------------------- ### Example HAL Response Source: https://grails.apache.org/docs/7.0.4/guide/REST.html This is an example of a HAL response for a collection of books, with the default 'book' key for the embedded collection. ```json { "_links": { "self": { "href": "http://localhost:8080/books", "hreflang": "en", "type": "application/hal+json" } }, "_embedded": { "book": [ { "_links": { "self": { "href": "http://localhost:8080/books/1", "hreflang": "en", "type": "application/hal+json" } }, "title": "The Stand" }, { "_links": { "self": { "href": "http://localhost:8080/books/2", "hreflang": "en", "type": "application/hal+json" } }, "title": "Infinite Jest" }, { "_links": { "self": { "href": "http://localhost:8080/books/3", "hreflang": "en", "type": "application/hal+json" } }, "title": "Walden" } ] } } ``` -------------------------------- ### Gradle Build Configuration for Grails Source: https://grails.apache.org/docs/7.0.4/guide/commandLine.html Example 'build.gradle' file demonstrating how to configure Grails projects using Gradle, including plugins, repositories, and dependencies. ```gradle plugins { id 'org.apache.grails.gradle.grails-web' version 'x.y.z' // Grails plugin } repositories { mavenCentral() } dependencies { implementation 'org.springframework.boot:spring-boot-starter' implementation 'org.grails:grails-core' // Add more dependencies as needed... } ``` -------------------------------- ### Profile YAML: Include Gradle Plugins Source: https://grails.apache.org/docs/7.0.4/guide/profiles.html Example of how to specify a list of Gradle plugins to configure in the generated build within the `profile.yml` file. ```yaml build: plugins: - eclipse - idea - org.grails.grails-core ``` -------------------------------- ### Content Negotiation Example Source: https://grails.apache.org/docs/7.0.4/guide/theWebLayer.html Demonstrates how Grails Framework uses content negotiation to serve different views based on the request format or Accept header. This example shows serving JSON or GSP based on the request URI or Accept header. ```groovy def show() { respond Book.get(params.id) } ``` -------------------------------- ### Example JSON API Book Object Source: https://grails.apache.org/docs/7.0.4/guide/theWebLayer.html This is an example of how a `Book` domain class instance would be rendered according to the JSON API specification, including attributes and relationships. ```JSON { "data": { "type": "book", "id": "3", "attributes": { "title": "The Return of the King" }, "relationships": { "author": { "links": { "self": "/author/9" }, "data": { "type": "author", "id": "9" } } } }, "links": { "self": "http://localhost:8080/book/3" } } ``` -------------------------------- ### Create a Simple Greet Command Source: https://grails.apache.org/docs/7.0.4/guide/commandLine.html Example of creating a custom command by implementing the GrailsApplicationCommand trait. This command provides a name, description, and a simple greeting. ```groovy // grails-app/commands/com/example/GreetCommand.groovy package com.example import grails.dev.commands.GrailsApplicationCommand class GreetCommand implements GrailsApplicationCommand { String getName() { return "greet" } String getDescription() { return "Greet the user" } boolean handle() { println("Hello, user!") ``` -------------------------------- ### JSON View Output Example Source: https://grails.apache.org/docs/7.0.4/guide/REST.html The JSON view defined in the example produces the corresponding JSON output. This demonstrates the direct mapping from .gson syntax to JSON. ```json {"person":{"name":"bob"}} ``` -------------------------------- ### Example HAL JSON Document for Orders Source: https://grails.apache.org/docs/7.0.4/guide/REST.html This is an example of a HAL document representing a list of orders, including links, embedded resources, and resource states. ```json { "_links": { "self": { "href": "/orders" }, "next": { "href": "/orders?page=2" }, "find": { "href": "/orders{?id}", "templated": true }, "admin": [{ "href": "/admins/2", "title": "Fred" }, { "href": "/admins/5", "title": "Kate" }] }, "currentlyProcessing": 14, "shippedToday": 20, "_embedded": { "order": [{ "_links": { "self": { "href": "/orders/123" }, "basket": { "href": "/baskets/98712" }, "customer": { "href": "/customers/7809" } }, "total": 30.00, "currency": "USD", "status": "shipped" }, { "_links": { "self": { "href": "/orders/124" }, "basket": { "href": "/baskets/97213" }, "customer": { "href": "/customers/12369" } }, "total": 20.00, "currency": "USD", "status": "processing" }] } } ``` -------------------------------- ### Configure HTTPS/SSL via Command-Line Arguments Source: https://grails.apache.org/docs/7.0.4/guide/deployment.html Alternatively, specify SSL properties directly on the command line when starting the application. ```bash -Dserver.ssl.enabled=true -Dserver.ssl.key-store=/path/to/keystore ``` -------------------------------- ### Profile YAML: Configure Dependencies Source: https://grails.apache.org/docs/7.0.4/guide/profiles.html Example of how to configure scopes and dependencies, including the use of the 'excludes' scope, within the `profile.yml` file. ```yaml dependencies: - scope: excludes coords: "org.grails:hibernate:*" - scope: build coords: "org.grails:grails-gradle-plugin:$grailsVersion" - scope: compile coords: "org.springframework.boot:spring-boot-starter-logging" - scope: compile coords: "org.springframework.boot:spring-boot-autoconfigure" ``` -------------------------------- ### Markup View Configuration Example Source: https://grails.apache.org/docs/7.0.4/guide/theWebLayer.html Configure Markup views by setting properties in grails-app/conf/application.yml. ```yaml grails: views: markup: compileStatic: true cacheTemplates: true autoIndent: true ... ``` -------------------------------- ### HAL Output Example Source: https://grails.apache.org/docs/7.0.4/guide/theWebLayer.html This is an example of the HAL JSON output generated by the previous snippet, showing links and embedded author information. ```JSON { "_links": { "self": { "href": "http://localhost:8080/book/show/1", "hreflang": "en", "type": "application/hal+json" } }, "_embedded": { "author": { "_links": { "self": { "href": "http://localhost:8080/author/show/1", "hreflang": "en", "type": "application/hal+json" } }, "name": "Stephen King" } }, "title": "The Stand" } ``` -------------------------------- ### Grails Application Configuration Example Source: https://grails.apache.org/docs/7.0.4/guide/spring.html Define database connection properties in application.groovy. ```groovy database.driver="com.mysql.jdbc.Driver" database.dbname="mysql:mydb" ``` -------------------------------- ### Quartz Grails Plugin Metadata Example Source: https://grails.apache.org/docs/7.0.4/guide/plugins.html This example shows a more detailed plugin descriptor class with various metadata properties like version, author, description, and more. ```groovy package quartz @Slf4j class QuartzGrailsPlugin extends Plugin { // the version or versions of Grails the plugin is designed for def grailsVersion = "3.0.0.BUILD-SNAPSHOT > *" // resources that are excluded from plugin packaging def pluginExcludes = [ "grails-app/views/error.gsp" ] def title = "Quartz" // Headline display name of the plugin def author = "Jeff Brown" def authorEmail = "zzz@yyy.com" def description = '''\ Adds Quartz job scheduling features ''' def profiles = ['web'] List loadAfter = ['hibernate3', 'hibernate4', 'hibernate5', 'services'] def documentation = "https://apache.github.io/grails-quartz/latest/" def license = "APACHE" def issueManagement = [ system: "Github Issues", url: "https://github.com/apache/grails-quartzissues" ] def developers = [ [ name: "Joe Dev", email: "joedev@gmail.com" ] ] def scm = [ url: "https://github.com/apache/grails-quartz" ] Closure doWithSpring()...... ``` -------------------------------- ### Groovy Configuration Example Source: https://grails.apache.org/docs/7.0.4/guide/conf.html Example of using Groovy's ConfigSlurper syntax for application configuration. The 'userHome' variable represents the home directory of the user running the Grails application. ```Groovy my.tmp.dir = "${userHome}/.grails/tmp" ``` -------------------------------- ### Profile YAML: Include Maven Repositories Source: https://grails.apache.org/docs/7.0.4/guide/profiles.html Example of how to specify a list of Maven repositories to be included in the generated build within the `profile.yml` file. ```yaml repositories: - "https://repo1.maven.org/maven2" ``` -------------------------------- ### Windows Environment Variables Setup Source: https://grails.apache.org/docs/7.0.4/guide/gettingStarted.html Instructions for accessing and editing environment variables on Windows to include the Grails bin directory in the system PATH. ```bash Start + R ``` -------------------------------- ### Basic RestfulController Implementation Source: https://grails.apache.org/docs/7.0.4/guide/REST.html An example of a basic controller extending Grails' RestfulController to handle RESTful resources. ```Groovy class BookController extends RestfulController { static responseFormats = ['json', 'xml'] BookController() { super(Book) } } ``` -------------------------------- ### Create a Web Plugin Source: https://grails.apache.org/docs/7.0.4/guide/profiles.html Use this command to create a new Grails web plugin project. This is the primary command for starting a new plugin. ```bash grails create-web-plugin myplugin ``` -------------------------------- ### Run Grails Application Source: https://grails.apache.org/docs/7.0.4/guide/commandLine.html Execute this command to start your Grails application, typically for development and testing. ```bash gradle bootRun ``` -------------------------------- ### Example Usage of `generate-all` Script Source: https://grails.apache.org/docs/7.0.4/guide/commandLine.html Demonstrates how to invoke the `generate-all` Grails script with a domain class name and an optional force flag. ```bash grails generate-all MyClass --force ``` -------------------------------- ### Synchronous Service Example Source: https://grails.apache.org/docs/7.0.4/guide/async.html A basic synchronous service class with a method to find books. ```groovy class BookService { List findBooks(String title) { // implementation } } ``` -------------------------------- ### Example feature.yml for Asset Pipeline Source: https://grails.apache.org/docs/7.0.4/guide/profiles.html Defines the 'asset-pipeline' feature, including its description, build plugins, and runtime dependencies. ```yaml description: Adds Asset Pipeline to a Grails project build: plugins: - asset-pipeline dependencies: - scope: build coords: 'cloud.wondrify:asset-pipeline-gradle' - scope: runtime coords: "org.grails.plugins:asset-pipeline" ``` -------------------------------- ### Profile YAML: Default Features Source: https://grails.apache.org/docs/7.0.4/guide/profiles.html Example of how to specify a default list of features to be used if no explicit features are specified within the `profile.yml` file. ```yaml features: defaults: - hibernate - asset-pipeline ``` -------------------------------- ### Publish Profile Locally Source: https://grails.apache.org/docs/7.0.4/guide/profiles.html After configuring your profile, use the `gradle install` command to publish it to your local repository. This makes the profile available for use in creating new applications. ```bash $ gradle install ``` -------------------------------- ### Grails Interactive Mode Command Completion Source: https://grails.apache.org/docs/7.0.4/guide/gettingStarted.html When in Grails interactive mode, use TAB completion to see available commands. This example shows commands starting with 'create'. ```bash grails> create create-app create-plugin create-webapp create-controller create-restapi create-domain-class create-web-plugin ``` -------------------------------- ### Dependency Injection in Integration Tests Source: https://grails.apache.org/docs/7.0.4/guide/testing.html Illustrates how dependency injection works in Grails integration tests, ensuring injected services are available during setup. This example uses the @Integration annotation. ```groovy package demo import grails.testing.mixin.integration.Integration import spock.lang.Specification @Integration class DependencyInjectionSpec extends Specification { HelperService helperService def setup() { assert helperService != null } void 'some test method'() { expect: helperService != null } } ``` -------------------------------- ### Basic Grails Script Example Source: https://grails.apache.org/docs/7.0.4/guide/commandLine.html A simple Grails script that prints 'Hello World' to the console. The `description` method provides help text for `grails help`. ```groovy description "Example description", "grails hello-world" println "Hello World" ``` -------------------------------- ### URI Versioning Controller Definitions Source: https://grails.apache.org/docs/7.0.4/guide/REST.html Example controller classes for URI versioning, each associated with a specific namespace. ```Groovy package myapp.v1 class BookController { static namespace = 'v1' } package myapp.v2 class BookController { static namespace = 'v2' } ``` -------------------------------- ### Per-Environment Configuration in application.yml Source: https://grails.apache.org/docs/7.0.4/guide/conf.html Define environment-specific settings for `development`, `test`, and `production` in the `application.yml` file. This example shows configuration for the `dataSource` properties. ```yaml environments: development: dataSource: dbCreate: create-drop url: jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE test: dataSource: dbCreate: update url: jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE production: dataSource: dbCreate: update url: jdbc:h2:prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE properties: jmxEnabled: true initialSize: 5 ... ``` -------------------------------- ### Integration Test with SetupData Method (Rolled Back) Source: https://grails.apache.org/docs/7.0.4/guide/testing.html Shows how to use setupData() to create records that are rolled back after the test. Persistence operations should be called from the test method itself to ensure rollback. ```groovy import grails.testing.mixin.integration.Integration import grails.gorm.transactions.* import spock.lang.* @Integration @Rollback class BookSpec extends Specification { void setupData() { // Below line would roll back new Book(name: 'Grails in Action').save(flush: true) } void "test something"() { given: setupData() expect: Book.count() == 1 } } ``` -------------------------------- ### External SpringBeans.groovy Example Source: https://grails.apache.org/docs/7.0.4/guide/spring.html An example of an external Groovy script defining DataSource and SessionFactory beans. ```groovy import org.apache.commons.dbcp.BasicDataSource import org.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean beans { dataSource(BasicDataSource) { driverClassName = "org.h2.Driver" url = "jdbc:h2:mem:grailsDB" username = "sa" password = "" } sessionFactory(ConfigurableLocalSessionFactoryBean) { dataSource = dataSource hibernateProperties = ["hibernate.hbm2ddl.auto": "create-drop", "hibernate.show_sql": "true"] } } ``` -------------------------------- ### User Instructions Source: https://grails.apache.org/docs/7.0.4/guide/profiles.html Provides text to be displayed to the user after the application is created. ```yaml instructions: Here are some instructions ``` -------------------------------- ### Per-Environment Configuration in application.groovy Source: https://grails.apache.org/docs/7.0.4/guide/conf.html Express environment-specific settings using Groovy syntax in `application.groovy`. This example mirrors the `application.yml` configuration for `dataSource`. ```groovy dataSource { pooled = false driverClassName = "org.h2.Driver" username = "sa" password = "" } environments { development { dataSource { dbCreate = "create-drop" url = "jdbc:h2:mem:devDb" } } test { dataSource { dbCreate = "update" url = "jdbc:h2:mem:testDb" } } production { dataSource { dbCreate = "update" url = "jdbc:h2:prodDb" properties { jmxEnabled = true initialSize = 5 } } } } ``` -------------------------------- ### Grails Create App Help Source: https://grails.apache.org/docs/7.0.4/guide/commandLine.html Displays detailed usage information for the `create-app` command, including available options and their descriptions. Use this to understand all configuration possibilities for creating a new Grails application. ```bash grails> create-app -h Usage: grails create-app [-hivVx] [--list-features] [-g=GORM Implementation] [--jdk=] [-s=Servlet Implementation] [-t=TEST] [-f=FEATURE[,FEATURE...]]... [NAME] Creates an application [NAME] The name of the application to create. -f, --features=FEATURE[,FEATURE...] The features to use. Possible values: h2, scaffolding, gorm-hibernate5, spring-boot-starter-jetty, spring-boot-starter-tomcat, micronaut-http-client, cache-ehcache, hibernate-validator, postgres, mysql, cache, database-migration, grails-gsp, hamcrest, gorm-mongodb, assertj, mockito, spring-boot-starter-undertow, github-workflow-java-ci, jrebel, testcontainers, sqlserver, grails-console, views-markup, asset-pipeline-grails, views-json, gorm-neo4j, asciidoctor, grails-web-console, logbackGroovy, mongo-sync, shade, geb, properties -g, --gorm=GORM Implementation Which GORM Implementation to configure. Possible values: hibernate, mongodb, neo4j. -h, --help Show this help message and exit. -i, --inplace Create a service using the current directory --jdk, --java-version= The JDK version the project should target --list-features Output the available features and their descriptions -s, --servlet=Servlet Implementation Which Servlet Implementation to configure. Possible values: none, tomcat, jetty, undertow. -t, --test=TEST Which test framework to use. Possible values: junit, spock. -v, --verbose Create verbose output. -V, --version Print version information and exit. -x, --stacktrace Show full stack trace when exceptions occur. ``` -------------------------------- ### Get Plugin Information Source: https://grails.apache.org/docs/7.0.4/guide/plugins.html Retrieves detailed information about a specific plugin, such as its description and author. Replace [plugin-name] with the actual plugin name. ```bash grails plugin-info [plugin-name] ``` -------------------------------- ### Grails Controller Code Example Source: https://grails.apache.org/docs/7.0.4/guide/gettingStarted.html Example Groovy code for a simple Grails controller that renders a greeting message. ```groovy package myapp class GreetingController { def index() { render "Hello, Congratulations for your first Grails application!" } } ``` -------------------------------- ### Data Binding Example Source: https://grails.apache.org/docs/7.0.4/guide/validation.html Instantiates a User object and binds request parameters to it. Errors due to type conversion may occur at this stage. ```groovy def user = new User(params) ``` -------------------------------- ### Get Information About a Grails Profile Source: https://grails.apache.org/docs/7.0.4/guide/profiles.html Run this command outside of a Grails project directory to get details about a specific profile and its commands/features. ```bash grails profile-info profile ``` -------------------------------- ### External Configuration with Wildcards (Groovy) Source: https://grails.apache.org/docs/7.0.4/guide/conf.html Demonstrates using wildcards in file paths for external configuration in Groovy format. This allows matching multiple files that follow a pattern. ```groovy grails.config.locations = [ "file:/etc/app/myconfig*.groovy", "~/.grails/myconfig*.groovy", ] ``` -------------------------------- ### Run Packaged WAR/JAR File Source: https://grails.apache.org/docs/7.0.4/guide/deployment.html Execute the created WAR or JAR file using your Java installation. Specify the environment using the `grails.env` system property. ```bash java -Dgrails.env=prod -jar build/libs/mywar-0.1.war (or .jar) ``` -------------------------------- ### Implement Show Action with Respond Source: https://grails.apache.org/docs/7.0.4/guide/REST.html A concise implementation of the 'show' action that uses Grails' automatic domain instance lookup and the `respond` method. ```Groovy def show(Book book) { respond book } ``` -------------------------------- ### JSON Response Example Source: https://grails.apache.org/docs/7.0.4/guide/theWebLayer.html Example of a JSON response generated by the respond method for a list of books. The structure includes 'id' and 'title' for each book. ```json [ {id:1,"title":"The Stand"}, {id:2,"title":"Shining"} ] ``` -------------------------------- ### Grails Factories File Example Source: https://grails.apache.org/docs/7.0.4/guide/plugins.html Example of a `META-INF/grails.factories` descriptor file that lists trait injectors. This file is automatically generated but can be manually defined. ```properties #Grails Factories File grails.compiler.traits.TraitInjector= myplugin.ControllerTraitInjector,myplugin.DateTraitTraitInjector ``` -------------------------------- ### RxGORM Basic Get Operation Source: https://grails.apache.org/docs/7.0.4/guide/async.html Perform a non-blocking 'get' operation on a Book using RxGORM. The result is returned as an rx.Observable, allowing for reactive subscription. ```groovy Book.get(id) .subscribe { Book it -> println "Title = ${it.title}" } ``` -------------------------------- ### Packaging Grails Application as WAR (Gradle) Source: https://grails.apache.org/docs/7.0.4/guide/conf.html Package the Grails application into a runnable WAR file using the './gradlew bootWar' command. This is an alternative to using the Grails CLI for packaging. ```bash $ ./gradlew bootWar $ java -jar build/libs/myapp-0.1.war ``` -------------------------------- ### Get REST API Plugin Profile Information Source: https://grails.apache.org/docs/7.0.4/guide/profiles.html Run this command outside of a Grails project directory to get details about the 'rest-api-plugin' profile and its capabilities. ```bash grails profile-info rest-api-plugin ``` -------------------------------- ### Run Grails Command with Options Source: https://grails.apache.org/docs/7.0.4/guide/commandLine.html Execute the 'greet' command with an additional option, such as '--loud'. This demonstrates how to pass flags or modifiers to commands. ```bash ./gradlew runCommand -Pargs="greet --loud" ``` -------------------------------- ### Install Form Fields Templates Source: https://grails.apache.org/docs/7.0.4/guide/theWebLayer.html Installs scaffolding templates from the Fields plugin into your application. This command overwrites existing create.gsp and edit.gsp files in src/templates/scaffolding. ```bash grails install-form-fields-templates ``` -------------------------------- ### Equivalent Command for Creating Application with Profile Source: https://grails.apache.org/docs/7.0.4/guide/profiles.html This command is functionally equivalent to `grails create-profile myprofile`, specifying the profile via an argument. ```bash grails create-app myprofile --profile=profile ``` -------------------------------- ### External Configuration with Wildcards (YML) Source: https://grails.apache.org/docs/7.0.4/guide/conf.html Demonstrates using wildcards in file paths for external configuration in YML format. This allows matching multiple files that follow a pattern. ```yaml grails: config: locations: - file:/etc/app/myconfig*.groovy - ~/.grails/myconfig*.groovy ``` -------------------------------- ### Basic JSON View Example Source: https://grails.apache.org/docs/7.0.4/guide/REST.html Create a .gson file in grails-app/views to define a JSON structure. This example creates a simple JSON object with a 'name' property. ```groovy json.person { name "bob" } ``` -------------------------------- ### Invalid DataSource Configuration Example Source: https://grails.apache.org/docs/7.0.4/guide/conf.html This example demonstrates an invalid configuration where type declarations are used, causing Groovy to treat them as local variables that are ignored by Grails. ```groovy dataSource { boolean pooled = true // type declaration results in ignored local variable ... } ``` -------------------------------- ### Get Grails Version using GrailsUtil Source: https://grails.apache.org/docs/7.0.4/guide/conf.html Retrieve the running Grails version at runtime using the static GrailsUtil class. This is an alternative method to get the framework version. ```groovy import grails.util.GrailsUtil ... def grailsVersion = GrailsUtil.grailsVersion ``` -------------------------------- ### Sample Tag Library Definition Source: https://grails.apache.org/docs/7.0.4/guide/testing.html Defines a simple tag library with a 'helloWorld' tag. ```groovy package demo class SampleTagLib { static defaultEncodeAs = [taglib:'html'] static namespace = 'demo' def helloWorld = { attrs -> out << 'Hello, World!' } } ``` -------------------------------- ### Single Promise API with Blocking and Timeout Source: https://grails.apache.org/docs/7.0.4/guide/async.html The `grails.async.Promise` interface provides methods like `onError`, `onComplete`, `get`, and `get` with a timeout for managing individual long-running promises. ```groovy import static java.util.concurrent.TimeUnit.* import static grails.async.Promises.* Promise p = task { // Long running task } p.onError { Throwable err -> println "An error occured ${err.message}" } p.onComplete { result -> println "Promise returned $result" } // block until result is called def result = p.get() // block for the specified time def result = p.get(1,MINUTES) ``` -------------------------------- ### Run All Tests (Gradle) Source: https://grails.apache.org/docs/7.0.4/guide/testing.html Execute all unit tests located in the standard `src/main/groovy/com/example/` directory using the Gradle check task. ```bash ./gradlew check ``` -------------------------------- ### Create Grails App with Plugin Profile Source: https://grails.apache.org/docs/7.0.4/guide/profiles.html This command is equivalent to creating a plugin directly, specifying the 'plugin' profile for the application. ```bash grails create-app myplugin --profile=plugin ``` -------------------------------- ### Configure Multi-Project Build with settings.gradle Source: https://grails.apache.org/docs/7.0.4/guide/plugins.html Create a settings.gradle file in the project root to include both the application and the plugin for a multi-project build. ```gradle include "myapp", "myplugin" ``` -------------------------------- ### Grails JSON View Example Source: https://grails.apache.org/docs/7.0.4/guide/theWebLayer.html Example of a Grails JSON view using the .gson format to render a list of books. It demonstrates how to access the 'bookList' model variable and iterate over it. ```groovy @Field List bookList = [] json bookList, { Book book -> title book.title } ``` -------------------------------- ### Using Asynchronous Service Source: https://grails.apache.org/docs/7.0.4/guide/async.html Shows how to inject and use the asynchronous service, handling the Promise completion. ```groovy AsyncBookService asyncBookService def findBooks(String title) { asyncBookService.findBooks(title) .onComplete { List results -> println "Books = ${results}" } } ``` -------------------------------- ### Grails Forge CLI Configuration Example Source: https://grails.apache.org/docs/7.0.4/guide/commandLine.html An example 'grails-forge-cli.yml' file showing default settings for a Grails web application, including application type, package, test framework, and features. ```yaml applicationType: web defaultPackage: com.example testFramework: spock sourceLanguage: groovy buildTool: gradle gormImpl: gorm-hibernate5 servletImpl: spring-boot-starter-tomcat features: - app-name - asset-pipeline-grails - base - geb - gorm-hibernate5 - gradle - grails-application - grails-console - grails-dependencies - grails-gorm-testing-support - grails-gradle-plugin - grails-gsp - grails-url-mappings - grails-web - grails-web-testing-support - h2 - logback - readme - scaffolding - spock - spring-boot-autoconfigure - spring-boot-starter - spring-boot-starter-tomcat - yaml ``` -------------------------------- ### Show Action Equivalent with Manual Handling Source: https://grails.apache.org/docs/7.0.4/guide/REST.html This is a functionally equivalent 'show' action that manually checks for null and renders a 404 status if the domain instance is not found. ```Groovy def show(Book book) { if(book == null) { render status:404 } else { return [book: book] } } ``` -------------------------------- ### Atom Feed Example Source: https://grails.apache.org/docs/7.0.4/guide/REST.html An example of the XML structure for an Atom feed, a standard interchange format for REST APIs. This structure includes elements like title, link, updated, author, and entry. ```xml Example Feed 2003-12-13T18:30:02Z John Doe urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6 Atom-Powered Robots Run Amok urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a 2003-12-13T18:30:02Z Some text. ``` -------------------------------- ### Configure Plugin Environments (List) Source: https://grails.apache.org/docs/7.0.4/guide/plugins.html Specify a list of environments in which the plugin should load. The plugin will only be active in these specified environments. ```groovy def environments = ['development', 'test', 'myCustomEnv'] ``` -------------------------------- ### Generate Domain Class and REST Endpoints with Gradle Source: https://grails.apache.org/docs/7.0.4/guide/REST.html Create a domain class and generate corresponding REST endpoints using Gradle and a custom runCommand task. ```bash $ grails create-domain-class my.api.Book $ ./gradlew runCommand -Pargs="generate-all my.api.Book" ``` -------------------------------- ### Navigate to Project Directory Source: https://grails.apache.org/docs/7.0.4/guide/gettingStarted.html Command to change the current directory to the newly created Grails project. ```bash $ cd myapp ``` -------------------------------- ### Create Application with Web Plugin Profile Source: https://grails.apache.org/docs/7.0.4/guide/profiles.html This command is equivalent to `grails create-web-plugin`, allowing you to create an application with the `web-plugin` profile explicitly specified. ```bash grails create-app myplugin --profile=web-plugin ``` -------------------------------- ### Get Information on a Specific Profile Source: https://grails.apache.org/docs/7.0.4/guide/profiles.html Retrieves detailed information about a specific application profile, such as 'rest-api'. ```bash grails profile-info rest-api ``` -------------------------------- ### Run Grails App with Gradle Wrapper (Standalone) Source: https://grails.apache.org/docs/7.0.4/guide/deployment.html Execute the `bootRun` Gradle task using the Gradle Wrapper to start your application. You can specify the environment using a system property. ```bash ./gradlew bootRun ``` ```bash ./gradlew -Dgrails.env=prod bootRun ``` -------------------------------- ### Creating Image Instance with Data Binding Source: https://grails.apache.org/docs/7.0.4/guide/theWebLayer.html Demonstrates creating a new Image instance by binding parameters directly from the request. ```groovy def img = new Image(params) ``` -------------------------------- ### Grails 3 build.gradle dependencies Source: https://grails.apache.org/docs/7.0.4/guide/upgrading.html Example of Geb 1.1.x dependencies in Grails 3's build.gradle. ```gradle dependencies { testCompile "org.grails.plugins:geb:1.1.2" testRuntime "org.seleniumhq.selenium:selenium-htmlunit-driver:2.47.1" testRuntime "net.sourceforge.htmlunit:htmlunit:2.18" } ``` -------------------------------- ### Create a Basic Grails Plugin Source: https://grails.apache.org/docs/7.0.4/guide/plugins.html Use this command in the Grails Shell CLI to generate a standard plugin project. ```bash grails create-plugin <> ``` -------------------------------- ### Generated Asynchronous Method Source: https://grails.apache.org/docs/7.0.4/guide/async.html An example of the asynchronous method automatically generated by the DelegateAsync transformation, returning a Promise. ```groovy Promise> findBooks(String title) { Promises.task { bookService.findBooks(title) } } ``` -------------------------------- ### GSP Loop Example Source: https://grails.apache.org/docs/7.0.4/guide/theWebLayer.html Embed loops using Groovy syntax within `<% %>` scriptlets to iterate over collections in GSP. ```gsp <% [1,2,3,4].each { num -> %>

<%="Hello ${num}!" %>

<%}%> ``` -------------------------------- ### Create Grails Application and Plugin Source: https://grails.apache.org/docs/7.0.4/guide/plugins.html Use the grails command-line tool to create a new Grails application and a new plugin. ```bash $ grails create-app myapp $ grails create-plugin myplugin ``` -------------------------------- ### Customized HAL Response Source: https://grails.apache.org/docs/7.0.4/guide/REST.html Example of a HAL response where the embedded collection is named 'publications' instead of the default 'book'. ```json { "_links": { "self": { "href": "http://localhost:8080/books", "hreflang": "en", "type": "application/hal+json" } }, "_embedded": { "publications": [ { "_links": { "self": { "href": "http://localhost:8080/books/1", "hreflang": "en", "type": "application/hal+json" } }, "title": "The Stand" }, { "_links": { "self": { "href": "http://localhost:8080/books/2", "hreflang": "en", "type": "application/hal+json" } }, "title": "Infinite Jest" }, { "_links": { "self": { "href": "http://localhost:8080/books/3", "hreflang": "en", "type": "application/hal+json" } }, "title": "Walden" } ] } } ``` -------------------------------- ### Profile YAML: Include Buildscript Maven Repositories Source: https://grails.apache.org/docs/7.0.4/guide/profiles.html Example of how to specify a list of Maven repositories for the buildscript section of the generated build within the `profile.yml` file. ```yaml build: repositories: - "https://repo1.maven.org/maven2" ``` -------------------------------- ### Configure Servlet Implementation Source: https://grails.apache.org/docs/7.0.4/guide/commandLine.html Selects the servlet implementation for a Grails project, with options like tomcat, jetty, or undertow. ```bash --servlet=tomcat ``` -------------------------------- ### Basic GSP Tag Usage Source: https://grails.apache.org/docs/7.0.4/guide/theWebLayer.html GSP tags start with the `g:` prefix and are automatically recognized. They can be self-closing or have a body. ```GSP ``` ```GSP Hello world ``` -------------------------------- ### Run Unit and Integration Tests Separately (Gradle) Source: https://grails.apache.org/docs/7.0.4/guide/testing.html Execute unit tests using the `test` task and integration tests using the `integrationTest` task. ```bash ./gradlew test ``` ```bash ./gradlew integrationTest ``` -------------------------------- ### Run Grails Application Source: https://grails.apache.org/docs/7.0.4/guide/gettingStarted.html Starts the Grails application using the built-in Tomcat server on the default port 8080. ```bash grails run-app ``` -------------------------------- ### YAML Configuration with System Properties Source: https://grails.apache.org/docs/7.0.4/guide/conf.html Reference system properties or command-line arguments within YAML configuration files. ```yaml production: dataSource: url: '${JDBC_CONNECTION_STRING}' ``` -------------------------------- ### Start Grails Forge CLI Interactive Console Source: https://grails.apache.org/docs/7.0.4/guide/gettingStarted.html Command to launch the interactive console of the Grails Forge CLI. ```bash $ grails -t forge ``` -------------------------------- ### Configure Plugin Environments (Single String) Source: https://grails.apache.org/docs/7.0.4/guide/plugins.html Specify a single environment for the plugin to load in. This is a shorthand for a list containing one environment. ```groovy def environments = "test" ``` -------------------------------- ### Get Application Version Source: https://grails.apache.org/docs/7.0.4/guide/conf.html Retrieve the application version at runtime using the GrailsApplication class. This is typically used within controllers. ```groovy def version = grailsApplication.metadata.getApplicationVersion() ``` -------------------------------- ### Read Person by ID Source: https://grails.apache.org/docs/7.0.4/guide/GORM.html Retrieves a Person instance from the database using its unique ID. The `get()` method is used for this purpose. ```groovy def p = Person.get(1) assert 1 == p.id ``` -------------------------------- ### Implement Index Action with Respond Source: https://grails.apache.org/docs/7.0.4/guide/REST.html Use the `respond` method to return a list of objects. The `model` argument is optional and used for pagination. ```Groovy def index(Integer max) { params.max = Math.min(max ?: 10, 100) respond Book.list(params), model:[bookCount: Book.count()] } ``` -------------------------------- ### JSON Accept Header for Non-Browser Clients Source: https://grails.apache.org/docs/7.0.4/guide/theWebLayer.html An example of a specific Accept header sent by non-browser clients requesting JSON. ```text application/json ``` -------------------------------- ### Use Date Formatting Tag in GSP Source: https://grails.apache.org/docs/7.0.4/guide/theWebLayer.html Example of using the custom 'dateFormat' tag within a GSP to format a date. ```GSP ``` -------------------------------- ### Run Grails Command with Specific Argument Source: https://grails.apache.org/docs/7.0.4/guide/commandLine.html Execute the 'greet' command, providing a specific argument like a user's name. This allows for personalized command execution. ```bash ./gradlew runCommand -Pargs="greet Alice" ``` -------------------------------- ### GSP Conditional Logic Example Source: https://grails.apache.org/docs/7.0.4/guide/theWebLayer.html Implement logical branching using Groovy `if/else` syntax within `<% %>` scriptlets in GSP. ```gsp <% if (params.hello == 'true')%> <%="Hello!"%> <% else %> <%="Goodbye!"%> ``` -------------------------------- ### JSON for Nested Command Objects Source: https://grails.apache.org/docs/7.0.4/guide/theWebLayer.html Example of a JSON structure that can be submitted to bind correctly with nested command objects and lists. ```JSON { "fullName": "Graeme Rocher", "books": [{ "title": "The Definitive Guide to Grails", "isbn": "1111-343455-1111" }, { "title": "The Definitive Guide to Grails 2", "isbn": "1111-343455-1112" }], } ``` -------------------------------- ### Declare Spring Namespace Source: https://grails.apache.org/docs/7.0.4/guide/spring.html Declare a Spring namespace in BeanBuilder to use its features. This example shows how to declare the 'context' namespace. ```groovy xmlns context:"https://www.springframework.org/schema/context" ``` -------------------------------- ### Grails Shell CLI vs. Gradle Tasks Source: https://grails.apache.org/docs/7.0.4/guide/gettingStarted.html Illustrates the mapping between common Grails shell CLI commands and their corresponding Gradle tasks, showing how Grails scripts and plugins interact with Gradle. ```bash ./grails run-app ``` ```bash ./gradlew bootRun ``` ```bash ./grails test run-app ``` ```bash ./gradlew bootRun -Dgrails.env=test ``` ```bash ./grails package ``` ```bash ./gradlew assemble -Dgrails.env=prod ``` ```bash ./grails generate-all org.bookstore.Author ``` ```bash ./gradlew runCommand -Pargs="generate-all org.bookstore.Author" ``` ```bash ./grails dbm-update ``` ```bash ./gradlew dbmUpdate ``` ```bash ./grails dbm-generate-changelog person-domain.groovy ``` ```bash ./gradlew dbmGenerateChangelog -Pargs="person-domain.groovy" ``` ```bash ./grails s2-quickstart com.yourapp User Role ``` ```bash ./gradlew runCommand -Pargs="s2-quickstart com.yourapp User Role" ``` -------------------------------- ### Grails Plugin Descriptor Class Example Source: https://grails.apache.org/docs/7.0.4/guide/plugins.html This is a basic structure for a Grails plugin descriptor class, which must end in 'GrailsPlugin'. ```groovy import grails.plugins.* class ExampleGrailsPlugin extends Plugin { ... } ``` -------------------------------- ### Combine Test and Phase Targeting (Gradle) Source: https://grails.apache.org/docs/7.0.4/guide/testing.html Combine specific test targeting with phase selection for granular test execution. ```bash ./gradlew test some.org.**.* ``` -------------------------------- ### Run Grails Application in Interactive Mode Source: https://grails.apache.org/docs/7.0.4/guide/gettingStarted.html Starts the Grails application in interactive mode, allowing for quick restarts and other commands. ```bash grails grails> run-app | Grails application running at http://localhost:8080 in environment: development grails> stop-app | Shutting down application... | Application shutdown. grails> run-app | Grails application running at http://localhost:8080 in environment: development ``` -------------------------------- ### List Available Gradle Tasks Source: https://grails.apache.org/docs/7.0.4/guide/commandLine.html This command displays all the tasks that can be executed by Gradle within your project. ```bash gradle tasks ```