-
-
Notifications
You must be signed in to change notification settings - Fork 116
Expand file tree
/
Copy pathAbstractFolder.java
More file actions
1305 lines (1172 loc) · 43.1 KB
/
AbstractFolder.java
File metadata and controls
1305 lines (1172 loc) · 43.1 KB
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 2015-2016 CloudBees, 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 com.cloudbees.hudson.plugins.folder;
import com.cloudbees.hudson.plugins.folder.computed.ComputedFolder;
import com.cloudbees.hudson.plugins.folder.computed.FolderComputation;
import com.cloudbees.hudson.plugins.folder.config.AbstractFolderConfiguration;
import com.cloudbees.hudson.plugins.folder.health.FolderHealthMetric;
import com.cloudbees.hudson.plugins.folder.health.FolderHealthMetricDescriptor;
import com.cloudbees.hudson.plugins.folder.icons.StockFolderIcon;
import com.cloudbees.hudson.plugins.folder.views.AbstractFolderViewHolder;
import com.cloudbees.hudson.plugins.folder.views.DefaultFolderViewHolder;
import hudson.BulkChange;
import hudson.Extension;
import hudson.ExtensionList;
import hudson.Util;
import static hudson.Util.fixEmpty;
import hudson.init.InitMilestone;
import hudson.init.Initializer;
import hudson.model.AbstractItem;
import hudson.model.Action;
import hudson.model.AllView;
import hudson.model.Descriptor;
import hudson.model.Failure;
import hudson.model.HealthReport;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.Items;
import hudson.model.Job;
import hudson.model.ModifiableViewGroup;
import hudson.model.Queue;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.model.TopLevelItem;
import hudson.model.View;
import hudson.model.ViewGroupMixIn;
import hudson.model.listeners.ItemListener;
import hudson.model.listeners.RunListener;
import hudson.search.CollectionSearchIndex;
import hudson.search.SearchIndexBuilder;
import hudson.search.SearchItem;
import hudson.util.AlternativeUiTextProvider;
import hudson.util.CopyOnWriteMap;
import hudson.util.DescribableList;
import hudson.util.FormApply;
import hudson.util.FormValidation;
import hudson.util.HttpResponses;
import hudson.views.DefaultViewsTabBar;
import hudson.views.ViewsTabBar;
import io.jenkins.servlet.ServletExceptionWrapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Stack;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import jenkins.model.DirectlyModifiableTopLevelItemGroup;
import jenkins.model.Jenkins;
import jenkins.model.ModelObjectWithChildren;
import jenkins.model.ProjectNamingStrategy;
import jenkins.model.TransientActionFactory;
import jenkins.security.stapler.StaplerNotDispatchable;
import net.sf.json.JSONObject;
import org.jenkins.ui.icon.IconSpec;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.Beta;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerFallback;
import org.kohsuke.stapler.StaplerOverridable;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerRequest2;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.StaplerResponse2;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.kohsuke.stapler.verb.POST;
import org.springframework.security.access.AccessDeniedException;
/**
* A general-purpose {@link ItemGroup}.
* Base for {@link Folder} and {@link ComputedFolder}.
* <p>
* <b>Extending Folders UI</b><br>
* As any other {@link Item} type, folder types support extension of UI via {@link Action}s.
* These actions can be persisted or added via {@link TransientActionFactory}.
* See <a href="https://wiki.jenkins-ci.org/display/JENKINS/Action+and+its+family+of+subtypes">this page</a>
* for more details about actions.
* In folders actions provide the following features:
* <ul>
* <li>Left sidepanel hyperlink, which opens the page specified by action's {@code index.jelly}.</li>
* <li>Optional summary boxes on the main panel, which may be defined by {@code summary.jelly}.</li>
* </ul>
* @since 4.11-beta-1
*/
@SuppressWarnings({"unchecked", "rawtypes"}) // mistakes in various places
public abstract class AbstractFolder<I extends TopLevelItem> extends AbstractItem implements TopLevelItem, ItemGroup<I>, ModifiableViewGroup, StaplerFallback, ModelObjectWithChildren, StaplerOverridable, IconSpec {
/**
* Our logger.
*/
private static final Logger LOGGER = Logger.getLogger(AbstractFolder.class.getName());
private static final Random ENTROPY = new Random();
private static final int HEALTH_REPORT_CACHE_REFRESH_MIN = Math.max(10, Math.min(1440, Integer.getInteger(
AbstractFolder.class.getName()+".healthReportCacheRefreshMin", 60
)));
private static long loadingTick;
private static final AtomicInteger jobTotal = new AtomicInteger();
private static final AtomicInteger jobEncountered = new AtomicInteger();
private static final AtomicBoolean loadJobTotalRan = new AtomicBoolean();
private static final int TICK_INTERVAL = 15000;
/** Whether execution is currently inside {@link #reloadThis}. */
@Restricted(NoExternalUse.class)
protected static final ThreadLocal<Boolean> reloadingThis = ThreadLocal.withInitial(() -> false);
@Initializer(before=InitMilestone.JOB_LOADED, fatal=false)
public static void loadJobTotal() {
if (!loadJobTotalRan.compareAndSet(false, true)) {
return; // TODO why does Jenkins run the initializer many times?!
}
scan(new File(Jenkins.get().getRootDir(), "jobs"), 0);
// TODO reset count after reload config from disk (otherwise goes up to 200% etc.)
}
private static void scan(File d, int depth) {
File[] projects = d.listFiles();
if (projects == null) {
return;
}
for (File project : projects) {
if (!new File(project, "config.xml").isFile()) {
continue;
}
if (depth > 0) {
jobTotal.incrementAndGet();
}
File jobs = new File(project, "jobs"); // cf. getJobsDir
if (jobs.isDirectory()) {
scan(jobs, depth + 1);
}
}
}
/** Child items, keyed by {@link Item#getName}. */
protected transient Map<String,I> items = new CopyOnWriteMap.Tree<>(String.CASE_INSENSITIVE_ORDER);
private DescribableList<AbstractFolderProperty<?>,AbstractFolderPropertyDescriptor> properties;
private /*almost final*/ AbstractFolderViewHolder folderViews;
/**
* {@link View}s.
*/
@Deprecated
private transient /*almost final*/ CopyOnWriteArrayList<View> views;
/**
* Currently active Views tab bar.
*/
@Deprecated
private transient volatile ViewsTabBar viewsTabBar;
/**
* Name of the primary view.
*/
@Deprecated
private transient volatile String primaryView;
private transient /*almost final*/ ViewGroupMixIn viewGroupMixIn;
private DescribableList<FolderHealthMetric,FolderHealthMetricDescriptor> healthMetrics;
private FolderIcon icon;
private transient volatile long nextHealthReportsRefreshMillis;
private transient volatile List<HealthReport> healthReports;
/**
* Subclasses should also call {@link #init}.
*
* @param parent the parent of this folder.
* @param name the name
*/
protected AbstractFolder(ItemGroup parent, String name) {
super(parent, name);
}
protected void init() {
if (properties == null) {
properties = new DescribableList<>(this);
} else {
properties.setOwner(this);
}
for (AbstractFolderProperty p : properties) {
p.setOwner(this);
}
if (icon == null) {
icon = newDefaultFolderIcon();
}
icon.setOwner(this);
if (folderViews == null) {
if (views != null && !views.isEmpty()) {
if (primaryView != null) {
primaryView = AllView.migrateLegacyPrimaryAllViewLocalizedName(views, primaryView);
}
folderViews = new DefaultFolderViewHolder(views, primaryView, viewsTabBar == null ? newDefaultViewsTabBar()
: viewsTabBar);
} else {
folderViews = newFolderViewHolder();
}
views = null;
primaryView = null;
viewsTabBar = null;
}
viewGroupMixIn = new ViewGroupMixIn(this) {
@Override
protected List<View> views() {
return folderViews.getViews();
}
@Override
protected String primaryView() {
String primaryView = folderViews.getPrimaryView();
return primaryView == null ? folderViews.getViews().get(0).getViewName() : primaryView;
}
@Override
protected void primaryView(String name) {
folderViews.setPrimaryView(name);
}
@Override
public void addView(View v) throws IOException {
if (folderViews.isViewsModifiable()) {
super.addView(v);
}
}
@Override
public boolean canDelete(View view) {
return folderViews.isViewsModifiable() && super.canDelete(view);
}
@Override
public synchronized void deleteView(View view) throws IOException {
if (folderViews.isViewsModifiable()) {
super.deleteView(view);
}
}
};
if (healthMetrics == null) {
healthMetrics = new DescribableList<>(this, AbstractFolderConfiguration.get().getHealthMetrics());
}
}
protected DefaultViewsTabBar newDefaultViewsTabBar() {
return new DefaultViewsTabBar();
}
protected AbstractFolderViewHolder newFolderViewHolder() {
CopyOnWriteArrayList views = new CopyOnWriteArrayList<View>();
try {
initViews(views);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to set up the initial view", e);
}
return new DefaultFolderViewHolder(views, null, newDefaultViewsTabBar());
}
@Override
public String getIconClassName() {
// avoid https://issues.jenkins.io/browse/JENKINS-74990
if (icon.getClass().getName().equals("jenkins.branch.MetadataActionFolderIcon")) {
return getDescriptor().getIconClassName();
}
return icon.getIconClassName();
}
protected FolderIcon newDefaultFolderIcon() {
return new StockFolderIcon();
}
protected void initViews(List<View> views) throws IOException {
AllView v = new AllView("All", this);
views.add(v);
}
/**
* Loads all the child {@link Item}s.
*
* @param parent the parent of the children.
* @param modulesDir Directory that contains sub-directories for each child item.
* @param key the key generating function.
* @param <K> the key type
* @param <V> the child type.
* @return a map of the children keyed by the generated keys.
*/
// TODO replace with ItemGroupMixIn.loadChildren once baseline core has JENKINS-41222 merged
public static <K, V extends TopLevelItem> Map<K, V> loadChildren(AbstractFolder<V> parent, File modulesDir,
Function<? super V, ? extends K> key) {
return ExtensionList.lookupFirst(ChildLoader.class).loadChildren(parent, modulesDir, key);
}
@Override
public String getItemName(File dir, I item) {
String name = childNameGenerator().itemNameFromItem(this, item);
if (name == null) {
name = dir.getName();
}
return name;
}
protected final I itemsPut(String name, I item) {
return items.put(name, item);
}
/**
* Reloads this folder itself.
* Compared to {@link #load}, this method skips parts of {@link #onLoad} such as the call to {@link #loadChildren}.
* Nor will it set {@link Items#whileUpdatingByXml}.
* In the case of a {@link ComputedFolder} it also will not call {@link FolderComputation#load}.
*/
@SuppressWarnings("unchecked")
@Restricted(Beta.class)
public void reloadThis() throws IOException {
LOGGER.fine(() -> "reloadThis " + this);
checkPermission(Item.CONFIGURE);
getConfigFile().unmarshal(this);
boolean old = reloadingThis.get();
try {
reloadingThis.set(true);
onLoad(getParent(), getParent().getItemName(getRootDir(), this));
} finally {
reloadingThis.set(old);
}
}
/**
* Adds an item to be the folder which was already loaded via {@link Items#load}.
* Unlike {@link DirectlyModifiableTopLevelItemGroup#add} this can be used even on a {@link ComputedFolder}.
*/
@Restricted(Beta.class)
public void addLoadedChild(I item, String name) throws IOException, IllegalArgumentException {
if (items.containsKey(name)) {
throw new IllegalArgumentException("already an item '" + name + "'");
}
itemsPut(item.getName(), item);
}
/**
* {@inheritDoc}
*/
@Override
public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
super.onLoad(parent, name);
init();
if (reloadingThis.get()) {
LOGGER.fine(() -> this + " skipping the rest of onLoad");
return;
}
final Thread t = Thread.currentThread();
String n = t.getName();
try {
if (items == null) {
// When Jenkins is getting reloaded, we want children being loaded to be able to find existing items that they will be overriding.
// This is necessary for them to correctly keep the running builds, for example.
// ItemGroupMixIn.loadChildren handles the rest of this logic.
Item current = parent.getItem(name);
if (current != null && current.getClass() == getClass()) {
this.items = ((AbstractFolder) current).items;
}
}
final ChildNameGenerator<AbstractFolder<I>,I> childNameGenerator = childNameGenerator();
items = loadChildren(this, getJobsDir(), item -> {
String fullName = item.getFullName();
t.setName("Loading job " + fullName);
float percentage = 100.0f * jobEncountered.incrementAndGet() / Math.max(1, jobTotal.get());
long now = System.currentTimeMillis();
if (loadingTick == 0) {
loadingTick = now;
} else if (now - loadingTick > TICK_INTERVAL) {
LOGGER.log(Level.INFO, String.format("Loading job %s (%.1f%%)", fullName, percentage));
loadingTick = now;
}
String childName = childNameGenerator.itemNameFromItem(AbstractFolder.this, item);
if (childName == null) {
return childNameGenerator.itemNameFromLegacy(AbstractFolder.this, item.getName());
}
return childName;
});
} finally {
t.setName(n);
}
}
ChildNameGenerator<AbstractFolder<I>,I> childNameGenerator() {
return getDescriptor().childNameGenerator();
}
/**
* {@inheritDoc}
*/
@Override
public AbstractFolderDescriptor getDescriptor() {
return (AbstractFolderDescriptor) Jenkins.get().getDescriptorOrDie(getClass());
}
/**
* May be used to enumerate or remove properties.
* To add properties, use {@link #addProperty}.
* @return the list of properties.
*/
public DescribableList<AbstractFolderProperty<?>,AbstractFolderPropertyDescriptor> getProperties() {
return properties;
}
@SuppressWarnings("rawtypes") // else setOwner will not compile
public void addProperty(AbstractFolderProperty p) throws IOException {
if (!p.getDescriptor().isApplicable(getClass())) {
throw new IllegalArgumentException(p.getClass().getName() + " cannot be applied to " + getClass().getName());
}
p.setOwner(this);
properties.add(p);
}
/**
* May be overridden, but {@link #loadJobTotal} will be inaccurate in that case.
* @return the jobs directory.
*/
protected File getJobsDir() {
return new File(getRootDir(), "jobs");
}
protected final File getRootDirFor(String name) {
return new File(getJobsDir(), name);
}
@Override
public File getRootDirFor(I child) {
return getRootDirFor(childNameGenerator().dirName(this, child));
}
/**
* It is unwise to override this, lest links to children from nondefault {@link View}s break.
* TODO remove this warning if and when JENKINS-35243 is fixed in the baseline.
* {@inheritDoc}
*/
@Override
public String getUrlChildPrefix() {
return "job";
}
/**
* For URL binding.
*
* @param name the name of the child.
* @return the job or {@code null} if there is no such child.
* @see #getUrlChildPrefix
*/
public I getJob(String name) {
return getItem(name);
}
/**
* {@inheritDoc}
*/
@Override
public String getPronoun() {
return AlternativeUiTextProvider.get(PRONOUN, this, getDescriptor().getDisplayName());
}
/**
* Overrides from job properties.
*/
@Override
public Collection<?> getOverrides() {
List<Object> r = new ArrayList<>();
for (AbstractFolderProperty<?> p : properties) {
r.addAll(p.getItemContainerOverrides());
}
return r;
}
/**
* {@inheritDoc}
*/
@Override
public void addView(View v) throws IOException {
viewGroupMixIn.addView(v);
}
/**
* {@inheritDoc}
*/
@Override
public boolean canDelete(View view) {
return viewGroupMixIn.canDelete(view);
}
/**
* {@inheritDoc}
*/
@Override
public void deleteView(View view) throws IOException {
viewGroupMixIn.deleteView(view);
}
/**
* {@inheritDoc}
*/
@Override
public View getView(String name) {
return viewGroupMixIn.getView(name);
}
/**
* {@inheritDoc}
*/
@Exported
@Override
public Collection<View> getViews() {
return viewGroupMixIn.getViews();
}
public AbstractFolderViewHolder getFolderViews() {
return folderViews;
}
public void resetFolderViews() {
folderViews = newFolderViewHolder();
}
/**
* {@inheritDoc}
*/
@Exported
@Override
public View getPrimaryView() {
return viewGroupMixIn.getPrimaryView();
}
public void setPrimaryView(View v) {
if (folderViews.isPrimaryModifiable()) {
folderViews.setPrimaryView(v.getViewName());
}
}
/**
* {@inheritDoc}
*/
@Override
public void onViewRenamed(View view, String oldName, String newName) {
viewGroupMixIn.onViewRenamed(view, oldName, newName);
}
/**
* {@inheritDoc}
*/
@Override
public ViewsTabBar getViewsTabBar() {
return folderViews.getTabBar();
}
/**
* {@inheritDoc}
*/
@Override
public ItemGroup<? extends TopLevelItem> getItemGroup() {
return this;
}
/**
* {@inheritDoc}
*/
@Override
public List<Action> getViewActions() {
return Collections.emptyList();
}
/**
* Fallback to the primary view.
*/
@Override
public View getStaplerFallback() {
return getPrimaryView();
}
/**
* {@inheritDoc}
*/
@Override
protected SearchIndexBuilder makeSearchIndex() {
return super.makeSearchIndex().add(new CollectionSearchIndex<TopLevelItem>() {
/**
* {@inheritDoc}
*/
@Override
protected SearchItem get(String key) {
return Jenkins.get().getItem(key, grp());
}
/**
* {@inheritDoc}
*/
@Override
protected Collection<TopLevelItem> all() {
return Items.getAllItems(grp(), TopLevelItem.class);
}
/**
* {@inheritDoc}
*/
@Override
protected String getName(TopLevelItem j) {
return j.getRelativeNameFrom(grp());
}
/** Disambiguates calls that otherwise would match {@link Item} too. */
private ItemGroup<?> grp() {
return AbstractFolder.this;
}
});
}
/**
* {@inheritDoc}
*/
@Override
public ContextMenu doChildrenContextMenu(StaplerRequest2 request, StaplerResponse2 response) {
if (Util.isOverridden(AbstractFolder.class, getClass(), "doChildrenContextMenu", StaplerRequest.class, StaplerResponse.class)) {
return doChildrenContextMenu(request != null ? StaplerRequest.fromStaplerRequest2(request) : null, response != null ? StaplerResponse.fromStaplerResponse2(response) : null);
} else {
return doChildrenContextMenuImpl(request, response);
}
}
/**
* @deprecated use {@link #doChildrenContextMenu(StaplerRequest2, StaplerResponse2)}
*/
@Deprecated
@Override
@StaplerNotDispatchable
public ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse response) {
return doChildrenContextMenuImpl(request != null ? StaplerRequest.toStaplerRequest2(request) : null, response != null ? StaplerResponse.toStaplerResponse2(response) : null);
}
private ContextMenu doChildrenContextMenuImpl(StaplerRequest2 request, StaplerResponse2 response) {
ContextMenu menu = new ContextMenu();
for (View view : getViews()) {
menu.add(view.getAbsoluteUrl(),view.getDisplayName());
}
return menu;
}
@POST
public synchronized void doCreateView(StaplerRequest2 req, StaplerResponse2 rsp)
throws IOException, ServletException, ParseException, Descriptor.FormException {
if (Util.isOverridden(AbstractFolder.class, getClass(), "doCreateView", StaplerRequest.class, StaplerResponse.class)) {
try {
doCreateView(req != null ? StaplerRequest.fromStaplerRequest2(req) : null, rsp != null ? StaplerResponse.fromStaplerResponse2(rsp) : null);
} catch (javax.servlet.ServletException e) {
throw ServletExceptionWrapper.toJakartaServletException(e);
}
} else {
doCreateViewImpl(req, rsp);
}
}
/**
* @deprecated use {@link #doCreateView(StaplerRequest2, StaplerResponse2)}
*/
@Deprecated
@StaplerNotDispatchable
public synchronized void doCreateView(StaplerRequest req, StaplerResponse rsp)
throws IOException, javax.servlet.ServletException, ParseException, Descriptor.FormException {
try {
doCreateViewImpl(req != null ? StaplerRequest.toStaplerRequest2(req) : null, rsp != null ? StaplerResponse.toStaplerResponse2(rsp) : null);
} catch (ServletException e) {
throw ServletExceptionWrapper.fromJakartaServletException(e);
}
}
private void doCreateViewImpl(StaplerRequest2 req, StaplerResponse2 rsp)
throws IOException, ServletException, ParseException, Descriptor.FormException {
checkPermission(View.CREATE);
addView(View.create(req, rsp, this));
}
/**
* Checks if a top-level view with the given name exists.
*
* @param value the name of the child.
* @return the validation results.
*/
public FormValidation doViewExistsCheck(@QueryParameter String value) {
checkPermission(View.CREATE);
String view = fixEmpty(value);
if (view == null) {
return FormValidation.ok();
}
if (getView(view) == null) {
return FormValidation.ok();
} else {
return FormValidation.error(Messages.Hudson_ViewAlreadyExists(view));
}
}
/**
* Get the current health report for a folder.
*
* @return the health report. Never returns null
*/
public HealthReport getBuildHealth() {
List<HealthReport> reports = getBuildHealthReports();
return reports.isEmpty() ? new HealthReport() : reports.get(0);
}
/**
* Invalidates the cache of build health reports.
*
* @since FIXME
*/
public void invalidateBuildHealthReports() {
healthReports = null;
}
@Exported(name = "healthReport")
public List<HealthReport> getBuildHealthReports() {
if (healthMetrics == null || healthMetrics.isEmpty()) {
return Collections.emptyList();
}
List<HealthReport> reports = healthReports;
if (reports != null && nextHealthReportsRefreshMillis > System.currentTimeMillis()) {
// cache is still valid
return reports;
}
// ensure we refresh on average once every HEALTH_REPORT_CACHE_REFRESH_MIN but not all at once
nextHealthReportsRefreshMillis = System.currentTimeMillis()
+ TimeUnit.MINUTES.toMillis(HEALTH_REPORT_CACHE_REFRESH_MIN * 3L / 4L)
+ ENTROPY.nextInt((int)TimeUnit.MINUTES.toMillis(HEALTH_REPORT_CACHE_REFRESH_MIN / 2));
reports = new ArrayList<>();
for (FolderHealthMetric metric : healthMetrics) {
FolderHealthMetric.Reporter reporter = metric.reporter();
observeMetric(metric.getType(), reporter);
reports.addAll(reporter.report());
}
for (AbstractFolderProperty<?> p : getProperties()) {
for (FolderHealthMetric metric : p.getHealthMetrics()) {
FolderHealthMetric.Reporter reporter = metric.reporter();
observeMetric(metric.getType(), reporter);
reports.addAll(p.getHealthReports());
}
}
Collections.sort(reports);
healthReports = reports; // idempotent write
return reports;
}
private void observeMetric(FolderHealthMetric.Type type, FolderHealthMetric.Reporter reporter) {
if (type.isWithChildren()) {
if (type.isRecursive()) {
Stack<Iterable<? extends Item>> stack = new Stack<>();
stack.push(getItems());
if (type.isTopLevelItems()) {
while (!stack.isEmpty()) {
for (Item item : stack.pop()) {
if (item instanceof TopLevelItem) {
reporter.observe(item);
if (item instanceof Folder) {
stack.push(((Folder) item).getItems());
}
}
}
}
} else {
while (!stack.isEmpty()) {
for (Item item : stack.pop()) {
reporter.observe(item);
if (item instanceof Folder) {
stack.push(((Folder) item).getItems());
}
}
}
}
} else {
for (Item item : getItems()) {
reporter.observe(item);
}
}
} else {
reporter.observe(this);
}
}
public DescribableList<FolderHealthMetric, FolderHealthMetricDescriptor> getHealthMetrics() {
return healthMetrics;
}
public HttpResponse doLastBuild(StaplerRequest2 req) {
if (Util.isOverridden(AbstractFolder.class, getClass(), "doLastBuild", StaplerRequest.class)) {
return doLastBuild(req != null ? StaplerRequest.fromStaplerRequest2(req) : null);
} else {
return doLastBuildImpl(req);
}
}
/**
* @deprecated use {@link #doLastBuild(StaplerRequest2)}
*/
@Deprecated
@StaplerNotDispatchable
public HttpResponse doLastBuild(StaplerRequest req) {
return doLastBuildImpl(req != null ? StaplerRequest.toStaplerRequest2(req) : null);
}
private HttpResponse doLastBuildImpl(StaplerRequest2 req) {
return HttpResponses.redirectToDot();
}
/**
* Gets the icon used for this folder.
*
* @return the icon.
*/
public FolderIcon getIcon() {
return icon;
}
public void setIcon(FolderIcon icon) {
this.icon = icon;
icon.setOwner(this);
}
public FolderIcon getIconColor() {
return icon;
}
/**
* {@inheritDoc}
*/
@Override
public Collection<? extends Job> getAllJobs() {
Set<Job> jobs = new HashSet<>();
for (Item i : getItems()) {
jobs.addAll(i.getAllJobs());
}
return jobs;
}
/**
* {@inheritDoc}
*/
@Exported(name="jobs")
@Override
public Collection<I> getItems() {
return getItems(item -> true);
}
/**
* {@inheritDoc}
*/
@Override
public Collection<I> getItems(Predicate<I> pred) {
List<I> viewableItems = new ArrayList<>();
for (I item : items.values()) {
if (pred.test(item) && item.hasPermission(Item.READ)) {
viewableItems.add(item);
}
}
return viewableItems;
}
/**
* Checks if folder has visible items
* @return true if folder has visible items false otherwise
*/
public boolean hasVisibleItems() {
for (I item : items.values()) {
if (item.hasPermission(Item.READ)) {
return true;
}
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public I getItem(String name) throws AccessDeniedException {
if (items == null) {
return null;
}
I item = items.get(name);
if (item == null) {
return null;
}
if (!item.hasPermission(Item.READ)) {
if (item.hasPermission(Item.DISCOVER)) {
throw new AccessDeniedException("Please log in to access " + name);
}
return null;
}
return item;
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("deprecation")
@Override
public void onRenamed(I item, String oldName, String newName) throws IOException {
items.remove(oldName);
itemsPut(newName, item);
// For compatibility with old views:
for (View v : folderViews.getViews()) {
v.onJobRenamed(item, oldName, newName);
}
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("deprecation")
@Override
public void onDeleted(I item) throws IOException {
ItemListener.fireOnDeleted(item);
items.remove(item.getName());
// For compatibility with old views:
for (View v : folderViews.getViews()) {
v.onJobRenamed(item, item.getName(), null);
}
}
/**
* Is this folder disabled. A disabled folder should have all child items disabled.
*
* @return {@code true} if and only if the folder is disabled.
* @since 6.1.0
* @see FolderJobQueueDecisionHandler
*/
public boolean isDisabled() {
return false;
}
/**
* Sets the folder as disabled.
*
* @param disabled {@code true} if and only if the folder is to be disabled.
* @since 6.1.0
*/
protected void setDisabled(boolean disabled) {
throw new UnsupportedOperationException("must be implemented if supportsMakeDisabled is overridden");
}