forked from jenkinsci/jenkins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ListView.java
626 lines (557 loc) · 20.5 KB
/
ListView.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
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Erik Ramfelt, Seiji Sogabe, Martin Eigenbrodt, Alan Harder
*
* 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 edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.Util;
import hudson.diagnosis.OldDataMonitor;
import hudson.model.Descriptor.FormException;
import hudson.model.listeners.ItemListener;
import hudson.search.SearchIndexBuilder;
import hudson.security.ACL;
import hudson.security.ACLContext;
import hudson.util.DescribableList;
import hudson.util.FormValidation;
import hudson.util.HttpResponses;
import hudson.views.ListViewColumn;
import hudson.views.StatusFilter;
import hudson.views.ViewJobFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.servlet.ServletException;
import jenkins.model.Jenkins;
import net.jcip.annotations.GuardedBy;
import net.sf.json.JSONObject;
import org.jenkinsci.Symbol;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.kohsuke.stapler.verb.POST;
import org.springframework.security.access.AccessDeniedException;
/**
* Displays {@link Job}s in a flat list view.
*
* @author Kohsuke Kawaguchi
*/
public class ListView extends View implements DirectlyModifiableView {
/**
* List of job names. This is what gets serialized.
*/
@GuardedBy("this")
/*package*/ /*almost-final*/ SortedSet<String> jobNames = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
private DescribableList<ViewJobFilter, Descriptor<ViewJobFilter>> jobFilters;
private DescribableList<ListViewColumn, Descriptor<ListViewColumn>> columns;
/**
* Include regex string.
*/
private String includeRegex;
/**
* Whether to recurse in ItemGroups
*/
private boolean recurse;
/**
* Compiled include pattern from the includeRegex string.
*/
private transient Pattern includePattern;
/**
* Filter by enabled/disabled status of jobs.
* Null for no filter, true for enabled-only, false for disabled-only.
* @deprecated Status filter is now controlled via a {@link ViewJobFilter}, see {@link StatusFilter}
*/
@Deprecated
private transient Boolean statusFilter;
@DataBoundConstructor
public ListView(String name) {
super(name);
initColumns();
initJobFilters();
}
public ListView(String name, ViewGroup owner) {
this(name);
this.owner = owner;
}
/**
* Sets the columns of this view.
*/
@DataBoundSetter
public void setColumns(List<ListViewColumn> columns) throws IOException {
this.columns.replaceBy(columns);
}
@DataBoundSetter
public void setJobFilters(List<ViewJobFilter> jobFilters) throws IOException {
this.jobFilters.replaceBy(jobFilters);
}
protected Object readResolve() {
if (includeRegex != null) {
try {
includePattern = Pattern.compile(includeRegex);
} catch (PatternSyntaxException x) {
includeRegex = null;
OldDataMonitor.report(this, Set.of(x));
}
}
synchronized (this) {
if (jobNames == null) {
jobNames = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
}
}
initColumns();
initJobFilters();
if (statusFilter != null) {
jobFilters.add(new StatusFilter(statusFilter));
}
return this;
}
protected void initColumns() {
if (columns == null)
columns = new DescribableList<>(this,
ListViewColumn.createDefaultInitialColumnList(getClass())
);
}
protected void initJobFilters() {
if (jobFilters == null)
jobFilters = new DescribableList<>(this);
}
/**
* Used to determine if we want to display the Add button.
*/
public boolean hasJobFilterExtensions() {
return !ViewJobFilter.all().isEmpty();
}
public DescribableList<ViewJobFilter, Descriptor<ViewJobFilter>> getJobFilters() {
return jobFilters;
}
@Override
public DescribableList<ListViewColumn, Descriptor<ListViewColumn>> getColumns() {
return columns;
}
public synchronized Set<String> getJobNames() {
return Collections.unmodifiableSet(jobNames);
}
/**
* Returns a read-only view of all {@link Job}s in this view.
*
* <p>
* This method returns a separate copy each time to avoid
* concurrent modification issue.
*/
@Override
public List<TopLevelItem> getItems() {
return getItems(this.recurse);
}
/**
* Returns a read-only view of all {@link Job}s in this view.
*
*
* <p>
* This method returns a separate copy each time to avoid
* concurrent modification issue.
* @param recurse {@code false} not to recurse in ItemGroups
* true to recurse in ItemGroups
*/
private List<TopLevelItem> getItems(boolean recurse) {
SortedSet<String> names;
List<TopLevelItem> items = new ArrayList<>();
synchronized (this) {
names = new TreeSet<>(jobNames);
}
ItemGroup<? extends TopLevelItem> parent = getOwner().getItemGroup();
if (recurse) {
if (!names.isEmpty() || includePattern != null) {
items.addAll(parent.getAllItems(TopLevelItem.class, item -> {
String itemName = item.getRelativeNameFrom(parent);
if (names.contains(itemName)) {
return true;
}
if (includePattern != null) {
return includePattern.matcher(itemName).matches();
}
return false;
}));
}
} else {
for (String name : names) {
try {
TopLevelItem i = parent.getItem(name);
if (i != null) {
items.add(i);
}
} catch (AccessDeniedException e) {
//Ignore
}
}
if (includePattern != null) {
items.addAll(parent.getItems(item -> {
String itemName = item.getRelativeNameFrom(parent);
return includePattern.matcher(itemName).matches();
}));
}
}
Collection<ViewJobFilter> jobFilters = getJobFilters();
if (!jobFilters.isEmpty()) {
List<TopLevelItem> candidates = recurse ? parent.getAllItems(TopLevelItem.class) : new ArrayList<>(parent.getItems());
// check the filters
for (ViewJobFilter jobFilter : jobFilters) {
items = jobFilter.filter(items, candidates, this);
}
}
// for sanity, trim off duplicates
items = new ArrayList<>(new LinkedHashSet<>(items));
return items;
}
@Override
public SearchIndexBuilder makeSearchIndex() {
SearchIndexBuilder sib = new SearchIndexBuilder().addAllAnnotations(this);
makeSearchIndex(sib);
// add the display name for each item in the search index
addDisplayNamesToSearchIndex(sib, getItems(true));
return sib;
}
@Override
public boolean contains(TopLevelItem item) {
return getItems().contains(item);
}
public synchronized boolean jobNamesContains(TopLevelItem item) {
if (item == null) return false;
return jobNames.contains(item.getRelativeNameFrom(getOwner().getItemGroup()));
}
/**
* Adds the given item to this view.
*
* @since 1.389
*/
@Override
public void add(TopLevelItem item) throws IOException {
synchronized (this) {
jobNames.add(item.getRelativeNameFrom(getOwner().getItemGroup()));
}
save();
}
/**
* Removes given item from this view.
*
* @since 1.566
*/
@Override
public boolean remove(TopLevelItem item) throws IOException {
synchronized (this) {
String name = item.getRelativeNameFrom(getOwner().getItemGroup());
if (!jobNames.remove(name)) return false;
}
save();
return true;
}
public String getIncludeRegex() {
return includeRegex;
}
public boolean isRecurse() {
return recurse;
}
/**
* @since 1.568
*/
@DataBoundSetter
public void setRecurse(boolean recurse) {
this.recurse = recurse;
}
/**
* Filter by enabled/disabled status of jobs.
* Null for no filter, true for enabled-only, false for disabled-only.
* @deprecated Status filter is now controlled via a {@link ViewJobFilter}, see {@link StatusFilter}
*/
@Deprecated
public Boolean getStatusFilter() {
return statusFilter;
}
/**
* Determines the initial state of the checkbox.
*
* @return true when the view is empty or already contains jobs specified by name.
*/
@Restricted(NoExternalUse.class) // called from newJob_button-bar view
@SuppressWarnings("unused") // called from newJob_button-bar view
public boolean isAddToCurrentView() {
synchronized (this) {
return !jobNames.isEmpty() || // There are already items in this view specified by name
(jobFilters.isEmpty() && includePattern == null) // No other way to include items is used
;
}
}
private boolean needToAddToCurrentView(StaplerRequest req) throws ServletException {
String json = req.getParameter("json");
if (json != null && json.length() > 0) {
// Submitted via UI
JSONObject form = req.getSubmittedForm();
return form.has("addToCurrentView") && form.getBoolean("addToCurrentView");
} else {
// Submitted via API
return true;
}
}
@Override
@POST
public Item doCreateItem(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
ItemGroup<? extends TopLevelItem> ig = getOwner().getItemGroup();
if (ig instanceof ModifiableItemGroup) {
TopLevelItem item = ((ModifiableItemGroup<? extends TopLevelItem>) ig).doCreateItem(req, rsp);
if (item != null) {
if (needToAddToCurrentView(req)) {
synchronized (this) {
jobNames.add(item.getRelativeNameFrom(getOwner().getItemGroup()));
}
owner.save();
}
}
return item;
}
return null;
}
@Override
@RequirePOST
public HttpResponse doAddJobToView(@QueryParameter String name) throws IOException, ServletException {
checkPermission(View.CONFIGURE);
if (name == null)
throw new Failure("Query parameter 'name' is required");
TopLevelItem item = resolveName(name);
if (item == null)
throw new Failure("Query parameter 'name' does not correspond to a known item");
if (contains(item)) return HttpResponses.ok();
add(item);
owner.save();
return HttpResponses.ok();
}
@Override
@RequirePOST
public HttpResponse doRemoveJobFromView(@QueryParameter String name) throws IOException, ServletException {
checkPermission(View.CONFIGURE);
if (name == null)
throw new Failure("Query parameter 'name' is required");
TopLevelItem item = resolveName(name);
if (item == null)
throw new Failure("Query parameter 'name' does not correspond to a known and readable item");
if (remove(item))
owner.save();
return HttpResponses.ok();
}
private @CheckForNull TopLevelItem resolveName(String name) {
TopLevelItem item = getOwner().getItemGroup().getItem(name);
if (item == null) {
name = Items.getCanonicalName(getOwner().getItemGroup(), name);
item = Jenkins.get().getItemByFullName(name, TopLevelItem.class);
}
return item;
}
/**
* Handles the configuration submission.
*
* Load view-specific properties here.
*/
@Override
protected void submit(StaplerRequest req) throws ServletException, FormException, IOException {
JSONObject json = req.getSubmittedForm();
synchronized (this) {
recurse = json.optBoolean("recurse", true);
jobNames.clear();
Iterable<? extends TopLevelItem> items;
if (recurse) {
items = getOwner().getItemGroup().getAllItems(TopLevelItem.class);
} else {
items = getOwner().getItemGroup().getItems();
}
for (TopLevelItem item : items) {
String relativeNameFrom = item.getRelativeNameFrom(getOwner().getItemGroup());
if (req.getParameter(relativeNameFrom) != null) {
jobNames.add(relativeNameFrom);
}
}
}
setIncludeRegex(req.getParameter("useincluderegex") != null ? req.getParameter("includeRegex") : null);
if (columns == null) {
columns = new DescribableList<>(this);
}
columns.rebuildHetero(req, json, ListViewColumn.all(), "columns");
if (jobFilters == null) {
jobFilters = new DescribableList<>(this);
}
jobFilters.rebuildHetero(req, json, ViewJobFilter.all(), "jobFilters");
String filter = Util.fixEmpty(req.getParameter("statusFilter"));
statusFilter = filter != null ? "1".equals(filter) : null;
}
/** @since 1.526 */
@DataBoundSetter
public void setIncludeRegex(String includeRegex) {
this.includeRegex = Util.nullify(includeRegex);
if (this.includeRegex == null)
this.includePattern = null;
else
this.includePattern = Pattern.compile(includeRegex);
}
@DataBoundSetter
public synchronized void setJobNames(Set<String> jobNames) {
this.jobNames = new TreeSet<>(jobNames);
}
/**
* @deprecated Status filter is now controlled via a {@link ViewJobFilter}, see {@link StatusFilter}
*/
@Deprecated
@DataBoundSetter
public void setStatusFilter(Boolean statusFilter) {
this.statusFilter = statusFilter;
}
@Extension @Symbol("list")
public static class DescriptorImpl extends ViewDescriptor {
@NonNull
@Override
public String getDisplayName() {
return Messages.ListView_DisplayName();
}
/**
* Checks if the include regular expression is valid.
*/
public FormValidation doCheckIncludeRegex(@QueryParameter String value) throws IOException, ServletException, InterruptedException {
String v = Util.fixEmpty(value);
if (v != null) {
try {
Pattern.compile(v);
} catch (PatternSyntaxException pse) {
return FormValidation.error(pse.getMessage());
}
}
return FormValidation.ok();
}
}
/**
* @deprecated as of 1.391
* Use {@link ListViewColumn#createDefaultInitialColumnList()}
*/
@Deprecated
public static List<ListViewColumn> getDefaultColumns() {
return ListViewColumn.createDefaultInitialColumnList(ListView.class);
}
@Restricted(NoExternalUse.class)
@Extension
public static final class Listener extends ItemListener {
@Override
public void onLocationChanged(final Item item, final String oldFullName, final String newFullName) {
try (ACLContext acl = ACL.as2(ACL.SYSTEM2)) {
locationChanged(oldFullName, newFullName);
}
}
private void locationChanged(String oldFullName, String newFullName) {
final Jenkins jenkins = Jenkins.get();
locationChanged(jenkins, oldFullName, newFullName);
for (Item g : jenkins.allItems()) {
if (g instanceof ViewGroup) {
locationChanged((ViewGroup) g, oldFullName, newFullName);
}
}
}
private void locationChanged(ViewGroup vg, String oldFullName, String newFullName) {
for (View v : vg.getViews()) {
if (v instanceof ListView) {
renameViewItem(oldFullName, newFullName, vg, (ListView) v);
}
if (v instanceof ViewGroup) {
locationChanged((ViewGroup) v, oldFullName, newFullName);
}
}
}
private void renameViewItem(String oldFullName, String newFullName, ViewGroup vg, ListView lv) {
boolean needsSave;
synchronized (lv) {
Set<String> oldJobNames = new HashSet<>(lv.jobNames);
lv.jobNames.clear();
for (String oldName : oldJobNames) {
lv.jobNames.add(Items.computeRelativeNamesAfterRenaming(oldFullName, newFullName, oldName, vg.getItemGroup()));
}
needsSave = !oldJobNames.equals(lv.jobNames);
}
if (needsSave) { // do not hold ListView lock at the time
try {
lv.save();
} catch (IOException x) {
Logger.getLogger(ListView.class.getName()).log(Level.WARNING, null, x);
}
}
}
@Override
public void onDeleted(final Item item) {
try (ACLContext acl = ACL.as2(ACL.SYSTEM2)) {
deleted(item);
}
}
private void deleted(Item item) {
final Jenkins jenkins = Jenkins.get();
deleted(jenkins, item);
for (Item g : jenkins.allItems()) {
if (g instanceof ViewGroup) {
deleted((ViewGroup) g, item);
}
}
}
private void deleted(ViewGroup vg, Item item) {
for (View v : vg.getViews()) {
if (v instanceof ListView) {
deleteViewItem(item, vg, (ListView) v);
}
if (v instanceof ViewGroup) {
deleted((ViewGroup) v, item);
}
}
}
private void deleteViewItem(Item item, ViewGroup vg, ListView lv) {
boolean needsSave;
synchronized (lv) {
needsSave = lv.jobNames.remove(item.getRelativeNameFrom(vg.getItemGroup()));
}
if (needsSave) {
try {
lv.save();
} catch (IOException x) {
Logger.getLogger(ListView.class.getName()).log(Level.WARNING, null, x);
}
}
}
}
}