How to dynamically add all methods of a class into another class - jenkins

I have a global shared library on Jenkins implicitly loaded on all pipelines, then my Jenkinsfile is like that:
new com.company.Pipeline()()
And then the shared library has on directory src/com/company some files, below the Pipeline.groovy class:
package com.company
import static Utils.*
def call() {
// some stuff here...
}
The problem is, this way I have to static declare all methods, thus I lose the context and cannot access jenkins' methods easly without the Pipeline class' instance. As you can see here they passing this to the method mvn.
Thinking of avoid this I was wondering about dynamically add all methods as closures by calling Utils.install this instead of using import static Utils.*, then my Utils.groovy is something like that:
package com.company
private Utils() {}
static def install(def instance) {
def utils = new Utils()
// Some extra check needed here I know, but it is not the problem now
for (def method in (utils.metaClass.methods*.name as Set) - (instance.metaClass.methods*.name as Set)) {
def closure = utils.&"$method"
closure.delegate = instance
instance.metaClass."$method" = closure
}
}
def someMethod() {
// here I want to use sh(), tool(), and other stuff freely.
}
But it raises an GStringImpl cannot be cast to String error, I believe .& do not work with variables, how can I convert a method into closure having the method name on a variable? I have the MetaMethod mostly being a CachedMethod instance, if it were possible to turn it a ClosureMetaMethod instance maybe the problem can be solved, but whenever I search for method to closure conversion for groovy I just found the .& solution!
If I use instance.metaClass.someMethod = utils.&someMethod it do work, but I want it to be dinamic as I add new methods without needing to worry about sharing it.

There is a way to do it dynamically. Notation utils.&someMethod returns a MethodClosure object that can be simply instantiated with its constructor:
MethodClosure(Object owner, String method)
Consider following example:
class Utils {
def foo() {
println "Hello, Foo!"
}
def bar() {
println "Hello, Bar!"
}
}
class Consumer {
}
def instance = new Consumer()
def utils = new Utils()
(utils.metaClass.methods*.name - instance.metaClass.methods*.name).each { method ->
def closure = new MethodClosure(utils, method)
closure.delegate = instance
instance.metaClass."$method" = closure
}
instance.foo() // Prints "Hello, Foo!"
instance.bar() // Prints "Hello, Bar!"
In this example I use def closure = new MethodClosure(utils, method) to get object method reference and then add this method to instance object. I hope it helps.

Related

Jenkins Shared Library Immutable Singleton

I have a Singleton patter class in my Jenkins shared library:
public class Configuration {
private static final INSTANCE = new Configuration()
static getInstance() { return INSTANCE }
private Configuration() {
}
def initialize(env, params) {
Foo = params.FOO;
}
public String Foo = ''
}
Later I can call this from elsewhere using something like this:
Configuration.instance.initialize(env, params);
config = Configuration.instance;
println 'FOO: ' + config.Foo
Ideally, I want the benefit of the Singleton pattern, but I don't want some fields to be overridden by consumers.
First Attempt:
On first thought, I would think this would work:
public class Configuration {
private static final INSTANCE = new Configuration()
static getInstance() { return INSTANCE }
private Configuration() {
}
def initialize(env, params) {
INSTANCE.#Foo = params.FOO;
}
public final String Foo = ''
}
Error:
groovy.lang.GroovyRuntimeException: Cannot set the property 'Foo' because the backing field is final.
Second Attempt:
On Second thought, I would think initializing in the constructor would work, however I don't seem to have access to params and env, unless these are passed in from the vars function, via the initialize() method.
How can I make this Singleton class immutable, or its fields read only?
I think you Could:
Define your class with "implements Serializable", as documentation advices.
Implement the constructor that would accept 1 parameter of type BaseScript, and pass this to it upon instantiation, relative to that this (which you could call internal script) you can refer to script.params, script.env, etc. and I mean you don't HAVE to use initialize, you can do all you want in the c'tor.
But wait, please tell more:
why does CI/CD code need to have a Singleton?
You're passing its data as parameters [so it's not really an immutable entity :)]
Maybe you could "simply" create an immutable map out of your parameters....
Configuration as singleton feels as if you can delegate configuration management to ... configuration management service (consul, etcd, or others).
Please elaborate, it's very curious!
Also you referred to something as "consumers". are these library consumers? or people running the jobs?
Thank you!

How to access Job DSL's readFileFromWorkspace from a helper class?

I have a large number of Jenkins job definitions in Job DSL that all rely on some common functionality that I implemented in helper classes. This is the essence of the jobDsl step running these scripts:
jobDsl {
additionalClasspath('jobdsl/src/main/groovy')
targets('jobdsl/*.groovy')
sandbox(true)
}
One of the helper classes in jobdsl/src/main/groovy needs to read a file from the workspace, but it cannot access the readFileFromWorkspace function.
So this one wouldn't work:
class MyHelper {
static Closure processFile(String src) {
...
def txt = readFileFromWorkspace(src)
...
}
}
I have to take a closure parameter instead:
class MyHelper {
static Closure processFile(String src, Closure rffw) {
...
def txt = rffw(src)
...
}
}
Which makes the code calling this helper bloated:
MyHelper.processFile('foo.txt', { readFileFromWorkspace(it) })
Is there a way to make my class see readFileFromWorkspace? Actually, I couldn't even figure out to which class does this function belong to. Or whether is it a real function at all or something "magicly" defined by the DSL.
HelperClass is present in other file which is out of Job-dsl context. So to make it visible, try doing as below.
class MyHelper {
static Closure processFile(String src, def dslFactory) {
...
def txt = dslFactory.readFileFromWorkspace(src)
...
}
}
MyHelper.processFile('foo.txt', this)
The above code should work for you, else please revert to me if you encounter any problems.

Groovy object tracking for binding

I'm developing a Groovy library providing variable binding/syncronization with simple syntax and rich event handler.
Firstly I'm aiming to archive running the following:
def a = 1
def b = 1
def c = 1
a bind { b + c }
assert a==2 & b==1 & c==1
b = 3
assert a==4 & b==3 & c==1
c = -1
assert a==2 & b==3 & c==-1
I'd like avoid Java FX approach of providing additional classes but rather enhance objects with this functionality.
I'm stuck at finding some tracking of objects. Groovy doesn't feature overload of assignment expression.
Currently I see solution in heavy AST transformation (maybe dsld might help).
Maybe there is some object tracking, events or whatever, I've missed?
I'm presuming you are writing your code using scripts. Did what you wanted with the following ideas:
Instead of binding values to keys using the Script.binding, it is better if you create a Variable class which represents both the value and the variable name;
Every method called on the Variable object gets delegated to its value;
A Listener class which encapsulates a reference to the updating operation AND the Variable object which needs to be updated;
An updateListeners() method, to, well, update the listeners;
A bind(closure) method that just bypasses the closure to the variable object. It could pretty much be dropped and written as a { b + c };
class Listener { Closure operation; Variable variable }
class Variable implements GroovyInterceptable {
String name; def value
def invokeMethod(String method, args) {
def var = args[0]
var.class == Variable ?
value."$method"(var.value) : value."$method"(var)
}
}
Variable.metaClass.call = { Closure operation ->
binding['listeners'] <<
new Listener(operation: operation, variable: delegate)
updateListeners()
}
def bind(Closure operation) { operation }
def updateListeners() {
binding.listeners.each {
it.variable.value = it.operation()
}
}
void setProperty(String prop, value) {
if (!binding.hasVariable('listeners')) binding['listeners'] = []
binding[prop] = new Variable(name: prop, value: value)
updateListeners()
}
And your tests worked like a charm.

Grails: why would this service class be null?

Given this grossly simplified rendition of the setup:
package net.myexample.plugin
class MyExampleService {
Map doMunge(Map m) {
// do stuff to 'm'
return m
}
}
/****************************** BREAK: NEXT FILE ******************************/
package net.myexample.plugin
class MyTagLib {
static namespace = 'p'
def myExampleService
def tag = { attrs, body ->
def m = doMungeAndFilter(attrs.remove('m'))
out << g.render(template: '/template', plugin: 'my-example-plugin', model: m)
}
Map doMungeAndFilter(def m) {
def mm = myExampleService.doMunge(m)
// do stuff to 'm'
return mm
}
}
/****************************** BREAK: NEXT FILE ******************************/
package net.myexample.app
import net.myexample.plugin.MyExampleService
class MyExampleService extends net.myexample.plugin.MyExampleService {
def doMunge(def m) {
def mm = super.doMunge(m)
// do more stuff to 'mm'
return mm
}
}
/****************************** BREAK: NEXT FILE ******************************/
package net.myexample.app
import net.myexample.plugin.MyTagLib
class MyTagLib extends net.myexample.plugin.MyTagLib {
static namespace = 'a'
def myExampleService
def tag = { attrs, body ->
def m = doMungeAndFilter(attrs.remove('m'))
out << g.render(template: '/template', plugin: 'my-example-plugin', model: m)
}
Map doMungeAndFilter(def m) {
def mm = super.doMungeAndFilter(m)
// do more stuff to 'mm'
return mm
}
}
/**
* But we get an exception that cites that it cannot call 'doMunge' on a null
* object -- which could only be 'myExampleService'
*/
Why would the service appear to be null when the method on the app's taglib calls its superclass (the taglib on the plugin), which in turn calls the method on the service?
The best theory I could come up with is that the service is not actually being instantiated in the app's taglib class because there are no explicit references to it aside from the def. I presume that this is the case because if I move all the logic from service class's method into the taglib's method, it works as expected.
(For the sake of painting a complete picture: MyExampleService.doMunge is called in other places, whereas the subsequent filtering (in MyTagLib.doMungeAndFilter) is only needed for the taglib.)
Alternatively: if I move doMungeAndFilter into another service class, creating the base version in the plugin and extending it in the app, that works fine. Which I suppose is an acceptable conclusion, though it feels like bloat to create another service class just to support the taglib like that.
Thoughts? Tips? Glaring errors or omissions?
Remove the def myExampleService from the subclass taglib. A property like that in Groovy compiles to a private field plus a public getter and setter, so in the superclass taglib you have implicitly
private Object myExampleService;
public void setMyExampleService(Object svc) {
this.myExampleService = svc;
}
// getter similar
When you declare myExampleService again in the subclass the subclass gets its own private field (with the same name) and the setter gets overridden to store the supplied value in this subclass field instead of the superclass one. Spring calls the setter to inject the service, so the end result is that the superclass private myExampleService never gets set, hence the null pointer exception when trying to call myExampleService.doMunge in the superclass.
The subclass has access to the superclass property via the inherited getter and setter so it doesn't need to re-declare it.
This is just a quick guess, but is you taglib class file located under /grails-app/taglib, or somewhere in your /src directory? I've noticed I can't get services to inject (automatically, at least) into classes located outside the /grails-app folder.

Add methods to controllers

In a Grails application I would like to add a foo() method to all my controller classes. I know that I can do this inside a plugin's doWithDynamicMethods closure using code like:
application.controllerClasses.toList()*.metaClass*.foo = { println 'foo called' }
However, I don't want to create a plugin just for this purpose. Is there anywhere else I can do this. I suspect it might be possible within the init closure of BootStrap.groovy, but I don't know how to get access to the GrailsApplication instance in this closure.
Thanks,
Don
def grailsApplication = org.codehaus.groovy.grails.commons.ApplicationHolder.application
The question was asked a long time ago, so my answer might not have been possible back then - but now it's April 2014. This code shows the most straightforward way of adding a method to all your controllers (from within BootStrap.init):
grailsApplication.controllerClasses.each { controllerClass ->
if (controllerClass.clazz.name.contains("org.idurkan.foo")) {
controllerClass.metaClass.respondError = { String message, int status = 404 ->
response.status = status
render([errorMessage: message] as JSON)
}
}
}
In BootStrap.groovy, inject grailsApplication like this: def grailsApplication
Make a call like mine above, substituting your own package name - to avoid messing around with plugins' classes.
Now in any controller you can use the repondError closure (invoke it like a method).
Note this does not add an action! It's just a utility closure/method available in every
controller.
class BootStrap {
def grailsApplication
def init = { servletContext ->
...
}
}

Resources