-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathjpinpoint-kotlin-rules.xml
More file actions
1036 lines (965 loc) · 51.5 KB
/
jpinpoint-kotlin-rules.xml
File metadata and controls
1036 lines (965 loc) · 51.5 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
<?xml version="1.0" encoding="UTF-8"?>
<ruleset name="jpinpoint-kotlin-rules"
xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
<description>
jPinpoint rules for responsible Kotlin coding, sponsored by Rabobank. Uses PMD-7.
</description>
<!-- IMPORTANT NOTICE: The content of this file is generated. Do not edit this file directly since changes may be lost when this file is regenerated! -->
<!-- BEGIN Included file 'common.xml' -->
<rule name="AvoidDecimalAndChoiceFormatAsField"
language="kotlin"
message="Avoid using NumberFormat, DecimalFormat or ChoiceFormat as field since it is thread-unsafe."
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#isio01">
<description>
Problem: java.text.DecimalFormat and java.text.ChoiceFormat are thread-unsafe.
Solution: usual solution is to create a new local one when needed in a method.
(jpinpoint-rules)
(jpinpoint-rules)</description>
<priority>1</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="xpath">
<value><![CDATA[
(: check if at least one java.text imports exists as filter for same named classes in other packages :)
//ImportHeader[.//T-Identifier[@Text='java'] and .//T-Identifier[@Text='text']][1]/ancestor::KotlinFile
(: PrimaryExpression finds the constructors instead of type declarations :)
(: filter matches in functions :)
//TopLevelObject//PrimaryExpression//SimpleIdentifier//T-Identifier[
(@Text="DecimalFormat" or @Text="ChoiceFormat")
and not(ancestor::FunctionBody)
]
]]>
</value>
</property>
</properties>
<example><![CDATA[
class Foo {
companion object {
val NUMBER_FORMAT: DecimalFormat = DecimalFormat("###.###") // bad
}
private val numFormat: NumberFormat = DecimalFormat("###.###") //bad
private val limits = doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0)
private val dayOfWeekNames = arrayOf("Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat")
private val form = ChoiceFormat(limits, dayOfWeekNames) // bad
fun shouldNotMatchInsideMethod() {
val format: NumberFormat = DecimalFormat("##.##")
val choiceFormat = ChoiceFormat(limits, dayOfWeekNames)
}
}
]]>
</example>
</rule>
<rule name="AvoidImplicitlyRecompilingRegex"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
language="kotlin"
message="String regex method, Pattern.matches or FileSystem.getPathMatcher is used. Implicitly compiles a regex pattern, can be expensive."
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#ireu01">
<description>A regular expression is compiled implicitly on every invocation. Problem: this can be expensive, depending on the length of the regular expression.
Solution: Compile the regex pattern only once and assign it to a private static final Pattern field. java.util.Pattern objects are thread-safe so they can be shared among threads.
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="xpath">
<value><![CDATA[
//FunctionDeclaration//PostfixUnaryExpression//SimpleIdentifier/T-Identifier[
@Text='Regex'
(: not called on fun parameter :)
and not(ancestor::PostfixUnaryExpression//CallSuffix//PrimaryExpression//T-Identifier[
@Text = ancestor::FunctionDeclaration//FunctionValueParameter//Parameter/SimpleIdentifier/T-Identifier/@Text])
(: not called on 'dynamic' function call :)
and not(ancestor::PostfixUnaryExpression/PostfixUnarySuffix/CallSuffix//CallSuffix//CallSuffix)
(: not if based on local variable initialized by fun parameter :)
and not(ancestor::CallSuffix//PostfixUnaryExpression/PrimaryExpression/SimpleIdentifier/T-Identifier[
@Text = ancestor::FunctionBody//PropertyDeclaration/VariableDeclaration/SimpleIdentifier/T-Identifier/@Text])
(: not param in String template in fun parameter :)
and not(../../../../PostfixUnaryExpression//CallSuffix/ValueArguments/ValueArgument//LineStringContent/T-LineStrRef[
@Text = ancestor::FunctionDeclaration//Parameter/SimpleIdentifier/T-Identifier/concat('$', @Text)])
(: not param in String template of class var field :)
and not(../../../../PostfixUnaryExpression//CallSuffix/ValueArguments/ValueArgument//LineStringContent/T-LineStrRef[
@Text = ancestor::ClassDeclaration//PropertyDeclaration[T-VAR]//SimpleIdentifier/T-Identifier/concat('$', @Text)])
(: not param in String concatenation of class var field :)
and not(../../../../PostfixUnaryExpression//CallSuffix/ValueArguments/ValueArgument[//LineStringLiteral]//AdditiveExpression/MultiplicativeExpression//SimpleIdentifier/T-Identifier[
@Text = ancestor::ClassDeclaration//PropertyDeclaration[T-VAR]//SimpleIdentifier/T-Identifier/@Text])
]
|
//FunctionDeclaration//PostfixUnaryExpression/PostfixUnarySuffix/NavigationSuffix/SimpleIdentifier/T-Identifier[
@Text='toRegex'
(: not called on function parameter :)
and not(../../../../PrimaryExpression//T-Identifier[
@Text = ancestor::FunctionDeclaration//FunctionValueParameter//Parameter/SimpleIdentifier/T-Identifier/@Text])
(: not called on 'dynamic' function call :)
and not(ancestor::PostfixUnaryExpression/PostfixUnarySuffix[1]/CallSuffix)
(: not if based on local variable initialized by fun parameter :)
and not(../../../../../PostfixUnaryExpression/PrimaryExpression/SimpleIdentifier/T-Identifier[
@Text = ancestor::FunctionBody//PropertyDeclaration/VariableDeclaration/SimpleIdentifier/T-Identifier/@Text])
]
|
(: check if java.util.regex.Pattern import exists as filter for same named classes in other packages :)
//ImportHeader[
(.//T-Identifier[@Text='java'] and .//T-Identifier[@Text='util'] and .//T-Identifier[@Text='regex'] and .//T-Identifier[@Text='Pattern'] or .//T-MULT)
][1]/ancestor::KotlinFile
//SimpleIdentifier/T-Identifier[@Text='Pattern'
and ../../../PostfixUnarySuffix//T-Identifier[@Text='matches']
(: not if first param is fun parameter :)
and not(../../../PostfixUnarySuffix/CallSuffix/ValueArguments/ValueArgument[1]//SimpleIdentifier/T-Identifier[
@Text = ancestor::FunctionDeclaration//Parameter/SimpleIdentifier/T-Identifier/@Text])
]
|
(: check if java.nio.file.FileSystems or java.nio.file.Path imports exists as filter for same named classes in other packages :)
(: TODO is this a bug: having to use T-FILE for 'file' :)
//ImportHeader[
(.//T-Identifier[@Text='java']
and .//T-Identifier[@Text='nio'] and .//T-FILE[@Text='file'] and .//T-Identifier[@Text='FileSystems' or @Text='Path'] or .//T-MULT)
][1]/ancestor::KotlinFile
(: added [ancestor::NavigationSuffix] to avoid PAT_STRING param from being selected too :)
//FunctionDeclaration//PostfixUnarySuffix//T-Identifier[ancestor::NavigationSuffix][@Text='getPathMatcher'
and (ancestor::PostfixUnaryExpression/PrimaryExpression//T-Identifier[@Text=
ancestor::Statement/preceding-sibling::Statement//VariableDeclaration[../Expression//T-Identifier[@Text='FileSystems']]//T-Identifier/@Text]
or ancestor::PostfixUnaryExpression/PrimaryExpression/SimpleIdentifier/T-Identifier[@Text='FileSystems']
)
(: not if first param is fun parameter :)
and not(ancestor::PrefixUnaryExpression//CallSuffix/ValueArguments/ValueArgument//SimpleIdentifier/T-Identifier[
@Text = ancestor::FunctionDeclaration//Parameter/SimpleIdentifier/T-Identifier/@Text])
(: not param in String template in fun parameter :)
and not(ancestor::PrefixUnaryExpression//CallSuffix/ValueArguments/ValueArgument//LineStringContent/T-LineStrRef[
@Text = ancestor::FunctionDeclaration//Parameter/SimpleIdentifier/T-Identifier/concat('$', @Text)])
]
]]></value>
</property>
</properties>
<example>
class Foo {
companion object {
val INNER_LINE_BREAK_REGEX = """([^.\n])\n""".toRegex()
val INNER_LINE_BREAK_PATTERN = """([^.\n])\n""".toPattern()
}
fun bad_replaceInnerLineBreakBySpace(text: String): String {
return text.replace("""([^.\n])\n""".toRegex(), "$1 ") // bad
}
fun good_replaceInnerLineBreakBySpace1(text: String): String {
return text.replace(INNER_LINE_BREAK_REGEX, "$1 ") // good
}
fun good_replaceInnerLineBreakBySpace2(text: String): String {
return INNER_LINE_BREAK_PATTERN.matcher(text).replaceAll("$1 ") // good
}
fun storeUsingRegex(regex: String, sourceName: String, dataTable: DataTable) {
val dtm = dataTable.asMaps()
val source = testContext.parameter(sourceName)
val matches = Regex(regex).findAll(source.toString()).toList()
}
}
</example>
</rule>
<rule name="AvoidInMemoryStreamingDefaultConstructor"
language="kotlin"
message="The default capacity or smaller is used for ByteArrayOutputStream or StringWriter, it usually needs expensive expansions."
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#isio01">
<description>
The default constructor of ByteArrayOutputStream creates a 32-byte initial capacity and for StringWriter 16 chars. Problem: Such a small buffer as capacity usually needs several expensive expansions.
Solution: Pre-size the ByteArrayOutputStream or StringWriter with an initial capacity such that an expansion is not needed in most cases, typically much larger than 32, for instance, 4096.
(jpinpoint-rules)
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="xpath">
<value><![CDATA[
//ImportHeader[.//T-Identifier[@Text='java'] and .//T-Identifier[@Text='io']][1]/ancestor::KotlinFile
//Expression//T-Identifier[(@Text='ByteArrayOutputStream' and ../../../
PostfixUnarySuffix[1]//ValueArguments[not(ValueArgument) or ValueArgument//T-IntegerLiteral[number(@Text)<=32]])
or (@Text='StringWriter' and ../../../
PostfixUnarySuffix[1]//ValueArguments[not(ValueArgument) or ValueArgument//T-IntegerLiteral[number(@Text)<=16]])]
]]>
</value>
</property>
</properties>
<example><![CDATA[
import java.io.ByteArrayOutputStream
import java.io.StringWriter
class AvoidInMemoryStreamingDefaultConstructor {
fun bad() {
var baos = ByteArrayOutputStream() //bad
val sw = StringWriter() //bad
baos = ByteArrayOutputStream(32) //bad - not larger than default
}
fun good() {
val baos = ByteArrayOutputStream(8192) // 8 kiB
val sw = StringWriter(2048)
}
}
]]>
</example>
</rule>
<rule name="AvoidMultipleConcatStatements" class="net.sourceforge.pmd.lang.rule.xpath.XPathRule" language="kotlin" message="Multiple statements concatenate to the same String. Use StringBuilder append." externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#isu02">
<description>Multiple statements concatenate to the same String. Problem: Each statement with one or more +-operators creates a hidden temporary StringBuilder, a char[] and a new String object, which all have to be garbage collected.
Solution: Use StringBuilder.append.
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="xpath">
<value><![CDATA[
//FunctionBody[
not(ancestor::FunctionDeclaration/SimpleIdentifier/T-Identifier[@Text='hashCode'])
and
count(
.//Assignment[
.//(AssignmentAndOperator/T-ADD_ASSIGNMENT|AdditiveOperator/T-ADD)
and
(AssignableExpression|DirectlyAssignableExpression)//T-Identifier[
(: property a string literal :)
@Text = ancestor::FunctionBody//PropertyDeclaration[
(
Expression[not(.//Expression)]//StringLiteral
(: explicit type String:)
or VariableDeclaration/Type//T-Identifier[@Text='String']
(: assigned parameter of type String :)
or Expression[.//T-Identifier[@Text = ancestor::FunctionDeclaration/FunctionValueParameters/FunctionValueParameter[Parameter/Type//T-Identifier[@Text='String']]//T-Identifier/@Text]]
(: assigned non-nested function of explicit type String :) (: known issue: ignores parameters, may give false positives with overloaded methods :)
or Expression[.//T-Identifier[not(ancestor::CallSuffix)][@Text = ancestor::ClassMemberDeclarations//FunctionDeclaration[Type//T-Identifier[@Text='String']]//T-Identifier/@Text]]
)
and not(Expression//T-Identifier[@Text='toMutableList'])
]/VariableDeclaration//T-Identifier/@Text
]
]
) > 1
]
//Statement[Assignment//(T-ADD_ASSIGNMENT|T-ADD)][position()=last()]
]]></value>
</property>
</properties>
<example>
</example>
</rule>
<rule name="AvoidRecompilingPatterns"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
language="kotlin"
message="Pattern.compile is used in a method. Compiling a regex pattern can be expensive, make it a constant or instance field."
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#ireu02">
<description>A regular expression is compiled on every invocation. Problem: this can be expensive, depending on the length of the regular expression.
Solution: Usually a pattern is a literal, not dynamic and can be compiled only once. Assign it to a private constant or instance field.
java.util.Pattern objects are thread-safe so they can be shared among threads. (jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="xpath">
<value><![CDATA[
(: check if java.util.regex imports exists as filter for same named classes in other packages :)
//ImportHeader[.//T-Identifier[@Text='java'] and .//T-Identifier[@Text='util'] and .//T-Identifier[@Text='regex']][1]/ancestor::KotlinFile
//FunctionBody//T-Identifier[@Text='Pattern' and ../../../PostfixUnarySuffix//T-Identifier[@Text='compile']
(: check for variables $action or ${action} in String of compile() call (first in possible call chain): allow dynamic input :)
and not(
let $params := ancestor::FunctionDeclaration//FunctionValueParameter/Parameter/SimpleIdentifier/T-Identifier/@Text
return
((../../..//ValueArgument)[1]//PostfixUnaryExpression//T-Identifier | (../../..//ValueArgument)[1]//T-LineStrRef)[
@Text = $params
or (some $x in $params satisfies @Text = concat('$', $x))
]
)
]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
import java.util.regex.Pattern
internal object Bad {
const val STR_PAT1: String = "[A-Z][a-z]+"
fun bad() {
val p1: Pattern = Pattern.compile(STR_PAT1) // bad
val p2: Pattern = Pattern.compile("(?=\\p{Lu})") // bad
val b: Boolean = p1.matcher("Start ").matches()
}
}
internal object Good {
val PAT1: Pattern = Pattern.compile("[A-Z][a-z]+")
val PAT2: Pattern = Pattern.compile("(?=\\p{Lu})")
fun good() {
val b: Boolean = PAT1.matcher("Start ").matches()
}
}
]]>
</example>
</rule>
<rule name="AvoidRecompilingXPathExpression" class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
language="kotlin"
message="XPathExpression is created and compiled every time. Beware it is thread-unsafe."
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#ux02">
<description>XPathExpression is created and compiled on every method call, compiled possibly implicitly by XPath::evaluate.
Problem: Creation of XPath and compilation of XPathExpression takes time. It may slow down your application.
Solution:
1. Avoid XPath usage.
2. Compile the xpath expression as String into a XPathExpression. However, since XPath and XPathExpression classes are thread-unsafe, they are not easily cached. Caching it in a ThreadLocal may be a solution.
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="xpath">
<value><![CDATA[
//ImportHeader[.//T-Identifier[@Text='javax'] and .//T-Identifier[@Text='xml'] and .//T-Identifier[@Text='xpath']]/ancestor::KotlinFile
//FunctionBody//T-Identifier[@Text='newXPath']
/ancestor::FunctionBody//T-Identifier[@Text='compile'
or (@Text='evaluate' and ancestor::PostfixUnarySuffix/..//ValueArguments[count(./ValueArgument) = 3])]
(: note on limitation, the 2-argument version is not found, difficult to do the typeIs checking like in Java :)
]]></value>
</property>
</properties>
<example>
<![CDATA[
import org.w3c.dom.Document
import org.w3c.dom.NodeList
import javax.xml.xpath.*
class AvoidRecompilingXPathExpressionKotlin {
fun bad1(doc: Document?): NodeList {
val xpath: XPath = XPathFactory.newInstance().newXPath()
val expr: XPathExpression = xpath.compile("//book[author='Isaac Asimov']/title/text()") // bad
return expr.evaluate(doc, XPathConstants.NODESET) as NodeList
}
@Throws(XPathExpressionException::class)
fun bad2(doc: Document?): NodeList {
val xpath: XPath = XPathFactory.newInstance().newXPath()
val xPathQuery = "//book[author='Isaac Asimov']/title/text()"
return xpath.evaluate(xPathQuery, doc, XPathConstants.NODESET) as NodeList // bad
}
}
object GoodAvoidRecompilingXPathExpressionKt {
private val tlFac = ThreadLocal.withInitial { XPathFactory.newInstance() }
private val tlExpr: ThreadLocal<XPathExpression>
init {
val xpath = tlFac.get().newXPath()
val expr: XPathExpression = try {
xpath.compile("//book[author='Isaac Asimov']/title/text()")
} catch (e: XPathExpressionException) {
throw RuntimeException(e)
}
tlExpr = ThreadLocal.withInitial { expr } // good
}
@Throws(XPathExpressionException::class)
fun good(doc: Document?): NodeList {
return tlExpr!!.get().evaluate(doc, XPathConstants.NODESET) as NodeList // good
}
}
]]>
</example>
</rule>
<rule name="AvoidRecreatingDateTimeFormatter"
message="Avoid recreating DateTimeFormatter, it is relatively expensive."
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule" language="kotlin"
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/master/docs/JavaCodePerformance.md#idtf02">
<description>
Problem: Recreating a DateTimeFormatter is relatively expensive.
Solution: org.joda.time.format.DateTimeFormatter or Java 8 java.time.DateTimeFormatter is thread-safe and can be shared among threads. Create the
formatter from a pattern only once, to initialize a constant or instance field.
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="xpath">
<value>
<![CDATA[
(: check if java.time.format or org.joda.time.format imports exists as filter for same named classes in other packages :)
//ImportHeader[
(.//T-Identifier[@Text='org'] and .//T-Identifier[@Text='joda'] and .//T-Identifier[@Text='time'] and .//T-Identifier[@Text='format'])
or (.//T-Identifier[@Text='java'] and .//T-Identifier[@Text='time'] and .//T-Identifier[@Text='format'])
][1]/ancestor::KotlinFile
/TopLevelObject//Expression//T-Identifier[
(@Text='DateTimeFormatter' or @Text='DateTimeFormat' or @Text='DateTimeFormatterBuilder' or @Text='ISODateTimeFormat')
(: val is "final" and is allowed in CompanionObject :)
and (not(ancestor::PropertyDeclaration/T-VAL) or (ancestor::PropertyDeclaration/T-VAL and not(ancestor::CompanionObject)))
(: and 'final static' is allowed, top level, field outside of class/object :)
and (ancestor::ClassDeclaration or ancestor::ObjectDeclaration)
(: do not match explicit type declarations :)
and not(ancestor::TypeReference)
(: variable params are allowed, e.g. when it is an incoming function param :)
and not(ancestor::PrefixUnaryExpression//ValueArgument[.//T-Identifier[@Text = ancestor::FunctionDeclaration/FunctionValueParameters/FunctionValueParameter/Parameter/SimpleIdentifier/T-Identifier/@Text]])
(: variable class params are allowed in val fields :)
and (not(ancestor::PropertyDeclaration/T-VAL) or not(ancestor::PrefixUnaryExpression//ValueArgument[.//T-Identifier[@Text = ancestor::ClassDeclaration//ClassParameters/ClassParameter/SimpleIdentifier/T-Identifier/@Text]])
(: not when like DateTimeFormatter.ISO_DATE_TIME :)
and (not(ancestor::PostfixUnaryExpression[count(PostfixUnarySuffix) = 1]))
)
]
|
(: java.time.format.DateTimeFormatter variable params are allowed in field init in constructors if val :)
//ImportHeader[
.//T-Identifier[@Text='java'] and .//T-Identifier[@Text='time'] and .//T-Identifier[@Text='format']
][1]/ancestor::KotlinFile
/TopLevelObject//Expression//T-Identifier[
@Text='DateTimeFormatter'
(: check if variable function params in init constructor with two params :)
and ancestor::PostfixUnaryExpression/PostfixUnarySuffix//ValueArguments[
count(ValueArgument) = 2
and count(./ValueArgument//T-Identifier[@Text = ancestor::FunctionDeclaration/FunctionValueParameters/FunctionValueParameter/Parameter/SimpleIdentifier/T-Identifier/@Text]) = 2
(: check if variable is a var :)
and ancestor::Statement/Assignment//T-Identifier[@Text = ancestor::ClassBody//VariableDeclaration//T-Identifier[ancestor::PropertyDeclaration/T-VAR]/@Text]
]
]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
class Bad {
public String formatDate(LocalDateTime date) {
DateTimeFormatter dtf = new DateTimeFormatterBuilder().toFormatter(); // bad, created each time
return dtf.format(date);
}
}
class Good {
private static final DateTimeFormatter DTF = new DateTimeFormatterBuilder().toFormatter();
public String formatDate(LocalDateTime date) {
return DTF.format(date); // good, reuse thread-safe formatter
}
}
]]>
</example>
</rule>
<rule name="AvoidSimpleDateFormat"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
language="kotlin"
message="SimpleDateFormat is used. Since it is thread-unsafe, it needs expensive recreation."
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#idtf01">
<description>Problem: java.util.SimpleDateFormat is thread-unsafe. The usual solution is to create a new one when needed in a method. Creating SimpleDateFormat is relatively expensive.
Solution: Use java.time.DateTimeFormatter. These classes are immutable, thus thread-safe and can be made static.
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="xpath">
<value><![CDATA[
(: check if java.text imports exists as filter for same named classes in other packages :)
//ImportHeader[.//T-Identifier[@Text='java'] and .//T-Identifier[@Text='text']][1]/../..
(: if used in setDateFormat function, allow if jackson ObjectMapper or XmlMapper is used :)
//ClassMemberDeclaration//SimpleIdentifier//T-Identifier[(@Text="SimpleDateFormat")
and not (ancestor::ClassMemberDeclaration//T-Identifier[@Text="setDateFormat"]
and //ImportHeader[.//T-Identifier[@Text='fasterxml'] and .//T-Identifier[@Text='jackson']]
)
]
]]></value>
</property>
</properties>
<example><![CDATA[
import java.text.SimpleDateFormat
import java.util.*
class Foo {
private fun toKey(calcDate: Date): String {
val formatter = SimpleDateFormat("yyyy-MM-dd") //bad
return formatter.format(calcDate)
}
}
]]>
</example>
</rule>
<rule name="AvoidStringBuffer" class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
language="kotlin"
message="StringBuffer is used. It introduces locking overhead, use StringBuilder."
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#isu01" >
<description>Problem: StringBuffer introduces locking overhead because it is thread safe. Its thread-safety is rarely needed.
Solution: Replace StringBuffer by StringBuilder. (jpinpoint-rules)</description>
<priority>3</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="xpath">
<value><![CDATA[
//VariableDeclaration/Type//T-Identifier[@Text='StringBuffer'],
//Declaration//PrimaryExpression//T-Identifier[@Text='StringBuffer']
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
class AvoidStringBuffer {
var fieldSb: StringBuffer? = null // bad
fun bad() {
val sb = StringBuffer() // bad
}
fun good() {
val sb = StringBuilder()
}
]]>
</example>
</rule>
<rule name="AvoidWideScopeXPathExpression"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
language="kotlin"
message="XPathExpression targets a wide scope, this is potentially slow."
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#ux01">
<description>The XPathExpression targets a wide scope since it starts with `//`. Problem: XPath has to search in a wide scope for occurrences, this may take a while.
Solution:
1. Avoid XPath usage.
2. Make the scope as narrow as possible, do not start with `//`.
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="xpath">
<value><![CDATA[
(: check if javax.xml.xpath imports exists as filter for same named classes in other packages :)
//ImportHeader[.//T-Identifier[@Text='javax'] and .//T-Identifier[@Text='xml'] and .//T-Identifier[@Text='xpath']][1]/../..
(: if 'compile' method exists with one parameter of String literal with first chars '//' :)
//ClassMemberDeclaration//SimpleIdentifier//T-Identifier[(@Text="compile")
and ancestor::Expression//ValueArguments[count(./ValueArgument) = 1]/ValueArgument//PrimaryExpression/StringLiteral//T-LineStrText[starts-with(@Text, '//')]
]
]]></value>
</property>
</properties>
<example><![CDATA[
import org.w3c.dom.Node
import javax.xml.xpath.XPath
import javax.xml.xpath.XPathFactory
class Foo {
var xpath: XPath = XPathFactory.newInstance().newXPath()
fun parseSomething(books: Node) {
val expr = xpath
.compile("//book[author='Isaac Asimov']/title/text()") // bad
val result = expr.evaluate(books)
}
}
]]>
</example>
</rule>
<rule name="AvoidXPathAPIUsage"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
language="kotlin"
message="XPathAPI is used. XPathAPI implementation has bad performance."
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#ux01">
<description>XPathAPI is used. Problem: XPathAPI implementation is slow.
Solution:
1. try to avoid using XPathAPI.
2. improve performance by using jvm parameters and possibly CachedXPathAPI.
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<!--property name="tag" value="performance" type="String" description="for-sonar"/-->
<property name="xpath">
<value><![CDATA[
//ImportHeader[.//T-Identifier[@Text='org'] and .//T-Identifier[@Text='apache'] and .//T-Identifier[@Text='xpath']][1]/ancestor::KotlinFile
//ClassBody//SimpleIdentifier/T-Identifier[@Text='XPathAPI']
]]></value>
</property>
</properties>
<example><![CDATA[
import org.w3c.dom.Node
import org.apache.xpath.XPathAPI
import org.apache.xpath.CachedXPathAPI
class FooBad {
fun getAction(doc: Node?): String? {
return try {
XPathAPI.eval(doc, "/Envelope/Header/Action").toString() // bad
} catch (e: TransformerException) {
null
}
}
}
class FooGood {
fun getAction(doc: Node?): String? {
return try {
CachedXPathAPI.eval(doc, "/Envelope/Header/Action").toString()
} catch (e: TransformerException) {
null
}
}
}
]]>
</example>
</rule>
<rule name="MDCPutWithoutRemove"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
language="kotlin"
message="MDC put is used without remove or clear in the same function"
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#IL04">
<description>
MDC values are added for logging, but no corresponding remove or clear is performed. Problem: MDC values can leak to other user transactions (requests) and log incorrect information. Solution: remove the MDC value in a finally clause or clear the MDC.
(jpinpoint-rules - Kotlin)
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="xpath">
<value><![CDATA[
(: Only consider files that import org.slf4j.MDC :)
//ImportHeader[.//T-Identifier[@Text='org'] and .//T-Identifier[@Text='slf4j'] and .//T-Identifier[@Text='MDC']][1]/ancestor::KotlinFile
(: Select calls to MDC.put(..) :)
//PostfixUnaryExpression[
PrimaryExpression/SimpleIdentifier/T-Identifier[@Text='MDC']
and PostfixUnarySuffix/NavigationSuffix/SimpleIdentifier/T-Identifier[@Text='put']
]
(: Report the 'put' identifier if there is no MDC.remove(..) or MDC.clear() in same function, nor via a method called from a finally block (Issue #653) :)
/PostfixUnarySuffix/NavigationSuffix/SimpleIdentifier/T-Identifier[@Text='put'
and not(
(: same function body has direct MDC.remove/clear :)
ancestor::FunctionBody//PostfixUnaryExpression[
PrimaryExpression/SimpleIdentifier/T-Identifier[@Text='MDC']
and PostfixUnarySuffix/NavigationSuffix/SimpleIdentifier/T-Identifier[@Text=('remove','clear')]
]
or
(
(: put-arg text equals any remove-arg text inside a helper method that is called from a finally block in this class :)
ancestor::ClassDeclaration
//FunctionDeclaration[
SimpleIdentifier/T-Identifier/@Text = ancestor::ClassDeclaration//TryExpression//FinallySection//PostfixUnaryExpression[PostfixUnarySuffix/CallSuffix]//PrimaryExpression/SimpleIdentifier/T-Identifier/@Text
]
//PostfixUnaryExpression[
PrimaryExpression/SimpleIdentifier/T-Identifier[@Text='MDC']
and PostfixUnarySuffix/NavigationSuffix/SimpleIdentifier/T-Identifier[@Text='remove']
]/PostfixUnarySuffix/CallSuffix/ValueArguments/ValueArgument[1]//(SimpleIdentifier/T-Identifier|LineStringLiteral//T-LineStrText)/@Text
=
ancestor::PostfixUnaryExpression/PostfixUnarySuffix/CallSuffix/ValueArguments/ValueArgument[1]//(SimpleIdentifier/T-Identifier|LineStringLiteral//T-LineStrText)/@Text
)
or
(
(: helper method called from finally does MDC.clear() :)
ancestor::ClassDeclaration
//FunctionDeclaration[
SimpleIdentifier/T-Identifier/@Text = ancestor::ClassDeclaration//TryExpression//FinallySection//PostfixUnaryExpression/PostfixUnarySuffix/NavigationSuffix/SimpleIdentifier/T-Identifier/@Text
]
//PostfixUnaryExpression[
PrimaryExpression/SimpleIdentifier/T-Identifier[@Text='MDC']
and PostfixUnarySuffix/NavigationSuffix/SimpleIdentifier/T-Identifier[@Text='clear']
]
)
or
(
(: looser, anywhere in class: a remove of same key exists :)
ancestor::ClassDeclaration//PostfixUnaryExpression[
PrimaryExpression/SimpleIdentifier/T-Identifier[@Text='MDC']
and PostfixUnarySuffix/NavigationSuffix/SimpleIdentifier/T-Identifier[@Text='remove']
]/PostfixUnarySuffix/CallSuffix/ValueArguments/ValueArgument[1]//(SimpleIdentifier/T-Identifier|LineStringLiteral//T-LineStrText)/@Text
=
ancestor::PostfixUnaryExpression/PostfixUnarySuffix/CallSuffix/ValueArguments/ValueArgument[1]//(SimpleIdentifier/T-Identifier|LineStringLiteral//T-LineStrText)/@Text
)
or
(
(: looser, anywhere in class: a clear exists :)
ancestor::ClassDeclaration//PostfixUnaryExpression[
PrimaryExpression/SimpleIdentifier/T-Identifier[@Text='MDC']
and PostfixUnarySuffix/NavigationSuffix/SimpleIdentifier/T-Identifier[@Text='clear']
]
)
)
]
]]></value>
</property>
</properties>
<example><![CDATA[
import org.slf4j.MDC
class BadKotlinMdc {
fun bad() {
MDC.put("levelKey1", "levelName1") // bad, not removed or cleared
MDC.put("levelKey2", "levelName2") // bad, not removed or cleared
}
}
class GoodKotlinMdc {
fun good() {
try {
MDC.put("levelKey1", "levelName1")
MDC.put("levelKey2", "levelName2")
} finally {
MDC.clear()
}
}
}
]]></example>
</rule>
<!-- END Included file 'common.xml' -->
<!-- BEGIN Included file 'remoting.xml' -->
<rule name="AvoidDeprecatedHystrix"
language="kotlin"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
message="Netflix Hystrix is deprecated. Use an alternative like resilience4j"
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#ibi11">
<description>Problem: Hystrix is not actively maintained anymore.
Solution: Netflix recommends to use open source alternatives like resilience4j. (jpinpoint-rules)</description>
<priority>3</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="xpath">
<value><![CDATA[
(: check if javax.xml.xpath imports exists as filter for same named classes in other packages :)
//ImportHeader[.//T-Identifier[@Text='com'] and .//T-Identifier[@Text='netflix'] and .//T-Identifier[@Text='hystrix']][1]/../..
]]>
</value>
</property>
</properties>
<example>
</example>
</rule>
<rule name="HttpClientBuilderWithoutDisableConnectionState"
language="kotlin"
message="A HttpClient builder is used and disableConnectionState is not called. HTTP client tracks connection state while using TLS."
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#ibi07">
<description>
Problem: NTLM authenticated connections and SSL/TLS connections with client certificate authentication are stateful: they have a specific user identity/security context per session. If HttpClients have enabled connection state tracking which is the default, established TLS connections will not be reused because it is assumed that the user identity or security context may differ.
Then performance will suffer due to a full TLS handshake for each request.
Solution: HttpClients should disable connection state tracking in order to reuse TLS connections, since service calls for one pool have the same user identity/security context for all sessions. (jpinpoint-rules)
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="xpath">
<value><![CDATA[
(:locally created http client builder without disableConnectionState :)
//PostfixUnarySuffix//SimpleIdentifier/T-Identifier[@Text="custom"
and ancestor::PostfixUnaryExpression/PrimaryExpression/SimpleIdentifier/T-Identifier/@Text="HttpClients"
and not(ancestor::PostfixUnaryExpression/PostfixUnarySuffix/NavigationSuffix/SimpleIdentifier/T-Identifier/@Text="disableConnectionState")]
,
//PostfixUnarySuffix//SimpleIdentifier/T-Identifier[@Text="create"
and ancestor::PostfixUnaryExpression/PrimaryExpression/SimpleIdentifier/T-Identifier[(@Text="HttpClientBuilder" or @Text="HttpAsyncClientBuilder")
and not(ancestor::PostfixUnaryExpression/PostfixUnarySuffix/NavigationSuffix/SimpleIdentifier/T-Identifier/@Text="disableConnectionState")]]
,
(: method param http client builder without disableConnectionState :)
//FunctionValueParameter/Parameter/Type/TypeReference/UserType/SimpleUserType/SimpleIdentifier/T-Identifier[(@Text="HttpClients" or @Text="HttpClientBuilder" or @Text="HttpAsyncClientBuilder")
and not(ancestor::FunctionDeclaration//PostfixUnarySuffix/NavigationSuffix/SimpleIdentifier/T-Identifier/@Text="disableConnectionState")]
]]>
</value>
</property>
</properties>
<example><![CDATA[
private fun createHttpClientBuilder(properties: ConnectionProperties) =
HttpClients.custom()
.setDefaultRequestConfig(createRequestConfig(properties))
.setMaxConnTotal(properties.maxConnTotal)
.setMaxConnPerRoute(properties.maxConnPerRoute) // violation, no disableConnectionState() call
]]>
</example>
</rule>
<rule name="HttpClientBuilderWithoutPoolSize"
language="kotlin"
message="HttpClient builder connection pool is not configured."
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#ibi03">
<description>
Problem: when the [default max connections per route] external calls are being made to the same host,
the next thread requesting a connection to that host must wait for a free connection.
For Apache HttpClient v4, this default = 2 and for v5 this default = 5, often too low.
Max total connections are 20 and 25 respectively.
Solution: HttpClients should explicitly define the number of connections per route. If only one route is
used, make the max number of connections equal to conn per route.
Solution:
1. use setConnectionManager and call setMaxTotal and setDefaultMaxPerRoute on that connection manager, or
2. use no ConnectionManager, call setMaxConnTotal and setMaxConnPerRoute on the client directly (v4 only).
(jpinpoint-rules)
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="xpath">
<value><![CDATA[
(: check if Apache HttpClient v4 or v5 imports exist to avoid name clashes :)
//ImportHeader[
(.//T-Identifier[@Text='org'] and .//T-Identifier[@Text='apache'] and .//T-Identifier[@Text='http'])
or
(.//T-Identifier[@Text='org'] and .//T-Identifier[@Text='apache'] and .//T-Identifier[@Text='hc'] and .//T-Identifier[@Text='client5'])
][1]/ancestor::KotlinFile
//PostfixUnarySuffix//SimpleIdentifier/T-Identifier[
@Text='custom' and ancestor::PostfixUnaryExpression/PrimaryExpression/SimpleIdentifier/T-Identifier/@Text='HttpClients'
][
ancestor::FunctionDeclaration[
not(.//SimpleIdentifier/T-Identifier[@Text='setConnectionManager'] or
(.//SimpleIdentifier/T-Identifier[@Text='setMaxConnTotal'] and .//SimpleIdentifier/T-Identifier[@Text='setMaxConnPerRoute'])
)
]
]
|
//ImportHeader[
(.//T-Identifier[@Text='org'] and .//T-Identifier[@Text='apache'] and .//T-Identifier[@Text='http'])
or
(.//T-Identifier[@Text='org'] and .//T-Identifier[@Text='apache'] and .//T-Identifier[@Text='hc'] and .//T-Identifier[@Text='client5'])
][1]/ancestor::KotlinFile
//PostfixUnarySuffix//SimpleIdentifier/T-Identifier[
@Text='create' and ancestor::PostfixUnaryExpression/PrimaryExpression/SimpleIdentifier/T-Identifier[@Text='HttpClientBuilder' or @Text='HttpAsyncClientBuilder']
][
ancestor::FunctionDeclaration[
not(.//SimpleIdentifier/T-Identifier[@Text='setConnectionManager'] or
(.//SimpleIdentifier/T-Identifier[@Text='setMaxConnTotal'] and .//SimpleIdentifier/T-Identifier[@Text='setMaxConnPerRoute'])
)
]
]
|
//ImportHeader[
(.//T-Identifier[@Text='org'] and .//T-Identifier[@Text='apache'] and .//T-Identifier[@Text='http'])
or
(.//T-Identifier[@Text='org'] and .//T-Identifier[@Text='apache'] and .//T-Identifier[@Text='hc'] and .//T-Identifier[@Text='client5'])
][1]/ancestor::KotlinFile
//FunctionDeclaration//TypeReference//SimpleIdentifier/T-Identifier[@Text='PoolingHttpClientConnectionManager' or @Text='PoolingAsyncClientConnectionManager']
[
ancestor::FunctionDeclaration[
not(
(.//SimpleIdentifier/T-Identifier[@Text='setMaxTotal'] and .//SimpleIdentifier/T-Identifier[@Text='setDefaultMaxPerRoute'])
or (
(.//SimpleIdentifier/T-Identifier[@Text='setMaxConnTotal'] and .//SimpleIdentifier/T-Identifier[@Text='setMaxConnPerRoute'])
and .//SimpleIdentifier/T-Identifier[@Text='PoolingHttpClientConnectionManagerBuilder']
)
)
and not(
ancestor::ClassBody//FunctionDeclaration[
(.//SimpleIdentifier/T-Identifier[@Text='setMaxTotal'] and .//SimpleIdentifier/T-Identifier[@Text='setDefaultMaxPerRoute'])
or (
(.//SimpleIdentifier/T-Identifier[@Text='setMaxConnTotal'] and .//SimpleIdentifier/T-Identifier[@Text='setMaxConnPerRoute'])
and .//SimpleIdentifier/T-Identifier[@Text='PoolingHttpClientConnectionManagerBuilder']
)
]
)
]
]
]]></value>
</property>
</properties>
<example><![CDATA[
fun bad(conMgr: Any?): HttpClient =
HttpClientBuilder.create() // bad, missing setMaxConnPerRoute/setMaxConnTotal or setConnectionManager
.build()
fun goodWithMgr(conMgr: Any?): HttpClient =
HttpClientBuilder.create()
.setConnectionManager(conMgr) // good, delegated to manager
.build()
fun goodWithSizes(): HttpClient =
HttpClients.custom()
.setMaxConnPerRoute(MAX_CONNECTIONS)
.setMaxConnTotal(MAX_CONNECTIONS)
.build()
]]></example>
</rule>
<rule name="HttpClientBuilderWithoutTimeouts"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
language="kotlin"
message="Apache HttpClient builder is used and not all three timeouts are configured."
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#IBI10">
<description>Problem: for connectionRequestTimeout, connectTimeout, socketTimeout (using
HttpComponentsClientHttpRequestFactory/RequestConfig) or readTimeout/responseTimeout (using RequestConfig v4/v5) and connectTimeout (using ConnectionConfig v5)
the default timeout settings are not optimal in most cases.
Solution: Set the timeouts explicitly to proper reasoned values. See best practice values via the link. Use
the setDefaultRequestConfig with a method with a RequestConfig object on HttpClient builders to set the
timeouts. (jpinpoint-rules)
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tags" value="io,jpinpoint-rule,performance,pitfall,resilience" type="String" description="classification"/>
<property name="xpath">
<value><![CDATA[
(: v4/v5 builders without setDefaultRequestConfig :)
//PostfixUnarySuffix//SimpleIdentifier/T-Identifier[@Text="create"
and ancestor::PostfixUnaryExpression/PrimaryExpression/SimpleIdentifier/T-Identifier/@Text="HttpClientBuilder"
and not(ancestor::PostfixUnaryExpression/PostfixUnarySuffix/NavigationSuffix/SimpleIdentifier/T-Identifier/@Text="setDefaultRequestConfig")]
,
//PostfixUnarySuffix//SimpleIdentifier/T-Identifier[@Text="create"
and ancestor::PostfixUnaryExpression/PrimaryExpression/SimpleIdentifier/T-Identifier/@Text="HttpAsyncClientBuilder"
and not(ancestor::PostfixUnaryExpression/PostfixUnarySuffix/NavigationSuffix/SimpleIdentifier/T-Identifier/@Text="setDefaultRequestConfig")]
,
//PostfixUnarySuffix//SimpleIdentifier/T-Identifier[@Text="custom"
and ancestor::PostfixUnaryExpression/PrimaryExpression/SimpleIdentifier/T-Identifier/@Text="HttpClients"
and not(ancestor::PostfixUnaryExpression/PostfixUnarySuffix/NavigationSuffix/SimpleIdentifier/T-Identifier/@Text="setDefaultRequestConfig")]
,
(: v4 RequestConfig missing at least one of the three timeouts:)
//ImportHeader[.//T-Identifier[@Text='org'] and .//T-Identifier[@Text='apache'] and .//T-Identifier[@Text='http'] and .//T-Identifier[@Text='client'] and .//T-Identifier[@Text='config'] and .//T-Identifier[@Text='RequestConfig']][1]/ancestor::KotlinFile
//PostfixUnarySuffix//SimpleIdentifier/T-Identifier[
@Text="custom"
and ancestor::PostfixUnaryExpression/PrimaryExpression/SimpleIdentifier/T-Identifier/@Text="RequestConfig"
and not(
count(ancestor::PostfixUnaryExpression/PostfixUnarySuffix/NavigationSuffix/SimpleIdentifier/T-Identifier[@Text=('setConnectionRequestTimeout','setConnectTimeout','setSocketTimeout')]/@Text) = 3
)
]
,
(: v5 RequestConfig missing at least one of the two timeouts:)
//ImportHeader[.//T-Identifier[@Text='org'] and .//T-Identifier[@Text='apache'] and .//T-Identifier[@Text='hc'] and .//T-Identifier[@Text='client5'] and .//T-Identifier[@Text='http'] and .//T-Identifier[@Text='config'] and .//T-Identifier[@Text='RequestConfig']][1]/ancestor::KotlinFile
//PostfixUnarySuffix//SimpleIdentifier/T-Identifier[
@Text="custom"
and ancestor::PostfixUnaryExpression/PrimaryExpression/SimpleIdentifier/T-Identifier/@Text="RequestConfig"
and not(
ancestor::PostfixUnaryExpression/PostfixUnarySuffix/NavigationSuffix/SimpleIdentifier/T-Identifier/@Text="setConnectionRequestTimeout"
and ancestor::PostfixUnaryExpression/PostfixUnarySuffix/NavigationSuffix/SimpleIdentifier/T-Identifier/@Text="setResponseTimeout"
)
]
,
(: Spring HttpComponentsClientHttpRequestFactory missing full timeout configuration in a function :)
//SimpleIdentifier/T-Identifier[@Text='HttpComponentsClientHttpRequestFactory'
and ancestor::FunctionDeclaration[
count(.//SimpleIdentifier/T-Identifier[@Text=('setConnectTimeout', 'setConnectionRequestTimeout', 'setReadTimeout')]) < 3
]
]
]]>
</value>
</property>
</properties>
<example><![CDATA[
class BadHttpClientV5 {
public HttpClient createClient() {
RequestConfig requestConfig = RequestConfig.custom()
.setResponseTimeout(Timeout.ofMilliseconds(1200))
.build();
return HttpClients.custom()
.build();
}
}
class GoodHttpClientV5 {
public CloseableHttpClient createHttpClient() {
ConnectionConfig connectionConfig = ConnectionConfig.custom()
.setConnectTimeout(Timeout.ofMilliseconds(300))
.build();
PoolingHttpClientConnectionManager connectionManager =
PoolingHttpClientConnectionManagerBuilder.create()
.setDefaultConnectionConfig(connectionConfig)
.build();
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(Timeout.ofMilliseconds(100))
.setResponseTimeout(Timeout.ofMilliseconds(1200))
.build();
return HttpClients.custom() // good, all expected overrides for timeouts
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(connectionManager)
.build();
}
}
]]>
</example>
</rule>
<rule name="NettyConnectionProviderWithoutMaxOrTimeout"
message="Netty ConnectionProvider has no defined maxConnections or pendingAcquireTimeout."
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
language="kotlin"
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#ibi26">
<description>Problem: If a Reactor Netty Connection Provider is built without an explicit `maxConnections`, this defaults to `max(#CPU, 8) * 2`.