Search code examples
jenkinsgroovypipeline

How to make a workaround for the keyword 'use' in Groovy in a Jenkins Pipeline?


I have groovy application, and I am using the following code to make some json validations work:

 String method = "{\n" +
                "\"method\":\"filesContentReplacer\"," +
                "\"filesContentReplacer\":{\n" +
                "\"files\":[" +
                "{" +
                "\"path\":\"pom.xml\"," +
                "\"target\":\"1.9.0\"," +
                "\"replacement\":\"STF_SomeNumber\"" +
                "}" +
                "]" +
                "}" +
                "}"
        def json = new JsonSlurper().parseText(method)
        use(JsonSchema){
            assert json instanceof Map
            json.schema = (Map) executeReadJson([text: readFromResources('methods/filesContentReplacer.json')])
            Log.instance.debug( "json.schema:${json.schema}")
            assert json.conformsSchema()
        }

That is pure groovy code, based from this git repo: https://github.com/alexdeleon/groovy-json-schema

The problem is when I run the code on a jenkins pipeline, it throws the following error:

expected to call org.codehaus.groovy.runtime.GroovyCategorySupport.use but wound up catching org.jenkinsci.plugins.workflow.cps.CpsClosure2.call; see: https://jenkins.io/redirect/pipeline-cps-method-mismatches/

After some research, it turns out, that the guys who made this pipeline groovy language, have not made everything they should have, and the keyword 'use' is not supported.

Now I need somehow to make it work. Can you help me?

Also, if you need any more code, I will provide. But I basically just copied the 2 classes from the git into my project.

Thank you for your time.


Solution

  • don't have jenkins to test but here what you could try:

    1/

    org.codehaus.groovy.runtime.GroovyCategorySupport.use(JsonSchema){...}
    

    2/

    @NonCPS
    def myConformsSchema(String json, String schema){
      ...here put your code to validate json against schema
    }
    

    3/

    you could try to use static methods from https://github.com/alexdeleon/groovy-json-schema/blob/master/src/main/groovy/com/lumata/os/groovy/jsonschema/JsonSchema.groovy

    like this:

    def schema = executeReadJson(...)
    assert JsonSchema.conformsSchema(json, schema)