User.java 8.8 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

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;
K
kohsuke 已提交
26
import java.util.Collection;
K
kohsuke 已提交
27 28 29 30 31 32 33 34
import java.util.logging.Level;
import java.util.logging.Logger;

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


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

K
kohsuke 已提交
57 58 59 60
    /**
     * Loads the other data from disk if it's available.
     */
    private synchronized void load() {
61 62
        properties.clear();

K
kohsuke 已提交
63 64 65 66 67 68 69 70
        XmlFile config = getConfigFile();
        try {
            if(config.exists())
                config.unmarshal(this);
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, "Failed to load "+config,e);
        }

K
kohsuke 已提交
71 72 73 74 75 76 77 78 79 80
        // 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 已提交
81 82 83 84
        for (UserProperty p : properties)
            p.setUser(this);
    }

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

    public String getUrl() {
91 92 93 94 95
        return "user/"+id;
    }

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

K
kohsuke 已提交
98 99 100
    /**
     * The URL of the user page.
     */
K
kohsuke 已提交
101
    @Exported(visibility=999)
K
kohsuke 已提交
102 103 104 105
    public String getAbsoluteUrl() {
        return Stapler.getCurrentRequest().getRootPath()+'/'+getUrl();
    }

K
kohsuke 已提交
106 107 108 109 110 111 112
    /**
     * Gets the human readable name of this user.
     * This is configurable by the user.
     *
     * @return
     *      never null.
     */
K
kohsuke 已提交
113
    @Exported(visibility=999)
K
kohsuke 已提交
114 115 116 117
    public String getFullName() {
        return fullName;
    }

K
kohsuke 已提交
118
    @Exported
K
kohsuke 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
    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))
136
                return clazz.cast(p);
K
kohsuke 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
        }
        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 已提交
153 154 155 156 157
    /**
     * Gets the fallback "unknown" user instance.
     * <p>
     * This is used to avoid null {@link User} instance.
     */
158 159 160
    public static User getUnknown() {
        return get("unknown");
    }
K
kohsuke 已提交
161

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

K
kohsuke 已提交
180 181 182 183 184 185 186 187 188
    /**
     * Gets all the users.
     */
    public static Collection<User> getAll() {
        synchronized (byName) {
            return new ArrayList<User>(byName.values());
        }
    }

189 190 191 192 193 194 195 196 197
    /**
     * 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 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210
    /**
     * 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 已提交
211 212 213
    public List<AbstractBuild> getBuilds() {
        List<AbstractBuild> r = new ArrayList<AbstractBuild>();
        for (AbstractProject<?,?> p : Hudson.getInstance().getAllItems(AbstractProject.class)) {
K
kohsuke 已提交
214
            for (AbstractBuild<?,?> b : p.getBuilds()) {
K
kohsuke 已提交
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
                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() {
235
        return new XmlFile(XSTREAM,new File(Hudson.getInstance().getRootDir(),"users/"+ id +"/config.xml"));
K
kohsuke 已提交
236 237 238 239 240 241
    }

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

K
kohsuke 已提交
245 246 247 248 249 250 251
    /**
     * Exposed remote API.
     */
    public Api getApi() {
        return new Api(this);
    }

K
kohsuke 已提交
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 280 281 282 283 284 285 286 287 288 289 290 291 292
    /**
     * 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 已提交
293 294
     * Keyed by {@link User#id}. This map is used to ensure
     * singleton-per-id semantics of {@link User} objects.
K
kohsuke 已提交
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
     */
    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();
        }

325 326 327 328 329
        public String getEntryDescription(Run entry) {
            // TODO: provide useful details
            return null;
        }

K
kohsuke 已提交
330 331 332 333 334
        public Calendar getEntryTimestamp(Run entry) {
            return entry.getTimestamp();
        }
    };
}