/
Fingerprint.java
1518 lines (1328 loc) · 50.8 KB
/
Fingerprint.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-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, 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.infradna.tool.bridge_method_injector.WithBridgeMethods;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.converters.basic.DateConverter;
import com.thoughtworks.xstream.converters.collections.CollectionConverter;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.BulkChange;
import hudson.Extension;
import hudson.ExtensionList;
import hudson.Util;
import hudson.model.listeners.ItemListener;
import hudson.security.ACL;
import hudson.security.ACLContext;
import hudson.util.HexBinaryConverter;
import hudson.util.Iterators;
import hudson.util.PersistedList;
import hudson.util.RunList;
import hudson.util.XStream2;
import java.io.File;
import java.io.IOException;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.fingerprints.FileFingerprintStorage;
import jenkins.fingerprints.FingerprintStorage;
import jenkins.model.FingerprintFacet;
import jenkins.model.Jenkins;
import jenkins.model.TransientFingerprintFacetFactory;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
/**
* A file being tracked by Jenkins.
*
* <p>
* Lifecycle is managed by {@link FingerprintMap}.
*
* @author Kohsuke Kawaguchi
* @see FingerprintMap
*/
@ExportedBean
public class Fingerprint implements ModelObject, Saveable {
/**
* Pointer to a {@link Build}.
*/
@ExportedBean(defaultVisibility = 2)
public static class BuildPtr {
String name;
final int number;
public BuildPtr(String name, int number) {
this.name = name;
this.number = number;
}
public BuildPtr(Run run) {
this(run.getParent().getFullName(), run.getNumber());
}
/**
* Gets {@link Job#getFullName() the full name of the job}.
* Such job could be since then removed, so there might not be a corresponding {@link Job}.
*
* @return A name of the job
*/
@Exported
@NonNull
public String getName() {
return name;
}
/**
* Checks if the current user has permission to see this pointer.
* @return {@code true} if the job exists and user has {@link Item#READ} permissions
* or if the current user has {@link Jenkins#ADMINISTER} permissions.
* If the job exists, but the current user has no permission to discover it,
* {@code false} will be returned.
* If the job has been deleted and the user has no {@link Jenkins#ADMINISTER} permissions,
* it also returns {@code false} in order to avoid the job existence fact exposure.
*/
private boolean hasPermissionToDiscoverBuild() {
// We expose the data to Jenkins administrators in order to
// let them manage the data for deleted jobs (also works for SYSTEM2)
final Jenkins instance = Jenkins.get();
if (instance.hasPermission(Jenkins.ADMINISTER)) {
return true;
}
return canDiscoverItem(name);
}
void setName(String newName) {
name = newName;
}
/**
* Gets the {@link Job} that this pointer points to,
* or null if such a job no longer exists.
*/
@WithBridgeMethods(value = AbstractProject.class, castRequired = true)
public Job<?, ?> getJob() {
return Jenkins.get().getItemByFullName(name, Job.class);
}
/**
* Gets the project build number.
* <p>
* Such {@link Run} could be since then discarded.
* @return A build number
*/
@Exported
@NonNull
public int getNumber() {
return number;
}
/**
* Gets the {@link Job} that this pointer points to,
* or null if such a job no longer exists.
*/
public Run getRun() {
Job j = getJob();
if (j == null) return null;
return j.getBuildByNumber(number);
}
private boolean isAlive() {
return getRun() != null;
}
/**
* Returns true if {@link BuildPtr} points to the given run.
*/
public boolean is(Run r) {
return r.getNumber() == number && r.getParent().getFullName().equals(name);
}
/**
* Returns true if {@link BuildPtr} points to the given job.
*/
public boolean is(Job job) {
return job.getFullName().equals(name);
}
/**
* Returns true if {@link BuildPtr} points to the given job
* or one of its subordinates.
*
* <p>
* This is useful to check if an artifact in MavenModule
* belongs to MavenModuleSet.
*/
public boolean belongsTo(Job job) {
Item p = Jenkins.get().getItemByFullName(name);
while (p != null) {
if (p == job)
return true;
// go up the chain while we
ItemGroup<? extends Item> parent = p.getParent();
if (!(parent instanceof Item)) {
return false;
}
p = (Item) parent;
}
return false;
}
@Override public String toString() {
return name + " #" + number;
}
}
/**
* Range of build numbers [start,end). Immutable.
*/
@ExportedBean(defaultVisibility = 4)
public static final class Range {
final int start;
final int end;
public Range(int start, int end) {
assert start < end;
this.start = start;
this.end = end;
}
@Exported
public int getStart() {
return start;
}
@Exported
public int getEnd() {
return end;
}
public boolean isSmallerThan(int i) {
return end <= i;
}
public boolean isBiggerThan(int i) {
return i < start;
}
public boolean includes(int i) {
return start <= i && i < end;
}
public Range expandRight() {
return new Range(start, end + 1);
}
public Range expandLeft() {
return new Range(start - 1, end);
}
public boolean isAdjacentTo(Range that) {
return this.end == that.start;
}
@Override
public String toString() {
return "[" + start + "," + end + ")";
}
/**
* Returns true if two {@link Range}s can't be combined into a single range.
*/
public boolean isIndependent(Range that) {
return this.end < that.start || that.end < this.start;
}
/**
* Returns true if two {@link Range}s do not share any common integer.
*/
public boolean isDisjoint(Range that) {
return this.end <= that.start || that.end <= this.start;
}
/**
* Returns true if this range only represents a single number.
*/
public boolean isSingle() {
return end - 1 == start;
}
/**
* If this range contains every int that's in the other range, return true
*/
public boolean contains(Range that) {
return this.start <= that.start && that.end <= this.end;
}
/**
* Returns the {@link Range} that combines two ranges.
*/
public Range combine(Range that) {
assert !isIndependent(that);
return new Range(
Math.min(this.start, that.start),
Math.max(this.end, that.end));
}
/**
* Returns the {@link Range} that represents the intersection of the two.
*/
public Range intersect(Range that) {
assert !isDisjoint(that);
return new Range(
Math.max(this.start, that.start),
Math.min(this.end, that.end));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Range that = (Range) o;
return start == that.start && end == that.end;
}
@Override
public int hashCode() {
return 31 * start + end;
}
}
/**
* Set of {@link Range}s. Mutable.
*/
@ExportedBean(defaultVisibility = 3)
public static final class RangeSet {
// sorted
private final List<Range> ranges;
public RangeSet() {
this(new ArrayList<>());
}
private RangeSet(List<Range> data) {
this.ranges = data;
}
private RangeSet(Range initial) {
this();
ranges.add(initial);
}
/**
* List all numbers in this range set, in the ascending order.
*/
public Iterable<Integer> listNumbers() {
final List<Range> ranges = getRanges();
return new Iterable<>() {
@Override
public Iterator<Integer> iterator() {
return new Iterators.FlattenIterator<>(ranges) {
@Override
protected Iterator<Integer> expand(Range range) {
return Iterators.sequence(range.start, range.end).iterator();
}
};
}
};
}
/**
* List all numbers in this range set in the descending order.
*/
public Iterable<Integer> listNumbersReverse() {
final List<Range> ranges = getRanges();
return new Iterable<>() {
@Override
public Iterator<Integer> iterator() {
return new Iterators.FlattenIterator<>(Iterators.reverse(ranges)) {
@Override
protected Iterator<Integer> expand(Range range) {
return Iterators.reverseSequence(range.start, range.end).iterator();
}
};
}
};
}
/**
* Gets all the ranges.
*/
@Exported
public synchronized List<Range> getRanges() {
return new ArrayList<>(ranges);
}
/**
* Expands the range set to include the given value.
* If the set already includes this number, this will be a no-op.
*/
public synchronized void add(int n) {
for (int i = 0; i < ranges.size(); i++) {
Range r = ranges.get(i);
if (r.includes(n)) return; // already included
if (r.end == n) {
ranges.set(i, r.expandRight());
checkCollapse(i);
return;
}
if (r.start == n + 1) {
ranges.set(i, r.expandLeft());
checkCollapse(i - 1);
return;
}
if (r.isBiggerThan(n)) {
// needs to insert a single-value Range
ranges.add(i, new Range(n, n + 1));
return;
}
}
ranges.add(new Range(n, n + 1));
}
public synchronized void addAll(int... n) {
for (int i : n)
add(i);
}
private void checkCollapse(int i) {
if (i < 0 || i == ranges.size() - 1) return;
Range lhs = ranges.get(i);
Range rhs = ranges.get(i + 1);
if (lhs.isAdjacentTo(rhs)) {
// collapsed
Range r = new Range(lhs.start, rhs.end);
ranges.set(i, r);
ranges.remove(i + 1);
}
}
public synchronized boolean includes(int i) {
for (Range r : ranges) {
if (r.includes(i))
return true;
}
return false;
}
public synchronized void add(RangeSet that) {
int lhs = 0, rhs = 0;
while (lhs < this.ranges.size() && rhs < that.ranges.size()) {
Range lr = this.ranges.get(lhs);
Range rr = that.ranges.get(rhs);
// no overlap
if (lr.end < rr.start) {
lhs++;
continue;
}
if (rr.end < lr.start) {
ranges.add(lhs, rr);
lhs++;
rhs++;
continue;
}
// overlap. merge two
Range m = lr.combine(rr);
rhs++;
// since ranges[lhs] is expanded, it might overlap with others in this.ranges
while (lhs + 1 < this.ranges.size() && !m.isIndependent(this.ranges.get(lhs + 1))) {
m = m.combine(this.ranges.get(lhs + 1));
this.ranges.remove(lhs + 1);
}
this.ranges.set(lhs, m);
}
// if anything is left in that.ranges, add them all
this.ranges.addAll(that.ranges.subList(rhs, that.ranges.size()));
}
/**
* Updates this range set by the intersection of this range and the given range.
*
* @return true if this range set was modified as a result.
*/
public synchronized boolean retainAll(RangeSet that) {
List<Range> intersection = new ArrayList<>();
int lhs = 0, rhs = 0;
while (lhs < this.ranges.size() && rhs < that.ranges.size()) {
Range lr = this.ranges.get(lhs);
Range rr = that.ranges.get(rhs);
if (lr.end <= rr.start) { // lr has no overlap with that.ranges
lhs++;
continue;
}
if (rr.end <= lr.start) { // rr has no overlap with this.ranges
rhs++;
continue;
}
// overlap. figure out the intersection
Range v = lr.intersect(rr);
intersection.add(v);
// move on to the next pair
if (lr.end < rr.end) {
lhs++;
} else {
rhs++;
}
}
boolean same = this.ranges.equals(intersection);
if (!same) {
this.ranges.clear();
this.ranges.addAll(intersection);
return true;
} else {
return false;
}
}
/**
* Updates this range set by removing all the values in the given range set.
*
* @return true if this range set was modified as a result.
*/
public synchronized boolean removeAll(RangeSet that) {
boolean modified = false;
List<Range> sub = new ArrayList<>();
int lhs = 0, rhs = 0;
while (lhs < this.ranges.size() && rhs < that.ranges.size()) {
Range lr = this.ranges.get(lhs);
Range rr = that.ranges.get(rhs);
if (lr.end <= rr.start) { // lr has no overlap with that.ranges. lr stays
sub.add(lr);
lhs++;
continue;
}
if (rr.end <= lr.start) { // rr has no overlap with this.ranges
rhs++;
continue;
}
// some overlap between lr and rr
assert !lr.isDisjoint(rr);
modified = true;
if (rr.contains(lr)) {
// lr completely removed by rr
lhs++;
continue;
}
// we want to look at A and B below, if they are non-null.
// |------------| lr
// |-----| rr
// A B
//
// note that lr and rr could be something like or the other way around
// |------------| lr
// |------------| rr
// A (no B)
if (lr.start < rr.start) { // if A is non-empty, that will stay
Range a = new Range(lr.start, rr.start);
sub.add(a);
}
if (rr.end < lr.end) { // if B is non-empty
// we still need to check that with that.ranges, so keep it in the place of lr.
// how much of them will eventually stay is up to the remainder of that.ranges
this.ranges.set(lhs, new Range(rr.end, lr.end));
rhs++;
} else {
// if B is empty, we are done considering lr
lhs++;
}
}
if (!modified) return false; // no changes
// whatever that remains in lhs will survive
sub.addAll(this.ranges.subList(lhs, this.ranges.size()));
this.ranges.clear();
this.ranges.addAll(sub);
return true;
}
@Override
public synchronized String toString() {
StringBuilder buf = new StringBuilder();
for (Range r : ranges) {
if (buf.length() > 0) buf.append(',');
buf.append(r);
}
return buf.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
return ranges.equals(((RangeSet) o).ranges);
}
@Override
public int hashCode() {
return ranges.hashCode();
}
public synchronized boolean isEmpty() {
return ranges.isEmpty();
}
/**
* Returns the smallest value in this range.
* <p>
* If this range is empty, this method throws an exception.
*/
public synchronized int min() {
return ranges.get(0).start;
}
/**
* Returns the largest value in this range.
* <p>
* If this range is empty, this method throws an exception.
*/
public synchronized int max() {
return ranges.get(ranges.size() - 1).end;
}
/**
* Returns true if all the integers logically in this {@link RangeSet}
* is smaller than the given integer. For example, {[1,3)} is smaller than 3,
* but {[1,3),[100,105)} is not smaller than anything less than 105.
*
* Note that {} is smaller than any n.
*/
public synchronized boolean isSmallerThan(int n) {
if (ranges.isEmpty()) return true;
return ranges.get(ranges.size() - 1).isSmallerThan(n);
}
/**
* Parses a {@link RangeSet} from a string like "1-3,5,7-9"
*/
public static RangeSet fromString(String list, boolean skipError) {
RangeSet rs = new RangeSet();
// Reject malformed ranges like "1---10", "1,,,,3" etc.
if (list.contains("--") || list.contains(",,")) {
if (!skipError) {
throw new IllegalArgumentException(
String.format("Unable to parse '%s', expected correct notation M,N or M-N", list));
}
// ignore malformed notation
return rs;
}
String[] items = Util.tokenize(list, ",");
if (items.length > 1 && items.length <= StringUtils.countMatches(list, ",")) {
if (!skipError) {
throw new IllegalArgumentException(
String.format("Unable to parse '%s', expected correct notation M,N or M-N", list));
}
// ignore malformed notation like ",1,2" or "1,2,"
return rs;
}
for (String s : items) {
s = s.trim();
// s is either single number or range "x-y".
// note that the end range is inclusive in this notation, but not in the Range class
try {
if (s.isEmpty()) {
if (!skipError) {
throw new IllegalArgumentException(
String.format("Unable to parse '%s', expected number", list)); }
// ignore "" element
continue;
}
if (s.contains("-")) {
if (StringUtils.countMatches(s, "-") > 1) {
if (!skipError) {
throw new IllegalArgumentException(String.format(
"Unable to parse '%s', expected correct notation M,N or M-N", list));
}
// ignore malformed ranges like "-5-2" or "2-5-"
continue;
}
String[] tokens = Util.tokenize(s, "-");
if (tokens.length == 2) {
int left = Integer.parseInt(tokens[0]);
int right = Integer.parseInt(tokens[1]);
if (left < 0 || right < 0) {
if (!skipError) {
throw new IllegalArgumentException(
String.format("Unable to parse '%s', expected number above zero", list));
}
// ignore a range which starts or ends under zero like "-5-3"
continue;
}
if (left > right) {
if (!skipError) {
throw new IllegalArgumentException(String.format(
"Unable to parse '%s', expected string with a range M-N where M<N", list));
}
// ignore inverse range like "10-5"
continue;
}
rs.ranges.add(new Range(left, right + 1));
} else {
if (!skipError) {
throw new IllegalArgumentException(
String.format("Unable to parse '%s', expected string with a range M-N", list));
}
// ignore malformed text like "1-10-50"
continue;
}
} else {
int n = Integer.parseInt(s);
rs.ranges.add(new Range(n, n + 1));
}
} catch (NumberFormatException e) {
if (!skipError)
throw new IllegalArgumentException(
String.format("Unable to parse '%s', expected number", list), e);
// ignore malformed text
}
}
return rs;
}
/**
* Converter Implementation for RangeSet.
*
* @since 2.253
*/
public static final class ConverterImpl implements Converter {
private final Converter collectionConv; // used to convert ArrayList in it
public ConverterImpl(Converter collectionConv) {
this.collectionConv = collectionConv;
}
/**
* Check if the given class can be converted (i.e. check if it is of type RangeSet).
*/
@Override
public boolean canConvert(Class type) {
return type == RangeSet.class;
}
@Override
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
RangeSet src = (RangeSet) source;
writer.setValue(serialize(src));
}
/**
* Used to serialize the range sets (builds) of the fingerprint using commas and dashes.
* For e.g., if used in builds 1,2,3,5, it will be serialized to 1-3,5
*/
public static String serialize(RangeSet src) {
StringBuilder buf = new StringBuilder(src.ranges.size() * 10);
for (Range r : src.ranges) {
if (buf.length() > 0) buf.append(',');
if (r.isSingle())
buf.append(r.start);
else
buf.append(r.start).append('-').append(r.end - 1);
}
return buf.toString();
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, final UnmarshallingContext context) {
if (reader.hasMoreChildren()) {
/* old format where <range> elements are nested like
<range>
<start>1337</start>
<end>1479</end>
</range>
*/
return new RangeSet((List<Range>) collectionConv.unmarshal(reader, context));
} else {
return RangeSet.fromString(reader.getValue(), true);
}
}
}
}
@Extension
public static final class ProjectRenameListener extends ItemListener {
@Override
public void onLocationChanged(final Item item, final String oldName, final String newName) {
try (ACLContext acl = ACL.as2(ACL.SYSTEM2)) {
locationChanged(item, oldName, newName);
}
}
private void locationChanged(Item item, String oldName, String newName) {
if (item instanceof Job) {
Job p = Jenkins.get().getItemByFullName(newName, Job.class);
if (p != null) {
RunList<? extends Run> builds = p.getBuilds();
for (Run build : builds) {
Collection<Fingerprint> fingerprints = build.getBuildFingerprints();
for (Fingerprint f : fingerprints) {
try {
f.rename(oldName, newName);
} catch (IOException e) {
logger.log(Level.WARNING, "Failed to update fingerprint record " + f.getFileName() + " when " + oldName + " was renamed to " + newName, e);
}
}
}
}
}
}
}
private static final DateConverter DATE_CONVERTER = new DateConverter();
/**
* Time when the fingerprint has been captured.
*/
private final @NonNull Date timestamp;
/**
* Null if this fingerprint is for a file that's
* apparently produced outside.
*/
private final @CheckForNull BuildPtr original;
private final byte[] md5sum;
private final String fileName;
/**
* Range of builds that use this file keyed by a job full name.
*/
private Hashtable<String, RangeSet> usages = new Hashtable<>();
PersistedList<FingerprintFacet> facets = new PersistedList<>(this);
/**
* Lazily computed immutable {@link FingerprintFacet}s created from {@link TransientFingerprintFacetFactory}.
*/
private transient volatile List<FingerprintFacet> transientFacets = null;
public Fingerprint(@CheckForNull Run build, @NonNull String fileName, @NonNull byte[] md5sum) throws IOException {
this(build == null ? null : new BuildPtr(build), fileName, md5sum);
save();
}
Fingerprint(@CheckForNull BuildPtr original, @NonNull String fileName, @NonNull byte[] md5sum) {
this.original = original;
this.md5sum = md5sum;
this.fileName = fileName;
this.timestamp = new Date();
}
/**
* The first build in which this file showed up,
* if the file looked like it's created there.
* <p>
* This is considered as the "source" of this file,
* or the owner, in the sense that this project "owns"
* this file.
*
* @return null
* if the file is apparently created outside Hudson or if the current
* user has no permission to discover the job.
*/
@Exported
public @CheckForNull BuildPtr getOriginal() {
if (original != null && original.hasPermissionToDiscoverBuild()) {
return original;
}
return null;
}
@Override
public @NonNull String getDisplayName() {
return fileName;
}
/**
* The file name (like "foo.jar" without path).
*/
@Exported
public @NonNull String getFileName() {
return fileName;
}
/**
* Gets the MD5 hash string.
*/
@Exported(name = "hash")
public @NonNull String getHashString() {
return Util.toHexString(md5sum);
}
/**
* Gets the timestamp when this record is created.
*/
@Exported
public @NonNull Date getTimestamp() {
return timestamp;
}
/**
* Gets the string that says how long since this build has scheduled.
*
* @return
* string like "3 minutes" "1 day" etc.
*/
public @NonNull String getTimestampString() {
long duration = System.currentTimeMillis() - timestamp.getTime();
return Util.getTimeSpanString(duration);
}
/**
* Gets the build range set for the given job name.
*
* <p>
* These builds of this job has used this file.
* @return may be empty but not null.
*/
public @NonNull RangeSet getRangeSet(String jobFullName) {
RangeSet r = usages.get(jobFullName);
if (r == null) r = new RangeSet();
return r;
}
public RangeSet getRangeSet(Job job) {
return getRangeSet(job.getFullName());
}
/**
* Gets the sorted list of job names where this jar is used.
*/
@NonNull
public synchronized List<String> getJobs() {
List<String> r = new ArrayList<>(usages.keySet());
Collections.sort(r);
return r;
}
public @CheckForNull Hashtable<String, RangeSet> getUsages() {
return usages;
}
@ExportedBean(defaultVisibility = 2)
public static final class RangeItem {
@Exported
public final String name;
@Exported
public final RangeSet ranges;
public RangeItem(String name, RangeSet ranges) {
this.name = name;
this.ranges = ranges;
}
}
// this is for remote API
@Exported(name = "usage")
public @NonNull List<RangeItem> _getUsages() {
List<RangeItem> r = new ArrayList<>();
final Jenkins instance = Jenkins.get();
for (Map.Entry<String, RangeSet> e : usages.entrySet()) {
final String itemName = e.getKey();
if (instance.hasPermission(Jenkins.ADMINISTER) || canDiscoverItem(itemName)) {
r.add(new RangeItem(itemName, e.getValue()));
}