User.java 8.6 KB
Newer Older
K
kohsuke 已提交
1 2 3
package hudson.model;

import com.thoughtworks.xstream.XStream;
K
kohsuke 已提交
4
import hudson.CopyOnWrite;
K
kohsuke 已提交
5 6
import hudson.FeedAdapter;
import hudson.XmlFile;
K
kohsuke 已提交
7 8
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.export.Exported;
K
kohsuke 已提交
9 10 11 12 13 14
import hudson.model.Descriptor.FormException;
import hudson.scm.ChangeLogSet;
import hudson.util.RunList;
import hudson.util.XStream2;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
K
kohsuke 已提交
15
import org.kohsuke.stapler.Stapler;
K
kohsuke 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33

import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Represents a user.
 * 
 * @author Kohsuke Kawaguchi
 */
K
kohsuke 已提交
34
@ExportedBean
K
kohsuke 已提交
35 36 37 38 39 40 41 42 43 44 45
public class User extends AbstractModelObject {

    private transient final String id;

    private volatile String fullName;

    private volatile String description;

    /**
     * List of {@link UserProperty}s configured for this project.
     */
K
kohsuke 已提交
46
    @CopyOnWrite
K
kohsuke 已提交
47 48 49 50 51 52
    private volatile List<UserProperty> properties = new ArrayList<UserProperty>();


    private User(String id) {
        this.id = id;
        this.fullName = id;   // fullName defaults to name
K
kohsuke 已提交
53 54
        load();
    }
K
kohsuke 已提交
55

K
kohsuke 已提交
56 57 58 59
    /**
     * Loads the other data from disk if it's available.
     */
    private synchronized void load() {
K
kohsuke 已提交
60 61 62 63 64 65 66 67
        XmlFile config = getConfigFile();
        try {
            if(config.exists())
                config.unmarshal(this);
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, "Failed to load "+config,e);
        }

K
kohsuke 已提交
68
        properties.clear();
K
kohsuke 已提交
69 70 71 72 73 74 75 76 77 78
        // allocate default instances if needed.
        // doing so after load makes sure that newly added user properties do get reflected
        for (UserPropertyDescriptor d : UserProperties.LIST) {
            if(getProperty(d.clazz)==null) {
                UserProperty up = d.newInstance(this);
                if(up!=null)
                    properties.add(up);
            }
        }

K
kohsuke 已提交
79 80 81 82
        for (UserProperty p : properties)
            p.setUser(this);
    }

K
kohsuke 已提交
83
    @Exported
K
kohsuke 已提交
84 85 86 87 88 89 90 91
    public String getId() {
        return id;
    }

    public String getUrl() {
        return "user/"+ id;
    }

K
kohsuke 已提交
92 93 94
    /**
     * The URL of the user page.
     */
K
kohsuke 已提交
95
    @Exported(visibility=999)
K
kohsuke 已提交
96 97 98 99
    public String getAbsoluteUrl() {
        return Stapler.getCurrentRequest().getRootPath()+'/'+getUrl();
    }

K
kohsuke 已提交
100 101 102 103 104 105 106
    /**
     * Gets the human readable name of this user.
     * This is configurable by the user.
     *
     * @return
     *      never null.
     */
K
kohsuke 已提交
107
    @Exported(visibility=999)
K
kohsuke 已提交
108 109 110 111
    public String getFullName() {
        return fullName;
    }

K
kohsuke 已提交
112
    @Exported
K
kohsuke 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
    public String getDescription() {
        return description;
    }

    /**
     * Gets the user properties configured for this user.
     */
    public Map<Descriptor<UserProperty>,UserProperty> getProperties() {
        return Descriptor.toMap(properties);
    }

    /**
     * Gets the specific property, or null.
     */
    public <T extends UserProperty> T getProperty(Class<T> clazz) {
        for (UserProperty p : properties) {
            if(clazz.isInstance(p))
130
                return clazz.cast(p);
K
kohsuke 已提交
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
        }
        return null;
    }

    /**
     * Accepts the new description.
     */
    public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        req.setCharacterEncoding("UTF-8");

        description = req.getParameter("description");
        save();
        
        rsp.sendRedirect(".");  // go to the top page
    }

K
kohsuke 已提交
147 148 149 150 151
    /**
     * Gets the fallback "unknown" user instance.
     * <p>
     * This is used to avoid null {@link User} instance.
     */
152 153 154
    public static User getUnknown() {
        return get("unknown");
    }
K
kohsuke 已提交
155

K
kohsuke 已提交
156 157 158 159 160
    /**
     * Gets the {@link User} object by its id.
     */
    public static User get(String id) {
        if(id==null)
K
kohsuke 已提交
161
            return null;
K
kohsuke 已提交
162
        id = id.replace('\\', '_').replace('/', '_');
163
        
K
kohsuke 已提交
164
        synchronized(byName) {
K
kohsuke 已提交
165
            User u = byName.get(id);
K
kohsuke 已提交
166
            if(u==null) {
K
kohsuke 已提交
167 168
                u = new User(id);
                byName.put(id,u);
K
kohsuke 已提交
169 170 171 172 173
            }
            return u;
        }
    }

174 175 176 177 178 179 180 181 182
    /**
     * Reloads the configuration from disk.
     */
    public static void reload() {
        // iterate over an array to be concurrency-safe
        for( User u : byName.values().toArray(new User[0]) )
            u.load();
    }

K
kohsuke 已提交
183 184 185 186 187 188 189 190 191 192 193 194 195
    /**
     * Returns the user name.
     */
    public String getDisplayName() {
        return getFullName();
    }

    /**
     * Gets the list of {@link Build}s that include changes by this user,
     * by the timestamp order.
     * 
     * TODO: do we need some index for this?
     */
K
kohsuke 已提交
196 197 198
    public List<AbstractBuild> getBuilds() {
        List<AbstractBuild> r = new ArrayList<AbstractBuild>();
        for (AbstractProject<?,?> p : Hudson.getInstance().getAllItems(AbstractProject.class)) {
K
kohsuke 已提交
199
            for (AbstractBuild<?,?> b : p.getBuilds()) {
K
kohsuke 已提交
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
                for (ChangeLogSet.Entry e : b.getChangeSet()) {
                    if(e.getAuthor()==this) {
                        r.add(b);
                        break;
                    }
                }
            }
        }
        Collections.sort(r,Run.ORDER_BY_DATE);
        return r;
    }

    public String toString() {
        return fullName;
    }

    /**
     * The file we save our configuration.
     */
    protected final XmlFile getConfigFile() {
220
        return new XmlFile(XSTREAM,new File(Hudson.getInstance().getRootDir(),"users/"+ id +"/config.xml"));
K
kohsuke 已提交
221 222 223 224 225 226 227 228 229 230 231
    }

    /**
     * Save the settings to a file.
     */
    public synchronized void save() throws IOException {
        XmlFile config = getConfigFile();
        config.mkdirs();
        config.write(this);
    }

K
kohsuke 已提交
232 233 234 235 236 237 238
    /**
     * Exposed remote API.
     */
    public Api getApi() {
        return new Api(this);
    }

K
kohsuke 已提交
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
    /**
     * Accepts submission from the configuration page.
     */
    public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        if(!Hudson.adminCheck(req,rsp))
            return;

        req.setCharacterEncoding("UTF-8");

        try {
            fullName = req.getParameter("fullName");
            description = req.getParameter("description");

            List<UserProperty> props = new ArrayList<UserProperty>();
            for (Descriptor<UserProperty> d : UserProperties.LIST)
                props.add(d.newInstance(req));
            this.properties = props;

            save();

            rsp.sendRedirect(".");
        } catch (FormException e) {
            sendError(e,req,rsp);
        }
    }

    public void doRssAll( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        rss(req, rsp, " all builds", RunList.fromRuns(getBuilds()));
    }

    public void doRssFailed( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        rss(req, rsp, " regression builds", RunList.fromRuns(getBuilds()).regressionOnly());
    }

    private void rss(StaplerRequest req, StaplerResponse rsp, String suffix, RunList runs) throws IOException, ServletException {
        RSS.forwardToRss(getDisplayName()+ suffix, getUrl(),
            runs.newBuilds(), FEED_ADAPTER, req, rsp );
    }


    /**
K
kohsuke 已提交
280 281
     * Keyed by {@link User#id}. This map is used to ensure
     * singleton-per-id semantics of {@link User} objects.
K
kohsuke 已提交
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
     */
    private static final Map<String,User> byName = new HashMap<String,User>();

    /**
     * Used to load/save user configuration.
     */
    private static final XStream XSTREAM = new XStream2();

    private static final Logger LOGGER = Logger.getLogger(User.class.getName());

    static {
        XSTREAM.alias("user",User.class);
    }

    /**
     * {@link FeedAdapter} to produce build status summary in the feed.
     */
    public static final FeedAdapter<Run> FEED_ADAPTER = new FeedAdapter<Run>() {
        public String getEntryTitle(Run entry) {
            return entry+" : "+entry.getBuildStatusSummary().message;
        }

        public String getEntryUrl(Run entry) {
            return entry.getUrl();
        }

        public String getEntryID(Run entry) {
            return "tag:"+entry.getParent().getName()+':'+entry.getId();
        }

312 313 314 315 316
        public String getEntryDescription(Run entry) {
            // TODO: provide useful details
            return null;
        }

K
kohsuke 已提交
317 318 319 320 321
        public Calendar getEntryTimestamp(Run entry) {
            return entry.getTimestamp();
        }
    };
}