/
View.java
1286 lines (1124 loc) · 43.5 KB
/
View.java
1
2
3
4
5
6
7
8
9
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
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
280
281
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
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
368
369
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* The MIT License
*
* Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi, Tom Huybrechts,
* Yahoo!, Inc.
*
* 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.
*/
package hudson.model;
import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.io.StreamException;
import com.thoughtworks.xstream.io.xml.XppDriver;
import hudson.DescriptorExtensionList;
import hudson.Extension;
import hudson.ExtensionPoint;
import hudson.Functions;
import hudson.Indenter;
import hudson.Util;
import hudson.model.Descriptor.FormException;
import hudson.model.labels.LabelAtomPropertyDescriptor;
import hudson.scm.ChangeLogSet;
import hudson.scm.ChangeLogSet.Entry;
import hudson.search.CollectionSearchIndex;
import hudson.search.SearchIndexBuilder;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.security.PermissionScope;
import hudson.tasks.UserAvatarResolver;
import hudson.util.AlternativeUiTextProvider;
import hudson.util.AlternativeUiTextProvider.Message;
import hudson.util.DescribableList;
import hudson.util.DescriptorList;
import hudson.util.FormApply;
import hudson.util.RunList;
import hudson.util.XStream2;
import hudson.views.ListViewColumn;
import hudson.widgets.Widget;
import jenkins.model.item_category.Categories;
import jenkins.model.Jenkins;
import jenkins.model.ModelObjectWithChildren;
import jenkins.util.ProgressiveRendering;
import jenkins.util.xml.XMLUtils;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.tools.ant.filters.StringInputStream;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.WebMethod;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.interceptor.RequirePOST;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static jenkins.model.Jenkins.*;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.xml.sax.SAXException;
/**
* Encapsulates the rendering of the list of {@link TopLevelItem}s
* that {@link Jenkins} owns.
*
* <p>
* This is an extension point in Hudson, allowing different kind of
* rendering to be added as plugins.
*
* <h2>Note for implementers</h2>
* <ul>
* <li>
* {@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.
* </ul>
*
* @author Kohsuke Kawaguchi
* @see ViewDescriptor
* @see ViewGroup
*/
@ExportedBean
public abstract class View extends AbstractModelObject implements AccessControlled, Describable<View>, ExtensionPoint, Saveable, ModelObjectWithChildren {
/**
* Container of this view. Set right after the construction
* and never change thereafter.
*/
protected /*final*/ ViewGroup owner;
/**
* Name of this view.
*/
protected String name;
/**
* Message displayed in the view page.
*/
protected String description;
/**
* If true, only show relevant executors
*/
protected boolean filterExecutors;
/**
* If true, only show relevant queue items
*/
protected boolean filterQueue;
protected transient List<Action> transientActions;
/**
* List of {@link ViewProperty}s configured for this view.
* @since 1.406
*/
private volatile DescribableList<ViewProperty,ViewPropertyDescriptor> properties = new PropertyList(this);
protected View(String name) {
this.name = name;
}
protected View(String name, ViewGroup owner) {
this.name = name;
this.owner = owner;
}
/**
* Gets all the items in this collection in a read-only view.
*/
@Exported(name="jobs")
public abstract Collection<TopLevelItem> getItems();
/**
* Gets all the items recursively contained in this collection in a read-only view.
* <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.
*
* @since 1.520
*/
public Collection<TopLevelItem> getAllItems() {
if (this instanceof ViewGroup) {
final Collection<TopLevelItem> items = new LinkedHashSet<TopLevelItem>(getItems());
for(View view: ((ViewGroup) this).getViews()) {
items.addAll(view.getAllItems());
}
return Collections.unmodifiableCollection(items);
} else {
return getItems();
}
}
/**
* Gets the {@link TopLevelItem} of the given name.
*/
public TopLevelItem getItem(String name) {
return getOwnerItemGroup().getItem(name);
}
/**
* Alias for {@link #getItem(String)}. This is the one used in the URL binding.
*/
public final TopLevelItem getJob(String name) {
return getItem(name);
}
/**
* Checks if the job is in this collection.
*/
public abstract boolean contains(TopLevelItem item);
/**
* Gets the name of all this collection.
*
* @see #rename(String)
*/
@Exported(visibility=2,name="name")
public String getViewName() {
return name;
}
/**
* Renames this view.
*/
public void rename(String newName) throws Failure, FormException {
if(name.equals(newName)) return; // noop
checkGoodName(newName);
if(owner.getView(newName)!=null)
throw new FormException(Messages.Hudson_ViewAlreadyExists(newName),"name");
String oldName = name;
name = newName;
owner.onViewRenamed(this,oldName,newName);
}
/**
* Gets the {@link ViewGroup} that this view belongs to.
*/
public ViewGroup getOwner() {
return owner;
}
/**
* Backward-compatible way of getting {@code getOwner().getItemGroup()}
*/
public ItemGroup<? extends TopLevelItem> getOwnerItemGroup() {
try {
return owner.getItemGroup();
} catch (AbstractMethodError e) {
return Jenkins.getInstance();
}
}
public View getOwnerPrimaryView() {
try {
return _getOwnerPrimaryView();
} catch (AbstractMethodError e) {
return null;
}
}
private View _getOwnerPrimaryView() {
return owner.getPrimaryView();
}
public List<Action> getOwnerViewActions() {
try {
return _getOwnerViewActions();
} catch (AbstractMethodError e) {
return Jenkins.getInstance().getActions();
}
}
private List<Action> _getOwnerViewActions() {
return owner.getViewActions();
}
/**
* Message displayed in the top page. Can be null. Includes HTML.
*/
@Exported
public String getDescription() {
return description;
}
/**
* Gets the view properties configured for this view.
* @since 1.406
*/
public DescribableList<ViewProperty,ViewPropertyDescriptor> getProperties() {
// 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.
synchronized (PropertyList.class) {
if (properties == null) {
properties = new PropertyList(this);
} else {
properties.setOwner(this);
}
return properties;
}
}
/**
* 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;
}
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();
}
}
/**
* List of all {@link ViewProperty}s exposed primarily for the remoting API.
* @since 1.406
*/
@Exported(name="property",inline=true)
public List<ViewProperty> getAllProperties() {
return getProperties().toList();
}
public ViewDescriptor getDescriptor() {
return (ViewDescriptor) Jenkins.getInstance().getDescriptorOrDie(getClass());
}
public String getDisplayName() {
return getViewName();
}
public String getNewPronoun() {
return AlternativeUiTextProvider.get(NEW_PRONOUN, this, Messages.AbstractItem_Pronoun());
}
/**
* 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;
}
/**
* Enables or disables automatic refreshes of the view.
* By default, automatic refreshes are enabled.
* @since 1.557
*/
public boolean isAutomaticRefreshEnabled() {
return true;
}
/**
* If true, only show relevant executors
*/
public boolean isFilterExecutors() {
return filterExecutors;
}
/**
* If true, only show relevant queue items
*/
public boolean isFilterQueue() {
return filterQueue;
}
/**
* Gets the {@link Widget}s registered on this object.
*
* <p>
* For now, this just returns the widgets registered to Hudson.
*/
public List<Widget> getWidgets() {
return Collections.unmodifiableList(Jenkins.getInstance().getWidgets());
}
/**
* If this view uses <t:projectView> for rendering, this method returns columns to be displayed.
*/
public Iterable<? extends ListViewColumn> getColumns() {
return ListViewColumn.createDefaultInitialColumnList();
}
/**
* If this view uses <t:projectView> for rendering, this method returns the indenter used
* to indent each row.
*/
public Indenter getIndenter() {
return null;
}
/**
* If true, this is a view that renders the top page of Hudson.
*/
public boolean isDefault() {
return getOwnerPrimaryView()==this;
}
public List<Computer> getComputers() {
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) {
if (isRelevant(labels, c)) result.add(c);
}
return result;
}
private boolean isRelevant(Collection<Label> labels, Computer computer) {
Node node = computer.getNode();
if (node == null) return false;
if (labels.contains(null) && node.getMode() == Mode.NORMAL) return true;
for (Label l : labels)
if (l != null && l.contains(node))
return true;
return false;
}
private List<Queue.Item> filterQueue(List<Queue.Item> base) {
if (!isFilterQueue()) {
return base;
}
Collection<TopLevelItem> items = getItems();
List<Queue.Item> result = new ArrayList<Queue.Item>();
for (Queue.Item qi : base) {
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;
}
public List<Queue.Item> getQueueItems() {
return filterQueue(Arrays.asList(Jenkins.getInstance().getQueue().getItems()));
}
/**
* @deprecated Use {@link #getQueueItems()}. As of 1.607 the approximation is no longer needed.
* @return The items in the queue.
*/
@Deprecated
public List<Queue.Item> getApproximateQueueItemsQuickly() {
return filterQueue(Jenkins.getInstance().getQueue().getApproximateItemsQuickly());
}
/**
* Returns the path relative to the context root.
*
* Doesn't start with '/' but ends with '/' (except returns
* empty string when this is the default view).
*/
public String getUrl() {
return isDefault() ? (owner!=null ? owner.getUrl() : "") : getViewUrl();
}
/**
* Same as {@link #getUrl()} except this returns a view/{name} path
* even for the default view.
*/
public String getViewUrl() {
return (owner!=null ? owner.getUrl() : "") + "view/" + Util.rawEncode(getViewName()) + '/';
}
@Override public String toString() {
return super.toString() + "[" + getViewUrl() + "]";
}
public String getSearchUrl() {
return getUrl();
}
/**
* 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.
*
* @see Jenkins#getActions()
*/
public List<Action> getActions() {
List<Action> result = new ArrayList<Action>();
result.addAll(getOwnerViewActions());
synchronized (this) {
if (transientActions == null) {
updateTransientActions();
}
result.addAll(transientActions);
}
return result;
}
public synchronized void updateTransientActions() {
transientActions = TransientViewActionFactory.createAllFor(this);
}
public Object getDynamic(String token) {
for (Action a : getActions()) {
String url = a.getUrlName();
if (url==null) continue;
if(a.getUrlName().equals(token))
return a;
}
return null;
}
/**
* Gets the absolute URL of this view.
*/
@Exported(visibility=2,name="url")
public String getAbsoluteUrl() {
return Jenkins.getInstance().getRootUrl()+getUrl();
}
public Api getApi() {
return new Api(this);
}
/**
* 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";
}
/**
* Returns the {@link ACL} for this object.
*/
public ACL getACL() {
return Jenkins.getInstance().getAuthorizationStrategy().getACL(this);
}
public void checkPermission(Permission p) {
getACL().checkPermission(p);
}
public boolean hasPermission(Permission p) {
return getACL().hasPermission(p);
}
/** @deprecated Does not work properly with moved jobs. Use {@link ItemListener#onLocationChanged} instead. */
@Deprecated
public void onJobRenamed(Item item, String oldName, String newName) {}
@ExportedBean(defaultVisibility=2)
public static final class UserInfo implements Comparable<UserInfo> {
private final User user;
/**
* When did this user made a last commit on any of our projects? Can be null.
*/
private Calendar lastChange;
/**
* Which project did this user commit? Can be null.
*/
private AbstractProject project;
/** @see UserAvatarResolver */
String avatar;
UserInfo(User user, AbstractProject p, Calendar lastChange) {
this.user = user;
this.project = p;
this.lastChange = lastChange;
}
@Exported
public User getUser() {
return user;
}
@Exported
public Calendar getLastChange() {
return lastChange;
}
@Exported
public AbstractProject getProject() {
return project;
}
/**
* Returns a human-readable string representation of when this user was last active.
*/
public String getLastChangeTimeString() {
if(lastChange==null) return "N/A";
long duration = new GregorianCalendar().getTimeInMillis()- ordinal();
return Util.getTimeSpanString(duration);
}
public String getTimeSortKey() {
if(lastChange==null) return "-";
return Util.XS_DATETIME_FORMATTER.format(lastChange.getTime());
}
public int compareTo(UserInfo that) {
long rhs = that.ordinal();
long lhs = this.ordinal();
if(rhs>lhs) return 1;
if(rhs<lhs) return -1;
return 0;
}
private long ordinal() {
if(lastChange==null) return 0;
return lastChange.getTimeInMillis();
}
}
/**
* Does this {@link View} has any associated user information recorded?
* @deprecated Potentially very expensive call; do not use from Jelly views.
*/
@Deprecated
public boolean hasPeople() {
return People.isApplicable(getItems());
}
/**
* Gets the users that show up in the changelog of this job collection.
*/
public People getPeople() {
return new People(this);
}
/**
* @since 1.484
*/
public AsynchPeople getAsynchPeople() {
return new AsynchPeople(this);
}
@ExportedBean
public static final class People {
@Exported
public final List<UserInfo> users;
public final ModelObject parent;
public People(Jenkins parent) {
this.parent = parent;
// for Hudson, really load all users
Map<User,UserInfo> users = getUserInfo(parent.getItems());
User unknown = User.getUnknown();
for (User u : User.getAll()) {
if(u==unknown) continue; // skip the special 'unknown' user
if(!users.containsKey(u))
users.put(u,new UserInfo(u,null,null));
}
this.users = toList(users);
}
public People(View parent) {
this.parent = parent;
this.users = toList(getUserInfo(parent.getItems()));
}
private Map<User,UserInfo> getUserInfo(Collection<? extends Item> items) {
Map<User,UserInfo> users = new HashMap<User,UserInfo>();
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();
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();
}
}
}
}
}
}
return users;
}
private List<UserInfo> toList(Map<User,UserInfo> users) {
ArrayList<UserInfo> list = new ArrayList<UserInfo>();
list.addAll(users.values());
Collections.sort(list);
return Collections.unmodifiableList(list);
}
public Api getApi() {
return new Api(this);
}
/**
* @deprecated Potentially very expensive call; do not use from Jelly views.
*/
@Deprecated
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;
}
}
/**
* Variant of {@link People} which can be displayed progressively, since it may be slow.
* @since 1.484
*/
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;
/** @see Jenkins#getAsynchPeople */
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.validateIconSize(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();
UserInfo info = users.get(user);
if (info == null) {
UserInfo userInfo = new UserInfo(user, p, build.getTimestamp());
userInfo.avatar = UserAvatarResolver.resolveOrNull(user, iconSize);
synchronized (this) {
users.put(user, userInfo);
modified.add(user);
}
} else if (info.getLastChange().before(build.getTimestamp())) {
synchronized (this) {
info.project = p;
info.lastChange = build.getTimestamp();
modified.add(user);
}
}
}
// TODO consider also adding the user of the UserCause when applicable
buildCount++;
// 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)
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;
}
for (User u : User.getAll()) { // TODO nice to have a method to iterate these lazily
if (canceled()) {
return;
}
if (u == unknown) {
continue;
}
if (!users.containsKey(u)) {
UserInfo userInfo = new UserInfo(u, null, null);
userInfo.avatar = UserAvatarResolver.resolveOrNull(u, iconSize);
synchronized (this) {
users.put(u, userInfo);
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()).
accumulate("avatar", i.avatar != null ? i.avatar : Stapler.getCurrentRequest().getContextPath() + Functions.getResourcePath() + "/images/" + iconSize + "/user.png").
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() {
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;
}
}
}
void addDisplayNamesToSearchIndex(SearchIndexBuilder sib, Collection<TopLevelItem> items) {
for(TopLevelItem item : items) {
if(LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine((String.format("Adding url=%s,displayName=%s",
item.getSearchUrl(), item.getDisplayName())));
}
sib.add(item.getSearchUrl(), item.getDisplayName());
}
}
@Override
public SearchIndexBuilder makeSearchIndex() {
SearchIndexBuilder sib = super.makeSearchIndex();
sib.add(new CollectionSearchIndex<TopLevelItem>() {// for jobs in the view
protected TopLevelItem get(String key) { return getItem(key); }
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();
}
});
// add the display name for each item in the search index
addDisplayNamesToSearchIndex(sib, getItems());
return sib;
}
/**
* Accepts the new description.
*/
@RequirePOST
public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
checkPermission(CONFIGURE);
description = req.getParameter("description");
save();
rsp.sendRedirect("."); // go to the top page
}
/**
* Accepts submission from the configuration page.
*
* Subtypes should override the {@link #submit(StaplerRequest)} method.
*/
@RequirePOST
public final synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
checkPermission(CONFIGURE);
submit(req);
description = Util.nullify(req.getParameter("description"));
filterExecutors = req.getParameter("filterExecutors") != null;
filterQueue = req.getParameter("filterQueue") != null;
rename(req.getParameter("name"));
getProperties().rebuild(req, req.getSubmittedForm(), getApplicablePropertyDescriptors());
updateTransientActions();
save();
FormApply.success("../" + Util.rawEncode(name)).generateResponse(req,rsp,this);
}
/**
* Handles the configuration submission.
*
* Load view-specific properties here.
*/
protected abstract void submit(StaplerRequest req) throws IOException, ServletException, FormException;
/**
* Deletes this view.
*/
@RequirePOST
public synchronized void doDoDelete(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
checkPermission(DELETE);
owner.deleteView(this);
rsp.sendRedirect2(req.getContextPath()+"/" + owner.getUrl());
}
/**
* Creates a new {@link Item} in this collection.
*
* <p>
* This method should call {@link ModifiableItemGroup#doCreateItem(StaplerRequest, StaplerResponse)}
* and then add the newly created item to this view.
*
* @return
* null if fails.