Toni26
Toni26

Reputation: 605

How does scripted Jenkins Pipeline with Groovy work

stage('deploy') {
    steps {
        script {

            import java.net.URL;
            import java.net.URLConnection;

            def serviceURL = ""

            if (env.BRANCH_NAME == "master") {

                serviceURL="http://myserver:8100/jira/rest/plugins/1.0"
            }
            if (env.BRANCH_NAME == "develop") {

                serviceURL = "http://myserver:8100/jira/rest/plugins/1.0"
            }
            if(env.BRANCH_NAME.startsWith("release")
            {
                serviceURL="http://myserver:8100/jira/rest/plugins/1.0"
            }

            // Request to get token
            URL myURL = new URL(serviceURL+"?"+"os_authType=basic");
            HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();
  }

This is an extract of my jenkinsfile. It is written in Groovy . Right now I get this error:

WorkflowScript: 66: expecting ')', found 'URL' @ line 66, column 17.

It is complaining about this line:

URL myURL = new URL(serviceURL+"?"+"os_authType=basic");

I do not know why. But one thing I was wondering now. How does it actually work with imports. I mean normally you have to do

 import java.net.URL

How would it actually work with extern libraries which are not part of Java SDK. Normally you would put them on the classpath. How would that work with jenkinsfile scripted pipeline. So I wonder when you can actually use jenkinsfile with groovy or when to better create an own project and create job for it and then add it in the jenkinsfile.

Upvotes: 0

Views: 437

Answers (1)

injecteer
injecteer

Reputation: 20707

You don't have to import java.net.*, groovy imports them by default. https://groovy-lang.org/structure.html#_default_imports.

Your problem is a result of a missing ) in the line:

if(env.BRANCH_NAME.startsWith("release")

it should be

if(env.BRANCH_NAME.startsWith("release"))

The whole script should look like so in idiomatic Groovy:

stage('deploy') {
    steps {
        script {

            String serviceURL

            switch(env.BRANCH_NAME)
             case 'master':
             case 'develop':
                serviceURL = "http://myserver:8100/jira/rest/plugins/1.0"
                break
             case ~/^release.*$/:
                serviceURL = "http://myserver:8100/jira/rest/plugins/1.0"
                break
             default:
               throw new Exception( 'Unknown' )
            }

            // Request to get token
            "${serviceURL}?os_authType=basic".toURL().openConnection().with{
              if( 200 != responseCode ) return

              outputStream.withWriter{ it << jsonInputString }
           }
        }
     }
}

Here the withWriter{} takes care about stream flushing and closing.

Upvotes: 1

Related Questions