Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathPlot.java
More file actions
Latest commit
1042 lines (935 loc) · 34 KB
/
Copy pathPlot.java
File metadata and controls
1042 lines (935 loc) · 34 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
/*
* Copyright (c) 2007-2009 Yahoo! Inc. All rights reserved.
* The copyrights to the contents of this file are licensed under the MIT License
* (http://www.opensource.org/licenses/mit-license.php)
*/
packagehudson.plugins.plot;
importstaticorg.jfree.chart.plot.PlotOrientation.VERTICAL;
importcom.opencsv.CSVReader;
importcom.opencsv.CSVWriter;
importcom.opencsv.exceptions.CsvValidationException;
importhudson.FilePath;
importhudson.model.AbstractBuild;
importhudson.model.AbstractProject;
importhudson.model.Job;
importhudson.model.Run;
importhudson.util.ChartUtil;
importhudson.util.ShiftedCategoryAxis;
importjava.awt.BasicStroke;
importjava.awt.Color;
importjava.awt.Polygon;
importjava.awt.Shape;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.io.OutputStreamWriter;
importjava.io.PrintStream;
importjava.nio.charset.Charset;
importjava.text.NumberFormat;
importjava.text.SimpleDateFormat;
importjava.util.ArrayList;
importjava.util.Date;
importjava.util.List;
importjava.util.logging.Level;
importjava.util.logging.Logger;
importorg.apache.commons.collections.CollectionUtils;
importorg.apache.commons.lang3.StringUtils;
importorg.jfree.chart.ChartFactory;
importorg.jfree.chart.ChartRenderingInfo;
importorg.jfree.chart.ChartUtilities;
importorg.jfree.chart.JFreeChart;
importorg.jfree.chart.axis.CategoryAxis;
importorg.jfree.chart.axis.CategoryLabelPositions;
importorg.jfree.chart.axis.LogarithmicAxis;
importorg.jfree.chart.axis.NumberAxis;
importorg.jfree.chart.axis.ValueAxis;
importorg.jfree.chart.labels.StandardCategoryToolTipGenerator;
importorg.jfree.chart.plot.CategoryPlot;
importorg.jfree.chart.plot.DefaultDrawingSupplier;
importorg.jfree.chart.plot.DrawingSupplier;
importorg.jfree.chart.renderer.category.AbstractCategoryItemRenderer;
importorg.jfree.chart.renderer.category.LineAndShapeRenderer;
importorg.kohsuke.stapler.DataBoundConstructor;
importorg.kohsuke.stapler.StaplerRequest;
importorg.kohsuke.stapler.StaplerRequest2;
importorg.kohsuke.stapler.StaplerResponse;
importorg.kohsuke.stapler.StaplerResponse2;
/**
* Represents the configuration for a single plot. A plot can have one or more
* data series (lines). Each data series has one data point per build. The
* x-axis is always the build number.
* <p>
* A plot has the following characteristics:
* <ul>
* <li>a title (mandatory)
* <li>y-axis label (defaults to no label)
* <li>one or more data series
* <li>plot group (defaults to no group)
* <li>number of builds to show on the plot (defaults to all)
* </ul>
* <p>
* A plots group effects the way in which plots are displayed. Group names are
* listed as links on the top-level plot page. The user then clicks on a group
* and sees the plots that belong to that group.
*
* @author Nigel Daley
*/
publicclassPlotimplementsComparable<Plot> {
privatestaticfinalLoggerLOGGER = Logger.getLogger(Plot.class.getName());
privatestaticfinalSimpleDateFormatDATE_FORMAT = newSimpleDateFormat("MMM d");
/**
* Effectively a 2-dimensional array, where each row is the data for one
* data series of an individual build; the columns are: series y-value,
* series label, build number, optional URL
*/
privatetransientList<String[]> rawPlotData;
/**
* The generated plot, which is only regenerated when new data is added (it
* is re-rendered, however, every time it is requested).
*/
privatetransientJFreeChartplot;
/**
* The project (or job) that this plot belongs to. A reference to the
* project is needed to retrieve and save the CSV file that is stored in the
* project's root directory.
*/
privatetransientJob<?, ?> project;
/**
* All plots share the same JFreeChart drawing supplier object.
*/
privatestaticfinalDrawingSupplierSUPPLIER = newDefaultDrawingSupplier(
DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE,
DefaultDrawingSupplier.DEFAULT_OUTLINE_PAINT_SEQUENCE,
DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE,
DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE,
// the plot data points are a small diamond shape
newShape[] {newPolygon(newint[] {3, 0, -3, 0}, newint[] {0, 4, 0, -4}, 4)});
/**
* The default plot width.
*/
privatestaticfinalintDEFAULT_WIDTH = 750;
/**
* The default plot height.
*/
privatestaticfinalintDEFAULT_HEIGHT = 450;
// Transient values
/**
* The width of the plot.
*/
privatetransientintwidth;
/**
* The height of the plot.
*/
privatetransientintheight;
/**
* The right-most build number on the plot.
*/
privatetransientintrightBuildNum;
/**
* Whether or not the plot has a legend.
*/
privatetransientbooleanhasLegend = true;
/**
* Number of builds back to show on this plot from url.
*/
@SuppressWarnings("visibilitymodifier")
publictransientStringurlNumBuilds;
/**
* Title of plot from url.
*/
@SuppressWarnings("visibilitymodifier")
publictransientStringurlTitle;
/**
* Style of plot from url.
*/
@SuppressWarnings("visibilitymodifier")
publictransientStringurlStyle;
/**
* Use description flag from url.
*/
@SuppressWarnings("visibilitymodifier")
publictransientBooleanurlUseDescr;
// Configuration values
/**
* Title of plot. Mandatory.
*/
@SuppressWarnings("visibilitymodifier")
publicStringtitle;
/**
* Description of plot. Optional.
*/
@SuppressWarnings("visibilitymodifier")
publicStringdescription;
/**
* Y-axis label. Optional.
*/
@SuppressWarnings("visibilitymodifier")
publicStringyaxis;
/**
* List of data series.
*/
@SuppressWarnings("visibilitymodifier")
publicList<Series> series;
/**
* Group name that this plot belongs to.
*/
@SuppressWarnings("visibilitymodifier")
publicStringgroup;
/**
* Number of builds back to show on this plot. Empty string means all
* builds. Must not be "0".
*/
@SuppressWarnings("visibilitymodifier")
publicStringnumBuilds;
/**
* The name of the CSV file that persists the plots data. The CSV file is
* stored in the projects root directory. This is different from the source
* csv file that can be used as a source for the plot.
*/
@SuppressWarnings("visibilitymodifier")
publicStringcsvFileName;
/**
* The date of the last change to the CSV file.
*/
privatelongcsvLastModification;
/**
* Optional style of plot: line, line3d, stackedArea, stackedBar, etc.
*/
@SuppressWarnings("visibilitymodifier")
publicStringstyle;
/**
* Whether or not to use build descriptions as X-axis labels. Optional.
*/
@SuppressWarnings("visibilitymodifier")
publicbooleanuseDescr;
/**
* Keep records for builds that were deleted.
*/
privatebooleankeepRecords;
/**
* Whether or not to exclude zero as default Y-axis value. Optional.
*/
@SuppressWarnings("visibilitymodifier")
publicbooleanexclZero;
/**
* Use a logarithmic Y-axis.
*/
@SuppressWarnings("visibilitymodifier")
publicbooleanlogarithmic;
/**
* Min/max yaxis values, string used so if no value defaults used
*/
@SuppressWarnings("visibilitymodifier")
publicStringyaxisMinimum;
@SuppressWarnings("visibilitymodifier")
publicStringyaxisMaximum;
staticclassLabelimplementsComparable<Label> {
privatefinalIntegerbuildNum;
privatefinalStringbuildDate;
privatefinalStringtext;
publicLabel(StringbuildNum, StringbuildTime, Stringtext) {
this.buildNum = Integer.parseInt(buildNum);
synchronized (DATE_FORMAT) {
this.buildDate = DATE_FORMAT.format(newDate(Long.parseLong(buildTime)));
}
this.text = text;
}
publicLabel(StringbuildNum, StringbuildTime) {
this(buildNum, buildTime, null);
}
publicintcompareTo(Labelthat) {
returnthis.buildNum - that.buildNum;
}
@Override
publicbooleanequals(Objecto) {
returnoinstanceofLabel && ((Label) o).buildNum.equals(buildNum);
}
@Override
publicinthashCode() {
returnbuildNum.hashCode();
}
publicStringnumDateString() {
return"#" + buildNum + " (" + buildDate + ")";
}
@Override
publicStringtoString() {
returntext != null ? text : numDateString();
}
}
privateenumChartStyle {
AREA("area"),
BAR("bar"),
BAR_3D("bar3d"),
LINE("line"),
LINE_3D("line3d"),
LINE_SIMPLE("lineSimple"),
STACKED_AREA("stackedArea"),
STACKED_BAR("stackedBar"),
STACKED_BAR_3D("stackedBar3d"),
WATERFALL("waterfall");
privatefinalStringname;
ChartStyle(Stringname) {
this.name = name;
}
staticChartStyleforName(Stringname) {
for (ChartStylechartStyle : ChartStyle.values()) {
if (name.equalsIgnoreCase(chartStyle.name)) {
returnchartStyle;
}
}
returnChartStyle.LINE_SIMPLE;
}
}
/**
* Creates a new plot with the given parameters. If numBuilds is the empty
* string, then all builds will be included. Must not be zero.
*/
@SuppressWarnings("parameternumber")
@DataBoundConstructor
publicPlot(
Stringtitle,
Stringyaxis,
Stringgroup,
StringnumBuilds,
StringcsvFileName,
Stringstyle,
booleanuseDescr,
booleankeepRecords,
booleanexclZero,
booleanlogarithmic,
StringyaxisMinimum,
StringyaxisMaximum,
Stringdescription) {
this.title = title;
this.yaxis = yaxis;
this.group = group;
this.numBuilds = numBuilds;
this.csvFileName = csvFileName;
this.style = style;
this.useDescr = useDescr;
this.keepRecords = keepRecords;
this.exclZero = exclZero;
this.logarithmic = logarithmic;
this.yaxisMinimum = yaxisMinimum;
this.yaxisMaximum = yaxisMaximum;
this.description = description;
}
/**
* @deprecated Kept for backward compatibility.
*/
@Deprecated
publicPlot(
Stringtitle,
Stringyaxis,
Stringgroup,
StringnumBuilds,
StringcsvFileName,
Stringstyle,
booleanuseDescr) {
this(title, yaxis, group, numBuilds, csvFileName, style, useDescr, false, false, false, null, null, null);
}
// needed for serialization
publicPlot() {}
publicbooleangetKeepRecords() {
returnkeepRecords;
}
publicbooleangetExclZero() {
returnexclZero;
}
publicbooleanisLogarithmic() {
returnlogarithmic;
}
publicbooleanhasYaxisMinimum() {
return (getYaxisMinimum() != null);
}
publicDoublegetYaxisMinimum() {
returngetDoubleFromString(yaxisMinimum);
}
publicbooleanhasYaxisMaximum() {
return (getYaxisMaximum() != null);
}
publicDoublegetYaxisMaximum() {
returngetDoubleFromString(yaxisMaximum);
}
publicDoublegetDoubleFromString(Stringinput) {
Doubleresult = null;
if (!StringUtils.isEmpty(input)) {
try {
result = Double.parseDouble(input);
} catch (NumberFormatExceptionnfe) {
LOGGER.log(
Level.INFO,
"Failed to parse double from '" + input + "'. Not a problem, result already set",
nfe);
}
}
returnresult;
}
publicintcompareTo(Ploto) {
if (title == null) {
returno == null || o.getTitle() == null ? 0 : -1;
}
if (o == null || o.getTitle() == null) {
return1;
}
returntitle.compareTo(o.getTitle());
}
publicbooleanequals(Objecto) {
returnoinstanceofPlot && this.compareTo((Plot) o) == 0;
}
@Override
publicinthashCode() {
returnthis.title.hashCode();
}
@Override
publicStringtoString() {
return"TITLE(" + getTitle() + "),YAXIS(" + yaxis + "),NUMSERIES("
+ CollectionUtils.size(series) + "),GROUP(" + group
+ "),NUMBUILDS(" + numBuilds + "),RIGHTBUILDNUM("
+ getRightBuildNum() + "),HASLEGEND(" + hasLegend()
+ "),ISLOGARITHMIC(" + isLogarithmic() + "),YAXISMINIMUM("
+ yaxisMinimum + "),YAXISMAXIMUM(" + yaxisMaximum
+ "),FILENAME(" + getCsvFileName() + "),DESCRIPTION("
+ getDescription() + ")";
}
publicStringgetYaxis() {
returnyaxis;
}
publicList<Series> getSeries() {
returnseries;
}
publicStringgetGroup() {
returngroup;
}
publicStringgetCsvFileName() {
if (StringUtils.isBlank(csvFileName) && project != null) {
try {
csvFileName = File.createTempFile("plot-", ".csv", project.getRootDir())
.getName();
LOGGER.log(Level.WARNING, "Loading " + csvFileName);
} catch (IOExceptione) {
LOGGER.log(Level.SEVERE, "Unable to create temporary CSV file.", e);
}
}
returncsvFileName;
}
/**
* Sets the title for the plot from the "title" parameter in the given
* StaplerRequest.
*/
privatevoidsetTitle(StaplerRequest2req) {
urlTitle = req.getParameter("title");
}
privateStringgetURLTitle() {
returnurlTitle != null ? urlTitle : title;
}
publicStringgetTitle() {
returntitle;
}
privatevoidsetStyle(StaplerRequest2req) {
urlStyle = req.getParameter("style");
}
privateStringgetUrlStyle() {
returnurlStyle != null ? urlStyle : (style != null ? style : "");
}
privatevoidsetUseDescr(StaplerRequest2req) {
Stringu = req.getParameter("usedescr");
if (u == null) {
urlUseDescr = null;
} else {
urlUseDescr = "on".equalsIgnoreCase(u) || "true".equalsIgnoreCase(u);
}
}
privatebooleangetUrlUseDescr() {
returnurlUseDescr != null ? urlUseDescr : useDescr;
}
/**
* Sets the "hasLegend" parameter in the given StaplerRequest. If the
* parameter doesn't exist then a default is used.
*/
privatevoidsetHasLegend(StaplerRequest2req) {
Stringlegend = req.getParameter("haslegend");
hasLegend = legend == null || "on".equalsIgnoreCase(legend) || "true".equalsIgnoreCase(legend);
}
publicbooleanhasLegend() {
returnhasLegend;
}
/**
* Sets the number of builds to plot from the "numbuilds" parameter in the
* given StaplerRequest. If the parameter doesn't exist or isn't an integer
* then a default is used.
*/
privatevoidsetNumBuilds(StaplerRequest2req) {
urlNumBuilds = req.getParameter("numbuilds");
if (urlNumBuilds != null) {
try {
// simply try and parse the string to see if it's a valid
// number, throw away the result.
Integer.parseInt(urlNumBuilds);
} catch (NumberFormatExceptionnfe) {
urlNumBuilds = null;
}
}
}
publicStringgetURLNumBuilds() {
returnurlNumBuilds != null ? urlNumBuilds : numBuilds;
}
publicStringgetNumBuilds() {
returnnumBuilds;
}
/**
* Sets the description of the plot from the "description" parameter in the
* given StaplerRequest. If the parameter doesn't exist or isn't an string
* then a default is used.
*/
privatevoidsetDescription(StaplerRequest2req) {
description = req.getParameter("description");
}
publicStringgetDescription() {
returndescription;
}
/**
* Sets the right-most build number shown on the plot from the
* "rightbuildnum" parameter in the given StaplerRequest. If the parameter
* doesn't exist or isn't an integer then a default is used.
*/
privatevoidsetRightBuildNum(StaplerRequest2req) {
Stringbuild = req.getParameter("rightbuildnum");
if (StringUtils.isBlank(build)) {
rightBuildNum = Integer.MAX_VALUE;
} else {
try {
rightBuildNum = Integer.parseInt(build);
} catch (NumberFormatExceptionnfe) {
LOGGER.log(Level.SEVERE, "Exception converting to integer", nfe);
rightBuildNum = Integer.MAX_VALUE;
}
}
}
privateintgetRightBuildNum() {
returnrightBuildNum;
}
/**
* Sets the plot width from the "width" parameter in the given
* StaplerRequest. If the parameter doesn't exist or isn't an integer then a
* default is used.
*/
privatevoidsetWidth(StaplerRequest2req) {
Stringw = req.getParameter("width");
if (w == null) {
width = DEFAULT_WIDTH;
} else {
try {
width = Integer.parseInt(w);
} catch (NumberFormatExceptionnfe) {
LOGGER.log(Level.SEVERE, "Exception converting to integer", nfe);
width = DEFAULT_WIDTH;
}
}
}
privateintgetWidth() {
returnwidth;
}
/**
* Sets the plot height from the "height" parameter in the given
* StaplerRequest. If the parameter doesn't exist or isn't an integer then a
* default is used.
*/
privatevoidsetHeight(StaplerRequest2req) {
Stringh = req.getParameter("height");
if (h == null) {
height = DEFAULT_HEIGHT;
} else {
try {
height = Integer.parseInt(h);
} catch (NumberFormatExceptionnfe) {
LOGGER.log(Level.SEVERE, "Exception converting to integer", nfe);
height = DEFAULT_HEIGHT;
}
}
}
privateintgetHeight() {
returnheight;
}
publicJob<?, ?> getJob() {
returnproject;
}
publicvoidsetJob(Job<?, ?> job) {
this.project = job;
}
@Deprecated
publicAbstractProject<?, ?> getProject() {
return (AbstractProject<?, ?>) project;
}
/**
* A reference to the project is needed to retrieve the project's root
* directory where the CSV file is located. Unfortunately, a reference to
* the project is not available when this object is created.
*/
publicvoidsetProject(AbstractProject<?, ?> project) {
this.project = project;
}
/**
* Generates and writes the plot to the response output stream.
*
* @param req the incoming request
* @param rsp the response stream
* @throws IOException
*/
publicvoidplotGraph(StaplerRequest2req, StaplerResponse2rsp) throwsIOException {
if (ChartUtil.awtProblemCause != null) {
// Not available. Send out error message.
rsp.sendRedirect2(req.getContextPath() + "/images/headless.png");
return;
}
setWidth(req);
setHeight(req);
setNumBuilds(req);
setRightBuildNum(req);
setHasLegend(req);
setTitle(req);
setStyle(req);
setUseDescr(req);
// need to force regenerate the plot in case build
// descriptions (used for tool tips) have changed
generatePlot(true);
ChartUtil.generateGraph(
StaplerRequest.fromStaplerRequest2(req),
StaplerResponse.fromStaplerResponse2(rsp),
plot,
getWidth(),
getHeight());
}
/**
* Generates and writes the plot's clickable map to the response output
* stream.
*
* @param req the incoming request
* @param rsp the response stream
* @throws IOException
*/
publicvoidplotGraphMap(StaplerRequest2req, StaplerResponse2rsp) throwsIOException {
if (ChartUtil.awtProblemCause != null) {
// not available. send out error message
rsp.sendRedirect2(req.getContextPath() + "/images/headless.png");
return;
}
setWidth(req);
setHeight(req);
setNumBuilds(req);
setRightBuildNum(req);
setHasLegend(req);
setTitle(req);
setStyle(req);
setUseDescr(req);
generatePlot(false);
ChartRenderingInfoinfo = newChartRenderingInfo();
plot.createBufferedImage(getWidth(), getHeight(), info);
rsp.setContentType("text/plain;charset=UTF-8");
rsp.getWriter().println(ChartUtilities.getImageMap(getCsvFileName(), info));
}
/**
* @see #addBuild(Run, PrintStream, FilePath)
*/
publicvoidaddBuild(AbstractBuild<?, ?> build, PrintStreamlogger) {
addBuild(build, logger, build.getWorkspace());
}
/**
* Called when a build completes. Adds the finished build to this plot. This
* method extracts the data for each data series from the build and saves it
* in the plot's CSV file.
*/
publicvoidaddBuild(Run<?, ?> run, PrintStreamlogger, FilePathworkspace) {
if (project == null) {
project = run.getParent();
}
// load the existing plot data from disk
loadPlotData();
// extract the data for each data series
for (Seriess : getSeries()) {
if (s == null) {
continue;
}
List<PlotPoint> seriesData = s.loadSeries(workspace, run.getNumber(), logger);
if (seriesData != null) {
for (PlotPointpoint : seriesData) {
if (point == null) {
continue;
}
rawPlotData.add(newString[] {
point.getYvalue(),
point.getLabel(),
run.getNumber() + "", // convert to a string
run.getTimestamp().getTimeInMillis() + "",
point.getUrl()
});
}
}
}
// save the updated plot data to disk
savePlotData();
}
/**
* Generates the plot and stores it in the plot instance variable.
*
* @param forceGenerate if true, force the plot to be re-generated even if the on-disk
* data hasn't changed
*/
privatevoidgeneratePlot(booleanforceGenerate) {
// LOGGER.info("Determining if we should generate plot " +
// getCsvFileName());
FilecsvFile = newFile(project.getRootDir(), getCsvFileName());
if (csvFile.lastModified() == csvLastModification && plot != null && !forceGenerate) {
// data hasn't changed so don't regenerate the plot
return;
}
if (rawPlotData == null || csvFile.lastModified() > csvLastModification) {
// data has changed or has not been loaded so load it now
loadPlotData();
}
// LOGGER.info("Generating plot " + getCsvFileName());
csvLastModification = csvFile.lastModified();
PlotCategoryDatasetdataset = newPlotCategoryDataset();
for (String[] record : rawPlotData) {
// record: series y-value, series label, build number, build date,
// url
intbuildNum;
try {
buildNum = Integer.parseInt(record[2]);
if (!reportBuild(buildNum) || buildNum > getRightBuildNum()) {
continue; // skip this record
}
} catch (NumberFormatExceptionnfe) {
LOGGER.log(Level.SEVERE, "Exception converting to integer", nfe);
continue; // skip this record all together
}
Numbervalue;
try {
value = Integer.parseInt(record[0]);
} catch (NumberFormatExceptionnfe) {
try {
value = Double.parseDouble(record[0]);
} catch (NumberFormatExceptionnfe2) {
LOGGER.log(Level.SEVERE, "Exception converting to number", nfe2);
continue; // skip this record all together
}
}
LabelcolumnXLabel = getUrlUseDescr()
? newLabel(record[2], record[3], descriptionForBuild(buildNum))
: newLabel(record[2], record[3]);
Stringurl = null;
if (record.length >= 5) {
url = record[4];
}
StringrowSeries = record[1];
dataset.setValue(value, url, rowSeries, columnXLabel);
}
Stringbuilds = getURLNumBuilds();
intbuildsNumber;
if (StringUtils.isBlank(builds)) {
buildsNumber = Integer.MAX_VALUE;
} else {
try {
buildsNumber = Integer.parseInt(builds);
} catch (NumberFormatExceptionnfe) {
LOGGER.log(Level.SEVERE, "Exception converting to integer", nfe);
buildsNumber = Integer.MAX_VALUE;
}
}
dataset.clipDataset(buildsNumber);
plot = createChart(dataset);
CategoryPlotcategoryPlot = (CategoryPlot) plot.getPlot();
categoryPlot.setDomainGridlinePaint(Color.black);
categoryPlot.setRangeGridlinePaint(Color.black);
categoryPlot.setDrawingSupplier(Plot.SUPPLIER);
CategoryAxisdomainAxis = newShiftedCategoryAxis(Messages.Plot_Build());
categoryPlot.setDomainAxis(domainAxis);
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
domainAxis.setLowerMargin(0.0);
domainAxis.setUpperMargin(0.03);
domainAxis.setCategoryMargin(0.0);
for (Objectcategory : dataset.getColumnKeys()) {
Labellabel = (Label) category;
if (label.text != null) {
domainAxis.addCategoryLabelToolTip(label, label.numDateString());
} else {
domainAxis.addCategoryLabelToolTip(label, descriptionForBuild(label.buildNum));
}
}
// Replace the range axis by a logarithmic axis if the option is
// selected
if (isLogarithmic()) {
LogarithmicAxislogAxis = newLogarithmicAxis(getYaxis());
categoryPlot.setRangeAxis(logAxis);
}
// optionally exclude zero as default y-axis value
ValueAxisrangeAxis = categoryPlot.getRangeAxis();
if ((rangeAxis != null) && (rangeAxisinstanceofNumberAxis)) {
if (hasYaxisMinimum()) {
rangeAxis.setLowerBound(getYaxisMinimum());
}
if (hasYaxisMaximum()) {
rangeAxis.setUpperBound(getYaxisMaximum());
}
((NumberAxis) rangeAxis).setAutoRangeIncludesZero(!getExclZero());
}
AbstractCategoryItemRendererrenderer = (AbstractCategoryItemRenderer) categoryPlot.getRenderer();
intnumColors = dataset.getRowCount();
for (inti = 0; i < numColors; i++) {
renderer.setSeriesPaint(i, newColor(Color.HSBtoRGB((1f / numColors) * i, 1f, 1f)));
}
renderer.setBaseStroke(newBasicStroke(2.0f));
renderer.setBaseToolTipGenerator(
newStandardCategoryToolTipGenerator(Messages.Plot_Build() + " {1}: {2}", NumberFormat.getInstance()));
renderer.setBaseItemURLGenerator(newPointURLGenerator());
if (rendererinstanceofLineAndShapeRendererlasRenderer) {
Strings = getUrlStyle();
lasRenderer.setShapesVisible(!"lineSimple".equalsIgnoreCase(s));
}
}
/**
* Creates a Chart of the style indicated by getUrlStyle() using the given
* dataset. Defaults to using createLineChart.
*/
// spotless:off
privateJFreeChartcreateChart(PlotCategoryDatasetdataset) {
returnswitch (ChartStyle.forName(getUrlStyle())) {
caseAREA ->
ChartFactory.createAreaChart(
getURLTitle(), null, getYaxis(), dataset, VERTICAL, hasLegend(), true, false);
caseBAR ->
ChartFactory.createBarChart(
getURLTitle(), null, getYaxis(), dataset, VERTICAL, hasLegend(), true, false);
caseBAR_3D ->
ChartFactory.createBarChart3D(
getURLTitle(), null, getYaxis(), dataset, VERTICAL, hasLegend(), true, false);
caseLINE_3D ->
ChartFactory.createLineChart3D(
getURLTitle(), null, getYaxis(), dataset, VERTICAL, hasLegend(), true, false);
caseLINE_SIMPLE ->
ChartFactory.createLineChart(
getURLTitle(), null, getYaxis(), dataset, VERTICAL, hasLegend(), true, false);
caseSTACKED_AREA ->
ChartFactory.createStackedAreaChart(
getURLTitle(), null, getYaxis(), dataset, VERTICAL, hasLegend(), true, false);
caseSTACKED_BAR ->
ChartFactory.createStackedBarChart(
getURLTitle(), null, getYaxis(), dataset, VERTICAL, hasLegend(), true, false);
caseSTACKED_BAR_3D ->
ChartFactory.createStackedBarChart3D(
getURLTitle(), null, getYaxis(), dataset, VERTICAL, hasLegend(), true, false);
caseWATERFALL ->
ChartFactory.createWaterfallChart(
getURLTitle(), null, getYaxis(), dataset, VERTICAL, hasLegend(), true, false);
default ->
ChartFactory.createLineChart(
getURLTitle(), null, getYaxis(), dataset, VERTICAL, hasLegend(), true, false);
};
}
// spotless:on
/**
* Returns a trimmed description string for the build specified by the given
* build number.
*/
privateStringdescriptionForBuild(intbuildNum) {
Runr = project.getBuildByNumber(buildNum);
if (r != null) {
Stringtip = r.getTruncatedDescription();
if (tip != null) {
returntip.replaceAll("<p> *|<br> *", ", ");
}
}
returnnull;
}
/**
* Loads the plot data from the CSV file on disk. The CSV file is stored in
* the projects root directory. The data is stored in the rawPlotData
* instance variable.
*/
privatevoidloadPlotData() {
rawPlotData = newArrayList<>();
// load existing plot file
FileplotFile = newFile(project.getRootDir(), getCsvFileName());
if (!plotFile.exists()) {
return;
}
CSVReaderreader = null;
rawPlotData = newArrayList<>();
try {
reader = newCSVReader(newInputStreamReader(newFileInputStream(plotFile), Charset.defaultCharset()));
// throw away 2 header lines
reader.readNext();
reader.readNext();
// read each line of the CSV file and add to rawPlotData
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
rawPlotData.add(nextLine);
}
} catch (CsvValidationException | IOExceptionioe) {
LOGGER.log(Level.SEVERE, "Exception reading plot file", ioe);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOExceptione) {
LOGGER.log(Level.SEVERE, "Failed to close plot reader", e);
}
}
}
}
/**
* Saves the plot data to the CSV file on disk. The CSV file is stored in
* the projects root directory. The data is read from the rawPlotData
* instance variable.
*/
privatevoidsavePlotData() {
FileplotFile = newFile(project.getRootDir(), getCsvFileName());
CSVWriterwriter = null;
try {
writer = newCSVWriter(newOutputStreamWriter(newFileOutputStream(plotFile), Charset.defaultCharset()));
// write 2 header lines
String[] header1 = newString[] {Messages.Plot_Title(), this.getTitle()};
String[] header2 = newString[] {
Messages.Plot_Value(),