My approach:
import hudson.plugins.audit_trail.AuditTrailPlugin
import hudson.plugins.jobConfigHistory.JobConfigHistory
import net.sf.json.JSONObject
def auditTrialPlugin = Jenkins.getInstance().getPlugin(AuditTrailPlugin.class)
// println(auditTrialPlugin.getConfigXml().asString())
println("Going to configure...")
def logger = new JSONObject()
logger.put("log", "Vibin")
logger.put("limit", "1")
logger.put("count", "2")
logger.put("stapler-class", "hudson.plugins.audit_trail.LogFileAuditLogger")
logger.put("\$class", "hudson.plugins.audit_trail.LogFileAuditLogger")
def plugin = new JSONObject()
plugin.put("name", "audit-trail")
plugin.put("pattern", "")
plugin.put("logBuildCause", true)
plugin.put("loggers", logger)
auditTrialPlugin.configure(null, plugin)
Error happening:
java.lang.NoSuchMethodException: hudson.plugins.audit_trail.LogFileAuditLogger.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.newInstance(Class.java:412)
Caused: java.lang.InstantiationException: hudson.plugins.audit_trail.LogFileAuditLogger
at java.lang.Class.newInstance(Class.java:427)
at hudson.model.Descriptor.newInstance(Descriptor.java:578)
Caused: java.lang.Error: Failed to instantiate class hudson.plugins.audit_trail.LogFileAuditLogger from {"log":"Vibin","limit":"1","count":"2","stapler-class":"hudson.plugins.audit_trail.LogFileAuditLogger","$class":"hudson.plugins.audit_trail.LogFileAuditLogger"}
at hudson.model.Descriptor.newInstance(Descriptor.java:600)
at hudson.model.Descriptor.newInstancesFromHeteroList(Descriptor.java:1055)
at hudson.model.Descriptor.newInstancesFromHeteroList(Descriptor.java:1017)
at hudson.plugins.audit_trail.AuditTrailPlugin.configure(AuditTrailPlugin.java:78)
at hudson.plugins.audit_trail.AuditTrailPlugin$configure$1.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
at Script1.run(Script1.groovy:24)
I tried to follow the code base of the plugin which I found on GitHub. There is a 'configure' function for the plugin which I tried to use which isn't working.
Codebase of plugin: GitHub link
Try this:
import jenkins.model.*;
import hudson.plugins.audit_trail.AuditTrailPlugin;
import hudson.plugins.audit_trail.LogFileAuditLogger;
def log = "Vibin"
def limit = 1
def count = 2
LogFileAuditLogger logFileAuditLogger = new LogFileAuditLogger(log, limit, count)
Jenkins j = Jenkins.getInstance();
AuditTrailPlugin plugin = j.getPlugin(AuditTrailPlugin.class);
plugin.loggers.clear()
plugin.loggers.add(logFileAuditLogger)
plugin.pattern = "" // empty pattern?
plugin.save()
plugin.start()
I think using LogFileAuditLogger class is more clear than 'configure' function.
Related
I'm trying to add a Snyk installation to Jenkins using groovy. The plugin is installed and I can see the installation option in Global Tool Configuration:
The problem is the Descriptor is not available until I manually add the installer and click Save. If I don't do this task manually, which I want to prevent, it causes my code to fail with the following error message "Cannot invoke method setInstallations() on null object"
My code:
import hudson.model.*
import jenkins.model.*
import hudson.tools.*
import hudson.tasks.*
import io.snyk.jenkins.tools.SnykInstaller
import io.snyk.jenkins.tools.SnykInstallation
def snyk_name = "Snyk"
def snyk_home = ""
def snyk_installer = new SnykInstaller("", "latest", 24)
def snyk_properties = new InstallSourceProperty([snyk_installer])
def instance = Jenkins.getInstance()
println("[init.groovy.d] START Configuring Snyk Installation...")
// Get the GlobalConfiguration descriptor of Snyk plugin.
def snyk_conf = instance.getDescriptor("io.snyk.jenkins.SnykStepBuilder.SnykStepBuilderDescriptor")
def snyk_inst = new SnykInstallation(
snyk_name,
snyk_home,
[snyk_properties]
)
// Only add the new Snyk setting if it does not exist - do not overwrite existing config
def snyk_installations = snyk_conf.getInstallations()
def snyk_inst_exists = false
snyk_installations.each {
installation = (SnykInstallation) it
if (snyk_inst.getName() == installation.getName()) {
snyk_inst_exists = true
println("Found existing installation: " + installation.getName())
}
}
if (!snyk_inst_exists) {
snyk_installations += snyk_inst
snyk_conf.setInstallations((SnykInstallation[]) snyk_installations)
snyk_conf.save()
}
// Save the state
instance.save()
println("[init.groovy.d] END")
Is there any way to do what I want programmatically?
After testing your groovy on my local Jenkins (v 2.263.1) I came up with the below which then worked for me:
import hudson.model.*
import jenkins.model.*
import hudson.tools.*
import hudson.tasks.*
import io.snyk.jenkins.tools.*
def instance = Jenkins.getInstance()
def snyk_name = "SnykLatest"
def snyk_home = ""
def snyk_installer = new SnykInstaller("", "latest", 24L, null)
def snyk_properties = new InstallSourceProperty([snyk_installer])
println("[init.groovy.d] START Configuring Snyk Installation...")
// Get the GlobalConfiguration descriptor of Snyk plugin.
def snyk_conf = instance.getDescriptor("io.snyk.jenkins.tools.SnykInstallation")
def snyk_inst = new SnykInstallation(
snyk_name,
snyk_home,
[snyk_properties]
)
// Only add the new Snyk setting if it does not exist - do not overwrite existing config
def snyk_installations = snyk_conf.getInstallations()
def snyk_inst_exists = false
snyk_installations.each {
installation = (SnykInstallation) it
if (snyk_inst.getName() == installation.getName()) {
snyk_inst_exists = true
println("Found existing installation: " + installation.getName())
}
}
if (!snyk_inst_exists) {
snyk_installations += snyk_inst
snyk_conf.setInstallations((SnykInstallation[]) snyk_installations)
snyk_conf.save()
}
// Save the state
instance.save()
println("[init.groovy.d] END")
In basic Terms the SnykInstaller was expecting 4 values not 3. Groovy also took the 3rd value as an Integer when it was expecting a Long Value.
References:
https://javadoc.jenkins.io/plugin/snyk-security-scanner/io/snyk/jenkins/tools/SnykInstaller.html
https://github.com/jenkinsci/snyk-security-scanner-plugin/blob/master/src/main/java/io/snyk/jenkins/tools/SnykInstaller.java
https://github.com/jenkinsci/snyk-security-scanner-plugin/blob/master/src/main/java/io/snyk/jenkins/tools/PlatformItem.java
I was trying to configure artifactory in Jenkins using groovy init scripts, this is my script which I'm trying to execute
import jenkins.model.*
import org.jfrog.*
import org.jfrog.hudson.*
import org.jfrog.hudson.util.Credentials;
def inst = Jenkins.getInstance()
def desc = inst.getDescriptor("org.jfrog.hudson.ArtifactoryBuilder")
def deployerCredentials = new Credentials("admin", "password")
def resolverCredentials = new Credentials("", "")
def sinst = [new ArtifactoryServer(
"server-id",
"http://localhost:8081/artifactory",
deployerCredentials,
resolverCredentials,
300,
false,
false,
false,
1)
]
desc.setArtifactoryServers(sinst)
desc.save()
But I was getting the following error
groovy.lang.GroovyRuntimeException: Could not find matching constructor for: org.jfrog.hudson.CredentialsConfig(java.lang.String, java.lang.String)
at groovy.lang.MetaClassImpl.invokeConstructor(MetaClassImpl.java:1732)
at groovy.lang.MetaClassImpl.invokeConstructor(MetaClassImpl.java:1532)
at org.codehaus.groovy.runtime.callsite.MetaClassConstructorSite.callConstructor(MetaClassConstructorSite.java:49)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:60)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:235)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:255)
at Script1.run(Script1.groovy:17)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:585)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:623)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:594)
at hudson.util.RemotingDiagnostics$Script.call(RemotingDiagnostics.java:142)
at hudson.util.RemotingDiagnostics$Script.call(RemotingDiagnostics.java:114)
at hudson.remoting.LocalChannel.call(LocalChannel.java:45)
at hudson.util.RemotingDiagnostics.executeGroovy(RemotingDiagnostics.java:111)
at jenkins.model.Jenkins._doScript(Jenkins.java:4350)
at jenkins.model.Jenkins.doScriptText(Jenkins.java:4328)
at java.lang.invoke.MethodHandle.invokeWithArguments(MethodHandle.java:627)
at org.kohsuke.stapler.Function$MethodFunction.invoke(Function.java:343)
at org.kohsuke.stapler.Function.bindAndInvoke(Function.java:184)
at org.kohsuke.stapler.Function.bindAndInvokeAndServeResponse(Function.java:117)
at org.kohsuke.stapler.MetaClass$1.doDispatch(MetaClass.java:129)
at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:58)
at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:715)
at org.kohsuke.stapler.Stapler.invoke(Stapler.java:845)
at org.kohsuke.stapler.Stapler.invoke(Stapler.java:649)
at org.kohsuke.stapler.Stapler.service(Stapler.java:238)
It would be great if anyone could help me figuring out this issue.
this one works for me
//artifactory
import jenkins.model.*
import org.jfrog.*
import org.jfrog.hudson.*
import org.jfrog.hudson.util.Credentials;
inst = Jenkins.getInstance()
desc = inst.getDescriptor("org.jfrog.hudson.ArtifactoryBuilder")
deployerCredentials = new CredentialsConfig("user", "password","1",true)
sinst = [new ArtifactoryServer(
"1",
"https://artifactory-url/",
deployerCredentials,
null,
300,
false ,
3)]
desc.setUseCredentialsPlugin(false)
desc.setArtifactoryServers(sinst)
desc.save()
I am trying to send mail using javamail from my Grails application (via a service).
Both the from and to addresses being used have the organization domain names.
The same code, when run via command line as a groovy script (on the same server) works as expected.
However, running on the grails server (under war mode) produces the following exception :
javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay for ---#---.com
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1873)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1120)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at javax.mail.Transport$send.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:40)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:124)
at cs.MailService.mail(MailService.groovy:66)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at
The code is written as follows :
import javax.mail.internet.*
import javax.mail.*
import javax.activation.*
class Mailer {
def static mail(String toAddress, String subject, String body) {
println "mail called"
println "${toAddress}, ${subject}, ${body}"
try {
def fromAddress = "---#---.com"
def properties = new Properties()
properties.setProperty("mail.transport.protocol","smtp")
properties.setProperty("mail.smtp.host","---------")
def sessionInstance = Session.getDefaultInstance(properties,null);
def msg = new MimeMessage(sessionInstance)
def stringTokenizer = new StringTokenizer(toAddress,";")
def toAddressList = []
while(stringTokenizer.hasMoreElements()){
toAddressList.add(new InternetAddress(stringTokenizer.nextElement().toString()));
}
def to = new InternetAddress[toAddressList.size()]
to = (InternetAddress[]) toAddressList.toArray(to)
msg.setRecipients(MimeMessage.RecipientType.TO,to)
def from = new InternetAddress(fromAddress)
msg.setFrom(from);
msg.setSubject(subject)
def mimeMultipart = new MimeMultipart()
def mimeBodyPart = new MimeBodyPart()
mimeBodyPart.setContent("<p style='font-family:calibri;color:blue;font-size:20px;text-align:center;'>"+body+"</p>", "text/html")
mimeMultipart.addBodyPart(mimeBodyPart)
msg.setContent(mimeMultipart)
def transporter = sessionInstance.getTransport("smtp")
transporter.connect()
transporter.send(msg)
} catch(Exception e) {
e.printStackTrace()
}
}
public static void main(String[] args) {
def to="---#---.com"
def subject="Call Scheduler Notification"
def body='<font face="Segoe UI"><p><b><font color="#6B0667">Hi --- ---,<br><br>Your Call (id: 1281) Was Updated Successfully</b></font></p><table cellpadding="10" bgcolor="#B799B6"><caption><b><font color="#6B0667">Call Details</font></b></caption><tr><td><b>Title</b></td><td>---------</td></tr><tr><td><b>Start</b></td><td>---------</td></tr><tr><td><b>End</b></td><td>---------</td></tr><tr><td><b>Number</b></td><td>---------</td></tr><tr><td><b>Passcode</b></td><td>---------</td></tr><td><b>Special Instructions</b></td><td></td></tr><td><b>Callback Number</b></td><td>---------</td></tr></table><br><p><b><font color="#6B0667">Regards<br>Call Scheduler</b></font></p></font>'
mail(to, subject, body);
}
}
How do i get past this error ?
Update : Still not entirely sure what was wrong here. But resetting all the tcp/ip connections (from the mail server) resolved the issue.
You probably need to authenticate.
I don't know why it works from the command line.
This is with regard to activiti workflow timer jobs in grails application.
While starting the grails app with expired jobs, exception is thrown for normal grails features such as log and methods of domain classes.
For eg:
Caused by: groovy.lang.MissingPropertyException: No such property: log for class: com.service.common.UtilityService
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:49)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassGetPropertySite.getProperty(PogoMetaClassGetPropertySite.java:50)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:239)
at com.service.common.UtilityService.insertToQueue(UtilityService.groovy:370)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.activiti.engine.impl.javax.el.BeanELResolver.invoke(BeanELResolver.java:479)
... 71 more
This happens in dev environment running the app from Spring STS. We are using activiti plugin 5.8.2 for grails (1.3.6)
After the web-app is started up completely, the jobs (schedule to a time after startup) run properly and no missing property exception is thrown.
Even though we can fix the of missing property issue for log by using private static final log = LogFactory.getLog(this) instead, then any reference to domain classes throw an error, like using get or find method.
eg:
Caused by: groovy.lang.MissingMethodException: No signature of method: static com.domain.wr.WorkRequest.read() is applicable for argument types: (java.lang.String) values: [44700]
Possible solutions: getId(), getAt(java.lang.String), setId(java.lang.Long), grep(java.lang.Object), each(groovy.lang.Closure), find(groovy.lang.Closure)
at groovy.lang.MetaClassImpl.invokeStaticMissingMethod(MetaClassImpl.java:1357)
at groovy.lang.MetaClassImpl.invokeStaticMethod(MetaClassImpl.java:1343)
at groovy.lang.ExpandoMetaClass.invokeStaticMethod(ExpandoMetaClass.java:1082)
at org.codehaus.groovy.runtime.callsite.StaticMetaClassSite.call(StaticMetaClassSite.java:50)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:40)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:124)
at com.service.common.UtilityService.insertToQueue(UtilityService.groovy:373)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.activiti.engine.impl.javax.el.BeanELResolver.invoke(BeanELResolver.java:479)
... 71 more
Activiti Configuration
Config.groovy
// Added by the Grails Activiti plugin:
activiti {
processEngineName = "activiti-engine-default"
databaseType = "oracle"
deploymentName = appName
history = "audit" // "none", "activity", "audit" or "full"
sessionUsernameKey = "username"
useFormKey = true
deploymentResources = ["classpath:activiti/escalation/WorkRequest.bpmn20.xml"]
}
Config.properties
activiti.processEngineName =activiti-engine-default
activiti.databaseSchemaUpdate =true
activiti.jobExecutorActivate =true
activiti.mailServerHost = "mail1.net"
activiti.mailServerPort = 25
activiti.mailServerUsername = ""
activiti.mailServerPassword = ""
activiti.mailServerDefaultFrom = ""
This is killing my application as a downtime makes the workflow unusable with timer tasks.
I had more or less the same problem, and in our case was caused by Activiti starting jobs execution before Spring injection being finished. That's why it only happens at startup: the job is accessing properties that are not there yet.
You can confirm that you are in the same situation by increasing the RETRIES_ in the ACT_RU_JOB table after the app has finished bootstraping and see if the jobs execute successfully.
If this is your case, I think the only option is to upgrade the plugin and if still fails, create a bug.
This issue got solved.
1) Edit Config.groovy and disable activiti during startup
activiti {
processEngineName = "activiti-engine-default"
databaseType = "oracle"
disabled = true
deploymentName = appName
sessionUsernameKey = "username"
useFormKey = true
deploymentResources = []
}
2) add the initialization of Activiti Objects in the init method of User BootStrap
def init = { servletContext ->
org.springframework.context.ApplicationContext ctx = ServletContextHolder.getServletContext().getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT)
def bb = new grails.spring.BeanBuilder(ctx)
bb.beans {
//println "Activiti Process Engine Initialization..."
customDbIdGenerator(com.mycompany.activiti.customDbIdGenerator){
idBlockSize=CH.config.activiti.idBlockSize?:100
}
processEngineConfiguration(org.activiti.spring.SpringProcessEngineConfiguration) {
processEngineName = CH.config.activiti.processEngineName?:ActivitiConstants.DEFAULT_PROCESS_ENGINE_NAME
databaseType = CH.config.activiti.databaseType?:ActivitiConstants.DEFAULT_DATABASE_TYPE
databaseSchemaUpdate = CH.config.activiti.databaseSchemaUpdate ? CH.config.activiti.databaseSchemaUpdate.toString() : ActivitiConstants.DEFAULT_DATABASE_SCHEMA_UPDATE
deploymentName = CH.config.activiti.deploymentName?:ActivitiConstants.DEFAULT_DEPLOYMENT_NAME
deploymentResources = CH.config.activiti.deploymentResources?:ActivitiConstants.DEFAULT_DEPLOYMENT_RESOURCES
jobExecutorActivate = CH.config.activiti.jobExecutorActivate?:ActivitiConstants.DEFAULT_JOB_EXECUTOR_ACTIVATE
history = CH.config.activiti.history?:ActivitiConstants.DEFAULT_HISTORY
mailServerHost = CH.config.activiti.mailServerHost?:ActivitiConstants.DEFAULT_MAIL_SERVER_HOST
mailServerPort = CH.config.activiti.mailServerPort?:ActivitiConstants.DEFAULT_MAIL_SERVER_PORT
mailServerUsername = CH.config.activiti.mailServerUsername
mailServerPassword = CH.config.activiti.mailServerPassword
mailServerDefaultFrom = CH.config.activiti.mailServerDefaultFrom?:ActivitiConstants.DEFAULT_MAIL_SERVER_FROM
dataSource = ref("dataSource")
transactionManager = ref("transactionManager")
idGenerator= ref("customDbIdGenerator")
}
processEngine(org.activiti.spring.ProcessEngineFactoryBean) {
processEngineConfiguration = ref("processEngineConfiguration")
}
runtimeService(processEngine:"getRuntimeService")
repositoryService(processEngine:"getRepositoryService")
taskService(processEngine:"getTaskService")
managementService(processEngine:"getManagementService")
identityService(processEngine:"getIdentityService")
historyService(processEngine:"getHistoryService")
formService(processEngine:"getFormService")
activitiService(org.grails.activiti.ActivitiService) {
runtimeService = ref("runtimeService")
taskService = ref("taskService")
identityService = ref("identityService")
formService = ref("formService")
}
}
println "## Registering Beans ##";
bb.registerBeans(ctx);
ctx.getBean("processEngine");
println "Bean Count2 "+ctx.getBeanDefinitionCount();
}
Please note that DB Id Generator used is custom and can be replaced by the default one.
I'm trying to debug a Grails application. Unfortunately, I have no prior experience in said language.
When I do grails generate-all org.example.Book, I get back a vague error:
Generating controller for domain class org.example.Book ...
groovy.lang.MissingPropertyException: No such property: Event for class: SimpleTemplateScript6
at SimpleTemplateScript6.run(SimpleTemplateScript6.groovy:22)
at _GrailsGenerate_groovy.generateForDomainClass(_GrailsGenerate_groovy:88)
at _GrailsGenerate_groovy$_run_closure1.doCall(_GrailsGenerate_groovy:48)
at GenerateAll$_run_closure1.doCall(GenerateAll.groovy:42)
at gant.Gant$_dispatch_closure5.doCall(Gant.groovy:381)
at gant.Gant$_dispatch_closure7.doCall(Gant.groovy:415)
at gant.Gant$_dispatch_closure7.doCall(Gant.groovy)
at gant.Gant.withBuildListeners(Gant.groovy:427)
at gant.Gant.this$2$withBuildListeners(Gant.groovy)
at gant.Gant$this$2$withBuildListeners.callCurrent(Unknown Source)
at gant.Gant.dispatch(Gant.groovy:415)
at gant.Gant.this$2$dispatch(Gant.groovy)
at gant.Gant.invokeMethod(Gant.groovy)
at gant.Gant.executeTargets(Gant.groovy:590)
at gant.Gant.executeTargets(Gant.groovy:589)
Error running generate-all: No such property: Event for class: SimpleTemplateScript6
After looking at the generated org.example.BookController.groovy source, I noticed that it was not fully generated (stopped at List fields = []):
package org.example
// import needed for export plugin
import org.codehaus.groovy.grails.commons.ConfigurationHolder
class BookController {
...
def exportService
def export = {attrs ->
def response = attrs.response
List fields = []
This error appears to be caused by the following code in templates/scaffolding/Controller.groovy:
<%=packageName ? "package ${packageName}\n\n" : ''%>
// import needed for export plugin
import org.codehaus.groovy.grails.commons.ConfigurationHolder
class ${className}Controller {
static allowedMethods = [save: "POST", update: "POST", delete: "POST"]^M
def exportService
...
def export = {attrs ->
def response = attrs.response
List fields = []
<% excludedProps = Event.allEvents.toList() << 'version'
allowedNames = domainClass.persistentProperties*.name << 'id' << 'dateCreated' << 'lastUpdated'
props = domainClass.properties.findAll { allowedNames.contains(it.name) && !excludedProps.contains(it.name) && !Collection.isAssignableFrom(it.type) }
Collections.sort(props, comparator.constructors[0].newInstance([domainClass] as Object[]))
props.eachWithIndex {p, i -> %>fields.push("${p.name}"<%="\n"%><% } %>
Map labels = [:]
<% props.eachWithIndex { p, i -> %>labels.putAt("\${p.name}", "\${p.naturalName}")<%="\n "%><% } %>
Map formatters = [:]
Map parameters = [:]
response.setHeader("Content-disposition", "attachment; filename=${domainClass.propertyName}s.\${attrs.extension}")
if("\${attrs.extension}" == "xml") {
exportService.export(attrs.format, response.outputStream, attrs.exportList, fields, [:], formatters, parameters)
} else {
exportService.export(attrs.format, response.outputStream, attrs.exportList, fields, labels, formatters, parameters)
}
}
...
}
It appears that the def export {} block seems to be causing problems. Is there something wrong with the above code?
What is the Event class? Is there an import for it?
Check your domain class for syntax errors. Make sure that in your domain class, you've included necessary packages, in your case, package org.example.