mmoghrabi
mmoghrabi

Reputation: 1291

how to get the list of jobs in Jenkins using java?

I have downloaded and configured Jenkins in a server, my problem is that i need to access Jenkins through Java to perform some process such as starting a job, returning the current working job and returning list of jobs in the server(all that using Json) i've tried several codes such as this but im getting no results, also i cant find a clear way to achieve that, is there is any clear API and example to do it?

Upvotes: 0

Views: 3012

Answers (1)

stefan.schwetschke
stefan.schwetschke

Reputation: 8932

You can use the Jenkins API over XML:

    import org.dom4j.io.*;
    import org.dom4j.*;
    import java.net.*;
    import java.util.*;

    public class Main {
        public static void main(String[] args) throws Exception {
            URL url = new URL("http://your-hudson-server.local/hudson/api/xml");
            Document dom = new SAXReader().read(url);

            for( Element job : (List<Element>)dom.getRootElement().elements("job")) {
                System.out.println(String.format("Job %s has status %s",
                    job.elementText("name"), job.elementText("color")));
            }
        }
    }

A complete example (with sources) can be found here.

If these examples don't work, you might have problems with Jenkins Security (your client must provide login data before it can send the request)or with CSRF protection (you have to retrieve a token before the first request and add this token as a parameter to each request).

Upvotes: 1

Related Questions