DownloadService.java 6.7 KB
Newer Older
K
kohsuke 已提交
1 2 3 4 5
package hudson.model;

import hudson.Extension;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
6
import hudson.security.csrf.CrumbIssuer;
K
kohsuke 已提交
7 8
import hudson.util.QuotedStringTokenizer;
import hudson.util.TextFile;
9
import hudson.util.TimeUnit2;
K
kohsuke 已提交
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.Stapler;

import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;

import net.sf.json.JSONObject;

/**
 * Service for plugins to periodically retrieve update data files
 * (like the one in the update center) through browsers.
 *
 * <p>
 * Because the retrieval of the file goes through XmlHttpRequest,
 * we cannot reliably pass around binary.
 *
 * @author Kohsuke Kawaguchi
 */
@Extension
public class DownloadService extends PageDecorator {
    public DownloadService() {
        super(DownloadService.class);
    }

    /**
     * Builds up an HTML fragment that starts all the download jobs.
     */
    public String generateFragment() {
        StringBuilder buf = new StringBuilder();
40 41
        if(Hudson.getInstance().hasPermission(Hudson.READ)) {
            long now = System.currentTimeMillis();
42 43 44 45 46 47 48
            CrumbIssuer ci = Hudson.getInstance().getCrumbIssuer();
            String crumbName = null;
            String crumb = null;
            if(ci!=null) {
                crumbName = ci.getCrumbRequestField();
                crumb = ci.getCrumb();
            }
49 50
            for (Downloadable d : Downloadable.all()) {
                if(d.getDue()<now) {
51 52 53 54 55 56 57
                    buf.append("<script>");
                    if(ci!=null) {
                        buf.append("downloadService.crumbName="+QuotedStringTokenizer.quote(crumbName))
                           .append(";downloadService.crumb="+QuotedStringTokenizer.quote(crumb))
                           .append(';');
                    }
                    buf.append("downloadService.download(")
58 59 60 61 62 63 64 65 66 67
                       .append(QuotedStringTokenizer.quote(d.getId()))
                       .append(',')
                       .append(QuotedStringTokenizer.quote(d.getUrl()))
                       .append(',')
                       .append("{version:"+QuotedStringTokenizer.quote(Hudson.VERSION)+'}')
                       .append(',')
                       .append(QuotedStringTokenizer.quote(Stapler.getCurrentRequest().getContextPath()+'/'+getUrl()+"/byId/"+d.getId()+"/postBack"))
                       .append(',')
                       .append("null);</script>");
                }
K
kohsuke 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
            }
        }
        return buf.toString();
    }

    /**
     * Gets {@link Downloadable} by its ID.
     * Used to bind them to URL.
     */
    public Downloadable getById(String id) {
        for (Downloadable d : Downloadable.all())
            if(d.getId().equals(id))
                return d;
        return null;
    }

K
kohsuke 已提交
84 85 86 87
    /**
     * Represents a periodically updated JSON data file obtained from a remote URL.
     *
     * <p>
88
     * This mechanism is one of the basis of the update center, which involves fetching
K
kohsuke 已提交
89 90 91 92
     * up-to-date data file.
     *
     * @since 1.305
     */
93
    public static class Downloadable implements ExtensionPoint {
K
kohsuke 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
        private final String id;
        private final String url;
        private final long interval;
        private volatile long due=0;

        /**
         *
         * @param url
         *      URL relative to {@link UpdateCenter#getUrl()}.
         *      So if this string is "foo.json", the ultimate URL will be
         *      something like "https://hudson.dev.java.net/foo.json"
         *
         *      For security and privacy reasons, we don't allow the retrieval
         *      from random locations.
         */
109
        public Downloadable(String id, String url, long interval) {
K
kohsuke 已提交
110 111 112 113 114
            this.id = id;
            this.url = url;
            this.interval = interval;
        }

115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
        /**
         * Uses the class name as an ID.
         */
        public Downloadable(Class id) {
            this(id.getName().replace('$','.'));
        }

        public Downloadable(String id) {
            this(id,id+".json");
        }

        public Downloadable(String id, String url) {
            this(id,url,TimeUnit2.DAYS.toMillis(1));
        }

K
kohsuke 已提交
130 131 132 133 134 135 136 137
        public String getId() {
            return id;
        }

        /**
         * URL to download.
         */
        public String getUrl() {
138
            return Hudson.getInstance().getUpdateCenter().getUrl()+"updates/"+url;
K
kohsuke 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
        }

        /**
         * How often do we retrieve the new image?
         *
         * @return
         *      number of milliseconds between retrieval.
         */
        public long getInterval() {
            return interval;
        }

        /**
         * This is where the retrieved file will be stored.
         */
        public TextFile getDataFile() {
            return new TextFile(new File(Hudson.getInstance().getRootDir(),"updates/"+id));
        }

        /**
         * When shall we retrieve this file next time?
         */
        public long getDue() {
            if(due==0)
                // if the file doesn't exist, this code should result
                // in a very small (but >0) due value, which should trigger
                // the retrieval immediately.
                due = getDataFile().file.lastModified()+interval;
            return due;
        }

        /**
         * Loads the current file into JSON and returns it, or null
         * if no data exists.
         */
        public JSONObject getData() throws IOException {
            TextFile df = getDataFile();
            if(df.exists())
                return JSONObject.fromObject(df.read());
            return null;
        }

        /**
         * This is where the browser sends us the data. 
         */
        public void doPostBack(@QueryParameter String json) throws IOException {
            long dataTimestamp = System.currentTimeMillis();
            TextFile df = getDataFile();
            df.write(json);
            df.file.setLastModified(dataTimestamp);
            due = dataTimestamp+getInterval();
            LOGGER.info("Obtained the updated data file for "+id);
        }

        /**
         * Returns all the registered {@link Downloadable}s.
         */
        public static ExtensionList<Downloadable> all() {
            return Hudson.getInstance().getExtensionList(Downloadable.class);
        }

200 201 202 203 204 205 206 207 208 209 210
        /**
         * Returns the {@link Downloadable} that has the given ID.
         */
        public static Downloadable get(String id) {
            for (Downloadable d : all()) {
                if(d.id.equals(id))
                    return d;
            }
            return null;
        }

K
kohsuke 已提交
211 212 213
        private static final Logger LOGGER = Logger.getLogger(Downloadable.class.getName());
    }
}
214