-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruleset.xml
More file actions
1155 lines (1033 loc) · 41.5 KB
/
ruleset.xml
File metadata and controls
1155 lines (1033 loc) · 41.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="Default"
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 https://pmd.github.io/ruleset_2_0_0.xsd">
<description>
This ruleset checks the code for discouraged programming constructs.
</description>
<!-- Only rules that don't overlap with CheckStyle! -->
<!-- About: Formatting -->
<!-- Some lines (e.g. description, examples and CDATA) have to start without any indents or this will result in incorrect formatting -->
<rule ref="category/java/bestpractices.xml/AvoidPrintStackTrace"/>
<rule ref="category/java/bestpractices.xml/AvoidUsingHardCodedIP"/>
<rule ref="category/java/bestpractices.xml/ConstantsInInterface"/>
<rule ref="category/java/bestpractices.xml/ExhaustiveSwitchHasDefault"/>
<rule ref="category/java/bestpractices.xml/LabeledStatement"/>
<rule ref="category/java/bestpractices.xml/LiteralsFirstInComparisons"/>
<!-- CheckStyle can't handle this switch behavior -> delegated to PMD -->
<rule ref="category/java/bestpractices.xml/NonExhaustiveSwitch"/>
<rule ref="category/java/bestpractices.xml/OneDeclarationPerLine">
<properties>
<property name="strictMode" value="true"/>
</properties>
</rule>
<rule ref="category/java/bestpractices.xml/PreserveStackTrace"/>
<rule ref="category/java/bestpractices.xml/SimplifiableTestAssertion"/>
<rule ref="category/java/bestpractices.xml/SystemPrintln"/>
<rule ref="category/java/bestpractices.xml/UnnecessaryWarningSuppression"/>
<rule ref="category/java/bestpractices.xml/UnusedAssignment"/>
<rule ref="category/java/bestpractices.xml/UnusedFormalParameter"/>
<rule ref="category/java/bestpractices.xml/UnusedPrivateField"/>
<rule ref="category/java/bestpractices.xml/UnusedPrivateMethod"/>
<rule ref="category/java/bestpractices.xml/UseCollectionIsEmpty"/>
<rule ref="category/java/bestpractices.xml/UseEnumCollections"/>
<rule ref="category/java/bestpractices.xml/UseStandardCharsets"/>
<rule ref="category/java/bestpractices.xml/UseTryWithResources"/>
<!-- Native code is platform dependent; Loading external native libs might pose a security threat -->
<rule ref="category/java/codestyle.xml/AvoidUsingNativeCode"/>
<rule ref="category/java/codestyle.xml/IdenticalCatchBranches"/>
<rule ref="category/java/codestyle.xml/LambdaCanBeMethodReference"/>
<rule ref="category/java/codestyle.xml/NoPackage"/>
<rule ref="category/java/codestyle.xml/PrematureDeclaration"/>
<rule ref="category/java/codestyle.xml/UnnecessarySemicolon"/>
<rule ref="category/java/codestyle.xml/VariableCanBeInlined"/>
<rule ref="category/java/design.xml">
<!-- Sometimes abstract classes have just fields -->
<exclude name="AbstractClassWithoutAnyMethod"/>
<!-- Using RuntimeExceptions is ok -->
<exclude name="AvoidCatchingGenericException"/>
<exclude name="AvoidThrowingRawExceptionTypes"/>
<!-- Limit too low -->
<exclude name="AvoidDeeplyNestedIfStmts"/>
<!-- Limit too low -->
<exclude name="CouplingBetweenObjects"/>
<!-- Limit too low -->
<exclude name="CyclomaticComplexity"/>
<!-- Makes entity classes impossible -->
<exclude name="DataClass"/>
<!-- Used commonly particular in bigger methods with upstream throws -->
<exclude name="ExceptionAsFlowControl"/>
<!-- Limit too low -->
<exclude name="ExcessiveImports"/>
<!-- Handled by TooManyFields/TooManyMethods -->
<exclude name="ExcessivePublicCount"/>
<!-- Prohibits accessing members using multiple depths -->
<exclude name="LawOfDemeter"/>
<!-- No effect -->
<exclude name="LoosePackageCoupling"/>
<!-- Prohibits singleton pattern -->
<exclude name="MutableStaticState"/>
<!-- Checks LoC, already handled by Checkstyle -->
<exclude name="NcssCount"/>
<!-- Some override methods or Junit require this -->
<exclude name="SignatureDeclareThrowsException"/>
<!-- Reports FP for equals methods -->
<exclude name="SimplifyBooleanReturns"/>
<!-- Limit too low -->
<exclude name="TooManyFields"/>
<!-- Limit too low -->
<exclude name="TooManyMethods"/>
<!-- Limit too low -->
<exclude name="UseObjectForClearerAPI"/>
</rule>
<rule ref="category/java/design.xml/AvoidDeeplyNestedIfStmts">
<properties>
<property name="problemDepth" value="4"/>
</properties>
</rule>
<rule ref="category/java/design.xml/CouplingBetweenObjects">
<properties>
<property name="threshold" value="100"/>
</properties>
</rule>
<rule ref="category/java/design.xml/CyclomaticComplexity">
<properties>
<property name="classReportLevel" value="150"/>
<property name="methodReportLevel" value="25"/>
<property name="cycloOptions" value=""/>
</properties>
</rule>
<rule ref="category/java/design.xml/ExcessiveImports">
<properties>
<property name="minimum" value="200"/>
</properties>
</rule>
<rule ref="category/java/design.xml/TooManyFields">
<properties>
<property name="maxfields" value="50"/>
</properties>
</rule>
<rule ref="category/java/design.xml/TooManyMethods">
<properties>
<property name="maxmethods" value="100"/>
</properties>
</rule>
<rule ref="category/java/errorprone.xml/AssignmentToNonFinalStatic"/>
<rule ref="category/java/errorprone.xml/AvoidDecimalLiteralsInBigDecimalConstructor"/>
<rule ref="category/java/errorprone.xml/AvoidMultipleUnaryOperators"/>
<rule ref="category/java/errorprone.xml/AvoidUsingOctalValues"/>
<rule ref="category/java/errorprone.xml/BrokenNullCheck"/>
<rule ref="category/java/errorprone.xml/CollectionTypeMismatch"/>
<rule ref="category/java/errorprone.xml/ComparisonWithNaN"/>
<rule ref="category/java/errorprone.xml/DoNotCallGarbageCollectionExplicitly"/>
<rule ref="category/java/errorprone.xml/DontUseFloatTypeForLoopIndices"/>
<rule ref="category/java/errorprone.xml/EqualsNull"/>
<rule ref="category/java/errorprone.xml/IdempotentOperations"/>
<rule ref="category/java/errorprone.xml/IdenticalConditionalBranches"/>
<rule ref="category/java/errorprone.xml/ImplicitSwitchFallThrough"/>
<rule ref="category/java/errorprone.xml/InstantiationToGetClass"/>
<rule ref="category/java/errorprone.xml/InvalidLogMessageFormat"/>
<rule ref="category/java/errorprone.xml/JumbledIncrementer"/>
<rule ref="category/java/errorprone.xml/MisplacedNullCheck"/>
<rule ref="category/java/errorprone.xml/MoreThanOneLogger"/>
<rule ref="category/java/errorprone.xml/NonStaticInitializer"/>
<rule ref="category/java/errorprone.xml/ReplaceJavaUtilCalendar"/>
<rule ref="category/java/errorprone.xml/ReplaceJavaUtilDate"/>
<rule ref="category/java/errorprone.xml/ReturnFromFinallyBlock"/>
<rule ref="category/java/errorprone.xml/SingletonClassReturningNewInstance"/>
<rule ref="category/java/errorprone.xml/UnconditionalIfStatement"/>
<rule ref="category/java/errorprone.xml/UnnecessaryCaseChange"/>
<rule ref="category/java/errorprone.xml/UnsupportedJdkApiUsage"/>
<rule ref="category/java/errorprone.xml/UselessPureMethodCall"/>
<rule ref="category/java/multithreading.xml">
<!-- Just bloats code; improved in JEP-491/Java 24+ -->
<exclude name="AvoidSynchronizedAtMethodLevel"/>
<!-- NOPE -->
<exclude name="DoNotUseThreads"/>
<!-- Doesn't detect nested thread safe singleton pattern -->
<exclude name="NonThreadSafeSingleton"/>
<!-- Should relevant for fields that use multithreading which is rare -->
<exclude name="UseConcurrentHashMap"/>
</rule>
<rule ref="category/java/performance.xml">
<!-- This was fixed in Java 10 -->
<exclude name="AvoidFileStream"/>
<!-- Used everywhere and has neglectable performance impact -->
<exclude name="AvoidInstantiatingObjectsInLoops"/>
<!-- Handled by checkstyle -->
<exclude name="RedundantFieldInitializer"/>
<!-- Not in use and resource intensive -->
<exclude name="UseIOStreamsWithApacheCommonsFileItem"/>
<!-- Nowadays optimized by compiler; No code bloating needed -->
<exclude name="UseStringBufferForStringAppends"/>
</rule>
<rule ref="category/java/performance.xml/TooFewBranchesForSwitch">
<properties>
<!-- If you have one case only please use a if -->
<property name="minimumNumberCaseForASwitch" value="2"/>
</properties>
</rule>
<rule ref="category/java/security.xml"/>
<rule name="AvoidOptionalGet"
language="java"
message="Avoid using Optional#get"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
externalInfoUrl="https://stackoverflow.com/a/49159955">
<description>
`Optional#get` can be interpreted as a getter by developers, however this is not the case as it throws an exception when empty.
It should be replaced by
* doing a mapping directly using `.map` or `.ifPresent`
* using the preferred `.orElseThrow`, `.orElse` or `.or` methods
Java Developer Brian Goetz also writes regarding this topic:
> Java 8 was a huge improvement to the platform, but one of the few mistakes we made was the naming of `Optional.get()`, because the name just invites people to call it without calling `isPresent()`, undermining the whole point of using `Optional` in the first place.
>
> During the Java 9 time frame, we proposed to deprecate `Optional.get()`, but the public response to that was ... let's say cold. As a smaller step, we introduced `orElseThrow()` in 10 (see [JDK-8140281](https://bugs.openjdk.java.net/browse/JDK-8140281)) as a more transparently named synonym for the current pernicious behavior of `get()`. IDEs warn on unconditional use of `get()`, but not on `orElseThrow()`, which is a step forward in teaching people to code better. The question is, in a sense, a "glass half empty" view of the current situation; `get()` is still problematic.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//MethodCall[pmd-java:matchesSig('java.util.Optional#get()')]
]]>
</value>
</property>
</properties>
</rule>
<rule name="AvoidStringBuilderOrBuffer"
language="java"
message="StringBuilder/StringBuffer should not be used"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule">
<description>
Usually all cases where `StringBuilder` (or the outdated `StringBuffer`) is used are either due to confusing (legacy) logic or in situations where it may be easily replaced by a simpler string concatenation.
Solution:
* Do not use `StringBuffer` because it's thread-safe and usually this is not needed
* If `StringBuilder` is only used in a simple method (like `toString`) and is effectively inlined: Use a simpler string concatenation (`"a" + x + "b"`). This will be [optimized by the Java compiler internally](https://docs.oracle.com/javase/specs/jls/se25/html/jls-15.html#jls-15.18.1).
* In all other cases:
* Check what is happening and if it makes ANY sense! If for example a CSV file is built here consider using a proper library instead!
* Abstract the Strings into a DTO, join them together using a collection (or `StringJoiner`) or use Java's Streaming API instead
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ConstructorCall/ClassType[pmd-java:typeIs('java.lang.StringBuffer') or pmd-java:typeIs('java.lang.StringBuilder')]
]]>
</value>
</property>
</properties>
</rule>
<rule name="AvoidSystemSetterCall"
language="java"
message="Setters of java.lang.System should not be called unless really needed"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule">
<description>
Calling setters of `java.lang.System` usually indicates bad design and likely causes unexpected behavior.
For example, it may break when multiple Threads are working with the same value.
It may also overwrite user defined options or properties.
Try to pass the value only to the place where it's really needed and use it there accordingly.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//MethodCall[starts-with(@MethodName,'set')]/TypeExpression[pmd-java:typeIsExactly('java.lang.System')]
]]>
</value>
</property>
</properties>
</rule>
<rule name="AvoidPostConstruct"
language="java"
message="Avoid @PostConstruct"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule">
<description>
Using a `@PostConstruct` method is usually only done when field injection is used and initialization needs to be performed after that.
It's better to do this directly in the constructor with constructor injection, so that all logic will be encapsulated there.
This also makes using the bean in environments where JavaEE is not present - for example in tests - a lot easier, as forgetting to call the `@PostConstruct` method is no longer possible.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//MethodDeclaration[pmd-java:hasAnnotation('jakarta.annotation.PostConstruct')]
]]>
</value>
</property>
</properties>
</rule>
<rule name="AvoidPreDestroy"
language="java"
message="Avoid @PreDestroy"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule">
<description>
`@PreDestroy` should be replaced by implementing `AutoCloseable` and overwriting the `close` method instead.
This also makes using the bean in environments where JavaEE is not present - for example in tests - a lot easier, as forgetting to call the `@PreDestroy` method is no much more difficult.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//MethodDeclaration[pmd-java:hasAnnotation('jakarta.annotation.PreDestroy')]
]]>
</value>
</property>
</properties>
</rule>
<rule name="AvoidUnmanagedThreads"
language="java"
message="Avoid unmanaged threads"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule">
<description>
Trying to manually manage threads usually gets quickly out of control and may result in various problems like uncontrollable spawning of threads.
Threads can also not be cancelled properly.
Use managed Thread services like `ExecutorService` and `CompletableFuture` instead.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//MethodCall[pmd-java:matchesSig('java.lang.Thread#start()') or pmd-java:matchesSig('java.lang.Thread#startVirtualThread(java.lang.Runnable)') or pmd-java:matchesSig('java.lang.Thread$Builder#start(java.lang.Runnable)')]
]]>
</value>
</property>
</properties>
</rule>
<rule name="EnsureZipEntryNameIsSanitized"
language="java"
message="ZipEntry name should be sanitized"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule">
<description>
ZipEntry name should be sanitized.
Unsanitized names may contain '..' which can result in path traversal ("ZipSlip").
You can suppress this warning when you properly sanitized the name.
</description>
<priority>4</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//MethodCall[pmd-java:matchesSig('java.util.zip.ZipEntry#getName()') or pmd-java:matchesSig('org.apache.commons.compress.archivers.ArchiveEntry#getName()')]
]]>
</value>
</property>
</properties>
</rule>
<rule name="JavaObjectSerializationIsUnsafe"
language="java"
message="Using Java Object (De-)Serialization is unsafe and has led to too many security vulnerabilities"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule">
<description>
Nearly every known usage of (Java) Object Deserialization has resulted in [a security vulnerability](https://cloud.google.com/blog/topics/threat-intelligence/hunting-deserialization-exploits?hl=en).
Vulnerabilities are so common that there are [dedicated projects for exploit payload generation](https://github.com/frohoff/ysoserial).
Java Object Serialization may also fail to deserialize properly when the underlying classes are changed.
This can result in unexpected crashes when outdated data is deserialized.
Use proven data interchange formats like JSON instead.
</description>
<priority>2</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ClassDeclaration[@Interface = false()]/ClassBody/FieldDeclaration/VariableDeclarator/VariableId[@Name='serialVersionUID'] |
//ConstructorCall/ClassType[pmd-java:typeIsExactly('java.io.ObjectInputStream') or pmd-java:typeIsExactly('java.io.ObjectOutputStream')]
]]>
</value>
</property>
</properties>
</rule>
<!-- Vaadin -->
<!-- For future reference: This should maybe be extracted into a ruleset if there are more Vaadin specific rules -->
<rule name="VaadinNativeHTMLIsUnsafe"
language="java"
message="Unescaped native HTML is unsafe and will result in XSS vulnerabilities"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
externalInfoUrl="https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML">
<description>
Do not use native HTML! Use Vaadin layouts and components to create required structure.
If you are 100% sure that you escaped the value properly and you have no better options you can suppress this.
</description>
<priority>2</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ConstructorCall[pmd-java:typeIs('com.vaadin.flow.component.Html')] |
//MethodCall[@MethodName='setAttribute' and //ImportDeclaration[starts-with(@PackageName,'com.vaadin')]]/ArgumentList/StringLiteral[1][contains(lower-case(@Image),'html')]
]]>
</value>
</property>
</properties>
</rule>
<!-- Jakarta Persistence -->
<rule name="AvoidListAsEntityRelation"
language="java"
message="Use a Set instead of a List in entity relations"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
externalInfoUrl="https://www.baeldung.com/spring-jpa-onetomany-list-vs-set#bd-pros-and-cons">
<description>
`List` allows duplicates while a `Set` does not.
A `Set` also prevents duplicates when the ORM reads multiple identical rows from the database (e.g. when using JOIN).
</description>
<priority>2</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ClassDeclaration[pmd-java:hasAnnotation('jakarta.persistence.Entity')]
//FieldDeclaration[pmd-java:hasAnnotation('jakarta.persistence.ManyToMany') or pmd-java:hasAnnotation('jakarta.persistence.OneToMany')]
/ClassType[pmd-java:typeIs('java.util.List')]
]]>
</value>
</property>
</properties>
</rule>
<!-- Rules from JPinPoint with slight modifications -->
<!-- https://github.com/jborgers/PMD-jPinpoint-rules -->
<!-- Licensed under Apache-2.0 -->
<rule name="AvoidDecimalAndChoiceFormatAsField"
language="java"
message="Avoid using DecimalFormat or ChoiceFormat as field since it is thread-unsafe"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule">
<description>
java.text.NumberFormat: DecimalFormat and ChoiceFormat are thread-unsafe.
Solution: Create a new local one when needed in a method.
</description>
<priority>1</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//FieldDeclaration/ClassType[pmd-java:typeIs('java.text.NumberFormat')]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class Foo {
public static final DecimalFormat NUMBER_FORMAT = new DecimalFormat("###.###"); // bad
public void bar() {
NumberFormat format = new DecimalFormat("###.###"); // good
}
}
]]>
</example>
</rule>
<rule name="AvoidImplicitlyRecompilingRegex"
language="java"
message="Detected possible resource expensive implicit regex pattern compilation"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule">
<description>
A regular expression is compiled implicitly on every invocation.
Problem: This can be (CPU) 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.
</description>
<priority>2</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
(:- method calls for non-short regex literals and used fields defined with non-short regex literal, or not defined as field -:)
//MethodDeclaration//MethodCall[pmd-java:matchesSig('java.lang.String#replaceAll(java.lang.String,java.lang.String)')
or pmd-java:matchesSig('java.lang.String#replaceFirst(java.lang.String,java.lang.String)')
or pmd-java:matchesSig('java.util.regex.Pattern#matches(java.lang.String,java.lang.CharSequence)')
or pmd-java:matchesSig('java.lang.String#split(java.lang.String)')
or pmd-java:matchesSig('java.lang.String#matches(java.lang.String)')
or pmd-java:matchesSig('java.nio.file.FileSystem#getPathMatcher(java.lang.String)')
]
/ArgumentList/*[1][(self::StringLiteral and string-length(@Image) > 5 and
(matches(@Image, '[\.\$\|\(\)\[\]\{\}\^\?\*\+\\]+')))
or
self::VariableAccess and @Name=ancestor::ClassBody[1]/FieldDeclaration/VariableDeclarator[StringLiteral[string-length(@Image) > 5 and
(matches(@Image, '[\.\$\|\(\)\[\]\{\}\^\?\*\+\\]+'))] or not(StringLiteral)]/VariableId/@Name]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
String bad_replaceInnerLineBreakBySpace() {
return text.replaceAll("([^\\.\\n])\\n", "$1 "); // bad
}
private static final Pattern INNER_LINE_BREAK_PATTERN = Pattern.compile("([^\\.\\n])\\n"); // good
String good_replaceInnerLineBreakBySpace() {
return INNER_LINE_BREAK_PATTERN.matcher(text).replaceAll("$1 "); // good
}
]]>
</example>
</rule>
<!-- CHANGED: Only match parameter-less constructor (Optimization) -->
<rule name="AvoidInMemoryStreamingDefaultConstructor"
language="java"
message="Default buffer capacity is used which usually needs expensive expansions"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule">
<description>
The default constructor of ByteArrayOutputStream creates a 32 bytes initial capacity and for StringWriter 16 chars.
Such a small buffer as capacity usually needs several expensive expansions.
Solution: Explicitly declared the buffer size so that an expansion is not needed in most cases.
Typically much larger than 32, e.g. 4096.
</description>
<priority>2</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ConstructorCall[pmd-java:matchesSig('java.io.ByteArrayOutputStream#new()') or pmd-java:matchesSig('java.io.StringWriter#new()')]
]]>
</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="AvoidReStreamingEnumValues"
language="java"
message="Avoid re-streaming enum values to find a value by a field"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule">
<description>
The time to find element is O(n); n = the number of enum values.
This identical processing is executed for every call.
Considered problematic when `n > 3`.
Solution: Use a static field-to-enum-value Map. Access time is O(1), provided the hashCode is well-defined.
Implement a fromString method to provide the reverse conversion by using the map.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//EnumDeclaration/EnumBody[count(EnumConstant) > 3]//MethodDeclaration/Block
//MethodCall[pmd-java:matchesSig('java.util.stream.Stream#findFirst()') or pmd-java:matchesSig('java.util.stream.Stream#findAny()')]
[//MethodCall[pmd-java:matchesSig('java.util.stream.Stream#of(_)') or pmd-java:matchesSig('java.util.Arrays#stream(_)')]
[ArgumentList/MethodCall[pmd-java:matchesSig('_#values()')]]]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
// BAD
public enum Fruit {
APPLE("apple"),
ORANGE("orange"),
BANANA("banana"),
KIWI("kiwi");
private final String name;
Fruit(String name) { this.name = name; }
@Override public String toString() { return name; }
public static Optional<Fruit> fromString(String name) {
return Stream.of(values()).filter(v -> v.toString().equals(name)).findAny(); // bad: iterates for every call, O(n) access time
}
}
Usage: `Fruit f = Fruit.fromString("banana");`
// GOOD
public enum Fruit {
APPLE("apple"),
ORANGE("orange"),
BANANA("banana"),
KIWI("kiwi");
private static final Map<String, Fruit> nameToValue =
Stream.of(values()).collect(toMap(Object::toString, v -> v));
private final String name;
Fruit(String name) { this.name = name; }
@Override public String toString() { return name; }
public static Optional<Fruit> fromString(String name) {
return Optional.ofNullable(nameToValue.get(name)); // good, get from Map, O(1) access time
}
}
]]>
</example>
</rule>
<rule name="AvoidRecompilingPatterns"
language="java"
message="Pattern.compile is used in a method. Compiling a regex pattern can be expensive, make it a static final field."
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule">
<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.
</description>
<priority>2</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//MethodDeclaration//MethodCall[pmd-java:matchesSig('java.util.regex.Pattern#compile(java.lang.String)')
and not(.//VariableAccess[@Name = ancestor::MethodDeclaration//FormalParameter/VariableId/@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>
<!-- CHANGED: Removed joda time -->
<rule name="AvoidRecreatingDateTimeFormatter"
language="java"
message="Avoid expensive recreation of DateTimeFormatter"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule">
<description>
Recreating a DateTimeFormatter is relatively expensive.
Solution: 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.
</description>
<priority>2</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//FieldDeclaration
[ClassType[pmd-java:typeIs('java.time.format.DateTimeFormatter')]]
[(not(pmd-java:modifiers() = 'static') and VariableDeclarator[@Initializer=true()]) or not(pmd-java:modifiers() = 'final')]
|
//(MethodDeclaration|ConstructorDeclaration)//MethodCall[((pmd-java:matchesSig('java.time.format.DateTimeFormatter#ofPattern(_)'))
and not(ArgumentList/VariableAccess/@Name = ancestor::Block/..//FormalParameter/VariableId/@Name))
or pmd-java:matchesSig('java.time.format.DateTimeFormatterBuilder#toFormatter()')
or pmd-java:matchesSig('java.time.format.DateTimeFormatterBuilder#toFormatter(_)')
]
]]>
</value>
</property>
</properties>
</rule>
<rule name="AvoidRecreatingSecurityProviders"
language="java"
message="Avoid expensive recreation of security providers"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule">
<description>
Creating a security provider is expensive because of loading of algorithms and other classes.
Additionally, it uses synchronized which leads to lock contention when used with multiple threads.
Solution: This only needs to happen once in the JVM lifetime, because once loaded the provider is typically available from the Security class.
Create the security provider only once: Only in case when it's not yet available from the Security class.
</description>
<priority>2</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//MethodDeclaration
[not((@Name='main' and @Static=true())or ModifierList/Annotation/@SimpleName='PostConstruct'
or .//IfStatement//InfixExpression
[@Operator='=='][VariableAccess[pmd-java:typeIs('java.security.Provider')] and NullLiteral]
)]
//ConstructorCall[pmd-java:typeIs('java.security.Provider') or pmd-java:typeIs('org.bouncycastle.jce.provider.BouncyCastleProvider')]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
import java.security.*;
import javax.crypto.*;
import org.bouncycastle.jce.provider.*;
class Foo {
public Cipher initBlowfishBad() throws GeneralSecurityException {
Security.addProvider(new BouncyCastleProvider()); // bad
// build a Cipher
}
public Cipher initBlowfishGood() throws GeneralSecurityException {
Provider bouncyCastleProvider = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME);
if (bouncyCastleProvider == null) {
bouncyCastleProvider = new BouncyCastleProvider();
Security.addProvider(bouncyCastleProvider);
}
// build a Cipher
}
}
]]>
</example>
</rule>
<rule name="AvoidReflectionInToStringAndHashCode"
language="java"
message="Expensive Reflection is used"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule">
<description>
Reflection is relatively expensive.
Solution: Avoid reflection. Use the non-reflective, explicit way like generation by IDE.
</description>
<priority>2</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//MethodCall[starts-with(@MethodName, 'reflection')][(TypeExpression|ConstructorCall)
[pmd-java:typeIs('org.apache.commons.lang3.builder.EqualsBuilder') or pmd-java:typeIs('org.apache.commons.lang3.builder.HashCodeBuilder')]]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
class Bad {
private int state;
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(o, this); // bad
}
}
class Good {
private int state;
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Good)) return false;
return new EqualsBuilder().append(((Good)o).state, state).isEquals();
}
}
]]>
</example>
</rule>
<rule name="AvoidSimpleDateFormat"
language="java"
message="SimpleDateFormat is used. Since it is thread-unsafe, it needs expensive recreation."
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule">
<description>
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.
</description>
<priority>2</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ConstructorCall/ClassType[pmd-java:typeIs('java.text.SimpleDateFormat')
and not ((ancestor::LocalVariableDeclaration/following-sibling::ExpressionStatement/MethodCall|ancestor::MethodCall)
[@MethodName='setDateFormat']/VariableAccess[pmd-java:typeIs('com.fasterxml.jackson.databind.ObjectMapper')
or pmd-java:typeIs('com.fasterxml.jackson.dataformat.xml.XmlMapper')])
]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class Foo {
private String toKeyBad(final Date date) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); //bad
return formatter.format(date);
}
private String toKeyGood(final LocalDate localDate) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); //good
return formatter.format(localDate);
}
}
]]>
</example>
</rule>
<rule name="AvoidCommonPoolForBlockingCalls"
language="java"
message="Avoid the ForkJoinPool::commonPool used in parallelStream for blocking calls"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule">
<description>
Blocking calls, for instance remote calls, may exhaust the common pool for some time thereby blocking all other use of the common pool.
In addition, nested use of the common pool can lead to deadlock. Do not use the common pool for blocking calls.
The parallelStream() call uses the common pool.
Solution: Use a dedicated thread pool with enough threads to get proper parallelism.
The number of threads in the common pool is equal to the number of CPUs and meant to utilize all of them.
It assumes CPU-intensive non-blocking processing of in-memory data.
See also: [_Be Aware of ForkJoinPool#commonPool()_](https://dzone.com/articles/be-aware-of-forkjoinpoolcommonpool)
</description>
<priority>2</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
(: assumption: if import of web client / http client is present, parallelStreaming is for remote calls :)
//ImportDeclaration[@PackageName=('org.springframework.web.client','org.apache.commons.httpclient')]
/..//MethodCall[
pmd-java:matchesSig('java.util.Collection#parallelStream()')
and not(ancestor::ExpressionStatement//MethodCall[pmd-java:matchesSig('java.util.concurrent.ExecutorService#submit(_)')])
]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
import java.util.concurrent.*;
import java.util.stream.*;
import java.util.*;
import org.springframework.web.client.RestTemplate;
public class Foo {
final List<String> list = new ArrayList();
final ForkJoinPool myFjPool = new ForkJoinPool(10);
final ExecutorService myExePool = Executors.newFixedThreadPool(10);
void bad1() {
list.parallelStream().forEach(elem -> storeDataRemoteCall(elem)); // bad
}
void good1() {
CompletableFuture[] futures = list.stream().map(elem -> CompletableFuture.supplyAsync(() -> storeDataRemoteCall(elem), myExePool))
.toArray(CompletableFuture[]::new);
CompletableFuture.allOf(futures).get(10, TimeUnit.MILLISECONDS));
}
void good2() throws ExecutionException, InterruptedException {
myFjPool.submit(() ->
list.parallelStream().forEach(elem -> storeDataRemoteCall(elem))
).get();
}
String storeDataRemoteCall(String elem) {
// do remote call, blocking. We don't use the returned value.
RestTemplate tmpl;
return "";
}
}
]]>
</example>
</rule>
<rule name="AvoidCommonPoolForFutureAsync"
language="java"
message="Avoid using the common thread pool, use a separate pool"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule">
<description>
CompletableFuture.supplyAsync/runAsync is typically used for remote calls.
By default it uses the common pool.
The number of threads in the common pool is equal to the number of CPU's, which is suitable for in-memory processing.
For I/O, however, this number is typically not suitable because most time is spent waiting for the response and not in CPU.
The common pool must not be used for blocking calls.
Solution: A separate, properly sized pool of threads (an Executor) should be used for the async calls.
See also: [_Be Aware of ForkJoinPool#commonPool()_](https://dzone.com/articles/be-aware-of-forkjoinpoolcommonpool)
</description>
<priority>2</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//MethodCall[pmd-java:matchesSig('java.util.concurrent.CompletableFuture#supplyAsync(_)') or pmd-java:matchesSig('java.util.concurrent.CompletableFuture#runAsync(_)')]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class Foo {
private final ExecutorService asyncPool = Executors.newFixedThreadPool(8);
void bad() {
CompletableFuture<Pair<String, Boolean>>[] futures = accounts.stream()
.map(account -> CompletableFuture.supplyAsync(() -> isAccountBlocked(account))) // bad
.toArray(CompletableFuture[]::new);
}
void good() {
CompletableFuture<Pair<String, Boolean>>[] futures = accounts.stream()
.map(account -> CompletableFuture.supplyAsync(() -> isAccountBlocked(account), asyncPool)) // good
.toArray(CompletableFuture[]::new);
}
}
]]>
</example>
</rule>
<rule name="AvoidCompletionServiceTake"
language="java"
message="Avoid CompletionService.take, use poll"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule">
<description>
`take()` stalls indefinitely in case of hanging threads and consumes a thread.
Solution: use `poll()` with a timeout value and handle the timeout.
</description>
<priority>2</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//MethodCall[pmd-java:matchesSig('java.util.concurrent.CompletionService#take()')]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public static <T> void collectAllCollectionReplyFromThreads(CompletionService<List<T>> completionService) {
try {
Future<List<T>> futureLocal = completionService.take(); // bad
Future<List<T>> futuresGood = completionService.poll(3, TimeUnit.SECONDS); // good
responseCollector.addAll(futuresGood.get(10, TimeUnit.SECONDS)); // good
} catch (InterruptedException | ExecutionException e) {
LOGGER.error("Error in Thread : {}", e);
} catch (TimeoutException e) {
LOGGER.error("Timeout in Thread : {}", e);
}
}
]]>
</example>