0

I have the following in a groovy file...

// jenkins/Application.groovy
package jenkins

class Application{
    String name
    Application(name){
        this.name = name
    }
}

I am trying to import it and I have tried these but none seem to work. These are all in jenkins/Test.groovy

final GroovyScriptEngineImpl engine = (GroovyScriptEngineImpl) this.scriptingEngines.getEngineByName("groovy");
GroovyClassLoader classLoader = engine.getClassLoader();
classLoader.parseClass(new GroovyCodeSource("./jenkins/Application.groovy"))
engine.setClassLoader(classLoader)

This gives..

Script1.groovy: 17: unable to resolve class Application

Then I tried...

// jenkins/Application.groovy
// Added
return { Application }
// jenkins/Test.groovy
app = load "./jenkins/Application.groovy"

def dna = new app.Application("blah")

and I get...

Script1.groovy: 11: unable to resolve class app.Application

How do I import a call in a Jenkins GroovyScript?

Update

I changed my code to the following (and moved into a domain folder)...

app = load "./jenkins/domain/Application.groovy"
def dna = app.newInstance([name:"blah"] as Object[])

When I run I get...

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use staticMethod org.codehaus.groovy.runtime.DefaultGroovyMethods newInstance java.lang.Class java.lang.Object[]

JGleason
  • 3,067
  • 6
  • 20
  • 54

1 Answers1

1

the idea

you could return from loaded script - the class (not an instance)

then to create new instance you could call class.newInstance( Object [] argList )

http://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/Class.html#newInstance(java.lang.Object[])

so, theoretically this should work:

./jenkins/Application.groovy


class Application{
    String name
    Application(name){
        this.name = name
    }
}

return Application.class

pipeline:

def app = load "./jenkins/Application.groovy"
def dna = app.newInstance( "blah" )
daggett
  • 26,404
  • 3
  • 40
  • 56
  • Thanks! any idea how I would use the type in a constructor? I know groovy is not typed but I was hoping I could use it – JGleason Jun 21 '19 at 12:58
  • Getting [ERROR] Exception in pipeline: No signature of method: java.lang.Class.newInstance() is applicable for argument types: (java.util.ArrayList) values: [[103740]] Possible solutions: newInstance(), newInstance(), newInstance([Ljava.lang.Object;), isInstance(java.lang.Object) – JGleason Jun 21 '19 at 13:10
  • For your update there is a standard solution - administrator. – daggett Jun 21 '19 at 15:56
  • Not sure I follow does that mean an admin has to configure something because that probably won't happen – JGleason Jun 21 '19 at 17:22
  • It's quite standard security issue. Just search over the Internet. Jenkins restricts calling some methods. https://stackoverflow.com/questions/38276341/jenkins-ci-pipeline-scripts-not-permitted-to-use-method-groovy-lang-groovyobject – daggett Jun 21 '19 at 18:16