Grails上的NoClassDefFoundError GANT脚本

时间:2012-02-14 16:56:09

标签: java grails groovy classpath gant

我正在尝试在Grails插件之前构建一些GANT脚本。 基本上,我想用新的Class扩展DefaultGrailsTemplateGenerator类,它通过Grails模板方案添加新方法来自动生成服务类。

假设我用Service生成器命名我的类,它扩展了DefaulGrailsTemplateGenerator并添加了generateService方法。

import org.codehaus.groovy.grails.scaffolding.DefaultGrailsTemplateGenerator;

class ServiceGenerator extends DefaultGrailsTemplateGenerator {
        void generateService(GrailsDomainClass domainClass, String destdir) {
        }
}

一切正常(例如GANT脚本被调用),除了我实施ServiceGeneratorClass的一行代码,它返回错误:

Error Error executing script GenerateService: com.cygnus.grails.util.scaffolding.ServiceGenerator
java.lang.NoClassDefFoundError: com.cygnus.grails.util.scaffolding.ServiceGenerator
    at GenerateExt_groovy.class$(GenerateExt_groovy)
    at GenerateExt_groovy.$get$$class$com$cygnus$grails$util$scaffolding$ServiceGenerator(GenerateExt_groovy)
    at GenerateExt_groovy.generateForDomainClass(GenerateExt_groovy:81)

我尝试浏览此错误并尝试通过更改语法来调用该类:

def templateGenerator = new ServiceGenerator(classLoader)

到:

def myClass = classLoader.loadClass("org.my.ServiceGenerator")

我仍然找到了java.lang.NoClassDefFoundError。 我仍然无法弄清楚为什么会发生这件事。 有人能帮助我吗?

我附上调用服务生成器的GANT脚本

/**
 * Gant Script for generating Service Class based on Artifact
 * This Script was used for auto generate service class which is needed to handle basic transactional statements such as:
 * - AuditTrail for tables
 * - Logging before insert / update on tables
 */
includeTargets << grailsScript("_GrailsCreateArtifacts")
includeTargets << new File("${myPluginPluginDir}/scripts/GenerateExt.groovy")



target ('main': "Generates the CRUD service for a specified domain class") {
    depends(checkVersion, parseArguments, packageApp,classpath,configureProxy, 
            loadApp, configureApp, compile)

    promptForName(type: "Domain Class")
    generateViews = false
    generateForName = argsMap["params"][0]
    generateForOne()
}
setDefaultTarget(main)

任何帮助将不胜感激

由于

1 个答案:

答案 0 :(得分:1)

我终于完成了!

这是您想要做的一个示例:grails-flex-scaffold-script

这是我的实施:

*为您的插件名称

更改$ userInterfacePluginDir

将这些文件放在脚本中:

GenerateService.groovy

includeTargets << grailsScript("_GrailsInit")
includeTargets << grailsScript("_GrailsCreateArtifacts")
includeTargets << new File("$userInterfacePluginDir/scripts/_GrailsGenerateService.groovy")

target ('default': "Generates the service for a specified domain class") {
depends(checkVersion, parseArguments, packageApp)
promptForName(type: "Domain Class")
generateForName = argsMap["params"][0]
generateServiceForOne()
}

_GrailsGenerateService.groovy

import org.codehaus.groovy.grails.commons.GrailsDomainClass;
import org.codehaus.groovy.grails.scaffolding.*
import org.springframework.core.io.AbstractResource;
import org.springframework.core.io.FileSystemResource;
import grails.util.GrailsNameUtils

/**
 * Gant script that generates a service for a given domain class
 *
 * @author Martín Caballero
 *
 */

includeTargets << grailsScript("_GrailsBootstrap")

generateForName = null

target(generateServiceForOne: "Generates service for only one domain class.") {
    depends(loadApp)

    def name = generateForName
    name = name.indexOf('.') > 0 ? name : GrailsNameUtils.getClassNameRepresentation(name)
    def domainClass = grailsApp.getDomainClass(name)

    if (!domainClass) {
        grailsConsole.updateStatus "Domain class not found in grails-app/domain, trying hibernate mapped classes..."
        bootstrap()
        domainClass = grailsApp.getDomainClass(name)
    }

    if (domainClass) {
        generateServiceForDomainClass(domainClass)
        event("StatusFinal", ["Finished generation for domain class ${domainClass.fullName}"])
    }
    else {
        event("StatusFinal", ["No domain class found for name ${name}. Please try again and enter a valid domain class name"])
        exit(1)
    }
}

def generateServiceForDomainClass(domainClass) {
    UserInterfaceTemplateGenerator = classLoader.loadClass('plugin.ui.scaffold.UserInterfaceTemplateGenerator')
    def templateGenerator = UserInterfaceTemplateGenerator.newInstance(classLoader)
    templateGenerator.grailsApplication = grailsApp
    templateGenerator.pluginManager = pluginManager

    event("StatusUpdate", ["Generating service for domain class ${domainClass.fullName}"])
    templateGenerator.generateService(domainClass, basedir)
    event("GenerateServiceEnd", [domainClass.fullName])
}

UserInterfaceTemplateGenerator :(辅助类 - 扩展DefaultGrailsTemplateGenerator)

package plugin.ui.scaffold

import org.codehaus.groovy.grails.scaffolding.DefaultGrailsTemplateGenerator;
import grails.build.logging.GrailsConsole
import grails.util.BuildSettingsHolder
import groovy.text.SimpleTemplateEngine
import groovy.text.Template
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.codehaus.groovy.grails.commons.GrailsApplication
import org.codehaus.groovy.grails.commons.GrailsDomainClass
import org.codehaus.groovy.grails.plugins.GrailsPluginManager
import org.codehaus.groovy.grails.plugins.PluginManagerAware
import org.springframework.context.ResourceLoaderAware
import org.springframework.core.io.ClassPathResource
import org.springframework.core.io.FileSystemResource
import org.springframework.core.io.ResourceLoader
import org.springframework.core.io.support.PathMatchingResourcePatternResolver
import org.springframework.util.Assert
import org.springframework.core.io.AbstractResource
import org.codehaus.groovy.grails.scaffolding.SimpleDomainClassPropertyComparator
import org.codehaus.groovy.grails.scaffolding.DomainClassPropertyComparator

class UserInterfaceTemplateGenerator extends DefaultGrailsTemplateGenerator {
    public UserInterfaceTemplateGenerator(ClassLoader classLoader){
        super(classLoader)
    }

    void generateService(GrailsDomainClass domainClass, String destdir) {
        Assert.hasText destdir, "Argument [destdir] not specified"

        if (domainClass) {
            def fullName = domainClass.fullName
            def pkg = ""
            def pos = fullName.lastIndexOf('.')
            if (pos != -1) {
                // Package name with trailing '.'
                pkg = fullName[0..pos]
            }

            def destFile = new File("${destdir}/grails-app/services/${pkg.replace('.' as char, '/' as char)}${domainClass.shortName}Service.groovy")
            if (canWrite(destFile)) {
                destFile.parentFile.mkdirs()

                destFile.withWriter { w ->
                    generateService(domainClass, w)
                }

                LOG.info("Controller generated at ${destFile}")
            }
        }
    }

    void generateService(GrailsDomainClass domainClass, Writer out) {
        def templateText = getTemplateText("Service.groovy")

        boolean hasHibernate =pluginManager?.hasGrailsPlugin('hibernate')
        def binding = [pluginManager: pluginManager,
                       packageName: domainClass.packageName,
                       domainClass: domainClass,
                       className: domainClass.shortName,
                       propertyName: getPropertyName(domainClass),
                       comparator: hasHibernate ? DomainClassPropertyComparator : SimpleDomainClassPropertyComparator]

        def t = engine.createTemplate(templateText)
        t.make(binding).writeTo(out)
    }

    protected canWrite(File testFile) {
        if (!overwrite && testFile.exists()) {
            try {
                def response = GrailsConsole.getInstance().userInput("File ${makeRelativeIfPossible(testFile.absolutePath, basedir)} already exists. Overwrite?",['y','n','a'] as String[])
                overwrite = overwrite || response == "a"
                return overwrite || response == "y"
            }
            catch (Exception e) {
                // failure to read from standard in means we're probably running from an automation tool like a build server
                return true
            }
        }
        return true
    }

    protected String getPropertyName(GrailsDomainClass domainClass) { "${domainClass.propertyName}${domainSuffix}" }

}

最后,这是我的模板:(把它放在src / templates / scaffolding /中)

Service.groovy

<%import org.codehaus.groovy.grails.commons.GrailsClassUtils;%>
<%=packageName ? "package ${packageName}\n\n" : ''%>
class ${className}Service {

    def getTable() {
        def query = {
            <%
                def searchFields = GrailsClassUtils.getStaticPropertyValue(domainClass.clazz, 'search' )
                if(searchFields)
                {
            %>
                    if (params.q) {
                        or{
                        <%searchFields.each { field ->%>
                            ilike("${field}", '%' + params.q + '%')
                        <%}%>
                        }
                    }
            <%  }   %>
            if (params.sort){
                order(params.sort,params.order)
            }
        }
        def criteria = ${className}.createCriteria()
        return criteria.list(query, max: params.max, offset: params.offset)
    }
}

然后,您将该命令用作“grails generate-service yourdomainclass”

希望有所帮助!

这是答案的基本要点:

UserInterfaceTemplateGenerator = classLoader.loadClass('plugin.ui.scaffold.UserInterfaceTemplateGenerator')
def templateGenerator = UserInterfaceTemplateGenerator.newInstance(classLoader)