/
common.xml
2143 lines (2033 loc) · 110 KB
/
common.xml
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-common-rules" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd" xmlns="http://pmd.sourceforge.net/ruleset/2.0.0">
<description>jPinpoint rule set for performance aware Java coding, sponsored by Rabobank.</description>
<rule name="AvoidCDIReferenceLeak"
language="java"
message="Explicit CDI references need to be destroyed otherwise they leak."
class="net.sourceforge.pmd.lang.rule.XPathRule"
typeResolution="true"
externalInfoUrl="${doc_root}/JavaCodePerformance.md#pml05">
<description>Problem: A proxy object is created by Contexts and Dependency Injection (CDI) for explicit references, they are not de-referenced implicitly and become a memory leak.
Solution: Destroy the reference explicitly.
</description>
<priority>1</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="version" value="2.0"/>
<property name="xpath">
<value><![CDATA[
//Expression/PrimaryExpression/PrimaryPrefix/Name[@Image='CDI.current']/../../
PrimarySuffix[@Image = 'select'
and not
(ancestor::MethodDeclaration//TryStatement/FinallyStatement//PrimaryExpression[
PrimaryPrefix/Name/@Image='CDI.current'][PrimarySuffix/@Image = 'destroy']
[PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix/Name/@Image =
ancestor::MethodDeclaration//Expression/PrimaryExpression/PrimaryPrefix/Name[@Image='CDI.current']/../../
PrimarySuffix[@Image = 'select']/ancestor::StatementExpression/PrimaryExpression/PrimaryPrefix/Name/@Image
])
and not
(ancestor::MethodDeclaration//TryStatement/FinallyStatement//PrimaryExpression[
PrimaryPrefix/Name/@Image='CDI.current'][PrimarySuffix/@Image = 'destroy']
[PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix/Name/@Image =
ancestor::MethodDeclaration//VariableInitializer/Expression/PrimaryExpression/PrimaryPrefix/Name[@Image='CDI.current']/../../
PrimarySuffix[@Image = 'select']/ancestor::VariableDeclarator/VariableDeclaratorId/@Name
])]
]]></value>
</property>
</properties>
<example>
<![CDATA[
public class CDIStuff {
private void bad() {
MyClass o = CDI.current().select(MyClass.class).get();
o.doStuff();
// bad - missing destroy in finally
}
private void good() {
MyClass o = CDI.current().select(MyClass.class).get();
try {
o.doStuff();
} finally {
CDI.current().destroy(o); // good - destroy properly
}
}
}
]]>
</example>
</rule>
<rule name="AvoidConstantsInInterface" class="net.sourceforge.pmd.lang.rule.XPathRule" dfa="false" language="java" message="Interface defines constants. It may expose implementation details." typeResolution="true"
externalInfoUrl="${doc_root}/JavaCodePerformance.md#voedos04">
<description>Interface defines constants. Problem: Possibly exposes implementation details.
Solution: Make it a Class which cannot be instantiated, or an Enum. Use static imports.
(jpinpoint-rules)</description>
<priority>3</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="version" value="2.0"/>
<property name="xpath">
<value><![CDATA[
//ClassOrInterfaceDeclaration[@Interface=true()]/ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/FieldDeclaration
]]></value>
</property>
</properties>
<example>
<![CDATA[
public interface Foo {
static final Object CONST = new Object(); //bad
}
]]>
</example>
</rule>
<rule name="AvoidDecimalAndChoiceFormatAsField" class="net.sourceforge.pmd.lang.rule.XPathRule"
dfa="false" language="java"
message="Avoid using DecimalFormat or ChoiceFormat as field since it is thread-unsafe."
typeResolution="true"
externalInfoUrl="${doc_root}/JavaCodePerformance.md#idtf01">
<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)
</description>
<priority>1</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="version" value="2.0"/>
<property name="xpath">
<value><![CDATA[
//FieldDeclaration/VariableDeclarator/VariableInitializer/Expression[pmd-java:typeIs('java.text.DecimalFormat') or pmd-java:typeIs('java.text.ChoiceFormat')]
]]></value>
</property>
</properties>
</rule>
<rule name="AvoidDuplicateAssignmentsInCases"
message="Avoid duplicate assignments in different switch cases"
class="net.sourceforge.pmd.lang.rule.XPathRule" dfa="false" language="java"
typeResolution="true" externalInfoUrl="${doc_root}/JavaCodeQuality.md#SSC01">
<description>
Problem: Potential bug: expected are different assignments in different cases.
Solution: assign different values in different cases, common assignments should be taken out of the switch.
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="version" value="2.0"/>
<property name="xpath">
<value>
<![CDATA[
//SwitchStatement/BlockStatement[
(.//AssignmentOperator/../../..//StatementExpression[not(pmd-java:typeIs('boolean'))]/Expression/PrimaryExpression/PrimaryPrefix/Name/@Image
=preceding-sibling::SwitchLabel/preceding-sibling::BlockStatement//AssignmentOperator/../../..//StatementExpression/Expression/PrimaryExpression/PrimaryPrefix/Name/@Image
or
.//AssignmentOperator/../../..//StatementExpression[not(pmd-java:typeIs('boolean'))]/Expression/PrimaryExpression/PrimaryPrefix//Literal/@Image
=preceding-sibling::SwitchLabel/preceding-sibling::BlockStatement//AssignmentOperator/../../..//StatementExpression/Expression/PrimaryExpression/PrimaryPrefix//Literal/@Image)
and
.//AssignmentOperator/../../..//StatementExpression[not(pmd-java:typeIs('boolean'))]/PrimaryExpression/PrimaryPrefix/Name/@Image
=preceding-sibling::SwitchLabel/preceding-sibling::BlockStatement//AssignmentOperator/../../..//StatementExpression/PrimaryExpression/PrimaryPrefix/Name/@Image
and
not(.//AssignmentOperator/../../..//StatementExpression[not(pmd-java:typeIs('boolean'))]/Expression/PrimaryExpression/PrimarySuffix/Arguments/@Size > 0
or preceding-sibling::SwitchLabel[@Default=true()])
]
]]>
</value>
</property>
</properties>
</rule>
<rule name="AvoidImplicitlyRecompilingRegex" class="net.sourceforge.pmd.lang.rule.XPathRule" dfa="false" language="java" message="String regex method, Pattern.matches or FileSystem.getPathMatcher is used.
Implicitly compiles a regex pattern, can be expensive." typeResolution="true"
externalInfoUrl="${doc_root}/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="version" value="2.0"/>
<property name="xpath">
<value><![CDATA[
(//MethodDeclaration//(PrimaryPrefix/Name[ends-with(@Image, '.replaceAll') or ends-with(@Image, '.replaceFirst') or @Image='Pattern.matches']
|PrimarySuffix[@Image = 'replaceAll' or ends-with(@Image, '.replaceFirst')])
/following::PrimarySuffix[1]/Arguments[ArgumentList/@Size=2]//Expression[1]//PrimaryPrefix[
Literal[string-length(@Image) > 5 and
(matches(@Image, '[\.\$\|\(\)\[\]\{\}\^\?\*\+\\]+'))] or Name
and not(../PrimarySuffix)
and not (
Name/@Image=ancestor::MethodDeclaration//VariableDeclaratorId/@Name)
and not (
Name[@Image=ancestor::ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/FieldDeclaration/VariableDeclarator[
VariableInitializer/Expression/PrimaryExpression/PrimaryPrefix/Literal[string-length(@Image) < 6 or not
(matches(@Image, '[\.\$\|\(\)\[\]\{\}\^\?\*\+\\]+'))]
]/VariableDeclaratorId/@Name])
]
,
//MethodDeclaration//PrimaryPrefix/Name[ends-with(@Image, '.split') or ends-with(@Image, 'getPathMatcher')]/../../PrimarySuffix/Arguments[ArgumentList/@Size=1]//Expression[1]//PrimaryPrefix[
Literal[string-length(@Image) > 5 and
matches(@Image, '[\.\$\|\(\)\[\]\{\}\^\?\*\+\\]+')] or Name
and not(../PrimarySuffix)
and not (
Name/@Image=ancestor::MethodDeclaration//VariableDeclaratorId/@Name)
and not (
(:--- not (if foreign field (with .), or field with short String or without regex char) ---:)
Name[contains(@Image, '.') or @Image=ancestor::ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/FieldDeclaration/VariableDeclarator[
VariableInitializer/Expression/PrimaryExpression/PrimaryPrefix/Literal[string-length(@Image) < 6 or not
(matches(@Image, '[\.\$\|\(\)\[\]\{\}\^\?\*\+\\]+'))]
]/VariableDeclaratorId/@Name])
]
,
//MethodDeclaration//PrimarySuffix[@Image='getPathMatcher']/../PrimarySuffix/Arguments[ArgumentList/@Size=1]/ArgumentList/Expression[1]/PrimaryExpression/PrimaryPrefix[
Literal[string-length(@Image) > 5] or Name
and not(../PrimarySuffix)
and not (
Name/@Image=ancestor::MethodDeclaration//VariableDeclaratorId/@Name)
and not (
Name[@Image=ancestor::ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/FieldDeclaration/VariableDeclarator[
VariableInitializer/Expression/PrimaryExpression/PrimaryPrefix/Literal[string-length(@Image) < 6]]/VariableDeclaratorId/@Name])
]
,
(: --- String.matches called on formalparams, locals and fields --- :)
//MethodDeclaration//PrimaryPrefix/Name[ends-with(@Image, '.matches')]
[
(exists(index-of((ancestor::MethodDeclaration//FormalParameter[pmd-java:typeIs('java.lang.String')]/VariableDeclaratorId/@Name), substring-before(@Image,'.')))
or
exists(index-of((ancestor::MethodDeclaration//LocalVariableDeclaration/Type[pmd-java:typeIs('java.lang.String')]/../VariableDeclarator/VariableDeclaratorId/@Name), substring-before(@Image,'.')))
or
exists(index-of((ancestor::ClassOrInterfaceBody//FieldDeclaration[pmd-java:typeIs('java.lang.String')]/VariableDeclarator/VariableDeclaratorId/@Name), substring-before(@Image,'.'))))
and
(: for matches param is >5 literal or something named :)
../../PrimarySuffix/Arguments[ArgumentList/@Size=1]//Expression[1]//PrimaryPrefix[
Literal[string-length(@Image) > 5] or Name
(: exclude method calls :)
and not(../PrimarySuffix)
(: exclude for param is method arg or local :)
and not (
Name/@Image=ancestor::MethodDeclaration//VariableDeclaratorId/@Name)
(: exclude for param is short fields :)
and not (
Name[@Image=ancestor::ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/FieldDeclaration/VariableDeclarator[
VariableInitializer/Expression/PrimaryExpression/PrimaryPrefix/Literal[string-length(@Image) < 6]
]/VariableDeclaratorId/@Name])
]])
]]></value>
</property>
</properties>
</rule>
<rule name="AvoidInMemoryStreamingDefaultConstructor" class="net.sourceforge.pmd.lang.rule.XPathRule" dfa="false" language="java"
message="The default capacity or smaller is used for ByteArrayOutputStream or StringWriter, it usually needs expensive expansions." typeResolution="true"
externalInfoUrl="${doc_root}/JavaCodePerformance.md#isio01">
<description>Problem: The default constructor of ByteArrayOutputStream creates a 32 bytes initial capacity and for StringWriter 16 chars. Problem: Such a small buffer as capacity usually needs several expensive expansions.
Solution: Presize 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)</description>
<priority>2</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="version" value="2.0"/>
<property name="xpath">
<value><![CDATA[
//PrimaryExpression/PrimaryPrefix/AllocationExpression/ClassOrInterfaceType[pmd-java:typeIs('java.io.ByteArrayOutputStream') or pmd-java:typeIs('java.io.StringWriter')]
[not(../Arguments/ArgumentList)
or
(pmd-java:typeIs('java.io.ByteArrayOutputStream') and (../Arguments//Literal[number(@Image) <= 32] or ../Arguments//Name[@Image = ancestor::ClassOrInterfaceDeclaration//FieldDeclaration//VariableDeclaratorId[number(..//Literal/@Name) <= 32]/@Image]))
or
(pmd-java:typeIs('java.io.StringWriter') and (../Arguments//Literal[number(@Image) <= 16] or ../Arguments//Name[@Image = ancestor::ClassOrInterfaceDeclaration//FieldDeclaration//VariableDeclaratorId[number(..//Literal/@Image) <= 16]/@Name]))
]/..
]]></value>
</property>
</properties>
<example>
<![CDATA[
class Bad {
public static void bad() {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); //bad
StringWriter sw = new StringWriter(); //bad
baos = new ByteArrayOutputStream(32); //bad - not larger than default
}
}
class Good {
public static void good() {
ByteArrayOutputStream baos = new ByteArrayOutputStream(8192); // 8 kiB
StringWriter sw = new StringWriter(2048);
}
}
]]>
</example>
</rule>
<rule name="AvoidMultipleConcatStatements" class="net.sourceforge.pmd.lang.rule.XPathRule" dfa="false" language="java" message="Multiple statements concatenate to the same String. Use StringBuilder append." typeResolution="true"
externalInfoUrl="${doc_root}/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="version" value="2.0"/>
<property name="xpath">
<value><![CDATA[
//MethodDeclaration/Block[
count(
./BlockStatement/Statement//StatementExpression/PrimaryExpression/PrimaryPrefix/Name
[@Image=./../../../../../../../../../../../..//VariableDeclaratorId/@Name
and
./../../../../../../..//VariableDeclaratorId/../../Type/ReferenceType/ClassOrInterfaceType[pmd-java:typeIs('java.lang.String')]
]
/../../../AssignmentOperator[@Image='+=']/
../Expression//PrimaryExpression/PrimaryPrefix/Name) > 1]/BlockStatement[position()=last()]
|
//MethodDeclaration/Block[
count(
./BlockStatement/Statement//StatementExpression[
./PrimaryExpression/PrimaryPrefix/Name[
@Image = ../../../Expression/AdditiveExpression/PrimaryExpression/PrimaryPrefix/Name/@Image
and
@Image = ./../../../../../../../..//VariableDeclaratorId/../../Type/ReferenceType/ClassOrInterfaceType[pmd-java:typeIs('java.lang.String')]/../../../VariableDeclarator/VariableDeclaratorId/@Name
]
]) > 1 ]//BlockStatement[position()=last()]//StatementExpression/Expression/AdditiveExpression[@Operator = '+']
]]></value>
</property>
</properties>
</rule>
<rule name="AvoidRecompilingPatterns" class="net.sourceforge.pmd.lang.rule.XPathRule" dfa="false" language="java" message="Pattern.compile is used in a method. Compiling a regex pattern can be expensive, make it a static final field." typeResolution="true"
externalInfoUrl="${doc_root}/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 static 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="version" value="2.0"/>
<property name="xpath">
<value><![CDATA[
//TypeDeclaration/ClassOrInterfaceDeclaration/ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/MethodDeclaration
//PrimaryExpression/PrimaryPrefix/Name[pmd-java:typeIs('java.util.regex.Pattern') and ends-with(@Image, '.compile') and
count(../../PrimarySuffix[1]/Arguments/ArgumentList/Expression//PrimaryExpression) = 1
and not (
../../PrimarySuffix[1]/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix/Name/@Image=
ancestor::MethodDeclaration/MethodDeclarator/FormalParameters/FormalParameter/VariableDeclaratorId/@Name)]
]]></value>
</property>
</properties>
<example>
<![CDATA[
class Bad {
public static final String STR_PAT1 = "[A-Z][a-z]+";
public static void bad() {
Pattern p1 = Pattern.compile(STR_PAT1); // bad
Pattern p2 = Pattern.compile("(?=\\p{Lu})"); // bad
boolean b = p1.matcher("Start ").matches();
}
}
class Good {
public static final Pattern PAT1 = Pattern.compile("[A-Z][a-z]+");
public static final Pattern PAT2 = Pattern.compile("(?=\\p{Lu})");
public static void good() {
boolean b = PAT1.matcher("Start ").matches();
}
}
]]>
</example>
</rule>
<rule name="AvoidRecompilingXPathExpression" class="net.sourceforge.pmd.lang.rule.XPathRule" dfa="false" language="java" message="XPathExpression is created and compiled every time. Beware it is thread-unsafe." typeResolution="true"
externalInfoUrl="${doc_root}/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="version" value="2.0"/>
<property name="xpath">
<value><![CDATA[
//TypeDeclaration//ClassOrInterfaceBodyDeclaration/MethodDeclaration
//PrimaryExpression/(PrimarySuffix|PrimaryPrefix/Name)[ends-with(@Image,'newXPath')]
/ancestor::MethodDeclaration
//PrimaryExpression/(PrimarySuffix|PrimaryPrefix/Name)[ends-with(@Image, 'compile')
or (pmd-java:typeIs('javax.xml.xpath.XPath') and ends-with(@Image, 'evaluate'))]
]]></value>
</property>
</properties>
<example>
<![CDATA[
class Bad {
public static NodeList bad1(Document doc) {
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("//book[author='Isaac Asimov']/title/text()"); // bad
return (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
}
public static NodeList bad2(Document doc) throws XPathExpressionException {
XPath xpath = XPathFactory.newInstance().newXPath();
String xPathQuery = "//book[author='Isaac Asimov']/title/text()";
return (NodeList) xpath.evaluate(xPathQuery, doc, XPathConstants.NODESET); // bad
}
}
class Good {
private static final ThreadLocal<XPathFactory> tlFac = ThreadLocal.withInitial(XPathFactory::newInstance);
private static final ThreadLocal<XPathExpression> tlExpr;
static {
XPath xpath = tlFac.get().newXPath();
XPathExpression expr = xpath.compile("//book[author='Isaac Asimov']/title/text()"); // good
tlExpr = ThreadLocal.withInitial(expr); // good
}
public static NodeList good(Document doc) {
return tlExpr.get().evaluate(doc, XPathConstants.NODESET); // good
}
}
]]>
</example>
</rule>
<rule name="AvoidRecreatingDateTimeFormatter"
message="Avoid recreating DateTimeFormatter, it is relatively expensive."
class="net.sourceforge.pmd.lang.rule.XPathRule" dfa="false" language="java"
typeResolution="true" externalInfoUrl="${doc_root}/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 static final field.
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="version" value="2.0"/>
<property name="xpath">
<value>
<![CDATA[
//FieldDeclaration[@Final=false()]//ReferenceType/ClassOrInterfaceType[pmd-java:typeIs('org.joda.time.format.DateTimeFormatter') or pmd-java:typeIs('org.threeten.bp.format.DateTimeFormatter') or pmd-java:typeIs('java.time.format.DateTimeFormatter')],
//FieldDeclaration[@Final=true() and @Static=false()]//ReferenceType/ClassOrInterfaceType[pmd-java:typeIs('org.joda.time.format.DateTimeFormatter') or pmd-java:typeIs('org.threeten.bp.format.DateTimeFormatter') or pmd-java:typeIs('java.time.format.DateTimeFormatter')](: has assignment, otherwise check in constructor :)[ancestor::ClassOrInterfaceBodyDeclaration//VariableInitializer],
//ConstructorDeclaration/BlockStatement//Expression/PrimaryExpression/PrimaryPrefix/Name[ends-with(@Image, 'DateTimeFormat.forPattern')]
(: check if parameter is argument of constructor call :)[not(ancestor::BlockStatement//Expression/PrimaryExpression/PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix/Name/@Image=ancestor::ConstructorDeclaration//PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix/Name/@Image)],
//MethodDeclaration/Block/BlockStatement//Expression//AllocationExpression/ClassOrInterfaceType[pmd-java:typeIs('org.joda.time.format.DateTimeFormatter') or pmd-java:typeIs('org.threeten.bp.format.DateTimeFormatter') or pmd-java:typeIs('java.time.format.DateTimeFormatter')],
//MethodDeclaration/Block/BlockStatement//VariableInitializer/Expression/PrimaryExpression/PrimaryPrefix/Name[ends-with(@Image, 'DateTimeFormatter.ofPattern')]
(: check if parameter is argument of method call :)[not(ancestor::LocalVariableDeclaration//PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix/Name/@Image=
ancestor::MethodDeclaration/MethodDeclarator/FormalParameters/FormalParameter/VariableDeclaratorId/@Name)],
//MethodDeclaration/Block/BlockStatement//Expression/PrimaryExpression/PrimaryPrefix/Name[contains(@Image, 'ISODateTimeFormat.')],
//MethodDeclaration/Block/BlockStatement//Expression/PrimaryExpression/PrimaryPrefix/Name[contains(@Image, 'DateTimeFormat.fullDateTime')],
//MethodDeclaration/Block/BlockStatement//Expression/PrimaryExpression/PrimaryPrefix/Name[ends-with(@Image, 'DateTimeFormat.forPattern')]
(: check if parameter is argument of method call :)[not(ancestor::LocalVariableDeclaration//PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix/Name/@Image=
ancestor::MethodDeclaration/MethodDeclarator/FormalParameters/FormalParameter/VariableDeclaratorId/@Name)],
//MethodDeclaration/Block/BlockStatement//Expression//AllocationExpression/ClassOrInterfaceType[pmd-java:typeIs('org.joda.time.format.DateTimeFormatterBuilder')][ancestor::PrimaryExpression/PrimarySuffix[@Image="toFormatter"]]
]]>
</value>
</property>
</properties>
</rule>
<rule name="AvoidReflectionInToStringAndHashCode" class="net.sourceforge.pmd.lang.rule.XPathRule" dfa="false" language="java" message="Reflection is used in toString or hashCode, which is expensive." typeResolution="true"
externalInfoUrl="${doc_root}/JavaCodePerformance.md#uuor01">
<description>Problem: Reflection is relatively expensive.
Solution: Avoid to use reflection. Use the non-reflective, explicit way, like generation by IDE or Lombok.
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="version" value="2.0"/>
<property name="xpath">
<value><![CDATA[
//PrimaryPrefix/AllocationExpression/ClassOrInterfaceType
[
pmd-java:typeIs('org.apache.commons.lang.builder.EqualsBuilder')
or pmd-java:typeIs('org.apache.commons.lang.builder.HashCodeBuilder')
]
[../../../PrimarySuffix[1]
[
@Image='reflectionEquals'
or @Image='reflectionHashCode'
]
] |
//PrimaryPrefix/Name
[
@Image='EqualsBuilder.reflectionEquals'
or @Image='HashCodeBuilder.reflectionHashCode'
]
]]></value>
</property>
</properties>
</rule>
<rule name="AvoidSimpleDateFormat" class="net.sourceforge.pmd.lang.rule.XPathRule" dfa="false" language="java" message="SimpleDateFormat is used. Since it is thread-unsafe, it needs expensive recreation." typeResolution="true"
externalInfoUrl="${doc_root}/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="version" value="2.0"/>
<property name="xpath">
<value><![CDATA[
//AllocationExpression/ClassOrInterfaceType[
pmd-java:typeIs('java.text.SimpleDateFormat')
and not (ancestor::ClassOrInterfaceBodyDeclaration//PrimaryPrefix/Name[
ends-with(@Image, 'setDateFormat')
and ( pmd-java:typeIs('com.fasterxml.jackson.databind.ObjectMapper')
or pmd-java:typeIs('com.fasterxml.jackson.dataformat.xml.XmlMapper'))
])
]
]]></value>
</property>
</properties>
</rule>
<rule name="AvoidStringBuffer" class="net.sourceforge.pmd.lang.rule.XPathRule" dfa="false" language="java" message="StringBuffer is used. It introduces locking overhead, use StringBuilder." typeResolution="true"
externalInfoUrl="${doc_root}/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="version" value="2.0"/>
<property name="xpath">
<value><![CDATA[
//VariableDeclarator[../Type/ReferenceType/ClassOrInterfaceType[pmd-java:typeIs('java.lang.StringBuffer')]]
]]></value>
</property>
</properties>
</rule>
<rule name="AvoidUnconditionalBuiltLogStrings" class="net.sourceforge.pmd.lang.rule.XPathRule" dfa="false" language="java" message="Log String is built irrespective of log level." typeResolution="true"
externalInfoUrl="${doc_root}/JavaCodePerformance.md#il02">
<description>A String to be logged is built unconditionally. Problem: String building, concatenation and/or other operations happen before the debug, trace or info method executes, so independent of the need to actually log. Concatenation is relatively expensive.
Solution: Build the String conditionally on the log level, within an if statement.
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="version" value="2.0"/>
<property name="xpath">
<value><![CDATA[
//MethodDeclaration/Block/BlockStatement/Statement//StatementExpression/PrimaryExpression/PrimaryPrefix/Name[
(substring-before(@Image, '.') =
ancestor::MethodDeclaration//BlockStatement/Statement/StatementExpression/PrimaryExpression/PrimaryPrefix/Name[ends-with
(@Image, '.debug') or ends-with(@Image, '.trace') or ends-with(@Image, '.info')]
/../../PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix/Name/attribute::Image
and
substring-after(@Image, '.') = 'append')
and count(ancestor::IfStatement) = 0
and
count(ancestor::MethodDeclaration/Block/BlockStatement/Statement//PrimaryExpression/PrimaryPrefix/Name[
(substring-before(@Image, '.') =
ancestor::MethodDeclaration//BlockStatement/Statement//PrimaryExpression/PrimaryPrefix/Name[ends-with
(@Image, '.debug') or ends-with(@Image, '.trace') or ends-with(@Image, '.info')]
/../../PrimarySuffix/Arguments/ArgumentList//PrimaryExpression/PrimaryPrefix/Name/attribute::Image
and
substring-after(@Image, '.') != 'append')]) = 0
]
]]></value>
</property>
</properties>
</rule>
<rule name="AvoidWideScopeXPathExpression" class="net.sourceforge.pmd.lang.rule.XPathRule" dfa="false" language="java" message="XPathExpression targets a wide scope, this is potentially slow." typeResolution="true"
externalInfoUrl="${doc_root}/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="version" value="2.0"/>
<property name="xpath">
<value><![CDATA[
//TypeDeclaration/ClassOrInterfaceDeclaration/ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/MethodDeclaration
//PrimaryExpression/PrimarySuffix[
Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix/
Literal[starts-with(@Image, '"//')]
and
../PrimaryPrefix/Name[ends-with(@Image, '.compile')]
]
]]></value>
</property>
</properties>
</rule>
<rule name="AvoidXPathAPIUsage" class="net.sourceforge.pmd.lang.rule.XPathRule" dfa="false" language="java" message="XPathAPI is used. XPathAPI implementation has bad performance." typeResolution="true"
externalInfoUrl="${doc_root}/JavaCodePerformance.md#ux03">
<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>3</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="version" value="2.0"/>
<property name="xpath">
<value><![CDATA[
//TypeDeclaration/ClassOrInterfaceDeclaration/ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration
//PrimaryExpression/PrimaryPrefix/Name[starts-with(@Image, 'XPathAPI.')]
]]></value>
</property>
</properties>
</rule>
<rule name="AvoidXPathUsage" class="net.sourceforge.pmd.lang.rule.XPathRule" dfa="false" language="java" message="XPath is used. XPath implementation has bad performance." typeResolution="true"
externalInfoUrl="${doc_root}/JavaCodePerformance.md#ux03">
<description>XPath is used. Problem: XPath implementation is slow.
Solution: 1. avoid using XPath. 2. improve performance by using jvm parameters and possibly Cached XPath API.
(jpinpoint-rules)</description>
<priority>3</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="version" value="2.0"/>
<property name="xpath">
<value><![CDATA[
//TypeDeclaration/ClassOrInterfaceDeclaration/ClassOrInterfaceBody/
ClassOrInterfaceBodyDeclaration
//PrimaryExpression/PrimaryPrefix/Name[@Image='XPathFactory.newInstance']
[not (ancestor::FieldDeclaration//ClassOrInterfaceType/@Image = 'ThreadLocal')]
]]></value>
</property>
</properties>
</rule>
<rule name="ImplementEqualsHashCodeOnValueObjects"
message="Equals and/or hashCode is missing for a value object."
class="net.sourceforge.pmd.lang.rule.XPathRule" dfa="false" language="java"
typeResolution="true" externalInfoUrl="${doc_root}/JavaCodeQuality.md#incorrect-equals-and-hashcode">
<description>
Problem: If equals and hashCode are not defined, they don't meet the programmer's expectations and the requirements for use with the collections API. It may result in unexpected, undesired behavior.
Solution: Add proper equals and hashCode methods that meet the equals-hashCode contract to all objects which might anyhow be put in a Map, Set or other collection. Or use Lombok @EqualsAndHashCode, @Value or @Data. Also holds for inner classes.
If the object should never be checked for equality or used in a collection, also add those methods and let them throw UnsupportedOperationException to fail fast. @Xml... , @Entity, Throwable and Executor objects are ignored because they are assumed to be not used as value objects.
(jpinpoint-rules)</description>
<priority>3</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="version" value="2.0"/>
<property name="xpath">
<value>
<![CDATA[
(:-- top level class - not annotated that would make it a non-value object --:)
//TypeDeclaration[not(./Annotation//Name[@Image='Data' or @Image='Value' or @Image='EqualsAndHashCode'
or @Image='Singleton' or @Image='Component' or @Image='Service' or @Image='Repository' or @Image='Configuration' or @Image='Endpoint' or @Image='RestController' or @Image='ControllerAdvice'
or starts-with(@Image, 'Xml') or @Image='Entity' or @Image='Embeddable' or @Image='MappedSuperclass'])]
/ClassOrInterfaceDeclaration[@Interface=false() and @Abstract=false() and not(pmd-java:typeIs('java.util.concurrent.Executor') or pmd-java:typeIs('java.lang.Throwable'))]
/ClassOrInterfaceBody[ClassOrInterfaceBodyDeclaration/FieldDeclaration[@Static=false()]
[
(not (../Annotation//Name[@Image = 'XmlElement']))
and
(:-- a getter with result type of a field --:)
(
ancestor::ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/MethodDeclaration
[@Public=true() and @Static=false() and starts-with(@Name, 'get') and string-length(@Name) > 3 or starts-with(@Name, 'is') and string-length(@Name) > 2]
[ResultType/Type/ReferenceType/ClassOrInterfaceType/@Image =
ancestor::ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/FieldDeclaration[@Static=false()]/Type/ReferenceType/ClassOrInterfaceType/@Image]
or
ancestor::TypeDeclaration/Annotation//Name[@Image='Getter']
)
(:-- and class has no equals or hashCode method --:)
and (not (ancestor::ClassOrInterfaceBody//MethodDeclaration[@Public=true() and @Static=false() and @Name='equals' or @Name='hashCode']))
(:-- and class has a toString and #fields <= 1+#getters --:)
and
((ancestor::ClassOrInterfaceBody//MethodDeclaration[@Public=true() and @Static=false() and @Name='toString']
and
count(ancestor::ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/FieldDeclaration[@Static=false()]) <=
(1 + count(ancestor::ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/MethodDeclaration
[@Public=true() and @Static=false() and starts-with(@Name, 'get') and string-length(@Name) > 3 or starts-with(@Name, 'is') and string-length(@Name) > 2]))
)
or
ancestor::ClassOrInterfaceDeclaration[ends-with(@SimpleName, 'Dto')]
or
(:-- #fields == #getters --:)
count(ancestor::ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/FieldDeclaration[@Static=false()]) =
count(ancestor::ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/MethodDeclaration
[@Public=true() and @Static=false() and starts-with(@Name, 'get') and string-length(@Name) > 3 or starts-with(@Name, 'is') and string-length(@Name) > 2])
or
ancestor::TypeDeclaration/Annotation//Name[@Image='Getter']
)]
]/.. (:--up to class --:)
(:-- inner classes --:)
,
//ClassOrInterfaceBodyDeclaration[not(./Annotation//Name[@Image='Data' or @Image='Value' or @Image='EqualsAndHashCode'])]
/ClassOrInterfaceDeclaration[@Interface=false() and @Abstract=false() and not(pmd-java:typeIs('java.util.concurrent.Executor') or pmd-java:typeIs('java.lang.Throwable'))]
/ClassOrInterfaceBody[ClassOrInterfaceBodyDeclaration/FieldDeclaration[@Static=false()]
[(
ancestor::ClassOrInterfaceBody[1]/ClassOrInterfaceBodyDeclaration/MethodDeclaration
[@Static=false() and starts-with(@Name, 'get') and string-length(@Name) > 3 or starts-with(@Name, 'is') and string-length(@Name) > 2]
[ResultType/Type/ReferenceType/ClassOrInterfaceType/@Image =
ancestor::ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/FieldDeclaration[@Static=false()]/Type/ReferenceType/ClassOrInterfaceType/@Image]
)
and
(not (
ancestor::ClassOrInterfaceBody[1]//MethodDeclaration[@Static=false() and @Name='equals'])
)
and
((ancestor::ClassOrInterfaceBody[1]//MethodDeclaration[@Static=false() and @Name='toString']
and
count(ancestor::ClassOrInterfaceBody[1]/ClassOrInterfaceBodyDeclaration/FieldDeclaration[@Static=false()]) <=
(1 + count(ancestor::ClassOrInterfaceBody[1]/ClassOrInterfaceBodyDeclaration/MethodDeclaration
[@Static=false() and starts-with(@Name, 'get') and string-length(@Name) > 3 or starts-with(@Name, 'is') and string-length(@Name) > 2]))
)
or
ancestor::ClassOrInterfaceDeclaration[1][ends-with(@SimpleName, 'Dto')]
or
count(ancestor::ClassOrInterfaceBody[1]/ClassOrInterfaceBodyDeclaration/FieldDeclaration[@Static=false()]) =
count(ancestor::ClassOrInterfaceBody[1]/ClassOrInterfaceBodyDeclaration/MethodDeclaration
[@Static=false() and starts-with(@Name, 'get') and string-length(@Name) > 3 or starts-with(@Name, 'is') and string-length(@Name) > 2])
)]
or
ancestor::ClassOrInterfaceBodyDeclaration[1]/Annotation//Name[@Image='Getter']
]/.. (:--up to class --:)
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
class Getters { // bad
private String someState1 = "some1";
private String someState2 = "some2";
public String getSomeState1() {
return someState1;
}
public String getSomeState2() {
return someState2;
}
}
@Getter
class LombokGetterBad { // bad
private String someState1 = "some1";
private String someState2 = "some2";
}
@Getter
@EqualsAndHashCode
class LombokGetterGood {
private String someState1 = "some1";
private String someState2 = "some2";
}
]]>
</example>
</rule>
<rule name="MDCPutWithoutRemove" message="MDC put is used without finally remove." class="net.sourceforge.pmd.lang.rule.XPathRule" dfa="false" language="java" typeResolution="true" externalInfoUrl="${doc_root}/JavaCodePerformance.md#IL04">
<description>
MDC values are added for logging, but not removed. Problem: MDC values can leak to other user transactions (requests) and log incorrect information. Solution: remove the MDC value in a finally clause.
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="version" value="2.0"/>
<property name="xpath">
<value>
<![CDATA[
//MethodDeclaration//PrimaryExpression/PrimaryPrefix/Name[@Image='MDC.put']
/../../PrimarySuffix/Arguments/ArgumentList/Expression[1]/PrimaryExpression/PrimaryPrefix/(Name|Literal)[not(@Image=
(ancestor::MethodDeclaration//TryStatement/FinallyStatement//StatementExpression|ancestor::ClassOrInterfaceBody//MethodDeclaration[@Name='afterCompletion' or @Name='postHandle']/Block)//Name[@Image='MDC.remove']
/../../PrimarySuffix/Arguments/ArgumentList/Expression[1]/PrimaryExpression/PrimaryPrefix/(Name|Literal)/@Image)
and not((ancestor::MethodDeclaration//TryStatement/FinallyStatement//StatementExpression|ancestor::ClassOrInterfaceBody//MethodDeclaration[@Name='afterCompletion' or @Name='postHandle']/Block)//Name[@Image='MDC.clear'])
]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
class Bad {
public void bad() {
MDC.put("levelKey1", "levelName1"); // bad, not removed in finally
MDC.put("levelKey2", "levelName2"); // bad, not removed at all
doStuff();
MDC.remove("levelKey1");
}
}
class Good {
public void good() {
try {
MDC.put("levelKey1", "levelName1");
MDC.put("levelKey2", "levelName2");
doStuff();
} finally {
MDC.remove("levelKey1");
MDC.remove("levelKey2");
}
}
}
]]>
</example>
</rule>
<rule name="MinimizeAttributesInSession" class="net.sourceforge.pmd.lang.rule.XPathRule" dfa="false" language="java" message="Attribute is set in the session, yet not removed. This may bloat the session." typeResolution="true"
externalInfoUrl="${doc_root}/JavaCodePerformance.md#tmsu01">
<description>An attribute is set in the session and not removed. Problem: This may be a large object and data in the sessions takes heap space and stay in the session until time-out. This may take substantial heap space.
Solution: remove the attribute if not really needed in the session, remove it from the session as soon as possible. Alternatively, use render parameters.
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="version" value="2.0"/>
<property name="xpath">
<value><![CDATA[
//ClassOrInterfaceBodyDeclaration/MethodDeclaration[../..//(VariableDeclaratorId |ReturnStatement/Expression)[pmd-java:typeIs('javax.portlet.PortletSession') or pmd-java:typeIs('javax.servlet.http.HttpSession')]]
/Block/BlockStatement/Statement[
./StatementExpression/PrimaryExpression/(PrimaryPrefix/Name|PrimarySuffix)[ends-with(@Image, 'setAttribute')]
/ancestor::ClassOrInterfaceBody[not(
ClassOrInterfaceBodyDeclaration//MethodDeclaration/Block//PrimaryExpression/(PrimaryPrefix/Name|PrimarySuffix)[ends-with(@Image, 'removeAttribute')]
)]]
,
//ClassOrInterfaceBodyDeclaration/MethodDeclaration/Block/BlockStatement/Statement[
.//StatementExpression/PrimaryExpression/PrimaryPrefix/Name[@Image = 'PortletUtils.setSessionAttribute']
/ancestor::ClassOrInterfaceBody[not(
ClassOrInterfaceBodyDeclaration//MethodDeclaration/Block//PrimaryExpression/PrimaryPrefix/Name[@Image = 'PortletUtils.setSessionAttribute']
/../../PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix/Literal/NullLiteral
)]]
]]></value>
</property>
</properties>
<example>
<![CDATA[
class Bad {
PortletSession session; // same for HttpSession
public void setAttribute(String name, Object obj) {
session.setAttribute(name, obj); // bad
}
public Object getAttribute(String name) {
return session.getAttribute(name);
}
}
class Good {
PortletSession session; // same for HttpSession
public void setAttribute(String name, final Object obj) {
session.setAttribute(name, obj);
}
public Object getAttribute(String name) {
return session.getAttribute(name);
}
public void removeAttribute(String name) {
session.removeAttribute(name);
}
}
]]>
</example>
</rule>
<rule name="UnconditionalConcatInLogArgument" class="net.sourceforge.pmd.lang.rule.XPathRule" dfa="false" language="java" message="String concatenation (+) is executed regardless of log level and can be expensive" typeResolution="true"
externalInfoUrl="${doc_root}/JavaCodePerformance.md#il01">
<description>Problem: String concatenation (+) is executed regardless of log level and can be expensive.
Solution: Use SLF4J formatting with {}-placeholders or log and format conditionally. (jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="version" value="2.0"/>
<property name="xpath">
<value><![CDATA[
//PrimaryPrefix/Name[ends-with(@Image,'.trace') or ends-with(@Image,'.debug') or
ends-with(@Image,'.info')]/../../PrimarySuffix/Arguments/ArgumentList/Expression/AdditiveExpression[pmd-java:typeIs('java.lang.String')]
[PrimaryExpression/PrimaryPrefix/Name]
[not(ancestor::IfStatement/Expression/PrimaryExpression/PrimaryPrefix/Name[
ends-with(@Image,'.isTraceEnabled')
or ends-with(@Image,'.isDebugEnabled')
or ends-with(@Image,'.isInfoEnabled')
or ends-with(@Image,'.isLoggable')
])]
]]></value>
</property>
</properties>
<example>
<![CDATA[
@slf4j
class Foo {
void bad(String a, String b) {
log.debug("message: {}", a + b); // bad
}
void good(String a, String b) {
log.debug("message: {}{}", a, b); // good
}
}
]]>
</example>
</rule>
<rule name="UnconditionalOperationOnLogArgument" class="net.sourceforge.pmd.lang.rule.XPathRule" dfa="false" language="java" message="Operation is executed regardless of log level and can be expensive" typeResolution="true"
externalInfoUrl="${doc_root}/JavaCodePerformance.md#il03">
<description>Problem: An operation is executed regardless of log level. This could be much processing while the result is typically not used. Detected are obj.toString() and operations with one or more arguments except usually cheap obj.getXXX(arg).
Solution: Execute the operation only conditionally and utilize SLF4J formatting with {}-placeholders. (jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="version" value="2.0"/>
<property name="xpath">
<value><![CDATA[
//PrimaryPrefix/Name
(: log levels typically/often not enabled :)
[
ends-with(@Image,'.trace')
or ends-with(@Image,'.debug')
or ends-with(@Image,'.info')
]
(: no violation if conditionally: only executed if level enabled is okay :)
[not(ancestor::IfStatement//Name
[
ends-with(@Image,'.isTraceEnabled')
or ends-with(@Image,'.isDebugEnabled')
or ends-with(@Image,'.isInfoEnabled')
or ends-with(@Image,'.isLoggable')
])
]
(: no violation if return conditionally before :)
[not(ancestor::BlockStatement/preceding-sibling::BlockStatement//IfStatement//ReturnStatement/ancestor::IfStatement//Name
[
ends-with(@Image,'.isTraceEnabled')
or ends-with(@Image,'.isDebugEnabled')
or ends-with(@Image,'.isInfoEnabled')
or ends-with(@Image,'.isLoggable')
])
]
(: in the log method :)
/../../PrimarySuffix/Arguments/ArgumentList/Expression//PrimaryExpression
[
(: toString on argument :)
PrimaryPrefix/Name[ends-with(@Image,'.toString')]
or
(: a method call with an argument list :)
(PrimarySuffix/Arguments/ArgumentList)
(: exclude a simple getXXX(i), like list.get(0) or env.getProperty(key), assumed to be fast :)
and not (PrimaryPrefix/Name[contains(@Image,'.get')])
]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
LOG.debug("customer = {}", customer.toString()); // bad
LOG.debug("Complete Soap response: {}", getSoapMsgAsString(context.getMessage())); // bad
LOG.debug("customer = {}", customer); // good
if (LOG.isDebugEnabled()) { // good
LOG.debug("Complete Soap response: {}", getSoapMsgAsString(context.getMessage()));
}
]]>
</example>
</rule>
<rule name="UsingSuppressWarningsHighRisk" class="net.sourceforge.pmd.lang.rule.XPathRule" dfa="false" language="java" message="Using SuppressWarnings for a rule that is meant to prevent high risk problems." typeResolution="true"
externalInfoUrl="${doc_root}/JavaCodePerformance.md">
<description>(Informative) Problem: This rule detects high risk problems, suppressing them without full knowledge can lead to incidents like customer data mix-up, corrupt data, server crashes or very bad performance.
Solution: Suppress warnings judiciously based on full knowledge and report reasons to suppress (false positives) to the rule maintainers so these can be fixed. (jpinpoint-rules)</description>
<priority>4</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="ruleIdMatches" type="String" value="AvoidUnguardedMutableFieldsInSharedObjects|AvoidUnguardedAssignmentToNonFinalFieldsInSharedObjects|AvoidMutableStaticFields|[^\w]ALL[^\w]|[^\w]all[^\w]|PMD[^\.]|pmd[^:]"
description="Regex for inclusion of high risk rules"/>
<property name="ruleIdNotMatches" type="String" value="^$"
description="Regex for exclusion of high risk rules"/>
<property name="version" value="2.0"/>
<property name="xpath">
<value><![CDATA[
//Annotation//Name[@Image="SuppressWarnings" or @Image="SuppressFBWarnings"]/..//Literal[(matches(@Image, $ruleIdMatches)) and not (matches(@Image, $ruleIdNotMatches))]
]]>
</value>
</property>
</properties>
</rule>
<rule name="UsingSuppressWarnings" class="net.sourceforge.pmd.lang.rule.XPathRule" dfa="false" language="java" message="Using SuppressWarnings." typeResolution="true"
externalInfoUrl="${doc_root}/JavaCodePerformance.md">
<description>(Informative) Problem: This rule detects problems, suppressing them without full knowledge can lead to the problems this rule is trying to prevent.
Solution: Suppress warnings judiciously based on full knowledge and report reasons to suppress (false positives) to the rule maintainers so these can be fixed. (jpinpoint-rules)</description>
<priority>5</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="ruleIdMatches" type="String" value=".*"
description="Regex for inclusion of rules"/>
<property name="ruleIdNotMatches" type="String" value="^$"
description="Regex for exclusion of rules"/>
<property name="version" value="2.0"/>
<property name="xpath">
<value><![CDATA[
//Annotation//Name[@Image="SuppressWarnings" or @Image="SuppressFBWarnings"]/..//Literal[(matches(@Image, $ruleIdMatches)) and not (matches(@Image, $ruleIdNotMatches))]
]]>
</value>
</property>
</properties>
</rule>
<rule name="AvoidTimeUnitConfusion" class="net.sourceforge.pmd.lang.rule.XPathRule" dfa="false" language="java" message="A primitive variable identifier or @Value member ends with time, timeout, duration or similar: time unit is missing." typeResolution="true"
externalInfoUrl="${doc_root}/JavaCodePerformance.md#IBI19">
<description>Problem: Time unit like hours, seconds, milliseconds is not specified and may be assumed differently by readers.
Different assumptions will lead to errors or hidden problems like ineffective caches.
Solution: Specify the time unit in the identifier, like connectTimeoutMillis. (jpinpoint-rules)</description>
<priority>3</priority>
<properties>
<property name="tag" value="jpinpoint-rule" type="String" description="for-sonar"/>
<property name="version" value="2.0"/>
<property name="xpath">
<value><![CDATA[
(: for fields, formal parameters and local variables :)
//Type/PrimitiveType/../..//VariableDeclaratorId[ends-with(lower-case(@Name), 'timetolive') or ends-with(lower-case(@Name), 'time_to_live') or
ends-with(lower-case(@Name), 'time')
or ends-with(lower-case(@Name), 'timeout') or ends-with(lower-case(@Name), 'time_out')
or ends-with(lower-case(@Name), 'duration') or ends-with(lower-case(@Name), 'durationout') or ends-with(lower-case(@Name), 'duration_out')
or ends-with(lower-case(@Name), 'ttl') or ends-with(lower-case(@Name), 'timestamp')]
,
(: @Value :)
//SingleMemberAnnotation/Name[@Image='Value']/..//Literal[ends-with(lower-case(@Image), 'timetolive') or ends-with(lower-case(@Image), 'expirytime}"')
or ends-with(lower-case(@Image), 'timeout}"') or ends-with(lower-case(@Image), 'ttl}"') or ends-with(lower-case(@Image), 'timestamp}"')]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
@Autowired
public RetrieveCache(final @Value("${cache.expiryTime}") long timeToLive) { // 2x bad
}
@Autowired
public RetrieveCache(final @Value("${cache.expiryTimeMillis}") long timeToLiveMillis) { // 2x good
}
]]>
</example>
</rule>
<rule name="AvoidTimeUnitConfusionPMD7" since="7.0" class="net.sourceforge.pmd.lang.rule.XPathRule" language="java" message="A primitive variable identifier or @Value member ends with time, timeout, duration or similar: time unit is missing." typeResolution="true"