grailsgrails-domain-class

Grails 4 how to get an handle to artifacts in custom command


I need to build a custom command in a Grails 4 application (https://docs.grails.org/4.0.11/guide/single.html#creatingCustomCommands), and I need to get an handle to some Grails Services and Domain classes which I will query as needed.

The custom command skeleton is quite simple:

import grails.dev.commands.*
import org.apache.maven.artifact.Artifact

class HelloWorldCommand implements GrailsApplicationCommand {

    boolean handle() {
        return true
    }
}

While the documentation says that a custom command has access to the whole application context, I haven't found any examples on how to get an handle of that and start accessing the various application artifacts.

Any hints?

EDIT: to add context and clarify the goal of the custom command in order for further recommendation/best practices/etc.: the command reads data from a file in a custom format, persist the data, and writes reports in another custom format. Will eventually be replaced by a recurrent job, once the data will be available on demand from a third party REST API.


Solution

  • See the project at github.com/jeffbrown/marco-vittorini-orgeas-artifacts-cli.

    grails-app/services/marco/vittorini/orgeas/artifacts/cli/GreetingService.groovy

    package marco.vittorini.orgeas.artifacts.cli
    
    class GreetingService {
        String greeting = 'Hello World'
    }
    

    grails-app/commands/marco/vittorini/orgeas/artifacts/cli/HelloCommand.groovy

    package marco.vittorini.orgeas.artifacts.cli
    
    
    import grails.dev.commands.*
    
    class HelloCommand implements GrailsApplicationCommand {
        GreetingService greetingService
        boolean handle() {
    
            println greetingService.greeting
    
            return true
        }
    }
    

    EDIT:

    I have added a commit at github.com/jeffbrown/marco-vittorini-orgeas-artifacts-cli/commit/49a846e3902073f8ea0539fcde550f6d002b9d89 which demonstrates accessing a domain class, which was part of the question I overlooked when writing the initial answer.