### Enum Mapping Setup Source: https://grails.apache.org/docs/3.3.18/ref/Database%20Mapping/column.html Example domain setup and enum definition for testing different enum mapping strategies. ```groovy package demo import groovy.transform.CompileStatic @CompileStatic class BootStrap { def init = { servletContext -> Book.saveAll( new Book(name: 'Grails 3 - Step by Step', status: Status.NOT_SET), new Book(name: 'Grails 3 - A practical guide to application development', status: Status.BORROWED), new Book(name: 'Falando de Grails', status: Status.SOLD), ) } def destroy = { } } ``` ```groovy package demo import groovy.transform.CompileStatic @CompileStatic enum Status { NOT_SET(-1), BORROWED(0), SOLD(1), final int id private Status(int id) { this.id = id } } ``` -------------------------------- ### Create Controller Command Examples Source: https://grails.apache.org/docs/3.3.18/ref/Command%20Line/create-controller.html Basic usage examples for generating controllers with or without specified names and packages. ```bash grails create-controller grails create-controller Book grails create-controller org.bookstore.book ``` -------------------------------- ### create-unit-test command examples Source: https://grails.apache.org/docs/3.3.18/ref/Command%20Line/create-unit-test.html Basic usage examples for generating unit tests with or without package specifications. ```bash grails create-unit-test grails create-unit-test book grails create-unit-test org.bookstore.Book ``` -------------------------------- ### create-domain-class command usage examples Source: https://grails.apache.org/docs/3.3.18/ref/Command%20Line/create-domain-class.html Examples of invoking the command with different naming conventions and package structures. ```bash grails create-domain-class grails create-domain-class Book grails create-domain-class org.bookstore.Book ``` -------------------------------- ### Handle Setup Persistence in Integration Tests Source: https://grails.apache.org/docs/3.3.18/guide/testing.html Demonstrates how data persisted in setup() is not rolled back, requiring manual cleanup or alternative strategies. ```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 } } ``` -------------------------------- ### Create Interceptor Command Examples Source: https://grails.apache.org/docs/3.3.18/ref/Command%20Line/create-interceptor.html Basic usage examples for generating interceptors with or without specified names and packages. ```bash grails create-interceptor grails create-interceptor Book grails create-interceptor org.bookstore.book ``` -------------------------------- ### Install and Create Applications with Profiles Source: https://grails.apache.org/docs/3.3.18/guide/single.html Commands for installing a profile locally and creating new applications using specific profile identifiers. ```bash $ gradle install ``` ```bash $ grails create-app myapp --profile mycompany ``` ```bash $ grails create-app myapp --profile com.mycompany:mycompany:1.0.1 ``` -------------------------------- ### Create Integration Test Examples Source: https://grails.apache.org/docs/3.3.18/ref/Command%20Line/create-integration-test.html Basic usage examples for generating integration tests with or without specific class names and packages. ```bash grails create-integration-test grails create-integration-test book grails create-integration-test org.bookstore.Book ``` -------------------------------- ### Build Grails Installation Source: https://grails.apache.org/docs/3.3.18/guide/contributing.html Create a local GRAILS_HOME installation from the project root. ```bash ./gradlew install ``` -------------------------------- ### List available plugins Source: https://grails.apache.org/docs/3.3.18/ref/Command%20Line/list-plugins.html Basic command to list all installable plugins. ```bash grails list-plugins ``` -------------------------------- ### Example feature.yml configuration Source: https://grails.apache.org/docs/3.3.18/guide/profiles.html A concrete example of a feature configuration defining build plugins and dependencies. ```yaml description: Adds Asset Pipeline to a Grails project build: plugins: - asset-pipeline dependencies: build: - 'com.bertramlabs.plugins:asset-pipeline-gradle:2.5.0' runtime: - "org.grails.plugins:asset-pipeline" ``` -------------------------------- ### Create functional test command examples Source: https://grails.apache.org/docs/3.3.18/ref/Command%20Line/create-functional-test.html Basic usage examples for generating functional tests with or without specific names and packages. ```bash grails create-functional-test grails create-functional-test book grails create-functional-test org.bookstore.Book ``` -------------------------------- ### Auto-wire a Bean into a Controller (Partial) Source: https://grails.apache.org/docs/3.3.18/guide/spring.html Example showing the start of a controller class for auto-wiring beans defined in XML. ```groovy class ExampleController { ``` -------------------------------- ### Install and Use a Local Plugin Source: https://grails.apache.org/docs/3.3.18/guide/plugins.html Commands to install a plugin to the local Maven cache and declare it as a dependency in build.gradle. ```bash grails install ``` ```groovy compile "org.grails.plugins:quartz:0.1" ``` -------------------------------- ### Quartz Plugin Metadata Example Source: https://grails.apache.org/docs/3.3.18/guide/plugins.html A comprehensive example of a plugin descriptor class defining metadata and configuration properties. ```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 = "http://grails.org/plugin/quartz" def license = "APACHE" def issueManagement = [ system: "Github Issues", url: "http://github.com/grails3-plugins/quartz/issues" ] def developers = [ [ name: "Joe Dev", email: "joedev@gmail.com" ] ] def scm = [ url: "https://github.com/grails3-plugins/quartz/" ] Closure doWithSpring()...... ``` -------------------------------- ### publishGuide() Source: https://grails.apache.org/docs/3.3.18/api/grails/doc/gradle/PublishGuide.html Executes the generation of the gdoc-based HTML user guide. ```APIDOC ## publishGuide() ### Description Executes the task to generate a gdoc-based HTML user guide based on the configured properties. ### Return Type java.lang.Object ``` -------------------------------- ### Verify Grails installation Source: https://grails.apache.org/docs/3.3.18/guide/gettingStarted.html Check the installed Grails version to confirm successful setup. ```text Grails version: 3.3.18 ``` -------------------------------- ### Setup Multi-Project Build Source: https://grails.apache.org/docs/3.3.18/guide/plugins.html Commands and configuration files for setting up an application and plugin in a multi-project build environment. ```bash $ grails create-app myapp $ grails create-plugin myplugin ``` ```groovy include "myapp", "myplugin" ``` -------------------------------- ### Example output of list-plugins Source: https://grails.apache.org/docs/3.3.18/ref/Command%20Line/list-plugins.html Typical output format when running the list-plugins command. ```text | Available Plugins * asset-pipeline * cache * cache-ehcache * fields * geb * hibernate * mongodb * quartz * scaffolding ``` -------------------------------- ### Setup Inline Plugins Source: https://grails.apache.org/docs/3.3.18/guide/plugins.html Commands and configuration to set up a multi-project build for inline plugin development. ```bash $ grails create-app myapp $ grails create-plugin myplugin ``` ```groovy include 'myapp', 'myplugin' ``` ```groovy compile project(':myplugin') ``` -------------------------------- ### GORM find Method Usage Examples Source: https://grails.apache.org/docs/3.3.18/ref/Domain%20Classes/find.html Demonstrates various ways to use the find method including HQL with parameters, query caching, query by example, and where criteria. ```groovy // Dan brown's first book Book.find("from Book as b where b.author='Dan Brown'") // with a positional parameter Book.find("from Book as b where b.author=?", ['Dan Brown']) // with a named parameter Book.find("from Book as b where b.author=:author", [author: 'Dan Brown']) // use the query cache Book.find("from Book as b where b.author='Dan Brown'", [cache: true]) Book.find("from Book as b where b.author=:author", [author: 'Dan Brown'], [cache: true]) // query by example def example = new Book(author: "Dan Brown") Book.find(example) // Using where criteria (since Grails 2.0) Person p = Person.find { firstName == "Bart" } ``` -------------------------------- ### Example Request URL Source: https://grails.apache.org/docs/3.3.18/guide/theWebLayer.html A sample URL demonstrating how request parameters are passed to the save action. ```text /book/save?title=The%20Stand&author=Stephen%20King ``` -------------------------------- ### Run a Grails application Source: https://grails.apache.org/docs/3.3.18/guide/commandLine.html Standard command to start a Grails application. ```bash grails run-app ``` -------------------------------- ### Basic script implementation Source: https://grails.apache.org/docs/3.3.18/guide/commandLine.html A simple script example that defines a description and prints output to the console. ```groovy description "Example description", "grails hello-world" println "Hello World" ``` -------------------------------- ### findAll Pagination and Caching Source: https://grails.apache.org/docs/3.3.18/ref/Domain%20Classes/findAll.html Examples showing how to apply pagination and 2nd level cache settings to HQL queries. ```Groovy Book.findAll("from Book as b where b.author=:author", [author: 'Dan Brown'], [max: 10, offset: 5]) ``` ```Groovy Book.findAll("from Book as b where b.author=:author", [author:'Dan Brown'], [max: 10, offset: 5, cache: true]) ``` -------------------------------- ### waitForStartup Source: https://grails.apache.org/docs/3.3.18/api/org/grails/cli/profile/commands/io/ServerInteraction.html Blocks execution until the server at the specified host and port has started. ```APIDOC ## void waitForStartup(String host, int port) ### Description Waits for the server to startup at the specified host and port. ### Parameters - **host** (String) - Optional (default: "localhost") - The host address. - **port** (int) - Optional (default: 8080) - The port number. ``` -------------------------------- ### Example profile.yml configuration Source: https://grails.apache.org/docs/3.3.18/guide/profiles.html Defines default features, build plugins, and dependencies for the custom profile. ```yaml features: defaults: - hibernate - asset-pipeline build: plugins: - org.grails.grails-web excludes: - org.grails.grails-core dependencies: compile: - "org.mycompany:myplugin:1.0.1" ``` -------------------------------- ### Print Hello World in a Grails script Source: https://grails.apache.org/docs/3.3.18/guide/single.html A basic example of printing output from a Grails script. ```Groovy println "Hello World" ``` -------------------------------- ### publish() Source: https://grails.apache.org/docs/3.3.18/api/grails/doc/gradle/PublishPdf.html Executes the PDF generation process for the user guide. ```APIDOC ## publish() ### Description Executes the task to generate a PDF user guide based on gdoc files. This method assumes that the single-page HTML user guide has already been created in the default location. ### Return Type java.lang.Object ``` -------------------------------- ### Define Hello World controller action Source: https://grails.apache.org/docs/3.3.18/guide/gettingStarted.html Example implementation of a controller action that renders a string to the browser. ```groovy package helloworld class HelloController { def index() { render "Hello World!" } } ``` -------------------------------- ### UrlValidator Usage Examples Source: https://grails.apache.org/docs/3.3.18/api/org/grails/validation/routines/UrlValidator.html Demonstrates how to instantiate and use UrlValidator with specific schemes versus default settings. ```java String[] schemes = {"http","https"}. UrlValidator urlValidator = new UrlValidator(schemes); if (urlValidator.isValid("ftp://foo.bar.com/")) { System.out.println("url is valid"); } else { System.out.println("url is invalid"); } ``` ```java UrlValidator urlValidator = new UrlValidator(); if (urlValidator.isValid("ftp://foo.bar.com/")) { System.out.println("url is valid"); } else { System.out.println("url is invalid"); } ``` -------------------------------- ### Display Profile Information Source: https://grails.apache.org/docs/3.3.18/ref/Command%20Line/profile-info.html Examples of using the profile-info command with different identifier formats. ```bash grails profile-info rest-api grails profile-info org.grails.profiles:rest-api grails profile-info org.grails.profiles:rest-api:3.1.0 ``` -------------------------------- ### Example JSON Output Source: https://grails.apache.org/docs/3.3.18/guide/REST.html The resulting JSON output from rendering a domain instance. ```json {id:1, title:"The Stand"} ``` -------------------------------- ### findAll HQL and Query by Example usage Source: https://grails.apache.org/docs/3.3.18/ref/Domain%20Classes/findAll.html Demonstrates basic HQL queries, positional and named parameters, pagination, joins, and query-by-example. ```Groovy // everything Book.findAll() // with a positional parameter Book.findAll("from Book as b where b.author=?", ['Dan Brown']) // 10 books from Dan Brown staring from 5th book ordered by release date Book.findAll("from Book as b where b.author=? order by b.releaseDate", ['Dan Brown'], [max: 10, offset: 5]) // examples with max/offset usage def query = "from Book as b where b.author='Dan Brown' order by b.releaseDate" // first 10 books Book.findAll(query, [max: 10]) // 10 books starting from 5th Book.findAll(query, [max: 10, offset: 5]) // examples with named parameters Book.findAll("from Book as b where b.author=:author", [author: 'Dan Brown']) Book.findAll("from Book as b where b.author=:author", [author: 'Dan Brown'], [max: 10, offset: 5]) Book.findAll("from Book as b where b.author in (:authors)", [authors: ['Dan Brown', 'Jack London']]) // examples with tables join Book.findAll("from Book as b where not exists " + "(from Borrow as br where br.book = b)") // query by example def example = new Book(author: "Dan Brown") Book.findAll(example) // Use where criteria (since Grails 2.0) def results = Person.findAll { lastName == "Simpson" } def results = Person.findAll(sort:"firstName") { lastName == "Simpson" } ``` -------------------------------- ### Example JSON output Source: https://grails.apache.org/docs/3.3.18/guide/theWebLayer.html The resulting JSON structure from the render method example. ```json [ {"title":"The Stand"}, {"title":"Shining"} ] ``` -------------------------------- ### Gradle Build Output Source: https://grails.apache.org/docs/3.3.18/guide/plugins.html Example output showing plugin sources being compiled and added to the application classpath. ```text :myplugin:compileAstJava UP-TO-DATE :myplugin:compileAstGroovy UP-TO-DATE :myplugin:processAstResources UP-TO-DATE :myplugin:astClasses UP-TO-DATE :myplugin:compileJava UP-TO-DATE :myplugin:configScript UP-TO-DATE :myplugin:compileGroovy :myplugin:copyAssets UP-TO-DATE :myplugin:copyCommands UP-TO-DATE :myplugin:copyTemplates UP-TO-DATE :myplugin:processResources :myapp:compileJava UP-TO-DATE :myapp:compileGroovy :myapp:processResources UP-TO-DATE :myapp:classes :myapp:findMainClass :myapp:bootRun Grails application running at http://localhost:8080 in environment: development ``` -------------------------------- ### Configure Multiple DataSources Source: https://grails.apache.org/docs/3.3.18/guide/services.html Example configuration for defining primary and secondary data sources. ```YAML dataSources: dataSource: pooled: true jmxExport: true ..... secondary: pooled: true jmxExport: true ..... ``` -------------------------------- ### Vnd.Error Response Example Source: https://grails.apache.org/docs/3.3.18/guide/REST.html Example response when the client requests application/vnd.error+json format. ```bash $ curl -i -H "Accept: application/vnd.error+json,application/json" -H "Content-Type: application/json" -X POST -d "" http://localhost:8080/books HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Content-Type: application/vnd.error+json;charset=ISO-8859-1 [ { "logref": "book.nullable, "message": "Property [title] of class [class rest.test.Book] cannot be null", "_links": { "resource": { "href": "http://localhost:8080/rest-test/books" } } } ] ``` -------------------------------- ### Example script content Source: https://grails.apache.org/docs/3.3.18/ref/Command%20Line/create-script.html The generated script file structure using the GroovyScriptCommand API. ```groovy description "Example description", "grails example-usage" println "Example Script" ``` -------------------------------- ### Build with Gradle directly Source: https://grails.apache.org/docs/3.3.18/guide/commandLine.html Invoke a local installation of Gradle to perform build tasks. ```bash $ gradle assemble ``` -------------------------------- ### XML Request Body Example Source: https://grails.apache.org/docs/3.3.18/guide/REST.html Example XML structure used as a request body for binding to a Book object. ```xml The Stand Stephen King ``` -------------------------------- ### Retrieve First Instance with first() Source: https://grails.apache.org/docs/3.3.18/ref/Domain%20Classes/first.html Examples of using the first() method with and without sorting parameters. ```groovy // retrieve the first person ordered by the identifier def p = Person.first() // retrieve the first person ordered by the lastName property p = Person.first(sort: 'lastName') // retrieve the first person ordered by the lastName property p = Person.first('lastName') ``` -------------------------------- ### Launch Grails Console with Environment Source: https://grails.apache.org/docs/3.3.18/ref/Command%20Line/console.html Starts the console within a specific Grails environment. ```bash grails <>* console ``` -------------------------------- ### Create Tag Library Examples Source: https://grails.apache.org/docs/3.3.18/ref/Command%20Line/create-taglib.html Demonstrates various ways to invoke the create-taglib command, including interactive mode and specifying names with or without packages. ```bash grails create-taglib grails create-taglib book grails create-taglib org.bookstore.Book ``` -------------------------------- ### Start Grails interactive console Source: https://grails.apache.org/docs/3.3.18/guide/gettingStarted.html Navigate to the project directory and launch the interactive Grails shell. ```bash $ cd helloworld $ grails ``` -------------------------------- ### Install Plugin to Local Maven Repository Source: https://grails.apache.org/docs/3.3.18/ref/Command%20Line/package-plugin.html Installs the packaged plugin into the local Maven repository for use in other projects. ```bash grails install ``` -------------------------------- ### Create a New Grails Application Source: https://grails.apache.org/docs/3.3.18/guide/single.html Initialize a new project directory named helloworld. ```text grails create-app helloworld ``` -------------------------------- ### Test Execution Output Example Source: https://grails.apache.org/docs/3.3.18/guide/testing.html Sample console output showing the results of a test run. ```text ------------------------------------------------------- Running Unit Tests... Running test FooTests...FAILURE Unit Tests Completed in 464ms ... ------------------------------------------------------- ``` -------------------------------- ### Package and Run Application Source: https://grails.apache.org/docs/3.3.18/guide/conf.html Package the application into a WAR file and execute it using java -jar. ```bash $ grails package $ java -jar build/libs/myapp-0.1.war ``` -------------------------------- ### Example HAL JSON document Source: https://grails.apache.org/docs/3.3.18/guide/REST.html A sample representation of an orders list using the HAL standard. ```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" }] } } ``` -------------------------------- ### Install Grails via SDKMAN Source: https://grails.apache.org/docs/3.3.18/guide/gettingStarted.html Commands to install the latest or a specific version of Grails using the SDKMAN tool. ```bash sdk install grails ``` ```bash sdk install grails {version} ``` -------------------------------- ### init(String) Source: https://grails.apache.org/docs/3.3.18/api/org/grails/test/support/GrailsTestRequestEnvironmentInterceptor.html Establishes a mock request environment. ```APIDOC ## Method: init(String controllerName) ### Description Establishes a mock request environment for the specified controller. ### Parameters - **controllerName** (java.lang.String) - Optional - The name of the controller to mock. Defaults to DEFAULT_CONTROLLER_NAME. ``` -------------------------------- ### Grails CLI Error Example Source: https://grails.apache.org/docs/3.3.18/guide/conf.html Example of an error message triggered when referencing application classes in application.groovy during CLI execution. ```text Error occurred running Grails CLI: startup failed:script14738267015581837265078.groovy: 13: unable to resolve class com.foo.Bar ``` -------------------------------- ### Create an application using a custom profile Source: https://grails.apache.org/docs/3.3.18/guide/profiles.html Uses the custom profile to bootstrap a new application. ```bash $ grails create-app myapp --profile mycompany ``` ```bash $ grails create-app myapp --profile com.mycompany:mycompany:1.0.1 ``` -------------------------------- ### Publish profile to local repository Source: https://grails.apache.org/docs/3.3.18/guide/profiles.html Installs the profile locally using Gradle to make it available for use. ```bash $ gradle install ``` -------------------------------- ### Usage syntax for create-profile Source: https://grails.apache.org/docs/3.3.18/ref/Command%20Line/create-profile.html The standard command syntax for creating a profile. ```bash grails create-profile <> ``` -------------------------------- ### Configure SSL via command-line Source: https://grails.apache.org/docs/3.3.18/guide/deployment.html Alternative method to enable SSL using system properties during application startup. ```bash -Dserver.ssl.enabled=true -Dserver.ssl.key-store=/path/to/keystore ``` -------------------------------- ### Accessing URL Mapping Constraints Source: https://grails.apache.org/docs/3.3.18/api/grails/web/mapping/UrlMapping.html Example of a URL pattern that results in multiple ConstrainedProperty instances. ```text /blog/$author/$title/$year?/$month?/$day? ``` -------------------------------- ### Run Application with Plugin Source: https://grails.apache.org/docs/3.3.18/guide/single.html Execute the application and observe the Gradle output to verify plugin sources are on the classpath. ```bash $ cd myapp $ grails run-app -verbose ``` ```text :myplugin:compileAstJava UP-TO-DATE :myplugin:compileAstGroovy UP-TO-DATE :myplugin:processAstResources UP-TO-DATE :myplugin:astClasses UP-TO-DATE :myplugin:compileJava UP-TO-DATE :myplugin:configScript UP-TO-DATE :myplugin:compileGroovy :myplugin:copyAssets UP-TO-DATE :myplugin:copyCommands UP-TO-DATE :myplugin:copyTemplates UP-TO-DATE :myplugin:processResources :myapp:compileJava UP-TO-DATE :myapp:compileGroovy :myapp:processResources UP-TO-DATE :myapp:classes :myapp:findMainClass :myapp:bootRun Grails application running at http://localhost:8080 in environment: development ``` -------------------------------- ### create-service command usage examples Source: https://grails.apache.org/docs/3.3.18/ref/Command%20Line/create-service.html Demonstrates various ways to invoke the create-service command, including interactive mode and specifying names with or without packages. ```bash grails create-service grails create-service book grails create-service org.bookstore.Book ``` -------------------------------- ### GET /books Source: https://grails.apache.org/docs/3.3.18/guide/single.html Retrieves a list of books. ```APIDOC ## GET /books ### Description Retrieves a list of all books. ### Method GET ### Endpoint /books ``` -------------------------------- ### nextValue() Source: https://grails.apache.org/docs/3.3.18/api/org/grails/web/json/JSONTokener.html Get the next value from the source. ```APIDOC ## public java.lang.Object nextValue() ### Description Get the next value. The value can be a Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. ### Returns - **Object** - The parsed value. ### Throws - **JSONException** - If syntax error. ``` -------------------------------- ### Usage Examples for generate-all Source: https://grails.apache.org/docs/3.3.18/ref/Command%20Line/generate-all.html Demonstrates various ways to invoke the generate-all command, including targeting specific classes or all domain classes. ```bash grails generate-all grails generate-all org.bookstore.Book grails generate-all "*" ``` -------------------------------- ### get() Source: https://grails.apache.org/docs/3.3.18/api/grails/util/Holder.html Retrieves the object held by the instance. ```APIDOC ## Method: get() ### Description Retrieves the object currently held by this instance. ### Returns - **T** - The held object. ``` -------------------------------- ### GET /books/{id} Source: https://grails.apache.org/docs/3.3.18/guide/single.html Retrieves a specific book by its ID. ```APIDOC ## GET /books/{id} ### Description Retrieves a specific book by its ID. ### Method GET ### Endpoint /books/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the book. ``` -------------------------------- ### main(String[] args) Source: https://grails.apache.org/docs/3.3.18/api/grails/ui/script/GrailsApplicationScriptRunner.html The main entry point to run an existing Application class. ```APIDOC ## static void main(java.lang.String[] args) ### Description Main method to run an existing Application class. ### Parameters - **args** (String[]) - Required - Command line arguments. ``` -------------------------------- ### Define a Domain Model Source: https://grails.apache.org/docs/3.3.18/guide/services.html Example of a domain class with a hasMany relationship. ```Groovy class Author { String name Integer age static hasMany = [books: Book] } ``` -------------------------------- ### getPluginVersion(Class clazz) Source: https://grails.apache.org/docs/3.3.18/api/grails/plugins/GrailsVersionUtils.html Get the version of the plugin for a particular class. ```APIDOC ## static String getPluginVersion(Class clazz) ### Description Get the version of the plugin for a particular class. ``` -------------------------------- ### Execute install-templates command Source: https://grails.apache.org/docs/3.3.18/ref/Command%20Line/install-templates.html Run this command to copy Grails generation templates to the project's src/main/templates/scaffolding directory. ```bash grails install-templates ``` -------------------------------- ### getPluginName(Class clazz) Source: https://grails.apache.org/docs/3.3.18/api/grails/plugins/GrailsVersionUtils.html Get the name of the plugin for a particular class. ```APIDOC ## static String getPluginName(Class clazz) ### Description Get the name of the plugin for a particular class. ``` -------------------------------- ### Generate Project Documentation Source: https://grails.apache.org/docs/3.3.18/ref/Command%20Line/docs.html Execute the documentation generation process using Gradle or the Grails CLI. ```bash gradle docs ``` ```bash grails doc ``` -------------------------------- ### Start Grails Application Source: https://grails.apache.org/docs/3.3.18/guide/gettingStarted.html Executes the embedded server on port 8080. ```shell grails> run-app ``` -------------------------------- ### static void main(java.lang.String[] args) Source: https://grails.apache.org/docs/3.3.18/api/grails/ui/script/GrailsApplicationScriptRunner.html The main entry point to run an existing Application class. The last argument is the Application class name, and all other arguments are script names. ```APIDOC ## static void main(java.lang.String[] args) ### Description Main method to run an existing Application class. ### Parameters - **args** (java.lang.String[]) - Required - The last argument is the Application class name. All other args are script names. ``` -------------------------------- ### withFormat without wildcard Source: https://grails.apache.org/docs/3.3.18/guide/theWebLayer.html Example of withFormat behavior when no wildcard block is provided. ```groovy withFormat { html bookList: books json { render books as JSON } xml { render books as XML } } ``` -------------------------------- ### publishGuide() Source: https://grails.apache.org/docs/3.3.18/api/grails/doc/gradle/PublishGuide.html The publishGuide method is the primary task action for generating and publishing documentation. ```APIDOC ## publishGuide() ### Description Executes the documentation publishing process for the project. ### Method TaskAction ### Parameters - **asciidoc** (boolean) - Optional - Configuration for AsciiDoc processing. - **language** (String) - Optional - Specifies the language for the documentation. - **macros** (Collection) - Required - Collection of macros to be used. - **properties** (Properties) - Optional - Configuration properties. - **propertiesFiles** (List) - Optional - List of property files. - **resourcesDir** (File) - Optional - Directory containing resources. - **sourceDir** (File) - Required - Directory containing source files. - **sourceRepo** (String) - Optional - Source repository URL. - **targetDir** (File) - Required - Output directory for published documentation. - **workDir** (File) - Required - Working directory for the task. ``` -------------------------------- ### Example JSON Output Source: https://grails.apache.org/docs/3.3.18/guide/theWebLayer.html Sample JSON representation produced by the respond method. ```JSON [ {id:1,"title":"The Stand"}, {id:2,"title":"Shining"} ] ``` -------------------------------- ### Define Domain Class Source: https://grails.apache.org/docs/3.3.18/ref/Domain%20Classes/findOrSaveBy.html Example domain class used for demonstrating findOrSaveBy. ```groovy class Book { String title String author } ``` -------------------------------- ### Retrieve domain instances using getAll Source: https://grails.apache.org/docs/3.3.18/ref/Domain%20Classes/getAll.html Demonstrates retrieving domain instances using variable arguments, a list of IDs, or fetching all instances. ```groovy // get a list which contains Book instances with ids 2, 1, 3 respectively def bookList = Book.getAll(2, 1, 3) // can take a list of ids as only argument, very // useful when the ids list is calculated in code def bookList = Book.getAll([1, 2, 3]) // when called without arguments returns list of all objects def bookList = Book.getAll() ``` -------------------------------- ### Create Grails application and plugin Source: https://grails.apache.org/docs/3.3.18/guide/single.html Initialize a new application and plugin in a parent directory to prepare for a multi-project build. ```bash $ grails create-app myapp $ grails create-plugin myplugin ``` -------------------------------- ### generate-views Command Examples Source: https://grails.apache.org/docs/3.3.18/ref/Command%20Line/generate-views.html Common usage patterns for generating views for specific domain classes or all classes using a wildcard. ```bash grails generate-views grails generate-views org.bookstore.Book grails generate-views "*" ``` -------------------------------- ### Example of a specific resource path Source: https://grails.apache.org/docs/3.3.18/api/org/grails/io/support/PathMatchingResourcePatternResolver.html A representation of a single XML resource path. ```text com/mycompany/package1/service-context.xml ``` -------------------------------- ### get(int index) Source: https://grails.apache.org/docs/3.3.18/api/org/grails/web/json/JSONArray.html Retrieves the object value associated with the specified index. ```APIDOC ## get(int index) ### Description Get the object value associated with an index. ### Parameters - **index** (int) - Required - The index must be between 0 and length() - 1. ### Returns - **Object** - An object value. ### Throws - **JSONException** - If there is no value for the index. ``` -------------------------------- ### Navigate to Project Directory Source: https://grails.apache.org/docs/3.3.18/guide/single.html Change the current working directory to the newly created project folder. ```text cd helloworld ``` -------------------------------- ### nextTo(char d) Source: https://grails.apache.org/docs/3.3.18/api/org/grails/web/json/JSONTokener.html Get the text up but not including the specified character or the end of line. ```APIDOC ## public java.lang.String nextTo(char d) ### Description Get the text up but not including the specified character or the end of line, whichever comes first. ### Parameters - **d** (char) - A delimiter character. ### Returns - **String** - The extracted string. ``` -------------------------------- ### getPathFromRoot(java.lang.String path) Source: https://grails.apache.org/docs/3.3.18/api/org/grails/io/support/GrailsResourceUtils.html Get the path relative to an artefact folder under grails-app. ```APIDOC ### public static java.lang.String getPathFromRoot(java.lang.String path) #### Description Get the path relative to an artefact folder under grails-app. #### Parameters - **path** (java.lang.String) - The path to evaluate #### Returns - (java.lang.String) - The path relative to the root folder grails-app ``` -------------------------------- ### run(String... args) Source: https://grails.apache.org/docs/3.3.18/api/grails/ui/script/GrailsApplicationScriptRunner.html Executes the application with the provided arguments and returns the configured application context. ```APIDOC ## org.springframework.context.ConfigurableApplicationContext run(java.lang.String... args) ### Description Runs the Grails application with the specified arguments. ### Parameters - **args** (String...) - Required - Arguments for the application execution. ### Response - **Return Type** (ConfigurableApplicationContext) - The configured application context. ``` -------------------------------- ### Run Grails Application Source: https://grails.apache.org/docs/3.3.18/guide/single.html Starts the application using the built-in Tomcat server. ```bash grails run-app ``` ```bash grails run-app -port=8090 ``` -------------------------------- ### Limit Bound Properties Source: https://grails.apache.org/docs/3.3.18/guide/single.html Example of retrieving a domain instance for secure property updates. ```groovy def p = Person.get(1) ``` -------------------------------- ### Implement the Show Action Source: https://grails.apache.org/docs/3.3.18/guide/REST.html Implementation of the show action using automatic domain instance lookup. ```groovy def show(Book book) { respond book } ``` ```groovy def show(Book book) { if(book == null) { render status:404 } else { return [book: book] } } ``` -------------------------------- ### Configure Plugin Dependency Source: https://grails.apache.org/docs/3.3.18/guide/single.html Example of declaring a plugin dependency in a Grails project configuration. ```groovy - "org.grails.plugins:myplugin2:1.0" ``` -------------------------------- ### Create a Grails Application Source: https://grails.apache.org/docs/3.3.18/guide/profiles.html Commands to initialize a new Grails application using the default or a specific profile. ```bash grails create-app myapp ``` ```bash grails create-app myapp --profile=rest-api ``` -------------------------------- ### Accept header examples Source: https://grails.apache.org/docs/3.3.18/guide/theWebLayer.html Common Accept header values sent by browsers and clients. ```text */* ``` ```text text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, \ text/plain;q=0.8, image/png, */*;q=0.5 ``` ```text application/json ``` -------------------------------- ### Define post-creation instructions in profile.yml Source: https://grails.apache.org/docs/3.3.18/guide/profiles.html Specify text to display to the user after application creation. ```yaml instructions: Here are some instructions ``` -------------------------------- ### Criteria Projections Example Source: https://grails.apache.org/docs/3.3.18/ref/Domain%20Classes/createCriteria.html Using projections to count distinct values in a criteria query. ```Groovy def c = Account.createCriteria() def branchCount = c.get { projections { countDistinct "branch" } } ``` -------------------------------- ### Generate Application Skeleton Source: https://grails.apache.org/docs/3.3.18/guide/gettingStarted.html Use the generate-all command to create a controller, unit test, and views for a domain class. ```bash grails generate-all helloworld.Book ``` -------------------------------- ### Custom Renderer Output Format Source: https://grails.apache.org/docs/3.3.18/guide/REST.html Example of the XML output generated by the custom BookXmlRenderer. ```xml ``` -------------------------------- ### Command Usage Syntax Source: https://grails.apache.org/docs/3.3.18/ref/Command%20Line/plugin-info.html The standard syntax for executing the plugin-info command. ```bash grails plugin-info <> ``` -------------------------------- ### REST Response Formats Source: https://grails.apache.org/docs/3.3.18/guide/REST.html Example XML and JSON responses returned by the RESTful resource. ```xml The Stand ``` ```json {"id":1,"title":"The Stand"} ``` -------------------------------- ### Command Usage Syntax Source: https://grails.apache.org/docs/3.3.18/ref/Command%20Line/create-app.html General syntax for executing the create-app command with optional profile and feature flags. ```bash grails create-app <> [--profile] <> [--features] <> ``` -------------------------------- ### Environment-specific war commands Source: https://grails.apache.org/docs/3.3.18/ref/Command%20Line/war.html Examples of running the war command in different Grails environments. ```bash grails test war grails dev war grails prod war ``` -------------------------------- ### Create Application In-Place Source: https://grails.apache.org/docs/3.3.18/ref/Command%20Line/create-app.html Initializes a new Grails application within the current working directory. ```bash $ mkdir bookstore $ cd bookstore $ grails create-app --inplace ``` -------------------------------- ### Advanced DataSource Configuration Source: https://grails.apache.org/docs/3.3.18/guide/conf.html Example of configuring advanced connection pool properties for the DataSource. ```groovy dataSource { pooled = true dbCreate = "update" url = "jdbc:mysql://localhost:3306/my_database" driverClassName = "com.mysql.jdbc.Driver" dialect = org.hibernate.dialect.MySQL5InnoDBDialect username = "username" password = "password" type = "com.zaxxer.hikari.HikariDataSource" properties { // Documentation for Tomcat JDBC Pool // http://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html#Common_Attributes // https://tomcat.apache.org/tomcat-7.0-doc/api/org/apache/tomcat/jdbc/pool/PoolConfiguration.html jmxEnabled = true initialSize = 5 maxActive = 50 minIdle = 5 maxIdle = 25 maxWait = 10000 maxAge = 10 * 60000 timeBetweenEvictionRunsMillis = 5000 minEvictableIdleTimeMillis = 60000 validationQuery = "SELECT 1" validationQueryTimeout = 3 validationInterval = 15000 ``` -------------------------------- ### Run Full Test Suite Source: https://grails.apache.org/docs/3.3.18/guide/contributing.html Execute the complete set of tests for the project. ```bash ./gradlew test ``` -------------------------------- ### Per-Environment Bootstrapping Source: https://grails.apache.org/docs/3.3.18/guide/conf.html Execute environment-specific logic during application startup within BootStrap.groovy. ```groovy def init = { ServletContext ctx -> environments { production { ctx.setAttribute("env", "prod") } development { ctx.setAttribute("env", "dev") } } ctx.setAttribute("foo", "bar") } ``` -------------------------------- ### Define i18n Message Source: https://grails.apache.org/docs/3.3.18/guide/validation.html Example of a message entry in messages.properties for a specific constraint violation. ```properties user.login.blank=Your login name must be specified! ``` -------------------------------- ### Generate documentation locally Source: https://grails.apache.org/docs/3.3.18/guide/contributing.html Gradle command to build the documentation, excluding the API documentation task for faster execution. ```bash $ ./gradlew publishGuide -x apiDocs ``` -------------------------------- ### Execute a command with arguments Source: https://grails.apache.org/docs/3.3.18/guide/commandLine.html Example of invoking a command that utilizes defined flags and arguments. ```bash grails generate-all MyClass --force ``` -------------------------------- ### Execute HQL Queries with executeQuery Source: https://grails.apache.org/docs/3.3.18/ref/Domain%20Classes/executeQuery.html Examples demonstrating various ways to invoke executeQuery, including parameter passing, pagination, and Hibernate-specific configuration options. ```Groovy // simple query Account.executeQuery("select distinct a.number from Account a") // using with list of parameters Account.executeQuery("select distinct a.number from Account a " + "where a.branch = ? and a.created > ?", ['London', lastMonth]) // using with a single parameter and pagination params Account.executeQuery("select distinct a.number from Account a " + "where a.branch = ?", ['London'], [max: 10, offset: 5]) // using with Map of named parameters Account.executeQuery("select distinct a.number from Account a " + "where a.branch = :branch", [branch: 'London']) // using with Map of named parameters and pagination params Account.executeQuery("select distinct a.number from Account a " + "where a.branch = :branch", [branch: 'London', max: 10, offset: 5]) // same as previous Account.executeQuery("select distinct a.number from Account a " + "where a.branch = :branch", [branch: 'London'], [max: 10, offset: 5]) // tell underlying Hibernate Query object to not attach newly retrieved // objects to the session, will only save with explicit `save` Account.executeQuery("select distinct a.number from Account a", null, [readOnly: true]) // time request out after 18 seconds Account.executeQuery("select distinct a.number from Account a", null, [timeout: 18]) // have Hibernate Query object return 30 rows at a time Account.executeQuery("select distinct a.number from Account a", null, [fetchSize: 30]) // modify the FlushMode of the Query (default is `FlushMode.AUTO`) Account.executeQuery("select distinct a.number from Account a", null, [flushMode: FlushMode.MANUAL]) ``` -------------------------------- ### Read Domain Instance Source: https://grails.apache.org/docs/3.3.18/guide/GORM.html Retrieving instances using get, read, and load methods. ```groovy def p = Person.get(1) assert 1 == p.id ``` ```groovy def p = Person.read(1) ``` ```groovy def p = Person.load(1) ``` -------------------------------- ### Responding with a Map and Arguments Source: https://grails.apache.org/docs/3.3.18/ref/Controllers/respond.html Illustrates the correct syntax for responding with a Map and arguments to avoid parameter reversal. ```Groovy respond([:], status: 200) ``` -------------------------------- ### REST Resource JSON Response Source: https://grails.apache.org/docs/3.3.18/guide/single.html Example JSON output format for a REST resource request. ```json {"id":1,"title":"The Stand"} ``` -------------------------------- ### REST Resource XML Response Source: https://grails.apache.org/docs/3.3.18/guide/single.html Example XML output format for a REST resource request. ```xml The Stand ``` -------------------------------- ### Render a Domain Instance in a Template Source: https://grails.apache.org/docs/3.3.18/guide/REST.html Basic template syntax for rendering a Book domain instance. ```groovy model { Book book } json g.render(book) ``` -------------------------------- ### main(String[] args) Source: https://grails.apache.org/docs/3.3.18/api/grails/ui/console/GrailsSwingConsole.html The main method used to run an existing Application class. ```APIDOC ## static void main(String[] args) ### Description Main method to run an existing Application class. ### Parameters - **args** (String[]) - Required - Command line arguments. ``` -------------------------------- ### Create a Grails plugin Source: https://grails.apache.org/docs/3.3.18/ref/Command%20Line/create-plugin.html Initializes a new Grails plugin project with the specified name. ```bash grails create-plugin simple ``` ```bash grails create-plugin <> ``` -------------------------------- ### Criteria Method Examples Source: https://grails.apache.org/docs/3.3.18/ref/Domain%20Classes/createCriteria.html Common criteria methods for filtering and ordering domain class queries. ```Groovy between("balance", 500, 1000) ``` ```Groovy eq("branch", "London") ``` ```Groovy eq("branch", "london", [ignoreCase: true]) ``` ```Groovy eqProperty("lastTx", "firstTx") ``` ```Groovy gt("balance",1000) ``` ```Groovy gtProperty("balance", "overdraft") ``` ```Groovy ge("balance", 1000) ``` ```Groovy geProperty("balance", "overdraft") ``` ```Groovy idEq(1) ``` ```Groovy ilike("holderFirstName", "Steph%") ``` ```Groovy 'in'("age",[18..65]) or not {'in'("age",[18..65])} ``` ```Groovy isEmpty("transactions") ``` ```Groovy isNotEmpty("transactions") ``` ```Groovy isNull("holderGender") ``` ```Groovy isNotNull("holderGender") ``` ```Groovy lt("balance", 1000) ``` ```Groovy ltProperty("balance", "overdraft") ``` ```Groovy le("balance", 1000) ``` ```Groovy leProperty("balance", "overdraft") ``` ```Groovy like("holderFirstName", "Steph%") ``` ```Groovy ne("branch", "London") ``` ```Groovy neProperty("lastTx", "firstTx") ``` ```Groovy order("holderLastName", "desc") ``` ```Groovy rlike("holderFirstName", /Steph.+/) ``` ```Groovy sizeEq("transactions", 10) ``` ```Groovy sizeGt("transactions", 10) ``` ```Groovy sizeGe("transactions", 10) ``` ```Groovy sizeLt("transactions", 10) ``` ```Groovy sizeLe("transactions", 10) ``` ```Groovy sizeNe("transactions", 10) ``` ```Groovy sqlRestriction "char_length(first_name) = 4" ``` -------------------------------- ### Data Binding Examples Source: https://grails.apache.org/docs/3.3.18/ref/Controllers/bindData.html Demonstrates various ways to bind request parameters to a target object, including filtering by property names and prefixes. ```groovy // binds request parameters to a target object bindData(target, params) // exclude firstName and lastName bindData(target, params, [exclude: ['firstName', 'lastName']]) // only use parameters starting with "author." e.g. author.email bindData(target, params, "author") bindData(target, params, [exclude: ['firstName', 'lastName']], "author") // using inclusive map bindData(target, params, [include: ['firstName', 'lastName']], "author") ``` -------------------------------- ### Custom Link Output Example Source: https://grails.apache.org/docs/3.3.18/guide/REST.html The resulting JSON output after applying a custom link to a resource. ```json { "_links": { "self": { "href": "http://localhost:8080/books/1", "hreflang": "en", "type": "application/vnd.books.org.book+json" } "publisher": { "href": "http://localhost:8080/books/1/publisher", "hreflang": "en" } }, "title": "\"The Stand\"" } ``` -------------------------------- ### Create Application with Custom Profile Source: https://grails.apache.org/docs/3.3.18/guide/profiles.html Commands to create an application using a specific profile artifact or a configured default. ```bash $ grails create-app myapp --profile=com.mycompany.grails.profiles:myprofile:1.0.0 ``` ```bash $ grails create-app myapp --profile=myprofile ``` -------------------------------- ### JSON View Output Source: https://grails.apache.org/docs/3.3.18/guide/REST.html The resulting JSON output produced by the basic JSON view example. ```JSON {"person":{"name":"bob"}} ``` -------------------------------- ### Initialize Object with Map Source: https://grails.apache.org/docs/3.3.18/guide/theWebLayer.html Demonstrates creating a new object instance using a map of values. ```groovy def bindingMap = [firstName: 'Peter', lastName: 'Gabriel', age: 63] def person = new Person(bindingMap) assert person.firstName == 'Peter' assert person.lastName == 'Gabriel' assert person.age == 63 ``` -------------------------------- ### Execute Application Tasks Source: https://grails.apache.org/docs/3.3.18/guide/REST.html Commands to run the server, client, or both applications using Gradle. ```bash ./gradlew server:bootRun ``` ```bash ./gradlew client:bootRun ``` ```bash ./gradlew bootRun --parallel ``` -------------------------------- ### Model Merging Example Source: https://grails.apache.org/docs/3.3.18/ref/Controllers/chain.html Demonstrates how the chained model is merged with the model returned by the target action. ```groovy def one() { chain action: 'two', model: [name: 'Tony', town: 'Birmingham'] } def two() { [name: 'Anthony', country: 'England'] } ``` -------------------------------- ### Basic max constraint usage Source: https://grails.apache.org/docs/3.3.18/ref/Constraints/max.html Examples of applying the max constraint to different property types. ```groovy age max: new Date() price max: 999F ``` -------------------------------- ### Populate Map via Binding Map Source: https://grails.apache.org/docs/3.3.18/guide/theWebLayer.html Example of initializing a domain object with a map containing key-based player data. ```groovy def bindingMap = [title: 'The Lamb Lies Down On Broadway', 'players[guitar]': [name: 'Steve Hackett'], 'players[vocals]': [name: 'Peter Gabriel'], 'players[keyboards]': [name: 'Tony Banks']] def album = new Album(bindingMap) assert album.title == 'The Lamb Lies Down On Broadway' assert album.players.size() == 3 assert album.players.guitar.name == 'Steve Hackett' assert album.players.vocals.name == 'Peter Gabriel' assert album.players.keyboards.name == 'Tony Banks' ``` -------------------------------- ### Basic min constraint usage Source: https://grails.apache.org/docs/3.3.18/ref/Constraints/min.html Examples of applying the min constraint to different data types. ```groovy age min: new Date() price min: 0F ```