### Example Multi-Project Setup
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/create-multi-project-build.html
This example demonstrates the typical workflow: creating an application and plugins, then running the `create-multi-project-build` command. The generated `pom.xml` will include dependencies for the plugins.
```bash
$ grails create-app myapp
$ grails create-plugin plugin1
$ grails create-plugin plugin2
$ grails create-multi-project-build org.mycompany:parent:1.0
```
```xml
org.grails.pluginsplugin10.1zipcompile
```
--------------------------------
### Install Plugin from URL
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/install-plugin.html
Installs a plugin from a remote URL. This command is deprecated.
```bash
grails install-plugin http://foo.com/grails-bar-1.0.zip
```
--------------------------------
### Find First Book by Example
Source: https://grails.apache.org/docs/2.5.5/ref/Domain%20Classes/find.html
Use this to find the first book that matches the properties of a given example instance.
```groovy
// query by example
def example = new Book(author: "Dan Brown")
Book.find(example)
```
--------------------------------
### Install Plugin from Local File
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/install-plugin.html
Installs a plugin from a local zip file. This command is deprecated.
```bash
grails install-plugin ../grails-bar-1.0.zip
```
--------------------------------
### Grails Help Output Example
Source: https://grails.apache.org/docs/2.5.5/guide/commandLine.html
Example output from the 'grails help' command, showing usage format and available targets.
```text
Usage (optionals marked with *):
grails [environment]* [target] [arguments]*Examples:
grails dev run-app
grails create-app booksAvailable Targets (type grails help 'target-name' for more info):
grails bootstrap
grails bug-report
grails clean
grails compile
...
```
--------------------------------
### Example Plugin List Output
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/list-plugins.html
This is an example of the typical output when listing available plugins, showing plugin name, version, and description.
```text
Plugins available in the grailsCentral repository are listed below:
-------------------------------------------------------------
acegi <0.5.3.2> -- Grails Spring Security 2.0 Plugin
activemq <0.3> -- Grails ActiveMQ Plugin
activiti <5.6> -- Grails Activiti Plugin
ajax-uploader <0.3> -- Ajax Uploader Plugin
ajaxflow <0.2.1> -- This plugin enables Ajaxified Webflows
akismet <0.2> -- Akismet Anti-Spam Plugin
alfresco <0.4> -- Plugin de integracion con Alfresco.
...
```
--------------------------------
### Start Grails Console with Environment
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/console.html
Starts the Grails console, optionally specifying one or more Grails environments.
```bash
grails [environment]* console
```
--------------------------------
### Example Output of list-plugin-updates
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/list-plugin-updates.html
This is an example of the output you might see when running the list-plugin-updates command, showing plugins with available updates.
```text
Plugins with available updates are listed below:
-------------------------------------------------------------
acegi 0.4 0.5.2
console 0.1 0.2.2
```
--------------------------------
### Grails Controller Example
Source: https://grails.apache.org/docs/2.5.5/ref/Tags/createLink.html
An example controller for an application named 'shop' demonstrating list and show actions.
```groovy
class BookController {
static defaultAction = "list"
def list() {
[books: Book.list(params)]
}
def show() {
[book: Book.get(params.id)]
}
}
```
--------------------------------
### Example Controller for formRemote
Source: https://grails.apache.org/docs/2.5.5/ref/Tags/formRemote.html
This is an example controller that can be used with the formRemote tag to fetch book data.
```Groovy
class BookController {
def show() {
[book: Book.get(params.id)]
}
def byAuthor() {
[books: Book.findByAuthor(params.author, params)]
}
}
```
--------------------------------
### Grails Controller Example
Source: https://grails.apache.org/docs/2.5.5/ref/Tags/remoteLink.html
Example controller for an application named 'shop' demonstrating actions that can be called remotely.
```Groovy
class BookController {
def list() {
[books: Book.list(params)]
}
def show() {
[book: Book.get(params.id)]
}
def bookByName() {
[book: Book.findByName(params.bookName)]
}
}
```
--------------------------------
### Start Grails Interactive Console
Source: https://grails.apache.org/docs/2.5.5/guide/gettingStarted.html
Navigate to your project directory and start the Grails interactive console to execute commands.
```bash
cd helloworld
grails
```
--------------------------------
### Grails Controller Example
Source: https://grails.apache.org/docs/2.5.5/ref/Tags/link.html
An example Grails controller with 'list' and 'show' actions. This controller is used in subsequent link tag examples.
```groovy
class BookController {
def list() {
[books: Book.list(params)]
}
def show() {
[book : Book.get(params.id)]
}
}
```
--------------------------------
### List Available Plugins
Source: https://grails.apache.org/docs/2.5.5/guide/plugins.html
Use this command to list all plugins available in the central repository. This command requires no setup.
```bash
grails list-plugins
```
--------------------------------
### Build Grails Installation from Source
Source: https://grails.apache.org/docs/2.5.5/guide/contributing.html
After cloning the repository, run this Gradle command from the project's root directory to build a Grails installation. This fetches dependencies and creates a GRAILS_HOME compatible structure. It skips the extensive test classes collection.
```bash
./gradlew install
```
--------------------------------
### Initialize Project Documentation Template
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/doc.html
Initializes a template for project documentation. Use this to set up the basic structure for your user guide.
```bash
grails doc --init
```
--------------------------------
### Grails Controller Example
Source: https://grails.apache.org/docs/2.5.5/ref/Tags/remoteFunction.html
This is an example controller for a Grails application that defines actions for listing, showing, and finding books.
```groovy
class BookController {
def list() {
[books: Book.list(params)]
}
def show() {
[book: Book.get(params.id)]
}
def bookByName() {
[book: Book.findByName(params.bookName)]
}
}
```
--------------------------------
### findAllBy* Examples
Source: https://grails.apache.org/docs/2.5.5/ref/Domain%20Classes/findAllBy.html
Demonstrates various ways to use the `findAllBy*` dynamic finder with different property conditions and operators.
```groovy
def results = Book.findAllByTitle("The Shining",
[max: 10, sort: "title", order: "desc", offset: 100])
```
```groovy
results = Book.findAllByTitleAndAuthor("The Sum of All Fears", "Tom Clancy")
```
```groovy
results = Book.findAllByReleaseDateBetween(firstDate, new Date())
```
```groovy
results = Book.findAllByReleaseDateGreaterThanEquals(firstDate)
```
```groovy
results = Book.findAllByTitleLike("%Hobbit%")
```
```groovy
results = Book.findAllByTitleIlike("%Hobbit%") // ignore case
```
```groovy
results = Book.findAllByTitleNotEqual("Harry Potter")
```
```groovy
results = Book.findAllByReleaseDateIsNull()
```
```groovy
results = Book.findAllByReleaseDateIsNotNull()
```
```groovy
results = Book.findAllPaperbackByAuthor("Douglas Adams")
```
```groovy
results = Book.findAllNotPaperbackByAuthor("Douglas Adams")
```
```groovy
results = Book.findAllByAuthorInList(["Douglas Adams", "Hunter S. Thompson"])
```
--------------------------------
### Grails Controller Example
Source: https://grails.apache.org/docs/2.5.5/ref/Tags/form.html
An example controller for a Grails application that handles book listing and retrieval. This controller is used in conjunction with the form tag examples.
```groovy
class Book {
def list() {
[books: Book.list(params)]
}
def show() {
[book: Book.get(params.id)]
}
}
```
--------------------------------
### Install Dependency with Explicit Group, Name, and Version
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/install-dependency.html
Installs a dependency by explicitly providing the group, name, and version as separate arguments.
```bash
grails install-dependency --group=mysql --name=mysql-connector-java --version=5.1.16
```
--------------------------------
### Grails Shell Example Prompt
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/shell.html
This is an example of the prompt you will see when the Grails shell is active.
```groovy
Groovy Shell (1.8.0, JVM: 1.6.0_26)
Type 'help' or 'h' for help.
-----------------------------------
groovy:000>
```
--------------------------------
### GORM Basic CRUD Example
Source: https://grails.apache.org/docs/2.5.5/guide/GORM.html
Demonstrates adding authors to a book and saving the changes using GORM's dynamic methods.
```groovy
def book = Book.findByTitle("Groovy in Action")
book
.addToAuthors(name:"Dierk Koenig")
.addToAuthors(name:"Guillaume LaForge")
.save()
```
--------------------------------
### Example Decorated Page Structure
Source: https://grails.apache.org/docs/2.5.5/ref/Tags/layoutBody.html
This is an example of a page that will be decorated by a layout. It includes head elements and the body content.
```html
Page to be decorated
```
--------------------------------
### Grails Redirect Examples
Source: https://grails.apache.org/docs/2.5.5/ref/Controllers/redirect.html
Demonstrates various ways to use the redirect method for different redirection scenarios.
```groovy
redirect(action: "show")
```
```groovy
redirect(controller: "book", action: "list")
```
```groovy
redirect(controller: "book", action: "list", namespace: "publishing")
```
```groovy
redirect(controller: "book", action: "list", plugin: "publishingUtils")
```
```groovy
redirect(action: "show", id: 4, params: [author: "Stephen King"])
```
```groovy
redirect(controller: "book", action: "show", fragment: "profile")
```
```groovy
redirect(uri: "book/list")
```
```groovy
redirect(url: "http://www.blogjava.net/BlueSUN")
```
--------------------------------
### Install Dependency from a Specific Repository
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/install-dependency.html
Installs a dependency and specifies a custom repository URL to resolve the JAR file from, useful if the dependency is not found in default repositories.
```bash
grails install-dependency mysql:mysql-connector-java:5.1.16 \
--repository=http://download.java.net/maven/2
```
--------------------------------
### Example Decorated Page
Source: https://grails.apache.org/docs/2.5.5/ref/Tags/pageProperty.html
This is an example of a page that will be decorated by a layout. It includes meta tags and body attributes that can be accessed by the layout.
```html
Page to be decorated
```
--------------------------------
### Basic Max Constraint Examples
Source: https://grails.apache.org/docs/2.5.5/ref/Constraints/max.html
Demonstrates the 'max' constraint for different data types. Use this for simple maximum value enforcement.
```Groovy
age max: new Date()
price max: 999F
```
--------------------------------
### Basic Controller Unit Test Setup
Source: https://grails.apache.org/docs/2.5.5/guide/testing.html
Use the `grails.test.mixin.TestFor` annotation to specify the controller under test and activate `ControllerUnitTestMixin`.
```groovy
import grails.test.mixin.TestFor
import spock.lang.Specification
@TestFor(SimpleController)
class SimpleControllerSpec extends Specification {
void "test something"() {
}
}
```
--------------------------------
### Example Grails Controller
Source: https://grails.apache.org/docs/2.5.5/ref/Tags/include.html
Defines actions for listing and showing books, which can be included by other parts of the application.
```groovy
class BookController {
def list() {
[books: Book.list(params)]
}
def show() {
[book: Book.get(params.id)]
}
}
```
--------------------------------
### Asynchronous GORM list and get all
Source: https://grails.apache.org/docs/2.5.5/guide/async.html
Demonstrates asynchronous `list()` and `getAll()` GORM operations. `onComplete` handles the results for `list()`, and `get()` retrieves results for `getAll()`.
```groovy
import static grails.async.Promises.*
Person.async.list().onComplete { List results ->
println "Got people = ${results}"
}
def p = Person.async.getAll(1L, 2L, 3L)
List results = p.get()
```
--------------------------------
### Start Grails Shell
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/shell.html
Starts an instance of the Groovy terminal shell with an initialized Grails runtime. Useful variables like 'ctx' and 'grailsApplication' are available.
```bash
grails shell
```
--------------------------------
### Example GSP Debug Template Comment
Source: https://grails.apache.org/docs/2.5.5/guide/theWebLayer.html
An example of the HTML comments added by the 'debugTemplates' feature, showing template start, end, and rendering time.
```HTML Comment
.
.
.
```
--------------------------------
### Grails Config.groovy Example
Source: https://grails.apache.org/docs/2.5.5/guide/spring.html
Define database properties in Config.groovy to be used as placeholders.
```groovy
database.driver="com.mysql.jdbc.Driver"
database.dbname="mysql:mydb"
```
--------------------------------
### Custom XML Rendering Example
Source: https://grails.apache.org/docs/2.5.5/guide/webServices.html
Illustrates the resulting XML format for a Book object when using the custom BookXmlRenderer.
```xml
```
--------------------------------
### Display Help for a Specific Grails Command
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/help.html
To get detailed help for a specific Grails command, provide the command name as an argument. For example, to get help for the 'run-app' command.
```bash
grails help run-app
```
--------------------------------
### Example HAL JSON Response with Custom Link
Source: https://grails.apache.org/docs/2.5.5/guide/webServices.html
Illustrates a HAL JSON response after customizing link rendering to include a 'publisher' link.
```json
{
"_links": {
"self": {
"href": "http://localhost:8080/myapp/books/1",
"hreflang": "en",
"type": "application/vnd.books.org.book+json"
}
"publisher": {
"href": "http://localhost:8080/myapp/books/1/publisher",
"hreflang": "en"
}
},
"title": ""The Stand""
}
```
--------------------------------
### formRemote with Fallback Method and Action
Source: https://grails.apache.org/docs/2.5.5/ref/Tags/formRemote.html
This example configures formRemote to use a GET method and a specific action as a fallback when JavaScript is unavailable. It also specifies which element to update.
```GSP
Book Id:
```
--------------------------------
### Non-interactive Mode for Grails Scripts
Source: https://grails.apache.org/docs/2.5.5/guide/commandLine.html
Use the --non-interactive switch to accept default answers for prompts, useful for automated processes like CI builds. For example, to install a missing plugin without user input.
```bash
grails war --non-interactive
```
--------------------------------
### Build Grails Documentation
Source: https://grails.apache.org/docs/2.5.5/guide/contributing.html
Execute the Gradle wrapper to build the project documentation. This command may take a significant amount of time.
```bash
./gradlew docs
```
--------------------------------
### Asset Pipeline Manifest Example
Source: https://grails.apache.org/docs/2.5.5/guide/introduction.html
Define asset dependencies and include self or other files using require directives. This example shows how to include jQuery, the self file, a specific file, and all files in the current directory.
```javascript
//= require jquery
//= require_self
//= require file_a
//= require_tree .
```
--------------------------------
### Split Script into Command and Internal Components
Source: https://grails.apache.org/docs/2.5.5/guide/commandLine.html
Example of splitting a script into a command script and an internal implementation script for better organization and reusability.
```groovy
./scripts/FunctionalTests.groovy:
includeTargets << new File("${basedir}/scripts/_FunctionalTests.groovy")
target(default: "Runs the functional tests for this project.") {
depends(runFunctionalTests)
}
```
```groovy
./scripts/_FunctionalTests.groovy:
includeTargets << grailsScript("_GrailsTest")
target(runFunctionalTests: "Run functional tests.") {
depends(...)
…
}
```
--------------------------------
### Install a Grails Plugin
Source: https://grails.apache.org/docs/2.5.5/ref/Plug-ins/Usage.html
Installs a packaged plugin into a Grails application.
```bash
grails install-plugin ../grails-simple-0.1.zip
```
--------------------------------
### Configuring Additional DataSources per Environment
Source: https://grails.apache.org/docs/2.5.5/guide/conf.html
This example demonstrates how to add a second DataSource named `dataSource_lookup` within specific environments (development and production). It shows different database configurations for MySQL in development and Oracle in production.
```groovy
environments {
development {
dataSource {
dbCreate = "create-drop"
url = "jdbc:h2:mem:devDb"
}
dataSource_lookup {
dialect = org.hibernate.dialect.MySQLInnoDBDialect
driverClassName = 'com.mysql.jdbc.Driver'
username = 'lookup'
password = 'secret'
url = 'jdbc:mysql://localhost/lookup'
dbCreate = 'update'
}
}
test {
dataSource {
dbCreate = "update"
url = "jdbc:h2:mem:testDb"
}
}
production {
dataSource {
dbCreate = "update"
url = "jdbc:h2:prodDb"
}
dataSource_lookup {
dialect = org.hibernate.dialect.Oracle10gDialect
driverClassName = 'oracle.jdbc.driver.OracleDriver'
username = 'lookup'
password = 'secret'
url = 'jdbc:oracle:thin:@localhost:1521:lookup'
dbCreate = 'update'
}
}
}
```
--------------------------------
### List Installed Plugins
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/list-plugins.html
Filters the plugin list to show only those that are currently installed in the application.
```bash
grails list-plugins -installed
```
--------------------------------
### Verify Grails Installation
Source: https://grails.apache.org/docs/2.5.5/guide/gettingStarted.html
Check if Grails is installed correctly by running the version command in your terminal.
```bash
grails -version
```
--------------------------------
### Get Plugin Information
Source: https://grails.apache.org/docs/2.5.5/guide/plugins.html
Retrieve detailed information about a specific plugin from the central repository. Replace [plugin-name] with the actual plugin name.
```bash
grails plugin-info [plugin-name]
```
--------------------------------
### Generate PDF Project Documentation
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/doc.html
Generates project documentation including a PDF version of the user guide. Ensure your documentation source files are in `src/docs`.
```bash
grails doc --pdf
```
--------------------------------
### Generate Project Documentation
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/doc.html
Generates a user guide and Javadoc/Groovydoc API documentation for the current Grails project. Documentation is output to `docs/api`, `docs/gapi`, `docs/guide`, and `docs/ref`.
```bash
grails doc
```
--------------------------------
### Save a new domain instance
Source: https://grails.apache.org/docs/2.5.5/ref/Domain%20Classes/save.html
Creates a new Book instance and saves it to the database. The object is not persisted immediately unless `flush` is used.
```groovy
def b = new Book(title: "The Shining")
b.save()
```
--------------------------------
### Example HAL Document for Orders
Source: https://grails.apache.org/docs/2.5.5/guide/webServices.html
Demonstrates a HAL (Hypertext Application Language) document structure for a list of orders, including links and embedded resources.
```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"
}]
}
}
```
--------------------------------
### Run migrate-docs Command
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/migrate-docs.html
Execute the migrate-docs command to automatically convert existing user guide source files from the old format (section numbers in filenames) to the new format (using a toc.yml file). This process generates `toc.yml`, `links.yml`, and `rewriteRules.txt` in `src/docs/migratedGuide`.
```bash
grails migrate-docs
```
--------------------------------
### Create Domain Class with Name
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/create-domain-class.html
Use this command to create a domain class with a specified name, including package. If the package is omitted, the application's name is used. The command will also capitalize the class name if it's not already.
```bash
grails create-domain-class Book
```
```bash
grails create-domain-class org.bookstore.Book
```
--------------------------------
### Install Specific Plugin Version
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/install-plugin.html
Installs a specific version of a plugin from the Grails central SVN repository. This command is deprecated.
```bash
grails install-plugin shiro 1.1
```
--------------------------------
### Create Scaffold Controller (No Domain Specified)
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/create-scaffold-controller.html
Use this command when you want the system to prompt you for the domain class name to scaffold. This is useful for interactive use.
```bash
grails create-scaffold-controller
```
--------------------------------
### Install Plugin from Grails Repository
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/install-plugin.html
Installs the latest version of a plugin from the Grails central SVN repository. This command is deprecated.
```bash
grails install-plugin shiro
```
--------------------------------
### Install Local Grails Plugin
Source: https://grails.apache.org/docs/2.5.5/guide/plugins.html
Run this command to install a Grails plugin into your local Maven cache for use in applications.
```groovy
grails maven-install
```
--------------------------------
### Load a single domain instance
Source: https://grails.apache.org/docs/2.5.5/ref/Domain%20Classes/load.html
Use `Book.load(id)` to get a proxy for a specific book. The proxy is initialized when you access its properties, like `title`.
```groovy
def b = Book.load(1)
String title = b.title
```
--------------------------------
### Get Single Record with Detached Criteria
Source: https://grails.apache.org/docs/2.5.5/guide/GORM.html
Retrieve a single matching record using the `find` or `get` methods on a DetachedCriteria.
```groovy
Person p = criteria.find() // or criteria.get()
```
--------------------------------
### Grails Dependency Graph Output Example
Source: https://grails.apache.org/docs/2.5.5/guide/conf.html
This is an example of the console output for a Grails dependency graph, showing the hierarchical structure of dependencies.
```text
compile - Dependencies placed on the classpath for compilation (total: 73)
+--- org.codehaus.groovy:groovy-all:2.0.6
+--- org.grails:grails-plugin-codecs:2.3.0
| --- org.grails:grails-web:2.3.0
| --- commons-fileupload:commons-fileupload:1.2.2
| --- xpp3:xpp3_min:1.1.4c
| --- commons-el:commons-el:1.0
| --- opensymphony:sitemesh:2.4
| --- org.springframework:spring-webmvc:3.1.2.RELEASE
| --- commons-codec:commons-codec:1.5
| --- org.slf4j:slf4j-api:1.7.2
+--- org.grails:grails-plugin-controllers:2.3.0
| --- commons-beanutils:commons-beanutils:1.8.3
| --- org.grails:grails-core:2.3.0
...
```
--------------------------------
### Display Plugin Information
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/plugin-info.html
Use this command to view detailed information about a specific plugin. Replace '[name]' with the actual plugin name.
```bash
grails plugin-info shiro
```
--------------------------------
### Create a New Grails Application
Source: https://grails.apache.org/docs/2.5.5/guide/gettingStarted.html
Use the 'create-app' command to generate a new Grails project named 'helloworld'.
```bash
grails create-app helloworld
```
--------------------------------
### Install Dependency to Specific Directory
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/install-dependency.html
Installs a dependency and places the JAR files into a specified directory, such as 'lib', instead of the default cache.
```bash
grails install-dependency mysql:mysql-connector-java:5.1.16 --dir=lib
```
--------------------------------
### Target Tests by Phase and Package
Source: https://grails.apache.org/docs/2.5.5/guide/testing.html
Combine phase targeting with package pattern matching to run tests within specified phases and packages. This example targets tests in the `integration` and `unit` phases within the `some.org` package or its subpackages.
```bash
grails test-app integration: unit: some.org.**.*
```
--------------------------------
### Retrieve Domain Instances by IDs using getAll
Source: https://grails.apache.org/docs/2.5.5/ref/Domain%20Classes/getAll.html
Use `Book.getAll()` to fetch `Book` instances by their IDs. You can pass IDs as individual arguments or as a list. If no arguments are provided, it returns all instances of the domain class.
```groovy
def bookList = Book.getAll(2, 1, 3)
```
```groovy
def bookList = Book.getAll([1, 2, 3])
```
```groovy
def bookList = Book.getAll()
```
--------------------------------
### Example Decorator Layout with layoutBody
Source: https://grails.apache.org/docs/2.5.5/ref/Tags/layoutBody.html
This is an example of a Grails layout file that uses the layoutBody tag to insert the content from the decorated page into its own body.
```grails
```
--------------------------------
### Disable Transitive Plugin Installs
Source: https://grails.apache.org/docs/2.5.5/guide/conf.html
Completely disables the resolution of any transitive plugin dependencies for a given plugin declaration. Only the specified plugin will be installed.
```groovy
plugins {
runtime(':weceem:0.8') {
transitive = false
}
runtime ':searchable:0.5.4' // specifies a fixed searchable version
}
```
--------------------------------
### Extend integrate-with Command with Custom Integrations
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/integrate-with.html
You can extend the `integrate-with` command by handling the `IntegrateWithStart` event in an `_Events.groovy` file. This allows you to define custom integration commands, such as `--myide`.
```groovy
eventIntegrateWithStart = {
binding.integrateMyide = {
// your code here
}
}
```
--------------------------------
### Controller and Domain Mocking Setup
Source: https://grails.apache.org/docs/2.5.5/guide/testing.html
Configure a test for a `BookController` and mock associated domain classes (`Book`, `Author`) and a `BookService`. The `@TestFor` annotation specifies the controller under test, and `@Mock` lists the collaborators to be mocked.
```java
@TestFor(BookController)
@Mock([Book, Author, BookService])
```
--------------------------------
### Example Grails Script Structure
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/create-script.html
This is an example of the Groovy code generated for a new Grails script. It defines targets for execution, similar to Ant or Make.
```groovy
target('default': "The description of the script goes here!") {
doStuff()
}
target(doStuff: "The implementation task") {
// logic here
}
```
--------------------------------
### Decorated Page Example - Grails
Source: https://grails.apache.org/docs/2.5.5/ref/Tags/layoutTitle.html
This is an example of a page that will be decorated by a layout. The title tag content within this page will be rendered by the g:layoutTitle tag in the layout.
```html
Hello World!
Page to be decorated
```
--------------------------------
### Install Jetty Plugin for Grails
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/run-app.html
To run Grails with Jetty instead of the default Tomcat container, first uninstall the Tomcat plugin and then install the Jetty plugin.
```bash
grails uninstall-plugin tomcat
```
```bash
grails install-plugin jetty
```
--------------------------------
### Basic createLink Usages
Source: https://grails.apache.org/docs/2.5.5/ref/Tags/createLink.html
Demonstrates generating links to specific actions and controllers using createLink.
```gsp
// generates "/shop/book/show/1"
```
```gsp
// generates "/shop/book/show?foo=bar&boo=far"
```
```gsp
// generates "/shop/book"
```
```gsp
// generates "/shop/book/list"
```
```gsp
// generates "/shop/book/list"
```
--------------------------------
### Implement 'show' action with respond
Source: https://grails.apache.org/docs/2.5.5/guide/webServices.html
A concise implementation for the 'show' action that uses `respond` to handle resource display. Grails automatically looks up the domain instance by ID.
```groovy
def show(Book book) {
respond book
}
```
--------------------------------
### Querying with findWhere
Source: https://grails.apache.org/docs/2.5.5/ref/Domain%20Classes/findWhere.html
Demonstrates how to use the findWhere method to retrieve a single 'Book' instance based on author and title. Also shows how to check for the existence of a book with a specific author and title where the release date is null.
```groovy
def book = Book.findWhere(author: "Stephen King", title: "The Stand")
```
```groovy
boolean isReleased = Book.findWhere(author: "Stephen King",
title: "The Stand",
releaseDate: null) != null
```
--------------------------------
### Define Domain Classes for instanceOf Example
Source: https://grails.apache.org/docs/2.5.5/ref/Domain%20Classes/instanceOf.html
These Groovy classes define the domain model used in the instanceOf examples. They establish relationships and inheritance for testing type checking.
```groovy
class Container {
static hasMany = [children: Child]
}
```
```groovy
class Child {
String name
static belongsTo = [container: Container]
}
```
```groovy
class Thing extends Child {}
```
```groovy
class Other extends Child {}
```
--------------------------------
### List Plugins from a Specific Repository
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/list-plugins.html
Lists plugins available only from a specified repository. Replace 'myRepository' with the actual name of the repository.
```bash
grails list-plugins -repository=myRepository
```
--------------------------------
### Grails Filter: Action Name Patterns with Exclusion
Source: https://grails.apache.org/docs/2.5.5/guide/theWebLayer.html
Apply a filter to actions starting with 'b' but exclude those starting with 'bad*'. 'find: true' enables partial matching.
```groovy
actionBeginningWithBButNotBad(action: 'b*', actionExclude: 'bad*', find: true) {
}
```
--------------------------------
### executeUpdate Examples
Source: https://grails.apache.org/docs/2.5.5/ref/Domain%20Classes/executeUpdate.html
Demonstrates various ways to use executeUpdate for deleting and updating records. Supports simple queries, positional parameters, and named parameters.
```groovy
Account.executeUpdate("delete Book b where b.pages > 100")
```
```groovy
Account.executeUpdate("delete Book b where b.title like ?",
['Groovy In Action'])
```
```groovy
Account.executeUpdate("delete Book b where b.author=?",
[Author.load(1)])
```
```groovy
Account.executeUpdate("update Book b set b.title='Groovy In Action'" +
"where b.title='GINA'")
```
```groovy
Account.executeUpdate("update Book b set b.title=:newTitle " +
"where b.title=:oldTitle",
[newTitle: 'Groovy In Action', oldTitle: 'GINA'])
```
--------------------------------
### Example Controller for remoteField
Source: https://grails.apache.org/docs/2.5.5/ref/Tags/remoteField.html
This is an example controller action that handles the data sent from the remoteField tag. It retrieves a book by ID, updates its title with the provided value, and saves the changes.
```Groovy
class BookController {
def changeTitle() {
def b = Book.get(params.id)
b.title = params.value
b.save()
}
}
```
--------------------------------
### Install Dependency by Group:Name:Version
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/install-dependency.html
Installs a specified dependency using the 'group:name:version' format. Grails will attempt to resolve it from built-in public Maven repositories.
```bash
grails install-dependency mysql:mysql-connector-java:5.1.16
```
--------------------------------
### Create Scaffold Controller (With Domain Specified)
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/create-scaffold-controller.html
Use this command to directly specify the domain class for which to generate a scaffolding controller. This is useful for scripting or when the domain class name is known.
```bash
grails create-scaffold-controller org.bookstore.Book
```
--------------------------------
### Retrieve Domain Instance by ID using get()
Source: https://grails.apache.org/docs/2.5.5/ref/Domain%20Classes/get.html
Use the `get()` method on a domain class to fetch a specific record by its ID. Returns null if no record with the given ID exists.
```groovy
def b = Book.get(1)
```
--------------------------------
### Run Full Test Suite
Source: https://grails.apache.org/docs/2.5.5/guide/contributing.html
Execute the entire test suite for the project. This command can take a significant amount of time.
```bash
./gradlew test
```
--------------------------------
### Example Usage of remoteField Tag
Source: https://grails.apache.org/docs/2.5.5/ref/Tags/remoteField.html
This example demonstrates how to use the remoteField tag in a GSP. It creates a text field for the book title, specifies the remote action and controller, and defines a div to update with the response.
```GSP
I'm updated with the new title!
```
--------------------------------
### Resulting HTML after Decoration
Source: https://grails.apache.org/docs/2.5.5/ref/Tags/layoutBody.html
This shows the final HTML output when the example decorated page is processed by the example decorator layout. The content of the decorated page's body is inserted where the layoutBody tag was placed.
```html
Page to be decorated
```
--------------------------------
### Grails Form Tag Usage Examples
Source: https://grails.apache.org/docs/2.5.5/ref/Tags/form.html
Demonstrates various ways to use the Grails form tag to generate HTML forms. These examples show how to specify the action, controller, and ID for form submissions.
```grails
...
```
```html
```
```grails
...
```
```html
```
```grails
...
```
```html
```
--------------------------------
### Build Documentation with Specified Grails Home
Source: https://grails.apache.org/docs/2.5.5/guide/contributing.html
Build the documentation while specifying the path to the Grails source code using the -Dgrails.home property. This avoids downloading and compiling Grails source if it's already available locally.
```bash
./gradlew -Dgrails.home=/home/user/projects/grails-core docs
```
--------------------------------
### Decorator Layout Example - Grails
Source: https://grails.apache.org/docs/2.5.5/ref/Tags/layoutTitle.html
This example shows a decorator layout that includes the g:layoutTitle tag to render the page's title. It also includes g:layoutHead and g:layoutBody for integrating page-specific resources and content.
```html
```
--------------------------------
### Equivalent 'show' action with manual null check
Source: https://grails.apache.org/docs/2.5.5/guide/webServices.html
This action manually checks if the domain instance is null and returns a 404 if it is, otherwise it returns the instance for rendering.
```groovy
def show(Book book) {
if(book == null) {
render status:404
}
else {
return [book: book]
}
}
```
--------------------------------
### Basic Select with OptionKey and OptionValue
Source: https://grails.apache.org/docs/2.5.5/ref/Tags/select.html
Use `optionKey` to set the value attribute of each option and `optionValue` to set the display text. This is useful when working with domain objects like `Book`.
```grails
```
--------------------------------
### Start Grails CLI in Interactive Mode
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/interactive.html
Starts the Grails CLI in interactive mode. This mode keeps the JVM running between commands, avoiding startup time and allowing for JIT compiler optimizations, which speeds up repeated command execution.
```bash
grails interactive
```
--------------------------------
### Create Unit Test Command
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/create-unit-test.html
Use this command to generate a unit test file. The argument is optional; if omitted, the command will prompt for the name.
```bash
grails create-unit-test
```
```bash
grails create-unit-test book
```
```bash
grails create-unit-test org.bookstore.Book
```
--------------------------------
### Refresh Dependencies
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/refresh-dependencies.html
Refreshes application dependencies and installs any required plugins.
```bash
grails refresh-dependencies
```
--------------------------------
### Define Domain Class
Source: https://grails.apache.org/docs/2.5.5/guide/GORM.html
Defines a simple domain class used in subsequent examples.
```groovy
// Box is a domain class…
class Box {
int width
int height
}
```
--------------------------------
### findAllBy* with Pagination and Sorting
Source: https://grails.apache.org/docs/2.5.5/ref/Domain%20Classes/findAllBy.html
Shows how to apply pagination and sorting parameters to a `findAllBy*` dynamic finder method.
```groovy
def results = Book.findAllByTitle("The Shining",
[max: 10, sort: "title", order: "desc", offset: 100])
```
--------------------------------
### Define a Grails Domain Class
Source: https://grails.apache.org/docs/2.5.5/ref/Tags/render.html
Defines a simple domain class for use in examples.
```groovy
class Book {
String title
String author
}
```
--------------------------------
### Customize Rendering with GSP
Source: https://grails.apache.org/docs/2.5.5/guide/webServices.html
Shows how to use a GSP file (show.xml.gsp) to customize the XML rendering for a specific action.
```groovy
def show(Book book) {
respond book
}
```
```xml
<%@page contentType="application/xml"%>
```
--------------------------------
### Include Plugin in Multiple Environments
Source: https://grails.apache.org/docs/2.5.5/guide/plugins.html
Configure a plugin to load in both 'development' and 'test' environments using a list.
```groovy
def environments = ["development", "test"]
```
--------------------------------
### Stop Application in Interactive Mode
Source: https://grails.apache.org/docs/2.5.5/guide/commandLine.html
Use 'stop-app' to stop an application started with 'run-app'.
```bash
stop-app
```
--------------------------------
### Find or Create Domain Instance with Grails
Source: https://grails.apache.org/docs/2.5.5/ref/Domain%20Classes/findOrCreateWhere.html
Use this method to retrieve an existing Book instance or create a new one if it doesn't exist. The new instance is initialized with the provided query parameters but is not automatically saved.
```groovy
class Book {
String title
Date releaseDate
String author
static constraints = {
releaseDate nullable: true
}
}
```
```groovy
def book = Book.findOrCreateWhere(author: "Stephen King", title: "The Stand")
```
--------------------------------
### Get Bean by Name
Source: https://grails.apache.org/docs/2.5.5/ref/Tags/set.html
Retrieves a bean named 'bookService' from the application context and assigns it to a variable.
```gsp
```
--------------------------------
### findOrCreateBy vs. findBy with Manual Creation
Source: https://grails.apache.org/docs/2.5.5/ref/Domain%20Classes/findOrCreateBy.html
Illustrates the equivalent logic of findOrCreateByTitle using findBy and a manual check for null, followed by creating a new instance if necessary. This highlights that findOrCreateBy simplifies this common pattern.
```groovy
def b = Book.findByTitle("The Shining")
if (!b) {
b = new Book(title: "The Shining")
}
```
--------------------------------
### Integrate Grails with TextMate
Source: https://grails.apache.org/docs/2.5.5/guide/gettingStarted.html
Use this command to generate project files for TextMate integration. Alternatively, use 'mate .' to open any project.
```bash
grails integrate-with --textmate
```
```bash
mate .
```
--------------------------------
### Grails findAll: Advanced Queries
Source: https://grails.apache.org/docs/2.5.5/ref/Domain%20Classes/findAll.html
Construct queries using subqueries (e.g., NOT EXISTS) or query by example.
```groovy
// examples with tables join
Book.findAll("from Book as b where not exists " +
"(from Borrow as br where br.book = b)")
```
```groovy
// query by example
def example = new Book(author: "Dan Brown")
Book.findAll(example)
```
--------------------------------
### Grails Domain Class Example
Source: https://grails.apache.org/docs/2.5.5/ref/Domain%20Classes/findOrCreateBy.html
Defines a simple Grails domain class with title and author properties.
```groovy
class Book {
String title
String author
}
```
--------------------------------
### Initialize Grails Application Directory Structure
Source: https://grails.apache.org/docs/2.5.5/ref/Command%20Line/init.html
Use this command to create the standard directory structure for a new Grails application. It also sets up common variables for use within Grails scripts.
```bash
grails init
```
--------------------------------
### createLink with Complex Parameters
Source: https://grails.apache.org/docs/2.5.5/ref/Tags/createLink.html
Example of generating a link with multiple parameters, including an ID and query string parameters.
```gsp
// generates "/shop/book/list/1?title=The+Shining&author=Stephen+King"
```
--------------------------------
### Unit Test Metaprogramming (Spock)
Source: https://grails.apache.org/docs/2.5.5/guide/testing.html
Perform runtime metaprogramming in Spock-based unit tests within the `setupSpec()` method to ensure it's done before the testing environment is fully initialized.
```groovy
package myapp
import grails.test.mixin.*
import spock.lang.Specification
@TestFor(SomeController)
class SomeControllerSpec extends Specification {
def setupSpec() {
SomeClass.metaClass.someMethod = { ->
// do something here
}
}
// …
}
```