-
-
Notifications
You must be signed in to change notification settings - Fork 295
Expand file tree
/
Copy pathJiraSite.java
More file actions
1608 lines (1405 loc) · 54.4 KB
/
JiraSite.java
File metadata and controls
1608 lines (1405 loc) · 54.4 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
package hudson.plugins.jira;
import static org.apache.commons.lang.StringUtils.isEmpty;
import static org.apache.commons.lang.StringUtils.isNotEmpty;
import com.atlassian.event.api.EventPublisher;
import com.atlassian.httpclient.apache.httpcomponents.DefaultHttpClientFactory;
import com.atlassian.httpclient.api.HttpClient;
import com.atlassian.httpclient.api.factory.HttpClientOptions;
import com.atlassian.jira.rest.client.api.AuthenticationHandler;
import com.atlassian.jira.rest.client.api.JiraRestClientFactory;
import com.atlassian.jira.rest.client.api.RestClientException;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.atlassian.jira.rest.client.auth.BasicHttpAuthenticationHandler;
import com.atlassian.jira.rest.client.internal.async.AtlassianHttpClientDecorator;
import com.atlassian.jira.rest.client.internal.async.DisposableHttpClient;
import com.atlassian.sal.api.ApplicationProperties;
import com.atlassian.sal.api.UrlMode;
import com.atlassian.sal.api.executor.ThreadLocalContextManager;
import com.cloudbees.hudson.plugins.folder.AbstractFolder;
import com.cloudbees.hudson.plugins.folder.Folder;
import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import com.cloudbees.plugins.credentials.domains.DomainRequirement;
import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Extension;
import hudson.Util;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import hudson.model.Descriptor.FormException;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.Job;
import hudson.plugins.jira.extension.ExtendedAsynchronousJiraRestClient;
import hudson.plugins.jira.extension.ExtendedJiraRestClient;
import hudson.plugins.jira.extension.ExtendedVersion;
import hudson.plugins.jira.model.JiraIssue;
import hudson.security.ACL;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import hudson.util.Secret;
import jakarta.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.annotation.PreDestroy;
import jenkins.model.Jenkins;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.interceptor.RequirePOST;
/**
* <b>You must get instance of this only by using the static {@link #get} or {@link #getSitesFromFolders(ItemGroup)} methods</b>
* <b>The constructors are only used by Jenkins</b>
* <p>
* Represents an external Jira installation and configuration
* needed to access this Jira.
* </p>
* <b>When adding new fields do not miss to look at readResolve method!!</b>
* @author Kohsuke Kawaguchi
*/
public class JiraSite extends AbstractDescribableImpl<JiraSite> {
private static final Logger LOGGER = Logger.getLogger(JiraSite.class.getName());
/**
* Regexp pattern that identifies Jira issue token.
* If this pattern changes help pages (help-issue-pattern_xy.html) must be updated
* First char must be a letter, then at least one letter, digit or underscore.
* See issue JENKINS-729, JENKINS-4092
*/
public static final Pattern DEFAULT_ISSUE_PATTERN =
Pattern.compile("([a-zA-Z][a-zA-Z0-9_]+-[1-9][0-9]*)([^.]|\\.[^0-9]|\\.$|$)");
/**
* Default rest api client calls timeout, in seconds
* See issue JENKINS-31113
*/
public static final int DEFAULT_TIMEOUT = 10;
public static final int DEFAULT_READ_TIMEOUT = 30;
public static final int DEFAULT_THREAD_EXECUTOR_NUMBER = 10;
/**
* URL of Jira for Jenkins access, like {@code http://jira.codehaus.org/}.
* Mandatory. Normalized to end with '/'
*/
public final URL url;
/**
* URL of Jira for normal access, like {@code http://jira.codehaus.org/}.
* Mandatory. Normalized to end with '/'
*/
@SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Backwards compatibility")
public URL alternativeUrl;
/**
* Jira requires HTTP Authentication for login
*/
@SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Backwards compatibility")
public boolean useHTTPAuth;
/**
* The id of the credentials to use. Optional.
*/
@SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Backwards compatibility")
public String credentialsId;
/**
* Jira requires Bearer Authentication for login
*/
@SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Backwards compatibility")
public boolean useBearerAuth;
/**
* User name needed to login. Optional.
* @deprecated use credentialsId
*/
@Deprecated
private transient String userName;
/**
* Password needed to login. Optional.
* @deprecated use credentialsId
*/
@Deprecated
private transient Secret password;
/**
* Group visibility to constrain the visibility of the added comment. Optional.
*/
@SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Backwards compatibility")
public String groupVisibility;
/**
* Role visibility to constrain the visibility of the added comment. Optional.
*/
@SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Backwards compatibility")
public String roleVisibility;
/**
* True if this Jira is configured to allow Confluence-style Wiki comment.
*/
@SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Backwards compatibility")
public boolean supportsWikiStyleComment;
/**
* to record scm changes in jira issue
*
* @since 1.21
*/
@SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Backwards compatibility")
public boolean recordScmChanges;
/**
* Disable annotating the changelogs
*
* @since todo
*/
@SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Backwards compatibility")
public boolean disableChangelogAnnotations;
/**
* user defined pattern
*
* @since 1.22
*/
private String userPattern;
private transient Pattern userPat;
/**
* updated jira issue for all status
*
* @since 1.22
*/
@SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Backwards compatibility")
public boolean updateJiraIssueForAllStatus;
/**
* connection timeout used when calling jira rest api, in seconds
*/
@SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Backwards compatibility")
public int timeout = DEFAULT_TIMEOUT;
/**
* response timeout for jira rest call
* @since 3.0.3
*/
private int readTimeout = DEFAULT_READ_TIMEOUT;
/**
* thread pool number
* @since 3.0.3
*/
private int threadExecutorNumber = DEFAULT_THREAD_EXECUTOR_NUMBER;
/**
* Configuration for formatting (date -> text) in jira comments.
*/
private String dateTimePattern;
/**
* To add scm entry change date and time in jira comments.
*
*/
private boolean appendChangeTimestamp;
private int ioThreadCount = Integer.getInteger(JiraSite.class.getName() + ".httpclient.options.ioThreadCount", 2);
/**
* List of project keys (i.e., "MNG" portion of "MNG-512"),
* last time we checked. Copy on write semantics.
*/
// TODO: seems like this is never invalidated (never set to null)
// should we implement to invalidate this (say every hour)?
private transient volatile Set<String> projects;
private transient Cache<String, Optional<Issue>> issueCache = makeIssueCache();
/**
* Used to guard the computation of {@link #projects}
*/
private transient Lock projectUpdateLock = new ReentrantLock();
private transient JiraSession jiraSession;
private static ExecutorService executorService;
// Deprecate the previous constructor but leave it in place for Java-level compatibility.
@Deprecated
public JiraSite(
URL url,
@CheckForNull URL alternativeUrl,
@CheckForNull String credentialsId,
boolean supportsWikiStyleComment,
boolean recordScmChanges,
@CheckForNull String userPattern,
boolean updateJiraIssueForAllStatus,
@CheckForNull String groupVisibility,
@CheckForNull String roleVisibility,
boolean useHTTPAuth) {
this(
url,
alternativeUrl,
credentialsId,
supportsWikiStyleComment,
recordScmChanges,
userPattern,
updateJiraIssueForAllStatus,
groupVisibility,
roleVisibility,
useHTTPAuth,
DEFAULT_TIMEOUT,
DEFAULT_READ_TIMEOUT,
DEFAULT_THREAD_EXECUTOR_NUMBER);
}
// Deprecate the previous constructor but leave it in place for Java-level compatibility.
@Deprecated
public JiraSite(
URL url,
@CheckForNull URL alternativeUrl,
String userName,
String password,
boolean supportsWikiStyleComment,
boolean recordScmChanges,
@CheckForNull String userPattern,
boolean updateJiraIssueForAllStatus,
@CheckForNull String groupVisibility,
@CheckForNull String roleVisibility,
boolean useHTTPAuth)
throws FormException {
this(
url,
alternativeUrl,
CredentialsHelper.migrateCredentials(userName, password, url),
supportsWikiStyleComment,
recordScmChanges,
userPattern,
updateJiraIssueForAllStatus,
groupVisibility,
roleVisibility,
useHTTPAuth);
}
// Deprecate the previous constructor but leave it in place for Java-level compatibility.
@Deprecated
public JiraSite(
URL url,
URL alternativeUrl,
StandardUsernamePasswordCredentials credentials,
boolean supportsWikiStyleComment,
boolean recordScmChanges,
String userPattern,
boolean updateJiraIssueForAllStatus,
String groupVisibility,
String roleVisibility,
boolean useHTTPAuth)
throws FormException {
this(
url,
alternativeUrl,
(String) null,
supportsWikiStyleComment,
recordScmChanges,
userPattern,
updateJiraIssueForAllStatus,
groupVisibility,
roleVisibility,
useHTTPAuth,
DEFAULT_TIMEOUT,
DEFAULT_READ_TIMEOUT,
DEFAULT_THREAD_EXECUTOR_NUMBER);
if (credentials != null) {
// we verify the credential really exists otherwise we migrate it
StandardUsernamePasswordCredentials standardUsernamePasswordCredentials =
CredentialsHelper.lookupSystemCredentials(credentials.getId(), url);
if (standardUsernamePasswordCredentials == null) {
credentials = CredentialsHelper.migrateCredentials(
credentials.getUsername(), credentials.getPassword().getPlainText(), url);
}
}
setCredentialsId(credentials == null ? null : credentials.getId());
}
// Deprecate the previous constructor but leave it in place for Java-level compatibility.
@Deprecated
public JiraSite(
URL url,
URL alternativeUrl,
String credentialsId,
boolean supportsWikiStyleComment,
boolean recordScmChanges,
String userPattern,
boolean updateJiraIssueForAllStatus,
String groupVisibility,
String roleVisibility,
boolean useHTTPAuth,
int timeout,
int readTimeout,
int threadExecutorNumber) {
if (url != null) {
url = toURL(url.toExternalForm());
}
if (alternativeUrl != null) {
alternativeUrl = toURL(alternativeUrl.toExternalForm());
}
this.url = url;
this.credentialsId = credentialsId;
this.timeout = timeout;
this.readTimeout = readTimeout;
this.threadExecutorNumber = threadExecutorNumber;
this.alternativeUrl = alternativeUrl;
this.supportsWikiStyleComment = supportsWikiStyleComment;
this.recordScmChanges = recordScmChanges;
setUserPattern(userPattern);
this.updateJiraIssueForAllStatus = updateJiraIssueForAllStatus;
setGroupVisibility(groupVisibility);
setRoleVisibility(roleVisibility);
this.useHTTPAuth = useHTTPAuth;
this.jiraSession = null;
}
@DataBoundConstructor
public JiraSite(String url) {
URL mainURL = toURL(url);
if (mainURL == null) {
throw new AssertionError("URL cannot be empty");
}
this.url = mainURL;
}
// Deprecate the previous constructor but leave it in place for Java-level compatibility.
@Deprecated
public JiraSite(
URL url,
URL alternativeUrl,
StandardUsernamePasswordCredentials credentials,
boolean supportsWikiStyleComment,
boolean recordScmChanges,
String userPattern,
boolean updateJiraIssueForAllStatus,
String groupVisibility,
String roleVisibility,
boolean useHTTPAuth,
int timeout,
int readTimeout,
int threadExecutorNumber) {
this(
url,
alternativeUrl,
credentials == null ? null : credentials.getId(),
supportsWikiStyleComment,
recordScmChanges,
userPattern,
updateJiraIssueForAllStatus,
groupVisibility,
roleVisibility,
useHTTPAuth,
timeout,
readTimeout,
threadExecutorNumber);
}
// Deprecate the previous constructor but leave it in place for Java-level compatibility.
@Deprecated
public JiraSite(
URL url,
URL alternativeUrl,
StandardUsernamePasswordCredentials credentials,
boolean supportsWikiStyleComment,
boolean recordScmChanges,
String userPattern,
boolean updateJiraIssueForAllStatus,
String groupVisibility,
String roleVisibility,
boolean useHTTPAuth,
int timeout,
int readTimeout,
int threadExecutorNumber,
boolean useBearerAuth) {
this(
url,
alternativeUrl,
credentials == null ? null : credentials.getId(),
supportsWikiStyleComment,
recordScmChanges,
userPattern,
updateJiraIssueForAllStatus,
groupVisibility,
roleVisibility,
useHTTPAuth,
timeout,
readTimeout,
threadExecutorNumber);
this.useBearerAuth = useBearerAuth;
}
static URL toURL(String url) {
url = Util.fixEmptyAndTrim(url);
if (url == null) {
return null;
}
if (!url.endsWith("/")) {
url = url + "/";
}
try {
return new URL(url);
} catch (MalformedURLException e) {
throw new AssertionError(e);
}
}
@DataBoundSetter
public void setDisableChangelogAnnotations(boolean disableChangelogAnnotations) {
this.disableChangelogAnnotations = disableChangelogAnnotations;
}
public boolean getDisableChangelogAnnotations() {
return disableChangelogAnnotations;
}
/**
* Sets connect timeout (in seconds).
* If not specified, a default timeout will be used.
* @param timeoutSec Timeout in seconds
*/
@DataBoundSetter
public void setTimeout(int timeoutSec) {
this.timeout = timeoutSec;
}
public int getTimeout() {
return timeout;
}
/**
* Sets read timeout (in seconds).
* If not specified, a default timeout will be used.
* @param readTimeout Timeout in seconds
*/
@DataBoundSetter
public void setReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
}
public int getReadTimeout() {
return readTimeout;
}
public String getCredentialsId() {
return credentialsId;
}
@DataBoundSetter
public void setCredentialsId(String credentialsId) {
this.credentialsId = Util.fixEmptyAndTrim(credentialsId);
}
@DataBoundSetter
public void setDateTimePattern(String dateTimePattern) {
this.dateTimePattern = Util.fixEmptyAndTrim(dateTimePattern);
}
@DataBoundSetter
public void setThreadExecutorNumber(int threadExecutorNumber) {
this.threadExecutorNumber = threadExecutorNumber;
}
public int getThreadExecutorNumber() {
return threadExecutorNumber;
}
@DataBoundSetter
public void setAppendChangeTimestamp(boolean appendChangeTimestamp) {
this.appendChangeTimestamp = appendChangeTimestamp;
}
public String getDateTimePattern() {
return dateTimePattern;
}
public boolean isAppendChangeTimestamp() {
return appendChangeTimestamp;
}
public URL getAlternativeUrl() {
return alternativeUrl;
}
public boolean isUseHTTPAuth() {
return useHTTPAuth;
}
public boolean isUseBearerAuth() {
return useBearerAuth;
}
public String getGroupVisibility() {
return groupVisibility;
}
public String getRoleVisibility() {
return roleVisibility;
}
public boolean isSupportsWikiStyleComment() {
return supportsWikiStyleComment;
}
public boolean isRecordScmChanges() {
return recordScmChanges;
}
public boolean isUpdateJiraIssueForAllStatus() {
return updateJiraIssueForAllStatus;
}
@DataBoundSetter
public void setAlternativeUrl(String alternativeUrl) {
this.alternativeUrl = toURL(alternativeUrl);
}
@DataBoundSetter
public void setUseHTTPAuth(boolean useHTTPAuth) {
this.useHTTPAuth = useHTTPAuth;
}
@DataBoundSetter
public void setUseBearerAuth(boolean useBearerAuth) {
this.useBearerAuth = useBearerAuth;
}
@DataBoundSetter
public void setGroupVisibility(String groupVisibility) {
this.groupVisibility = Util.fixEmptyAndTrim(groupVisibility);
}
@DataBoundSetter
public void setRoleVisibility(String roleVisibility) {
this.roleVisibility = Util.fixEmptyAndTrim(roleVisibility);
}
@DataBoundSetter
public void setSupportsWikiStyleComment(boolean supportsWikiStyleComment) {
this.supportsWikiStyleComment = supportsWikiStyleComment;
}
@DataBoundSetter
public void setRecordScmChanges(boolean recordScmChanges) {
this.recordScmChanges = recordScmChanges;
}
@DataBoundSetter
public void setUserPattern(String userPattern) {
this.userPattern = Util.fixEmptyAndTrim(userPattern);
if (this.userPattern == null) {
this.userPat = null;
} else {
this.userPat = Pattern.compile(this.userPattern);
}
}
@DataBoundSetter
public void setUpdateJiraIssueForAllStatus(boolean updateJiraIssueForAllStatus) {
this.updateJiraIssueForAllStatus = updateJiraIssueForAllStatus;
}
@SuppressWarnings("unused")
protected Object readResolve() throws FormException {
JiraSite jiraSite;
if (credentialsId == null && userName != null && password != null) { // Migrate credentials
jiraSite = new JiraSite(
url,
alternativeUrl,
userName,
password.getPlainText(),
supportsWikiStyleComment,
recordScmChanges,
userPattern,
updateJiraIssueForAllStatus,
groupVisibility,
roleVisibility,
useHTTPAuth);
} else {
jiraSite = new JiraSite(
url,
alternativeUrl,
credentialsId,
supportsWikiStyleComment,
recordScmChanges,
userPattern,
updateJiraIssueForAllStatus,
groupVisibility,
roleVisibility,
useHTTPAuth,
timeout,
readTimeout,
threadExecutorNumber);
}
jiraSite.setAppendChangeTimestamp(appendChangeTimestamp);
jiraSite.setDisableChangelogAnnotations(disableChangelogAnnotations);
jiraSite.setDateTimePattern(dateTimePattern);
jiraSite.setUseBearerAuth(useBearerAuth);
return jiraSite;
}
protected static Cache<String, Optional<Issue>> makeIssueCache() {
return Caffeine.newBuilder().expireAfterAccess(2, TimeUnit.MINUTES).build();
}
public String getName() {
return url.toExternalForm();
}
/**
* @deprecated should not be used
*/
@Deprecated
public JiraSession getSession() {
return getSession(null);
}
/**
* Gets a remote access session to this Jira site (job-aware)
* Creates one if none exists already.
*
* @return null if remote access is not supported.
*/
@Nullable
public JiraSession getSession(Item item) {
return getSession(item, false);
}
JiraSession getSession(Item item, boolean uiValidation) {
if (jiraSession == null) {
jiraSession = createSession(item, uiValidation);
}
return jiraSession;
}
JiraSession createSession(Item item) {
return createSession(item, false);
}
/**
* Creates a remote access session to this Jira.
*
* @return null if remote access is not supported.
*/
JiraSession createSession(Item item, boolean uiValidation) {
ItemGroup itemGroup = map(item);
item = itemGroup instanceof Folder ? ((Folder) itemGroup) : item;
StandardUsernamePasswordCredentials credentials = resolveCredentials(item, uiValidation);
if (credentials == null) {
LOGGER.fine("no Jira credentials available for " + item);
return null; // remote access not supported
}
URI uri;
try {
uri = url.toURI();
} catch (URISyntaxException e) {
LOGGER.warning("convert URL to URI error: " + e.getMessage());
throw new RuntimeException("failed to create JiraSession due to convert URI error");
}
LOGGER.fine("creating Jira Session: " + uri);
return JiraSessionFactory.create(this, uri, credentials);
}
Lock getProjectUpdateLock() {
return projectUpdateLock;
}
/**
* This method only supports credential matching by credentialsId.
* Older methods are not and will not be supported as the credentials should have been migrated already.
* @param item can be <code>null</code> if top level
* @param uiValidation if <code>true</code> and credentials not found at item level will not go up
*/
private StandardUsernamePasswordCredentials resolveCredentials(Item item, boolean uiValidation) {
if (credentialsId == null) {
LOGGER.fine("credentialsId is null");
return null; // remote access not supported
}
List<DomainRequirement> req = URIRequirementBuilder.fromUri(url != null ? url.toExternalForm() : null)
.build();
if (item != null) {
StandardUsernamePasswordCredentials credentials = CredentialsMatchers.firstOrNull(
CredentialsProvider.lookupCredentials(
StandardUsernamePasswordCredentials.class, item, ACL.SYSTEM, req),
CredentialsMatchers.withId(credentialsId));
if (credentials != null) {
return credentials;
}
// during UI validation of the configuration we definitely don't want to expose
// global credentials
if (uiValidation) {
return null;
}
}
return CredentialsMatchers.firstOrNull(
CredentialsProvider.lookupCredentials(
StandardUsernamePasswordCredentials.class, Jenkins.get(), ACL.SYSTEM, req),
CredentialsMatchers.withId(credentialsId));
}
protected HttpClientOptions getHttpClientOptions() {
final HttpClientOptions options = new HttpClientOptions();
options.setRequestTimeout(readTimeout, TimeUnit.SECONDS);
options.setSocketTimeout(timeout, TimeUnit.SECONDS);
options.setCallbackExecutor(getExecutorService());
options.setIoThreadCount(ioThreadCount);
return options;
}
private ExecutorService getExecutorService() {
if (executorService == null) {
synchronized (JiraSite.class) {
int nThreads = threadExecutorNumber;
if (nThreads < 1) {
LOGGER.warning("nThreads " + nThreads + " cannot be lower than 1 so use default "
+ DEFAULT_THREAD_EXECUTOR_NUMBER);
nThreads = DEFAULT_THREAD_EXECUTOR_NUMBER;
}
executorService = Executors.newFixedThreadPool(nThreads, new ThreadFactory() {
final AtomicInteger threadNumber = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "jira-plugin-http-request-" + threadNumber.getAndIncrement() + "-thread");
}
});
}
}
return executorService;
}
// not really used but let's leave when it will be implemented
@PreDestroy
public void destroy() {
try {
this.jiraSession = null;
} catch (Exception e) {
LOGGER.log(Level.WARNING, "skip error destroying JiraSite:" + e.getMessage(), e);
}
}
// -----------------------------------------------------------------------------------
// internal classes we want to override
// -----------------------------------------------------------------------------------
public static class ExtendedAsynchronousJiraRestClientFactory implements JiraRestClientFactory {
public ExtendedJiraRestClient create(
final URI serverUri, final AuthenticationHandler authenticationHandler, HttpClientOptions options) {
final DisposableHttpClient httpClient = createClient(serverUri, authenticationHandler, options);
Thread t = Thread.currentThread();
ClassLoader orig = t.getContextClassLoader();
t.setContextClassLoader(JiraSite.class.getClassLoader());
try {
return new ExtendedAsynchronousJiraRestClient(serverUri, httpClient);
} finally {
t.setContextClassLoader(orig);
}
}
@Override
public ExtendedJiraRestClient create(final URI serverUri, final AuthenticationHandler authenticationHandler) {
final DisposableHttpClient httpClient =
createClient(serverUri, authenticationHandler, new HttpClientOptions());
return new ExtendedAsynchronousJiraRestClient(serverUri, httpClient);
}
@Override
public ExtendedJiraRestClient createWithBasicHttpAuthentication(
final URI serverUri, final String username, final String password) {
return create(serverUri, new BasicHttpAuthenticationHandler(username, password));
}
@Override
public ExtendedJiraRestClient createWithAuthenticationHandler(
final URI serverUri, final AuthenticationHandler authenticationHandler) {
return create(serverUri, authenticationHandler);
}
@Override
public ExtendedJiraRestClient create(final URI serverUri, final HttpClient httpClient) {
final DisposableHttpClient disposableHttpClient = createClient(httpClient);
return new ExtendedAsynchronousJiraRestClient(serverUri, disposableHttpClient);
}
}
private static DisposableHttpClient createClient(
final URI serverUri, final AuthenticationHandler authenticationHandler, HttpClientOptions options) {
final DefaultHttpClientFactory defaultHttpClientFactory = new DefaultHttpClientFactory(
new NoOpEventPublisher(),
new RestClientApplicationProperties(serverUri),
new ThreadLocalContextManager() {
@Override
public Object getThreadLocalContext() {
return null;
}
@Override
public void setThreadLocalContext(Object context) {}
@Override
public void clearThreadLocalContext() {}
});
final HttpClient httpClient = defaultHttpClientFactory.create(options);
return new AtlassianHttpClientDecorator(httpClient, authenticationHandler) {
@Override
public void destroy() throws Exception {
defaultHttpClientFactory.dispose(httpClient);
}
};
}
private static DisposableHttpClient createClient(final HttpClient client) {
return new AtlassianHttpClientDecorator(client, null) {
@Override
public void destroy() throws Exception {
// This should never be implemented. This is simply creation of a wrapper
// for AtlassianHttpClient which is extended by a destroy method.
// Destroy method should never be called for AtlassianHttpClient coming from
// a client! Imagine you create a RestClient, pass your own HttpClient there
// and it gets destroy.
}
};
}
private static class NoOpEventPublisher implements EventPublisher {
@Override
public void publish(Object o) {}
@Override
public void register(Object o) {}
@Override
public void unregister(Object o) {}
@Override
public void unregisterAll() {}
}
@SuppressWarnings("deprecation")
private static class RestClientApplicationProperties implements ApplicationProperties {
private final String baseUrl;
private RestClientApplicationProperties(URI jiraURI) {
this.baseUrl = jiraURI.getPath();
}
@Override
public String getBaseUrl() {
return baseUrl;
}
/**
* We'll always have an absolute URL as a client.
*/
@NonNull
@Override
public String getBaseUrl(UrlMode urlMode) {
return baseUrl;
}
@NonNull
@Override
public String getDisplayName() {
return "Atlassian Jira Rest Java Client";
}
@NonNull
@Override
public String getPlatformId() {
return ApplicationProperties.PLATFORM_JIRA;
}
@NonNull
@Override
public String getVersion() {
return "";
}
@NonNull
@Override
public Date getBuildDate() {
throw new UnsupportedOperationException();
}
@NonNull
@Override
public String getBuildNumber() {
return String.valueOf(0);
}
@Override
public File getHomeDirectory() {
return new File(".");
}
@Override
public String getPropertyValue(final String s) {
throw new UnsupportedOperationException("Not implemented");
}
@NonNull