View.java 42.2 KB
Newer Older
K
kohsuke 已提交
1 2 3
/*
 * The MIT License
 * 
4 5
 * Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi, Tom Huybrechts,
 * Yahoo!, Inc.
K
kohsuke 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
K
kohsuke 已提交
25 26
package hudson.model;

27 28 29
import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.io.StreamException;
import com.thoughtworks.xstream.io.xml.XppDriver;
30
import hudson.DescriptorExtensionList;
31
import hudson.Extension;
32
import hudson.ExtensionPoint;
J
Jesse Glick 已提交
33
import hudson.Functions;
34
import hudson.Indenter;
35
import hudson.Util;
K
kohsuke 已提交
36
import hudson.model.Descriptor.FormException;
K
Kohsuke Kawaguchi 已提交
37
import hudson.model.labels.LabelAtomPropertyDescriptor;
J
Jesse Glick 已提交
38
import hudson.scm.ChangeLogSet;
39
import hudson.scm.ChangeLogSet.Entry;
40 41
import hudson.search.CollectionSearchIndex;
import hudson.search.SearchIndexBuilder;
42 43 44 45
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
46
import hudson.security.PermissionScope;
J
Jesse Glick 已提交
47
import hudson.tasks.UserAvatarResolver;
48 49
import hudson.util.AlternativeUiTextProvider;
import hudson.util.AlternativeUiTextProvider.Message;
50
import hudson.util.DescribableList;
51
import hudson.util.DescriptorList;
52
import hudson.util.FormApply;
53
import hudson.util.IOException2;
54
import hudson.util.RunList;
55
import hudson.util.XStream2;
56
import hudson.views.ListViewColumn;
57
import hudson.widgets.Widget;
58
import jenkins.model.Jenkins;
59
import jenkins.model.ModelObjectWithChildren;
J
Jesse Glick 已提交
60 61 62 63
import jenkins.util.ProgressiveRendering;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
64 65
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
J
Jesse Glick 已提交
66
import org.kohsuke.stapler.Stapler;
67 68
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
69
import org.kohsuke.stapler.WebMethod;
70 71
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
72
import org.kohsuke.stapler.interceptor.RequirePOST;
K
kohsuke 已提交
73

74
import javax.servlet.ServletException;
75 76 77 78 79 80 81 82 83
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
K
kohsuke 已提交
84
import java.io.IOException;
85
import java.io.InputStream;
86
import java.io.OutputStream;
87
import java.io.StringWriter;
88
import java.util.ArrayList;
89
import java.util.Arrays;
90 91 92 93 94 95
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.GregorianCalendar;
import java.util.HashMap;
96
import java.util.HashSet;
O
Oliver Gondža 已提交
97
import java.util.LinkedHashSet;
K
kohsuke 已提交
98
import java.util.List;
99
import java.util.Map;
J
Jesse Glick 已提交
100
import java.util.Set;
101 102
import java.util.logging.Level;
import java.util.logging.Logger;
103

104
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
105
import static jenkins.model.Jenkins.*;
106 107
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
K
kohsuke 已提交
108 109

/**
110
 * Encapsulates the rendering of the list of {@link TopLevelItem}s
111
 * that {@link Jenkins} owns.
K
kohsuke 已提交
112
 *
113 114 115 116 117 118 119
 * <p>
 * This is an extension point in Hudson, allowing different kind of
 * rendering to be added as plugins.
 *
 * <h2>Note for implementors</h2>
 * <ul>
 * <li>
K
kohsuke 已提交
120 121 122
 * {@link View} subtypes need the <tt>newViewDetail.jelly</tt> page,
 * which is included in the "new view" page. This page should have some
 * description of what the view is about. 
123 124
 * </ul>
 *
K
kohsuke 已提交
125
 * @author Kohsuke Kawaguchi
K
kohsuke 已提交
126 127
 * @see ViewDescriptor
 * @see ViewGroup
K
kohsuke 已提交
128
 */
K
kohsuke 已提交
129
@ExportedBean
130
public abstract class View extends AbstractModelObject implements AccessControlled, Describable<View>, ExtensionPoint, Saveable, ModelObjectWithChildren {
131

132 133 134 135 136 137
    /**
     * Container of this view. Set right after the construction
     * and never change thereafter.
     */
    protected /*final*/ ViewGroup owner;

K
kohsuke 已提交
138 139 140 141 142
    /**
     * Name of this view.
     */
    protected String name;

143 144 145 146
    /**
     * Message displayed in the view page.
     */
    protected String description;
147 148 149 150 151 152 153 154 155 156
    
    /**
     * If true, only show relevant executors
     */
    protected boolean filterExecutors;

    /**
     * If true, only show relevant queue items
     */
    protected boolean filterQueue;
157 158
    
    protected transient List<Action> transientActions;
K
kohsuke 已提交
159

160 161 162 163
    /**
     * List of {@link ViewProperty}s configured for this view.
     * @since 1.406
     */
164
    private volatile DescribableList<ViewProperty,ViewPropertyDescriptor> properties = new PropertyList(this);
165

K
kohsuke 已提交
166 167 168 169
    protected View(String name) {
        this.name = name;
    }

170 171 172 173 174
    protected View(String name, ViewGroup owner) {
        this.name = name;
        this.owner = owner;
    }

K
kohsuke 已提交
175
    /**
176
     * Gets all the items in this collection in a read-only view.
K
kohsuke 已提交
177
     */
178
    @Exported(name="jobs")
179
    public abstract Collection<TopLevelItem> getItems();
K
kohsuke 已提交
180

O
Oliver Gondža 已提交
181 182
    /**
     * Gets all the items recursively contained in this collection in a read-only view.
183 184 185 186
     * <p>
     * The default implementation recursively adds the items of all contained Views
     * in case this view implements {@link ViewGroup}, which should be enough for most cases.
     *
O
Oliver Gondža 已提交
187 188 189 190 191
     * @since 1.520
     */
    public Collection<TopLevelItem> getAllItems() {

        if (this instanceof ViewGroup) {
192
            final Collection<TopLevelItem> items = new LinkedHashSet<TopLevelItem>(getItems());
O
Oliver Gondža 已提交
193

194
            for(View view: ((ViewGroup) this).getViews()) {
O
Oliver Gondža 已提交
195 196
                items.addAll(view.getAllItems());
            }
197 198 199
            return Collections.unmodifiableCollection(items);
        } else {
            return getItems();
O
Oliver Gondža 已提交
200 201 202
        }
    }

203 204 205
    /**
     * Gets the {@link TopLevelItem} of the given name.
     */
206
    public TopLevelItem getItem(String name) {
207
        return getOwnerItemGroup().getItem(name);
208 209 210 211 212 213 214 215
    }

    /**
     * Alias for {@link #getItem(String)}. This is the one used in the URL binding.
     */
    public final TopLevelItem getJob(String name) {
        return getItem(name);
    }
216

K
kohsuke 已提交
217
    /**
218
     * Checks if the job is in this collection.
K
kohsuke 已提交
219
     */
220
    public abstract boolean contains(TopLevelItem item);
K
kohsuke 已提交
221 222

    /**
223
     * Gets the name of all this collection.
K
kohsuke 已提交
224 225
     *
     * @see #rename(String)
K
kohsuke 已提交
226
     */
227
    @Exported(visibility=2,name="name")
K
kohsuke 已提交
228 229 230
    public String getViewName() {
        return name;
    }
K
kohsuke 已提交
231

K
kohsuke 已提交
232 233 234
    /**
     * Renames this view.
     */
235
    public void rename(String newName) throws Failure, FormException {
K
kohsuke 已提交
236
        if(name.equals(newName))    return; // noop
K
kohsuke 已提交
237
        checkGoodName(newName);
238 239
        if(owner.getView(newName)!=null)
            throw new FormException(Messages.Hudson_ViewAlreadyExists(newName),"name");
K
kohsuke 已提交
240 241 242 243 244
        String oldName = name;
        name = newName;
        owner.onViewRenamed(this,oldName,newName);
    }

K
kohsuke 已提交
245 246 247 248 249 250 251
    /**
     * Gets the {@link ViewGroup} that this view belongs to.
     */
    public ViewGroup getOwner() {
        return owner;
    }

252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    /**
     * Backward-compatible way of getting {@code getOwner().getItemGroup()}
     */
    public ItemGroup<? extends TopLevelItem> getOwnerItemGroup() {
        try {
            return _getOwnerItemGroup();
        } catch (AbstractMethodError e) {
            return Hudson.getInstance();
        }
    }

    /**
     * A pointless function to work around what appears to be a HotSpot problem. See JENKINS-5756 and bug 6933067
     * on BugParade for more details.
     */
    private ItemGroup<? extends TopLevelItem> _getOwnerItemGroup() {
        return owner.getItemGroup();
    }

271 272 273 274 275 276 277 278 279 280 281 282
    public View getOwnerPrimaryView() {
        try {
            return _getOwnerPrimaryView();
        } catch (AbstractMethodError e) {
            return null;
        }
    }

    private View _getOwnerPrimaryView() {
        return owner.getPrimaryView();
    }

283 284 285 286 287 288 289 290 291 292 293 294
    public List<Action> getOwnerViewActions() {
        try {
            return _getOwnerViewActions();
        } catch (AbstractMethodError e) {
            return Hudson.getInstance().getActions();
        }
    }

    private List<Action> _getOwnerViewActions() {
        return owner.getViewActions();
    }

295 296 297
    /**
     * Message displayed in the top page. Can be null. Includes HTML.
     */
298
    @Exported
299
    public String getDescription() {
300
        return description;
301 302
    }
    
303 304 305 306
    /**
     * Gets the view properties configured for this view.
     * @since 1.406
     */
307
    public DescribableList<ViewProperty,ViewPropertyDescriptor> getProperties() {
308 309 310 311 312
        // readResolve was the best place to do this, but for compatibility reasons,
        // this class can no longer have readResolve() (the mechanism itself isn't suitable for class hierarchy)
        // see JENKINS-9431
        //
        // until we have that, putting this logic here.
313
        synchronized (PropertyList.class) {
314 315 316 317 318
            if (properties == null) {
                properties = new PropertyList(this);
            } else {
                properties.setOwner(this);
            }
319
            return properties;
320
        }
321 322
    }

K
Kohsuke Kawaguchi 已提交
323 324 325 326 327 328 329 330 331 332 333 334 335
    /**
     * Returns all the {@link LabelAtomPropertyDescriptor}s that can be potentially configured
     * on this label.
     */
    public List<ViewPropertyDescriptor> getApplicablePropertyDescriptors() {
        List<ViewPropertyDescriptor> r = new ArrayList<ViewPropertyDescriptor>();
        for (ViewPropertyDescriptor pd : ViewProperty.all()) {
            if (pd.isEnabledFor(this))
                r.add(pd);
        }
        return r;
    }

336 337 338 339 340 341
    public void save() throws IOException {
        // persistence is a part of the owner
        // due to initialization timing issue, it can be null when this method is called
        if (owner != null) {
            owner.save();
        }
342 343 344 345 346 347 348 349
    }

    /**
     * List of all {@link ViewProperty}s exposed primarily for the remoting API.
     * @since 1.406
     */
    @Exported(name="property",inline=true)
    public List<ViewProperty> getAllProperties() {
350
        return getProperties().toList();
351 352
    }

353
    public ViewDescriptor getDescriptor() {
354
        return (ViewDescriptor) Jenkins.getInstance().getDescriptorOrDie(getClass());
355
    }
356 357 358 359 360

    public String getDisplayName() {
        return getViewName();
    }

361 362 363 364
    public String getNewPronoun() {
        return AlternativeUiTextProvider.get(NEW_PRONOUN, this, Messages.AbstractItem_Pronoun());
    }

K
kohsuke 已提交
365 366 367 368 369 370 371 372 373 374
    /**
     * By default, return true to render the "Edit view" link on the page.
     * This method is really just for the default "All" view to hide the edit link
     * so that the default Hudson top page remains the same as before 1.316.
     *
     * @since 1.316
     */
    public boolean isEditable() {
        return true;
    }
375 376 377 378 379
    
    /**
     * If true, only show relevant executors
     */
    public boolean isFilterExecutors() {
380 381
        return filterExecutors;
    }
382
    
K
kohsuke 已提交
383
    /**
384 385 386
     * If true, only show relevant queue items
     */
    public boolean isFilterQueue() {
387
        return filterQueue;
388 389
    }

390
    /**
K
kohsuke 已提交
391 392 393 394 395 396
     * Gets the {@link Widget}s registered on this object.
     *
     * <p>
     * For now, this just returns the widgets registered to Hudson.
     */
    public List<Widget> getWidgets() {
397
        return Collections.unmodifiableList(Jenkins.getInstance().getWidgets());
K
kohsuke 已提交
398 399
    }

400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
    /**
     * If this view uses &lt;t:projectView> for rendering, this method returns columns to be displayed.
     */
    public Iterable<? extends ListViewColumn> getColumns() {
        return ListViewColumn.createDefaultInitialColumnList();
    }

    /**
     * If this view uses &lt;t:projectView> for rendering, this method returns the indenter used
     * to indent each row.
     */
    public Indenter getIndenter() {
        return null;
    }

415 416 417 418
    /**
     * If true, this is a view that renders the top page of Hudson.
     */
    public boolean isDefault() {
419
        return getOwnerPrimaryView()==this;
420
    }
421 422
    
    public List<Computer> getComputers() {
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
        Computer[] computers = Jenkins.getInstance().getComputers();

        if (!isFilterExecutors()) {
            return Arrays.asList(computers);
        }

        List<Computer> result = new ArrayList<Computer>();

        HashSet<Label> labels = new HashSet<Label>();
        for (Item item : getItems()) {
            if (item instanceof AbstractProject<?, ?>) {
                labels.addAll(((AbstractProject<?, ?>) item).getRelevantLabels());
            }
        }

        for (Computer c : computers) {
            Node n = c.getNode();
            if (n != null) {
K
Kohsuke Kawaguchi 已提交
441
                if (labels.contains(null) && n.getMode() == Mode.NORMAL || !isDisjoint(n.getAssignedLabels(), labels)) {
442 443 444 445 446 447
                    result.add(c);
                }
            }
        }

        return result;
448
    }
K
Kohsuke Kawaguchi 已提交
449 450 451 452 453 454 455 456

    private boolean isDisjoint(Collection c1, Collection c2) {
        for (Object o : c1)
            if (c2.contains(o))
                return false;
        return true;
    }

457
    private List<Queue.Item> filterQueue(List<Queue.Item> base) {
458
        if (!isFilterQueue()) {
459
            return base;
460 461 462 463
        }

        Collection<TopLevelItem> items = getItems();
        List<Queue.Item> result = new ArrayList<Queue.Item>();
464
        for (Queue.Item qi : base) {
465 466 467 468 469 470 471 472 473 474 475
            if (items.contains(qi.task)) {
                result.add(qi);
            } else
            if (qi.task instanceof AbstractProject<?, ?>) {
                AbstractProject<?,?> project = (AbstractProject<?, ?>) qi.task;
                if (items.contains(project.getRootProject())) {
                    result.add(qi);
                }
            }
        }
        return result;
476
    }
477

478 479 480 481 482 483 484 485
    public List<Queue.Item> getQueueItems() {
        return filterQueue(Arrays.asList(Jenkins.getInstance().getQueue().getItems()));
    }

    public List<Queue.Item> getApproximateQueueItemsQuickly() {
        return filterQueue(Jenkins.getInstance().getQueue().getApproximateItemsQuickly());
    }

K
kohsuke 已提交
486
    /**
487
     * Returns the path relative to the context root.
K
kohsuke 已提交
488
     *
489 490
     * Doesn't start with '/' but ends with '/' (except returns
     * empty string when this is the default view).
K
kohsuke 已提交
491
     */
K
kohsuke 已提交
492
    public String getUrl() {
493
        return isDefault() ? (owner!=null ? owner.getUrl() : "") : getViewUrl();
494 495 496 497 498 499 500
    }

    /**
     * Same as {@link #getUrl()} except this returns a view/{name} path
     * even for the default view.
     */
    public String getViewUrl() {
501
        return (owner!=null ? owner.getUrl() : "") + "view/" + Util.rawEncode(getViewName()) + '/';
K
kohsuke 已提交
502
    }
503

J
Jesse Glick 已提交
504 505 506 507
    @Override public String toString() {
        return super.toString() + "[" + getViewUrl() + "]";
    }

508 509 510 511
    public String getSearchUrl() {
        return getUrl();
    }

512 513 514 515 516 517 518
    /**
     * Returns the transient {@link Action}s associated with the top page.
     *
     * <p>
     * If views don't want to show top-level actions, this method
     * can be overridden to return different objects.
     *
519
     * @see Jenkins#getActions()
520 521
     */
    public List<Action> getActions() {
522
    	List<Action> result = new ArrayList<Action>();
523
    	result.addAll(getOwnerViewActions());
524 525
    	synchronized (this) {
    		if (transientActions == null) {
K
Kohsuke Kawaguchi 已提交
526
                updateTransientActions();
527 528 529 530 531 532
    		}
    		result.addAll(transientActions);
    	}
    	return result;
    }
    
533 534 535 536
    public synchronized void updateTransientActions() {
        transientActions = TransientViewActionFactory.createAllFor(this); 
    }
    
537
    public Object getDynamic(String token) {
538 539 540
        for (Action a : getActions()) {
            String url = a.getUrlName();
            if (url==null)  continue;
541 542
            if(a.getUrlName().equals(token))
                return a;
543
        }
544
        return null;
545 546
    }

547 548 549 550 551
    /**
     * Gets the absolute URL of this view.
     */
    @Exported(visibility=2,name="url")
    public String getAbsoluteUrl() {
552
        return Jenkins.getInstance().getRootUrl()+getUrl();
553 554
    }

K
kohsuke 已提交
555
    public Api getApi() {
556 557 558
        return new Api(this);
    }

K
kohsuke 已提交
559 560 561 562 563 564 565 566 567 568
    /**
     * Returns the page to redirect the user to, after the view is created.
     *
     * The returned string is appended to "/view/foobar/", so for example
     * to direct the user to the top page of the view, return "", etc.
     */
    public String getPostConstructLandingPage() {
        return "configure";
    }

569 570 571 572
    /**
     * Returns the {@link ACL} for this object.
     */
    public ACL getACL() {
573
        return Jenkins.getInstance().getAuthorizationStrategy().getACL(this);
574 575 576 577 578 579
    }

    public void checkPermission(Permission p) {
        getACL().checkPermission(p);
    }

580 581 582 583
    public boolean hasPermission(Permission p) {
        return getACL().hasPermission(p);
    }

584 585 586 587 588 589 590 591 592 593 594 595 596 597
    /**
     * Called when a job name is changed or deleted.
     *
     * <p>
     * If this view contains this job, it should update the view membership so that
     * the renamed job will remain in the view, and the deleted job is removed.
     *
     * @param item
     *      The item whose name is being changed.
     * @param oldName
     *      Old name of the item. Always non-null.
     * @param newName
     *      New name of the item, if the item is renamed. Or null, if the item is removed.
     */
K
kohsuke 已提交
598
    public abstract void onJobRenamed(Item item, String oldName, String newName);
599

600
    @ExportedBean(defaultVisibility=2)
601 602
    public static final class UserInfo implements Comparable<UserInfo> {
        private final User user;
603 604 605
        /**
         * When did this user made a last commit on any of our projects? Can be null.
         */
606
        private Calendar lastChange;
607 608 609
        /**
         * Which project did this user commit? Can be null.
         */
K
kohsuke 已提交
610
        private AbstractProject project;
K
kohsuke 已提交
611

612 613 614
        /** @see UserAvatarResolver */
        String avatar;

K
kohsuke 已提交
615
        UserInfo(User user, AbstractProject p, Calendar lastChange) {
616 617 618 619
            this.user = user;
            this.project = p;
            this.lastChange = lastChange;
        }
K
kohsuke 已提交
620

621
        @Exported
622 623 624
        public User getUser() {
            return user;
        }
K
kohsuke 已提交
625

626
        @Exported
627 628 629
        public Calendar getLastChange() {
            return lastChange;
        }
K
kohsuke 已提交
630

631
        @Exported
K
kohsuke 已提交
632
        public AbstractProject getProject() {
633 634
            return project;
        }
K
kohsuke 已提交
635

636 637 638 639
        /**
         * Returns a human-readable string representation of when this user was last active.
         */
        public String getLastChangeTimeString() {
640 641
            if(lastChange==null)    return "N/A";
            long duration = new GregorianCalendar().getTimeInMillis()- ordinal();
642 643
            return Util.getTimeSpanString(duration);
        }
K
kohsuke 已提交
644

645
        public String getTimeSortKey() {
646
            if(lastChange==null)    return "-";
647
            return Util.XS_DATETIME_FORMATTER.format(lastChange.getTime());
K
kohsuke 已提交
648 649
        }

650
        public int compareTo(UserInfo that) {
651 652
            long rhs = that.ordinal();
            long lhs = this.ordinal();
K
kohsuke 已提交
653 654 655
            if(rhs>lhs) return 1;
            if(rhs<lhs) return -1;
            return 0;
656
        }
657 658 659 660 661

        private long ordinal() {
            if(lastChange==null)    return 0;
            return lastChange.getTimeInMillis();
        }
K
kohsuke 已提交
662 663 664
    }

    /**
665
     * Does this {@link View} has any associated user information recorded?
666
     * @deprecated Potentially very expensive call; do not use from Jelly views.
K
kohsuke 已提交
667
     */
668
    public boolean hasPeople() {
669
        return People.isApplicable(getItems());
670
    }
K
kohsuke 已提交
671

672 673 674
    /**
     * Gets the users that show up in the changelog of this job collection.
     */
675
    public People getPeople() {
676
        return new People(this);
677
    }
678

J
Jesse Glick 已提交
679
    /**
J
@since  
Jesse Glick 已提交
680
     * @since 1.484
J
Jesse Glick 已提交
681 682 683 684 685
     */
    public AsynchPeople getAsynchPeople() {
        return new AsynchPeople(this);
    }

686
    @ExportedBean
687
    public static final class People  {
688 689 690
        @Exported
        public final List<UserInfo> users;

691
        public final ModelObject parent;
692

693
        public People(Jenkins parent) {
694 695
            this.parent = parent;
            // for Hudson, really load all users
696
            Map<User,UserInfo> users = getUserInfo(parent.getItems());
697
            User unknown = User.getUnknown();
698
            for (User u : User.getAll()) {
699
                if(u==unknown)  continue;   // skip the special 'unknown' user
700
                if(!users.containsKey(u))
701 702 703 704 705 706 707
                    users.put(u,new UserInfo(u,null,null));
            }
            this.users = toList(users);
        }

        public People(View parent) {
            this.parent = parent;
708
            this.users = toList(getUserInfo(parent.getItems()));
709 710
        }

711
        private Map<User,UserInfo> getUserInfo(Collection<? extends Item> items) {
712
            Map<User,UserInfo> users = new HashMap<User,UserInfo>();
713
            for (Item item : items) {
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
                for (Job job : item.getAllJobs()) {
                    if (job instanceof AbstractProject) {
                        AbstractProject<?,?> p = (AbstractProject) job;
                        for (AbstractBuild<?,?> build : p.getBuilds()) {
                            for (Entry entry : build.getChangeSet()) {
                                User user = entry.getAuthor();

                                UserInfo info = users.get(user);
                                if(info==null)
                                    users.put(user,new UserInfo(user,p,build.getTimestamp()));
                                else
                                if(info.getLastChange().before(build.getTimestamp())) {
                                    info.project = p;
                                    info.lastChange = build.getTimestamp();
                                }
729
                            }
730 731 732 733
                        }
                    }
                }
            }
734
            return users;
735
        }
736

737
        private List<UserInfo> toList(Map<User,UserInfo> users) {
738 739 740
            ArrayList<UserInfo> list = new ArrayList<UserInfo>();
            list.addAll(users.values());
            Collections.sort(list);
741
            return Collections.unmodifiableList(list);
742
        }
K
kohsuke 已提交
743

744 745 746
        public Api getApi() {
            return new Api(this);
        }
747

748 749 750
        /**
         * @deprecated Potentially very expensive call; do not use from Jelly views.
         */
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
        public static boolean isApplicable(Collection<? extends Item> items) {
            for (Item item : items) {
                for (Job job : item.getAllJobs()) {
                    if (job instanceof AbstractProject) {
                        AbstractProject<?,?> p = (AbstractProject) job;
                        for (AbstractBuild<?,?> build : p.getBuilds()) {
                            for (Entry entry : build.getChangeSet()) {
                                User user = entry.getAuthor();
                                if(user!=null)
                                    return true;
                            }
                        }
                    }
                }
            }
            return false;
        }
K
kohsuke 已提交
768 769
    }

J
Jesse Glick 已提交
770 771
    /**
     * Variant of {@link People} which can be displayed progressively, since it may be slow.
J
@since  
Jesse Glick 已提交
772
     * @since 1.484
J
Jesse Glick 已提交
773 774 775 776 777 778 779 780 781 782
     */
    public static final class AsynchPeople extends ProgressiveRendering { // JENKINS-15206

        private final Collection<TopLevelItem> items;
        private final User unknown;
        private final Map<User,UserInfo> users = new HashMap<User,UserInfo>();
        private final Set<User> modified = new HashSet<User>();
        private final String iconSize;
        public final ModelObject parent;

783
        /** @see Jenkins#getAsynchPeople */
J
Jesse Glick 已提交
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
        public AsynchPeople(Jenkins parent) {
            this.parent = parent;
            items = parent.getItems();
            unknown = User.getUnknown();
        }

        /** @see View#getAsynchPeople */
        public AsynchPeople(View parent) {
            this.parent = parent;
            items = parent.getItems();
            unknown = null;
        }

        {
            StaplerRequest req = Stapler.getCurrentRequest();
            iconSize = req != null ? Functions.getCookie(req, "iconSize", "32x32") : "32x32";
        }

        @Override protected void compute() throws Exception {
            int itemCount = 0;
            for (Item item : items) {
                for (Job<?,?> job : item.getAllJobs()) {
                    if (job instanceof AbstractProject) {
                        AbstractProject<?,?> p = (AbstractProject) job;
                        RunList<? extends AbstractBuild<?,?>> builds = p.getBuilds();
                        int buildCount = 0;
                        for (AbstractBuild<?,?> build : builds) {
                            if (canceled()) {
                                return;
                            }
                            for (ChangeLogSet.Entry entry : build.getChangeSet()) {
                                User user = entry.getAuthor();
816 817 818
                                UserInfo info = users.get(user);
                                if (info == null) {
                                    UserInfo userInfo = new UserInfo(user, p, build.getTimestamp());
819
                                    userInfo.avatar = UserAvatarResolver.resolveOrNull(user, iconSize);
820 821
                                    synchronized (this) {
                                        users.put(user, userInfo);
J
Jesse Glick 已提交
822
                                        modified.add(user);
823 824 825
                                    }
                                } else if (info.getLastChange().before(build.getTimestamp())) {
                                    synchronized (this) {
J
Jesse Glick 已提交
826 827 828 829 830 831
                                        info.project = p;
                                        info.lastChange = build.getTimestamp();
                                        modified.add(user);
                                    }
                                }
                            }
832
                            // TODO consider also adding the user of the UserCause when applicable
J
Jesse Glick 已提交
833
                            buildCount++;
J
Jesse Glick 已提交
834 835
                            // TODO this defeats lazy-loading. Should rather do a breadth-first search, as in hudson.plugins.view.dashboard.builds.LatestBuilds
                            // (though currently there is no quick implementation of RunMap.size() ~ idOnDisk.size(), which would be needed for proper progress)
J
Jesse Glick 已提交
836 837 838 839 840 841 842 843 844 845 846
                            progress((itemCount + 1.0 * buildCount / builds.size()) / (items.size() + 1));
                        }
                    }
                }
                itemCount++;
                progress(1.0 * itemCount / (items.size() + /* handling User.getAll */1));
            }
            if (unknown != null) {
                if (canceled()) {
                    return;
                }
847
                for (User u : User.getAll()) { // TODO nice to have a method to iterate these lazily
J
Jesse Glick 已提交
848 849 850 851
                    if (u == unknown) {
                        continue;
                    }
                    if (!users.containsKey(u)) {
852
                        UserInfo userInfo = new UserInfo(u, null, null);
853
                        userInfo.avatar = UserAvatarResolver.resolveOrNull(u, iconSize);
J
Jesse Glick 已提交
854
                        synchronized (this) {
855
                            users.put(u, userInfo);
J
Jesse Glick 已提交
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
                            modified.add(u);
                        }
                    }
                }
            }
        }

        @Override protected synchronized JSON data() {
            JSONArray r = new JSONArray();
            for (User u : modified) {
                UserInfo i = users.get(u);
                JSONObject entry = new JSONObject().
                        accumulate("id", u.getId()).
                        accumulate("fullName", u.getFullName()).
                        accumulate("url", u.getUrl()).
871
                        accumulate("avatar", i.avatar != null ? i.avatar : Stapler.getCurrentRequest().getContextPath() + Functions.getResourcePath() + "/images/" + iconSize + "/user.png").
J
Jesse Glick 已提交
872 873 874 875 876 877 878 879 880 881 882 883 884
                        accumulate("timeSortKey", i.getTimeSortKey()).
                        accumulate("lastChangeTimeString", i.getLastChangeTimeString());
                AbstractProject<?,?> p = i.getProject();
                if (p != null) {
                    entry.accumulate("projectUrl", p.getUrl()).accumulate("projectFullDisplayName", p.getFullDisplayName());
                }
                r.add(entry);
            }
            modified.clear();
            return r;
        }

        public Api getApi() {
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
            return new Api(new People());
        }

        /** JENKINS-16397 workaround */
        @Restricted(NoExternalUse.class)
        @ExportedBean
        public final class People {

            private View.People people;

            @Exported public synchronized List<UserInfo> getUsers() {
                if (people == null) {
                    people = parent instanceof Jenkins ? new View.People((Jenkins) parent) : new View.People((View) parent);
                }
                return people.users;
            }
J
Jesse Glick 已提交
901 902 903 904
        }

    }

905 906 907
    void addDisplayNamesToSearchIndex(SearchIndexBuilder sib, Collection<TopLevelItem> items) {
        for(TopLevelItem item : items) {
            
908 909
            if(LOGGER.isLoggable(Level.FINE)) {
                LOGGER.fine((String.format("Adding url=%s,displayName=%s",
910 911 912 913 914 915
                            item.getSearchUrl(), item.getDisplayName())));
            }
            sib.add(item.getSearchUrl(), item.getDisplayName());
        }        
    }
    
916
    @Override
917
    public SearchIndexBuilder makeSearchIndex() {
918 919
        SearchIndexBuilder sib = super.makeSearchIndex();
        sib.add(new CollectionSearchIndex<TopLevelItem>() {// for jobs in the view
920
                protected TopLevelItem get(String key) { return getItem(key); }
921 922 923 924 925 926
                protected Collection<TopLevelItem> all() { return getItems(); }                
                @Override
                protected String getName(TopLevelItem o) {
                    // return the name instead of the display for suggestion searching
                    return o.getName();
                }
927
            });
928 929 930 931 932
        
        // add the display name for each item in the search index
        addDisplayNamesToSearchIndex(sib, getItems());

        return sib;
933 934
    }

935 936 937 938 939 940 941
    /**
     * Accepts the new description.
     */
    public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        checkPermission(CONFIGURE);

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

K
kohsuke 已提交
946 947 948
    /**
     * Accepts submission from the configuration page.
     *
949
     * Subtypes should override the {@link #submit(StaplerRequest)} method.
K
kohsuke 已提交
950
     */
951
    @RequirePOST
952 953
    public final synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
        checkPermission(CONFIGURE);
K
kohsuke 已提交
954

955
        submit(req);
K
kohsuke 已提交
956

957
        description = Util.nullify(req.getParameter("description"));
958 959
        filterExecutors = req.getParameter("filterExecutors") != null;
        filterQueue = req.getParameter("filterQueue") != null;
K
kohsuke 已提交
960

961
        rename(req.getParameter("name"));
K
kohsuke 已提交
962

963
        getProperties().rebuild(req, req.getSubmittedForm(), getApplicablePropertyDescriptors());
964
        updateTransientActions();  
965

966
        save();
K
kohsuke 已提交
967

968
        FormApply.success("../" + Util.rawEncode(name)).generateResponse(req,rsp,this);
K
kohsuke 已提交
969 970 971 972 973 974 975 976 977
    }

    /**
     * Handles the configuration submission.
     *
     * Load view-specific properties here.
     */
    protected abstract void submit(StaplerRequest req) throws IOException, ServletException, FormException;

978 979 980
    /**
     * Deletes this view.
     */
981
    @RequirePOST
982
    public synchronized void doDoDelete(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
983 984 985
        checkPermission(DELETE);

        owner.deleteView(this);
986

987
        rsp.sendRedirect2(req.getContextPath()+"/" + owner.getUrl());
988 989 990
    }


K
kohsuke 已提交
991
    /**
992
     * Creates a new {@link Item} in this collection.
993
     *
994
     * <p>
995
     * This method should call {@link ModifiableItemGroup#doCreateItem(StaplerRequest, StaplerResponse)}
996 997
     * and then add the newly created item to this view.
     * 
998 999
     * @return
     *      null if fails.
K
kohsuke 已提交
1000
     */
K
kohsuke 已提交
1001
    public abstract Item doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException;
1002 1003

    public void doRssAll( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
K
kohsuke 已提交
1004
        rss(req, rsp, " all builds", getBuilds());
K
kohsuke 已提交
1005 1006
    }

1007
    public void doRssFailed( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
K
kohsuke 已提交
1008
        rss(req, rsp, " failed builds", getBuilds().failureOnly());
1009
    }
1010 1011
    
    public RunList getBuilds() {
1012
        return new RunList(this);
1013
    }
1014 1015 1016 1017
    
    public BuildTimelineWidget getTimeline() {
        return new BuildTimelineWidget(getBuilds());
    }
K
kohsuke 已提交
1018

1019 1020 1021
    private void rss(StaplerRequest req, StaplerResponse rsp, String suffix, RunList runs) throws IOException, ServletException {
        RSS.forwardToRss(getDisplayName()+ suffix, getUrl(),
            runs.newBuilds(), Run.FEED_ADAPTER, req, rsp );
K
kohsuke 已提交
1022
    }
1023

K
kohsuke 已提交
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
    public void doRssLatest( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        List<Run> lastBuilds = new ArrayList<Run>();
        for (TopLevelItem item : getItems()) {
            if (item instanceof Job) {
                Job job = (Job) item;
                Run lb = job.getLastBuild();
                if(lb!=null)    lastBuilds.add(lb);
            }
        }
        RSS.forwardToRss(getDisplayName()+" last builds only", getUrl(),
            lastBuilds, Run.FEED_ADAPTER_LATEST, req, rsp );
    }

1037 1038 1039 1040
    /**
     * Accepts <tt>config.xml</tt> submission, as well as serve it.
     */
    @WebMethod(name = "config.xml")
1041
    public HttpResponse doConfigDotXml(StaplerRequest req) throws IOException {
1042 1043 1044
        if (req.getMethod().equals("GET")) {
            // read
            checkPermission(READ);
1045 1046 1047
            return new HttpResponse() {
                public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException {
                    rsp.setContentType("application/xml");
1048
                    View.this.writeXml(rsp.getOutputStream());
1049 1050
                }
            };
1051 1052 1053
        }
        if (req.getMethod().equals("POST")) {
            // submission
1054
            updateByXml(new StreamSource(req.getReader()));
1055
            return HttpResponses.ok();
1056 1057 1058
        }

        // huh?
1059
        return HttpResponses.error(SC_BAD_REQUEST, "Unexpected request method " + req.getMethod());
1060 1061
    }

1062
    /**
1063
     * @since 1.538
1064 1065 1066 1067 1068 1069 1070 1071
     */
    public void writeXml(OutputStream out) throws IOException {
        // pity we don't have a handy way to clone Jenkins.XSTREAM to temp add the omit Field
        XStream2 xStream2 = new XStream2();
        xStream2.omitField(View.class, "owner");
        xStream2.toXMLUTF8(View.this,  out);
    }

1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
    /**
     * Updates Job by its XML definition.
     */
    public void updateByXml(Source source) throws IOException {
        checkPermission(CONFIGURE);
        StringWriter out = new StringWriter();
        try {
            // this allows us to use UTF-8 for storing data,
            // plus it checks any well-formedness issue in the submitted
            // data
            Transformer t = TransformerFactory.newInstance()
                    .newTransformer();
            t.transform(source,
                    new StreamResult(out));
            out.close();
        } catch (TransformerException e) {
            throw new IOException2("Failed to persist configuration.xml", e);
        }

        // try to reflect the changes by reloading
        InputStream in = new BufferedInputStream(new ByteArrayInputStream(out.toString().getBytes("UTF-8")));
        try {
1094 1095 1096
            // Do not allow overwriting view name as it might collide with another
            // view in same ViewGroup and might not satisfy Jenkins.checkGoodName.
            String oldname = name;
1097
            Jenkins.XSTREAM.unmarshal(new XppDriver().createReader(in), this);
1098
            name = oldname;
1099 1100 1101 1102 1103 1104 1105 1106 1107
        } catch (StreamException e) {
            throw new IOException2("Unable to read",e);
        } catch(ConversionException e) {
            throw new IOException2("Unable to read",e);
        } catch(Error e) {// mostly reflection errors
            throw new IOException2("Unable to read",e);
        } finally {
            in.close();
        }
1108
        save();
1109 1110
    }

1111 1112 1113 1114 1115 1116
    public ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse response) throws Exception {
        ContextMenu m = new ContextMenu();
        for (TopLevelItem i : getItems())
            m.add(i.getShortUrl(),i.getDisplayName());
        return m;
    }
1117

1118 1119
    /**
     * A list of available view types.
1120 1121
     * @deprecated as of 1.286
     *      Use {@link #all()} for read access, and use {@link Extension} for registration.
1122
     */
1123
    public static final DescriptorList<View> LIST = new DescriptorList<View>(View.class);
1124

1125 1126 1127 1128
    /**
     * Returns all the registered {@link ViewDescriptor}s.
     */
    public static DescriptorExtensionList<View,ViewDescriptor> all() {
1129
        return Jenkins.getInstance().<View,ViewDescriptor>getDescriptorList(View.class);
1130 1131
    }

1132 1133 1134 1135 1136 1137 1138 1139
    public static List<ViewDescriptor> allInstantiable() {
        List<ViewDescriptor> r = new ArrayList<ViewDescriptor>();
        for (ViewDescriptor d : all())
            if(d.isInstantiable())
                r.add(d);
        return r;
    }

1140 1141 1142 1143 1144
    public static final Comparator<View> SORTER = new Comparator<View>() {
        public int compare(View lhs, View rhs) {
            return lhs.getViewName().compareTo(rhs.getViewName());
        }
    };
1145

1146
    public static final PermissionGroup PERMISSIONS = new PermissionGroup(View.class,Messages._View_Permissions_Title());
1147
    /**
1148
     * Permission to create new views.
1149
     */
1150 1151 1152
    public static final Permission CREATE = new Permission(PERMISSIONS,"Create", Messages._View_CreatePermission_Description(), Permission.CREATE, PermissionScope.ITEM_GROUP);
    public static final Permission DELETE = new Permission(PERMISSIONS,"Delete", Messages._View_DeletePermission_Description(), Permission.DELETE, PermissionScope.ITEM_GROUP);
    public static final Permission CONFIGURE = new Permission(PERMISSIONS,"Configure", Messages._View_ConfigurePermission_Description(), Permission.CONFIGURE, PermissionScope.ITEM_GROUP);
1153
    public static final Permission READ = new Permission(PERMISSIONS,"Read", Messages._View_ReadPermission_Description(), Permission.READ, PermissionScope.ITEM_GROUP);
1154 1155 1156 1157 1158

    // to simplify access from Jelly
    public static Permission getItemCreatePermission() {
        return Item.CREATE;
    }
K
kohsuke 已提交
1159
    
1160
    public static View create(StaplerRequest req, StaplerResponse rsp, ViewGroup owner)
1161
            throws FormException, IOException, ServletException {
1162 1163 1164 1165 1166 1167
        String requestContentType = req.getContentType();
        if(requestContentType==null)
            throw new Failure("No Content-Type header set");

        boolean isXmlSubmission = requestContentType.startsWith("application/xml") || requestContentType.startsWith("text/xml");

1168 1169 1170
        String name = req.getParameter("name");
        checkGoodName(name);
        if(owner.getView(name)!=null)
1171
            throw new Failure(Messages.Hudson_ViewAlreadyExists(name));
K
kohsuke 已提交
1172

1173
        String mode = req.getParameter("mode");
1174 1175 1176 1177 1178 1179 1180 1181
        if (mode==null || mode.length()==0) {
            if(isXmlSubmission) {
                View v;
                v = createViewFromXML(name, req.getInputStream());
                v.owner = owner;
                rsp.setStatus(HttpServletResponse.SC_OK);
                return v;
            } else
1182
                throw new Failure(Messages.View_MissingMode());
1183
        }
1184

1185 1186 1187 1188 1189
        ViewDescriptor descriptor = all().findByName(mode);
        if (descriptor == null) {
            throw new Failure("No view type ‘" + mode + "’ is known");
        }

K
kohsuke 已提交
1190
        // create a view
1191
        View v = descriptor.newInstance(req,req.getSubmittedForm());
K
kohsuke 已提交
1192 1193 1194
        v.owner = owner;

        // redirect to the config screen
K
kohsuke 已提交
1195
        rsp.sendRedirect2(req.getContextPath()+'/'+v.getUrl()+v.getPostConstructLandingPage());
K
kohsuke 已提交
1196 1197 1198

        return v;
    }
1199

1200 1201 1202 1203 1204
    /**
     * Instantiate View subtype from XML stream.
     *
     * @param name Alternative name to use or <tt>null</tt> to keep the one in xml.
     */
1205 1206 1207 1208
    public static View createViewFromXML(String name, InputStream xml) throws IOException {
        InputStream in = new BufferedInputStream(xml);
        try {
            View v = (View) Jenkins.XSTREAM.fromXML(in);
1209 1210
            if (name != null) v.name = name;
            checkGoodName(v.name);
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
            return v;
        } catch(StreamException e) {
            throw new IOException2("Unable to read",e);
        } catch(ConversionException e) {
            throw new IOException2("Unable to read",e);
        } catch(Error e) {// mostly reflection errors
            throw new IOException2("Unable to read",e);
        } finally {
            in.close();
        }
    }

1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
    public static class PropertyList extends DescribableList<ViewProperty,ViewPropertyDescriptor> {
        private PropertyList(View owner) {
            super(owner);
        }

        public PropertyList() {// needed for XStream deserialization
        }

        public View getOwner() {
            return (View)owner;
1233 1234 1235 1236 1237
        }

        @Override
        protected void onModified() throws IOException {
            for (ViewProperty p : this)
1238
                p.setView(getOwner());
1239 1240
        }
    }
1241 1242 1243 1244 1245 1246

    /**
     * "Job" in "New Job". When a view is used in a context that restricts the child type,
     * It might be useful to override this.
     */
    public static final Message<View> NEW_PRONOUN = new Message<View>();
1247 1248

    private final static Logger LOGGER = Logger.getLogger(View.class.getName());
K
kohsuke 已提交
1249
}