coolguy
coolguy

Reputation: 3071

Jenkins - persist plugin settings without using Descriptor

I develop a simple Jenkins plugin. Here is the plugin class:

@Extension
public class Plugin extends hudson.Plugin {
    private static String URL;

    @Override
    public void configure(StaplerRequest req, JSONObject formData) throws IOException, ServletException, Descriptor.FormException {
        super.configure(req, formData);
        URL = formData.getString("url");
        save();
    }

    @Override
    public void start() throws Exception {
        super.start();
        load();
    }
}

And also I have the config.groovy that describes URL field at the /configure page:

package com.example.Plugin

f = namespace("lib/form")

f.section(title: "My settings section") {
    f.entry(title: "URL", field: "url") {
        f.textbox(value: my.URL) {
        }
    }
}

The problem is when I restart Jenkins my URL setting is lost. How can I persist it without implementing a Descriptor class for my plugin?

I tried to add load() method call to configure() and to Plugin constructor. Also I tried to override getConfigXml() method like this:

@Override
protected XmlFile getConfigXml() {
    return new XmlFile(Jenkins.XSTREAM, new File(Jenkins.getInstance().getRootDir(), getClass().getName()+".xml"));
}

But it didn't work out. Any ideas?

Upvotes: 0

Views: 499

Answers (1)

coolguy
coolguy

Reputation: 3071

Finally I found the way to solve this problem. Seems like Jenkins can't persist static class fields. My Plugin class now looks like this:

@Extension
public class Plugin extends hudson.Plugin {
    private String url;
    private static Plugin INSTANCE;

    @Override
    public void configure(StaplerRequest req, JSONObject formData) throws IOException, ServletException, Descriptor.FormException {
        super.configure(req, formData);
        url = formData.getString("url");
        save();
    }

    @Override
    public void start() throws Exception {
        super.start();
        load();
        INSTANCE = Jenkins.getInstance().getPlugin(Plugin.class);
    }

    static String getUrl() {
        if (INSTANCE == null) {
            throw new IllegalStateException("Plugin instance is not defined yet");
        }
        return INSTANCE.url;
    }
}

Upvotes: 1

Related Questions