User.java 11.2 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
import hudson.FeedAdapter;
K
kohsuke 已提交
6
import hudson.Util;
7
import hudson.XmlFile;
K
kohsuke 已提交
8 9 10
import hudson.model.Descriptor.FormException;
import hudson.util.RunList;
import hudson.util.XStream2;
11 12
import org.acegisecurity.Authentication;
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
13
import org.kohsuke.stapler.Stapler;
K
kohsuke 已提交
14 15
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
16 17
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
K
kohsuke 已提交
18 19 20 21 22 23

import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
24
import java.util.Collection;
K
kohsuke 已提交
25 26
import java.util.Collections;
import java.util.HashMap;
27 28
import java.util.HashSet;
import java.util.Iterator;
K
kohsuke 已提交
29 30
import java.util.List;
import java.util.Map;
31
import java.util.Set;
K
kohsuke 已提交
32 33 34 35 36 37 38 39
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Represents a user.
 * 
 * @author Kohsuke Kawaguchi
 */
K
kohsuke 已提交
40
@ExportedBean
K
kohsuke 已提交
41 42 43 44 45 46 47 48 49 50 51
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 已提交
52
    @CopyOnWrite
K
kohsuke 已提交
53 54 55 56 57 58
    private volatile List<UserProperty> properties = new ArrayList<UserProperty>();


    private User(String id) {
        this.id = id;
        this.fullName = id;   // fullName defaults to name
K
kohsuke 已提交
59 60
        load();
    }
K
kohsuke 已提交
61

K
kohsuke 已提交
62 63 64 65
    /**
     * Loads the other data from disk if it's available.
     */
    private synchronized void load() {
66 67
        properties.clear();

K
kohsuke 已提交
68 69 70 71 72 73 74 75
        XmlFile config = getConfigFile();
        try {
            if(config.exists())
                config.unmarshal(this);
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, "Failed to load "+config,e);
        }

76 77 78 79 80 81
        // remove nulls that have failed to load
        for (Iterator<UserProperty> itr = properties.iterator(); itr.hasNext();) {
            if(itr.next()==null)
                itr.remove();            
        }

K
kohsuke 已提交
82 83 84 85 86 87 88 89 90 91
        // 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 已提交
92 93 94 95
        for (UserProperty p : properties)
            p.setUser(this);
    }

K
kohsuke 已提交
96
    @Exported
K
kohsuke 已提交
97 98 99 100 101
    public String getId() {
        return id;
    }

    public String getUrl() {
102 103 104 105 106
        return "user/"+id;
    }

    public String getSearchUrl() {
        return "/user/"+id;
K
kohsuke 已提交
107 108
    }

K
kohsuke 已提交
109 110 111
    /**
     * The URL of the user page.
     */
K
kohsuke 已提交
112
    @Exported(visibility=999)
K
kohsuke 已提交
113 114 115 116
    public String getAbsoluteUrl() {
        return Stapler.getCurrentRequest().getRootPath()+'/'+getUrl();
    }

K
kohsuke 已提交
117 118 119 120 121 122 123
    /**
     * Gets the human readable name of this user.
     * This is configurable by the user.
     *
     * @return
     *      never null.
     */
K
kohsuke 已提交
124
    @Exported(visibility=999)
K
kohsuke 已提交
125 126 127 128
    public String getFullName() {
        return fullName;
    }

K
kohsuke 已提交
129 130 131 132 133 134 135 136
    /**
     * Sets the human readable name of thie user.
     */
    public void setFullName(String name) {
        if(Util.fixEmptyAndTrim(name)==null)    name=id;
        this.fullName = name;
    }

K
kohsuke 已提交
137
    @Exported
K
kohsuke 已提交
138 139 140 141 142 143 144 145 146 147 148
    public String getDescription() {
        return description;
    }

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

149 150 151 152 153 154 155 156 157
    /**
     * Updates the user object by adding a property.
     */
    public synchronized void addProperty(UserProperty p) throws IOException {
        UserProperty old = getProperty(p.getClass());
        List<UserProperty> ps = new ArrayList<UserProperty>(properties);
        if(old!=null)
            ps.remove(old);
        ps.add(p);
158
        p.setUser(this);
159 160 161
        properties = ps;
        save();
    }
162

K
kohsuke 已提交
163 164 165
    /**
     * List of all {@link UserProperties} exposed primarily for the remoting API.
     */
K
kohsuke 已提交
166
    @Exported(name="property",inline=true)
167 168 169
    public List<UserProperty> getAllProperties() {
        return Collections.unmodifiableList(properties);
    }
K
kohsuke 已提交
170
    
K
kohsuke 已提交
171 172 173 174 175 176
    /**
     * Gets the specific property, or null.
     */
    public <T extends UserProperty> T getProperty(Class<T> clazz) {
        for (UserProperty p : properties) {
            if(clazz.isInstance(p))
177
                return clazz.cast(p);
K
kohsuke 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
        }
        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 已提交
194 195 196 197 198
    /**
     * Gets the fallback "unknown" user instance.
     * <p>
     * This is used to avoid null {@link User} instance.
     */
199 200 201
    public static User getUnknown() {
        return get("unknown");
    }
K
kohsuke 已提交
202

K
kohsuke 已提交
203 204 205 206 207 208 209 210 211
    /**
     * Gets the {@link User} object by its id.
     *
     * @param create
     *      If true, this method will never return null for valid input
     *      (by creating a new {@link User} object if none exists.)
     *      If false, this method will return null if {@link User} object
     *      with the given name doesn't exist.
     */
K
kohsuke 已提交
212
    public static User get(String id, boolean create) {
K
kohsuke 已提交
213
        if(id==null)
K
kohsuke 已提交
214
            return null;
K
kohsuke 已提交
215
        id = id.replace('\\', '_').replace('/', '_');
216
        
K
kohsuke 已提交
217
        synchronized(byName) {
K
kohsuke 已提交
218
            User u = byName.get(id);
K
kohsuke 已提交
219
            if(u==null && create) {
K
kohsuke 已提交
220 221
                u = new User(id);
                byName.put(id,u);
K
kohsuke 已提交
222 223 224 225 226
            }
            return u;
        }
    }

K
kohsuke 已提交
227 228 229 230 231 232 233
    /**
     * Gets the {@link User} object by its id.
     */
    public static User get(String id) {
        return get(id,true);
    }

K
kohsuke 已提交
234 235 236 237 238 239 240 241 242 243 244 245
    /**
     * Gets the {@link User} object representing the currently logged-in user, or null
     * if the current user is anonymous.
     * @since 1.172
     */
    public static User current() {
        Authentication a = Hudson.getAuthentication();
        if(a instanceof AnonymousAuthenticationToken)
            return null;
        return get(a.getPrincipal().toString());
    }

K
kohsuke 已提交
246 247 248 249 250 251 252 253 254
    /**
     * Gets all the users.
     */
    public static Collection<User> getAll() {
        synchronized (byName) {
            return new ArrayList<User>(byName.values());
        }
    }

255 256 257 258 259 260 261 262 263
    /**
     * 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 已提交
264 265 266 267 268 269 270 271 272 273 274 275 276
    /**
     * 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 已提交
277 278
    public List<AbstractBuild> getBuilds() {
        List<AbstractBuild> r = new ArrayList<AbstractBuild>();
279 280 281 282
        for (AbstractProject<?,?> p : Hudson.getInstance().getAllItems(AbstractProject.class))
            for (AbstractBuild<?,?> b : p.getBuilds())
                if(b.hasParticipant(this))
                    r.add(b);
K
kohsuke 已提交
283 284 285 286
        Collections.sort(r,Run.ORDER_BY_DATE);
        return r;
    }

287 288 289 290 291 292 293 294 295 296 297 298
    /**
     * Gets all the {@link AbstractProject}s that this user has committed to.
     * @since 1.191
     */
    public Set<AbstractProject<?,?>> getProjects() {
        Set<AbstractProject<?,?>> r = new HashSet<AbstractProject<?,?>>();
        for (AbstractProject<?,?> p : Hudson.getInstance().getAllItems(AbstractProject.class))
            if(p.hasParticipant(this))
                r.add(p);
        return r;
    }

K
kohsuke 已提交
299 300 301 302 303 304 305 306
    public String toString() {
        return fullName;
    }

    /**
     * The file we save our configuration.
     */
    protected final XmlFile getConfigFile() {
307
        return new XmlFile(XSTREAM,new File(Hudson.getInstance().getRootDir(),"users/"+ id +"/config.xml"));
K
kohsuke 已提交
308 309 310 311 312 313
    }

    /**
     * Save the settings to a file.
     */
    public synchronized void save() throws IOException {
314
        getConfigFile().write(this);
K
kohsuke 已提交
315 316
    }

K
kohsuke 已提交
317 318 319 320 321 322 323
    /**
     * Exposed remote API.
     */
    public Api getApi() {
        return new Api(this);
    }

K
kohsuke 已提交
324 325 326 327 328 329 330 331 332 333 334 335 336 337
    /**
     * 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>();
338 339 340 341 342
            for (Descriptor<UserProperty> d : UserProperties.LIST) {
                UserProperty p = d.newInstance(req, null);
                p.setUser(this);
                props.add(p);
            }
K
kohsuke 已提交
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
            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 已提交
368 369
     * Keyed by {@link User#id}. This map is used to ensure
     * singleton-per-id semantics of {@link User} objects.
K
kohsuke 已提交
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
     */
    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();
        }

400 401 402 403 404
        public String getEntryDescription(Run entry) {
            // TODO: provide useful details
            return null;
        }

K
kohsuke 已提交
405 406 407 408 409
        public Calendar getEntryTimestamp(Run entry) {
            return entry.getTimestamp();
        }
    };
}