From f74679d350db80c6e8e9e2330e74ebeee375115a Mon Sep 17 00:00:00 2001 From: Irina Batinic <117161143+irina-batinic-sonarsource@users.noreply.github.com> Date: Mon, 13 May 2024 18:34:49 +0200 Subject: [PATCH] SONARJAVA-4951 Replace sonar-java specific verifier with analyzer-commons library (#4786) Use the CheckVerifier provided by the sonar-analyzer-commons testing module instead of the sonar-java-specific implementation to improve testing and allow for better maintanance and updates of the verifier logic. --- docs/CUSTOM_RULES_101.md | 19 +- .../test/files/NoIfStatementInTestsRule.java | 3 +- .../SecurityAnnotationMandatoryRule.java | 6 +- ...ingControllerRequestMappingEntityRule.java | 3 +- .../resources/autoscan/diffs/diff_S1128.json | 4 +- .../resources/autoscan/diffs/diff_S2699.json | 4 +- .../resources/autoscan/diffs/diff_S5786.json | 2 +- .../AwsConsumerBuilderUsageCheckSample.java | 3 +- .../AwsConsumerBuilderUsageCheckSample.java | 3 +- ...tialsShouldBeSetExplicitlyCheckSample.java | 18 +- .../aws/AwsLambdaSyncCallCheckSample.java | 3 +- .../aws/AwsLongTermAccessKeysCheckSample.java | 3 +- .../aws/AwsRegionSetterCheckSample.java | 3 +- ...egionShouldBeSetExplicitlyCheckSample.java | 9 +- ...leResourcesInitializedOnceCheckSample.java | 15 +- ...CredentialsShouldNotBeUsedCheckSample.java | 56 ++- ...ssNoFieldShouldBeInterfaceCheckSample.java | 3 +- ...eldShouldBeInterfaceCheckSample_java9.java | 3 +- .../AccessibilityChangeCheckSample.java | 20 +- .../checks/AllBranchesAreIdentical.java | 3 +- .../AnnotationDefaultArgumentCheckSample.java | 3 +- ...onymousClassShouldBeLambdaCheckSample.java | 4 +- .../checks/ArrayForVarArgCheckSample.java | 2 +- .../checks/CallOuterPrivateMethodCheck.java | 2 +- ...catedCodeFlaggedForRemovalCheck_java9.java | 4 +- .../checks/CastArithmeticOperandCheck.java | 2 +- .../checks/CatchOfThrowableOrErrorCheck.java | 10 +- .../CatchUsesExceptionWithContextCheck.java | 19 +- .../checks/CollapsibleIfCandidateCheck.java | 11 +- .../checks/ConfusingOverloadCheck.java | 2 +- .../DoubleCheckedLockingCheckSample.java | 5 +- .../checks/EnumMutableFieldCheckSample.java | 9 +- ...nicodeCharactersTextBlocksCheckSample.java | 16 +- .../ForLoopFalseConditionCheckSample.java | 3 +- .../GarbageCollectorCalledCheckSample.java | 3 +- .../IdenticalCasesInSwitchCheckSample.java | 4 +- .../checks/IndentationCheck_default.java | 22 +- .../checks/InstanceOfPatternMatching.java | 4 +- .../InterruptedExceptionCheckSample.java | 10 +- .../checks/LazyArgEvaluationCheckSample.java | 2 +- .../checks/LeastSpecificTypeCheckSample.java | 10 +- .../LeftCurlyBraceEndLineCheckSample.java | 2 +- .../LeftCurlyBraceStartLineCheckSample.java | 2 +- .../MapKeyNotComparableCheckSample.java | 6 +- ...MethodWithExcessiveReturnsCheckSample.java | 10 +- .../MissingDeprecatedCheckWithRecords.java | 2 +- .../checks/NestedEnumStatic.java | 4 +- .../NestedSwitchExpressionCheckSample.java | 9 +- .../checks/NoTestInTestClassCheckSample.java | 39 +- .../non-compiling/checks/OSCommandsPath.java | 32 +- .../ObjectFinalizeOverriddenCheckSample.java | 3 +- .../checks/OverrideAnnotationCheckSample.java | 6 +- .../checks/OverrideAnnotationCheck_java8.java | 6 +- .../ParameterReassignedToCheckSample.java | 5 +- .../PrivateFieldUsedLocallyCheckSample.java | 4 +- .../checks/RawTypeCheckSample.java | 3 +- ...RedundantThrowsDeclarationCheckSample.java | 3 +- .../checks/RedundantTypeCastCheckSample.java | 3 +- .../ReplaceGuavaWithJavaCheck_java9.java | 12 +- .../ReplaceLambdaByMethodRefCheckSample.java | 6 +- ...RestrictedIdentifiersUsageCheckSample.java | 9 +- .../checks/RunFinalizersCheckSample.java | 3 +- .../checks/SillyEqualsCheckSample.java | 2 +- .../checks/SimpleClassNameCheckSample.java | 10 +- ...StandardCharsetsConstantsCheck_java10.java | 15 +- .../checks/StaticFieldUpateCheckSample.java | 3 +- .../checks/StaticMemberAccess.java | 2 +- .../StrongCipherAlgorithmCheckSample.java | 2 +- .../checks/SunPackagesUsedCheckCustom.java | 4 +- .../checks/SunPackagesUsedCheckSample.java | 4 +- .../checks/SwitchCaseTooBigCheckSample.java | 7 +- ...asesShouldBeCommaSeparatedCheckSample.java | 13 +- .../SwitchDefaultLastCaseCheckSample.java | 3 +- .../SwitchInsteadOfIfSequenceCheckSample.java | 6 +- .../checks/SwitchWithLabelsCheckSample.java | 3 +- ...hronizationOnStringOrBoxedCheckSample.java | 22 +- .../checks/TextBlockTabsAndSpaces.java | 4 +- .../TextBlocksDuplicatedCheckSample.java | 38 +- .../checks/UselessExtendsCheck.java | 3 +- .../UselessImportCheck/WithinPackage.java | 15 +- .../UselessImportCheck/WithoutPackage.java | 3 +- .../regex/EmptyLineRegexCheckSample.java | 28 +- ...gleCharacterAlternationWithTextBlocks.java | 2 +- .../DebugFeatureEnabledCheckSample.java | 6 +- .../DisableAutoEscapingCheckSample.java | 3 +- ...cessiveContentRequestCheck_spring_2_4.java | 6 +- .../security/PubliclyWritableDirectories.java | 6 +- .../security/UnpredictableSaltCheck.java | 2 +- ...leFieldInSerializableClassCheckSample.java | 3 +- ...gIncompatibleTransactionalCheckSample.java | 2 +- ...nsactionalMethodVisibilityCheckSample.java | 3 +- .../tests/AssertionTypesCheck_JUnit4.java | 2 +- ...toArgumentMatchersUsedOnAllParameters.java | 3 +- .../MockitoEqSimplificationCheckSample.java | 18 +- .../unused/UnusedLocalVariableCheck.java | 3 +- .../ConditionAlwaysTrueOrFalseCheck.java | 26 +- .../checks/InvariantReturnCheckSample.java | 3 +- ...apComputeIfAbsentOrPresentCheckSample.java | 2 +- .../checks/NonNullSetToNullCheckSample.java | 2 +- .../SpringScanDefaultPackageCheckSample.java | 30 +- .../default/src/main/java/WithoutPackage.java | 2 +- ...ssNoFieldShouldBeInterfaceCheckSample.java | 3 +- .../AccessibilityChangeCheckSample.java | 40 +- ...ssibilityChangeCheckWithRecordSupport.java | 24 +- ...cessibilityChangeOnRecordsCheckSample.java | 4 +- .../java/checks/AllBranchesAreIdentical.java | 9 +- .../AnnotationDefaultArgumentCheckSample.java | 6 +- ...onymousClassShouldBeLambdaCheckSample.java | 4 +- .../ArrayDesignatorAfterTypeCheckSample.java | 17 +- .../ArrayDesignatorOnVariableCheckSample.java | 33 +- .../checks/ArrayForVarArgCheckSample.java | 17 +- .../ArrayHashCodeAndToStringCheckSample.java | 15 +- ...sAsListOfPrimitiveToStreamCheckSample.java | 9 +- .../AssertOnBooleanVariableCheckSample.java | 9 +- ...AssertionsInProductionCodeCheckSample.java | 10 +- ...OnParametersOfPublicMethodCheckSample.java | 3 +- .../AssignmentInSubExpressionCheckSample.java | 8 +- .../AtLeastOneConstructorCheckSample.java | 12 +- ...voidHighFrameratesOnMobileCheckSample.java | 3 +- .../src/main/java/checks/BadMethodName.java | 3 +- .../java/checks/BasicAuthCheckSample.java | 5 +- .../checks/BatchSQLStatementsCheckSample.java | 2 +- ...igDecimalDoubleConstructorCheckSample.java | 27 +- ...OperationsInVirtualThreadsCheckSample.java | 4 +- .../BluetoothLowPowerModeCheckSample.java | 6 +- .../checks/BooleanLiteralCheckSample.java | 180 ++++++--- .../BooleanMethodReturnCheckSample.java | 3 +- .../BoxedBooleanExpressionsCheckSample.java | 80 ++-- ...BooleanExpressionsCheckWithQuickFixes.java | 21 +- .../BrainMethodCheckLowerThresholds.java | 3 +- .../java/checks/BrainMethodCheckSample.java | 3 +- .../src/main/java/checks/CORSCheck.java | 32 +- .../checks/CallOuterPrivateMethodCheck.java | 12 +- .../CallSuperMethodFromInnerClassCheck.java | 5 +- .../checks/CallToFileDeleteOnExitMethod.java | 3 +- .../CaseInsensitiveComparisonCheck.java | 27 +- .../checks/CastArithmeticOperandCheck.java | 16 +- ...atchIllegalMonitorStateExceptionCheck.java | 3 +- .../checks/CatchOfThrowableOrErrorCheck.java | 19 +- .../CatchUsesExceptionWithContextCheck.java | 19 +- ...xceptionWithContextCheckAllExceptions.java | 8 +- .../java/checks/ClassComparedByNameCheck.java | 3 +- .../SimpleDefaultCase.java | 3 +- .../checks/CollapsibleIfCandidateCheck.java | 51 ++- .../CollectionConstructorReferenceCheck.java | 9 +- ...llectionImplementationReferencedCheck.java | 54 +-- .../CollectionInappropriateCallsCheck.java | 7 +- .../java/checks/CollectionIsEmptyCheck.java | 42 +- .../CollectionSizeAndArrayLengthCheck.java | 18 +- .../checks/CollectorsToListCheckSample.java | 22 +- .../main/java/checks/CombineCatchCheck.java | 11 +- .../src/main/java/checks/CommentedCode.java | 43 ++- ...mpareStringsBoxedTypesWithEqualsCheck.java | 30 +- .../checks/CompareToNotOverloadedCheck.java | 6 +- .../java/checks/CompareToResultTestCheck.java | 39 +- .../checks/CompareToReturnValueCheck.java | 3 +- .../ConcatenationWithStringValueOfCheck.java | 26 +- .../checks/ConditionalOnNewLineCheck.java | 24 +- .../ConfigurationBeanNamesCheckSample.java | 3 +- .../java/checks/ConfusingOverloadCheck.java | 3 +- .../java/checks/ConfusingVarargCheck.java | 9 +- .../main/java/checks/ConstantMathCheck.java | 6 +- .../main/java/checks/ConstantMethodCheck.java | 17 +- .../ConstantsShouldBeStaticFinalCheck.java | 9 +- .../ControlCharacterInLiteralCheck.java | Bin 3195 -> 3213 bytes ...rolCharacterInLiteralCheckTabsAllowed.java | Bin 3611 -> 3658 bytes ...terInLiteralCheckWithTextBlockSupport.java | 6 +- .../CounterModeIVShouldNotBeReusedCheck.java | 32 +- .../DanglingElseStatementsCheckSample.java | 2 +- .../checks/DateFormatWeekYearCheckSample.java | 54 ++- .../checks/DateTimeFormatterMismatch.java | 40 +- .../checks/DateUtilsTruncateCheckSample.java | 13 +- .../DateUtilsTruncateCheck_no_version.java | 12 +- .../java/checks/DeadStoreCheckSample.java | 44 ++- .../DefaultEncodingUsageCheckSample.java | 18 +- .../DefaultInitializedFieldCheckSample.java | 5 +- .../DeprecatedArgumentsCheckSample.java | 6 +- .../checks/DiamondOperatorCheck_java_7.java | 24 +- .../checks/DiamondOperatorCheck_java_8.java | 36 +- .../DiamondOperatorCheck_no_version.java | 32 +- .../detected_all_overload.java | 3 +- .../checks/DisallowedThreadGroupCheck.java | 5 +- .../DoubleBraceInitializationCheckSample.java | 6 +- .../DoubleCheckedLockingAssignment.java | 10 +- .../DoubleCheckedLockingCheckSample.java | 45 ++- ...DuplicateConditionIfElseIfCheckSample.java | 12 +- .../checks/DynamicClassLoadCheckSample.java | 3 +- .../src/main/java/checks/EmptyFile.java | 3 +- .../java/checks/EmptyFileCheckSample.java | 2 + .../java/checks/EmptyFileMissingNewLine.java | 2 + .../checks/EmptyMethodsCheckNoSemantics.java | 20 +- .../java/checks/EmptyMethodsCheckSample.java | 42 +- .../EmptyStatementUsageCheckOnyStatement.java | 5 +- .../EmptyStatementUsageCheckSample.java | 30 +- .../main/java/checks/EnumMapCheckSample.java | 6 +- .../checks/EnumMutableFieldCheckSample.java | 6 +- .../main/java/checks/EnumSetCheckSample.java | 9 +- .../main/java/checks/EqualsArgumentType.java | 3 +- ...alsNotOverriddenInSubclassCheckSample.java | 3 +- .../EqualsOnAtomicClassCheckSample.java | 3 +- ...alsParametersMarkedNonNullCheckSample.java | 8 +- .../checks/ErrorClassExtendedCheckSample.java | 6 +- .../EscapedUnicodeCharactersCheckSample.java | 9 +- .../ExpressionComplexityCheckCustom.java | 4 +- .../ExpressionComplexityCheckSample.java | 24 +- .../java/checks/FileHeaderCheck/Class1.java | 2 + .../java/checks/FileHeaderCheck/Class2.java | 2 + .../java/checks/FileHeaderCheck/Regex1.java | 2 + .../java/checks/FileHeaderCheck/Regex2.java | 2 + .../java/checks/FileHeaderCheck/Regex4.java | 2 + .../checks/FinalizeFieldsSetCheckSample.java | 3 +- .../checks/FixmeTagPresenceCheckSample.java | 10 +- .../src/main/java/checks/FloatEquality.java | 15 +- .../ForLoopFalseConditionCheckSample.java | 15 +- .../ForLoopIncrementAndUpdateCheckSample.java | 13 +- .../ForLoopVariableTypeCheckSample.java | 3 +- .../GarbageCollectorCalledCheckSample.java | 6 +- .../checks/GetClassLoaderCheckSample.java | 3 +- .../GetRequestedSessionIdCheckSample.java | 3 +- .../checks/HardCodedPasswordCheckCustom.java | 9 +- .../checks/HardCodedPasswordCheckSample.java | 45 ++- .../checks/HardCodedSecretCheckCustom.java | 3 +- .../checks/HardCodedSecretCheckSample.java | 22 +- .../java/checks/HardcodedIpCheckSample.java | 6 +- .../java/checks/HardcodedURICheckSample.java | 20 +- .../checks/HasNextCallingNextCheckSample.java | 3 +- .../java/checks/HiddenFieldCheckSample.java | 7 +- .../IdenticalCasesInSwitchCheckSample.java | 37 +- .../IdenticalOperandOnBinaryExpression.java | 20 +- .../IgnoredStreamReturnValueCheckSample.java | 3 +- .../ImmediateReverseBoxingCheckSample.java | 48 ++- ...mmediatelyReturnedVariableCheckSample.java | 15 +- .../ImplementsEnumerationCheckSample.java | 3 +- .../InappropriateRegexpCheckSample.java | 18 +- .../IncorrectOrderOfMembersCheckSample.java | 12 +- ...ndentationAfterConditionalCheckSample.java | 77 ++-- .../java/checks/IndentationCheck_custom.java | 40 +- .../java/checks/IndentationCheck_tab.java | 2 +- .../checks/IndexOfWithPositiveNumber.java | 3 +- ...nnerClassOfNonSerializableCheckSample.java | 9 +- .../InnerClassOfSerializableCheckSample.java | 6 +- .../InsecureCreateTempFileCheckSample.java | 4 +- ...nsecureCreateTempFileCheck_no_version.java | 5 +- .../checks/InstanceOfPatternMatching.java | 60 ++- .../InstanceofUsedOnExceptionCheckSample.java | 7 +- ...terfaceAsConstantContainerCheckSample.java | 5 +- ...rfaceOrSuperclassShadowingCheckSample.java | 8 +- .../InterruptedExceptionCheckSample.java | 40 +- .../checks/InvalidDateValuesCheckSample.java | 38 +- .../checks/IsInstanceMethodCheckSample.java | 5 +- .../IteratorNextExceptionCheckSample.java | 3 +- .../JacksonDeserializationCheckSample.java | 6 +- .../JdbcDriverExplicitLoadingCheckSample.java | 3 +- ...DriverExplicitLoadingCheck_no_version.java | 3 +- .../checks/JpaEagerFetchTypeCheckSample.java | 3 +- .../java/checks/KeySetInsteadOfEntrySet.java | 3 +- .../LabelsShouldNotBeUsedCheckSample.java | 3 +- .../java/checks/LambdaTooBigCheckCustom.java | 8 +- .../java/checks/LambdaTooBigCheckSample.java | 4 +- .../checks/LazyArgEvaluationCheckSample.java | 56 +-- .../LeftCurlyBraceEndLineCheckSample.java | 44 +-- .../LeftCurlyBraceStartLineCheckSample.java | 5 +- .../LoggedRethrownExceptionsCheckSample.java | 5 +- .../LongBitsToDoubleOnIntCheckSample.java | 3 +- .../MapKeyNotComparableCheckSample.java | 22 +- .../checks/MathClampMethodsCheckSample.java | 8 +- .../checks/MathClampRangeCheckSample.java | 15 +- .../java/checks/MathOnFloatCheckSample.java | 8 +- ...DifferOnlyByCapitalizationCheckSample.java | 57 ++- .../MethodOnlyCallsSuperCheckSample.java | 3 +- .../java/checks/MethodTooBigCheckCustom4.java | 3 +- ...MethodWithExcessiveReturnsCheckCustom.java | 9 +- ...MethodWithExcessiveReturnsCheckSample.java | 17 +- .../main/java/checks/MissingCurlyBraces.java | 18 +- .../checks/MissingDeprecatedCheckJava9.java | 3 +- .../checks/MissingDeprecatedCheckSample.java | 3 +- .../checks/MissingNewLineAtEndOfFile.java | 3 +- ...InRecordWithArrayComponentCheckSample.java | 9 +- ...singPathVariableAnnotationCheckSample.java | 5 +- .../checks/ModifiersOrderCheckSample.java | 11 +- .../ModifiersOrderCheckWithQuickFixes.java | 28 +- .../checks/ModulusEqualityCheckSample.java | 3 +- .../MutableMembersUsageCheckSample.java | 8 +- .../main/java/checks/NPEThrowCheckSample.java | 6 +- .../java/checks/NestedBlocksCheckSample.java | 3 +- .../main/java/checks/NestedEnumStatic.java | 3 +- .../checks/NestedIfStatementsCheckSample.java | 5 +- .../NestedSwitchStatementCheckSample.java | 9 +- .../NestedTernaryOperatorsCheckSample.java | 12 +- .../checks/NestedTryCatchCheckSample.java | 8 +- .../NoCheckstyleTagPresenceCheckSample.java | 10 +- .../checks/NoPmdTagPresenceCheckSample.java | 12 +- .../NonStaticClassInitializerCheckSample.java | 3 +- .../main/java/checks/NotifyCheckSample.java | 3 +- .../NullCheckWithInstanceofCheckSample.java | 9 +- ...ullReturnedOnComputeIfPresentOrAbsent.java | 8 +- ...houldNotBeUsedWithOptionalCheck_guava.java | 33 +- ...lShouldNotBeUsedWithOptionalCheck_jdk.java | 51 ++- .../src/main/java/checks/OSCommandsPath.java | 288 +++++++------- ...tCreatedOnlyToCallGetClassCheckSample.java | 3 +- .../checks/ObjectFinalizeCheckSample.java | 9 +- .../ObjectFinalizeOverriddenCheckSample.java | 3 +- ...verridenCallsSuperFinalizeCheckSample.java | 34 +- ...FinalizeOverridenNotPublicCheckSample.java | 3 +- .../OmitPermittedTypesCheckSample.java | 15 +- ...lassInterfacePerFileCheckNoncompliant.java | 2 + .../OneDeclarationPerLineCheckSample.java | 152 +------- .../OptionalAsParameterCheckSample.java | 25 +- .../OutputStreamOverrideWriteCheckSample.java | 3 +- .../OverrideAnnotationCheck_QuickFixes.java | 18 +- .../checks/PredictableSeedCheckSample.java | 3 +- .../java/checks/PreferStreamAnyMatch.java | 9 +- ...paredStatementAndResultSetCheckSample.java | 11 +- ...aredStatementLoopInvariantCheckSample.java | 30 +- ...eWrappersInTernaryOperatorCheckSample.java | 3 +- .../PrimitivesMarkedNullableCheckSample.java | 13 +- .../java/checks/PrintfFailCheckSample.java | 42 +- .../java/checks/PrintfMisuseCheckSample.java | 78 ++-- .../java/checks/PseudoRandomCheckSample.java | 24 +- ...ConstructorInAbstractClassCheckSample.java | 6 +- ...PublicStaticMutableMembersCheckSample.java | 9 +- .../checks/RandomFloatToIntCheckSample.java | 40 +- .../RawByteBitwiseOperationsCheckSample.java | 18 +- .../java/checks/RawExceptionCheckSample.java | 20 +- .../main/java/checks/RawTypeCheckSample.java | 23 +- .../RecordDuplicatedGetterCheckSample.java | 15 +- .../RecordInsteadOfClassCheckSample.java | 6 +- ...atternInsteadOfFieldAccessCheckSample.java | 12 +- .../checks/RedundantCloseCheckSample.java | 3 +- .../checks/RedundantModifierCheckSample.java | 17 +- .../RedundantRecordMethodsCheckSample.java | 21 +- ...RedundantThrowsDeclarationCheckSample.java | 16 +- .../checks/RedundantTypeCastCheckSample.java | 6 +- ...tionOnNonRuntimeAnnotationCheckSample.java | 3 +- .../ReplaceGuavaWithJavaCheckSample.java | 12 +- .../ReplaceGuavaWithJavaCheck_no_version.java | 3 +- .../ReplaceLambdaByMethodRefCheckSample.java | 86 +++-- ...RestrictedIdentifiersUsageCheckSample.java | 2 +- .../checks/ResultSetIsLastCheckSample.java | 3 +- .../ReturnEmptyArrayNotNullCheckSample.java | 21 +- ...nEmptyArrayNotNullCheckWithQuickFixes.java | 57 ++- ...yNotNullCheckWithQuickFixesAndImports.java | 12 +- .../java/checks/ReuseRandomCheckSample.java | 6 +- ...ReverseSequencedCollectionCheckSample.java | 2 +- ...dMethodSequencedCollectionCheckSample.java | 5 +- ...lyBraceSameLineAsNextBlockCheckSample.java | 11 +- .../checks/S1874_CallToDeprecatedMethod.java | 15 +- .../S1874_CallToDeprecatedMethod_java9.java | 6 +- .../S2201_IgnoredReturnValueCheckSample.java | 7 +- .../ChangeMethodContractCheck.java | 21 +- .../nonNullApi/ChangeMethodContractCheck.java | 7 +- .../ChangeMethodContractCheck.java | 10 +- .../S3749_CustomAnnotations.java | 2 +- .../S3749_DefaultAnnotations.java | 20 +- .../src/main/java/checks/SQLInjection.java | 9 +- ...uledThreadPoolExecutorZeroCheckSample.java | 6 +- .../checks/SelfAssignementCheckSample.java | 29 +- .../ServletInstanceFieldCheckJakarta.java | 8 +- .../ServletInstanceFieldCheckSample.java | 8 +- ...letMethodsExceptionsThrownCheckSample.java | 18 +- .../checks/ShiftOnIntOrLongCheckSample.java | 14 +- .../java/checks/SillyEqualsCheckSample.java | 3 +- .../SillyStringOperationsCheckSample.java | 62 +-- .../checks/SimpleClassNameCheckSample.java | 10 +- ...iteralForSingleLineStringsCheckSample.java | 4 +- ...InsteadOfPatternMatchGuardCheckSample.java | 5 +- .../checks/SingletonUsageCheckSample.java | 14 +- ...alizedFunctionalInterfacesCheckSample.java | 36 +- .../StandardCharsetsConstantsCheckSample.java | 101 +++-- .../checks/StaticFieldUpateCheckSample.java | 3 +- ...icFieldUpdateInConstructorCheckSample.java | 21 +- .../main/java/checks/StaticMemberAccess.java | 2 +- .../checks/StaticMemberAccessQuickFixes.java | 12 +- .../StaticMembersAccessCheckSample.java | 21 +- .../java/checks/StaticMethodCheckSample.java | 41 +- .../StaticMultithreadedUnsafeFields.java | 9 +- .../java/checks/StreamPeekCheckSample.java | 3 +- ...ngBufferAndBuilderWithCharCheckSample.java | 5 +- .../StringConcatToTextBlockCheckSample.java | 12 +- .../StringConcatenationInLoopCheckSample.java | 2 +- .../StringIndexOfRangesCheckSample.java | 30 +- .../StringLiteralDuplicatedCheckSample.java | 6 +- .../StringLiteralInsideEqualsCheckSample.java | 22 +- .../StringMethodsWithLocaleCheckSample.java | 9 +- .../StringOffsetMethodsCheckSample.java | 15 +- ...StringPrimitiveConstructorCheckSample.java | 63 ++- ...tringToPrimitiveConversionCheckSample.java | 3 +- .../src/main/java/checks/StringToString.java | 30 +- .../StrongCipherAlgorithmCheckSample.java | 8 +- .../SubClassStaticReferenceCheckSample.java | 3 +- .../java/checks/SuspiciousListRemove.java | 4 +- .../checks/SwitchCaseTooBigCheckSample.java | 5 +- ...asesShouldBeCommaSeparatedCheckSample.java | 13 +- .../SwitchDefaultLastCaseCheckSample.java | 3 +- .../SwitchInsteadOfIfSequenceCheckSample.java | 10 +- .../SwitchLastCaseIsDefaultCheckSample.java | 3 +- .../SwitchRedundantKeywordCheckSample.java | 17 +- .../SwitchWithTooManyCasesCheckCustom.java | 12 +- .../SwitchWithTooManyCasesCheckSample.java | 3 +- .../SyncGetterAndSetterCheckSample.java | 6 +- ...hronizationOnStringOrBoxedCheckSample.java | 17 +- .../SynchronizedClassUsageCheckSample.java | 63 +-- .../checks/SynchronizedLockCheckSample.java | 3 +- .../SynchronizedOverrideCheckSample.java | 6 +- .../SystemOutOrErrUsageCheckSample.java | 14 +- .../src/main/java/checks/TabCharacter.java | 2 + .../java/checks/TestsInProductionFile.java | 3 +- .../main/java/checks/TextBlockToString.java | 3 +- ...BlocksInComplexExpressionsCheckCustom.java | 2 +- ...BlocksInComplexExpressionsCheckSample.java | 5 +- .../ThreadAsRunnableArgumentCheckSample.java | 17 +- .../main/java/checks/ThreadLocalCleanup.java | 11 +- .../checks/ThreadOverridesRunCheckSample.java | 6 +- .../java/checks/ThreadRunCheckSample.java | 6 +- .../java/checks/ThreadSleepCheckSample.java | 8 +- .../checks/ThreadStartedInConstructor.java | 3 +- .../checks/ThreadWaitCallCheckSample.java | 3 +- .../checks/ThrowsFromFinallyCheckSample.java | 3 +- .../main/java/checks/ToArrayCheckSample.java | 12 +- .../ToStringReturningNullCheckSample.java | 15 +- .../ToStringUsingBoxingCheckSample.java | 27 +- .../checks/TodoTagPresenceCheckSample.java | 14 +- .../LineLengthLinkOrSee.java | 20 +- .../main/java/checks/TooManyLinesOfCode.java | 2 +- .../checks/TooManyMethodsCheckSample.java | 18 +- .../checks/TooManyParametersCheckSample.java | 3 +- .../java/checks/TooManyParametersCustom.java | 4 +- .../checks/TrailingCommentCheckCustom.java | 12 +- .../checks/TrailingCommentCheckSample.java | 4 +- ...ientFieldInNonSerializableCheckSample.java | 3 +- .../checks/TryWithResourcesCheckSample.java | 25 +- ...TryWithResourcesCheck_no_java_version.java | 5 +- .../java/checks/TwoLocksWaitCheckSample.java | 10 +- .../TypeParametersShadowingCheckSample.java | 46 ++- .../TypeUpperBoundNotFinalCheckSample.java | 21 +- .../checks/URLHashCodeAndEqualsCheck.java | 6 +- .../checks/UnnecessaryBitOperationCheck.java | 12 +- .../java/checks/UnreachableCatchCheck.java | 28 +- .../main/java/checks/UnusedPrivateClass.java | 12 +- .../main/java/checks/UnusedPrivateMethod.java | 18 +- ...tionSensorWithoutGyroscopeCheckSample.java | 6 +- .../main/java/checks/UselessExtendsCheck.java | 8 +- .../UselessImportCheck/WithQuickFixes.java | 35 +- .../WithQuickFixesSingleImport.java | 4 +- .../UselessImportCheck/WithinPackage.java | 13 +- .../java/checks/UselessIncrementCheck.java | 6 +- .../packageWithNoOtherFiles/package-info.java | 1 + ...ClassWithPublicConstructorCheckSample.java | 6 +- .../src/main/java/checks/VarArgCheck.java | 6 +- .../main/java/checks/VarCanBeUsedCheck.java | 3 +- ...rtualThreadNotSynchronizedCheckSample.java | 12 +- ...VirtualThreadUnsupportedMethodsSample.java | 15 +- .../VisibleForTestingUsageCheck/Service.java | 9 +- .../VolatileNonPrimitiveFieldCheck.java | 21 +- .../VolatileVariablesOperationsCheck.java | 8 +- .../java/checks/WaitOnConditionCheck.java | 10 +- .../main/java/checks/WeakSSLContextCheck.java | 23 +- .../java/checks/WeakSSLContextCheckJava8.java | 3 +- .../WildcardImportsShouldNotBeUsedCheck.java | 5 +- .../WildcardReturnParameterTypeCheck.java | 9 +- .../checks/WrongAssignmentOperatorCheck.java | 9 +- .../design/ClassImportCouplingCheck.java | 36 +- .../java/checks/emptyclass/EmptyClass.java | 3 +- .../naming/BadClassNameNoncompliant.java | 3 +- .../main/java/checks/naming/BadFieldName.java | 3 +- .../naming/BadInterfaceNameNoncompliant.java | 3 +- .../naming/BadRecordNameNoncompliant.java | 3 +- .../naming/ClassNamedLikeExceptionCheck.java | 6 +- .../FieldNameMatchingTypeNameCheckSample.java | 6 +- ...MethodNamedHashcodeOrEqualCheckSample.java | 6 +- .../regex/AbstractRegexCheckSample.java | 12 +- .../regex/AnchorPrecedenceCheckSample.java | 27 +- .../checks/regex/CanonEqFlagInRegexCheck.java | 11 +- ...DuplicatesInCharacterClassCheckSample.java | 195 +++++++--- .../regex/EmptyLineRegexCheckSample.java | 22 +- .../regex/EmptyRegexGroupCheckSample.java | 34 +- .../EmptyStringRepetitionCheckSample.java | 9 +- ...peSequenceControlCharacterCheckSample.java | 9 +- .../GraphemeClustersInClassesCheckSample.java | 19 +- .../ImpossibleBackReferenceCheckSample.java | 24 +- .../ImpossibleBoundariesCheckSample.java | 70 ++-- .../checks/regex/InvalidRegexCheckSample.java | 16 +- .../regex/MultipleWhitespaceCheckSample.java | 7 +- ...siveQuantifierContinuationCheckSample.java | 31 +- .../java/checks/regex/RedosCheckJava8.java | 9 +- .../java/checks/regex/RedosCheckSample.java | 9 +- ...RedundantRegexAlternativesCheckSample.java | 2 +- .../regex/RegexComplexityCheckSample.java | 21 +- .../RegexComplexityCheckWithThreshold0.java | 30 +- .../RegexComplexityCheckWithThreshold1.java | 14 +- .../regex/RegexLookaheadCheckSample.java | 5 +- ...OverflowCheckWithHighStackConsumption.java | 7 +- .../regex/ReluctantQuantifierCheckSample.java | 106 ++++-- ...ifierWithEmptyContinuationCheckSample.java | 3 +- .../SingleCharCharacterClassCheckSample.java | 16 +- ...SingleCharacterAlternationCheckSample.java | 24 +- .../main/java/checks/regex/StringReplace.java | 6 +- .../SuperfluousCurlyBraceCheckSample.java | 12 +- .../UnicodeAwareCharClassesCheckTest.java | 22 +- .../java/checks/regex/UnicodeCaseCheck.java | 30 +- .../UnquantifiedNonCapturingGroupCheck.java | 15 +- .../checks/regex/UnusedGroupNamesCheck.java | 37 +- .../java/checks/regex/VerboseRegexCheck.java | 29 +- ...BiometricAuthWithoutCryptoCheckSample.java | 6 +- ...bileDatabaseEncryptionKeysCheckSample.java | 4 +- ...droidNonAuthenticatedUsersCheckSample.java | 11 +- ...AndroidUnencryptedDatabaseCheckSample.java | 12 +- .../AndroidUnencryptedFilesCheckSample.java | 9 +- ...horizationsStrongDecisionsCheckSample.java | 6 +- .../security/CipherBlockChainingCheck.java | 17 +- .../checks/security/ClearTextProtocol.java | 15 +- .../checks/security/CookieHttpOnlyCheck.java | 20 +- .../security/CryptographicKeySizeCheck.java | 18 +- .../security/DataHashingCheckSample.java | 6 +- .../DebugFeatureEnabledCheckSample.java | 6 +- .../DisableAutoEscapingCheckSample.java | 9 +- .../DisclosingTechnologyFingerprints.java | 15 +- .../EmptyDatabasePasswordCheckSample.java | 16 +- .../EncryptionAlgorithmCheckSample.java | 25 +- .../ExcessiveContentRequestCheckSample.java | 3 +- ...cessiveContentRequestCheck_max8000000.java | 6 +- ...cessiveContentRequestCheck_sizeNotSet.java | 6 +- .../security/FilePermissionsCheckSample.java | 3 +- .../JWTWithStrongCipherCheckAuth0Test.java | 6 +- .../JWTWithStrongCipherCheckJwtkTest.java | 9 +- .../security/LogConfigurationCheckSample.java | 18 +- .../java/checks/security/PasswordEncoder.java | 4 +- .../security/PubliclyWritableDirectories.java | 20 +- .../security/SecureCookieCheckJakarta.java | 17 +- .../security/SecureCookieCheckSample.java | 28 +- .../ServerCertificatesCheckSample.java | 12 +- .../security/UnpredictableSaltCheck.java | 16 +- .../ApacheCommonEmail.java | 15 +- .../JavaMailSession.java | 5 +- .../WebViewJavaScriptSupportCheck.java | 3 +- .../security/WebViewsFileAccessCheck.java | 12 +- .../checks/security/XxeActiveMQCheck.java | 8 +- .../java/checks/security/ZipEntryCheck.java | 3 +- ...rnalizableClassConstructorCheckSample.java | 15 +- .../NonSerializableWriteCheckSample.java | 3 +- ...erializationIgnoredMembersCheckSample.java | 6 +- .../SerialVersionUidCheckSample.java | 8 +- ...leFieldInSerializableClassCheckSample.java | 9 +- ...erializableObjectInSessionCheckSample.java | 3 +- ...rializableSuperConstructorCheckSample.java | 3 +- .../AsyncMethodsCalledViaThisCheckSample.java | 3 +- ...ethodsOnConfigurationClassCheckSample.java | 3 +- .../AsyncMethodsReturnTypeCheckSample.java | 3 +- ...orWhenMultipleConstructorsCheckSample.java | 3 +- ...iredOnMultipleConstructorsCheckSample.java | 3 +- ...voidQualifierOnBeanMethodsCheckSample.java | 6 +- ...lerWithRestControllerReplacementCheck.java | 17 +- .../ControllerWithSessionAttributesCheck.java | 5 +- ...thodInvocationWithoutProxyCheckSample.java | 9 +- .../FieldDependencyInjectionCheckSample.java | 3 +- ...uteNamingConventionForSpELCheckSample.java | 3 +- ...gletonAutowiredInSingletonCheckSample.java | 22 +- ...eInjectedFieldsHaveDefaultValueSample.java | 8 +- ...OptionalRestParametersShouldBeObjects.java | 15 +- ...tityUsedAsRequestParameterCheckSample.java | 3 +- ...RequestMappingMethodPublicCheckSample.java | 10 +- .../spring/SpelExpressionCheckSample.java | 78 ++-- .../SpringAntMatcherOrderCheckSample.java | 14 +- ...SpringBeanNamingConventionCheckSample.java | 6 +- ...urationWithAutowiredFieldsCheckSample.java | 6 +- ...gIncompatibleTransactionalCheckSample.java | 84 ++-- ...SpringRequestMappingMethodCheckSample.java | 6 +- .../SpringSecurityDisableCSRFCheckSample.java | 15 +- .../SpringSessionFixationCheckSample.java | 11 +- .../StatusCodesOnResponseCheckSample.java | 9 +- ...uousResponseBodyAnnotationCheckSample.java | 3 +- ...nsactionalMethodVisibilityCheckSample.java | 5 +- ...ShouldInjectPropertyOrSpELCheckSample.java | 13 +- .../s4605/componentScan/ComponentScan.java | 5 +- .../componentScan/packageC/ComponentC.java | 3 +- .../s4605/springBootApplication/Ko/Ko.java | 3 +- .../fourthApp/controller/Controller.java | 3 +- .../thirdApp/controller/Controller.java | 3 +- .../AndroidExactAlarmCheckSample.java | 9 +- ...usedLocationProviderClientCheckSample.java | 3 +- .../unused/UnusedLocalVariableCheck.java | 121 ++++-- .../unused/UnusedMethodParameterCheck.java | 42 +- .../unused/UnusedPrivateFieldCheck.java | 48 ++- ...rivateFieldCheckWithIgnoredAnnotation.java | 6 +- .../checks/unused/UnusedThrowableCheck.java | 6 +- .../unused/UnusedTypeParameterCheck.java | 6 +- ...itionAlwaysTrueOrFalseCheckParentLoop.java | 2 +- .../checks/DenialOfServiceXMLCheckSample.java | 6 +- .../checks/DivisionByZeroCheckPrimitives.java | 18 +- .../checks/LocksNotUnlockedCheckCache.java | 12 +- .../checks/LocksNotUnlockedCheckSample.java | 8 +- ...apComputeIfAbsentOrPresentCheckSample.java | 6 +- ...thodInvocationLeadingToDivisionByZero.java | 1 + .../NonNullSetToNullCheckSample.java | 29 +- .../checks/ObjectOutputStreamCheckSample.java | 6 +- ...OptionalGetBeforeIsPresentCheckSample.java | 10 +- ...OptionalGetBeforeIsPresentCheck_jdk11.java | 16 +- .../ParameterNullnessCheckSample.java | 12 +- .../ParameterNullnessCheckSample.java | 9 +- .../checks/PrimitiveUnboxing.java | 45 ++- .../RedundantAssignmentsCheckSample.java | 14 +- ...rocessingCheck_DocumentBuilderFactory.java | 6 +- .../S2755_XxeProcessingCheck_SaxBuilder.java | 3 +- .../S2755_XxeProcessingCheck_SaxReader.java | 5 +- ...XxeProcessingCheck_TransformerFactory.java | 2 +- ...55_XxeProcessingCheck_XmlInputFactory.java | 3 +- .../S3958_StreamNotConsumedCheckSample.java | 4 +- ...InclusionCheck_DocumentBuilderFactory.java | 6 +- ...lowXMLInclusionCheck_SAXParserFactory.java | 5 +- ...llowXMLInclusionCheck_XMLInputFactory.java | 5 +- ...6377_XmlValidatedSignatureCheckSample.java | 9 +- .../XmlParserLoadsExternalSchemasCheck.java | 8 +- .../AssertJApplyConfigurationCheckSample.java | 3 +- ...ssertJAssertionsInConsumerCheckSample.java | 23 +- .../AssertJChainSimplificationCheckTest.java | 59 +-- ...ChainSimplificationCheckTest_QuickFix.java | 54 ++- ...ssertJConsecutiveAssertionCheckSample.java | 36 +- ...ertJContextBeforeAssertionCheckSample.java | 12 +- .../AssertJTestForEmptinessCheckSample.java | 4 +- .../AssertThatThrownByAloneCheckSample.java | 6 +- ...TrueInsteadOfDedicatedAssertCheckTest.java | 4 +- .../AssertionArgumentOrderCheckSample.java | 12 +- .../AssertionArgumentOrderCheck_JUnit5.java | 11 +- ...ssertionArgumentOrderCheck_QuickFixes.java | 35 +- .../AssertionArgumentOrderCheck_TestNG.java | 4 +- .../AssertionCompareToSelfCheck_Assertj.java | 38 +- ...ssertionCompareToSelfCheck_FestAssert.java | 23 +- .../AssertionCompareToSelfCheck_JUnit4.java | 3 +- .../AssertionCompareToSelfCheck_JUnit5.java | 3 +- .../AssertionInThreadRunCheckSample.java | 10 +- .../tests/AssertionInTryCatchCheckSample.java | 8 +- .../tests/AssertionTypesCheck_AssertJ.java | 55 +-- .../tests/AssertionTypesCheck_JUnit4.java | 49 +-- .../tests/AssertionTypesCheck_JUnit5.java | 39 +- .../AssertionsCompletenessCheckSample.java | 9 +- .../tests/AssertionsInTestsCheck/AssertJ.java | 2 +- .../tests/AssertionsInTestsCheck/Junit4.java | 3 +- .../AssertionsInTestsCheck/Selenide.java | 3 +- .../SpringBootSanityJ4Test.java | 2 +- .../SpringBootSanityTestSample.java | 2 +- .../AssertionsWithoutMessageCheckSample.java | 19 +- ...nOrNullLiteralInAssertionsCheckSample.java | 18 +- .../tests/CallSuperInTestCaseCheck.java | 3 +- .../tests/ExpectedExceptionCheckSample.java | 5 +- .../checks/tests/IgnoredTestsCheckSample.java | 10 +- .../JUnit45MethodAnnotationCheckSample.java | 7 +- .../tests/JUnit4AnnotationsCheckTest.java | 3 +- ...faultPackageClassAndMethodCheckSample.java | 12 +- ...lentlyIgnoreClassAndMethodCheckSample.java | 31 +- ...JUnitCompatibleAnnotationsCheckSample.java | 7 +- .../JunitNestedAnnotationCheckSample.java | 3 +- .../checks/tests/MockingAllMethodsCheck.java | 38 +- ...toAnnotatedObjectsShouldBeInitialized.java | 2 +- ...toArgumentMatchersUsedOnAllParameters.java | 23 +- .../MockitoEqSimplificationCheckSample.java | 18 +- .../NoTestInTestClassCheckArchUnitTest.java | 14 +- .../tests/NoTestInTestClassCheckEnclosed.java | 30 +- .../NoTestInTestClassCheckNoClasspath.java | 3 +- .../tests/NoTestInTestClassCustomPattern.java | 12 +- .../NoTestsInTestClassCheckPactTest.java | 3 +- ...neExpectedCheckedExceptionCheckSample.java | 17 +- ...neExpectedRuntimeExceptionCheckSample.java | 17 +- .../tests/ParameterizedTestCheckSample.java | 33 +- .../tests/RandomizedTestDataCheckSample.java | 43 ++- ...ngAssertionsSimplificationCheckSample.java | 9 +- ...ationWithExpectedExceptionCheckSample.java | 5 +- .../tests/TestStabilityCheckSample.java | 3 +- .../tests/ThreadSleepInTestsCheckSample.java | 12 +- .../tests/TooManyAssertionsCheckCustom2.java | 12 +- .../tests/TooManyAssertionsCheckCustom25.java | 3 +- .../checks/tests/UnusedTestRuleCheck.java | 5 +- .../tests/UnusedTestRuleCheck_JUnit5.java | 15 +- .../checks/WeakSSLContextCheckSample.java | 9 +- java-checks-testkit/pom.xml | 5 + .../java/checks/verifier/CheckVerifier.java | 117 +++--- .../verifier/internal/CheckVerifierUtils.java | 90 +++++ .../internal/InternalCheckVerifier.java | 62 +-- .../verifier/internal/JavaCheckVerifier.java | 360 ++++++++++++++++++ .../CommonsJavaCheckVerifier.java | 22 ++ .../CommonsJavaCheckVerifierOnFile.java | 7 + .../checks/verifier/CheckVerifierTest.java | 141 +++++-- .../internal/CheckVerifierTestUtils.java | 201 ++++++++++ .../internal/InternalCheckVerifierTest.java | 179 +-------- .../internal/JavaCheckVerifierTest.java | 292 ++++++++++++++ .../src/test/files/checks/AbsOnNegative.java | 6 +- ...stractClassWithoutAbstractMethodCheck.java | 6 +- .../src/test/files/checks/Architecture.java | 3 +- .../test/files/checks/ArchitectureSelf.java | 2 +- .../AssertionFailInCatchBlockCheck.java | 27 +- .../files/checks/BooleanInversionCheck.java | 14 +- .../files/checks/CatchExceptionCheck.java | 3 +- .../src/test/files/checks/CatchNPECheck.java | 6 +- .../files/checks/CatchRethrowingCheck.java | 5 +- .../files/checks/ChildClassShadowField.java | 3 +- .../test/files/checks/ClassCouplingCheck.java | 5 +- .../CountOnlyPublicFields.java | 3 +- .../ClassFieldCountCheck/UnusualTrees.java | 9 +- .../checks/ClassVariableVisibilityCheck.java | 3 +- ...thOnlyStaticMethodsInstantiationCheck.java | 6 +- .../CloneMethodCallsSuperCloneCheck.java | 3 +- .../test/files/checks/CloneOverrideCheck.java | 9 +- .../CognitiveComplexityMethodCheckMax0.java | 33 +- .../checks/CollectionCallingItselfCheck.java | 3 +- ...onInappropriateCallsCheckUnknownTypes.java | 2 +- ...CollectionMethodsWithLinearComplexity.java | 3 +- .../checks/CollectionsEmptyConstants.java | 3 +- .../checks/CommentRegularExpressionCheck.java | 8 +- .../ConstructorCallingOverridableCheck.java | 2 +- .../CustomCryptographicAlgorithmCheck.java | 8 +- .../CustomSerializationMethodCheck.java | 9 +- .../test/files/checks/DateAndTimesCheck.java | 2 +- .../checks/DeprecatedTagPresenceCheck.java | 6 +- .../files/checks/DisallowedClassCheck.java | 36 +- .../DisallowedClassCheckAnnotation.java | 6 +- .../checks/DisallowedClassCheckRegex.java | 33 +- .../DisallowedConstructorCheck/detected.java | 3 +- .../DisallowedMethodCheck/detected.java | 3 +- .../DoubleBraceInitializationCheck.java | 6 +- .../DoublePrefixOperatorCheck.java | 31 +- .../src/test/files/checks/EmptyBlock.java | 25 +- .../src/test/files/checks/EnumEqualCheck.java | 6 +- .../EqualsNotOverridenWithCompareToCheck.java | 9 +- .../EqualsOverridenWithHashCodeCheck.java | 6 +- .../ExceptionsShouldBeImmutableCheck.java | 6 +- .../src/test/files/checks/FieldModifier.java | 3 +- .../files/checks/FilesExistsJDK8Check.java | 3 +- .../test/files/checks/FinalClassCheck.java | 2 +- .../checks/ForLoopCounterChangedCheck.java | 31 +- .../checks/ForLoopIncrementSignCheck.java | 6 +- .../ForLoopTerminationConditionCheck.java | 4 +- .../checks/ForLoopUsedAsWhileLoopCheck.java | 3 +- .../checks/GettersSettersOnRightField.java | 4 +- .../IfElseIfStatementEndsWithElseCheck.java | 13 +- .../checks/IgnoredOperationStatusCheck.java | 9 +- ...ncrementDecrementInSubExpressionCheck.java | 3 +- .../checks/InnerStaticClassesCheckSample.java | 3 +- .../checks/InputStreamOverrideReadCheck.java | 3 +- .../LambdaOptionalParenthesisCheck.java | 3 +- ...ambdaSingleExpressionCheck_no_version.java | 3 +- .../checks/LambdaTypeParameterCheck.java | 12 +- .../files/checks/LoggersDeclarationCheck.java | 3 +- .../checks/LoopExecutingAtMostOnceCheck.java | 12 +- .../files/checks/LoopsOnSameSetCheck.java | 7 +- .../test/files/checks/MagicNumberCheck.java | 15 +- .../files/checks/MagicNumberCheckCustom.java | 3 +- .../MainMethodThrowsExceptionCheck.java | 3 +- .../MethodComplexityJavaLangPackage.java | 12 +- .../checks/MethodComplexityNoncompliant.java | 12 +- .../MethodIdenticalImplementationsCheck.java | 13 +- .../checks/MethodParametersOrderCheck.java | 9 +- .../checks/MissingBeanValidationCheck.java | 9 +- .../MultilineBlocksCurlyBracesCheck.java | 16 +- .../test/files/checks/NioFileDeleteCheck.java | 2 +- .../src/test/files/checks/NoSonar.java | 1 + .../checks/NonShortCircuitLogicCheck.java | 3 +- .../checks/ObjectFinalizeOverloadedCheck.java | 3 +- .../test/files/checks/OctalValuesCheck.java | 3 +- .../test/files/checks/OperatorPrecedence.java | 9 +- .../files/checks/OverwrittenKeyCheck.java | 30 +- .../PACKAGE/BadPackageNameNoncompliant.java | 3 +- .../PrimitiveTypeBoxingWithToStringCheck.java | 6 +- .../ProtectedMemberInFinalClassCheck.java | 3 +- .../PublicStaticFieldShouldBeFinalCheck.java | 3 +- .../checks/RedundantStreamCollectCheck.java | 4 +- .../files/checks/RepeatAnnotationCheck.java | 3 +- .../RepeatAnnotationCheck_no_version.java | 2 +- ...ReplaceGuavaWithJava8Check_no_version.java | 3 +- .../files/checks/ReturnInFinallyCheck.java | 12 +- .../ReturnOfBooleanExpressionsCheck.java | 3 +- ...rlyBraceDifferentLineAsNextBlockCheck.java | 5 +- .../checks/RightCurlyBraceStartLineCheck.java | 41 +- .../checks/SelectorMethodArgumentCheck.java | 5 +- .../SeveralBreakOrContinuePerLoopCheck.java | 16 +- .../SpringConstructorInjectionCheck.java | 9 +- .../StaticFieldInitializationCheck.java | 5 +- .../MixedStandardAndStaticImports.java | 10 +- ...andardAndStaticImportsCustomThreshold.java | 16 +- .../StaticImportCountCheck.java | 10 +- .../checks/StaticMembersAccessCheck.java | 6 +- .../checks/StringCallsBeyondBoundsCheck.java | 62 +-- .../checks/SuppressWarningsCheck/test1.java | 20 +- .../checks/SwitchAtLeastThreeCasesCheck.java | 3 +- .../checks/SwitchCaseWithoutBreakCheck.java | 18 +- .../files/checks/SymmetricEqualsCheck.java | 17 +- .../SynchronizationOnGetClassCheck.java | 18 +- .../SynchronizedFieldAssignmentCheck.java | 3 +- .../files/checks/SystemExitCalledCheck.java | 8 +- .../test/files/checks/TernaryOperator.java | 3 +- .../ThisExposedFromConstructorCheck.java | 2 +- .../checks/ThreadLocalWithInitialCheck.java | 3 +- .../checks/ThrowCheckedExceptionCheck.java | 3 +- .../checks/ThrowsSeveralCheckedException.java | 3 +- .../UndocumentedApiCheck/UndocumentedApi.java | 16 +- .../UndocumentedApiIncomplete.java | 24 +- .../checks/UnnecessarySemicolonCheck.java | 6 +- .../files/checks/UppercaseSuffixesCheck.java | 3 +- .../UppercaseSuffixesCheckOnlyLong.java | 3 +- .../checks/UseSwitchExpressionCheck.java | 6 +- .../files/checks/UselessParenthesesCheck.java | 9 +- ...asedObjectsShouldNotBeSerializedCheck.java | 27 +- .../checks/VariableDeclarationScopeCheck.java | 3 +- .../files/checks/WaitInSynchronizeCheck.java | 7 +- .../files/checks/WaitInWhileLoopCheck.java | 3 +- .../mismatchPackage/DefaultPackage.java | 2 +- .../checks/mismatchPackage/Matching.java | 2 +- .../checks/mismatchPackage/Mismatch.java | 3 +- .../naming/BadConstantNameNoncompliant.java | 3 +- .../naming/BadFieldNameStaticNonFinal.java | 3 +- .../naming/BadGenericNameNoncompliant.java | 3 +- .../BadLocalVariableNameNoncompliant.java | 3 +- .../naming/KeywordAsIdentifierCheck.java | 8 +- .../KeywordAsIdentifierCheck_java1.java | 5 +- .../naming/MethodNameSameAsClassCheck.java | 3 +- .../checks/naming/MethodNamedEqualsCheck.java | 3 +- .../files/checks/parsing/ParsingError.java | 2 +- .../BlindSerialVersionUidCheck.java | 3 +- .../PrivateReadResolveCheck.java | 4 +- .../SerializableComparatorCheck.java | 3 +- .../SpringComponentWithWrongScopeCheck.java | 9 +- .../SpringComposedRequestMappingCheck.java | 3 +- .../files/checks/unused/UnusedLabelCheck.java | 3 +- .../checks/unused/UnusedReturnedData.java | 6 +- .../ArrayDesignatorAfterTypeCheckTest.java | 5 +- .../ArrayDesignatorOnVariableCheckTest.java | 5 +- .../ArrayHashCodeAndToStringCheckTest.java | 5 +- .../BigDecimalDoubleConstructorCheckTest.java | 5 +- .../java/checks/BooleanLiteralCheckTest.java | 5 +- .../BoxedBooleanExpressionsCheckTest.java | 4 +- .../CollapsibleIfCandidateCheckTest.java | 4 +- ...tionImplementationReferencedCheckTest.java | 5 +- .../checks/CollectionIsEmptyCheckTest.java | 4 +- .../java/checks/CombineCatchCheckTest.java | 10 +- ...eStringsBoxedTypesWithEqualsCheckTest.java | 6 +- .../checks/CompareToResultTestCheckTest.java | 4 +- ...ncatenationWithStringValueOfCheckTest.java | 4 +- .../checks/DateFormatWeekYearCheckTest.java | 4 +- .../java/checks/DefaultPackageCheckTest.java | 2 +- .../java/checks/DiamondOperatorCheckTest.java | 4 +- .../sonar/java/checks/EmptyFileCheckTest.java | 4 +- .../java/checks/EmptyMethodsCheckTest.java | 8 +- .../checks/EmptyStatementUsageCheckTest.java | 8 +- ...qualsParametersMarkedNonNullCheckTest.java | 4 +- .../java/checks/FileHeaderCheckTest.java | 12 +- .../ImmediateReverseBoxingCheckTest.java | 6 +- .../ImmediatelyReturnedVariableCheckTest.java | 4 +- .../java/checks/MathClampRangeCheckTest.java | 30 +- .../MissingNewLineAtEndOfFileCheckTest.java | 18 +- .../checks/MissingPackageInfoCheckTest.java | 6 +- .../java/checks/ModifiersOrderCheckTest.java | 4 +- .../sonar/java/checks/NotifyCheckTest.java | 5 +- .../checks/OmitPermittedTypesCheckTest.java | 4 +- .../OneClassInterfacePerFileCheckTest.java | 2 +- .../OneDeclarationPerLineCheckTest.java | 5 +- .../checks/OverrideAnnotationCheckTest.java | 6 +- .../checks/PatternMatchUsingIfCheckTest.java | 7 +- .../PrimitivesMarkedNullableCheckTest.java | 4 +- .../PrivateFieldUsedLocallyCheckTest.java | 4 +- .../RedundantThrowsDeclarationCheckTest.java | 7 +- .../checks/RedundantTypeCastCheckTest.java | 9 +- .../ReplaceLambdaByMethodRefCheckTest.java | 9 +- .../ReturnEmptyArrayNotNullCheckTest.java | 7 +- ...urlyBraceSameLineAsNextBlockCheckTest.java | 5 +- .../java/checks/SelfAssignementCheckTest.java | 5 +- ...IfInsteadOfPatternMatchGuardCheckTest.java | 5 +- .../StandardCharsetsConstantsCheckTest.java | 15 +- .../checks/StaticMemberAccessCheckTest.java | 6 +- .../checks/StaticMembersAccessCheckTest.java | 5 +- .../java/checks/StaticMethodCheckTest.java | 6 +- .../StringLiteralInsideEqualsCheckTest.java | 11 +- .../StringPrimitiveConstructorCheckTest.java | 5 +- .../java/checks/StringToStringCheckTest.java | 8 +- .../SynchronizedClassUsageCheckTest.java | 3 +- .../java/checks/TabCharacterCheckTest.java | 2 +- .../checks/ThreadLocalCleanupCheckTest.java | 6 +- .../sonar/java/checks/ThreadRunCheckTest.java | 5 +- .../sonar/java/checks/ToArrayCheckTest.java | 5 +- .../ToStringReturningNullCheckTest.java | 5 +- .../checks/ToStringUsingBoxingCheckTest.java | 5 +- .../java/checks/UselessImportCheckTest.java | 9 +- .../checks/UselessPackageInfoCheckTest.java | 6 +- ...VirtualThreadNotSynchronizedCheckTest.java | 9 +- ...tualThreadUnsupportedMethodsCheckTest.java | 8 +- .../checks/design/BrainMethodCheckTest.java | 16 +- ...cMethodsOnConfigurationClassCheckTest.java | 5 +- .../AvoidQualifierOnBeanMethodsCheckTest.java | 4 +- ...ithRestControllerReplacementCheckTest.java | 5 +- ...jectedFieldsHaveDefaultValueCheckTest.java | 5 +- .../AssertJChainSimplificationCheckTest.java | 4 +- .../AssertionArgumentOrderCheckTest.java | 5 +- ...DefaultPackageClassAndMethodCheckTest.java | 4 +- ...SilentlyIgnoreClassAndMethodCheckTest.java | 9 +- .../unused/UnusedLocalVariableCheckTest.java | 4 +- .../UnusedMethodParameterCheckTest.java | 9 +- .../unused/UnusedPrivateFieldCheckTest.java | 9 +- .../unused/UnusedPrivateMethodCheckTest.java | 6 +- .../unused/UnusedThrowableCheckTest.java | 4 +- .../ast/visitors/CommentLinesVisitor.java | 18 +- .../org/sonar/java/se/SECheckVerifier.java | 2 +- pom.xml | 4 +- 899 files changed, 8164 insertions(+), 4648 deletions(-) create mode 100644 java-checks-test-sources/default/src/main/java/checks/EmptyFileCheckSample.java create mode 100644 java-checks-test-sources/default/src/main/java/checks/EmptyFileMissingNewLine.java create mode 100644 java-checks-testkit/src/main/java/org/sonar/java/checks/verifier/internal/CheckVerifierUtils.java create mode 100644 java-checks-testkit/src/main/java/org/sonar/java/checks/verifier/internal/JavaCheckVerifier.java create mode 100644 java-checks-testkit/src/test/files/java-check-verifier/CommonsJavaCheckVerifier.java create mode 100644 java-checks-testkit/src/test/files/java-check-verifier/CommonsJavaCheckVerifierOnFile.java create mode 100644 java-checks-testkit/src/test/java/org/sonar/java/checks/verifier/internal/CheckVerifierTestUtils.java create mode 100644 java-checks-testkit/src/test/java/org/sonar/java/checks/verifier/internal/JavaCheckVerifierTest.java diff --git a/docs/CUSTOM_RULES_101.md b/docs/CUSTOM_RULES_101.md index b32fee2959e..b98c6e64599 100644 --- a/docs/CUSTOM_RULES_101.md +++ b/docs/CUSTOM_RULES_101.md @@ -682,14 +682,25 @@ See: [pom.xml#L137-L197](./java-custom-rules-example/pom_SQ_9_9_LTS.xml#L137-L19 You can raise an issue on a given line, but you can also raise it at a specific Token. Because of that, you may want to specify, in your sample code used by your Unit Tests, the exact location, i.e. in between which 2 specific Columns, where you are expecting the issue to be raised. -This can be achieved using the special keywords `sc` (start-column) and `ec` (end-column) in the `// Noncompliant` comment. -In the following example, we are expecting to have the issue being raised between the columns 27 and 32 (i.e. exactly on the "Order" variable type): - +> **Deprecated** +> +>This can be achieved using the special keywords `sc` (start-column) and `ec` (end-column) in the `// Noncompliant` comment. +>In the following example, we are expecting to have the issue being raised between the columns 27 and 32 (i.e. exactly on the "Order" variable type): +> ```java +> public String updateOrder(Order order){ // Noncompliant [[sc=27;ec=32]] {{Don't use Order here because it's an @Entity}} +> // ... +> } +> ``` + +Assert precise primary location of an issue with the comment on a line below containing required number of `^`. ```java -public String updateOrder(Order order){ // Noncompliant [[sc=27;ec=32]] {{Don't use Order here because it's an @Entity}} +public String updateOrder(Order order){ // Noncompliant {{Don't use Order here because it's an @Entity}} +// ^^^^^ // ... } ``` +More information on how to test precise issue location can be found in: [SonarSource Analyzer Test Commons](https://github.com/SonarSource/sonar-analyzer-commons/tree/master/test-commons) library. + ### How to test the Source Version in a rule diff --git a/docs/java-custom-rules-example/src/test/files/NoIfStatementInTestsRule.java b/docs/java-custom-rules-example/src/test/files/NoIfStatementInTestsRule.java index 206480690b8..e24207d7fe8 100644 --- a/docs/java-custom-rules-example/src/test/files/NoIfStatementInTestsRule.java +++ b/docs/java-custom-rules-example/src/test/files/NoIfStatementInTestsRule.java @@ -9,7 +9,8 @@ public class ATest { @Test public void myTest() { - if (someCondition) { // Noncompliant [[sc=5;ec=7]] {{Remove this 'if' statement from this test.}} + if (someCondition) { // Noncompliant {{Remove this 'if' statement from this test.}} +// ^^ // verify something } } diff --git a/docs/java-custom-rules-example/src/test/files/SecurityAnnotationMandatoryRule.java b/docs/java-custom-rules-example/src/test/files/SecurityAnnotationMandatoryRule.java index 2a1de87f05b..4e78ba92919 100644 --- a/docs/java-custom-rules-example/src/test/files/SecurityAnnotationMandatoryRule.java +++ b/docs/java-custom-rules-example/src/test/files/SecurityAnnotationMandatoryRule.java @@ -12,10 +12,12 @@ class BusinessClassDelegate implements MySecurityInterface, SecondInterface { public void aMethod() { } @org.foo.MyOtherSecurityAnnotation - public void anotherMethod() { } // Noncompliant [[sc=15;ec=28]] {{Mandatory Annotation not set @MySecurityAnnotation}} + public void anotherMethod() { } // Noncompliant {{Mandatory Annotation not set @MySecurityAnnotation}} +// ^^^^^^^^^^^^^ @VariousAnnotation - public void differentMethod() { } // Noncompliant [[startColumn=15;endColumn=30]] {{Mandatory Annotation not set @MySecurityAnnotation}} + public void differentMethod() { } // Noncompliant {{Mandatory Annotation not set @MySecurityAnnotation}} +// ^^^^^^^^^^^^^^^ } class OtherClass implements FirstInterface, SecondInterface { diff --git a/docs/java-custom-rules-example/src/test/files/SpringControllerRequestMappingEntityRule.java b/docs/java-custom-rules-example/src/test/files/SpringControllerRequestMappingEntityRule.java index f7c3c9ae102..6e2da507583 100644 --- a/docs/java-custom-rules-example/src/test/files/SpringControllerRequestMappingEntityRule.java +++ b/docs/java-custom-rules-example/src/test/files/SpringControllerRequestMappingEntityRule.java @@ -6,7 +6,8 @@ public class HelloController { @RequestMapping("/updateOrder") - public String updateOrder(Order order, Client client) { // Noncompliant [[sc=29;ec=34]] {{Don't use Order here because it's an @Entity}} + public String updateOrder(Order order, Client client) { // Noncompliant {{Don't use Order here because it's an @Entity}} +// ^^^^^ return null; } diff --git a/its/autoscan/src/test/resources/autoscan/diffs/diff_S1128.json b/its/autoscan/src/test/resources/autoscan/diffs/diff_S1128.json index b1c359a59f5..e7b8f371752 100644 --- a/its/autoscan/src/test/resources/autoscan/diffs/diff_S1128.json +++ b/its/autoscan/src/test/resources/autoscan/diffs/diff_S1128.json @@ -1,6 +1,6 @@ { "ruleKey": "S1128", "hasTruePositives": true, - "falseNegatives": 34, + "falseNegatives": 33, "falsePositives": 0 -} +} \ No newline at end of file diff --git a/its/autoscan/src/test/resources/autoscan/diffs/diff_S2699.json b/its/autoscan/src/test/resources/autoscan/diffs/diff_S2699.json index d361a3c2311..cfb1224504f 100644 --- a/its/autoscan/src/test/resources/autoscan/diffs/diff_S2699.json +++ b/its/autoscan/src/test/resources/autoscan/diffs/diff_S2699.json @@ -1,6 +1,6 @@ { "ruleKey": "S2699", "hasTruePositives": true, - "falseNegatives": 151, + "falseNegatives": 150, "falsePositives": 1 -} +} \ No newline at end of file diff --git a/its/autoscan/src/test/resources/autoscan/diffs/diff_S5786.json b/its/autoscan/src/test/resources/autoscan/diffs/diff_S5786.json index 2bc5bf8b703..ef535f3f85e 100644 --- a/its/autoscan/src/test/resources/autoscan/diffs/diff_S5786.json +++ b/its/autoscan/src/test/resources/autoscan/diffs/diff_S5786.json @@ -1,6 +1,6 @@ { "ruleKey": "S5786", "hasTruePositives": true, - "falseNegatives": 63, + "falseNegatives": 62, "falsePositives": 0 } \ No newline at end of file diff --git a/java-checks-test-sources/aws/src/main/files/non-compiling/checks/aws/AwsConsumerBuilderUsageCheckSample.java b/java-checks-test-sources/aws/src/main/files/non-compiling/checks/aws/AwsConsumerBuilderUsageCheckSample.java index 65516b8e96a..66050a9e342 100644 --- a/java-checks-test-sources/aws/src/main/files/non-compiling/checks/aws/AwsConsumerBuilderUsageCheckSample.java +++ b/java-checks-test-sources/aws/src/main/files/non-compiling/checks/aws/AwsConsumerBuilderUsageCheckSample.java @@ -7,7 +7,8 @@ public class AwsConsumerBuilderUsageCheckSample { public void test() { AwsConsumerBuilderUsageCheckSample.builder() - .validDestination(Destination.builder() // Noncompliant [[sc=8;ec=24]] {{Consider using the Consumer Builder method instead of creating this nested builder.}} + .validDestination(Destination.builder() // Noncompliant {{Consider using the Consumer Builder method instead of creating this nested builder.}} +// ^^^^^^^^^^^^^^^^ .toAddresses("to-email@domain.com") .bccAddresses("bcc-email@domain.com") .build()) diff --git a/java-checks-test-sources/aws/src/main/java/checks/aws/AwsConsumerBuilderUsageCheckSample.java b/java-checks-test-sources/aws/src/main/java/checks/aws/AwsConsumerBuilderUsageCheckSample.java index 5097e5c1dc2..6c010b48877 100644 --- a/java-checks-test-sources/aws/src/main/java/checks/aws/AwsConsumerBuilderUsageCheckSample.java +++ b/java-checks-test-sources/aws/src/main/java/checks/aws/AwsConsumerBuilderUsageCheckSample.java @@ -18,7 +18,8 @@ public class AwsConsumerBuilderUsageCheckSample { void test_destination(Destination destination1) { software.amazon.awssdk.services.sesv2.model.SendEmailRequest.builder() - .destination(Destination.builder() // Noncompliant [[sc=8;ec=19]] {{Consider using the Consumer Builder method instead of creating this nested builder.}} + .destination(Destination.builder() // Noncompliant {{Consider using the Consumer Builder method instead of creating this nested builder.}} +// ^^^^^^^^^^^ .toAddresses("to-email@domain.com") .bccAddresses("bcc-email@domain.com") .build()) diff --git a/java-checks-test-sources/aws/src/main/java/checks/aws/AwsCredentialsShouldBeSetExplicitlyCheckSample.java b/java-checks-test-sources/aws/src/main/java/checks/aws/AwsCredentialsShouldBeSetExplicitlyCheckSample.java index 1b2f39166a3..414384593f1 100644 --- a/java-checks-test-sources/aws/src/main/java/checks/aws/AwsCredentialsShouldBeSetExplicitlyCheckSample.java +++ b/java-checks-test-sources/aws/src/main/java/checks/aws/AwsCredentialsShouldBeSetExplicitlyCheckSample.java @@ -12,22 +12,28 @@ public class AwsCredentialsShouldBeSetExplicitlyCheckSample { public static final AwsClientBuilder BUILDER = S3Client.builder(); // Compliant FN - Could be configured closer to build call void nonCompliant() { - S3Client.builder().build(); // Noncompliant [[sc=5;ec=31]] {{Set the credentials provider explicitly on this builder.}} - S3Client client = S3Client.builder().build(); // Noncompliant [[sc=23;ec=49]] {{Set the credentials provider explicitly on this builder.}} - S3Client otherClient = S3Client.builder() // Noncompliant [[sl=+0;sc=28;el=+2;ec=15]] {{Set the credentials provider explicitly on this builder.}} + S3Client.builder().build(); // Noncompliant {{Set the credentials provider explicitly on this builder.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^ + S3Client client = S3Client.builder().build(); // Noncompliant {{Set the credentials provider explicitly on this builder.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^ + S3Client otherClient = S3Client.builder() // Noncompliant {{Set the credentials provider explicitly on this builder.}} + //^[sc=28;ec=14;el=+3] .region(Region.of(System.getenv(SdkSystemSetting.AWS_REGION.environmentVariable()))) .build(); } void nonCompliantBuilderAsVariable() { - S3ClientBuilder builder = S3Client.builder(); // Noncompliant [[sc=5;ec=50]] {{Set the credentials provider explicitly on this builder.}} + S3ClientBuilder builder = S3Client.builder(); // Noncompliant {{Set the credentials provider explicitly on this builder.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ builder.build(); - S3ClientBuilder secondBuilder = S3Client.builder(); // Noncompliant [[sc=5;ec=56]] {{Set the credentials provider explicitly on this builder.}} + S3ClientBuilder secondBuilder = S3Client.builder(); // Noncompliant {{Set the credentials provider explicitly on this builder.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ secondBuilder.region(Region.of(System.getenv(SdkSystemSetting.AWS_REGION.environmentVariable()))); secondBuilder.build(); - S3ClientBuilder thirdBuilder = S3Client.builder() // Noncompliant [[sl=+0;sc=5;el=+1;ec=92]] {{Set the credentials provider explicitly on this builder.}} + S3ClientBuilder thirdBuilder = S3Client.builder() // Noncompliant {{Set the credentials provider explicitly on this builder.}} + //^[sc=5;ec=91;el=+2] .region(Region.of(System.getenv(SdkSystemSetting.AWS_REGION.environmentVariable()))); thirdBuilder.build(); } diff --git a/java-checks-test-sources/aws/src/main/java/checks/aws/AwsLambdaSyncCallCheckSample.java b/java-checks-test-sources/aws/src/main/java/checks/aws/AwsLambdaSyncCallCheckSample.java index fa8f7d3a5db..3b1e4c6c3c9 100644 --- a/java-checks-test-sources/aws/src/main/java/checks/aws/AwsLambdaSyncCallCheckSample.java +++ b/java-checks-test-sources/aws/src/main/java/checks/aws/AwsLambdaSyncCallCheckSample.java @@ -44,7 +44,8 @@ public Void handleRequest(Object o, Context context) { .withCredentials(new ProfileCredentialsProvider()) .withRegion(Regions.US_WEST_2).build(); - awsLambda.invoke(invokeRequest); // Noncompliant [[sc=17;ec=23]] {{Avoid synchronous calls to other lambdas.}} + awsLambda.invoke(invokeRequest); // Noncompliant {{Avoid synchronous calls to other lambdas.}} +// ^^^^^^ invokeSync(); invokeAsync(); diff --git a/java-checks-test-sources/aws/src/main/java/checks/aws/AwsLongTermAccessKeysCheckSample.java b/java-checks-test-sources/aws/src/main/java/checks/aws/AwsLongTermAccessKeysCheckSample.java index 76c61c31bf5..d680c8d878b 100644 --- a/java-checks-test-sources/aws/src/main/java/checks/aws/AwsLongTermAccessKeysCheckSample.java +++ b/java-checks-test-sources/aws/src/main/java/checks/aws/AwsLongTermAccessKeysCheckSample.java @@ -5,7 +5,8 @@ public class AwsLongTermAccessKeysCheckSample { void noncompliant() { - BasicAWSCredentials foo = new BasicAWSCredentials("", ""); // Noncompliant [[sc=35;ec=54]] {{Make sure using a long-term access key is safe here.}} + BasicAWSCredentials foo = new BasicAWSCredentials("", ""); // Noncompliant {{Make sure using a long-term access key is safe here.}} +// ^^^^^^^^^^^^^^^^^^^ } void compliant() { diff --git a/java-checks-test-sources/aws/src/main/java/checks/aws/AwsRegionSetterCheckSample.java b/java-checks-test-sources/aws/src/main/java/checks/aws/AwsRegionSetterCheckSample.java index cba8dce63d0..65e3251e043 100644 --- a/java-checks-test-sources/aws/src/main/java/checks/aws/AwsRegionSetterCheckSample.java +++ b/java-checks-test-sources/aws/src/main/java/checks/aws/AwsRegionSetterCheckSample.java @@ -11,7 +11,8 @@ public class AwsRegionSetterCheckSample { private static final Regions ENUM_EU_WEST_1 = Regions.EU_WEST_1; void nonCompliant() { - AmazonS3ClientBuilder.standard().withRegion("eu_west_1").build(); // Noncompliant [[sc=49;ec=60]] + AmazonS3ClientBuilder.standard().withRegion("eu_west_1").build(); // Noncompliant +// ^^^^^^^^^^^ AWSLambdaClientBuilder.standard().setRegion("eu_west_1"); // Noncompliant {{Give the enum value for this region instead.}} } diff --git a/java-checks-test-sources/aws/src/main/java/checks/aws/AwsRegionShouldBeSetExplicitlyCheckSample.java b/java-checks-test-sources/aws/src/main/java/checks/aws/AwsRegionShouldBeSetExplicitlyCheckSample.java index 6db79b74a35..739b5c2dccd 100644 --- a/java-checks-test-sources/aws/src/main/java/checks/aws/AwsRegionShouldBeSetExplicitlyCheckSample.java +++ b/java-checks-test-sources/aws/src/main/java/checks/aws/AwsRegionShouldBeSetExplicitlyCheckSample.java @@ -11,18 +11,21 @@ public class AwsRegionShouldBeSetExplicitlyCheckSample { public static final AwsClientBuilder BUILDER = getABuilder(); void nonCompliantChained() { - S3Client s3Client = S3Client.builder() // Noncompliant [[sl=+0;sc=25;el=+2;ec=15]] {{Set the region explicitly on this builder.}} + S3Client s3Client = S3Client.builder() // Noncompliant {{Set the region explicitly on this builder.}} + //^[el=+3;ec=14] .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); } void nonCompliantVariable() { - S3ClientBuilder builder = S3Client.builder(); // Noncompliant [[sc=5;ec=50]] {{Set the region explicitly on this builder.}} + S3ClientBuilder builder = S3Client.builder(); // Noncompliant {{Set the region explicitly on this builder.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ builder.build(); } class NonCompliantClientAsField { - S3Client incompleteClient = S3Client.builder().build(); // Noncompliant [[sc=33;ec=59]] {{Set the region explicitly on this builder.}} + S3Client incompleteClient = S3Client.builder().build(); // Noncompliant {{Set the region explicitly on this builder.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^ } void compliantChained() { diff --git a/java-checks-test-sources/aws/src/main/java/checks/aws/AwsReusableResourcesInitializedOnceCheckSample.java b/java-checks-test-sources/aws/src/main/java/checks/aws/AwsReusableResourcesInitializedOnceCheckSample.java index ad71b383ad2..2bfee82d1a6 100644 --- a/java-checks-test-sources/aws/src/main/java/checks/aws/AwsReusableResourcesInitializedOnceCheckSample.java +++ b/java-checks-test-sources/aws/src/main/java/checks/aws/AwsReusableResourcesInitializedOnceCheckSample.java @@ -31,11 +31,16 @@ public RequestHandlerImpl() throws SQLException { @SneakyThrows @Override public Void handleRequest(Object o, Context context) { - S3Client s3Client = S3Client.builder().region(Region.EU_CENTRAL_1).build(); // Noncompliant [[sc=74;ec=79]] {Instantiate this client outside the Lambda function.} - S3Client.builder().build(); // Noncompliant [[sc=26;ec=31]] {Instantiate this client outside the Lambda function.} - MachineLearningClient.builder().build(); // Noncompliant [[sc=39;ec=44]] {Instantiate this client outside the Lambda function.} - DriverManager.getConnection("foo"); // Noncompliant [[sc=21;ec=34]] {Instantiate this client outside the Lambda function.} - var customClient = new FooClient(); // Noncompliant [[sc=30;ec=39]] {Instantiate this client outside the Lambda function.} + S3Client s3Client = S3Client.builder().region(Region.EU_CENTRAL_1).build(); // Noncompliant {{Instantiate this client outside the Lambda function.}} +// ^^^^^ + S3Client.builder().build(); // Noncompliant {{Instantiate this client outside the Lambda function.}} +// ^^^^^ + MachineLearningClient.builder().build(); // Noncompliant {{Instantiate this client outside the Lambda function.}} +// ^^^^^ + DriverManager.getConnection("foo"); // Noncompliant {{Instantiate this database connection outside the Lambda function.}} +// ^^^^^^^^^^^^^ + var customClient = new FooClient(); // Noncompliant {{Instantiate this client outside the Lambda function.}} +// ^^^^^^^^^ var compliant = new Object(); build(); diff --git a/java-checks-test-sources/aws/src/main/java/checks/security/HardCodedCredentialsShouldNotBeUsedCheckSample.java b/java-checks-test-sources/aws/src/main/java/checks/security/HardCodedCredentialsShouldNotBeUsedCheckSample.java index 06c713aea92..193ab48cbfb 100644 --- a/java-checks-test-sources/aws/src/main/java/checks/security/HardCodedCredentialsShouldNotBeUsedCheckSample.java +++ b/java-checks-test-sources/aws/src/main/java/checks/security/HardCodedCredentialsShouldNotBeUsedCheckSample.java @@ -32,19 +32,25 @@ public class HardCodedCredentialsShouldNotBeUsedCheckSample { static final String FINAL_SECRET_STRING = "hunter2"; +// ^^^^^^^^^> static final byte[] FINAL_SECRET_BYTE_ARRAY = FINAL_SECRET_STRING.getBytes(StandardCharsets.UTF_8); +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^> private static String secretStringField = "hunter2"; private static byte[] secretByteArrayField = new byte[]{0xC, 0xA, 0xF, 0xE}; private static char[] secretCharArrayField = new char[]{0xC, 0xA, 0xF, 0xE}; private static CharSequence secretCharSequenceField = "Hello, World!".subSequence(0, 12); public static void nonCompliant(byte[] message, boolean condition, Charset encoding, SignatureAlgorithm paremSignatureAlgorithm) throws ServletException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, UnsupportedEncodingException, jakarta.servlet.ServletException { + // byte array based + SHA256.getHMAC(FINAL_SECRET_BYTE_ARRAY, message); // Noncompliant {{Revoke and change this password, as it is compromised.}} +// ^^^^^^^^^^^^^^^^^^^^^^^ + String effectivelyConstantString = "s3cr37"; +// ^^^^^^^^> byte[] key = effectivelyConstantString.getBytes(); - - // byte array based - SHA256.getHMAC(FINAL_SECRET_BYTE_ARRAY, message); // Noncompliant [[sc=20;ec=43;secondary=-11,-12]] {{Revoke and change this password, as it is compromised.}} - SHA256.getHMAC(key, message); // Noncompliant [[sc=20;ec=23;secondary=-4,-5]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^> + SHA256.getHMAC(key, message); // Noncompliant +// ^^^ SHA256.getHMAC(effectivelyConstantString.getBytes(), message); // Noncompliant SHA256.getHMAC("anotherS3cr37".getBytes(), message); // Noncompliant SHA256.getHMAC(FINAL_SECRET_STRING.getBytes(), message); // Noncompliant @@ -56,18 +62,36 @@ public static void nonCompliant(byte[] message, boolean condition, Charset encod // String based HttpServletRequest request = new HttpServletRequestWrapper(null); request.login("user", "password"); // Noncompliant - request.login("user", effectivelyConstantString); // Noncompliant [[sc=27;ec=52;secondary=-17]] - request.login("user", FINAL_SECRET_STRING); // Noncompliant [[sc=27;ec=46;secondary=-26]] + request.login("user", effectivelyConstantString); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^ + request.login("user", FINAL_SECRET_STRING); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^ String plainTextSecret = new String("BOOM"); +// ^^^^^^^^^^^^^^^^^^> request.login("user", plainTextSecret); // Noncompliant +// ^^^^^^^^^^^^^^^ request.login("user", new String("secret")); // Noncompliant request.login("user", new String(FINAL_SECRET_BYTE_ARRAY, 0, 7)); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^@36< +// ^^^^^^^^^@34< request.login("user", new String(FINAL_SECRET_BYTE_ARRAY, encoding)); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^@36< +// ^^^^^^^^^@34< + String conditionalButPredictable = condition ? FINAL_SECRET_STRING : plainTextSecret; - request.login("user", conditionalButPredictable); // Noncompliant [[sc=27;ec=52;secondary=-33,-6,-1]] - request.login("user", Json.MEDIA_TYPE); // Noncompliant [[sc=27;ec=42]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^> + request.login("user", conditionalButPredictable); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^ +// ^^^^^^^^^@34< +// ^^^^^^^^^^^^^^^^^^@69< + request.login("user", Json.MEDIA_TYPE); // Noncompliant +// ^^^^^^^^^^^^^^^ String concatenatedPassword = "abc" + true + ":" + 12 + ":" + 43L + ":" + 'a' + ":" + 0.2f + ":" + 0.2d; - request.login("user", concatenatedPassword); // Noncompliant [[sc=27;ec=47;secondary=-1]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^> + request.login("user", concatenatedPassword); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^ jakarta.servlet.http.HttpServletRequest requestJakarta = new jakarta.servlet.http.HttpServletRequestWrapper(null); requestJakarta.login("user", "password"); // Noncompliant @@ -76,17 +100,23 @@ public static void nonCompliant(byte[] message, boolean condition, Charset encod store.getKey("", new char[]{0xC, 0xA, 0xF, 0xE}); // Noncompliant char[] password = new char[]{0xC, 0xA, 0xF, 0xE}; - store.getKey("", password); // Noncompliant [[sc=22;ec=30;secondary=-1]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^> + store.getKey("", password); // Noncompliant +// ^^^^^^^^ String passwordAsString = "hunter2"; - store.getKey("", passwordAsString.toCharArray()); // Noncompliant [[sc=22;ec=52]] + store.getKey("", passwordAsString.toCharArray()); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ char[] reassignedArray; +// ^^^^^^^^^^^^^^^^^^^^^^^> reassignedArray = new char[]{'a', 'b', 'c', 'd', 'e', 'f'}; reassignedArray = new char[]{'a', 'b', 'c', 'd', 'e', 'f'}; - store.getKey("", reassignedArray); // Noncompliant [[sc=22;ec=37;secondary=-3]] + store.getKey("", reassignedArray); // Noncompliant +// ^^^^^^^^^^^^^^^ - Encryptors.delux(effectivelyConstantString.subSequence(0, effectivelyConstantString.length()), effectivelyConstantString); // Noncompliant [[sc=22;ec=98]] + Encryptors.delux(effectivelyConstantString.subSequence(0, effectivelyConstantString.length()), effectivelyConstantString); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Encryptors.delux("password".subSequence(0, 0), "salt"); // Noncompliant new Pbkdf2PasswordEncoder("secret"); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/AbstractClassNoFieldShouldBeInterfaceCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/AbstractClassNoFieldShouldBeInterfaceCheckSample.java index 8f6deaae52a..0ff535ccb5f 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/AbstractClassNoFieldShouldBeInterfaceCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/AbstractClassNoFieldShouldBeInterfaceCheckSample.java @@ -9,7 +9,8 @@ abstract class AbstractClassNoFieldShouldBeInterfaceCheckA { abstract void method(); } -abstract class AbstractClassNoFieldShouldBeInterfaceCheckB { // Noncompliant [[sc=16;ec=59]] {{Convert the abstract class "AbstractClassNoFieldShouldBeInterfaceCheckB" into an interface.}} +abstract class AbstractClassNoFieldShouldBeInterfaceCheckB { // Noncompliant {{Convert the abstract class "AbstractClassNoFieldShouldBeInterfaceCheckB" into an interface.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ int method(){ return 1; } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/AbstractClassNoFieldShouldBeInterfaceCheckSample_java9.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/AbstractClassNoFieldShouldBeInterfaceCheckSample_java9.java index 99283c6c29f..adc9799e96f 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/AbstractClassNoFieldShouldBeInterfaceCheckSample_java9.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/AbstractClassNoFieldShouldBeInterfaceCheckSample_java9.java @@ -3,7 +3,8 @@ abstract class A { abstract void method(); } -abstract class B { // Noncompliant [[sc=16;ec=17]] {{Convert the abstract class "B" into an interface.}} +abstract class B { // Noncompliant {{Convert the abstract class "B" into an interface.}} +// ^ int method(){ return 1; } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/AccessibilityChangeCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/AccessibilityChangeCheckSample.java index 227a4982772..86f60408177 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/AccessibilityChangeCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/AccessibilityChangeCheckSample.java @@ -10,24 +10,24 @@ void fieldModificationIsAlwaysCompliantForRecords() throws NoSuchFieldException, Person person = new Person("A", 26); Field uninitializedField; - uninitializedField.setAccessible(true); // Noncompliant FP Not exploring fields from unkwnon methods - uninitializedField.set(person, "B"); // Noncompliant FP Not exploring fields from unkwnon methods + uninitializedField.setAccessible(true); // Noncompliant + uninitializedField.set(person, "B"); // Noncompliant Field fieldOfUnknownOrigin = unknown(); - fieldOfUnknownOrigin.setAccessible(true); // Noncompliant FP Not exploring fields from unkwnon methods - fieldOfUnknownOrigin.set(person, "B"); // Noncompliant FP Not exploring fields from unkwnon methods + fieldOfUnknownOrigin.setAccessible(true); // Noncompliant + fieldOfUnknownOrigin.set(person, "B"); // Noncompliant Field fieldFromConstructor = new Field(){}; - fieldFromConstructor.setAccessible(true); // Noncompliant FP Not exploring fields from unkwnon methods - fieldFromConstructor.set(person, "B"); // Noncompliant FP Not exploring fields from unkwnon methods + fieldFromConstructor.setAccessible(true); // Noncompliant + fieldFromConstructor.set(person, "B"); // Noncompliant Field fieldFromUnkwownClass = Unknown.class.getField("myField"); - fieldFromUnkwownClass.setAccessible(true); // Noncompliant FP Not exploring fields from unkwnon methods - fieldFromUnkwownClass.set(person, "B"); // Noncompliant FP Not exploring fields from unkwnon methods + fieldFromUnkwownClass.setAccessible(true); // Noncompliant + fieldFromUnkwownClass.set(person, "B"); // Noncompliant Field fieldFromUnkwownClass = getUnknownClass().getField("myField"); - fieldFromUnkwownClass.setAccessible(true); // Noncompliant FP Not exploring fields from unkwnon methods - fieldFromUnkwownClass.set(person, "B"); // Noncompliant FP Not exploring fields from unkwnon methods + fieldFromUnkwownClass.setAccessible(true); // Noncompliant + fieldFromUnkwownClass.set(person, "B"); // Noncompliant } Field getAField() { diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/AllBranchesAreIdentical.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/AllBranchesAreIdentical.java index e92bcb2cc16..0bb78eb31f1 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/AllBranchesAreIdentical.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/AllBranchesAreIdentical.java @@ -3,7 +3,8 @@ class AllBranchesAreIdentical { void switchStatement(WeekendDay weekendDay) { - int i = switch (1) { // Noncompliant [[sc=13;ec=19]] {{Remove this conditional structure or edit its code blocks so that they're not all the same.}} + int i = switch (1) { // Noncompliant {{Remove this conditional structure or edit its code blocks so that they're not all the same.}} +// ^^^^^^ case 1: doSomething(); yield 1; diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/AnnotationDefaultArgumentCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/AnnotationDefaultArgumentCheckSample.java index 8d8bc4fc9c9..3474bf36eb5 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/AnnotationDefaultArgumentCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/AnnotationDefaultArgumentCheckSample.java @@ -13,7 +13,8 @@ void unknownAnnotation() { } - @MyAnnotationDefaultCheck(myName="myName", myInteger=2) // Noncompliant [[sc=29;ec=44]] {{Remove this default value assigned to parameter "myName".}} + @MyAnnotationDefaultCheck(myName="myName", myInteger=2) // Noncompliant {{Remove this default value assigned to parameter "myName".}} +// ^^^^^^^^^^^^^^^ void m1() { } } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/AnonymousClassShouldBeLambdaCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/AnonymousClassShouldBeLambdaCheckSample.java index 161c2f327cd..0de51776e55 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/AnonymousClassShouldBeLambdaCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/AnonymousClassShouldBeLambdaCheckSample.java @@ -24,7 +24,7 @@ interface InvokeStatic { int func(); static int staticFunc() { - InvokeStatic f = new InvokeStatic() { // Noncompliant + InvokeStatic f = new InvokeStatic() { // Noncompliant @Override public int func() { unknown(); @@ -35,4 +35,4 @@ public int func() { return f.func(); } } -} \ No newline at end of file +} diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/ArrayForVarArgCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/ArrayForVarArgCheckSample.java index 5a3841de2bd..c7c51b1da9c 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/ArrayForVarArgCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/ArrayForVarArgCheckSample.java @@ -7,7 +7,7 @@ class ArrayForVarArgCheckSample { public void callTheThing(String s) { ArrayForVarArgCheckFoo foo = new ArrayForVarArgCheckFoo(); - doTheThing2(new ArrayForVarArgCheckFoo[] {foo, foo}); // Noncompliant {{Remove this array creation and simply pass the elements.}} + doTheThing2(new ArrayForVarArgCheckFoo[] {foo, foo}); // Noncompliant {{Remove this array creation and simply pass the elements.}} unknown(new ArrayForVarArgCheckFoo[0]); // Compliant doTheThing2(new Unknown[0]); // Compliant diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/CallOuterPrivateMethodCheck.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/CallOuterPrivateMethodCheck.java index 045a576d3d7..ed7675f1047 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/CallOuterPrivateMethodCheck.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/CallOuterPrivateMethodCheck.java @@ -30,7 +30,7 @@ class UnknownInvocation { private void invoke(int a) {} private void invoke2(int a, int b) {} // Noncompliant private void invoke3(String a, String b, int... c) {} - private void invoke4(String a, String b, int... c) {} // Noncompliant invoke4 in InnerTwo can't be this method + private void invoke4(String a, String b, int... c) {} // Noncompliant private void invoke5(int a) {} private class InnerOne { diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/CallToDeprecatedCodeFlaggedForRemovalCheck_java9.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/CallToDeprecatedCodeFlaggedForRemovalCheck_java9.java index 56f7fbc8f7a..947352df9de 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/CallToDeprecatedCodeFlaggedForRemovalCheck_java9.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/CallToDeprecatedCodeFlaggedForRemovalCheck_java9.java @@ -20,11 +20,11 @@ void test() { bar(); qix(); - new DeprecatedForRemoval(); // Noncompliant {{Remove this use of "DeprecatedForRemoval", it has been marked for removal.} + new DeprecatedForRemoval(); // Noncompliant new DeprecatedDefault(); String s = a - + b; // Noncompliant {{Remove this use of a deprecated field, it has been marked for removal.} + + b; // Noncompliant } @Deprecated(forRemoval = true) diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/CastArithmeticOperandCheck.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/CastArithmeticOperandCheck.java index 52826c39c2b..6c55fe48ac8 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/CastArithmeticOperandCheck.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/CastArithmeticOperandCheck.java @@ -5,7 +5,7 @@ class CastArithmeticOperandCheck { CastArithmeticOperandCheck(int a, long l) {} void foo() { - longMethod(1 + 2, 1 + 2); // Noncompliant + longMethod(1 + 2, 1 + 2); // Noncompliant unknownMethod(1 + 2); // Compliant } void longMethod(int a, long l) {} diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/CatchOfThrowableOrErrorCheck.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/CatchOfThrowableOrErrorCheck.java index 5683cee7f19..1e93dd83c34 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/CatchOfThrowableOrErrorCheck.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/CatchOfThrowableOrErrorCheck.java @@ -17,10 +17,10 @@ private void f() throws Exception { } try {} catch (foo.java.lang.Throwable e) { // Compliant } - try {} catch (Throwable e) { // Noncompliant {{Catch Exception instead of Throwable.}} + try {} catch (Throwable e) { // Noncompliant {{Catch Exception instead of Throwable.}} throw e; } - try {} catch (Throwable e) { // Noncompliant {{Catch Exception instead of Throwable.}} + try {} catch (Throwable e) { // Noncompliant {{Catch Exception instead of Throwable.}} throw new Exception(e).getCause(); } try {} catch (Throwable e) { // Compliant @@ -29,10 +29,10 @@ private void f() throws Exception { try {} catch (java.lang.Throwable e) { // Compliant throw closer.rethrow(e); } - try {} catch (Throwable e) { // Noncompliant {{Catch Exception instead of Throwable.}} + try {} catch (Throwable e) { // Noncompliant {{Catch Exception instead of Throwable.}} throw closer.rethrow(new Exception(e)); } - try {} catch (Throwable e) { // Noncompliant {{Catch Exception instead of Throwable.}} + try {} catch (Throwable e) { // Noncompliant {{Catch Exception instead of Throwable.}} Throwable myThrowable = new Throwable(e); throw closer.rethrow(myThrowable); } @@ -87,7 +87,7 @@ private void doNotReportWhenUnknownMethodInTryBlock() { } // Ensure that we still raise an issue after encountering unrelated blocks containing incomplete semantics: - try {} catch (Throwable e) { // Noncompliant + try {} catch (Throwable e) { // Noncompliant } } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/CatchUsesExceptionWithContextCheck.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/CatchUsesExceptionWithContextCheck.java index 3cde9e4be1f..6c6f8beb50a 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/CatchUsesExceptionWithContextCheck.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/CatchUsesExceptionWithContextCheck.java @@ -28,13 +28,13 @@ void tryWithMultipleCatch() { foo(null, e).bar(); } catch (Exception e) { // Compliant throw foo(e).bar(); - } catch (Exception e) { // Noncompliant + } catch (Exception e) { // Noncompliant throw e.getCause(); } catch (Exception e) { // Compliant throw (Exception)e; } catch (Exception e) { // Compliant throw (e); - } catch (Exception e) { // Noncompliant + } catch (Exception e) { // Noncompliant throw (e).getClause(); } catch (Exception e) { // Compliant Exception e2 = e; @@ -50,11 +50,12 @@ void tryWithMultipleCatch() { } catch (MalformedURLException e) { // Compliant } catch (java.time.format.DateTimeParseException e) { // Compliant } catch (java.text.ParseException e) { // Compliant - } catch (java.text.foo e) { // Noncompliant - } catch (java.foo.ParseException e) { // Noncompliant [[sc=14;ec=39]] - } catch (foo.text.ParseException e) { // Noncompliant - } catch (text.ParseException e) { // Noncompliant - } catch (foo.java.text.ParseException e) { // Noncompliant + } catch (java.text.foo e) { // Noncompliant + } catch (java.foo.ParseException e) { // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^ + } catch (foo.text.ParseException e) { // Noncompliant + } catch (text.ParseException e) { // Noncompliant + } catch (foo.java.text.ParseException e) { // Noncompliant } catch (Exception e) { // Compliant Exception foo = false ? e : null; } catch (Exception e) { // Compliant @@ -67,9 +68,9 @@ void tryWithMultipleCatch() { } catch (Exception e) { // Compliant throw wrapHttpException ? null : e; } - catch (Exception e) { // Noncompliant + catch (Exception e) { // Noncompliant try { - } catch (Exception f) { // Noncompliant + } catch (Exception f) { // Noncompliant System.out.println("", e.getCause()); } } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/CollapsibleIfCandidateCheck.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/CollapsibleIfCandidateCheck.java index b6038325c33..cf92dd97e95 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/CollapsibleIfCandidateCheck.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/CollapsibleIfCandidateCheck.java @@ -8,7 +8,9 @@ void f() { } if (false) { // Compliant 3 - if (false) { // Noncompliant {{Merge this if statement with the enclosing one.}} [[sc=7;ec=9;secondary=10]] +// ^^> + if (false) { // Noncompliant {{Merge this if statement with the enclosing one.}} +// ^^ } } @@ -38,7 +40,8 @@ void f() { if (false) { // Compliant 13 } else if (false) { // Compliant 14 - if (false) { // Noncompliant {{Merge this if statement with the enclosing one.}} [[sc=7;ec=9;secondary=40]] + if (false) { // Noncompliant {{Merge this if statement with the enclosing one.}} +// ^^ } } @@ -87,8 +90,8 @@ void f() { } if (true) // Compliant 29 - if (false) // Noncompliant {{Merge this if statement with the enclosing one.}} - if (true) // Noncompliant {{Merge this if statement with the enclosing one.}} + if (false) // Noncompliant {{Merge this if statement with the enclosing one.}} + if (true) // Noncompliant {{Merge this if statement with the enclosing one.}} a = 0; } } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/ConfusingOverloadCheck.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/ConfusingOverloadCheck.java index 7fb1a112df9..6fcd261f8d7 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/ConfusingOverloadCheck.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/ConfusingOverloadCheck.java @@ -9,7 +9,7 @@ public static void staticDifference(int i) { public class SomeChild extends SomeParent { // Signature overloading of a static method does not compile - public void staticDifference(int i) { // Noncompliant {{Rename this method or make it "static".}} + public void staticDifference(int i) { // Noncompliant {{Rename this method or make it "static".}} return -1; } } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/DoubleCheckedLockingCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/DoubleCheckedLockingCheckSample.java index ddcff096c2b..091f4e63059 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/DoubleCheckedLockingCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/DoubleCheckedLockingCheckSample.java @@ -6,8 +6,11 @@ class DoubleCheckedLockingCheckSample { public UnknownType unknownType() { if (unknownType == null) { - synchronized (Helper.class) { // Noncompliant [[sc=6;ec=18;secondary=8,10]] {{Remove this dangerous instance of double-checked locking.}} +// ^^^^^^^^^^^^^^^^^^^> + synchronized (Helper.class) { // Noncompliant {{Remove this dangerous instance of double-checked locking.}} +// ^^^^^^^^^^^^ if (unknownType == null) { +// ^^^^^^^^^^^^^^^^^^^< this.unknownType = new UnknownType(); } } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/EnumMutableFieldCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/EnumMutableFieldCheckSample.java index 722576d20e0..6316717fce7 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/EnumMutableFieldCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/EnumMutableFieldCheckSample.java @@ -3,7 +3,8 @@ public enum Continent { NORTH_AMERICA(23, 24709000), EUROPE(50, 39310000); - public int countryCount; // Noncompliant [[sc=3;ec=9]] {{Lower the visibility of this field.}} + public int countryCount; // Noncompliant {{Lower the visibility of this field.}} +//^^^^^^ public static int countryCount2; // compliant, static field private int landMass; public final com.google.common.collect.ImmutableList regions; // Compliant - immutable @@ -12,7 +13,8 @@ public enum Continent { Continent(int countryCount, int landMass) { } - public void setLandMass(int landMass) { // Noncompliant [[sc=3;ec=9]] {{Lower the visibility of this setter or remove it altogether.}} + public void setLandMass(int landMass) { // Noncompliant {{Lower the visibility of this setter or remove it altogether.}} +//^^^^^^ this.landMass = landMass; } public void setLandMass(int landMass) { // compliant: empty setter is harmless : this can be a pattern used when implementing singleton enums. @@ -38,7 +40,8 @@ public enum Continent2 { Continent2(int countryCount, int landMass) { } - public abstract void setLandMass(int landMass); // Noncompliant [[sc=3;ec=9]] {{Lower the visibility of this setter or remove it altogether.}} + public abstract void setLandMass(int landMass); // Noncompliant {{Lower the visibility of this setter or remove it altogether.}} +//^^^^^^ public abstract void getLandMass(int landMass); } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/EscapedUnicodeCharactersTextBlocksCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/EscapedUnicodeCharactersTextBlocksCheckSample.java index cc52cc121c3..6c001885f0f 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/EscapedUnicodeCharactersTextBlocksCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/EscapedUnicodeCharactersTextBlocksCheckSample.java @@ -1,8 +1,9 @@ package checks; class EscapedUnicodeCharactersCheck { +// Noncompliant@+2 {{Remove this Unicode escape sequence and use the character instead.}} void method() { - String prefix0 = """ + String prefix0 = """ @@ -12,11 +13,13 @@ void method() { - """; // Noncompliant@-10 [[sc=22;ec=10]] {{Remove this Unicode escape sequence and use the character instead.}} - String prefix = """ - n\uuuu00E9e"""; // Noncompliant@-1 [[sc=21;ec=21]] {{Remove this Unicode escape sequence and use the character instead.}} + """; +// Noncompliant@+1 {{Remove this Unicode escape sequence and use the character instead.}} + String prefix = """ + n\uuuu00E9e"""; +// Noncompliant@+1 {{Remove this Unicode escape sequence and use the character instead.}} String prefix2= """ - n\\\uuuu00E9e"""; // Noncompliant@-1 [[sc=21;ec=23]] {{Remove this Unicode escape sequence and use the character instead.}} + n\\\uuuu00E9e"""; prefix = """ n\u00E9e\u0001v"""; // Noncompliant@-1 // compliant, only escaped @@ -27,8 +30,9 @@ void method() { a\u0001b\u0002c\u00A0"""; prefix = """ \u007f"""; +// Noncompliant@+1 prefix = """ - a\u0080b\u0002c\u00A0\u0083\u0164"""; // Noncompliant@-1 [[sc=14;ec=43]] + a\u0080b\u0002c\u00A0\u0083\u0164"""; prefix = """ n\\u00E9e"""; prefix = """ diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/ForLoopFalseConditionCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/ForLoopFalseConditionCheckSample.java index 0eafc79dc6a..a024b3577d8 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/ForLoopFalseConditionCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/ForLoopFalseConditionCheckSample.java @@ -6,7 +6,8 @@ void myMethod(int x, int y, int z) { for (int i ; i < 5; ) {} - for (int i = x; false; ) {} // Noncompliant [[sc=21;ec=26]] {{This loop will never execute.}} + for (int i = x; false; ) {} // Noncompliant {{This loop will never execute.}} +// ^^^^^ for (int i = x; !true; ) {} // Noncompliant diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/GarbageCollectorCalledCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/GarbageCollectorCalledCheckSample.java index c9f23e0d001..4da63699547 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/GarbageCollectorCalledCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/GarbageCollectorCalledCheckSample.java @@ -3,7 +3,8 @@ class A { Object o; private void f() { - System.gc(); // Noncompliant [[sc=12;ec=14]] {{Don't try to be smarter than the JVM, remove this call to run the garbage collector.}} + System.gc(); // Noncompliant {{Don't try to be smarter than the JVM, remove this call to run the garbage collector.}} +// ^^ foo.gc(); // Compliant System.exit(0); // Compliant o = System.gc; // Compliant diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/IdenticalCasesInSwitchCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/IdenticalCasesInSwitchCheckSample.java index a1248dd3c48..4a4b4537e95 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/IdenticalCasesInSwitchCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/IdenticalCasesInSwitchCheckSample.java @@ -4,9 +4,11 @@ class IdenticalCasesInSwitchCheckSample { void foo(WeekendDay weekendDay){ int i = switch (weekendDay) { case SATURDAY: +// ^[el=+3;ec=16]> trivial(); yield 1; - case SUNDAY: // Noncompliant [[sc=7;el=+2;ec=17;secondary=-3]] {{This case's code block is the same as the block for the case on line 6.}} + case SUNDAY: // Noncompliant {{This case's code block is the same as the block for the case on line 6.}} +//^[sc=7;ec=16;sl=10;el=13] trivial(); yield 1; }; diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/IndentationCheck_default.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/IndentationCheck_default.java index 59b85ced348..214314c58e2 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/IndentationCheck_default.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/IndentationCheck_default.java @@ -185,7 +185,7 @@ public static void testBlockIndentationArrowCases(Color color) { class Foo { int a; // Compliant - int b; // Noncompliant {{Make this line start after 2 spaces instead of 3 in order to indent the code consistently. (Indentation level is at 2.)}} + int b; // Noncompliant {{Make this line start after 2 spaces instead of 3 in order to indent the code consistently. (Indentation level is at 2.)}} int c; // Compliant - already reported public void foo1() { // Compliant @@ -193,20 +193,20 @@ public void foo1() { // Compliant } // Compliant public void foo2() { // Compliant - System.out.println("hehe"); // Noncompliant + System.out.println("hehe"); // Noncompliant System.out.println(); // Compliant - already reported } public void foo3() { // Compliant -System.out.println(); // Noncompliant +System.out.println(); // Noncompliant System.out.println(); // Compliant - already reported System.out.println(); // Compliant - already reported if (true) { // Compliant - already reported - System.out.println(); // Noncompliant + System.out.println(); // Noncompliant if (true) { // Compliant - already reported System.out.println(); // Compliant - System.out.println(); // Noncompliant {{Make this line start after 8 spaces instead of 4 in order to indent the code consistently. (Indentation level is at 2.)}} + System.out.println(); // Noncompliant {{Make this line start after 8 spaces instead of 4 in order to indent the code consistently. (Indentation level is at 2.)}} } ; System.out.println(); // Compliant @@ -217,7 +217,7 @@ class Foo { int a; // Compliant - int b; // Noncompliant + int b; // Noncompliant } @@ -328,13 +328,13 @@ enum Bar { public void foo1() { // Compliant } - public void foo2() { // Noncompliant + public void foo2() { // Noncompliant } } interface Qix { - void foo1(); // Noncompliant + void foo1(); // Noncompliant void foo2(); // Compliant @@ -346,9 +346,9 @@ void foo() { new MyInterface() { public void foo() { // Compliant System.out.println(); // Compliant - System.out.println(); // Noncompliant + System.out.println(); // Noncompliant } - public void bar() { // Noncompliant + public void bar() { // Noncompliant } }; } @@ -360,7 +360,7 @@ public void bar() { // Noncompliant } - class Qiz { // Noncompliant + class Qiz { // Noncompliant public void foo() { switch (0) { case 0: diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/InstanceOfPatternMatching.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/InstanceOfPatternMatching.java index 84a3305bfc2..c42f12bbf4d 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/InstanceOfPatternMatching.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/InstanceOfPatternMatching.java @@ -5,8 +5,10 @@ public class InstanceOfPatternMatching { int if1(Object o) { - if (o instanceof String) { // Noncompliant {{Replace this instanceof check and cast with 'instanceof String str'}} [[secondary=+1]] + if (o instanceof String) { // Noncompliant {{Replace this instanceof check and cast with 'instanceof String str'}} +// ^^^^^^^^^^^^^^^^^^^ String str = (String) o; +// ^^^^^^^^^^< return str.length(); } return 0; diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/InterruptedExceptionCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/InterruptedExceptionCheckSample.java index f121a8d6993..5d77a26da39 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/InterruptedExceptionCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/InterruptedExceptionCheckSample.java @@ -21,7 +21,8 @@ public void run1 () { } }catch (java.io.IOException e) { LOGGER.log(Level.WARN, "Interrupted!", e); - }catch (InterruptedException e) { // Noncompliant [[sc=13;ec=35]] {{Either re-interrupt this method or rethrow the "InterruptedException" that can be caught here.}} + }catch (InterruptedException e) { // Noncompliant {{Either re-interrupt this method or rethrow the "InterruptedException" that can be caught here.}} +// ^^^^^^^^^^^^^^^^^^^^^^ LOGGER.log(Level.WARN, "Interrupted!", e); } } @@ -43,7 +44,8 @@ public void catchUnionType () { while (true) { // do stuff } - } catch (InterruptedException | java.io.IOException e) { // Noncompliant [[sc=14;ec=58]] {{Either re-interrupt this method or rethrow the "InterruptedException" that can be caught here.}} + } catch (InterruptedException | java.io.IOException e) { // Noncompliant {{Either re-interrupt this method or rethrow the "InterruptedException" that can be caught here.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unknownField.log(Level.WARN, "Interrupted!", e); } } @@ -189,13 +191,13 @@ private static void cancelAllSubTasksAndInterrupt555(Set subTasks) { try { throwsInterruptedException(); - } catch (InterruptedException e) { // Noncompliant, unknown exception type is not regarded an InterruptedException + } catch (InterruptedException e) { // Noncompliant throw new NonExistentException(); } try { throwsInterruptedException(); - } catch (InterruptedException e) { // Noncompliant, unknown supertype of exception is not regarded an InterruptedException + } catch (InterruptedException e) { // Noncompliant throw new CustomizedInterruptedException(); } } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/LazyArgEvaluationCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/LazyArgEvaluationCheckSample.java index fda15fc4848..d43f3282b0c 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/LazyArgEvaluationCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/LazyArgEvaluationCheckSample.java @@ -14,6 +14,6 @@ int age () { } MyUnknownRecord myUnknownRecord = new MyUnknownRecord(new Unknown()); logger.log(Level.SEVERE, "Something went wrong: " + myUnknownRecord.name()); // Compliant - unkown types are filtered out - logger.log(Level.SEVERE, "Something went wrong: " + myUnknownRecord.age()); // Noncompliant - not a getter + logger.log(Level.SEVERE, "Something went wrong: " + myUnknownRecord.age()); // Noncompliant } } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/LeastSpecificTypeCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/LeastSpecificTypeCheckSample.java index 5b6c3bdc4dd..f6bc1fdfd8d 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/LeastSpecificTypeCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/LeastSpecificTypeCheckSample.java @@ -57,16 +57,16 @@ interface Inner {} static class T extends T2 implements IMB, IMA {} - public static void bla(T t) { // Noncompliant {{Use 'checks.LeastSpecificTypeCheckSample.I1' here; it is a more general type than 'T'.}} + public static void bla(T t) { // Noncompliant {{Use 'checks.LeastSpecificTypeCheckSample.I1' here; it is a more general type than 'T'.}} t.m(); } - public static void foo(T t) { // Noncompliant {{Use 'checks.LeastSpecificTypeCheckSample.T1' here; it is a more general type than 'T'.}} + public static void foo(T t) { // Noncompliant {{Use 'checks.LeastSpecificTypeCheckSample.T1' here; it is a more general type than 'T'.}} t.m(); t.mt1(); } - public static void ma(T t) { // Noncompliant {{Use 'checks.LeastSpecificTypeCheckSample.IMA' here; it is a more general type than 'T'.}} + public static void ma(T t) { // Noncompliant {{Use 'checks.LeastSpecificTypeCheckSample.IMA' here; it is a more general type than 'T'.}} // defined in both T2 and IMA, interface is preferred t.ma(); } @@ -93,7 +93,7 @@ class GImplSub extends GImpl { } - public static void generics(GImplSub s) { // Noncompliant {{Use 'checks.LeastSpecificTypeCheckSample.GImpl' here; it is a more general type than 'GImplSub'.}} + public static void generics(GImplSub s) { // Noncompliant {{Use 'checks.LeastSpecificTypeCheckSample.GImpl' here; it is a more general type than 'GImplSub'.}} s.get(); } @@ -101,7 +101,7 @@ class Generic implements IG { } - public static void generics2(Generic g) { // Noncompliant {{Use 'checks.LeastSpecificTypeCheckSample.IG' here; it is a more general type than 'Generic'.}} + public static void generics2(Generic g) { // Noncompliant {{Use 'checks.LeastSpecificTypeCheckSample.IG' here; it is a more general type than 'Generic'.}} g.get(); } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/LeftCurlyBraceEndLineCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/LeftCurlyBraceEndLineCheckSample.java index 88f66150715..15775e4efc9 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/LeftCurlyBraceEndLineCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/LeftCurlyBraceEndLineCheckSample.java @@ -1,7 +1,7 @@ class NestedSwitchStatementCheck { void switchExpressions(MyEnum myEnum) { int i = switch (myEnum) - { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} + { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} case A: yield 1; default: diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/LeftCurlyBraceStartLineCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/LeftCurlyBraceStartLineCheckSample.java index 2ae4a6f634c..1e81f257c66 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/LeftCurlyBraceStartLineCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/LeftCurlyBraceStartLineCheckSample.java @@ -10,7 +10,7 @@ void switchExpressions(MyEnum myEnum) yield 2; }; - int j = switch (myEnum) { // Noncompliant {{Move this left curly brace to the beginning of next line of code.}} + int j = switch (myEnum) { // Noncompliant {{Move this left curly brace to the beginning of next line of code.}} case A: yield 1; default: diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/MapKeyNotComparableCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/MapKeyNotComparableCheckSample.java index d0f13e332b5..9313527209e 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/MapKeyNotComparableCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/MapKeyNotComparableCheckSample.java @@ -24,11 +24,13 @@ static class UnknownClass implements Unknown {} static class Program { Map nonComparable = new HashMap<>(); // Potential false negative caused by unknown hierarchy Map nonComparable = new HashMap<>(); // Potential false negative caused by unknown symbol - Map nonCompliant = new HashMap<>(); // Noncompliant [[sc=9;ec=22]] {{The key type should implement Comparable.}} + Map nonCompliant = new HashMap<>(); // Noncompliant {{The key type should implement Comparable.}} +// ^^^^^^^^^^^^^ Map comparable = new HashMap<>(); // compliant Map noParams = new HashMap(); - Map buildNonComparableMap() { // Noncompliant [[sc=9;ec=22]] {{The key type should implement Comparable.}} + Map buildNonComparableMap() { // Noncompliant {{The key type should implement Comparable.}} +// ^^^^^^^^^^^^^ return nonComparable; } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/MethodWithExcessiveReturnsCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/MethodWithExcessiveReturnsCheckSample.java index 97fc789b350..e809c301095 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/MethodWithExcessiveReturnsCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/MethodWithExcessiveReturnsCheckSample.java @@ -11,17 +11,23 @@ class A { return; } - void foo() { // Noncompliant [[sc=8;ec=11]] {{This method has 4 returns, which is more than the 3 allowed.}} + void foo() { // Noncompliant {{This method has 4 returns, which is more than the 3 allowed.}} +// ^^^ return; return; return; return; } - boolean foo2() { // Noncompliant [[sc=11;ec=15;secondary=22,23,24,25]] {{This method has 4 returns, which is more than the 3 allowed.}} + boolean foo2() { // Noncompliant {{This method has 4 returns, which is more than the 3 allowed.}} +// ^^^^ return true; +// ^^^^^^< return false; +// ^^^^^^< return true; +// ^^^^^^< return false; +// ^^^^^^< } } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/MissingDeprecatedCheckWithRecords.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/MissingDeprecatedCheckWithRecords.java index 01c2e9d03c6..f77eb07d60e 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/MissingDeprecatedCheckWithRecords.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/MissingDeprecatedCheckWithRecords.java @@ -7,5 +7,5 @@ record MissingDeprecatedCheckWithRecords(@Deprecated int lo, int hi) { // Noncom } @Deprecated - void foo() {} // Noncompliant + void foo() {} // Noncompliant } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/NestedEnumStatic.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/NestedEnumStatic.java index bac0113ed02..4c7c73b657e 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/NestedEnumStatic.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/NestedEnumStatic.java @@ -1,5 +1,7 @@ package checks; // should be rejected during compilation -static enum MyStaticEnum {// Noncompliant [[sc=1;ec=7;secondary=4]] {{Remove this redundant "static" qualifier; nested enum types are implicitly static.}} +static enum MyStaticEnum { // Noncompliant {{Remove this redundant "static" qualifier; nested enum types are implicitly static.}} +//^[sc=1;ec=6] +// ^^^^@-1< } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/NestedSwitchExpressionCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/NestedSwitchExpressionCheckSample.java index 7d715c392e7..b73718594b8 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/NestedSwitchExpressionCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/NestedSwitchExpressionCheckSample.java @@ -5,11 +5,12 @@ void foo() { int myVar = 0; int i = switch (myVar) { // Compliant case 0: - int iNested = switch (0) { // Noncompliant + int iNested = switch (0) { // Noncompliant case 0: case 1: System.out.println(); - switch (1){ // Noncompliant [[sc=13;ec=19;el=+0]] {{Refactor the code to eliminate this nested "switch".}} + switch (1){ // Noncompliant {{Refactor the code to eliminate this nested "switch".}} +// ^^^^^^ case 0: case 1: yield 2; @@ -41,7 +42,7 @@ void foo() { case 2: yield 2; default:{ - yield switch(4) { // Noncompliant + yield switch(4) { // Noncompliant case 0: switch(5) { // Noncompliant default: @@ -49,7 +50,7 @@ yield switch(4) { // Noncompliant } yield 2; case 1: { - yield switch (6) { // Noncompliant + yield switch (6) { // Noncompliant case 0: yield 4; default: diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/NoTestInTestClassCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/NoTestInTestClassCheckSample.java index 3160cd6023a..1d4b27b8c1f 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/NoTestInTestClassCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/NoTestInTestClassCheckSample.java @@ -32,7 +32,8 @@ public void testNothing() { assertTrue(true); } } -class B extends junit.framework.TestCase { // Noncompliant [[sc=7;ec=8]] {{Add some tests to this class.}} +class B extends junit.framework.TestCase { // Noncompliant {{Add some tests to this class.}} +// ^ void foo() { } } @@ -56,22 +57,26 @@ public void test() { } } -class JUnit4WithJUnit3Test { // Noncompliant [[sc=7;ec=27]] +class JUnit4WithJUnit3Test { // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^ public void test() { // Simply naming test is not enough for JUnit 4 } } -class JUnit4WithJUnit3Tests { // Noncompliant [[sc=7;ec=28]] +class JUnit4WithJUnit3Tests { // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^ public void test() { } } -class JUnit4WithJUnit3TestCase { // Noncompliant [[sc=7;ec=31]] +class JUnit4WithJUnit3TestCase { // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^ public void test() { } } -class ATest { // Noncompliant [[sc=7;ec=12]] {{Add some tests to this class.}} +class ATest { // Noncompliant {{Add some tests to this class.}} +// ^^^^^ @Deprecated void foo() { new AnonymousClass() { @@ -111,7 +116,8 @@ public void test2() { } @org.testng.annotations.Test -public class TestNGClassTest { // Noncompliant [[sc=14;ec=29]] +public class TestNGClassTest { // Noncompliant +// ^^^^^^^^^^^^^^^ public int field; private void test1() { } public static void foo() {} @@ -146,16 +152,19 @@ public class MyCucumber2Test { // no issue } @RunWith(MyRunner.class) -public class MyCucumber3Test { // Noncompliant [[sc=14;ec=29]] - not recognized +public class MyCucumber3Test { // Noncompliant +// ^^^^^^^^^^^^^^^ } @RunWith(getRunner()) -public class MyCucumber4Test { // Noncompliant [[sc=14;ec=29]] - does not compile, not a class literal +public class MyCucumber4Test { // Noncompliant +// ^^^^^^^^^^^^^^^ public Class getRunner() { return null; } } @RunWith(value1= MyRunner.class, value2= YourRunner.class) -public class MyCucumber5Test { // Noncompliant [[sc=14;ec=29]] - does not compile, not a class literal +public class MyCucumber5Test { // Noncompliant +// ^^^^^^^^^^^^^^^ } public class CTest { @@ -164,7 +173,8 @@ public void testFoo() { assertThat(new A().foo(null)).isEqualTo(0); } } -public class DTest { // Noncompliant [[sc=14;ec=19]] {{Add some tests to this class.}} +public class DTest { // Noncompliant {{Add some tests to this class.}} +// ^^^^^ public void testFoo() { assertThat(new A().foo(null)).isEqualTo(0); } @@ -257,7 +267,8 @@ public void foo() { } } -class NoTestsInNestedTest { // Noncompliant [[sc=7;ec=26]] {{Add some tests to this class.}} +class NoTestsInNestedTest { // Noncompliant {{Add some tests to this class.}} +// ^^^^^^^^^^^^^^^^^^^ @Nested class NestedClass { public void foo() { @@ -266,7 +277,8 @@ public void foo() { } } -class SomeTest implements SomeInterface { }// Noncompliant [[sc=7;ec=15]] {{Add some tests to this class.}} +class SomeTest implements SomeInterface { } // Noncompliant {{Add some tests to this class.}} +// ^^^^^^^^ interface SomeInterface { class Foo implements SomeInterface { } @@ -274,7 +286,8 @@ class Foo implements SomeInterface { } @RunWith(ZohhakRunner.class) -public class MyZohhakTest { // Noncompliant [[sc=14;ec=26]] +public class MyZohhakTest { // Noncompliant +// ^^^^^^^^^^^^ } @RunWith(ZohhakRunner.class) diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/OSCommandsPath.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/OSCommandsPath.java index 906360ab91e..946d1f71a7c 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/OSCommandsPath.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/OSCommandsPath.java @@ -26,14 +26,14 @@ private void noInitializer() { } private void processBuilderListJava9() { - new ProcessBuilder(List.of("make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(List.of("m../ake")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(List.of("mak./e")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(List.of("bin~/make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(List.of("7:\\\\make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(List.of("m..\\ake")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(List.of("ma.\\ke")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(List.of("SERVER\\make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(List.of("make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(List.of("m../ake")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(List.of("mak./e")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(List.of("bin~/make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(List.of("7:\\\\make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(List.of("m..\\ake")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(List.of("ma.\\ke")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(List.of("SERVER\\make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} new ProcessBuilder(List.of("/usr/bin/make")); new ProcessBuilder(List.of("../make")); new ProcessBuilder(List.of("./make")); @@ -47,14 +47,14 @@ private void processBuilderListJava9() { private void commandJava9() { ProcessBuilder builder = new ProcessBuilder(); - builder.command(List.of("make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(List.of("m../ake")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(List.of("mak./e")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(List.of("bin~/make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(List.of("7:\\\\make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(List.of("m..\\ake")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(List.of("ma.\\ke")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(List.of("SERVER\\make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(List.of("make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(List.of("m../ake")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(List.of("mak./e")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(List.of("bin~/make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(List.of("7:\\\\make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(List.of("m..\\ake")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(List.of("ma.\\ke")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(List.of("SERVER\\make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} builder.command(List.of("/usr/bin/make")); builder.command(List.of("../make")); builder.command(List.of("./make")); diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/ObjectFinalizeOverriddenCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/ObjectFinalizeOverriddenCheckSample.java index 15d38669684..aeb91d94492 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/ObjectFinalizeOverriddenCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/ObjectFinalizeOverriddenCheckSample.java @@ -21,7 +21,8 @@ class ObjectFinalizeOverriddenCheckSample { class Foo { @Override - protected void finalize() throws Throwable { // Noncompliant [[sc=20;ec=28]] {{Do not override the Object.finalize() method.}} + protected void finalize() throws Throwable { // Noncompliant {{Do not override the Object.finalize() method.}} +// ^^^^^^^^ } public void foo() { // Compliant diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/OverrideAnnotationCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/OverrideAnnotationCheckSample.java index 1164a1dad6a..a03b5d1a063 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/OverrideAnnotationCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/OverrideAnnotationCheckSample.java @@ -13,7 +13,8 @@ interface K extends J { public boolean equals(Object obj); // Compliant - from Object } class B extends A implements I { - void foo() {} // Noncompliant [[sc=8;ec=11]] {{Add the "@Override" annotation above this method signature}} + void foo() {} // Noncompliant {{Add the "@Override" annotation above this method signature}} +// ^^^ void bar() {} // Compliant - from interface protected void finalize() { // Compliant - from Object @@ -40,7 +41,8 @@ class ExtendsAbstractClass extends AbstractClass { abstract class ImplementsFromJDK8 implements java.lang.reflect.AnnotatedElement { - public A[] getAnnotationsByType(Class annotationClass) { // Noncompliant [[sc=58;ec=78]] {{Add the "@Override" annotation above this method signature}} + public A[] getAnnotationsByType(Class annotationClass) { // Noncompliant {{Add the "@Override" annotation above this method signature}} +// ^^^^^^^^^^^^^^^^^^^^ return null; } } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/OverrideAnnotationCheck_java8.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/OverrideAnnotationCheck_java8.java index 3adcaee2b6f..c13da7755a3 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/OverrideAnnotationCheck_java8.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/OverrideAnnotationCheck_java8.java @@ -9,11 +9,13 @@ abstract class AbstractMethodFromInterface implements InterfaceWithDefault { } interface InterfaceExtendsDefault extends InterfaceWithDefault { - boolean qix(); // Noncompliant [[sc=11;ec=14]] {{Add the "@Override" annotation above this method signature}} + boolean qix(); // Noncompliant {{Add the "@Override" annotation above this method signature}} +// ^^^ @Override boolean gul(); // Compliant - hide default behavior } class ImplemInterfaceWithDefault implements InterfaceWithDefault { - public boolean gul() { return false; } // Noncompliant [[sc=18;ec=21]] {{Add the "@Override" annotation above this method signature}} + public boolean gul() { return false; } // Noncompliant {{Add the "@Override" annotation above this method signature}} +// ^^^ } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/ParameterReassignedToCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/ParameterReassignedToCheckSample.java index e2ef64e0a6e..e28df762362 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/ParameterReassignedToCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/ParameterReassignedToCheckSample.java @@ -40,7 +40,8 @@ public void f() { } abstract void method(); public void f(int a) { - a = 0; // Noncompliant [[sc=5;ec=6]] {{Introduce a new variable instead of reusing the parameter "a".}} + a = 0; // Noncompliant {{Introduce a new variable instead of reusing the parameter "a".}} +// ^ a += 1; // Noncompliant {{Introduce a new variable instead of reusing the parameter "a".}} int b = a; @@ -80,7 +81,7 @@ void foo(String param) {} void meth() { try { } catch (Exception e) { - e = new RuntimeException(); // Noncompliant reassigned before read. + e = new RuntimeException(); // Noncompliant throw e; } while (someBool) { diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/PrivateFieldUsedLocallyCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/PrivateFieldUsedLocallyCheckSample.java index 578d262a594..08133563cdb 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/PrivateFieldUsedLocallyCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/PrivateFieldUsedLocallyCheckSample.java @@ -8,8 +8,8 @@ private static void foo(int p) { } class Class1 { - private int privateField1; // Noncompliant {{Remove the "privateField1" field and declare it as a local variable in the relevant methods.}} - private static int staticPrivateField; // Noncompliant [[startColumn=24;endLine=+0;endColumn=42]] + private int privateField1; // Noncompliant {{Remove the "privateField1" field and declare it as a local variable in the relevant methods.}} + private static int staticPrivateField; // Noncompliant private int privateField2 = 42; public int publicField; diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/RawTypeCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/RawTypeCheckSample.java index 171b052a420..b5f313dd9a6 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/RawTypeCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/RawTypeCheckSample.java @@ -16,7 +16,8 @@ public int compare(Comparable first, Comparable second) { // Compliant because o return second.compareTo(first); } - public void checkNotNull(Comparable left) { // Noncompliant [[sc=30;ec=40]] + public void checkNotNull(Comparable left) { // Noncompliant +// ^^^^^^^^^^ } public void method(Comparable arg1, Unknown arg2) { // Compliant, unknown arg2 type, so may override diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/RedundantThrowsDeclarationCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/RedundantThrowsDeclarationCheckSample.java index 690c4e51bdd..8dbe5be93dd 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/RedundantThrowsDeclarationCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/RedundantThrowsDeclarationCheckSample.java @@ -52,7 +52,8 @@ public C() throws IllegalAccessException { record MyRecord(int a) { // [Compilation ERROR] invalid compact constructor in record MyRecord, throws clause not allowed for compact constructor - private MyRecord throws IOException { // Noncompliant [[sc=27;ec=38;quickfixes=qf_all_in_record]] {{Remove the declaration of thrown exception 'java.io.IOException', as it cannot be thrown from constructor's body.}} + private MyRecord throws IOException { // Noncompliant {{Remove the declaration of thrown exception 'java.io.IOException', as it cannot be thrown from constructor's body.}} [[quickfixes=qf_all_in_record]] +// ^^^^^^^^^^^ // fix@qf_all_in_record {{Remove "IOException"}} // edit@qf_all_in_record [[sc=19;ec=38]] {{}} } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/RedundantTypeCastCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/RedundantTypeCastCheckSample.java index 07f20fba803..96cad997b0f 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/RedundantTypeCastCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/RedundantTypeCastCheckSample.java @@ -19,7 +19,8 @@ class B extends A { } List list; List foo() { Object obj = null; - Object o1 = (List) foo(); // Noncompliant [[sc=17;ec=31]] {{Remove this unnecessary cast to "List".}} + Object o1 = (List) foo(); // Noncompliant {{Remove this unnecessary cast to "List".}} +// ^^^^^^^^^^^^^^ Object o2 = (List) foo(); // Noncompliant {{Remove this unnecessary cast to "List".}} Object o3 = (List) foo(); // Noncompliant {{Remove this unnecessary cast to "List".}} String s1 = (String) obj; // Compliant diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/ReplaceGuavaWithJavaCheck_java9.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/ReplaceGuavaWithJavaCheck_java9.java index 1386c18f0b0..d14fa7c1b5e 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/ReplaceGuavaWithJavaCheck_java9.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/ReplaceGuavaWithJavaCheck_java9.java @@ -8,7 +8,8 @@ import java.io.IOException; class ReplaceGuavaWithJavaCheck { - ReplaceGuavaWithJavaCheck(com.google.common.base.Predicate p) {} // Noncompliant [[sc=29;ec=61]] {{Use "java.util.function.Predicate" instead.}} + ReplaceGuavaWithJavaCheck(com.google.common.base.Predicate p) {} // Noncompliant {{Use "java.util.function.Predicate" instead.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ReplaceGuavaWithJavaCheck(com.google.common.base.Function f) {} // Noncompliant {{Use "java.util.function.Function" instead.}} ReplaceGuavaWithJavaCheck(com.google.common.base.Supplier s) {} // Noncompliant {{Use "java.util.function.Supplier" instead.}} ReplaceGuavaWithJavaCheck(com.google.common.base.Optional o) {} // Noncompliant {{Use "java.util.Optional" instead.}} @@ -41,7 +42,8 @@ void doZ() { } void doWithLambda(B> b) { - b.foo(o -> o.isPresent()); // Noncompliant [[sc=11;ec=12]] {{Use "java.util.Optional" instead.}} + b.foo(o -> o.isPresent()); // Noncompliant {{Use "java.util.Optional" instead.}} +// ^ } static class B { @@ -49,8 +51,10 @@ void foo(java.util.function.Predicate predicate) {} } void tempDir() throws IOException { - com.google.common.io.Files.createTempDir(); // Noncompliant [[sc=5;ec=47]] {{Use "java.nio.file.Files.createTempDirectory" instead.}} - Files.createTempDir(); // Noncompliant [[sc=5;ec=26]] {{Use "java.nio.file.Files.createTempDirectory" instead.}} + com.google.common.io.Files.createTempDir(); // Noncompliant {{Use "java.nio.file.Files.createTempDirectory" instead.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + Files.createTempDir(); // Noncompliant {{Use "java.nio.file.Files.createTempDirectory" instead.}} +// ^^^^^^^^^^^^^^^^^^^^^ java.nio.file.Files.createTempDirectory(""); // Compliant } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/ReplaceLambdaByMethodRefCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/ReplaceLambdaByMethodRefCheckSample.java index 9612655be2a..e24a6d2c9cb 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/ReplaceLambdaByMethodRefCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/ReplaceLambdaByMethodRefCheckSample.java @@ -10,8 +10,8 @@ class A { void fun() { Function method = x -> unknown(x); // Compliant, do not propose to replace with "!unknown!::!unknownMethod!" - Supplier constructor1 = () -> new Unknown(); // Noncompliant {{Replace this lambda with method reference 'Unknown::new'.}} - Supplier constructor2 = () -> new AnyClass.Unknown(); // Noncompliant {{Replace this lambda with method reference 'AnyClass.Unknown::new'.}} + Supplier constructor1 = () -> new Unknown(); // Noncompliant {{Replace this lambda with method reference 'Unknown::new'.}} + Supplier constructor2 = () -> new AnyClass.Unknown(); // Noncompliant {{Replace this lambda with method reference 'AnyClass.Unknown::new'.}} Arrays.asList(new A()).stream().filter(a -> a.coolerThan(0, a)); // Compliant @@ -98,7 +98,7 @@ class AmbiguousMethods { public static void main(String[] args) { Function f = a -> a.f(); // Compliant, A::f is ambiguous - Function f2 = ambig -> ambig.f(); // Noncompliant + Function f2 = ambig -> ambig.f(); // Noncompliant Function f3 = a -> a.f(a); // FN, could be replaced by NotAmbiguous2::f Function f4 = a -> a.unknown(); // Compliant, A::f is ambiguous diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/RestrictedIdentifiersUsageCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/RestrictedIdentifiersUsageCheckSample.java index c42f6fa56f4..09e3a508805 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/RestrictedIdentifiersUsageCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/RestrictedIdentifiersUsageCheckSample.java @@ -3,13 +3,16 @@ public class RestrictedIdentifiersUsageCheckSample { void noncompliant() { - String var = "var"; // Noncompliant [[sc=12;ec=15]]{{Rename this variable to not match a restricted identifier.}} + String var = "var"; // Noncompliant {{Rename this variable to not match a restricted identifier.}} +// ^^^ var = "what is this?"; - String record = "record"; // Noncompliant [[sc=12;ec=18]]{{Rename this variable to not match a restricted identifier.}} + String record = "record"; // Noncompliant {{Rename this variable to not match a restricted identifier.}} +// ^^^^^^ } - void yield(int i) { // Noncompliant [[sc=8;ec=13]]{{Rename this method to not match a restricted identifier.}} + void yield(int i) { // Noncompliant {{Rename this method to not match a restricted identifier.}} +// ^^^^^ switch (i) { case 1: System.out.println(1); diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/RunFinalizersCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/RunFinalizersCheckSample.java index 9d5b9d9f56b..fd497dabbab 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/RunFinalizersCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/RunFinalizersCheckSample.java @@ -2,7 +2,8 @@ class RunFinalizersCheckSample { void foo(){ - Runtime.runFinalizersOnExit(true); // Noncompliant [[sc=13;ec=32]] {{Remove this call to "Runtime.runFinalizersOnExit()".}} + Runtime.runFinalizersOnExit(true); // Noncompliant {{Remove this call to "Runtime.runFinalizersOnExit()".}} +// ^^^^^^^^^^^^^^^^^^^ System.runFinalizersOnExit(false); // Noncompliant } } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/SillyEqualsCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/SillyEqualsCheckSample.java index 4b206bf1461..39bb13d12fe 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/SillyEqualsCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/SillyEqualsCheckSample.java @@ -11,7 +11,7 @@ public void method(Object object) { boolean foo(String x) { lombok.val y = "Hello World"; - return x.equals(y); // Noncompliant - FP - removed by the lombok filter + return x.equals(y); // Noncompliant } } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/SimpleClassNameCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/SimpleClassNameCheckSample.java index 6d9a360b0d0..dc1af35f173 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/SimpleClassNameCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/SimpleClassNameCheckSample.java @@ -13,18 +13,18 @@ class A { ; void notWildcardImport() { var r = new java.util.ArrayList(); // Noncompliant - com.google.common.collect.ImmutableList list; // Noncompliant - com.google.common.collect.ImmutableList.Builder builder = // Noncompliant [[startColumn=5;endColumn=44]] + com.google.common.collect.ImmutableList list; // Noncompliant + com.google.common.collect.ImmutableList.Builder builder = // Noncompliant com.google.common.collect.ImmutableList.builder(); // Noncompliant {{Replace this fully qualified name with "ImmutableList"}} - System.out.println(com.google.common.collect.ImmutableList.class); // Noncompliant [[startColumn=24;endColumn=63]] + System.out.println(com.google.common.collect.ImmutableList.class); // Noncompliant ImmutableList.builder(); ImmutableList anotherList; } void wildcardImport() { - java.util.List myList = // Noncompliant {{Replace this fully qualified name with "List"}} - new java.util.ArrayList(); // Noncompliant [[startColumn=11;endColumn=30]] + java.util.List myList = // Noncompliant {{Replace this fully qualified name with "List"}} + new java.util.ArrayList(); // Noncompliant com.google.common.collect.ImmutableMap map; // Noncompliant diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/StandardCharsetsConstantsCheck_java10.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/StandardCharsetsConstantsCheck_java10.java index ff368d61ef6..d68ee3ccfd6 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/StandardCharsetsConstantsCheck_java10.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/StandardCharsetsConstantsCheck_java10.java @@ -16,16 +16,21 @@ class A { void myMethod() throws Exception { Charset.forName("UTF-8"); // Noncompliant {{Replace Charset.forName() call with StandardCharsets.UTF_8}} - (new ByteArrayOutputStream()).toString("UTF-8"); // Noncompliant {{Replace charset name argument with StandardCharsets.UTF_8}} [[sc=44;ec=51]] + (new ByteArrayOutputStream()).toString("UTF-8"); // Noncompliant {{Replace charset name argument with StandardCharsets.UTF_8}} +// ^^^^^^^ (new ByteArrayOutputStream()).toString(StandardCharsets.UTF_8); - new Scanner(inputStream, "UTF-8"); // Noncompliant {{Replace charset name argument with StandardCharsets.UTF_8}} [[sc=30;ec=37]] + new Scanner(inputStream, "UTF-8"); // Noncompliant {{Replace charset name argument with StandardCharsets.UTF_8}} +// ^^^^^^^ new Scanner(inputStream, StandardCharsets.UTF_8); - new Scanner(file, "UTF-8"); // Noncompliant {{Replace charset name argument with StandardCharsets.UTF_8}} [[sc=23;ec=30]] + new Scanner(file, "UTF-8"); // Noncompliant {{Replace charset name argument with StandardCharsets.UTF_8}} +// ^^^^^^^ new Scanner(file, StandardCharsets.UTF_8); - new Scanner(path, "UTF-8"); // Noncompliant {{Replace charset name argument with StandardCharsets.UTF_8}} [[sc=23;ec=30]] + new Scanner(path, "UTF-8"); // Noncompliant {{Replace charset name argument with StandardCharsets.UTF_8}} +// ^^^^^^^ new Scanner(path, StandardCharsets.UTF_8); - new Scanner(readableByteChannel, "UTF-8"); // Noncompliant {{Replace charset name argument with StandardCharsets.UTF_8}} [[sc=38;ec=45]] + new Scanner(readableByteChannel, "UTF-8"); // Noncompliant {{Replace charset name argument with StandardCharsets.UTF_8}} +// ^^^^^^^ new Scanner(readableByteChannel, StandardCharsets.UTF_8); } } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/StaticFieldUpateCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/StaticFieldUpateCheckSample.java index 27d349154e7..da0c65d7ab2 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/StaticFieldUpateCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/StaticFieldUpateCheckSample.java @@ -6,7 +6,8 @@ class StaticFieldUpateCheckSample { private static int[] staticArray; public void nonCompliantAssignments() { - staticValue = value + 1; // Noncompliant [[sc=5;ec=16]] {{Make the enclosing method "static" or remove this set.}} + staticValue = value + 1; // Noncompliant {{Make the enclosing method "static" or remove this set.}} +// ^^^^^^^^^^^ } public void compliantCode() { MyUnknownClass.staticField = value; // Compliant diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/StaticMemberAccess.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/StaticMemberAccess.java index a0f88922bd7..dec638f5937 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/StaticMemberAccess.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/StaticMemberAccess.java @@ -10,7 +10,7 @@ class StaticMemberAccessParent { class StaticMemberAccessChild extends StaticMemberAccessParent { public StaticMemberAccessChild() { - StaticMemberAccessChild.counter++; // Noncompliant {{Use static access with "checks.StaticMemberAccessParent" for "counter".}} + StaticMemberAccessChild.counter++; // Noncompliant {{Use static access with "checks.StaticMemberAccessParent" for "counter".}} StaticMemberAccessParent.counter++; // Compliant StaticMemberAccessChild.unknown++; // Compliant diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/StrongCipherAlgorithmCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/StrongCipherAlgorithmCheckSample.java index 2381b170349..46c1fad7644 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/StrongCipherAlgorithmCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/StrongCipherAlgorithmCheckSample.java @@ -12,7 +12,7 @@ class StrongCipherAlgorithmCheckSample { void foo() throws NoSuchAlgorithmException, NoSuchPaddingException { Cipher.getInstance(DES_STRING); // Noncompliant Cipher.getInstance(DES_TEXT_BLOCK); // Noncompliant - // Noncompliant@+1 + // Noncompliant@+1 Cipher.getInstance(""" DES"""); } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/SunPackagesUsedCheckCustom.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/SunPackagesUsedCheckCustom.java index bfe465f0a99..e820da1793a 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/SunPackagesUsedCheckCustom.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/SunPackagesUsedCheckCustom.java @@ -7,10 +7,12 @@ private void f() { com.sun.imageio.plugins.bmp d = // Compliant new com.sun.imageio.plugins.bmp(); // Compliant java.util.List a; - sun.Foo b; // Noncompliant [[sc=5;ec=12;secondary=13]] {{Use classes from the Java API instead of Sun classes.}} + sun.Foo b; // Noncompliant {{Use classes from the Java API instead of Sun classes.}} +// ^^^^^^^ db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils .IgnoreAllErrorHandler()); sun // secondary +// ^[el=+3;ec=12]< .Foo.toto .asd c; diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/SunPackagesUsedCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/SunPackagesUsedCheckSample.java index 24529c847b9..48135307e64 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/SunPackagesUsedCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/SunPackagesUsedCheckSample.java @@ -3,8 +3,10 @@ class SunPackagesUsedCheckSample { private void f() { java.util.List a; - sun.Foo b; // Noncompliant [[secondary=+1]] + sun.Foo b; // Noncompliant +// ^^^^^^^ sun.Foo.toto.asd c; // secondary +// ^^^^^^^^^^^^^^^^< } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/SwitchCaseTooBigCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/SwitchCaseTooBigCheckSample.java index 607f9e2db4d..da41c1f782a 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/SwitchCaseTooBigCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/SwitchCaseTooBigCheckSample.java @@ -9,7 +9,8 @@ void f(int myVariable) { System.out.println(); // 3 System.out.println(); // 4 yield 1; // 5 - case 1: // Noncompliant [[sc=7;ec=14]] {{Reduce this switch case number of lines from 7 to at most 5, for example by extracting code into methods.}} + case 1: // Noncompliant {{Reduce this switch case number of lines from 7 to at most 5, for example by extracting code into methods.}} +// ^^^^^^^ System.out.println(); // 1 System.out.println(); // 2 System.out.println(); // 3 @@ -17,7 +18,7 @@ void f(int myVariable) { System.out.println(); // 5 System.out.println(); // 6 yield 1; // 7 - case 2: { System.out.println(); // Noncompliant 1 + case 2: { System.out.println(); // Noncompliant System.out.println(); // 2 System.out.println(); // 3 System.out.println(); // 4 @@ -58,7 +59,7 @@ void f(int myVariable) { }; int j = switch (myVariable) { - case 0 -> { System.out.println(); // Noncompliant 1 + case 0 -> { System.out.println(); // Noncompliant System.out.println(); // 2 System.out.println(); // 3 System.out.println(); // 4 diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/SwitchCasesShouldBeCommaSeparatedCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/SwitchCasesShouldBeCommaSeparatedCheckSample.java index bf1792bef0e..ac18096077a 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/SwitchCasesShouldBeCommaSeparatedCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/SwitchCasesShouldBeCommaSeparatedCheckSample.java @@ -8,7 +8,9 @@ public void nonCompliant(String mode) { case "a": yield 0; case "b": - case "c": // Noncompliant [[sc=7;ec=16;secondary=-1]] {{Merge the previous cases into this one using comma-separated label.}} +// ^^^^^^^^^> + case "c": // Noncompliant {{Merge the previous cases into this one using comma-separated label.}} +// ^^^^^^^^^ yield 42; default: yield returnSomethingElse(); @@ -17,11 +19,16 @@ public void nonCompliant(String mode) { // Switch expression with multiple issues i = switch (mode) { case "a": +// ^^^^^^^^^> case "b": - case "c": // Noncompliant [[sc=7;ec=16;secondary=-1,-2]] {{Merge the previous cases into this one using comma-separated label.}} +// ^^^^^^^^^> + case "c": // Noncompliant {{Merge the previous cases into this one using comma-separated label.}} +// ^^^^^^^^^ yield 42; case "d": - case "e": // Noncompliant [[sc=7;ec=16;secondary=-1,]] {{Merge the previous cases into this one using comma-separated label.}} +// ^^^^^^^^^> + case "e": // Noncompliant {{Merge the previous cases into this one using comma-separated label.}} +// ^^^^^^^^^ default: yield returnSomethingElse(); }; diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/SwitchDefaultLastCaseCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/SwitchDefaultLastCaseCheckSample.java index b64c218cdea..a93a3e04700 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/SwitchDefaultLastCaseCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/SwitchDefaultLastCaseCheckSample.java @@ -5,7 +5,8 @@ class SwitchDefaultLastCaseCheckSample { void foo(WeekendDay weekendDay) { int i = switch (0) { case 0: - default: // Noncompliant [[sc=7;ec=15]] {{Move this default to the end of the switch.}} + default: // Noncompliant {{Move this default to the end of the switch.}} +// ^^^^^^^^ yield 1; case 1: yield 2; diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/SwitchInsteadOfIfSequenceCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/SwitchInsteadOfIfSequenceCheckSample.java index 51fc42d3846..b7a0dab7046 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/SwitchInsteadOfIfSequenceCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/SwitchInsteadOfIfSequenceCheckSample.java @@ -7,10 +7,10 @@ public class SwitchInsteadOfIfSequenceCheckSample { String myStringMethod(){ return ""; } - void foo() { // Noncompliant@+1 [[sc=9;ec=25]] {{Convert this "if/else if" structure into a "switch". (sonar.java.source not set. Assuming 7 or greater.)}} + void foo() { // Noncompliant@+1 {{Convert this "if/else if" structure into a "switch". (sonar.java.source not set. Assuming 7 or greater.)}} if (""" red - """.equals(choice)) { + """.equals(choice)) { dispenseRed(); } else if (""" blue @@ -65,7 +65,7 @@ void foo22() { } } - void foo3() { // Noncompliant@+1 {{Convert this "if/else if" structure into a "switch". (sonar.java.source not set. Assuming 7 or greater.)}} + void foo3() { // Noncompliant@+1 {{Convert this "if/else if" structure into a "switch". (sonar.java.source not set. Assuming 7 or greater.)}} if (""" red """.equals(choice)) { diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/SwitchWithLabelsCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/SwitchWithLabelsCheckSample.java index b5aa9a8c03e..4700b053f6b 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/SwitchWithLabelsCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/SwitchWithLabelsCheckSample.java @@ -7,7 +7,8 @@ public void f(String str, char ch) { break; case 1: break; - foo: // Noncompliant [[sc=7;ec=10]] {{Remove this misleading "foo" label.}} + foo: // Noncompliant {{Remove this misleading "foo" label.}} +// ^^^ break; bar: // Noncompliant break; diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/SynchronizationOnStringOrBoxedCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/SynchronizationOnStringOrBoxedCheckSample.java index dcc9170d1f8..aa8458ed3f2 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/SynchronizationOnStringOrBoxedCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/SynchronizationOnStringOrBoxedCheckSample.java @@ -29,13 +29,13 @@ class A { void method1() { list3 = List.of(); - synchronized(42) { // Noncompliant + synchronized(42) { // Noncompliant // ... } - synchronized(list) { // Noncompliant + synchronized(list) { // Noncompliant // ... } - synchronized(list1) { // Noncompliant + synchronized(list1) { // Noncompliant // ... } synchronized(list2) { // Compliant @@ -47,28 +47,28 @@ void method1() { synchronized(list4) { // Compliant // ... } - synchronized(set) { // Noncompliant + synchronized(set) { // Noncompliant // ... } - synchronized(set1) { // Noncompliant + synchronized(set1) { // Noncompliant // ... } - synchronized(map) { // Noncompliant + synchronized(map) { // Noncompliant // ... } - synchronized(map1) { // Noncompliant + synchronized(map1) { // Noncompliant // ... } - synchronized(entry) { // Noncompliant + synchronized(entry) { // Noncompliant // ... } - synchronized(map2) { // Noncompliant + synchronized(map2) { // Noncompliant // ... } - synchronized(processHandle) { // Noncompliant + synchronized(processHandle) { // Noncompliant // ... } - synchronized(List.of("", "b","c")) { // Noncompliant + synchronized(List.of("", "b","c")) { // Noncompliant // ... } synchronized(list5) { // Compliant diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/TextBlockTabsAndSpaces.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/TextBlockTabsAndSpaces.java index c18af7f29f3..72135c01f01 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/TextBlockTabsAndSpaces.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/TextBlockTabsAndSpaces.java @@ -14,7 +14,7 @@ public class TextBlockTabsAndSpaces { and this one also with tabs """; - // Noncompliant@+1 {{Use only spaces or only tabs for indentation}} + // Noncompliant@+1 {{Use only spaces or only tabs for indentation}} public final static String nonCompliant1 = """ this line is indented with spaces @@ -23,7 +23,7 @@ public class TextBlockTabsAndSpaces { this one also has tabs """; - // Noncompliant@+1 + // Noncompliant@+1 public final static String nonCompliant2 = """ This line is indented with two spaces and a tab """; diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/TextBlocksDuplicatedCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/TextBlocksDuplicatedCheckSample.java index 7ad91fc2977..ce4ab825d00 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/TextBlocksDuplicatedCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/TextBlocksDuplicatedCheckSample.java @@ -43,8 +43,8 @@ class AllConstants { allConstant allConstant allConstant - """; - + """; + private static final String Constant4 = """ allConstant @@ -64,28 +64,39 @@ class ConstantAlreadyDefined { blabla"""; void test() { - System.out.println(""" - constant"""); // Noncompliant@-1 [[secondary=+1]] {{Use already-defined constant 'A' instead of duplicating its value here.}} +// Noncompliant@+1 {{Use already-defined constant 'A' instead of duplicating its value here.}} + System.out.println(""" + constant"""); +// ^[sl=68;el=69;ec=17] + + System.out.println(""" constant"""); +// ^[sl=73;el=74;ec=17]< + + +// Noncompliant@+1 {{Use already-defined constant 'REPORT_WITHOUT_THRESHOLD' instead of duplicating its value here.}} System.out.println(""" - blabla"""); // Noncompliant@-1 [[secondary=+6,+7]] {{Use already-defined constant 'REPORT_WITHOUT_THRESHOLD' instead of duplicating its value here.}} + blabla"""); +// ^[sl=79;el=80;ec=15] System.out.println(""" constant constant"""); // Noncompliant@-2 {{Use already-defined constant 'C' instead of duplicating its value here.}} - - System.out.println("blabla"); + + System.out.println("blabla"); +// ^^^^^^^^< System.out.println(""" - blabla"""); + blabla"""); +// ^[sl=89;el=90;ec=15]< System.out.println(""" - blabla """); + blabla """); System.out.println(""" blabla - """); + """); System.out.println(""" blabla -"""); +"""); } public ConstantAlreadyDefined setProject(Proj project) { @@ -97,7 +108,7 @@ public ConstantAlreadyDefined setProject(Proj project) { } private void setFieldValue(String projectName, Object longName) { - + } public ConstantAlreadyDefined setProject(String projectKey, String projectName) { @@ -121,7 +132,7 @@ public Object key() { class CompleteCoverage { private final String notConstant = """ - blablah"""; // Noncompliant@-1 {{Define a constant instead of duplicating this text block 3 times.}} + blablah"""; // Noncompliant@-1 {{Define a constant instead of duplicating this text block 3 times.}} private final String notConstant2 = """ blablah"""; static String notConstant3 = """ @@ -132,3 +143,4 @@ class CompleteCoverage { private static final String NOT_USED = """ this constant is not used anywhere"""; } + diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/UselessExtendsCheck.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/UselessExtendsCheck.java index 9f64b2c6282..3f5cf3755b7 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/UselessExtendsCheck.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/UselessExtendsCheck.java @@ -9,7 +9,8 @@ class E extends D implements I1, I2 {} // Noncompliant {{"I1" is implemented by class N extends UnknownClass1 implements UnknownInterface1, UnknownInterface2 {} // Compliant -class C5 implements I1, I1 {} // Noncompliant [[sc=25;ec=27]] {{"I1" is listed multiple times.}} +class C5 implements I1, I1 {} // Noncompliant {{"I1" is listed multiple times.}} +// ^^ class Class5 extends UnknownClass1 implements UnknownInterface, diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/UselessImportCheck/WithinPackage.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/UselessImportCheck/WithinPackage.java index 437234aa577..4b2bdaa6864 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/UselessImportCheck/WithinPackage.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/UselessImportCheck/WithinPackage.java @@ -5,8 +5,9 @@ import a.b.c.Baz; import a.b.c.Qux; import a.b.c.ReferencedFromJavadoc; -import a.b.c.NonCompliant; // Noncompliant [[sc=1;ec=27]] -import NonCompliant2; // Noncompliant +import a.b.c.NonCompliant; // Noncompliant +//^[sc=1;ec=27] +import NonCompliant2; // Noncompliant import static a.b.c.Foo.d; import a.b.c.*; import static a.b.c.Foo.*; @@ -15,16 +16,16 @@ import a.b.c.MyAnnotation1; import a.b.c.MyAnnotation2; import a.b.c.MyAnnotation3; -import java.lang.String; // Noncompliant {{Remove this unnecessary import: java.lang classes are always implicitly imported.}} -import java.lang.*; // Noncompliant {{Remove this unnecessary import: java.lang classes are always implicitly imported.}} -import a.b.c.Foo; // Noncompliant {{Remove this duplicated import.}} +import java.lang.String; // Noncompliant {{Remove this unnecessary import: java.lang classes are always implicitly imported.}} +import java.lang.*; // Noncompliant {{Remove this unnecessary import: java.lang classes are always implicitly imported.}} +import a.b.c.Foo; // Noncompliant {{Remove this duplicated import.}} -import checks.UselessImportCheck.*; // Noncompliant {{Remove this unnecessary import: same package classes are always implicitly imported.}} +import checks.UselessImportCheck.*; // Noncompliant {{Remove this unnecessary import: same package classes are always implicitly imported.}} import checks.UselessImportCheckClose.*; import static checks.UselessImportCheck.Foo.*; import checks.UselessImportCheck.foo.*; import checks.UselessImportCheck.foo.Foo; -import pkg.NonCompliant1; // Noncompliant +import pkg.NonCompliant1; // Noncompliant import pkg.CompliantClass1; import pkg.CompliantClass2; import pkg.CompliantClass3; diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/UselessImportCheck/WithoutPackage.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/UselessImportCheck/WithoutPackage.java index 2130505f1f6..76fb18c8b78 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/UselessImportCheck/WithoutPackage.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/UselessImportCheck/WithoutPackage.java @@ -1,5 +1,6 @@ import a.Foo; // Compliant -import a.Bar; // Noncompliant [[sc=1;ec=14]] +import a.Bar; // Noncompliant +//^[sc=1;ec=14] class Foobar extends Foo { diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/regex/EmptyLineRegexCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/regex/EmptyLineRegexCheckSample.java index cdd14d4cb9f..52e0e13ca44 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/regex/EmptyLineRegexCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/regex/EmptyLineRegexCheckSample.java @@ -6,15 +6,18 @@ public class EmptyLineRegexCheckSample { private static final int MY_FLAG = 0x10; - private static final String MY_FIELD_STRING = """ - """; + private static final String MY_FIELD_STRING = ""; void non_compliant_pattern_assigned(String str) { - Pattern p1 = Pattern.compile("^$", Pattern.MULTILINE); // Noncompliant [[sc=34;ec=38;secondary=15,14]] {{Remove MULTILINE mode or change the regex.}} + Pattern p1 = Pattern.compile("^$", Pattern.MULTILINE); // Noncompliant {{Remove MULTILINE mode or change the regex.}} +// ^^^^ p1.matcher(str).find(); +// ^^^< p1.matcher((str)).find(); +// ^^^^^< - Pattern p2 = Pattern.compile("(?m)^$"); // Noncompliant [[sc=34;ec=42]] + Pattern p2 = Pattern.compile("(?m)^$"); // Noncompliant +// ^^^^^^^^ p2.matcher(str).find(); Pattern p3 = Pattern.compile("(?m)^$", Pattern.MULTILINE); // Noncompliant @@ -22,7 +25,8 @@ void non_compliant_pattern_assigned(String str) { } void non_compliant_pattern_directly_used(String str) { - Pattern.compile("^$", Pattern.MULTILINE).matcher(str).find(); // Noncompliant [[sc=21;ec=25]] + Pattern.compile("^$", Pattern.MULTILINE).matcher(str).find(); // Noncompliant +// ^^^^ ^^^< Pattern.compile("(^$)", Pattern.MULTILINE).matcher(str).find(); // Noncompliant Pattern.compile("(?:^$)", Pattern.MULTILINE).matcher(str).find(); // Noncompliant Pattern.compile("(?m)^$").matcher(str).find(); // Noncompliant @@ -41,9 +45,11 @@ void non_compliant_pattern_directly_used(String str) { void nonCompliantOnString(String str) { Pattern.compile("^$", Pattern.MULTILINE).matcher("").find(); // Noncompliant - Pattern p1 = Pattern.compile("^$", Pattern.MULTILINE); // Noncompliant [[secondary=46]] + Pattern p1 = Pattern.compile("^$", Pattern.MULTILINE); // Noncompliant +// ^^^^ boolean b1 = p1.matcher("notEmpty").find(); boolean b2 = p1.matcher("").find(); +// ^^< } void not_used_in_problematic_situations(String str) { @@ -129,12 +135,14 @@ boolean tested_for_emptiness_4(String str) { } boolean not_tested_for_emptiness(String str1, String str2) { - Pattern p4 = Pattern.compile("(?m)^$"); // Noncompliant [[secondary=137]] + Pattern p4 = Pattern.compile("(?m)^$"); // Noncompliant +// ^^^^^^^^ if (str1.isEmpty()) { return false; } return p4.matcher(str1).find() && p4.matcher(str2).find(); +// ^^^^< } void not_identifier(String str1) { @@ -157,7 +165,8 @@ void from_variable_compliant() { } void in_replace(String str) { - String s1 = str.replaceAll("(?m)^$", "Empty"); // Noncompliant [[sc=32;ec=40]] + String s1 = str.replaceAll("(?m)^$", "Empty"); // Noncompliant +// ^^^^^^^^ String s2 = str.replaceAll("^$", "Empty"); // Compliant String s3 = "".replaceAll("(?m)^$", "Empty"); // Noncompliant String s4 = (str).replaceAll("(?m)^$", "Empty"); // Noncompliant @@ -189,8 +198,7 @@ void in_matches(String str) { } String getString() { - return """ - """; + return ""; } @javax.validation.constraints.Pattern(regexp = "^$") // ignored diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/regex/SingleCharacterAlternationWithTextBlocks.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/regex/SingleCharacterAlternationWithTextBlocks.java index 4cc1b577151..1c21f467b8f 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/regex/SingleCharacterAlternationWithTextBlocks.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/regex/SingleCharacterAlternationWithTextBlocks.java @@ -4,7 +4,7 @@ public class SingleCharacterAlternationWithTextBlocks { void nonCompliant(String str) { str.matches(""" - a|b|c"""); // Noncompliant [[sc=7;ec=12]] {{Replace this alternation with a character class.}} + a|b|c"""); // Noncompliant {{Replace this alternation with a character class.}} [[sc=7;ec=12]] // Matches [ab\n] str.matches(""" a|b| diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/security/DebugFeatureEnabledCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/security/DebugFeatureEnabledCheckSample.java index a31f26cdda9..cc6b636479f 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/security/DebugFeatureEnabledCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/security/DebugFeatureEnabledCheckSample.java @@ -4,8 +4,10 @@ // Tests for @EnableWebSecurity. // Tests for printStackTrace are in java/checks/security/DebugFeatureEnabledCheckSample.java -@EnableWebSecurity(debug = true) // Noncompliant [[sc=20;ec=32]] {{Make sure this debug feature is deactivated before delivering the code in production.}} -@EnableWebSecurity(unknown = true, debug = Boolean.TRUE) // Noncompliant [[sc=36;ec=56]] +@EnableWebSecurity(debug = true) // Noncompliant {{Make sure this debug feature is deactivated before delivering the code in production.}} +// ^^^^^^^^^^^^ +@EnableWebSecurity(unknown = true, debug = Boolean.TRUE) // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^ @EnableWebSecurity(debug = false) @EnableWebSecurity(debug) @EnableWebSecurity(true) diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/security/DisableAutoEscapingCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/security/DisableAutoEscapingCheckSample.java index c24df7dc33e..75070bbd01d 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/security/DisableAutoEscapingCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/security/DisableAutoEscapingCheckSample.java @@ -13,7 +13,8 @@ public class DisableAutoEscapingCheckSample { */ public void jMustache() { Mustache.compiler() - .escapeHTML(false) // Noncompliant [[sc=19;ec=24]] {{Make sure disabling auto-escaping feature is safe here.}} + .escapeHTML(false) // Noncompliant {{Make sure disabling auto-escaping feature is safe here.}} +// ^^^^^ .compile(template) .execute(context); diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/security/ExcessiveContentRequestCheck_spring_2_4.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/security/ExcessiveContentRequestCheck_spring_2_4.java index a9d7517cc1a..ae3a5662a3f 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/security/ExcessiveContentRequestCheck_spring_2_4.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/security/ExcessiveContentRequestCheck_spring_2_4.java @@ -12,7 +12,8 @@ public class ExcessiveContentRequestCheck_spring_2_4 { void springMultipartConfigFactory() { MultipartConfigFactory factory = new MultipartConfigFactory(); - factory.setMaxRequestSize(DataSize.ofBytes(8388609)); // Noncompliant [[sc=5;ec=57]] {{The content length limit of 8388609 bytes is greater than the defined limit of 8388608; make sure it is safe here.}} + factory.setMaxRequestSize(DataSize.ofBytes(8388609)); // Noncompliant {{The content length limit of 8388609 bytes is greater than the defined limit of 8388608; make sure it is safe here.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ factory.setMaxRequestSize(DataSize.ofBytes(8388608)); // Compliant factory.setMaxRequestSize(DataSize.ofBytes(8000000)); // Compliant @@ -37,7 +38,8 @@ void springMultipartConfigFactory() { factory.setMaxRequestSize(DataSize.of(1, DataUnit.GIGABYTES)); // Noncompliant factory.setMaxRequestSize(DataSize.of(1, DataUnit.TERABYTES)); // Noncompliant - factory.setMaxFileSize(DataSize.parse("8388609")); // Noncompliant [[sc=5;ec=54]] {{The content length limit of 8388609 bytes is greater than the defined limit of 8388608; make sure it is safe here.}} + factory.setMaxFileSize(DataSize.parse("8388609")); // Noncompliant {{The content length limit of 8388609 bytes is greater than the defined limit of 8388608; make sure it is safe here.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ factory.setMaxFileSize(DataSize.parse("8388609B")); // Noncompliant factory.setMaxFileSize(DataSize.parse("9000KB")); // Noncompliant factory.setMaxFileSize(DataSize.parse("8193KB")); // Noncompliant {{The content length limit of 8389632 bytes is greater than the defined limit of 8388608; make sure it is safe here.}} diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/security/PubliclyWritableDirectories.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/security/PubliclyWritableDirectories.java index 8167712223a..52d3b726d63 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/security/PubliclyWritableDirectories.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/security/PubliclyWritableDirectories.java @@ -26,9 +26,9 @@ public String compliant(Map map) throws IOException { map5.get("TMP"); // Since Java 11 - Path.of("\\Windows\\Temp\\my.txt"); // Noncompliant - Path.of("\\Windows\\Temp\\", "my.txt"); // Noncompliant - Path.of("\\Windows\\Temp\\", "my", "my.txt"); // Noncompliant + Path.of("\\Windows\\Temp\\my.txt"); // Noncompliant + Path.of("\\Windows\\Temp\\", "my.txt"); // Noncompliant + Path.of("\\Windows\\Temp\\", "my", "my.txt"); // Noncompliant } } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/security/UnpredictableSaltCheck.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/security/UnpredictableSaltCheck.java index a00adc507a8..e1ec366c80f 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/security/UnpredictableSaltCheck.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/security/UnpredictableSaltCheck.java @@ -30,7 +30,7 @@ public void checkPBEKeySpec(char[] chars) throws NoSuchAlgorithmException { PBEKeySpec spec2 = new PBEKeySpec(chars, salt(), 1); // Compliant PBEKeySpec spec3 = new PBEKeySpec(chars, sSalt, 1); // Compliant - new PBEParameterSpec("notrandom".getBytes(), 10000); // Noncompliant + new PBEParameterSpec("notrandom".getBytes(), 10000); // Noncompliant new PBEParameterSpec(sSalt, 10000); // Compliant } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/serialization/SerializableFieldInSerializableClassCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/serialization/SerializableFieldInSerializableClassCheckSample.java index 5a78569d9f3..dd0c8926aa8 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/serialization/SerializableFieldInSerializableClassCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/serialization/SerializableFieldInSerializableClassCheckSample.java @@ -6,7 +6,8 @@ class Address { } class Person implements Serializable { - Address address; // Noncompliant [[sc=11;ec=18]] {{Make "address" transient or serializable.}} + Address address; // Noncompliant {{Make "address" transient or serializable.}} +// ^^^^^^^ UnknownField unknownField; // Compliant } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/spring/SpringIncompatibleTransactionalCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/spring/SpringIncompatibleTransactionalCheckSample.java index e3a7b091b1e..703f0aa077b 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/spring/SpringIncompatibleTransactionalCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/spring/SpringIncompatibleTransactionalCheckSample.java @@ -72,7 +72,7 @@ public void methodB() { class SpringIncompatibleTransactionalCheckSampleSupportJavaxTransactional { public void nonTransactional() { - javaxTransactionalDefault(); // Noncompliant + javaxTransactionalDefault(); // Noncompliant javaxTransactionalRequired(); // Compliant, REQUIRED has unknown type javaxTransactionalNotSupported(); javaxTransactionalNever(); diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/spring/TransactionalMethodVisibilityCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/spring/TransactionalMethodVisibilityCheckSample.java index 239dd334f1e..24f0d81d3dd 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/spring/TransactionalMethodVisibilityCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/spring/TransactionalMethodVisibilityCheckSample.java @@ -5,7 +5,8 @@ class TransactionalMethodVisibilityCheckSample { // Cannot compile because a Transactional method should be overridable @org.springframework.transaction.annotation.Transactional - private void privateTransactionalMethod() {} // Noncompliant [[sc=16;ec=42]] {{Make this method "public" or remove the "@Transactional" annotation.}} + private void privateTransactionalMethod() {} // Noncompliant {{Make this method "public" or remove the "@Transactional" annotation.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^ // Cannot compile because a Transactional method should be overridable @Transactional diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/tests/AssertionTypesCheck_JUnit4.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/tests/AssertionTypesCheck_JUnit4.java index 27c17092962..8bdf39af951 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/tests/AssertionTypesCheck_JUnit4.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/tests/AssertionTypesCheck_JUnit4.java @@ -40,7 +40,7 @@ void test_junit() { assertNotEquals(new A[][] {}, new X[][] {}); // Noncompliant assertNotEquals(new int[] {}, new int[] {}); - assertNotEquals(new A[] {}, new int[] {}); // Noncompliant + assertNotEquals(new A[] {}, new int[] {}); // Noncompliant assertNotEquals(new long[] {}, new int[] {}); // Noncompliant assertNotEquals(a, a2); diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/tests/MockitoArgumentMatchersUsedOnAllParameters.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/tests/MockitoArgumentMatchersUsedOnAllParameters.java index a514c6b62c5..55f73419909 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/tests/MockitoArgumentMatchersUsedOnAllParameters.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/tests/MockitoArgumentMatchersUsedOnAllParameters.java @@ -34,7 +34,8 @@ public class MockitoArgumentMatchersUsedOnAllParameters { @Test public void nonCompliant() { verify(foo).bar( - returnRawValue(), // Noncompliant [[sc=7;ec=23]] {{Add an "eq()" argument matcher on this parameter.}} + returnRawValue(), // Noncompliant {{Add an "eq()" argument matcher on this parameter.}} +// ^^^^^^^^^^^^^^^^ any(), any() ); } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/tests/MockitoEqSimplificationCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/tests/MockitoEqSimplificationCheckSample.java index d4f1486fedf..485eef38799 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/tests/MockitoEqSimplificationCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/tests/MockitoEqSimplificationCheckSample.java @@ -32,16 +32,24 @@ public void myTest() { Object v4 = new Object(); Object v5 = new Object(); - given(foo.bar(eq(v1), // Noncompliant [[sc=19;ec=21;secondary=+1,+2]] {{Remove this and every subsequent useless "eq(...)" invocation; pass the values directly.}} + given(foo.bar(eq(v1), // Noncompliant {{Remove this and every subsequent useless "eq(...)" invocation; pass the values directly.}} +// ^^ eq(v2), +// ^^< eq(v3))).willReturn(null); - when(foo.baz(eq(v4), // Noncompliant [[sc=18;ec=20;secondary=+1]] {{Remove this and every subsequent useless "eq(...)" invocation; pass the values directly.}} +// ^^< + when(foo.baz(eq(v4), // Noncompliant {{Remove this and every subsequent useless "eq(...)" invocation; pass the values directly.}} +// ^^ eq(v5))).thenReturn("foo"); - when(foo.baz(Matchers.eq(v4), // Noncompliant [[sc=18;ec=29;secondary=+1]] +// ^^< + when(foo.baz(Matchers.eq(v4), // Noncompliant +// ^^^^^^^^^^^ eq(v5))).thenReturn("foo"); - doThrow(new RuntimeException()).when(foo).quux(eq(42)); // Noncompliant [[sc=52;ec=54]] {{Remove this useless "eq(...)" invocation; pass the values directly.}} +// ^^< + doThrow(new RuntimeException()).when(foo).quux(eq(42)); // Noncompliant {{Remove this useless "eq(...)" invocation; pass the values directly.}} +// ^^ doCallRealMethod().when(foo).baz(eq(v4), eq(v5)); // Noncompliant - verify(foo).bar(eq(v1), eq(v2), eq(v3)); // Noncompliant + verify(foo).bar(eq(v1), eq(v2), eq(v3)); // Noncompliant verify(foo, never()).bar(eq(v1), eq(v2), eq(v3)); // Noncompliant InOrder inOrder = Mockito.inOrder(foo); diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/checks/unused/UnusedLocalVariableCheck.java b/java-checks-test-sources/default/src/main/files/non-compiling/checks/unused/UnusedLocalVariableCheck.java index c58a10bac62..08d88540153 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/checks/unused/UnusedLocalVariableCheck.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/checks/unused/UnusedLocalVariableCheck.java @@ -5,7 +5,8 @@ class UnusedLocalVariableCheck { public void f(int unusedParameter) { - int unusedLocalVariable; // Noncompliant [[sc=9;=ec=28]] {{Remove this unused "unusedLocalVariable" local variable.}} + int unusedLocalVariable; // Noncompliant {{Remove this unused "unusedLocalVariable" local variable.}} +// ^^^^^^^^^^^^^^^^^^^ unknown++; this.unknown++; } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/symbolicexecution/checks/ConditionAlwaysTrueOrFalseCheck.java b/java-checks-test-sources/default/src/main/files/non-compiling/symbolicexecution/checks/ConditionAlwaysTrueOrFalseCheck.java index 4b9a2fb4ce1..000864170cd 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/symbolicexecution/checks/ConditionAlwaysTrueOrFalseCheck.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/symbolicexecution/checks/ConditionAlwaysTrueOrFalseCheck.java @@ -682,7 +682,7 @@ public void relational_l(boolean parameter1, boolean parameter2) { public void relational_ne(boolean parameter1, boolean parameter2) { if (parameter1 != parameter2) { - if (parameter1 == parameter2) { // Noncompliant {{Change this condition so that it does not always evaluate to "false"}} + if (parameter1 == parameter2) { // Noncompliant {{Change this condition so that it does not always evaluate to "false"}} } if (parameter1 != parameter2) { // Noncompliant {{Remove this expression which always evaluates to "true"}} } @@ -1271,8 +1271,8 @@ boolean prodMode() { protected boolean shouldGzip() { return env.gzip() - && env.prodMode() - && request.header(ACCEPT_ENCODING, "").contains(GZIP); + && env.prodMode() + && request.header(ACCEPT_ENCODING, "").contains(GZIP); } private Object mutex; @@ -1331,7 +1331,7 @@ static void fromEntryArray(boolean foo) { Entry entry = new Object(); printState(); boolean reusable = entry instanceof ImmutableMapEntry - && entry.isReusable(); + && entry.isReusable(); printState(); Object o = reusable ? entry : new Object(); // compliant both path are explored. return; @@ -1982,19 +1982,19 @@ public void constant(boolean parameter) { } class Squid2583 { - private final transient java.io.ByteArrayOutputStream trasientBaos = new java.io.ByteArrayOutputStream(); + private final transient java.io.ByteArrayOutputStream trasientBaos = new java.io.ByteArrayOutputStream(); - private final java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); + private final java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); - public void raiseIssue() { - if (trasientBaos != null) { // Noncompliant {{Remove this expression which always evaluates to "true"}} - trasientBaos.reset(); - } + public void raiseIssue() { + if (trasientBaos != null) { // Noncompliant {{Remove this expression which always evaluates to "true"}} + trasientBaos.reset(); + } - if (baos != null) { // Noncompliant {{Remove this expression which always evaluates to "true"}} - baos.reset(); - } + if (baos != null) { // Noncompliant {{Remove this expression which always evaluates to "true"}} + baos.reset(); } + } } class NestedMax { diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/symbolicexecution/checks/InvariantReturnCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/symbolicexecution/checks/InvariantReturnCheckSample.java index 0f7a6df9c59..10034a5c63e 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/symbolicexecution/checks/InvariantReturnCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/symbolicexecution/checks/InvariantReturnCheckSample.java @@ -72,7 +72,8 @@ private Optional getSth(SelectableChannel channel) { class NoncompliantExample { - boolean filter(SelectableChannel channel) { // Noncompliant [[sc=13;ec=19]] {{Refactor this method to not always return the same value.}} + boolean filter(SelectableChannel channel) { // Noncompliant {{Refactor this method to not always return the same value.}} +// ^^^^^^ if (channel == null){ return false; } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/symbolicexecution/checks/MapComputeIfAbsentOrPresentCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/symbolicexecution/checks/MapComputeIfAbsentOrPresentCheckSample.java index 6a3dc72af20..9ad2059a813 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/symbolicexecution/checks/MapComputeIfAbsentOrPresentCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/symbolicexecution/checks/MapComputeIfAbsentOrPresentCheckSample.java @@ -26,7 +26,7 @@ void foo2(Map items, String key) throws MyException { } } void foo3(Map items, String key) { - Object value = items.get(key); // Noncompliant (bar2 is throwing a runtime exception) + Object value = items.get(key); // Noncompliant if (value == null) { items.put(key, bar2()); } diff --git a/java-checks-test-sources/default/src/main/files/non-compiling/symbolicexecution/checks/NonNullSetToNullCheckSample.java b/java-checks-test-sources/default/src/main/files/non-compiling/symbolicexecution/checks/NonNullSetToNullCheckSample.java index 43b6476ecdc..10a50e8d0db 100644 --- a/java-checks-test-sources/default/src/main/files/non-compiling/symbolicexecution/checks/NonNullSetToNullCheckSample.java +++ b/java-checks-test-sources/default/src/main/files/non-compiling/symbolicexecution/checks/NonNullSetToNullCheckSample.java @@ -22,7 +22,7 @@ public NonNullSetToNullCheckSample(@Nonnull String color, String other) { // ============ 2. Testing Return values ============ @Nonnull public String colorMix() { - return null; // Noncompliant + return null; // Noncompliant } @Nonnull diff --git a/java-checks-test-sources/default/src/main/java/SpringScanDefaultPackageCheckSample.java b/java-checks-test-sources/default/src/main/java/SpringScanDefaultPackageCheckSample.java index 112a1099e76..f0b69e43274 100644 --- a/java-checks-test-sources/default/src/main/java/SpringScanDefaultPackageCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/SpringScanDefaultPackageCheckSample.java @@ -6,26 +6,36 @@ class SpringScanDefaultPackageCheckSample { @Configuration - @ComponentScan // Noncompliant [[sc=4;ec=17]] {{Remove the annotation "@ComponentScan" or move the annotated class out of the default package.}} - @SpringBootApplication // Noncompliant [[sc=4;ec=25]] {{Remove the annotation "@SpringBootApplication" or move the annotated class out of the default package.}} - @ServletComponentScan // Noncompliant [[sc=4;ec=24]] {{Remove the annotation "@ServletComponentScan" or move the annotated class out of the default package.}} + @ComponentScan // Noncompliant {{Remove the annotation "@ComponentScan" or move the annotated class out of the default package.}} +// ^^^^^^^^^^^^^ + @SpringBootApplication // Noncompliant {{Remove the annotation "@SpringBootApplication" or move the annotated class out of the default package.}} +// ^^^^^^^^^^^^^^^^^^^^^ + @ServletComponentScan // Noncompliant {{Remove the annotation "@ServletComponentScan" or move the annotated class out of the default package.}} +// ^^^^^^^^^^^^^^^^^^^^ class SomeApp {} - @ComponentScan("") // Noncompliant [[sc=18;ec=20]] {{Define packages to scan. Don't rely on the default package.}} + @ComponentScan("") // Noncompliant {{Define packages to scan. Don't rely on the default package.}} +// ^^ @ComponentScan("org.company") @ComponentScan({ - "", // Noncompliant [[sc=5;ec=7]] {{Define packages to scan. Don't rely on the default package.}} + "", // Noncompliant {{Define packages to scan. Don't rely on the default package.}} +// ^^ "org.company", "" // Noncompliant }) - @ComponentScan(value = "") // Noncompliant [[sc=26;ec=28]] {{Define packages to scan. Don't rely on the default package.}} - @ComponentScan(value = {""}) // Noncompliant [[sc=27;ec=29]] {{Define packages to scan. Don't rely on the default package.}} - @ComponentScan(lazyInit = true, basePackages = "") // Noncompliant [[sc=50;ec=52]] + @ComponentScan(value = "") // Noncompliant {{Define packages to scan. Don't rely on the default package.}} +// ^^ + @ComponentScan(value = {""}) // Noncompliant {{Define packages to scan. Don't rely on the default package.}} +// ^^ + @ComponentScan(lazyInit = true, basePackages = "") // Noncompliant +// ^^ @ComponentScan(basePackages = {""}) // Noncompliant @ComponentScan(basePackageClasses = {Map.class, java.util.Map.class}) - @ComponentScan(basePackageClasses = App.class) // Noncompliant [[sc=39;ec=42]] {{Remove the annotation "@ComponentScan" or move the "App" class out of the default package.}} + @ComponentScan(basePackageClasses = App.class) // Noncompliant {{Remove the annotation "@ComponentScan" or move the "App" class out of the default package.}} +// ^^^ @ComponentScan(basePackageClasses = { - App.class, // Noncompliant [[sc=5;ec=8]] {{Remove the annotation "@ComponentScan" or move the "App" class out of the default package.}} + App.class, // Noncompliant {{Remove the annotation "@ComponentScan" or move the "App" class out of the default package.}} +// ^^^ Map.class, Controller.class, // Noncompliant }) diff --git a/java-checks-test-sources/default/src/main/java/WithoutPackage.java b/java-checks-test-sources/default/src/main/java/WithoutPackage.java index 3dc809c5f25..88f97753d86 100644 --- a/java-checks-test-sources/default/src/main/java/WithoutPackage.java +++ b/java-checks-test-sources/default/src/main/java/WithoutPackage.java @@ -1,5 +1,5 @@ import a.b.c.Foo; // Compliant -import a.b.c.Bar; // Noncompliant +import a.b.c.Bar; // Noncompliant class Foobar extends Foo { diff --git a/java-checks-test-sources/default/src/main/java/checks/AbstractClassNoFieldShouldBeInterfaceCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/AbstractClassNoFieldShouldBeInterfaceCheckSample.java index ef1ecc6a444..3ed146c431e 100644 --- a/java-checks-test-sources/default/src/main/java/checks/AbstractClassNoFieldShouldBeInterfaceCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/AbstractClassNoFieldShouldBeInterfaceCheckSample.java @@ -9,7 +9,8 @@ abstract class AbstractClassNoFieldShouldBeInterfaceCheckSampleA { abstract void method(); } -abstract class AbstractClassNoFieldShouldBeInterfaceCheckSampleB { // Noncompliant [[sc=16;ec=65]] {{Convert the abstract class "AbstractClassNoFieldShouldBeInterfaceCheckSampleB" into an interface.}} +abstract class AbstractClassNoFieldShouldBeInterfaceCheckSampleB { // Noncompliant {{Convert the abstract class "AbstractClassNoFieldShouldBeInterfaceCheckSampleB" into an interface.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ int method(){ return 1; } diff --git a/java-checks-test-sources/default/src/main/java/checks/AccessibilityChangeCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/AccessibilityChangeCheckSample.java index 884e1a8a948..86f186562ff 100644 --- a/java-checks-test-sources/default/src/main/java/checks/AccessibilityChangeCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/AccessibilityChangeCheckSample.java @@ -21,38 +21,38 @@ void accessibilityChangeOnRecordFields() throws NoSuchFieldException, IllegalAcc Person person = new Person("A", 26); Field field = Person.class.getDeclaredField("name"); - field.setAccessible(true); // Noncompliant before Java 16 - field.set(person, "B"); // Noncompliant before Java 16 + field.setAccessible(true); // Noncompliant + field.set(person, "B"); // Noncompliant - Person.class.getField("name").setAccessible(true); // Noncompliant before Java 16 - Person.class.getField("name").set(person, "B"); // Noncompliant before Java 16 + Person.class.getField("name").setAccessible(true); // Noncompliant + Person.class.getField("name").set(person, "B"); // Noncompliant Field[] fields = Person.class.getDeclaredFields(); - fields[0].setAccessible(true); // Noncompliant before Java 16 - fields[0].set(person, "B"); // Noncompliant before Java 16 - fields[0].setAccessible(true); // Noncompliant before Java 16 - fields[0].set(person, "B"); // Noncompliant before Java 16 + fields[0].setAccessible(true); // Noncompliant + fields[0].set(person, "B"); // Noncompliant + fields[0].setAccessible(true); // Noncompliant + fields[0].set(person, "B"); // Noncompliant - Person.class.getFields()[0].setAccessible(true); // Noncompliant before Java 16 - Person.class.getFields()[0].set(person, "B"); // Noncompliant before Java 16 - Person.class.getDeclaredFields()[0].setAccessible(true); // Noncompliant before Java 16 - Person.class.getDeclaredFields()[0].set(person, "B"); // Noncompliant before Java 16 + Person.class.getFields()[0].setAccessible(true); // Noncompliant + Person.class.getFields()[0].set(person, "B"); // Noncompliant + Person.class.getDeclaredFields()[0].setAccessible(true); // Noncompliant + Person.class.getDeclaredFields()[0].set(person, "B"); // Noncompliant Field someMagicField = getAField(); - someMagicField.setAccessible(true); // Noncompliant FP Not exploring fields retrieved from non standard methods - someMagicField.set(person, "B"); // Noncompliant FP Not exploring fields retrieved from non standard methods + someMagicField.setAccessible(true); // Noncompliant + someMagicField.set(person, "B"); // Noncompliant - getAField().setAccessible(true); // Noncompliant FP Not exploring fields retrieved from non standard methods - getAField().set(person, "B"); // Noncompliant FP Not exploring fields retrieved from non standard methods + getAField().setAccessible(true); // Noncompliant + getAField().set(person, "B"); // Noncompliant Field nullInitializedField = null; - nullInitializedField.setAccessible(true); // Noncompliant FP Not exploring fields retrieved from non standard methods - nullInitializedField.set(person, "B"); // Noncompliant FP Not exploring fields retrieved from non standard methods + nullInitializedField.setAccessible(true); // Noncompliant + nullInitializedField.set(person, "B"); // Noncompliant Field fieldFromDynamicallyLoadedClass = Class.forName("org.sonar.some.package.SomeClass").getDeclaredField(""); - fieldFromDynamicallyLoadedClass.setAccessible(true); // Noncompliant FP Not exploring fields retrieved from non standard methods - fieldFromDynamicallyLoadedClass.set(person, "B"); // Noncompliant FP Not exploring fields retrieved from non standard methods + fieldFromDynamicallyLoadedClass.setAccessible(true); // Noncompliant + fieldFromDynamicallyLoadedClass.set(person, "B"); // Noncompliant } Field getAField() { diff --git a/java-checks-test-sources/default/src/main/java/checks/AccessibilityChangeCheckWithRecordSupport.java b/java-checks-test-sources/default/src/main/java/checks/AccessibilityChangeCheckWithRecordSupport.java index 9feddf2f653..fed19cc028e 100644 --- a/java-checks-test-sources/default/src/main/java/checks/AccessibilityChangeCheckWithRecordSupport.java +++ b/java-checks-test-sources/default/src/main/java/checks/AccessibilityChangeCheckWithRecordSupport.java @@ -15,12 +15,12 @@ void doSomething() throws NoSuchFieldException, IllegalAccessException { this.getClass().getField("name").set(this, "B"); // Compliant because reported by S6216 // Wrong getClass - getClass(null).getField("name").setAccessible(true); // Noncompliant because not recognized as a Record - getClass(null).getField("name").set(this, "B"); // Noncompliant because not recognized as a Record + getClass(null).getField("name").setAccessible(true); // Noncompliant + getClass(null).getField("name").set(this, "B"); // Noncompliant Class getClass = null; - getClass.getField("name").setAccessible(true); // Noncompliant because not recognized as a Record - getClass.getField("name").set(this, "B"); // Noncompliant because not recognized as a Record + getClass.getField("name").setAccessible(true); // Noncompliant + getClass.getField("name").set(this, "B"); // Noncompliant } } @@ -47,19 +47,19 @@ void accessibilityChangeOnRecordFields() throws NoSuchFieldException, IllegalAcc Person.class.getDeclaredFields()[0].set(person, "B"); // Compliant because reported by S6216 Field someMagicField = getAField(); - someMagicField.setAccessible(true); // Noncompliant FP Not exploring fields retrieved from non standard methods - someMagicField.set(person, "B"); // Noncompliant FP Not exploring fields retrieved from non standard methods + someMagicField.setAccessible(true); // Noncompliant + someMagicField.set(person, "B"); // Noncompliant - getAField().setAccessible(true); // Noncompliant FP Not exploring fields retrieved from non standard methods - getAField().set(person, "B"); // Noncompliant FP Not exploring fields retrieved from non standard methods + getAField().setAccessible(true); // Noncompliant + getAField().set(person, "B"); // Noncompliant Field nullInitializedField = null; - nullInitializedField.setAccessible(true); // Noncompliant FP Not exploring fields retrieved from non standard methods - nullInitializedField.set(person, "B"); // Noncompliant FP Not exploring fields retrieved from non standard methods + nullInitializedField.setAccessible(true); // Noncompliant + nullInitializedField.set(person, "B"); // Noncompliant Field fieldFromDynamicallyLoadedClass = Class.forName("org.sonar.some.package.SomeClass").getDeclaredField(""); - fieldFromDynamicallyLoadedClass.setAccessible(true); // Noncompliant FP Not exploring fields retrieved from non standard methods - fieldFromDynamicallyLoadedClass.set(person, "B"); // Noncompliant FP Not exploring fields retrieved from non standard methods + fieldFromDynamicallyLoadedClass.setAccessible(true); // Noncompliant + fieldFromDynamicallyLoadedClass.set(person, "B"); // Noncompliant Class someType = Person.class; someType.getFields()[0].setAccessible(true); // Compliant because reported by S6216 diff --git a/java-checks-test-sources/default/src/main/java/checks/AccessibilityChangeOnRecordsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/AccessibilityChangeOnRecordsCheckSample.java index dae499a05f1..0f7911ce9ac 100644 --- a/java-checks-test-sources/default/src/main/java/checks/AccessibilityChangeOnRecordsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/AccessibilityChangeOnRecordsCheckSample.java @@ -11,7 +11,9 @@ private void modifyAccessibility() throws IllegalAccessException, NoSuchFieldExc Person person = new Person("A", 26); Field field = Person.class.getDeclaredField("name"); field.setAccessible(true); - field.set(person, "B"); // Noncompliant {{Remove this private field update which will never succeed}}[[secondary=-1]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^> + field.set(person, "B"); // Noncompliant {{Remove this private field update which will never succeed}} +// ^^^^^^^^^^^^^^^^^^^^^^ Field nameField = Person.class.getDeclaredField("name"); diff --git a/java-checks-test-sources/default/src/main/java/checks/AllBranchesAreIdentical.java b/java-checks-test-sources/default/src/main/java/checks/AllBranchesAreIdentical.java index 69f77a6da83..9c7703189d3 100644 --- a/java-checks-test-sources/default/src/main/java/checks/AllBranchesAreIdentical.java +++ b/java-checks-test-sources/default/src/main/java/checks/AllBranchesAreIdentical.java @@ -5,7 +5,8 @@ abstract class AllBranchesAreIdentical { int x; void conditionalExpression () { - x = true ? 1 : // Noncompliant [[sc=9;ec=15]] {{This conditional operation returns the same value whether the condition is "true" or "false".}} + x = true ? 1 : // Noncompliant {{This conditional operation returns the same value whether the condition is "true" or "false".}} +// ^^^^^^ (1); x = true ? 1 * 5 : 1 * 5; // Noncompliant {{This conditional operation returns the same value whether the condition is "true" or "false".}} x = true ? 1 : 2; @@ -13,7 +14,8 @@ void conditionalExpression () { } void switchStatement() { - switch (1) { // Noncompliant [[sc=5;ec=11]] {{Remove this conditional structure or edit its code blocks so that they're not all the same.}} + switch (1) { // Noncompliant {{Remove this conditional structure or edit its code blocks so that they're not all the same.}} +// ^^^^^^ case 1: doSomething(); break; @@ -63,7 +65,8 @@ void switchStatement() { void ifStatement(int b) { - if (b == 0) { // Noncompliant [[sc=5;ec=7]] {{Remove this conditional structure or edit its code blocks so that they're not all the same.}} + if (b == 0) { // Noncompliant {{Remove this conditional structure or edit its code blocks so that they're not all the same.}} +// ^^ doOneMoreThing(); } else { doOneMoreThing(); diff --git a/java-checks-test-sources/default/src/main/java/checks/AnnotationDefaultArgumentCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/AnnotationDefaultArgumentCheckSample.java index 7f207bdf486..20b00720145 100644 --- a/java-checks-test-sources/default/src/main/java/checks/AnnotationDefaultArgumentCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/AnnotationDefaultArgumentCheckSample.java @@ -17,12 +17,14 @@ class AnnotationDefaultArgumentCheckSample { private static final int FIELD_VALUE_INT = 0; @CustomAnnotation(field1="field1Default", field2="", field3="") // Noncompliant - @MyAnnotationDefaultCheck(myName="myName", myInteger=2) // Noncompliant [[sc=29;ec=44]] {{Remove this default value assigned to parameter "myName".}} + @MyAnnotationDefaultCheck(myName="myName", myInteger=2) // Noncompliant {{Remove this default value assigned to parameter "myName".}} +// ^^^^^^^^^^^^^^^ @MyAnnotationDefaultCheck2("defaultValue") // Noncompliant @MyAnnotationDefaultCheck3(myHexaInteger = 0x000) // Noncompliant {{Remove this default value assigned to parameter "myHexaInteger".}} void m1() { } - @MyAnnotationDefaultCheck(myName="foo", myInteger=0) // Noncompliant [[sc=43;ec=54]] {{Remove this default value assigned to parameter "myInteger".}} + @MyAnnotationDefaultCheck(myName="foo", myInteger=0) // Noncompliant {{Remove this default value assigned to parameter "myInteger".}} +// ^^^^^^^^^^^ @MyAnnotationDefaultCheck2("someValue") @CustomAnnotation(field1="", field2="field2Default", field3="") // Noncompliant void m2() { } diff --git a/java-checks-test-sources/default/src/main/java/checks/AnonymousClassShouldBeLambdaCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/AnonymousClassShouldBeLambdaCheckSample.java index 439d8236b15..d467859a8b4 100644 --- a/java-checks-test-sources/default/src/main/java/checks/AnonymousClassShouldBeLambdaCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/AnonymousClassShouldBeLambdaCheckSample.java @@ -256,7 +256,7 @@ public void foo() { }; Lvl2 level2 = () -> {}; - Function a = new Function() { // Noncompliant - function overrides equals from object + Function a = new Function() { // Noncompliant @Override public Date apply(Object o) { return new Date(); @@ -299,7 +299,7 @@ int globalPowerOfTwo(int n) { } void testNotThisInstanceMethod() { - Math f = new Math() { // Noncompliant + Math f = new Math() { // Noncompliant @Override public int powerOfTwo(int n) { return globalPowerOfTwo(n); diff --git a/java-checks-test-sources/default/src/main/java/checks/ArrayDesignatorAfterTypeCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ArrayDesignatorAfterTypeCheckSample.java index 3cfbaa2074d..d1c72452e4c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ArrayDesignatorAfterTypeCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ArrayDesignatorAfterTypeCheckSample.java @@ -4,39 +4,42 @@ class ArrayDesignatorAfterTypeCheckSample { - public int getVector()[] { return new int[0]; } // Noncompliant [[sc=25;ec=27;quickfixes=qf1]] {{Move the array designators [] to the end of the return type.}} + public int getVector()[] { return new int[0]; } // Noncompliant {{Move the array designators [] to the end of the return type.}} [[quickfixes=qf1]] +// ^^ // fix@qf1 {{Move [] to the return type}} // edit@qf1 [[sc=25;ec=27]] {{}} // edit@qf1 [[sc=13;ec=13]] {{[]}} - public List getList()[] { return null; } // Noncompliant [[sc=32;ec=34;quickfixes=qf2]] + public List getList()[] { return null; } // Noncompliant [[quickfixes=qf2]] +// ^^ // fix@qf2 {{Move [] to the return type}} // edit@qf2 [[sc=32;ec=34]] {{}} // edit@qf2 [[sc=22;ec=22]] {{[]}} public int[] getVectorCompliant() { return new int[0]; } // Compliant - public int[] getMatrix()[] { return new int[0][]; } // Noncompliant {{Move the array designators [] to the end of the return type.}} + public int[] getMatrix()[] { return new int[0][]; } // Noncompliant {{Move the array designators [] to the end of the return type.}} public int[][] getMatrixCompliant() { return new int[0][]; } // Compliant - public int foo()[][][][] { return new int[0][][][]; } // Noncompliant[[sc=19;ec=27;quickfixes=qf3]] {{Move the array designators [][][][] to the end of the return type.}} + public int foo()[][][][] { return new int[0][][][]; } // Noncompliant {{Move the array designators [][][][] to the end of the return type.}} [[quickfixes=qf3]] +// ^^^^^^^^ // fix@qf3 {{Move [][][][] to the return type}} // edit@qf3 [[sc=19;ec=27]] {{}} // edit@qf3 [[sc=13;ec=13]] {{[][][][]}} public int - bar()[] { return new int[0]; } // Noncompliant {{Move the array designators [] to the end of the return type.}} + bar()[] { return new int[0]; } // Noncompliant {{Move the array designators [] to the end of the return type.}} public int qix() - [] { return new int[0]; } // Noncompliant {{Move the array designators [] to the end of the return type.}} + [] { return new int[0]; } // Noncompliant {{Move the array designators [] to the end of the return type.}} public int[] goo() { return new int[0]; } // Compliant interface B { - int foo()[]; // Noncompliant {{Move the array designators [] to the end of the return type.}} + int foo()[]; // Noncompliant {{Move the array designators [] to the end of the return type.}} int[] bar(); // Compliant } diff --git a/java-checks-test-sources/default/src/main/java/checks/ArrayDesignatorOnVariableCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ArrayDesignatorOnVariableCheckSample.java index c64b7783234..04e0ccf7638 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ArrayDesignatorOnVariableCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ArrayDesignatorOnVariableCheckSample.java @@ -3,14 +3,18 @@ class ArrayDesignatorOnVariableCheckSample { int[] a, b, - c[][][][][], // Noncompliant [[sc=9;ec=20;quickfixes=!]] {{Move the array designators [][][][][] to the type.}} - d[], // Noncompliant [[sc=9;ec=12;quickfixes=!]] {{Move the array designators [] to the type.}} + c[][][][][], // Noncompliant {{Move the array designators [][][][][] to the type.}} +// ^^^^^^^^^^^ + d[], // Noncompliant [[quickfixes=!]] +// ^^^ e, - f // Noncompliant [[sc=9;sl=+0;ec=11;el=+1;quickfixes=!]] {{Move the array designators [] to the type.}} + f // Noncompliant [[quickfixes=!]] +// ^[sc=9;ec=10;sl=11;el=13] []; interface B { - int a[] = null; // Noncompliant [[sc=9;ec=12;quickfixes=qf1]] {{Move the array designators [] to the type.}} + int a[] = null; // Noncompliant [[quickfixes=qf1]] +// ^^^ // fix@qf1 {{Move [] to the variable type}} // edit@qf1 [[sc=10;ec=12]] {{}} // edit@qf1 [[sc=8;ec=8]]{{[]}} @@ -20,18 +24,21 @@ interface B { class C { private void foo( int[] a, - int b[]) { // Noncompliant [[sc=11;ec=14;quickfixes=qf2]] {{Move the array designators [] to the type.}} + int b[]) { // Noncompliant [[quickfixes=qf2]] +// ^^^ // fix@qf2 {{Move [] to the variable type}} // edit@qf2 [[sc=12;ec=14]] {{}} // edit@qf2 [[sc=10;ec=10]]{{[]}} - for (String c[] : new String[0][]) { // Noncompliant [[sc=19;ec=22;quickfixes=qf3]] {{Move the array designators [] to the type.}} + for (String c[] : new String[0][]) { // Noncompliant [[quickfixes=qf3]] +// ^^^ // fix@qf3 {{Move [] to the variable type}} // edit@qf3 [[sc=20;ec=22]] {{}} // edit@qf3 [[sc=18;ec=18]]{{[]}} } - for (String d[] = new String[0];;) { // Noncompliant [[sc=19;ec=22;quickfixes=qf4]] + for (String d[] = new String[0];;) { // Noncompliant [[quickfixes=qf4]] +// ^^^ // fix@qf4 {{Move [] to the variable type}} // edit@qf4 [[sc=20;ec=22]] {{}} // edit@qf4 [[sc=18;ec=18]]{{[]}} @@ -43,18 +50,22 @@ private void foo( { int g; - int h[]; // Noncompliant [[sc=13;ec=16;quickfixes=qf5]] + int h[]; // Noncompliant [[quickfixes=qf5]] +// ^^^ // fix@qf5 {{Move [] to the variable type}} // edit@qf5 [[sc=14;ec=16]] {{}} // edit@qf5 [[sc=12;ec=12]]{{[]}} int i; bar(); - int l[], m; // Noncompliant [[sc=13;ec=16;quickfixes=!]] - int[] n[][]; // Noncompliant [[sc=15;ec=20;quickfixes=qf6]] + int l[], m; // Noncompliant [[quickfixes=!]] +// ^^^ + int[] n[][]; // Noncompliant [[quickfixes=qf6]] +// ^^^^^ // fix@qf6 {{Move [][] to the variable type}} // edit@qf6 [[sc=16;ec=20]] {{}} // edit@qf6 [[sc=14;ec=14]]{{[][]}} - int[] o[][][]; // Noncompliant [[sc=15;ec=22;quickfixes=qf7]] + int[] o[][][]; // Noncompliant [[quickfixes=qf7]] +// ^^^^^^^ // fix@qf7 {{Move [][][] to the variable type}} // edit@qf7 [[sc=16;ec=22]] {{}} // edit@qf7 [[sc=14;ec=14]]{{[][][]}} diff --git a/java-checks-test-sources/default/src/main/java/checks/ArrayForVarArgCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ArrayForVarArgCheckSample.java index 34d8bcf4e69..7215280ddb3 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ArrayForVarArgCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ArrayForVarArgCheckSample.java @@ -10,28 +10,29 @@ class ArrayForVarArgCheckSample { ArrayForVarArgCheckSample(String ... params) { } ArrayForVarArgCheckSample(int i, X ... xs) { } public void callTheThing(String s) throws IOException { - doTrickyThing(new String[][]{new String[]{"hello", "world"}}); // Noncompliant {{Remove this array creation and simply pass the elements.}} + doTrickyThing(new String[][]{new String[]{"hello", "world"}}); // Noncompliant {{Remove this array creation and simply pass the elements.}} doTrickyThing(new String[]{"hello", "world"}); // Compliant - doTrickyThing(new ArrayForVarArgCheckSampleFoo[][]{new ArrayForVarArgCheckSampleFoo[]{foo, foo}}); // Noncompliant {{Remove this array creation and simply pass the elements.}} + doTrickyThing(new ArrayForVarArgCheckSampleFoo[][]{new ArrayForVarArgCheckSampleFoo[]{foo, foo}}); // Noncompliant {{Remove this array creation and simply pass the elements.}} doTrickyThing(new ArrayForVarArgCheckSampleFoo[]{foo, foo}); // Compliant - doTheThing(new String[] { "s1", "s2"}); // Noncompliant {{Remove this array creation and simply pass the elements.}} [[sc=16;ec=42]] + doTheThing(new String[] { "s1", "s2"}); // Noncompliant {{Remove this array creation and simply pass the elements.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^ doTheThing(new String[12]); - doTheThing(new String[0]); // Noncompliant {{Remove this array creation.}} - doTheThing(new String[] {}); // Noncompliant {{Remove this array creation.}} + doTheThing(new String[0]); // Noncompliant {{Remove this array creation.}} + doTheThing(new String[] {}); // Noncompliant {{Remove this array creation.}} doTheThing("s1", "s2"); doTheThing("s1"); - doTheThing2(new ArrayForVarArgCheckSampleFoo[] {foo, foo}); // Noncompliant {{Remove this array creation and simply pass the elements.}} + doTheThing2(new ArrayForVarArgCheckSampleFoo[] {foo, foo}); // Noncompliant {{Remove this array creation and simply pass the elements.}} doTheThing2(new ArrayForVarArgCheckSampleFoo[12]); - doTheThing2(new ArrayForVarArgCheckSampleFoo[0]); // Noncompliant {{Remove this array creation.}} + doTheThing2(new ArrayForVarArgCheckSampleFoo[0]); // Noncompliant {{Remove this array creation.}} doTheThing2(new ArrayForVarArgCheckSampleFoo(), new ArrayForVarArgCheckSampleBar()); callTheThing(""); new ArrayForVarArgCheckSample(); new ArrayForVarArgCheckSample(new String[0]); // Noncompliant {{Remove this array creation.}} new ArrayForVarArgCheckSample(new String[1 - 1]); new ArrayForVarArgCheckSample(new String[12]); - new ArrayForVarArgCheckSample(new String[] { "s1", "s2"}); // Noncompliant {{Remove this array creation and simply pass the elements.}} + new ArrayForVarArgCheckSample(new String[] { "s1", "s2"}); // Noncompliant {{Remove this array creation and simply pass the elements.}} java.util.List items = java.util.Arrays.asList(new String[]{"hello", "world"}); // Noncompliant {{Remove this array creation and simply pass the elements.}} foo(new String[]{"hello", "world"}); // Noncompliant {{Remove this array creation and simply pass the elements.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/ArrayHashCodeAndToStringCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ArrayHashCodeAndToStringCheckSample.java index 95de9e69619..eb801a02576 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ArrayHashCodeAndToStringCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ArrayHashCodeAndToStringCheckSample.java @@ -7,7 +7,8 @@ class ArrayHashCodeAndToStringCheckSample { Foo foo; void method(String[] args, String string) { - String argStr = args.toString(); // Noncompliant [[sc=26;ec=34]] {{Use "Arrays.toString(array)" instead.}} + String argStr = args.toString(); // Noncompliant {{Use "Arrays.toString(array)" instead.}} +// ^^^^^^^^ int argHash = args.hashCode(); // Noncompliant {{Use "Arrays.hashCode(array)" instead.}} Class class1 = args.getClass(); String str = string.toString(); @@ -15,11 +16,13 @@ void method(String[] args, String string) { } void testQuickfixes(String[] args) { - String argStr = args.toString(); // Noncompliant [[sc=26;ec=34;quickfixes=qfToString]] {{Use "Arrays.toString(array)" instead.}} + String argStr = args.toString(); // Noncompliant {{Use "Arrays.toString(array)" instead.}} [[quickfixes=qfToString]] +// ^^^^^^^^ // fix@qfToString {{Use "Arrays.toString(array)" instead}} // edit@qfToString [[sc=21;ec=36]] {{Arrays.toString(args)}} - int argHash = args.hashCode(); // Noncompliant [[sc=24;ec=32;quickfixes=qfHashCode]] {{Use "Arrays.hashCode(array)" instead.}} + int argHash = args.hashCode(); // Noncompliant {{Use "Arrays.hashCode(array)" instead.}} [[quickfixes=qfHashCode]] +// ^^^^^^^^ // fix@qfHashCode {{Use "Arrays.hashCode(array)" instead}} // edit@qfHashCode [[sc=19;ec=34]] {{Arrays.hashCode(args)}} @@ -27,11 +30,13 @@ void testQuickfixes(String[] args) { argHash = Arrays.hashCode(args); // Compliant int[][] array = new int[42][42]; - array[0].toString(); // Noncompliant [[sc=14;ec=22;quickfixes=qfToString1]] {{Use "Arrays.toString(array)" instead.}} + array[0].toString(); // Noncompliant {{Use "Arrays.toString(array)" instead.}} [[quickfixes=qfToString1]] +// ^^^^^^^^ // fix@qfToString1 {{Use "Arrays.toString(array)" instead}} // edit@qfToString1 [[sc=5;ec=24]] {{Arrays.toString(array[0])}} - this.foo.bar.myArray.toString(); // Noncompliant [[sc=26;ec=34;quickfixes=qfToString2]] {{Use "Arrays.toString(array)" instead.}} + this.foo.bar.myArray.toString(); // Noncompliant {{Use "Arrays.toString(array)" instead.}} [[quickfixes=qfToString2]] +// ^^^^^^^^ // fix@qfToString2 {{Use "Arrays.toString(array)" instead}} // edit@qfToString2 [[sc=5;ec=36]] {{Arrays.toString(this.foo.bar.myArray)}} } diff --git a/java-checks-test-sources/default/src/main/java/checks/ArraysAsListOfPrimitiveToStreamCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ArraysAsListOfPrimitiveToStreamCheckSample.java index ee0438acbf4..37b8bde2acd 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ArraysAsListOfPrimitiveToStreamCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ArraysAsListOfPrimitiveToStreamCheckSample.java @@ -9,9 +9,12 @@ void foo(Set s) { Arrays.asList("a1", "a2", "b1", "c2", "c1").stream().close(); // Compliant Arrays.asList(1.0, 2, 3L).stream().close(); // Compliant - Arrays.asList(1, 2, 3, 4).stream().close(); // Noncompliant [[sc=5;ec=18]] {{Use "Arrays.stream" instead of "Arrays.asList".}} - Arrays.asList(1L, 2L, 3L, 4L).stream().close(); // Noncompliant [[sc=5;ec=18]] {{Use "Arrays.stream" instead of "Arrays.asList".}} - Arrays.asList(1.0, 2.0, 3.0, 4.0).stream().close(); // Noncompliant [[sc=5;ec=18]] {{Use "Arrays.stream" instead of "Arrays.asList".}} + Arrays.asList(1, 2, 3, 4).stream().close(); // Noncompliant {{Use "Arrays.stream" instead of "Arrays.asList".}} +// ^^^^^^^^^^^^^ + Arrays.asList(1L, 2L, 3L, 4L).stream().close(); // Noncompliant {{Use "Arrays.stream" instead of "Arrays.asList".}} +// ^^^^^^^^^^^^^ + Arrays.asList(1.0, 2.0, 3.0, 4.0).stream().close(); // Noncompliant {{Use "Arrays.stream" instead of "Arrays.asList".}} +// ^^^^^^^^^^^^^ List integers = Arrays.asList(1, 2, 3, 4); integers.stream().close(); // Compliant - check only target inlined constructions diff --git a/java-checks-test-sources/default/src/main/java/checks/AssertOnBooleanVariableCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/AssertOnBooleanVariableCheckSample.java index 1e1b4f1299c..17ba385d719 100644 --- a/java-checks-test-sources/default/src/main/java/checks/AssertOnBooleanVariableCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/AssertOnBooleanVariableCheckSample.java @@ -5,8 +5,10 @@ public class AssertOnBooleanVariableCheckSample { void foo(AssertOnBooleanVariableCheckSample a, boolean b, List myList) { - assert myList.remove(myList.get(0)); // Noncompliant [[sc=19;ec=25]] {{Move this "assert" side effect to another statement.}} - assert myList.remove(myList.remove(1)); // Noncompliant [[sc=19;ec=25]] {{Move this "assert" side effect to another statement.}} + assert myList.remove(myList.get(0)); // Noncompliant {{Move this "assert" side effect to another statement.}} +// ^^^^^^ + assert myList.remove(myList.remove(1)); // Noncompliant {{Move this "assert" side effect to another statement.}} +// ^^^^^^ assert myList.add(new Object()); // Noncompliant assert myList.retainAll(Collections.singleton(new Object())); // Noncompliant @@ -15,7 +17,8 @@ void foo(AssertOnBooleanVariableCheckSample a, boolean b, List myList) { assert updateIfValid(false); // Noncompliant assert setValue(); // Noncompliant - assert bar() > 1 ? doNothing() : deleteStuff(); // Noncompliant [[sc=38;ec=49]] + assert bar() > 1 ? doNothing() : deleteStuff(); // Noncompliant +// ^^^^^^^^^^^ assert bar() == 0; // Compliant assert new AssertOnBooleanVariableCheckSample() { // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/AssertionsInProductionCodeCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/AssertionsInProductionCodeCheckSample.java index 21c412202ce..0f986eec338 100644 --- a/java-checks-test-sources/default/src/main/java/checks/AssertionsInProductionCodeCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/AssertionsInProductionCodeCheckSample.java @@ -5,14 +5,22 @@ public class AssertionsInProductionCodeCheckSample { void method_with_forbidden_assertions() { - assertEquals(0, 0); // Noncompliant [[sc=5;ec=23;secondary=9,10,11,12,13,14,15]] {{Remove this assertion from production code.}} + assertEquals(0, 0); // Noncompliant {{Remove this assertion from production code.}} +// ^^^^^^^^^^^^^^^^^^ org.junit.Assert.fail("message"); +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< org.junit.jupiter.api.Assertions.assertFalse(false); +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< org.junit.jupiter.api.Assertions.fail("message"); +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< org.assertj.core.api.Assertions.assertThat(2).isLessThan(3); +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< org.assertj.core.api.Assertions.fail("message"); +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< org.assertj.core.api.Fail.fail("message"); +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< org.fest.assertions.Assertions.assertThat(2).isEqualTo(2); +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< } long method_without_forbidden_assertions(int param) { diff --git a/java-checks-test-sources/default/src/main/java/checks/AssertsOnParametersOfPublicMethodCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/AssertsOnParametersOfPublicMethodCheckSample.java index 9c0a0d3f3fe..1fa505d8613 100644 --- a/java-checks-test-sources/default/src/main/java/checks/AssertsOnParametersOfPublicMethodCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/AssertsOnParametersOfPublicMethodCheckSample.java @@ -3,7 +3,8 @@ class S4274_A { public void setPrice(int price1) { - assert price1 >= 0 && price1 <= 10000; // Noncompliant [[sc=5;ec=43]] {{Replace this assert with a proper check.}} + assert price1 >= 0 && price1 <= 10000; // Noncompliant {{Replace this assert with a proper check.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } public int getPrice(int a) { diff --git a/java-checks-test-sources/default/src/main/java/checks/AssignmentInSubExpressionCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/AssignmentInSubExpressionCheckSample.java index 6cd40b5dca1..54b5ca37165 100644 --- a/java-checks-test-sources/default/src/main/java/checks/AssignmentInSubExpressionCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/AssignmentInSubExpressionCheckSample.java @@ -19,15 +19,17 @@ AssignmentInSubExpressionCheckSample foo() { int a = 0; // Compliant a = 0; // Compliant System.out.println(a); // Compliant - System.out.println(a = 0); // Noncompliant [[sc=26;ec=27]] {{Extract the assignment out of this expression.}} - System.out.println(a += 0); // Noncompliant [[sc=26;ec=28]] {{Extract the assignment out of this expression.}} + System.out.println(a = 0); // Noncompliant {{Extract the assignment out of this expression.}} +// ^ + System.out.println(a += 0); // Noncompliant {{Extract the assignment out of this expression.}} +// ^^ System.out.println(a == 0); // Compliant a = b = 0; // Compliant a += foo[i]; // Compliant _stack[ - index = 0 // Noncompliant + index = 0 // Noncompliant ] = node; while ((foo = bar()) != null) { // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/AtLeastOneConstructorCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/AtLeastOneConstructorCheckSample.java index b39fcc07373..37154d71f72 100644 --- a/java-checks-test-sources/default/src/main/java/checks/AtLeastOneConstructorCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/AtLeastOneConstructorCheckSample.java @@ -17,8 +17,10 @@ import org.codehaus.plexus.component.annotations.Configuration; import org.codehaus.plexus.component.annotations.Requirement; -class WithoutConstructor { // Noncompliant [[sc=7;ec=25;secondary=+1]] {{Add a constructor to the class, or provide default values.}} +class WithoutConstructor { // Noncompliant {{Add a constructor to the class, or provide default values.}} +// ^^^^^^^^^^^^^^^^^^ private int field; +//^^^^^^^^^^^^^^^^^^< } class WitConstructor { @@ -39,9 +41,11 @@ void foo() { } } -enum Enum { // Noncompliant [[secondary=+2]] {{Add a constructor to the enum, or provide default values.}} +enum Enum { // Noncompliant {{Add a constructor to the enum, or provide default values.}} +// ^^^^ A; private int field; +//^^^^^^^^^^^^^^^^^^< } abstract class AbstractD { @@ -65,10 +69,12 @@ class Inject1 { @Inject private MyService myService; } -class Inject2 { // Noncompliant [[secondary=+3]] +class Inject2 { // Noncompliant +// ^^^^^^^ @Inject private MyService myService; private MyService myService2; +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< } class ABuilder { // Compliant, Builder pattern are excluded diff --git a/java-checks-test-sources/default/src/main/java/checks/AvoidHighFrameratesOnMobileCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/AvoidHighFrameratesOnMobileCheckSample.java index e404e058cc5..ed6ccd4b7b8 100644 --- a/java-checks-test-sources/default/src/main/java/checks/AvoidHighFrameratesOnMobileCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/AvoidHighFrameratesOnMobileCheckSample.java @@ -9,7 +9,8 @@ public class AvoidHighFrameratesOnMobileCheckSample { private int HIGH_THRESHOLD_NON_FINAL = 120; void noncompliant(Surface surface, SurfaceControl surfaceControl) { - surface.setFrameRate(120, 0, 0); // Noncompliant [[sc=26;ec=29]] {{Avoid setting high frame rates higher than 60 on mobile devices.}} + surface.setFrameRate(120, 0, 0); // Noncompliant {{Avoid setting high frame rates higher than 60 on mobile devices.}} +// ^^^ surface.setFrameRate(120, 0); // Noncompliant surfaceControl.setFrameRate(surfaceControl, 120, 0, 0); // Noncompliant surfaceControl.setFrameRate(surfaceControl, 120, 0); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/BadMethodName.java b/java-checks-test-sources/default/src/main/java/checks/BadMethodName.java index 524a49fd752..8b2d828ccd5 100644 --- a/java-checks-test-sources/default/src/main/java/checks/BadMethodName.java +++ b/java-checks-test-sources/default/src/main/java/checks/BadMethodName.java @@ -6,7 +6,8 @@ class BadMethodName extends Bad { public BadMethodName() { } - void Bad() { // Noncompliant [[sc=8;ec=11]] {{Rename this method name to match the regular expression '^[a-z][a-zA-Z0-9]*$'.}} + void Bad() { // Noncompliant {{Rename this method name to match the regular expression '^[a-z][a-zA-Z0-9]*$'.}} +// ^^^ } void good() { diff --git a/java-checks-test-sources/default/src/main/java/checks/BasicAuthCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/BasicAuthCheckSample.java index d172478ef28..ff0287371a8 100644 --- a/java-checks-test-sources/default/src/main/java/checks/BasicAuthCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/BasicAuthCheckSample.java @@ -10,8 +10,9 @@ class BasicAuthCheckSample { void foo(String authent, URL url) throws IOException, URISyntaxException { String encoding = Base64.getEncoder().encodeToString("login:passwd".getBytes(StandardCharsets.UTF_8)); org.apache.http.client.methods.HttpPost httppost = new org.apache.http.client.methods.HttpPost(url.toURI()); - httppost.setHeader("Authorization", "Basic " + encoding+encoding); // Noncompliant [[sc=41;ec=49]] {{Use a more secure method than basic authentication.}} - httppost.addHeader("Authorization", "Basic " + encoding); // Noncompliant + httppost.setHeader("Authorization", "Basic " + encoding+encoding); // Noncompliant {{Use a more secure method than basic authentication.}} +// ^^^^^^^^ + httppost.addHeader("Authorization", "Basic " + encoding); // Noncompliant httppost.setHeader("Authorization", "Digest " + encoding); httppost.setHeader("Authorization", authent); httppost.setHeader("FlaFla", "Basic " + encoding); diff --git a/java-checks-test-sources/default/src/main/java/checks/BatchSQLStatementsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/BatchSQLStatementsCheckSample.java index f269246d8cc..77b57c14e20 100644 --- a/java-checks-test-sources/default/src/main/java/checks/BatchSQLStatementsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/BatchSQLStatementsCheckSample.java @@ -14,7 +14,7 @@ public class BatchSQLStatementsCheckSample { void requestsInLoop(Statement statement, List queries) throws SQLException { for (int i = 0; i < queries.size(); i++) { - statement.execute(queries.get(i)); // Noncompliant [sc=7,ec=40] {{Use "addBatch" and "executeBatch" to execute multiple SQL statements in a single call.}} + statement.execute(queries.get(i)); // Noncompliant {{Use "addBatch" and "executeBatch" to execute multiple SQL statements in a single call.}} } for (String query : queries) { diff --git a/java-checks-test-sources/default/src/main/java/checks/BigDecimalDoubleConstructorCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/BigDecimalDoubleConstructorCheckSample.java index 90156532fd7..05790f3eea5 100644 --- a/java-checks-test-sources/default/src/main/java/checks/BigDecimalDoubleConstructorCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/BigDecimalDoubleConstructorCheckSample.java @@ -10,30 +10,37 @@ class BigDecimalDoubleConstructorCheckSample { BigDecimal bd1_1 = new BigDecimal("2", mc); BigDecimal bd1_2 = new BigDecimal(new BigInteger("10"), mc); BigDecimal bd1_3 = new BigDecimal(1); - BigDecimal bd2 = new BigDecimal(2.0); // Noncompliant [[sc=20;ec=39;quickfixes=qf1]] {{Use "BigDecimal.valueOf" instead.}} + BigDecimal bd2 = new BigDecimal(2.0); // Noncompliant {{Use "BigDecimal.valueOf" instead.}} [[quickfixes=qf1]] +// ^^^^^^^^^^^^^^^^^^^ // fix@qf1 {{Replace with BigDecimal.valueOf}} // edit@qf1 [[sc=20;ec=34]] {{BigDecimal.valueOf}} - BigDecimal bd4 = new BigDecimal(2.0, mc); // Noncompliant [[sc=20;ec=43;quickfixes=qf1_2]] {{Use "new BigDecimal(String, MathContext)" instead.}} + BigDecimal bd4 = new BigDecimal(2.0, mc); // Noncompliant {{Use "new BigDecimal(String, MathContext)" instead.}} [[quickfixes=qf1_2]] +// ^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf1_2 {{Replace with BigDecimal("2.0",}} // edit@qf1_2 [[sc=35;ec=38]] {{"2.0"}} - BigDecimal bd43 = new BigDecimal(123.0, mc); // Noncompliant [[sc=21;ec=46;quickfixes=qf1_3]] {{Use "new BigDecimal(String, MathContext)" instead.}} + BigDecimal bd43 = new BigDecimal(123.0, mc); // Noncompliant {{Use "new BigDecimal(String, MathContext)" instead.}} [[quickfixes=qf1_3]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf1_3 {{Replace with BigDecimal("123.0",}} // edit@qf1_3 [[sc=36;ec=41]] {{"123.0"}} BigDecimal bd5 = new BigDecimal(2.0f); // Noncompliant {{Use "BigDecimal.valueOf" instead.}} - BigDecimal bd6 = new BigDecimal(2.0f, mc); // Noncompliant [[sc=20;ec=44;quickfixes=qf1_4]] {{Use "new BigDecimal(String, MathContext)" instead.}} + BigDecimal bd6 = new BigDecimal(2.0f, mc); // Noncompliant {{Use "new BigDecimal(String, MathContext)" instead.}} [[quickfixes=qf1_4]] +// ^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf1_4 {{Replace with BigDecimal("2.0",}} // edit@qf1_4 [[sc=35;ec=39]] {{"2.0"}} - BigDecimal bd6_2 = new BigDecimal(2.0d, mc); // Noncompliant [[sc=22;ec=46;quickfixes=qf1_5]] {{Use "new BigDecimal(String, MathContext)" instead.}} + BigDecimal bd6_2 = new BigDecimal(2.0d, mc); // Noncompliant {{Use "new BigDecimal(String, MathContext)" instead.}} [[quickfixes=qf1_5]] +// ^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf1_5 {{Replace with BigDecimal("2.0",}} // edit@qf1_5 [[sc=37;ec=41]] {{"2.0"}} - BigDecimal bd6_3 = new BigDecimal(2.0F, mc); // Noncompliant [[sc=22;ec=46;quickfixes=qf1_6]] {{Use "new BigDecimal(String, MathContext)" instead.}} + BigDecimal bd6_3 = new BigDecimal(2.0F, mc); // Noncompliant {{Use "new BigDecimal(String, MathContext)" instead.}} [[quickfixes=qf1_6]] +// ^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf1_6 {{Replace with BigDecimal("2.0",}} // edit@qf1_6 [[sc=37;ec=41]] {{"2.0"}} - BigDecimal bd6_4 = new BigDecimal(2.0D, mc); // Noncompliant [[sc=22;ec=46;quickfixes=qf1_7]] {{Use "new BigDecimal(String, MathContext)" instead.}} + BigDecimal bd6_4 = new BigDecimal(2.0D, mc); // Noncompliant {{Use "new BigDecimal(String, MathContext)" instead.}} [[quickfixes=qf1_7]] +// ^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf1_7 {{Replace with BigDecimal("2.0",}} // edit@qf1_7 [[sc=37;ec=41]] {{"2.0"}} @@ -42,7 +49,8 @@ class BigDecimalDoubleConstructorCheckSample { Double d = 0.1; BigDecimal bd7 = new BigDecimal(d); // Noncompliant {{Use "BigDecimal.valueOf" instead.}} BigDecimal bd8 = new BigDecimal((Double) 0.1); // Noncompliant {{Use "BigDecimal.valueOf" instead.}} - BigDecimal bd8_3 = new BigDecimal(d, mc); // Noncompliant [[sc=22;ec=43;quickfixes=!]] {{Use "new BigDecimal(String, MathContext)" instead.}} + BigDecimal bd8_3 = new BigDecimal(d, mc); // Noncompliant {{Use "new BigDecimal(String, MathContext)" instead.}} [[quickfixes=!]] +// ^^^^^^^^^^^^^^^^^^^^^ double d2 = 0.1; BigDecimal bd7_2 = new BigDecimal(d2); // Noncompliant @@ -54,7 +62,8 @@ class BigDecimalDoubleConstructorCheckSample { float f2 = 0.1f; BigDecimal bd9_2 = new BigDecimal(f2); // Noncompliant - BigDecimal bd10_2 = new BigDecimal((float) 0.1); // Noncompliant [[sc=23;ec=50;quickfixes=qf2]] + BigDecimal bd10_2 = new BigDecimal((float) 0.1); // Noncompliant [[quickfixes=qf2]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf2 {{Replace with BigDecimal.valueOf}} // edit@qf2 [[sc=23;ec=37]] {{BigDecimal.valueOf}} diff --git a/java-checks-test-sources/default/src/main/java/checks/BlockingOperationsInVirtualThreadsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/BlockingOperationsInVirtualThreadsCheckSample.java index 6d86d8918cc..7e07df70f79 100644 --- a/java-checks-test-sources/default/src/main/java/checks/BlockingOperationsInVirtualThreadsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/BlockingOperationsInVirtualThreadsCheckSample.java @@ -14,8 +14,10 @@ public BlockingOperationsInVirtualThreadsCheckSample() throws IOException { void newThread() throws IOException { new Thread(() -> { +// ^^^^^^> try { - con.getResponseMessage(); // Noncompliant [[sc=13;ec=31;secondary=-2]] {{Use virtual threads for heavy blocking operations.}} + con.getResponseMessage(); // Noncompliant {{Use virtual threads for heavy blocking operations.}} +// ^^^^^^^^^^^^^^^^^^ con.getResponseCode(); // Noncompliant con.disconnect(); // Compliant con.getInputStream(); // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/BluetoothLowPowerModeCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/BluetoothLowPowerModeCheckSample.java index 3c7ecc5cd4d..16f65d3c27d 100644 --- a/java-checks-test-sources/default/src/main/java/checks/BluetoothLowPowerModeCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/BluetoothLowPowerModeCheckSample.java @@ -11,11 +11,13 @@ public class BluetoothLowPowerModeCheckSample { public void nonCompliant(android.bluetooth.BluetoothGatt gatt, android.bluetooth.le.AdvertiseSettings.Builder builder) { gatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH); // Noncompliant {{Use the low power mode for this Bluetooth operation.}} - gatt.requestConnectionPriority(1); // Noncompliant [[sc=5;ec=35]] + gatt.requestConnectionPriority(1); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ builder.setAdvertiseMode(android.bluetooth.le.AdvertiseSettings.ADVERTISE_MODE_BALANCED); // Noncompliant {{Use the low power mode for this Bluetooth operation.}} builder.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY); // Noncompliant - builder.setAdvertiseMode(1); // Noncompliant [[sc=5;ec=29]] + builder.setAdvertiseMode(1); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^ } public void compliant(android.bluetooth.BluetoothGatt gatt, android.bluetooth.le.AdvertiseSettings.Builder builder) { diff --git a/java-checks-test-sources/default/src/main/java/checks/BooleanLiteralCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/BooleanLiteralCheckSample.java index ef33bb92f8a..92d6dfb9868 100644 --- a/java-checks-test-sources/default/src/main/java/checks/BooleanLiteralCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/BooleanLiteralCheckSample.java @@ -4,23 +4,27 @@ class BooleanLiteralCheckSample { public void f(boolean var, boolean foo) { boolean[] tests = { - var == false, // Noncompliant [[sc=12;ec=17]] {{Remove the unnecessary boolean literal.}} - var == true, // Noncompliant {{Remove the unnecessary boolean literal.}} - var != false, // Noncompliant - var != true, // Noncompliant - false == var, // Noncompliant - true == var, // Noncompliant - false != var, // Noncompliant - true != var, // Noncompliant - !true, // Noncompliant [[sc=6;ec=10;quickfixes=qf_negation_true]] + var == false, // Noncompliant {{Remove the unnecessary boolean literal.}} +// ^^^^^ + var == true, // Noncompliant {{Remove the unnecessary boolean literal.}} + var != false, // Noncompliant + var != true, // Noncompliant + false == var, // Noncompliant + true == var, // Noncompliant + false != var, // Noncompliant + true != var, // Noncompliant + !true, // Noncompliant [[quickfixes=qf_negation_true]] +// ^^^^ // fix@qf_negation_true {{Simplify the expression}} // edit@qf_negation_true [[sc=5;ec=10]] {{false}} - !false, // Noncompliant [[sc=6;ec=11;quickfixes=qf_negation_false]] + !false, // Noncompliant [[quickfixes=qf_negation_false]] +// ^^^^^ // fix@qf_negation_false {{Simplify the expression}} // edit@qf_negation_false [[sc=5;ec=11]] {{true}} - false && foo(), // Noncompliant - foo() || true, // Noncompliant - true || false, // Noncompliant [[sc=5;ec=9;secondary=+0]] {{Remove the unnecessary boolean literals.}} + false && foo(), // Noncompliant + foo() || true, // Noncompliant + true || false, // Noncompliant {{Remove the unnecessary boolean literals.}} +// ^^^^ ^^^^^< var == foo(true), // Compliant !foo, // Compliant @@ -28,34 +32,43 @@ false && foo(), // Noncompliant }; boolean exp = foo(); - var = foo() ? true : // Noncompliant [[sc=19;ec=23;secondary=+1;quickfixes=qf_cond1]] {{Remove the unnecessary boolean literals.}} + var = foo() ? true : // Noncompliant {{Remove the unnecessary boolean literals.}} [[quickfixes=qf_cond1]] +// ^^^^ false; +// ^^^^^< // fix@qf_cond1 {{Simplify the expression}} - // edit@qf_cond1 [[sc=16;el=+1;ec=12]] {{}} - var = foo() ? false : true; // Noncompliant [[sc=19;ec=24;quickfixes=qf_cond2]] + // edit@qf_cond1 [[sc=16;el=+2;ec=12]] {{}} + var = foo() ? false : true; // Noncompliant [[quickfixes=qf_cond2]] +// ^^^^^ // fix@qf_cond2 {{Simplify the expression}} // edit@qf_cond2 [[sc=16;ec=31]] {{}} // edit@qf_cond2 [[sc=11;ec=11]] {{!}} - var = foo() ? true : exp; // Noncompliant [[sc=19;ec=23;quickfixes=qf_cond3]] + var = foo() ? true : exp; // Noncompliant [[quickfixes=qf_cond3]] +// ^^^^ // fix@qf_cond3 {{Simplify the expression}} // edit@qf_cond3 [[sc=17;ec=25]] {{||}} - var = foo() ? false : exp; // Noncompliant [[sc=19;ec=24;quickfixes=qf_cond4]] + var = foo() ? false : exp; // Noncompliant [[quickfixes=qf_cond4]] +// ^^^^^ // fix@qf_cond4 {{Simplify the expression}} // edit@qf_cond4 [[sc=17;ec=26]] {{&&}} // edit@qf_cond4 [[sc=11;ec=11]] {{!}} - var = foo() ? exp : true; // Noncompliant [[sc=25;ec=29;quickfixes=qf_cond5]] + var = foo() ? exp : true; // Noncompliant [[quickfixes=qf_cond5]] +// ^^^^ // fix@qf_cond5 {{Simplify the expression}} // edit@qf_cond5 [[sc=22;ec=29]] {{}} // edit@qf_cond5 [[sc=11;ec=11]] {{!}} // edit@qf_cond5 [[sc=17;ec=18]] {{||}} - var = foo() ? exp : false; // Noncompliant [[sc=25;ec=30;quickfixes=qf_cond6]] + var = foo() ? exp : false; // Noncompliant [[quickfixes=qf_cond6]] +// ^^^^^ // fix@qf_cond6 {{Simplify the expression}} // edit@qf_cond6 [[sc=22;ec=30]] {{}} // edit@qf_cond6 [[sc=17;ec=18]] {{&&}} // The following are reported but we do not suggest a quick fix as it looks more like a bug (see S3923) - var = foo() ? true : true; // Noncompliant [[sc=19;ec=23;quickfixes=!]] - var = foo() ? false : false; // Noncompliant [[sc=19;ec=24;quickfixes=!]] + var = foo() ? true : true; // Noncompliant [[quickfixes=!]] +// ^^^^ + var = foo() ? false : false; // Noncompliant [[quickfixes=!]] +// ^^^^^ Boolean b1 = foo() ? true : null; // Compliant Boolean b2 = foo() ? exp : null; // Compliant @@ -71,124 +84,160 @@ false && foo(), // Noncompliant void quickFixForEquality(boolean var) { boolean b; - b = var == false; // Noncompliant [[sc=16;ec=21;quickfixes=qf_equal1]] + b = var == false; // Noncompliant [[quickfixes=qf_equal1]] +// ^^^^^ // fix@qf_equal1 {{Simplify the expression}} // edit@qf_equal1 [[sc=9;ec=9]] {{!}} // edit@qf_equal1 [[sc=12;ec=21]] {{}} - b = var == true; // Noncompliant [[sc=16;ec=20;quickfixes=qf_equal2]] + b = var == true; // Noncompliant [[quickfixes=qf_equal2]] +// ^^^^ // fix@qf_equal2 {{Simplify the expression}} // edit@qf_equal2 [[sc=12;ec=20]] {{}} - b = var != false; // Noncompliant [[sc=16;ec=21;quickfixes=qf_equal3]] + b = var != false; // Noncompliant [[quickfixes=qf_equal3]] +// ^^^^^ // fix@qf_equal3 {{Simplify the expression}} // edit@qf_equal3 [[sc=12;ec=21]] {{}} - b = var != true; // Noncompliant [[sc=16;ec=20;quickfixes=qf_equal4]] + b = var != true; // Noncompliant [[quickfixes=qf_equal4]] +// ^^^^ // fix@qf_equal4 {{Simplify the expression}} // edit@qf_equal4 [[sc=9;ec=9]] {{!}} // edit@qf_equal4 [[sc=12;ec=20]] {{}} - b = false == var; // Noncompliant [[sc=9;ec=14;quickfixes=qf_equal5]] + b = false == var; // Noncompliant [[quickfixes=qf_equal5]] +// ^^^^^ // fix@qf_equal5 {{Simplify the expression}} // edit@qf_equal5 [[sc=9;ec=18]] {{!}} - b = true == var; // Noncompliant [[sc=9;ec=13;quickfixes=qf_equal6]] + b = true == var; // Noncompliant [[quickfixes=qf_equal6]] +// ^^^^ // fix@qf_equal6 {{Simplify the expression}} // edit@qf_equal6 [[sc=9;ec=17]] {{}} - b = false != var; // Noncompliant [[sc=9;ec=14;quickfixes=qf_equal7]] + b = false != var; // Noncompliant [[quickfixes=qf_equal7]] +// ^^^^^ // fix@qf_equal7 {{Simplify the expression}} // edit@qf_equal7 [[sc=9;ec=18]] {{}} - b = true != var; // Noncompliant [[sc=9;ec=13;quickfixes=qf_equal8]] + b = true != var; // Noncompliant [[quickfixes=qf_equal8]] +// ^^^^ // fix@qf_equal8 {{Simplify the expression}} // edit@qf_equal8 [[sc=9;ec=17]] {{!}} - b = true == true; // Noncompliant [[sc=9;ec=13;quickfixes=qf_equal9]] + b = true == true; // Noncompliant [[quickfixes=qf_equal9]] +// ^^^^ // fix@qf_equal9 {{Simplify the expression}} // edit@qf_equal9 [[sc=9;ec=21]] {{true}} - b = false == false; // Noncompliant [[sc=9;ec=14;quickfixes=qf_equal10]] + b = false == false; // Noncompliant [[quickfixes=qf_equal10]] +// ^^^^^ // fix@qf_equal10 {{Simplify the expression}} // edit@qf_equal10 [[sc=9;ec=23]] {{true}} - b = false == true; // Noncompliant [[sc=9;ec=14;quickfixes=qf_equal11]] + b = false == true; // Noncompliant [[quickfixes=qf_equal11]] +// ^^^^^ // fix@qf_equal11 {{Simplify the expression}} // edit@qf_equal11 [[sc=9;ec=22]] {{false}} - b = true == false; // Noncompliant [[sc=9;ec=13;quickfixes=qf_equal12]] + b = true == false; // Noncompliant [[quickfixes=qf_equal12]] +// ^^^^ // fix@qf_equal12 {{Simplify the expression}} // edit@qf_equal12 [[sc=9;ec=22]] {{false}} - b = true != true; // Noncompliant [[sc=9;ec=13;quickfixes=qf_equal13]] + b = true != true; // Noncompliant [[quickfixes=qf_equal13]] +// ^^^^ // fix@qf_equal13 {{Simplify the expression}} // edit@qf_equal13 [[sc=9;ec=21]] {{false}} - b = false != false; // Noncompliant [[sc=9;ec=14;quickfixes=qf_equal14]] + b = false != false; // Noncompliant [[quickfixes=qf_equal14]] +// ^^^^^ // fix@qf_equal14 {{Simplify the expression}} // edit@qf_equal14 [[sc=9;ec=23]] {{false}} - b = false != true; // Noncompliant [[sc=9;ec=14;quickfixes=qf_equal15]] + b = false != true; // Noncompliant [[quickfixes=qf_equal15]] +// ^^^^^ // fix@qf_equal15 {{Simplify the expression}} // edit@qf_equal15 [[sc=9;ec=22]] {{true}} - b = true != false; // Noncompliant [[sc=9;ec=13;quickfixes=qf_equal16]] + b = true != false; // Noncompliant [[quickfixes=qf_equal16]] +// ^^^^ // fix@qf_equal16 {{Simplify the expression}} // edit@qf_equal16 [[sc=9;ec=22]] {{true}} } void quickFixForAndAndOr(boolean var, boolean var2) { boolean b; - b = f() || false; // Noncompliant [[sc=16;ec=21;quickfixes=qf_and_or1]] + b = f() || false; // Noncompliant [[quickfixes=qf_and_or1]] +// ^^^^^ // fix@qf_and_or1 {{Simplify the expression}} // edit@qf_and_or1 [[sc=12;ec=21]] {{}} - b = f() && true; // Noncompliant [[sc=16;ec=20;quickfixes=qf_and_or2]] + b = f() && true; // Noncompliant [[quickfixes=qf_and_or2]] +// ^^^^ // fix@qf_and_or2 {{Simplify the expression}} // edit@qf_and_or2 [[sc=12;ec=20]] {{}} // When the expression can have side effects, it is not always possible to simply fix the issue. // We are not suggesting a quick fix when it would require to extract the side effects. - b = f() || true; // Noncompliant [[sc=16;ec=20;quickfixes=!]] - b = f() && false; // Noncompliant [[sc=16;ec=21;quickfixes=!]] + b = f() || true; // Noncompliant [[quickfixes=!]] +// ^^^^ + b = f() && false; // Noncompliant [[quickfixes=!]] +// ^^^^^ // However, the same expression without side effect can be replaced safely - b = var || true; // Noncompliant [[sc=16;ec=20;quickfixes=qf_and_or3]] + b = var || true; // Noncompliant [[quickfixes=qf_and_or3]] +// ^^^^ // fix@qf_and_or3 {{Simplify the expression}} // edit@qf_and_or3 [[sc=9;ec=16]] {{}} - b = var && false; // Noncompliant [[sc=16;ec=21;quickfixes=qf_and_or4]] + b = var && false; // Noncompliant [[quickfixes=qf_and_or4]] +// ^^^^^ // fix@qf_and_or4 {{Simplify the expression}} // edit@qf_and_or4 [[sc=9;ec=16]] {{}} - b = true || f(); // Noncompliant [[sc=9;ec=13;quickfixes=qf_and_or5]] + b = true || f(); // Noncompliant [[quickfixes=qf_and_or5]] +// ^^^^ // fix@qf_and_or5 {{Simplify the expression}} // edit@qf_and_or5 [[sc=13;ec=20]] {{}} - b = false || f(); // Noncompliant [[sc=9;ec=14;quickfixes=qf_and_or6]] + b = false || f(); // Noncompliant [[quickfixes=qf_and_or6]] +// ^^^^^ // fix@qf_and_or6 {{Simplify the expression}} // edit@qf_and_or6 [[sc=9;ec=18]] {{}} - b = true && f(); // Noncompliant [[sc=9;ec=13;quickfixes=qf_and_or7]] + b = true && f(); // Noncompliant [[quickfixes=qf_and_or7]] +// ^^^^ // fix@qf_and_or7 {{Simplify the expression}} // edit@qf_and_or7 [[sc=9;ec=17]] {{}} - b = false && f(); // Noncompliant [[sc=9;ec=14;quickfixes=qf_and_or8]] + b = false && f(); // Noncompliant [[quickfixes=qf_and_or8]] +// ^^^^^ // fix@qf_and_or8 {{Simplify the expression}} // edit@qf_and_or8 [[sc=14;ec=21]] {{}} - b = true || true; // Noncompliant [[sc=9;ec=13;quickfixes=qf_and_or9]] + b = true || true; // Noncompliant [[quickfixes=qf_and_or9]] +// ^^^^ // fix@qf_and_or9 {{Simplify the expression}} // edit@qf_and_or9 [[sc=9;ec=21]] {{true}} - b = false || true; // Noncompliant [[sc=9;ec=14;quickfixes=qf_and_or10]] + b = false || true; // Noncompliant [[quickfixes=qf_and_or10]] +// ^^^^^ // fix@qf_and_or10 {{Simplify the expression}} // edit@qf_and_or10 [[sc=9;ec=22]] {{true}} - b = true || false; // Noncompliant [[sc=9;ec=13;quickfixes=qf_and_or11]] + b = true || false; // Noncompliant [[quickfixes=qf_and_or11]] +// ^^^^ // fix@qf_and_or11 {{Simplify the expression}} // edit@qf_and_or11 [[sc=9;ec=22]] {{true}} - b = false || false; // Noncompliant [[sc=9;ec=14;quickfixes=qf_and_or12]] + b = false || false; // Noncompliant [[quickfixes=qf_and_or12]] +// ^^^^^ // fix@qf_and_or12 {{Simplify the expression}} // edit@qf_and_or12 [[sc=9;ec=23]] {{false}} - b = true && true; // Noncompliant [[sc=9;ec=13;quickfixes=qf_and_or13]] + b = true && true; // Noncompliant [[quickfixes=qf_and_or13]] +// ^^^^ // fix@qf_and_or13 {{Simplify the expression}} // edit@qf_and_or13 [[sc=9;ec=21]] {{true}} - b = false && true; // Noncompliant [[sc=9;ec=14;quickfixes=qf_and_or14]] + b = false && true; // Noncompliant [[quickfixes=qf_and_or14]] +// ^^^^^ // fix@qf_and_or14 {{Simplify the expression}} // edit@qf_and_or14 [[sc=9;ec=22]] {{false}} - b = true && false; // Noncompliant [[sc=9;ec=13;quickfixes=qf_and_or15]] + b = true && false; // Noncompliant [[quickfixes=qf_and_or15]] +// ^^^^ // fix@qf_and_or15 {{Simplify the expression}} // edit@qf_and_or15 [[sc=9;ec=22]] {{false}} - b = false && false; // Noncompliant [[sc=9;ec=14;quickfixes=qf_and_or16]] + b = false && false; // Noncompliant [[quickfixes=qf_and_or16]] +// ^^^^^ // fix@qf_and_or16 {{Simplify the expression}} // edit@qf_and_or16 [[sc=9;ec=23]] {{false}} // Side effect can be nested into a more complex expression - b = (b ? var : bar()) || true; // Noncompliant [[sc=30;ec=34;quickfixes=!]] - b = (b ? var : var2) || true; // Noncompliant [[sc=29;ec=33;quickfixes=qf_side_effect]] + b = (b ? var : bar()) || true; // Noncompliant [[quickfixes=!]] +// ^^^^ + b = (b ? var : var2) || true; // Noncompliant [[quickfixes=qf_side_effect]] +// ^^^^ // fix@qf_side_effect {{Simplify the expression}} // edit@qf_side_effect [[sc=9;ec=29]] {{}} @@ -196,7 +245,8 @@ void quickFixForAndAndOr(boolean var, boolean var2) { boolean isNotNull(Object s, boolean exp) { boolean result; - result = s == null ? false : exp; // Noncompliant [[sc=26;ec=31;quickfixes=qf_proper_fix]] + result = s == null ? false : exp; // Noncompliant [[quickfixes=qf_proper_fix]] +// ^^^^^ // result = s != null && exp; // fix@qf_proper_fix {{Simplify the expression}} // edit@qf_proper_fix [[sc=24;ec=33]]{{&&}} @@ -206,7 +256,8 @@ boolean isNotNull(Object s, boolean exp) { boolean externalConditionisFalse(boolean externalCondition, boolean exp) { boolean result; - result = externalCondition ? false : exp; // Noncompliant [[sc=34;ec=39;quickfixes=regular_fix]] + result = externalCondition ? false : exp; // Noncompliant [[quickfixes=regular_fix]] +// ^^^^^ // result = !externalCondition && exp; // fix@regular_fix {{Simplify the expression}} // edit@regular_fix [[sc=32;ec=41]]{{&&}} @@ -215,7 +266,8 @@ boolean externalConditionisFalse(boolean externalCondition, boolean exp) { } boolean doesNotStartWithA(String s, boolean exp) { - return (s != null) && s.startsWith("a") ? false : exp; // Noncompliant[[sc=47;ec=52;quickfixes=complex_fix]] + return (s != null) && s.startsWith("a") ? false : exp; // Noncompliant [[quickfixes=complex_fix]] +// ^^^^^ // return ((s == null) || !s.startsWith("a")) && exp; // fix@complex_fix {{Simplify the expression}} // edit@complex_fix [[sc=45;ec=54]]{{&&}} @@ -227,7 +279,8 @@ boolean doesNotStartWithA(String s, boolean exp) { } boolean isNotADuck(String s, boolean exp) { - return s != null && s.startsWith("d") && s.endsWith("uck") ? false : exp; // Noncompliant[[sc=66;ec=71;quickfixes=duck_fix]] + return s != null && s.startsWith("d") && s.endsWith("uck") ? false : exp; // Noncompliant [[quickfixes=duck_fix]] +// ^^^^^ // return (s == null || !s.startsWith("d") || !s.endsWith("uck")) && exp; // fix@duck_fix {{Simplify the expression}} // edit@duck_fix [[sc=64;ec=73]]{{&&}} @@ -245,7 +298,8 @@ boolean isADuck(String s, boolean exp) { } boolean doesNotHaveWings(String s, boolean isMammal, boolean exp) { - return isADuck(s, exp) || (isMammal && s != null && s.equals("bat")) ? false : exp; // Noncompliant [[sc=76;ec=81;quickfixes=wings_qf]] + return isADuck(s, exp) || (isMammal && s != null && s.equals("bat")) ? false : exp; // Noncompliant [[quickfixes=wings_qf]] +// ^^^^^ // return !isADuck(s, exp) && (!isMammal || s == null || !s.equals("bat")) && exp; // fix@wings_qf {{Simplify the expression}} // edit@wings_qf [[sc=74;ec=83]]{{&&}} diff --git a/java-checks-test-sources/default/src/main/java/checks/BooleanMethodReturnCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/BooleanMethodReturnCheckSample.java index 2168a755f85..d304785cb32 100644 --- a/java-checks-test-sources/default/src/main/java/checks/BooleanMethodReturnCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/BooleanMethodReturnCheckSample.java @@ -46,7 +46,8 @@ private BooleanMethodReturnCheckSampleC foo() { return null; // Compliant } } - return null; // Noncompliant [[sc=12;ec=16]] {{Null is returned but a "Boolean" is expected.}} + return null; // Noncompliant {{Null is returned but a "Boolean" is expected.}} +// ^^^^ } @CheckForNull diff --git a/java-checks-test-sources/default/src/main/java/checks/BoxedBooleanExpressionsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/BoxedBooleanExpressionsCheckSample.java index d57f8f17051..81b4fa95a28 100644 --- a/java-checks-test-sources/default/src/main/java/checks/BoxedBooleanExpressionsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/BoxedBooleanExpressionsCheckSample.java @@ -384,19 +384,19 @@ void forStatementCheckedBeforeUse() { } Boolean checkedBeforeUse4 = getSurprizeBoxedBoolean(); if (checkedBeforeUse4 == alwaysTrue) { - for (; checkedBeforeUse4; ) {} // Noncompliant because the value is not checked against null + for (; checkedBeforeUse4; ) {} // Noncompliant } Boolean checkedBeforeUse5 = getSurprizeBoxedBoolean(); if (checkedBeforeUse5 == Boolean.TRUE) { - for (; checkedBeforeUse5; ) {} // Noncompliant because the value is not checked against null + for (; checkedBeforeUse5; ) {} // Noncompliant } Boolean checkedBeforeUse6 = getSurprizeBoxedBoolean(); if (alwaysTrue.equals(checkedBeforeUse6)) { - for (; checkedBeforeUse6; ) {} // Noncompliant because the value is not checked against null + for (; checkedBeforeUse6; ) {} // Noncompliant } Boolean checkedBeforeUse7 = getSurprizeBoxedBoolean(); if (Boolean.FALSE.equals(checkedBeforeUse7)) { - for (; checkedBeforeUse7; ) {} // Noncompliant because the value is not checked against null + for (; checkedBeforeUse7; ) {} // Noncompliant } Boolean checkedBeforeUse8 = getSurprizeBoxedBoolean(); @@ -411,13 +411,13 @@ void forStatementCheckedBeforeUse() { } else if (checkedBeforeUse9 == null) { for (; checkedBeforeUse9; ) {} // Compliant FN because the value is checked but sill used } else if (checkedBeforeUse10 == alwaysTrue) { - for (; checkedBeforeUse10; ) {} // Noncompliant because the value is not checked against null + for (; checkedBeforeUse10; ) {} // Noncompliant } else if (checkedBeforeUse11 == Boolean.FALSE) { - for (; checkedBeforeUse11; ) {} // Noncompliant because the value is not checked against null + for (; checkedBeforeUse11; ) {} // Noncompliant } else if (alwaysTrue.equals(checkedBeforeUse12)) { - for (; checkedBeforeUse12; ) {} // Noncompliant because the value is not checked against null + for (; checkedBeforeUse12; ) {} // Noncompliant } else if (Boolean.FALSE.equals(checkedBeforeUse13)) { - for (; checkedBeforeUse13; ) {} // Noncompliant because the value is not checked against null + for (; checkedBeforeUse13; ) {} // Noncompliant } } @@ -438,19 +438,19 @@ void whileStatementCheckedBeforeUse() { } Boolean checkedBeforeUse4 = getSurprizeBoxedBoolean(); if (checkedBeforeUse4 == alwaysTrue) { - while (checkedBeforeUse4) {} // // Noncompliant because the value is not checked against null + while (checkedBeforeUse4) {} // Noncompliant } Boolean checkedBeforeUse5 = getSurprizeBoxedBoolean(); if (checkedBeforeUse5 == Boolean.TRUE) { - while (checkedBeforeUse5) {} // Noncompliant because the value is not checked against null + while (checkedBeforeUse5) {} // Noncompliant } Boolean checkedBeforeUse6 = getSurprizeBoxedBoolean(); if (alwaysTrue.equals(checkedBeforeUse6)) { - while (checkedBeforeUse6) {} // Noncompliant because the value is not checked against null + while (checkedBeforeUse6) {} // Noncompliant } Boolean checkedBeforeUse7 = getSurprizeBoxedBoolean(); if (Boolean.FALSE.equals(checkedBeforeUse7)) { - while (checkedBeforeUse7) {} // Noncompliant because the value is not checked against null + while (checkedBeforeUse7) {} // Noncompliant } Boolean checkedBeforeUse8 = getSurprizeBoxedBoolean(); @@ -465,13 +465,13 @@ void whileStatementCheckedBeforeUse() { } else if (checkedBeforeUse9 == null) { while (checkedBeforeUse9) {} // Compliant FN because the value is checked but sill used } else if (checkedBeforeUse10 == alwaysTrue) { - while (checkedBeforeUse10) {} // Noncompliant because the value is not checked against null + while (checkedBeforeUse10) {} // Noncompliant } else if (checkedBeforeUse11 == Boolean.FALSE) { - while (checkedBeforeUse11) {} // Noncompliant because the value is not checked against null + while (checkedBeforeUse11) {} // Noncompliant } else if (alwaysTrue.equals(checkedBeforeUse12)) { - while (checkedBeforeUse12) {} // Noncompliant because the value is not checked against null + while (checkedBeforeUse12) {} // Noncompliant } else if (Boolean.FALSE.equals(checkedBeforeUse13)) { - while (checkedBeforeUse13) {} // Noncompliant because the value is not checked against null + while (checkedBeforeUse13) {} // Noncompliant } } @@ -493,19 +493,19 @@ void doWhileStatementCheckedBeforeUse() { } Boolean checkedBeforeUse4 = getSurprizeBoxedBoolean(); if (checkedBeforeUse4 == alwaysTrue) { - do {} while (checkedBeforeUse4); // // Noncompliant because the value is not checked against null + do {} while (checkedBeforeUse4); // Noncompliant } Boolean checkedBeforeUse5 = getSurprizeBoxedBoolean(); if (checkedBeforeUse5 == Boolean.TRUE) { - do {} while (checkedBeforeUse5); // Noncompliant because the value is not checked against null + do {} while (checkedBeforeUse5); // Noncompliant } Boolean checkedBeforeUse6 = getSurprizeBoxedBoolean(); if (alwaysTrue.equals(checkedBeforeUse6)) { - do {} while (checkedBeforeUse6); // Noncompliant because the value is not checked against null + do {} while (checkedBeforeUse6); // Noncompliant } Boolean checkedBeforeUse7 = getSurprizeBoxedBoolean(); if (Boolean.FALSE.equals(checkedBeforeUse7)) { - do {} while (checkedBeforeUse7); // Noncompliant because the value is not checked against null + do {} while (checkedBeforeUse7); // Noncompliant } Boolean checkedBeforeUse8 = getSurprizeBoxedBoolean(); @@ -520,13 +520,13 @@ void doWhileStatementCheckedBeforeUse() { } else if (checkedBeforeUse9 == null) { do {} while (checkedBeforeUse9); // Compliant FN because the value is checked but sill used } else if (checkedBeforeUse10 == alwaysTrue) { - do {} while (checkedBeforeUse10); // Noncompliant because the value is not checked against null + do {} while (checkedBeforeUse10); // Noncompliant } else if (checkedBeforeUse11 == Boolean.FALSE) { - do {} while (checkedBeforeUse11); // Noncompliant because the value is not checked against null + do {} while (checkedBeforeUse11); // Noncompliant } else if (alwaysTrue.equals(checkedBeforeUse12)) { - do {} while (checkedBeforeUse12); // Noncompliant because the value is not checked against null + do {} while (checkedBeforeUse12); // Noncompliant } else if (Boolean.FALSE.equals(checkedBeforeUse13)) { - do {} while (checkedBeforeUse13); // Noncompliant because the value is not checked against null + do {} while (checkedBeforeUse13); // Noncompliant } } @@ -549,19 +549,19 @@ void ifStatementCheckedBeforeUse() { } Boolean checkedBeforeUse4 = getSurprizeBoxedBoolean(); if (checkedBeforeUse4 == alwaysTrue) { - if (checkedBeforeUse4) {} // // Noncompliant because the value is not checked against null + if (checkedBeforeUse4) {} // Noncompliant } Boolean checkedBeforeUse5 = getSurprizeBoxedBoolean(); if (checkedBeforeUse5 == Boolean.TRUE) { - if (checkedBeforeUse5) {} // Noncompliant because the value is not checked against null + if (checkedBeforeUse5) {} // Noncompliant } Boolean checkedBeforeUse6 = getSurprizeBoxedBoolean(); if (alwaysTrue.equals(checkedBeforeUse6)) { - if (checkedBeforeUse6) {} // Noncompliant because the value is not checked against null + if (checkedBeforeUse6) {} // Noncompliant } Boolean checkedBeforeUse7 = getSurprizeBoxedBoolean(); if (Boolean.FALSE.equals(checkedBeforeUse7)) { - if (checkedBeforeUse7) {} // Noncompliant because the value is not checked against null + if (checkedBeforeUse7) {} // Noncompliant } Boolean checkedBeforeUse8 = getSurprizeBoxedBoolean(); @@ -576,13 +576,13 @@ void ifStatementCheckedBeforeUse() { } else if (checkedBeforeUse9 == null) { if (checkedBeforeUse9) {} // Compliant FN because the value is checked but sill used } else if (checkedBeforeUse10 == alwaysTrue) { - if (checkedBeforeUse10) {} // Noncompliant because the value is not checked against null + if (checkedBeforeUse10) {} // Noncompliant } else if (checkedBeforeUse11 == Boolean.FALSE) { - if (checkedBeforeUse11) {} // Noncompliant because the value is not checked against null + if (checkedBeforeUse11) {} // Noncompliant } else if (alwaysTrue.equals(checkedBeforeUse12)) { - if (checkedBeforeUse12) {} // Noncompliant because the value is not checked against null + if (checkedBeforeUse12) {} // Noncompliant } else if (Boolean.FALSE.equals(checkedBeforeUse13)) { - if (checkedBeforeUse13) {} // Noncompliant because the value is not checked against null + if (checkedBeforeUse13) {} // Noncompliant } } @@ -604,19 +604,19 @@ void conditionalCheckedBeforeUse() { } Boolean checkedBeforeUse4 = getSurprizeBoxedBoolean(); if (checkedBeforeUse4 == alwaysTrue) { - ignored = (checkedBeforeUse4 ? "a" : "b"); // Noncompliant because the value is not checked against null + ignored = (checkedBeforeUse4 ? "a" : "b"); // Noncompliant } Boolean checkedBeforeUse5 = getSurprizeBoxedBoolean(); if (checkedBeforeUse5 == Boolean.TRUE) { - ignored = (checkedBeforeUse5 ? "a" : "b"); // Noncompliant because the value is not checked against null + ignored = (checkedBeforeUse5 ? "a" : "b"); // Noncompliant } Boolean checkedBeforeUse6 = getSurprizeBoxedBoolean(); if (alwaysTrue.equals(checkedBeforeUse6)) { - ignored = (checkedBeforeUse6 ? "a" : "b"); // Noncompliant because the value is not checked against null + ignored = (checkedBeforeUse6 ? "a" : "b"); // Noncompliant } Boolean checkedBeforeUse7 = getSurprizeBoxedBoolean(); if (Boolean.FALSE.equals(checkedBeforeUse7)) { - ignored = (checkedBeforeUse7 ? "a" : "b"); // Noncompliant because the value is not checked against null + ignored = (checkedBeforeUse7 ? "a" : "b"); // Noncompliant } Boolean checkedBeforeUse8 = getSurprizeBoxedBoolean(); @@ -631,13 +631,13 @@ void conditionalCheckedBeforeUse() { } else if (checkedBeforeUse9 == null) { ignored = (checkedBeforeUse9 ? "a" : "b"); // Compliant FN because the value is checked but sill used } else if (checkedBeforeUse10 == alwaysTrue) { - ignored = (checkedBeforeUse10 ? "a" : "b"); // Noncompliant because the value is not checked against null + ignored = (checkedBeforeUse10 ? "a" : "b"); // Noncompliant } else if (checkedBeforeUse11 == Boolean.FALSE) { - ignored = (checkedBeforeUse11 ? "a" : "b"); // Noncompliant because the value is not checked against null + ignored = (checkedBeforeUse11 ? "a" : "b"); // Noncompliant } else if (alwaysTrue.equals(checkedBeforeUse12)) { - ignored = (checkedBeforeUse12 ? "a" : "b"); // Noncompliant because the value is not checked against null + ignored = (checkedBeforeUse12 ? "a" : "b"); // Noncompliant } else if (Boolean.FALSE.equals(checkedBeforeUse13)) { - ignored = (checkedBeforeUse13 ? "a" : "b"); // Noncompliant because the value is not checked against null + ignored = (checkedBeforeUse13 ? "a" : "b"); // Noncompliant } } diff --git a/java-checks-test-sources/default/src/main/java/checks/BoxedBooleanExpressionsCheckWithQuickFixes.java b/java-checks-test-sources/default/src/main/java/checks/BoxedBooleanExpressionsCheckWithQuickFixes.java index 154f98f08ce..941e868cb4a 100644 --- a/java-checks-test-sources/default/src/main/java/checks/BoxedBooleanExpressionsCheckWithQuickFixes.java +++ b/java-checks-test-sources/default/src/main/java/checks/BoxedBooleanExpressionsCheckWithQuickFixes.java @@ -5,49 +5,56 @@ public class BoxedBooleanExpressionsCheckWithQuickFixes { void boxedFor1(Boolean B, boolean b) { - if (B) { // Noncompliant [[sc=9;ec=10;quickfixes=qf1]] + if (B) { // Noncompliant [[quickfixes=qf1]] +// ^ // fix@qf1 {{Use a primitive boolean expression}} // edit@qf1 [[sc=9;ec=9]] {{Boolean.TRUE.equals(}} // edit@qf1 [[sc=10;ec=10]] {{)}} foo(); } - if (!B) { // Noncompliant [[sc=10;ec=11;quickfixes=qf2]] + if (!B) { // Noncompliant [[quickfixes=qf2]] +// ^ // fix@qf2 {{Use a primitive boolean expression}} // edit@qf2 [[sc=9;ec=10]] {{Boolean.FALSE.equals(}} // edit@qf2 [[sc=11;ec=11]] {{)}} foo(); } - for (;B;) { // Noncompliant [[sc=11;ec=12;quickfixes=qf3]] + for (;B;) { // Noncompliant [[quickfixes=qf3]] +// ^ // fix@qf3 {{Use a primitive boolean expression}} // edit@qf3 [[sc=11;ec=11]] {{Boolean.TRUE.equals(}} // edit@qf3 [[sc=12;ec=12]] {{)}} foo(); } - if (True()) { // Noncompliant [[sc=9;ec=15;quickfixes=qf4]] + if (True()) { // Noncompliant [[quickfixes=qf4]] +// ^^^^^^ // fix@qf4 {{Use a primitive boolean expression}} // edit@qf4 [[sc=9;ec=9]] {{Boolean.TRUE.equals(}} // edit@qf4 [[sc=15;ec=15]] {{)}} foo(); } - if (B == b) { // Noncompliant [[sc=9;ec=10;quickfixes=qf5]] + if (B == b) { // Noncompliant [[quickfixes=qf5]] +// ^ // fix@qf5 {{Use a primitive boolean expression}} // edit@qf5 [[sc=9;ec=9]] {{Boolean.TRUE.equals(}} // edit@qf5 [[sc=10;ec=10]] {{)}} foo(); } - if (b == B) { // Noncompliant [[sc=14;ec=15;quickfixes=qf6]] + if (b == B) { // Noncompliant [[quickfixes=qf6]] +// ^ // fix@qf6 {{Use a primitive boolean expression}} // edit@qf6 [[sc=14;ec=14]] {{Boolean.TRUE.equals(}} // edit@qf6 [[sc=15;ec=15]] {{)}} foo(); } - if (Optional.of(True()).orElse(null)) { // Noncompliant [[sc=9;ec=41;quickfixes=!]] + if (Optional.of(True()).orElse(null)) { // Noncompliant [[quickfixes=!]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ foo(); } } diff --git a/java-checks-test-sources/default/src/main/java/checks/BrainMethodCheckLowerThresholds.java b/java-checks-test-sources/default/src/main/java/checks/BrainMethodCheckLowerThresholds.java index 03a1d52f399..3502af33368 100644 --- a/java-checks-test-sources/default/src/main/java/checks/BrainMethodCheckLowerThresholds.java +++ b/java-checks-test-sources/default/src/main/java/checks/BrainMethodCheckLowerThresholds.java @@ -11,7 +11,8 @@ void empty() { public static native void alert(String msg); - void foo() { // Noncompliant [[sc=8;ec=11]] {{A "Brain Method" was detected. Refactor it to reduce at least one of the following metrics: LOC from 22 to 13, Complexity from 5 to 4, Nesting Level from 3 to 2, Number of Variables from 6 to 3.}} + void foo() { // Noncompliant {{A "Brain Method" was detected. Refactor it to reduce at least one of the following metrics: LOC from 22 to 13, Complexity from 5 to 4, Nesting Level from 3 to 2, Number of Variables from 6 to 3.}} +// ^^^ String a = "a"; String b = "b"; int x = 0; diff --git a/java-checks-test-sources/default/src/main/java/checks/BrainMethodCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/BrainMethodCheckSample.java index 93bffa474bf..3c88f2fbff1 100644 --- a/java-checks-test-sources/default/src/main/java/checks/BrainMethodCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/BrainMethodCheckSample.java @@ -2,7 +2,8 @@ class BrainMethodCheckSample { - void foo() { // Noncompliant [[sc=8;ec=11]] {{A "Brain Method" was detected. Refactor it to reduce at least one of the following metrics: LOC from 66 to 64, Complexity from 17 to 14, Nesting Level from 3 to 2, Number of Variables from 12 to 6.}} + void foo() { // Noncompliant {{A "Brain Method" was detected. Refactor it to reduce at least one of the following metrics: LOC from 66 to 64, Complexity from 17 to 14, Nesting Level from 3 to 2, Number of Variables from 12 to 6.}} +// ^^^ String a = "a"; String b = "b"; int x = 0; diff --git a/java-checks-test-sources/default/src/main/java/checks/CORSCheck.java b/java-checks-test-sources/default/src/main/java/checks/CORSCheck.java index 04c0ef89222..a04f5317cf9 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CORSCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/CORSCheck.java @@ -25,9 +25,11 @@ class CORSCheck { // === Java Servlet === protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setHeader("Content-Type", "text/plain; charset=utf-8"); - resp.setHeader("Access-Control-Allow-Origin", "*"); // Noncompliant [[sc=10;ec=19]] + resp.setHeader("Access-Control-Allow-Origin", "*"); // Noncompliant +// ^^^^^^^^^ // header names are case insensitive. see https://stackoverflow.com/questions/5258977/are-http-headers-case-sensitive/5259004#5259004 - resp.setHeader("Access-control-allow-Origin", "*"); // Noncompliant [[sc=10;ec=19]] + resp.setHeader("Access-control-allow-Origin", "*"); // Noncompliant +// ^^^^^^^^^ resp.setHeader("Access-Control-Allow-Origin", "http://localhost:8080"); // Compliant resp.setHeader("Access-Control-Allow-Credentials", "true"); // Compliant @@ -36,7 +38,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws Se resp.setHeader("Access-Control-Allow-Methods", "*"); // Compliant resp.addHeader("Content-Type", "text/plain; charset=utf-8"); - resp.addHeader("Access-Control-Allow-Origin", "*"); // Noncompliant [[sc=10;ec=19]] + resp.addHeader("Access-Control-Allow-Origin", "*"); // Noncompliant +// ^^^^^^^^^ resp.addHeader("Access-Control-Allow-Origin", "http://localhost:8080"); // // Compliant resp.addHeader("Access-Control-Allow-Credentials", "true"); // Compliant resp.addHeader("Access-Control-Allow-Methods", "GET"); // Compliant @@ -48,13 +51,17 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws Se } protected void doGetJakarta(jakarta.servlet.http.HttpServletRequest req, jakarta.servlet.http.HttpServletResponse resp) { - resp.setHeader("Access-Control-Allow-Origin", "*"); // Noncompliant [[sc=10;ec=19]] - resp.setHeader("Access-control-allow-Origin", "*"); // Noncompliant [[sc=10;ec=19]] - resp.addHeader("Access-Control-Allow-Origin", "*"); // Noncompliant [[sc=10;ec=19]] + resp.setHeader("Access-Control-Allow-Origin", "*"); // Noncompliant +// ^^^^^^^^^ + resp.setHeader("Access-control-allow-Origin", "*"); // Noncompliant +// ^^^^^^^^^ + resp.addHeader("Access-Control-Allow-Origin", "*"); // Noncompliant +// ^^^^^^^^^ } // === Spring MVC Controller annotation === - @CrossOrigin(origins = "*") // Noncompliant [[sc=4;ec=15]] {{Make sure that enabling CORS is safe here.}} + @CrossOrigin(origins = "*") // Noncompliant {{Make sure that enabling CORS is safe here.}} +// ^^^^^^^^^^^ @RequestMapping("") public class TestController { public String home(ModelMap model) { @@ -167,19 +174,19 @@ class Local { public CorsFilter corsFilter4() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); - config.addAllowedOrigin("*"); // Noncompliant [[secondary=+1,+2]] + config.addAllowedOrigin("*"); // Noncompliant config.applyPermitDefaultValues(); config.applyPermitDefaultValues(); - config.addAllowedOrigin("*"); // Noncompliant [[secondary=-2,-1]] + config.addAllowedOrigin("*"); // Noncompliant return new CorsFilter(source); } } UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); - config.addAllowedOrigin("*"); // Noncompliant [[secondary=+1,+2]] + config.addAllowedOrigin("*"); // Noncompliant config.applyPermitDefaultValues(); config.applyPermitDefaultValues(); - config.addAllowedOrigin("*"); // Noncompliant [[secondary=-2,-1]] + config.addAllowedOrigin("*"); // Noncompliant return new CorsFilter(source); } @@ -187,7 +194,8 @@ class S5122_Insecure implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") - .allowedOrigins("*"); // Noncompliant [[sc=10;ec=24]] + .allowedOrigins("*"); // Noncompliant +// ^^^^^^^^^^^^^^ } } diff --git a/java-checks-test-sources/default/src/main/java/checks/CallOuterPrivateMethodCheck.java b/java-checks-test-sources/default/src/main/java/checks/CallOuterPrivateMethodCheck.java index ff553f54146..36bac4027e9 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CallOuterPrivateMethodCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/CallOuterPrivateMethodCheck.java @@ -4,13 +4,17 @@ class CallOuterPrivateMethodCheck { public void foo() {} private void bar() {} - private void qix() { // Noncompliant [[sc=16;ec=19]] {{Move this method into "Inner".}} + private void qix() { // Noncompliant {{Move this method into "Inner".}} +// ^^^ bar(); } - private void baz(){} // Noncompliant [[sc=16;ec=19]] {{Move this method into "Inner".}} - private void bax(){} // Noncompliant [[sc=16;ec=19]] {{Move this method into the anonymous class declared at line 59.}} + private void baz(){} // Noncompliant {{Move this method into "Inner".}} +// ^^^ + private void bax(){} // Noncompliant {{Move this method into the anonymous class declared at line 63.}} +// ^^^ private static void bay(){} // Compliant, can't move static method into non-static inner class - private static void baw() {} // Noncompliant [[sc=23;ec=26]] {{Move this method into "StaticInner".}} + private static void baw() {} // Noncompliant {{Move this method into "StaticInner".}} +// ^^^ private void calledOnAnotherInstance() {} // Compliant, called on another instance, cannot move it inside inner class private void calledOnAnotherInstance2() {} // Compliant, called on another instance, cannot move it inside inner class private void calledOnCurrentInstance() {} // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/CallSuperMethodFromInnerClassCheck.java b/java-checks-test-sources/default/src/main/java/checks/CallSuperMethodFromInnerClassCheck.java index 7adedda21f4..58eb05f28b3 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CallSuperMethodFromInnerClassCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/CallSuperMethodFromInnerClassCheck.java @@ -14,7 +14,7 @@ public void foo() {} public void plop() {} class Inner extends Parent { public void doTheThing() { - foo(); // Noncompliant {{Prefix this call to "foo" with "super.".}} + foo(); // Noncompliant {{Prefix this call to "foo" with "super.".}} super.foo(); //Compliant: unambiguous Outer.this.foo(); //Compliant: unambiguous qix(); //Compliant: No ambiguity, not defined in outer class @@ -24,7 +24,8 @@ public void doTheThing() { } public interface I extends I2 { default void toto() { - plop();// Noncompliant [[sc=9;ec=13]] {{Prefix this call to "plop" with "super.".}} + plop(); // Noncompliant {{Prefix this call to "plop" with "super.".}} +// ^^^^ } } public interface I2 { diff --git a/java-checks-test-sources/default/src/main/java/checks/CallToFileDeleteOnExitMethod.java b/java-checks-test-sources/default/src/main/java/checks/CallToFileDeleteOnExitMethod.java index 47a6da0090c..38c0ad2203f 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CallToFileDeleteOnExitMethod.java +++ b/java-checks-test-sources/default/src/main/java/checks/CallToFileDeleteOnExitMethod.java @@ -5,7 +5,8 @@ public class CallToFileDeleteOnExitMethod { public void doWork(File file) { - file.deleteOnExit(); // Noncompliant [[sc=10;ec=22]] {{Remove this call to "deleteOnExit".}} + file.deleteOnExit(); // Noncompliant {{Remove this call to "deleteOnExit".}} +// ^^^^^^^^^^^^ file.delete(); } diff --git a/java-checks-test-sources/default/src/main/java/checks/CaseInsensitiveComparisonCheck.java b/java-checks-test-sources/default/src/main/java/checks/CaseInsensitiveComparisonCheck.java index 7f419a6d990..3191062def5 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CaseInsensitiveComparisonCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/CaseInsensitiveComparisonCheck.java @@ -8,15 +8,16 @@ abstract class CaseInsensitiveComparisonCheck { private static final String BAR = "BAR"; private void f(String arg, String arg2) { - boolean result = arg.toUpperCase().equals(arg2.toLowerCase()); // Noncompliant [[sc=22;ec=66]] {{Replace these toUpperCase()/toLowerCase() and equals() calls with a single equalsIgnoreCase() call.}} - result = arg.toLowerCase().equals(BAR); // Noncompliant - result = arg.toUpperCase().equals(BAR); // Noncompliant - result = "foo".toUpperCase().equals(BAR); // Noncompliant - result = FOO.equals(arg.toLowerCase()); // Noncompliant - result = BAR.equals(arg.toUpperCase()); // Noncompliant - result = "FOO".equals(arg.toUpperCase()); // Noncompliant + boolean result = arg.toUpperCase().equals(arg2.toLowerCase()); // Noncompliant {{Replace these toUpperCase()/toLowerCase() and equals() calls with a single equalsIgnoreCase() call.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + result = arg.toLowerCase().equals(BAR); // Noncompliant + result = arg.toUpperCase().equals(BAR); // Noncompliant + result = "foo".toUpperCase().equals(BAR); // Noncompliant + result = FOO.equals(arg.toLowerCase()); // Noncompliant + result = BAR.equals(arg.toUpperCase()); // Noncompliant + result = "FOO".equals(arg.toUpperCase()); // Noncompliant // This one can't actually return true, but it's most likely *intended* to be a case-insensitive comparison: - result = "foo".equals(arg.toUpperCase()); // Noncompliant {{Replace these toUpperCase()/toLowerCase() and equals() calls with a single equalsIgnoreCase() call.}} + result = "foo".equals(arg.toUpperCase()); // Noncompliant {{Replace these toUpperCase()/toLowerCase() and equals() calls with a single equalsIgnoreCase() call.}} result = "foo".equals("foo"); // Compliant - no use of toUpperCase or toLowerCase result = arg.equals(arg2); // Compliant - ditto @@ -28,10 +29,10 @@ private void f(String arg, String arg2) { result = arg.toUpperCase(trLocale).equals(BAR); // Compliant when locale is specified because it does not behave like equalsIgnoreCase result = FOO.equals(arg.toLowerCase(trLocale)); // Compliant - FOO.equals(arg2.toLowerCase()); // Noncompliant {{Replace these toUpperCase()/toLowerCase() and equals() calls with a single equalsIgnoreCase() call.}} + FOO.equals(arg2.toLowerCase()); // Noncompliant {{Replace these toUpperCase()/toLowerCase() and equals() calls with a single equalsIgnoreCase() call.}} FOO.equals(toLowerCase()); // Compliant - BAR.equals(something().somethingElse().toUpperCase()); // Noncompliant {{Replace these toUpperCase()/toLowerCase() and equals() calls with a single equalsIgnoreCase() call.}} - FOO.equals("bar".toLowerCase()); // Noncompliant {{Replace these toUpperCase()/toLowerCase() and equals() calls with a single equalsIgnoreCase() call.}} + BAR.equals(something().somethingElse().toUpperCase()); // Noncompliant {{Replace these toUpperCase()/toLowerCase() and equals() calls with a single equalsIgnoreCase() call.}} + FOO.equals("bar".toLowerCase()); // Noncompliant {{Replace these toUpperCase()/toLowerCase() and equals() calls with a single equalsIgnoreCase() call.}} result = arg.equalsIgnoreCase(arg2); // Compliant @@ -40,8 +41,8 @@ private void f(String arg, String arg2) { StringUtils.equals("foo", "bar".toLowerCase()); // Compliant - arg.toLowerCase().toLowerCase().equals(FOO); // Noncompliant {{Replace these toUpperCase()/toLowerCase() and equals() calls with a single equalsIgnoreCase() call.}} - arg.toLowerCase().toUpperCase().equals(BAR); // Noncompliant {{Replace these toUpperCase()/toLowerCase() and equals() calls with a single equalsIgnoreCase() call.}} + arg.toLowerCase().toLowerCase().equals(FOO); // Noncompliant {{Replace these toUpperCase()/toLowerCase() and equals() calls with a single equalsIgnoreCase() call.}} + arg.toLowerCase().toUpperCase().equals(BAR); // Noncompliant {{Replace these toUpperCase()/toLowerCase() and equals() calls with a single equalsIgnoreCase() call.}} result = equals(arg.toLowerCase()); // Compliant (for coverage) } diff --git a/java-checks-test-sources/default/src/main/java/checks/CastArithmeticOperandCheck.java b/java-checks-test-sources/default/src/main/java/checks/CastArithmeticOperandCheck.java index 2229b60a402..93c69178357 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CastArithmeticOperandCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/CastArithmeticOperandCheck.java @@ -8,7 +8,8 @@ class CastArithmeticOperandCheck { void foo() { CastArithmeticOperandCheck a = new CastArithmeticOperandCheck(1 + 2, 1 + 2); // Noncompliant {{Cast one of the operands of this addition operation to a "long".}} - long l1 = 1000 * 3600 * 24 * 365; // Noncompliant [[sc=32;ec=33]] {{Cast one of the operands of this multiplication operation to a "long".}} + long l1 = 1000 * 3600 * 24 * 365; // Noncompliant {{Cast one of the operands of this multiplication operation to a "long".}} +// ^ l1 += 10 + 2; long l2 = 1000L * 3600 * 24 * 365; float f = 4L / 3; // Noncompliant {{Cast one of the operands of this division operation to a "float".}} @@ -18,13 +19,14 @@ void foo() { l2 = 1000 * 3600 * 24 * 365; // Noncompliant {{Cast one of the operands of this multiplication operation to a "long".}} l2 = 1000L * 3600 * 24 * 365; // compliant double d = 2 / 3; // Noncompliant {{Cast one of the operands of this division operation to a "double".}} - long l3 = 2 + Integer.MAX_VALUE; // Noncompliant [[sc=17;ec=18]] {{Cast one of the operands of this addition operation to a "long".}} + long l3 = 2 + Integer.MAX_VALUE; // Noncompliant {{Cast one of the operands of this addition operation to a "long".}} +// ^ l3 = 2 - Integer.MIN_VALUE; // Noncompliant {{Cast one of the operands of this subtraction operation to a "long".}} - longMethod(1 + 2, 1 + 2); // Noncompliant {{Cast one of the operands of this addition operation to a "long".}} + longMethod(1 + 2, 1 + 2); // Noncompliant {{Cast one of the operands of this addition operation to a "long".}} longMethod(1 + 2, 1 + 2l); // Compliant doubleMethod(1 + 2, 1 + 2); // Noncompliant {{Cast one of the operands of this addition operation to a "double".}} doubleMethod(1 + 2, 1 + 2d);// Compliant - floatMethod(1 + 2, 1 + 2); // Noncompliant {{Cast one of the operands of this addition operation to a "float".}} + floatMethod(1 + 2, 1 + 2); // Noncompliant {{Cast one of the operands of this addition operation to a "float".}} floatMethod(1 + 2, 1 + 2f); // Compliant foo(); //Compliant double tst = 1 | 2; // Compliant @@ -62,9 +64,11 @@ float f() { } void test_int_division() { - double a = 1 / 2 * 5.0; // Noncompliant [[sc=16;ec=21]] {{Cast one of the operands of this integer division to a "double".}} + double a = 1 / 2 * 5.0; // Noncompliant {{Cast one of the operands of this integer division to a "double".}} +// ^^^^^ double b = (1+3) / 5.0; // Compliant - double c = ((1 + 0) / 2 + 0) / 5.0; // Noncompliant [[sc=17;ec=28]] {{Cast one of the operands of this integer division to a "double".}} + double c = ((1 + 0) / 2 + 0) / 5.0; // Noncompliant {{Cast one of the operands of this integer division to a "double".}} +// ^^^^^^^^^^^ } void test_constructors() { diff --git a/java-checks-test-sources/default/src/main/java/checks/CatchIllegalMonitorStateExceptionCheck.java b/java-checks-test-sources/default/src/main/java/checks/CatchIllegalMonitorStateExceptionCheck.java index f9b7090b873..6176703876c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CatchIllegalMonitorStateExceptionCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/CatchIllegalMonitorStateExceptionCheck.java @@ -4,7 +4,8 @@ class CatchIllegalMonitorStateExceptionCheck { void myMethod(Object anObject) { try { anObject.notify(); - } catch(IllegalMonitorStateException e) { // Noncompliant [[sc=13;ec=41]] {{Refactor this piece of code to not catch IllegalMonitorStateException}} + } catch(IllegalMonitorStateException e) { // Noncompliant {{Refactor this piece of code to not catch IllegalMonitorStateException}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } catch(IllegalStateException e) { diff --git a/java-checks-test-sources/default/src/main/java/checks/CatchOfThrowableOrErrorCheck.java b/java-checks-test-sources/default/src/main/java/checks/CatchOfThrowableOrErrorCheck.java index bd47ce51696..ad5da4fec94 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CatchOfThrowableOrErrorCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/CatchOfThrowableOrErrorCheck.java @@ -10,35 +10,36 @@ private void f() throws Exception { Closer closer = Closer.create(); try { } catch (RuntimeException e) { // Compliant - } catch (Throwable e) { // Noncompliant [[sc=16;ec=25]] {{Catch Exception instead of Throwable.}} + } catch (Throwable e) { // Noncompliant {{Catch Exception instead of Throwable.}} +// ^^^^^^^^^ } try { - } catch (Error e) { // Noncompliant {{Catch Exception instead of Error.}} + } catch (Error e) { // Noncompliant {{Catch Exception instead of Error.}} } try { } catch (StackOverflowError f) { // Compliant } try { } catch (ArithmeticException | - Error | // Noncompliant {{Catch Exception instead of Error.}} + Error | // Noncompliant {{Catch Exception instead of Error.}} MissingResourceException g) { } try { - } catch (Throwable f) { // Noncompliant {{Catch Exception instead of Throwable.}} + } catch (Throwable f) { // Noncompliant {{Catch Exception instead of Throwable.}} } try { } catch (java.lang.Throwable e) { // Noncompliant {{Catch Exception instead of Throwable.}} } try { - } catch (java.lang.Error e) { // Noncompliant {{Catch Exception instead of Error.}} + } catch (java.lang.Error e) { // Noncompliant {{Catch Exception instead of Error.}} } try { - } catch (Throwable e) { // Noncompliant {{Catch Exception instead of Throwable.}} + } catch (Throwable e) { // Noncompliant {{Catch Exception instead of Throwable.}} throw e; } try { - } catch (Throwable e) { // Noncompliant {{Catch Exception instead of Throwable.}} + } catch (Throwable e) { // Noncompliant {{Catch Exception instead of Throwable.}} throw new Exception(e); } try { @@ -50,11 +51,11 @@ private void f() throws Exception { throw closer.rethrow(e); } try { - } catch (Throwable e) { // Noncompliant {{Catch Exception instead of Throwable.}} + } catch (Throwable e) { // Noncompliant {{Catch Exception instead of Throwable.}} throw closer.rethrow(new Exception(e)); } try { - } catch (Throwable e) { // Noncompliant {{Catch Exception instead of Throwable.}} + } catch (Throwable e) { // Noncompliant {{Catch Exception instead of Throwable.}} Throwable myThrowable = new Throwable(e); throw closer.rethrow(myThrowable); } diff --git a/java-checks-test-sources/default/src/main/java/checks/CatchUsesExceptionWithContextCheck.java b/java-checks-test-sources/default/src/main/java/checks/CatchUsesExceptionWithContextCheck.java index 806eb195da8..f35ce10abc0 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CatchUsesExceptionWithContextCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/CatchUsesExceptionWithContextCheck.java @@ -22,14 +22,15 @@ private static class A {} private void f(Exception x) { try { - } catch (Exception e) { // Noncompliant {{Either log or rethrow this exception.}} [[sc=14;ec=25]] + } catch (Exception e) { // Noncompliant {{Either log or rethrow this exception.}} +// ^^^^^^^^^^^ } try { } catch (Exception e) { // Compliant System.out.println(e); } try { - }catch (Exception e) { // Noncompliant + }catch (Exception e) { // Noncompliant System.out.println("foo: " + e.getMessage()); } try { @@ -37,7 +38,7 @@ private void f(Exception x) { System.out.println("" + e); } try { - } catch (Exception f) { // Noncompliant + } catch (Exception f) { // Noncompliant System.out.println("" + x); } try { @@ -48,7 +49,7 @@ private void f(Exception x) { } catch (Exception e) { // Compliant System.out.println("" + e); try { - } catch (Exception f) { // Noncompliant + } catch (Exception f) { // Noncompliant } } try { @@ -60,7 +61,7 @@ private void f(Exception x) { System.out.println("" + e); } catch (Exception e) { try { - } catch (Exception f) { // Noncompliant {{Either log or rethrow this exception.}} + } catch (Exception f) { // Noncompliant {{Either log or rethrow this exception.}} System.out.println("" + e); } } @@ -78,7 +79,7 @@ private void h() throws Throwable { throw com.google.common.base.Throwables.propagate(e); } catch (RuntimeException e) { // Compliant - propagation throw e; - } catch (Exception e) { // Noncompliant + } catch (Exception e) { // Noncompliant throw new RuntimeException("context"); } @@ -95,9 +96,9 @@ private void h() throws Throwable { } try { - } catch (Exception e) { // Noncompliant + } catch (Exception e) { // Noncompliant int a; - } catch (Throwable e) { // Noncompliant + } catch (Throwable e) { // Noncompliant } try { @@ -110,7 +111,7 @@ private void h() throws Throwable { Files.read(""); } catch (IOException e) { // Compliant throw new RuntimeException(e); - } catch (Exception e) { // Noncompliant + } catch (Exception e) { // Noncompliant throw new RuntimeException(e.getMessage()); } catch (Error e) { // Compliant throw com.google.common.base.Throwables.propagate(e); diff --git a/java-checks-test-sources/default/src/main/java/checks/CatchUsesExceptionWithContextCheckAllExceptions.java b/java-checks-test-sources/default/src/main/java/checks/CatchUsesExceptionWithContextCheckAllExceptions.java index 15ba0c68fa2..6e58dcb1c1e 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CatchUsesExceptionWithContextCheckAllExceptions.java +++ b/java-checks-test-sources/default/src/main/java/checks/CatchUsesExceptionWithContextCheckAllExceptions.java @@ -9,10 +9,10 @@ abstract class CatchUsesExceptionWithContextCheckAllExceptions { private void bar() { try { foo(); - } catch (NumberFormatException e) { // Noncompliant {{Either log or rethrow this exception.}} - } catch (InterruptedException e) { // Noncompliant - } catch (ParseException e) { // Noncompliant - } catch (MalformedURLException e) { // Noncompliant + } catch (NumberFormatException e) { // Noncompliant {{Either log or rethrow this exception.}} + } catch (InterruptedException e) { // Noncompliant + } catch (ParseException e) { // Noncompliant + } catch (MalformedURLException e) { // Noncompliant } catch (DateTimeParseException e) { // Noncompliant } } diff --git a/java-checks-test-sources/default/src/main/java/checks/ClassComparedByNameCheck.java b/java-checks-test-sources/default/src/main/java/checks/ClassComparedByNameCheck.java index 2a1899069db..802e8bdd209 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ClassComparedByNameCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/ClassComparedByNameCheck.java @@ -6,7 +6,8 @@ class ClassComparedByNameCheck { Class valueClass; String foo(String s) { - A.class.getSimpleName().equals("A"); // Noncompliant [[sc=5;ec=40]] {{Use an "instanceof" comparison instead.}} + A.class.getSimpleName().equals("A"); // Noncompliant {{Use an "instanceof" comparison instead.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ new A().getClass().getSimpleName().equals("A"); // Noncompliant {{Use an "instanceof" comparison instead.}} new A().getClass().getName().equals("A"); // Noncompliant {{Use an "instanceof" comparison instead.}} String name = new A().getClass().getName(); diff --git a/java-checks-test-sources/default/src/main/java/checks/ClassFieldCountCheck/SimpleDefaultCase.java b/java-checks-test-sources/default/src/main/java/checks/ClassFieldCountCheck/SimpleDefaultCase.java index ff575f93e7a..edcba6155fe 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ClassFieldCountCheck/SimpleDefaultCase.java +++ b/java-checks-test-sources/default/src/main/java/checks/ClassFieldCountCheck/SimpleDefaultCase.java @@ -1,6 +1,7 @@ package checks.ClassFieldCountCheck; -class TooManyFields { // Noncompliant [[sc=7;ec=20]] {{Refactor this class so it has no more than 20 fields, rather than the 26 it currently has.}} +class TooManyFields { // Noncompliant {{Refactor this class so it has no more than 20 fields, rather than the 26 it currently has.}} +// ^^^^^^^^^^^^^ int field1; int field2; int field3; diff --git a/java-checks-test-sources/default/src/main/java/checks/CollapsibleIfCandidateCheck.java b/java-checks-test-sources/default/src/main/java/checks/CollapsibleIfCandidateCheck.java index 646373f37e2..1dfead55113 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CollapsibleIfCandidateCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/CollapsibleIfCandidateCheck.java @@ -8,20 +8,22 @@ public class CollapsibleIfCandidateCheck { void testMyFile(File file) { if (file != null) { - if (file.isFile() || file.isDirectory()) { // Noncompliant [[sc=7;ec=9;quickfixes=qf1]] + if (file.isFile() || file.isDirectory()) { // Noncompliant [[quickfixes=qf1]] +// ^^ LOGGER.log(Level.INFO, file.getAbsolutePath()); } // fix@qf1 {{Merge this if statement with the enclosing one}} // edit@qf1 [[sl=-1;el=+0;sc=21;ec=11]] {{ && }} // edit@qf1 [[sc=11;ec=11]] {{(}} // edit@qf1 [[sc=46;ec=46]] {{)}} - // edit@qf1 [[sl=+8;el=+8;sc=5;ec=6]] {{}} + // edit@qf1 [[sl=+9;el=+9;sc=5;ec=6]] {{}} } } void noBraceOnOuter(File file) { if (file != null) - if (file.isFile() || file.isDirectory()) { // Noncompliant [[sc=7;ec=9;quickfixes=qf2]] + if (file.isFile() || file.isDirectory()) { // Noncompliant [[quickfixes=qf2]] +// ^^ LOGGER.log(Level.INFO, file.getAbsolutePath()); } // fix@qf2 {{Merge this if statement with the enclosing one}} @@ -32,59 +34,64 @@ void noBraceOnOuter(File file) { void noBraceOnInner(File file) { if (file != null) { - if (file.isFile() || file.isDirectory()) LOGGER.log(Level.INFO, file.getAbsolutePath()); // Noncompliant [[sc=7;ec=9;quickfixes=qf3]] + if (file.isFile() || file.isDirectory()) LOGGER.log(Level.INFO, file.getAbsolutePath()); // Noncompliant [[quickfixes=qf3]] +// ^^ // fix@qf3 {{Merge this if statement with the enclosing one}} // edit@qf3 [[sl=-1;el=+0;sc=21;ec=11]] {{ && }} // edit@qf3 [[sc=11;ec=11]] {{(}} // edit@qf3 [[sc=46;ec=46]] {{)}} - // edit@qf3 [[sl=+6;el=+6;sc=5;ec=6]] {{}} + // edit@qf3 [[sl=+7;el=+7;sc=5;ec=6]] {{}} } } void leftConditionNeedsParenthesis(boolean a, boolean b, boolean c) { if (a || b) { - if (c) { // Noncompliant [[sc=7;ec=9;quickfixes=qf4]] + if (c) { // Noncompliant [[quickfixes=qf4]] +// ^^ // fix@qf4 {{Merge this if statement with the enclosing one}} // edit@qf4 [[sl=-1;el=+0;sc=15;ec=11]] {{ && }} // edit@qf4 [[sl=-1;el=-1;sc=9;ec=9]] {{(}} // edit@qf4 [[sl=-1;el=-1;sc=15;ec=15]] {{)}} - // edit@qf4 [[sl=+7;el=+7;sc=5;ec=6]] {{}} + // edit@qf4 [[sl=+8;el=+8;sc=5;ec=6]] {{}} } } } void rightConditionNeedsParenthesis(boolean a, boolean c, boolean d) { if (a) { - if (c || d) { // Noncompliant [[sc=7;ec=9;quickfixes=qf5]] + if (c || d) { // Noncompliant [[quickfixes=qf5]] +// ^^ // fix@qf5 {{Merge this if statement with the enclosing one}} // edit@qf5 [[sl=-1;el=+0;sc=10;ec=11]] {{ && }} // edit@qf5 [[sc=11;ec=11]] {{(}} // edit@qf5 [[sc=17;ec=17]] {{)}} - // edit@qf5 [[sl=+7;el=+7;sc=5;ec=6]] {{}} + // edit@qf5 [[sl=+8;el=+8;sc=5;ec=6]] {{}} } } } void bothConditionsNeedParenthesis(boolean a, boolean b, boolean c, boolean d) { if (a || b) { - if (c || d) { // Noncompliant [[sc=7;ec=9;quickfixes=qf6]] + if (c || d) { // Noncompliant [[quickfixes=qf6]] +// ^^ // fix@qf6 {{Merge this if statement with the enclosing one}} // edit@qf6 [[sl=-1;el=+0;sc=15;ec=11]] {{ && }} // edit@qf6 [[sl=-1;el=-1;sc=9;ec=9]] {{(}} // edit@qf6 [[sl=-1;el=-1;sc=15;ec=15]] {{)}} // edit@qf6 [[sc=11;ec=11]] {{(}} // edit@qf6 [[sc=17;ec=17]] {{)}} - // edit@qf6 [[sl=+9;el=+9;sc=5;ec=6]] {{}} + // edit@qf6 [[sl=+10;el=+10;sc=5;ec=6]] {{}} } } } void noConditionNeedsParenthesis(boolean a, boolean c) { if (a) { - if (c) { // Noncompliant [[sc=7;ec=9;quickfixes=qf7]] + if (c) { // Noncompliant [[quickfixes=qf7]] +// ^^ // fix@qf7 {{Merge this if statement with the enclosing one}} // edit@qf7 [[sl=-1;el=+0;sc=10;ec=11]] {{ && }} - // edit@qf7 [[sl=+5;el=+5;sc=5;ec=6]] {{}} + // edit@qf7 [[sl=+6;el=+6;sc=5;ec=6]] {{}} } } } @@ -97,7 +104,8 @@ void noInnerBlockImpliesSingleStatement(boolean a, boolean c) { } void noBraceOnAny(boolean a, boolean c) { - if (a) if (c); // Noncompliant [[sc=12;ec=14;quickfixes=qf10]] + if (a) if (c); // Noncompliant [[quickfixes=qf10]] +// ^^ // fix@qf10 {{Merge this if statement with the enclosing one}} // edit@qf10 [[sc=10;ec=16]] {{ && }} } @@ -105,31 +113,34 @@ void noBraceOnAny(boolean a, boolean c) { void operatorsWithLowerPrecedenceCoverage(boolean b, boolean c) { boolean a; if (a = b) { - if (c) { // Noncompliant [[sc=7;ec=9;quickfixes=qf11]] + if (c) { // Noncompliant [[quickfixes=qf11]] +// ^^ // fix@qf11 {{Merge this if statement with the enclosing one}} // edit@qf11 [[sl=-1;el=+0;sc=14;ec=11]] {{ && }} // edit@qf11 [[sl=-1;el=-1;sc=9;ec=9]] {{(}} // edit@qf11 [[sl=-1;el=-1;sc=14;ec=14]] {{)}} - // edit@qf11 [[sl=+7;el=+7;sc=5;ec=6]] {{}} + // edit@qf11 [[sl=+8;el=+8;sc=5;ec=6]] {{}} } } if (a? b: c) { - if (c) { // Noncompliant [[sc=7;ec=9;quickfixes=qf12]] + if (c) { // Noncompliant [[quickfixes=qf12]] +// ^^ // fix@qf12 {{Merge this if statement with the enclosing one}} // edit@qf12 [[sl=-1;el=+0;sc=16;ec=11]] {{ && }} // edit@qf12 [[sl=-1;el=-1;sc=9;ec=9]] {{(}} // edit@qf12 [[sl=-1;el=-1;sc=16;ec=16]] {{)}} - // edit@qf12 [[sl=+7;el=+7;sc=5;ec=6]] {{}} + // edit@qf12 [[sl=+8;el=+8;sc=5;ec=6]] {{}} } } } void operatorsWithHigherPrecedenceCoverage(boolean a, boolean b, boolean c) { if (a | b) { - if (c) { // Noncompliant [[sc=7;ec=9;quickfixes=qf13]] + if (c) { // Noncompliant [[quickfixes=qf13]] +// ^^ // fix@qf13 {{Merge this if statement with the enclosing one}} // edit@qf13 [[sl=-1;el=+0;sc=14;ec=11]] {{ && }} - // edit@qf13 [[sl=+5;el=+5;sc=5;ec=6]] {{}} + // edit@qf13 [[sl=+6;el=+6;sc=5;ec=6]] {{}} } } } diff --git a/java-checks-test-sources/default/src/main/java/checks/CollectionConstructorReferenceCheck.java b/java-checks-test-sources/default/src/main/java/checks/CollectionConstructorReferenceCheck.java index 672cb92562b..401a5efa7cd 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CollectionConstructorReferenceCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/CollectionConstructorReferenceCheck.java @@ -25,7 +25,8 @@ void foo() { Map> col1 = Stream.of(1, 2, 54000) .collect(Collectors.toMap( Function.identity(), - ArrayList::new));// Noncompliant [[sc=9;ec=23]] {{Replace this method reference by a lambda to explicitly show the usage of ArrayList(int initialCapacity) or ArrayList().}} + ArrayList::new)); // Noncompliant {{Replace this method reference by a lambda to explicitly show the usage of ArrayList(int initialCapacity) or ArrayList().}} +// ^^^^^^^^^^^^^^ Map> col2 = Stream.of(1, 2, 54000) .collect(Collectors.toMap( @@ -46,8 +47,10 @@ void foo() { BitSet::new, // Compliant, not a collection HashMap::new, // Noncompliant HashSet::new, // Noncompliant - Hashtable::new, // Noncompliant [[sc=7;ec=21]] {{Replace this method reference by a lambda to explicitly show the usage of Hashtable(int initialCapacity) or Hashtable().}} - IdentityHashMap::new, // Noncompliant [[sc=7;ec=27]] {{Replace this method reference by a lambda to explicitly show the usage of IdentityHashMap(int expectedMaxSize) or IdentityHashMap().}} + Hashtable::new, // Noncompliant {{Replace this method reference by a lambda to explicitly show the usage of Hashtable(int initialCapacity) or Hashtable().}} +// ^^^^^^^^^^^^^^ + IdentityHashMap::new, // Noncompliant {{Replace this method reference by a lambda to explicitly show the usage of IdentityHashMap(int expectedMaxSize) or IdentityHashMap().}} +// ^^^^^^^^^^^^^^^^^^^^ LinkedHashMap::new, // Noncompliant LinkedHashSet::new, // Noncompliant PriorityQueue::new, // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/CollectionImplementationReferencedCheck.java b/java-checks-test-sources/default/src/main/java/checks/CollectionImplementationReferencedCheck.java index 28324c39b7f..ee7ecb50cf9 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CollectionImplementationReferencedCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/CollectionImplementationReferencedCheck.java @@ -16,32 +16,37 @@ class EmployeesTopLevel { public EmployeesTopLevel(String s) { } - public HashSet employees = new HashSet<>(); // Noncompliant [[sc=10;ec=17;quickfixes=HashSet1]] {{The type of "employees" should be an interface such as "Set" rather than the implementation "HashSet".}} + public HashSet employees = new HashSet<>(); // Noncompliant {{The type of "employees" should be an interface such as "Set" rather than the implementation "HashSet".}} [[quickfixes=HashSet1]] +// ^^^^^^^ // fix@HashSet1 {{Replace "HashSet" by "Set"}} // edit@HashSet1 [[sc=10;ec=17]] {{Set}} private HashSet employees2 = new HashSet(); - public HashSet getEmployees() { return employees; } // Noncompliant {{The return type of this method should be an interface such as "Set" rather than the implementation "HashSet".}} + public HashSet getEmployees() { return employees; } // Noncompliant {{The return type of this method should be an interface such as "Set" rather than the implementation "HashSet".}} - public LinkedList foo1() { return null; } // Noncompliant [[sc=10;ec=20;quickfixes=LinkedList]] {{The return type of this method should be an interface such as "List" rather than the implementation "LinkedList".}} + public LinkedList foo1() { return null; } // Noncompliant {{The return type of this method should be an interface such as "List" rather than the implementation "LinkedList".}} [[quickfixes=LinkedList]] +// ^^^^^^^^^^ // fix@LinkedList {{Replace "LinkedList" by "List"}} // edit@LinkedList [[sc=10;ec=20]] {{List}} // edit@LinkedList [[sl=5;sc=29;el=5;ec=29]] {{\nimport java.util.List;}} private LinkedList foo2() { return null; } - public java.util.HashSet foo3() { return null; } // Noncompliant [[sc=10;ec=27;quickfixes=HashSet2]] {{The return type of this method should be an interface such as "Set" rather than the implementation "HashSet".}} + public java.util.HashSet foo3() { return null; } // Noncompliant {{The return type of this method should be an interface such as "Set" rather than the implementation "HashSet".}} [[quickfixes=HashSet2]] +// ^^^^^^^^^^^^^^^^^ // fix@HashSet2 {{Replace "HashSet" by "Set"}} // edit@HashSet2 [[sc=10;ec=27]] {{Set}} - public HashMap foo4() { return null; } // Noncompliant [[sc=10;ec=17]] {{The return type of this method should be an interface such as "Map" rather than the implementation "HashMap".}} + public HashMap foo4() { return null; } // Noncompliant {{The return type of this method should be an interface such as "Map" rather than the implementation "HashMap".}} +// ^^^^^^^ private Stack stack; private Vector vector; public LinkedList publicList; // Noncompliant {{The type of "publicList" should be an interface such as "List" rather than the implementation "LinkedList".}} private LinkedList privateList; - public ConcurrentHashMap concurrentHashMap() { return null; } // Noncompliant [[sc=10;ec=27;quickfixes=ConcurrentHashMap]] {{The return type of this method should be an interface such as "ConcurrentMap" rather than the implementation "ConcurrentHashMap".}} + public ConcurrentHashMap concurrentHashMap() { return null; } // Noncompliant {{The return type of this method should be an interface such as "ConcurrentMap" rather than the implementation "ConcurrentHashMap".}} [[quickfixes=ConcurrentHashMap]] +// ^^^^^^^^^^^^^^^^^ // fix@ConcurrentHashMap {{Replace "ConcurrentHashMap" by "ConcurrentMap"}} // edit@ConcurrentHashMap [[sc=10;ec=27]] {{ConcurrentMap}} // edit@ConcurrentHashMap [[sl=12;sc=47;el=12;ec=47]] {{\nimport java.util.concurrent.ConcurrentMap;}} @@ -52,7 +57,8 @@ private void method1(LinkedList employees) {} public void method2(LinkedList employees) {} // Noncompliant {{The type of "employees" should be an interface such as "List" rather than the implementation "LinkedList".}} class A { - public void foo(HashMap map) { } // Noncompliant [[sc=21;ec=28;quickfixes=HashMap]] + public void foo(HashMap map) { } // Noncompliant [[quickfixes=HashMap]] +// ^^^^^^^ // fix@HashMap {{Replace "HashMap" by "Map"}} // edit@HashMap [[sc=21;ec=28]] {{Map}} } @@ -76,19 +82,19 @@ public Set getEmployees(){ // Compliant abstract class ApiEnforcesClassSonarjava4590 { - public void foo1(TreeMap map) { } // Noncompliant, no TreeMap specific API used + public void foo1(TreeMap map) { } // Noncompliant public Map.Entry foo2(TreeMap map) { // Compliant, TreeMap specific API used return map.lowerEntry("bar"); } - public void foo3(TreeSet set) { } // Noncompliant, no TreeSet specific API used + public void foo3(TreeSet set) { } // Noncompliant public Integer foo4(TreeSet set) { // Compliant, TreeSet specific API used return set.ceiling(42); } - public Integer foo5(TreeSet set) { // Noncompliant, no TreeSet specific API used + public Integer foo5(TreeSet set) { // Noncompliant return set.size(); } @@ -101,7 +107,7 @@ public Integer foo6(LinkedList dq, boolean condition) { // Compliant, L } } - public Integer foo7(LinkedList dq, boolean condition) { // Noncompliant, no LinkedList specific API used + public Integer foo7(LinkedList dq, boolean condition) { // Noncompliant if (condition) { return dq.size(); } else { @@ -110,12 +116,12 @@ public Integer foo7(LinkedList dq, boolean condition) { // Noncompliant } } - public Map.Entry foo8(TreeMap map) { // Noncompliant due to current limitation of the rule + public Map.Entry foo8(TreeMap map) { // Noncompliant TreeMap map2 = map; return map2.lowerEntry("bar"); } - public Map.Entry foo9(TreeMap map) { // Noncompliant due to current limitation of the rule + public Map.Entry foo9(TreeMap map) { // Noncompliant var map2 = map; return map2.lowerEntry("bar"); } @@ -124,22 +130,26 @@ public Integer foo10(LinkedList l1, LinkedList l2, LinkedList< return l1.poll() + l2.poll() + l3.poll(); } - public Integer foo11(LinkedList l1, LinkedList l2, LinkedList l3) { // Noncompliant [[sc=48;ec=58]] + public Integer foo11(LinkedList l1, LinkedList l2, LinkedList l3) { // Noncompliant +// ^^^^^^^^^^ return l1.poll() + l2.get(0) + l3.poll(); } - // Noncompliant@+2 [[sc=24;ec=34]] - // Noncompliant@+1 [[sc=72;ec=82]] - public Integer foo12(LinkedList l1, LinkedList l2, LinkedList l3) { + + + public Integer foo12(LinkedList l1, LinkedList l2, LinkedList l3) { // Noncompliant 2 +// ^^^^^^^^^^ return l1.get(0) + l2.poll() + l3.get(0); } - // Noncompliant@+3 [[sc=33;ec=43]] - // Noncompliant@+2 [[sc=57;ec=67]] - // Noncompliant@+1 [[sc=81;ec=91]] - public abstract Integer foo13(LinkedList l1, LinkedList l2, LinkedList l3); - public Integer foo14(LinkedList list) { // Noncompliant [[sc=24;ec=34]] + + + public abstract Integer foo13(LinkedList l1, LinkedList l2, LinkedList l3); // Noncompliant 3 +// ^^^^^^^^^^ + + public Integer foo14(LinkedList list) { // Noncompliant +// ^^^^^^^^^^ return getList().poll(); } diff --git a/java-checks-test-sources/default/src/main/java/checks/CollectionInappropriateCallsCheck.java b/java-checks-test-sources/default/src/main/java/checks/CollectionInappropriateCallsCheck.java index 5c35a708f26..c45cfb72b29 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CollectionInappropriateCallsCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/CollectionInappropriateCallsCheck.java @@ -29,7 +29,8 @@ private void myMethod() { String[] myArrayString = new String[] {"myString"}; Integer[] myArrayInteger = new Integer[] {Integer.valueOf(1)}; - myList.contains(myInteger); // Noncompliant [[sc=12;ec=20]] {{A "List" cannot contain a "Integer".}} + myList.contains(myInteger); // Noncompliant {{A "List" cannot contain a "Integer".}} +// ^^^^^^^^ myList.remove(myInteger); // Noncompliant {{A "List" cannot contain a "Integer".}} myList.removeAll(myNumberList); // Noncompliant {{A "List" cannot contain a "Number".}} myList.removeAll(Arrays.asList("a", "b")); @@ -61,7 +62,7 @@ private void myMethod() { mapAString.remove(new A(), "val"); mapAString.remove(new A(), new A()); // Noncompliant {{A "Map" cannot contain a "A" in a "String" type.}} mapAString.remove("key", new A()); // Noncompliant - // Noncompliant@-1 + // Noncompliant@-1 mapAString.remove("key", "val"); // Noncompliant {{A "Map" cannot contain a "String" in a "A" type.}} Map mapStringA = new HashMap<>(); @@ -71,7 +72,7 @@ private void myMethod() { mapStringA.getOrDefault("key", new A()); mapStringA.remove("key"); mapStringA.remove(new A(), "val"); // Noncompliant - // Noncompliant@-1 + // Noncompliant@-1 mapStringA.remove(new A(), new A()); // Noncompliant {{A "Map" cannot contain a "A" in a "String" type.}} mapStringA.remove("key", new A()); mapStringA.remove("key", "val"); // Noncompliant {{A "Map" cannot contain a "String" in a "A" type.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/CollectionIsEmptyCheck.java b/java-checks-test-sources/default/src/main/java/checks/CollectionIsEmptyCheck.java index a760e807392..9ab4d84adf0 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CollectionIsEmptyCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/CollectionIsEmptyCheck.java @@ -12,59 +12,73 @@ private void foo(Collection myCollection, Collection myCollection2, CollectionIs boolean b; int i; - b = myCollection.size() == 0; // Noncompliant [[sc=9;ec=33;quickfixes=qf1]] {{Use isEmpty() to check whether the collection is empty or not.}} + b = myCollection.size() == 0; // Noncompliant {{Use isEmpty() to check whether the collection is empty or not.}} [[quickfixes=qf1]] +// ^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf1 {{Use "isEmpty()"}} // edit@qf1 [[sc=22;ec=33]] {{isEmpty()}} - b = myCollection.size() != 0; // Noncompliant [[sc=9;ec=33;quickfixes=qf2]] + b = myCollection.size() != 0; // Noncompliant [[quickfixes=qf2]] +// ^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf2 {{Use "isEmpty()"}} // edit@qf2 [[sc=9;ec=9]] {{!}} // edit@qf2 [[sc=22;ec=33]] {{isEmpty()}} - b = myCollection.size() > 0; // Noncompliant [[sc=9;ec=32;quickfixes=qf3]] + b = myCollection.size() > 0; // Noncompliant [[quickfixes=qf3]] +// ^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf3 {{Use "isEmpty()"}} // edit@qf3 [[sc=9;ec=9]] {{!}} // edit@qf3 [[sc=22;ec=32]] {{isEmpty()}} - b = myCollection.size() >= 1; // Noncompliant [[sc=9;ec=33;quickfixes=qf4]] + b = myCollection.size() >= 1; // Noncompliant [[quickfixes=qf4]] +// ^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf4 {{Use "isEmpty()"}} // edit@qf4 [[sc=9;ec=9]] {{!}} // edit@qf4 [[sc=22;ec=33]] {{isEmpty()}} - b = myCollection.size() < 1; // Noncompliant [[sc=9;ec=32;quickfixes=qf5]] + b = myCollection.size() < 1; // Noncompliant [[quickfixes=qf5]] +// ^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf5 {{Use "isEmpty()"}} // edit@qf5 [[sc=22;ec=32]] {{isEmpty()}} - b = myCollection.size() <= 0; // Noncompliant [[sc=9;ec=33;quickfixes=qf6]] + b = myCollection.size() <= 0; // Noncompliant [[quickfixes=qf6]] +// ^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf6 {{Use "isEmpty()"}} // edit@qf6 [[sc=22;ec=33]] {{isEmpty()}} - b = 0 == myCollection.size(); // Noncompliant [[sc=9;ec=33;quickfixes=qf7]] + b = 0 == myCollection.size(); // Noncompliant [[quickfixes=qf7]] +// ^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf7 {{Use "isEmpty()"}} // edit@qf7 [[sc=9;ec=14]] {{}} // edit@qf7 [[sc=27;ec=33]] {{isEmpty()}} - b = 0 != myCollection.size(); // Noncompliant [[sc=9;ec=33;quickfixes=qf8]] + b = 0 != myCollection.size(); // Noncompliant [[quickfixes=qf8]] +// ^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf8 {{Use "isEmpty()"}} // edit@qf8 [[sc=9;ec=14]] {{!}} // edit@qf8 [[sc=27;ec=33]] {{isEmpty()}} - b = 0 < myCollection.size(); // Noncompliant [[sc=9;ec=32;quickfixes=qf9]] + b = 0 < myCollection.size(); // Noncompliant [[quickfixes=qf9]] +// ^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf9 {{Use "isEmpty()"}} // edit@qf9 [[sc=9;ec=13]] {{!}} // edit@qf9 [[sc=26;ec=32]] {{isEmpty()}} - b = 1 <= myCollection.size(); // Noncompliant [[sc=9;ec=33;quickfixes=qf10]] + b = 1 <= myCollection.size(); // Noncompliant [[quickfixes=qf10]] +// ^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf10 {{Use "isEmpty()"}} // edit@qf10 [[sc=9;ec=14]] {{!}} // edit@qf10 [[sc=27;ec=33]] {{isEmpty()}} - b = 1 > myCollection.size(); // Noncompliant [[sc=9;ec=32;quickfixes=qf11]] + b = 1 > myCollection.size(); // Noncompliant [[quickfixes=qf11]] +// ^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf11 {{Use "isEmpty()"}} // edit@qf11 [[sc=9;ec=13]] {{}} // edit@qf11 [[sc=26;ec=32]] {{isEmpty()}} - b = 0 >= myCollection.size(); // Noncompliant [[sc=9;ec=33;quickfixes=qf12]] + b = 0 >= myCollection.size(); // Noncompliant [[quickfixes=qf12]] +// ^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf12 {{Use "isEmpty()"}} // edit@qf12 [[sc=9;ec=14]] {{}} // edit@qf12 [[sc=27;ec=33]] {{isEmpty()}} - b = 0 == Arrays.asList("a", "b").size(); // Noncompliant [[sc=9;ec=44;quickfixes=qf13]] + b = 0 == Arrays.asList("a", "b").size(); // Noncompliant [[quickfixes=qf13]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf13 {{Use "isEmpty()"}} // edit@qf13 [[sc=9;ec=14]] {{}} // edit@qf13 [[sc=38;ec=44]] {{isEmpty()}} - b = Arrays.asList("a", "b").size() != 0; // Noncompliant [[sc=9;ec=44;quickfixes=qf14]] + b = Arrays.asList("a", "b").size() != 0; // Noncompliant [[quickfixes=qf14]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf14 {{Use "isEmpty()"}} // edit@qf14 [[sc=9;ec=9]] {{!}} // edit@qf14 [[sc=33;ec=44]] {{isEmpty()}} diff --git a/java-checks-test-sources/default/src/main/java/checks/CollectionSizeAndArrayLengthCheck.java b/java-checks-test-sources/default/src/main/java/checks/CollectionSizeAndArrayLengthCheck.java index 93199f45f5f..d75b48ca5df 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CollectionSizeAndArrayLengthCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/CollectionSizeAndArrayLengthCheck.java @@ -11,20 +11,20 @@ abstract class CollectionSizeAndArrayLengthCheck implements List { void foo(Collection coll, String[] arr, B b) { - if (size() >= 0) { } // Noncompliant {{The size of a collection is always ">=0", so update this test to use isEmpty().}} + if (size() >= 0) { } // Noncompliant {{The size of a collection is always ">=0", so update this test to use isEmpty().}} if (0 >= size()) { } // Compliant - not always true or false - if (getList().size() < 0) { } // Noncompliant {{The size of a collection is always ">=0", so update this test to use isEmpty().}} - if (coll.size() >= 0) { } // Noncompliant {{The size of "coll" is always ">=0", so update this test to use isEmpty().}} - if (0 <= coll.size()) { } // Noncompliant {{The size of "coll" is always ">=0", so update this test to use isEmpty().}} + if (getList().size() < 0) { } // Noncompliant {{The size of a collection is always ">=0", so update this test to use isEmpty().}} + if (coll.size() >= 0) { } // Noncompliant {{The size of "coll" is always ">=0", so update this test to use isEmpty().}} + if (0 <= coll.size()) { } // Noncompliant {{The size of "coll" is always ">=0", so update this test to use isEmpty().}} - if (arr.length >= 0) { } // Noncompliant {{The length of "arr" is always ">=0", so update this test to either "==0" or ">0".}} + if (arr.length >= 0) { } // Noncompliant {{The length of "arr" is always ">=0", so update this test to either "==0" or ">0".}} if (getArray().length < 0) { } // Noncompliant {{The length of an array is always ">=0", so update this test to either "==0" or ">0".}} - if (this.ray.length >= 0) { } // Noncompliant {{The length of "ray" is always ">=0", so update this test to either "==0" or ">0".}} - if (0 <= arr.length) { } // Noncompliant {{The length of "arr" is always ">=0", so update this test to either "==0" or ">0".}} + if (this.ray.length >= 0) { } // Noncompliant {{The length of "ray" is always ">=0", so update this test to either "==0" or ">0".}} + if (0 <= arr.length) { } // Noncompliant {{The length of "arr" is always ">=0", so update this test to either "==0" or ">0".}} - if (0 > coll.size()) { } // Noncompliant {{The size of "coll" is always ">=0", so update this test to use isEmpty().}} - if (0 > arr.length) { } // Noncompliant {{The length of "arr" is always ">=0", so update this test to either "==0" or ">0".}} + if (0 > coll.size()) { } // Noncompliant {{The size of "coll" is always ">=0", so update this test to use isEmpty().}} + if (0 > arr.length) { } // Noncompliant {{The length of "arr" is always ">=0", so update this test to either "==0" or ">0".}} if (arr.length > 0) { } // Compliant if (coll.size() == 0) { } // Compliant - will be handled by S1155 diff --git a/java-checks-test-sources/default/src/main/java/checks/CollectorsToListCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/CollectorsToListCheckSample.java index 21213235827..35855b746c2 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CollectorsToListCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/CollectorsToListCheckSample.java @@ -18,19 +18,23 @@ static class ListWrapper { void noncompliant() { List list1 = Stream.of("A", "B", "C") - .collect(Collectors.toList()); // Noncompliant [[sc=16;ec=35]] {{Replace this usage of 'Stream.collect(Collectors.toList())' with 'Stream.toList()' and ensure that the list is unmodified.}} + .collect(Collectors.toList()); // Noncompliant {{Replace this usage of 'Stream.collect(Collectors.toList())' with 'Stream.toList()' and ensure that the list is unmodified.}} +// ^^^^^^^^^^^^^^^^^^^ // Not modifying the list list1.contains("B"); List list2 = Stream.of("A", "B", "C") - .collect(Collectors.toUnmodifiableList()); // Noncompliant [[sc=16;ec=47]] {{Replace this usage of 'Stream.collect(Collectors.toUnmodifiableList())' with 'Stream.toList()'.}} + .collect(Collectors.toUnmodifiableList()); // Noncompliant {{Replace this usage of 'Stream.collect(Collectors.toUnmodifiableList())' with 'Stream.toList()'.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Stream.of("A", "B", "C") - .collect(Collectors.toList()); // Noncompliant [[sc=16;ec=35]] {{Replace this usage of 'Stream.collect(Collectors.toList())' with 'Stream.toList()' and ensure that the list is unmodified.}} + .collect(Collectors.toList()); // Noncompliant {{Replace this usage of 'Stream.collect(Collectors.toList())' with 'Stream.toList()' and ensure that the list is unmodified.}} +// ^^^^^^^^^^^^^^^^^^^ Stream.of("A", "B", "C") - .collect(Collectors.toUnmodifiableList()); // Noncompliant [[sc=16;ec=47]] {{Replace this usage of 'Stream.collect(Collectors.toUnmodifiableList())' with 'Stream.toList()'.}} + .collect(Collectors.toUnmodifiableList()); // Noncompliant {{Replace this usage of 'Stream.collect(Collectors.toUnmodifiableList())' with 'Stream.toList()'.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ List> listOfLists = new ArrayList<>(); // list1 appears in a call to List.add, but it is not the receiver, so it should not be interpreted as mutable: @@ -65,7 +69,7 @@ void compliant_collections_methods() { void noncompliant_collections_methods() { var myMutableList = Stream.of("A", "B", "C") - .collect(Collectors.toList()); // Noncompliant, below methods do not modify the list + .collect(Collectors.toList()); // Noncompliant Collections.max(myMutableList); Collections.frequency(myMutableList, "A"); Collections.synchronizedList(myMutableList); @@ -126,14 +130,14 @@ void FNs() { List FPs() { List list1 = Stream.of("A", "B", "C") - .collect(Collectors.toList()); // Noncompliant - FP because we don't track lists across methods + .collect(Collectors.toList()); // Noncompliant addX(list1); - addX(Stream.of("A", "B", "C").collect(Collectors.toList())); // Noncompliant - same reason + addX(Stream.of("A", "B", "C").collect(Collectors.toList())); // Noncompliant - memberList2 = Stream.of("A", "B", "C").collect(Collectors.toList()); // Noncompliant - FP, see addX2 + memberList2 = Stream.of("A", "B", "C").collect(Collectors.toList()); // Noncompliant - return Stream.of("A", "B", "C").collect(Collectors.toList()); // Noncompliant - FP because we don't check how the return value is used + return Stream.of("A", "B", "C").collect(Collectors.toList()); // Noncompliant } void useFPs() { diff --git a/java-checks-test-sources/default/src/main/java/checks/CombineCatchCheck.java b/java-checks-test-sources/default/src/main/java/checks/CombineCatchCheck.java index d35f3a1e113..e129a3e0fdf 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CombineCatchCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/CombineCatchCheck.java @@ -10,10 +10,12 @@ void foo() { try { canThrow(); } catch (IOException e) { +// ^[el=+4;ec=5]> doCleanup(); logger.log(e); } - catch (SQLException e) { // Noncompliant [[sc=12;ec=26;secondary=12]] {{Combine this catch with the one at line 12, which has the same body.}} + catch (SQLException e) { // Noncompliant {{Combine this catch with the one at line 12, which has the same body.}} +// ^^^^^^^^^^^^^^ doCleanup(); logger.log(e); } @@ -21,7 +23,8 @@ void foo() { doCleanup(); throw e; } - catch (ArrayStoreException e) { // Noncompliant [[sc=11;ec=32;secondary=16]] {{Combine this catch with the one at line 16, which has the same body.}} + catch (ArrayStoreException e) { // Noncompliant {{Combine this catch with the one at line 17, which has the same body.}} +// ^^^^^^^^^^^^^^^^^^^^^ doCleanup(); logger.log(e); } @@ -29,10 +32,12 @@ void foo() { try { canThrow(); } catch (IOException | java.lang.IllegalArgumentException e) { +// ^[el=+4;ec=5]> doCleanup(); logger.log(e); } - catch (SQLException e) { // Noncompliant [[sc=12;ec=26;secondary=31]] {{Combine this catch with the one at line 31, which has the same body.}} + catch (SQLException e) { // Noncompliant {{Combine this catch with the one at line 34, which has the same body.}} +// ^^^^^^^^^^^^^^ doCleanup(); logger.log(e); } diff --git a/java-checks-test-sources/default/src/main/java/checks/CommentedCode.java b/java-checks-test-sources/default/src/main/java/checks/CommentedCode.java index 2041974fe1f..23f85a1125c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CommentedCode.java +++ b/java-checks-test-sources/default/src/main/java/checks/CommentedCode.java @@ -30,14 +30,14 @@ public class CommentedCode { public CommentedCode(int field) { this.field = field; // This is a comment, but next line is a commented-out code - // Noncompliant@+1 - // Noncompliant@+2 {{This block of commented-out lines of code should be removed.}} + // Noncompliant@+1 + // Noncompliant@+2 {{This block of commented-out lines of code should be removed.}} // for (Visitor visitor : visitors) { // continue; // } - // Noncompliant@+3 + // Noncompliant@+3 /* This is a comment, but next line is a commented-out code for (Visitor visitor : visitors) { @@ -45,46 +45,57 @@ public CommentedCode(int field) { } */ - // Noncompliant@+2 + // Noncompliant@+2 /* This is a comment, but next line is a commented-out code */ /* for (Visitor visitor : visitors) { */ /* continue; */ /* } */ - // Noncompliant@+2 [[sc=8;ec=42]] + +// Noncompliant@+2 /* Limitation: only the first line of a commented block is highlighted * for (Visitor visitor : visitors) { +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * continue; +// ^^^^^^^^< * } */ - // Noncompliant@+2 [[sc=8;ec=44]] + // Only one issue is highlighted per list of consecutive comments - /* for (Visitor visitor : visitors) { } */ /* for (Visitor visitor : visitors) { } */ + /* for (Visitor visitor : visitors) { } */ /* for (Visitor visitor : visitors) { } */ // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - // Noncompliant@+3 - // Noncompliant@+2 + // Noncompliant@+3 + // Noncompliant@+2 // Several issues are highlighted for non consecutive comments if (/* for (Visitor visitor : visitors) { } */field == 0) { /* for (Visitor visitor : visitors) { } */ } - // Noncompliant@+2 [[sc=16;ec=52]] +// Noncompliant@+2 // Comment prefix and suffix are not highlighted /* for (Visitor visitor : visitors) { } */ +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + - // Noncompliant@+2 [[sc=10;ec=46]] +// Noncompliant@+2 /* Leading star is not highlighted * for (Visitor visitor : visitors) { } +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */ - // Noncompliant@+2 [[sc=10;ec=46]] + +// Noncompliant@+2 /* Leading spaces are not highlighted for (Visitor visitor : visitors) { } +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */ - // Noncompliant@+2 [[sc=16;ec=50;secondary=88]] + +// Noncompliant@+2 // Leading spaces are not highlighted // for (Visitor visitor : visitors) { +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // } // TODO @@ -114,12 +125,16 @@ public static native void alert(String msg) /* not JSNI comment */ /*-{ } }-*/ - // Noncompliant@+3 [[sc=6;ec=40;secondary=121,122]] + +// Noncompliant@+3 /* * This is not a documentation comment * for (Visitor visitor : visitors) { +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * continue; +// ^^^^^^^^< * } +// ^< */ public void method(String s) { } diff --git a/java-checks-test-sources/default/src/main/java/checks/CompareStringsBoxedTypesWithEqualsCheck.java b/java-checks-test-sources/default/src/main/java/checks/CompareStringsBoxedTypesWithEqualsCheck.java index 907e0df01cb..68ca10a6046 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CompareStringsBoxedTypesWithEqualsCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/CompareStringsBoxedTypesWithEqualsCheck.java @@ -12,27 +12,32 @@ class Boxed { int myInt2 = 2; void offerQuickFixes() { - if (str1 == str2) {} // Noncompliant [[sc=16;ec=18;quickfixes=qf0]] {{Strings and Boxed types should be compared using "equals()".}} + if (str1 == str2) {} // Noncompliant {{Strings and Boxed types should be compared using "equals()".}} [[quickfixes=qf0]] +// ^^ // fix@qf0 {{Replace with boxed comparison}} // edit@qf0 [[sc=23;ec=23]]{{)}} // edit@qf0 [[sc=15;ec=19]]{{, }} // edit@qf0 [[sc=11;ec=11]]{{Objects.equals(}} // edit@qf0 [[sl=3;sc=25;el=3;ec=25]]{{\nimport java.util.Objects;}} - if (str1 == "blue") {} // Noncompliant [[sc=16;ec=18;quickfixes=qf1]] + if (str1 == "blue") {} // Noncompliant [[quickfixes=qf1]] +// ^^ // fix@qf1 {{Replace with boxed comparison}} // edit@qf1 [[sc=15;ec=25]]{{)}} // edit@qf1 [[sc=11;ec=11]]{{"blue".equals(}} - if ("blue" == str1) {} // Noncompliant [[sc=18;ec=20;quickfixes=qf2]] + if ("blue" == str1) {} // Noncompliant [[quickfixes=qf2]] +// ^^ // fix@qf2 {{Replace with boxed comparison}} // edit@qf2 [[sc=25;ec=25]]{{)}} // edit@qf2 [[sc=17;ec=21]]{{.equals(}} - if (str1 == "BLUE".toLowerCase(Locale.ROOT)) {} // Noncompliant [[sc=16;ec=18;quickfixes=qf3]] + if (str1 == "BLUE".toLowerCase(Locale.ROOT)) {} // Noncompliant [[quickfixes=qf3]] +// ^^ // fix@qf3 {{Replace with boxed comparison}} // edit@qf3 [[sc=50;ec=50]]{{)}} // edit@qf3 [[sc=15;ec=19]]{{, }} // edit@qf3 [[sc=11;ec=11]]{{Objects.equals(}} // edit@qf3 [[sl=3;sc=25;el=3;ec=25]]{{\nimport java.util.Objects;}} - if ("BLUE".toLowerCase(Locale.ROOT) == str1) {} // Noncompliant [[sc=43;ec=45;quickfixes=qf4]] + if ("BLUE".toLowerCase(Locale.ROOT) == str1) {} // Noncompliant [[quickfixes=qf4]] +// ^^ // fix@qf4 {{Replace with boxed comparison}} // edit@qf4 [[sc=50;ec=50]]{{)}} // edit@qf4 [[sc=42;ec=46]]{{, }} @@ -40,28 +45,33 @@ void offerQuickFixes() { // edit@qf4 [[sl=3;sc=25;el=3;ec=25]]{{\nimport java.util.Objects;}} /* -- NEGATION -- */ - if (str1 != str2) {} // Noncompliant [[sc=16;ec=18;quickfixes=qf100]] + if (str1 != str2) {} // Noncompliant [[quickfixes=qf100]] +// ^^ // fix@qf100 {{Replace with boxed comparison}} // edit@qf100 [[sc=23;ec=23]]{{)}} // edit@qf100 [[sc=15;ec=19]]{{, }} // edit@qf100 [[sc=11;ec=11]]{{!Objects.equals(}} // edit@qf100 [[sl=3;sc=25;el=3;ec=25]]{{\nimport java.util.Objects;}} - if (str1 != "blue") {} // Noncompliant [[sc=16;ec=18;quickfixes=qf101]] + if (str1 != "blue") {} // Noncompliant [[quickfixes=qf101]] +// ^^ // fix@qf101 {{Replace with boxed comparison}} // edit@qf101 [[sc=15;ec=25]]{{)}} // edit@qf101 [[sc=11;ec=11]]{{!"blue".equals(}} - if ("blue" != str1) {} // Noncompliant [[sc=18;ec=20;quickfixes=qf102]] + if ("blue" != str1) {} // Noncompliant [[quickfixes=qf102]] +// ^^ // fix@qf102 {{Replace with boxed comparison}} // edit@qf102 [[sc=25;ec=25]]{{)}} // edit@qf102 [[sc=17;ec=21]]{{.equals(}} // edit@qf102 [[sc=11;ec=11]]{{!}} - if (str1 != "BLUE".toLowerCase(Locale.ROOT)) {} // Noncompliant [[sc=16;ec=18;quickfixes=qf103]] + if (str1 != "BLUE".toLowerCase(Locale.ROOT)) {} // Noncompliant [[quickfixes=qf103]] +// ^^ // fix@qf103 {{Replace with boxed comparison}} // edit@qf103 [[sc=50;ec=50]]{{)}} // edit@qf103 [[sc=15;ec=19]]{{, }} // edit@qf103 [[sc=11;ec=11]]{{!Objects.equals(}} // edit@qf103 [[sl=3;sc=25;el=3;ec=25]]{{\nimport java.util.Objects;}} - if ("BLUE".toLowerCase(Locale.ROOT) != str1) {} // Noncompliant [[sc=43;ec=45;quickfixes=qf104]] + if ("BLUE".toLowerCase(Locale.ROOT) != str1) {} // Noncompliant [[quickfixes=qf104]] +// ^^ // fix@qf104 {{Replace with boxed comparison}} // edit@qf104 [[sc=50;ec=50]]{{)}} // edit@qf104 [[sc=42;ec=46]]{{, }} diff --git a/java-checks-test-sources/default/src/main/java/checks/CompareToNotOverloadedCheck.java b/java-checks-test-sources/default/src/main/java/checks/CompareToNotOverloadedCheck.java index 77564240090..b762262f99b 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CompareToNotOverloadedCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/CompareToNotOverloadedCheck.java @@ -9,7 +9,7 @@ public int compareTo(A a) { } class B extends A { - public int compareTo(B b) { // Noncompliant {{Refactor this method so that its argument is of type 'A'.}} + public int compareTo(B b) { // Noncompliant {{Refactor this method so that its argument is of type 'A'.}} return 0; } @@ -29,7 +29,7 @@ public int compareTo(Object a) { // Compliant } class E extends C { - public int compareTo(E e) { // Noncompliant {{Refactor this method so that its argument is of type 'Object'.}} + public int compareTo(E e) { // Noncompliant {{Refactor this method so that its argument is of type 'Object'.}} return -1; } } @@ -41,7 +41,7 @@ public int compareTo(A rhs) { } static class FooBar extends Bar { - public int compareTo(FooBar rhs) { // Noncompliant: Parameter should be of type Bar + public int compareTo(FooBar rhs) { // Noncompliant return 0; } } diff --git a/java-checks-test-sources/default/src/main/java/checks/CompareToResultTestCheck.java b/java-checks-test-sources/default/src/main/java/checks/CompareToResultTestCheck.java index 1f23bdba50d..a24a9f8447b 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CompareToResultTestCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/CompareToResultTestCheck.java @@ -15,7 +15,8 @@ public int compareTo(MyComparable other) { int field; public void aMethod(MyComparable other, NotComparable notComparable) { - if (compareTo(other) == -1) {} // Noncompliant [[sc=28;ec=30]] {{Only the sign of the result should be examined.}} + if (compareTo(other) == -1) {} // Noncompliant {{Only the sign of the result should be examined.}} +// ^^ if (compareTo(other) == (-1)) {} // Noncompliant if (compareTo(other) == -5) {} // Noncompliant if (compareTo(other) == 0) {} @@ -85,42 +86,54 @@ public int compareTo(MyComparable other1, MyComparable other2) { } public void quickFixes(MyComparable other, NotComparable notComparable) { - if (compareTo(other) == 1) {} // Noncompliant [[sc=28;ec=30;quickfixes=qf1]] + if (compareTo(other) == 1) {} // Noncompliant [[quickfixes=qf1]] +// ^^ // fix@qf1 {{Replace with "> 0"}} // edit@qf1 [[sc=28;ec=32]] {{> 0}} - if (compareTo(other) == -1) {} // Noncompliant [[sc=28;ec=30;quickfixes=qf2]] + if (compareTo(other) == -1) {} // Noncompliant [[quickfixes=qf2]] +// ^^ // fix@qf2 {{Replace with "< 0"}} // edit@qf2 [[sc=28;ec=33]] {{< 0}} - if (1 == compareTo(notComparable)) {} // Noncompliant [[sc=13;ec=15;quickfixes=qf3]] + if (1 == compareTo(notComparable)) {} // Noncompliant [[quickfixes=qf3]] +// ^^ // fix@qf3 {{Replace with "0 <"}} // edit@qf3 [[sc=11;ec=15]] {{0 <}} - if (-1 == compareTo(notComparable)) {} // Noncompliant [[sc=14;ec=16;quickfixes=qf4]] + if (-1 == compareTo(notComparable)) {} // Noncompliant [[quickfixes=qf4]] +// ^^ // fix@qf4 {{Replace with "0 >"}} // edit@qf4 [[sc=11;ec=16]] {{0 >}} - if (compareTo(other) == (-1)) {} // Noncompliant [[sc=28;ec=30;quickfixes=qf5]] + if (compareTo(other) == (-1)) {} // Noncompliant [[quickfixes=qf5]] +// ^^ // fix@qf5 {{Replace with "< 0"}} // edit@qf5 [[sc=28;ec=35]] {{< 0}} - if (compareTo(other) == MINUS_ONE) {} // Noncompliant [[sc=28;ec=30;quickfixes=qf6]] + if (compareTo(other) == MINUS_ONE) {} // Noncompliant [[quickfixes=qf6]] +// ^^ // fix@qf6 {{Replace with "< 0"}} // edit@qf6 [[sc=28;ec=40]] {{< 0}} - if (compareTo(other) == -MINUS_ONE) {} // Noncompliant [[sc=28;ec=30;quickfixes=qf7]] + if (compareTo(other) == -MINUS_ONE) {} // Noncompliant [[quickfixes=qf7]] +// ^^ // fix@qf7 {{Replace with "> 0"}} // edit@qf7 [[sc=28;ec=41]] {{> 0}} - if (compareTo(other) == -(-1)) {} // Noncompliant [[sc=28;ec=30;quickfixes=qf8]] + if (compareTo(other) == -(-1)) {} // Noncompliant [[quickfixes=qf8]] +// ^^ // fix@qf8 {{Replace with "> 0"}} // edit@qf8 [[sc=28;ec=36]] {{> 0}} // For !=, even if we could in theory replace by <=/>= 0, we do not suggest quick fixes and let the user figure out what was his intent - if (1 != compareTo(notComparable)) {} // Noncompliant [[sc=13;ec=15;quickfixes=!]] - if (-1 != compareTo(notComparable)) {} // Noncompliant [[sc=14;ec=16;quickfixes=!]] - if (compareTo(other) != 1) {} // Noncompliant [[sc=28;ec=30;quickfixes=!]] - if (compareTo(other) != -1) {} // Noncompliant [[sc=28;ec=30;quickfixes=!]] + if (1 != compareTo(notComparable)) {} // Noncompliant [[quickfixes=!]] +// ^^ + if (-1 != compareTo(notComparable)) {} // Noncompliant [[quickfixes=!]] +// ^^ + if (compareTo(other) != 1) {} // Noncompliant [[quickfixes=!]] +// ^^ + if (compareTo(other) != -1) {} // Noncompliant [[quickfixes=!]] +// ^^ } } diff --git a/java-checks-test-sources/default/src/main/java/checks/CompareToReturnValueCheck.java b/java-checks-test-sources/default/src/main/java/checks/CompareToReturnValueCheck.java index ec8fda53589..7e4bd25e913 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CompareToReturnValueCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/CompareToReturnValueCheck.java @@ -4,7 +4,8 @@ class CompareToReturnValueCheck { class A implements Comparable { @Override public int compareTo(A a) { - return Integer.MIN_VALUE; // Noncompliant [[sc=14;ec=31]] {{Simply return -1}} + return Integer.MIN_VALUE; // Noncompliant {{Simply return -1}} +// ^^^^^^^^^^^^^^^^^ } public int compareTo() { diff --git a/java-checks-test-sources/default/src/main/java/checks/ConcatenationWithStringValueOfCheck.java b/java-checks-test-sources/default/src/main/java/checks/ConcatenationWithStringValueOfCheck.java index 6e3642b9b7c..6638316c9df 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ConcatenationWithStringValueOfCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/ConcatenationWithStringValueOfCheck.java @@ -6,7 +6,8 @@ class ConcatenationWithStringValueOfCheck { ConcatenationWithStringValueOfCheck valueOf; private void f(int buf, ConcatenationWithStringValueOfCheck a) { - System.out.println("" + String.valueOf(0)); // Noncompliant [[sc=29;ec=46]] {{Directly append the argument of String.valueOf().}} + System.out.println("" + String.valueOf(0)); // Noncompliant {{Directly append the argument of String.valueOf().}} +// ^^^^^^^^^^^^^^^^^ System.out.println("" + String.valueOf(null, 0, 0)); // Compliant System.out.println(String.valueOf(0)); // Compliant System.out.println("" + ""); // Compliant @@ -37,23 +38,27 @@ private void f(int buf, ConcatenationWithStringValueOfCheck a) { private void quickfixes() { var num = 99; - var a = "" + String.valueOf(num) + " balloons"; // Noncompliant [[sc=18;ec=37;quickfixes=qf1]] {{Directly append the argument of String.valueOf().}} + var a = "" + String.valueOf(num) + " balloons"; // Noncompliant {{Directly append the argument of String.valueOf().}} [[quickfixes=qf1]] +// ^^^^^^^^^^^^^^^^^^^ // fix@qf1 {{Remove redundant String.valueOf() wrapping}} // edit@qf1 [[sc=18;ec=37]] {{num}} - a = "" + String.valueOf(num + num); // Noncompliant [[sc=14;ec=39;quickfixes=qf2]] + a = "" + String.valueOf(num + num); // Noncompliant [[quickfixes=qf2]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf2 {{Remove redundant String.valueOf() wrapping}} // edit@qf2 [[sc=14;ec=39]] {{(num + num)}} - a = "" + String.valueOf(num - num); // Noncompliant [[sc=14;ec=39;quickfixes=qf3]] + a = "" + String.valueOf(num - num); // Noncompliant [[quickfixes=qf3]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf3 {{Remove redundant String.valueOf() wrapping}} // edit@qf3 [[sc=14;ec=39]] {{(num - num)}} - a = "" + String.valueOf(-num); // Noncompliant [[sc=14;ec=34;quickfixes=qf4]] + a = "" + String.valueOf(-num); // Noncompliant [[quickfixes=qf4]] +// ^^^^^^^^^^^^^^^^^^^^ // fix@qf4 {{Remove redundant String.valueOf() wrapping}} // edit@qf4 [[sc=14;ec=34]] {{-num}} - // Noncompliant@+1 [[sc=14;sl=+1;ec=6;el=+4;quickfixes=qfml]] +// Noncompliant@+1 [[sc=14;ec=6;sl=+0;el=+3;quickfixes=qfml]] a = "" + String.valueOf(2 + 3 * 4 - 5 / 6 @@ -63,15 +68,18 @@ private void quickfixes() { // edit@qfml [[sc=14;ec=6;el=+3]] {{(2 +\n 3 * 4 -\n 5 / 6)}} var world = "world"; - var b = "Hello, " + String.valueOf(world + world); // Noncompliant [[sc=25;ec=54;quickfixes=qf5]] + var b = "Hello, " + String.valueOf(world + world); // Noncompliant [[quickfixes=qf5]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf5 {{Remove redundant String.valueOf() wrapping}} // edit@qf5 [[sc=25;ec=54]] {{world + world}} - b = "Hello, " + String.valueOf(world.charAt(2)) + "!"; // Noncompliant [[sc=21;ec=52;quickfixes=qf6]] + b = "Hello, " + String.valueOf(world.charAt(2)) + "!"; // Noncompliant [[quickfixes=qf6]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf6 {{Remove redundant String.valueOf() wrapping}} // edit@qf6 [[sc=21;ec=52]] {{world.charAt(2)}} - b = "Hello, " + String.valueOf((world.charAt(2))) + "!"; // Noncompliant [[sc=21;ec=54;quickfixes=qf7]] + b = "Hello, " + String.valueOf((world.charAt(2))) + "!"; // Noncompliant [[quickfixes=qf7]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf7 {{Remove redundant String.valueOf() wrapping}} // edit@qf7 [[sc=21;ec=54]] {{(world.charAt(2))}} } diff --git a/java-checks-test-sources/default/src/main/java/checks/ConditionalOnNewLineCheck.java b/java-checks-test-sources/default/src/main/java/checks/ConditionalOnNewLineCheck.java index da1053dccb8..4d015328de1 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ConditionalOnNewLineCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/ConditionalOnNewLineCheck.java @@ -4,14 +4,18 @@ class ConditionalOnNewLineCheck { void foo(boolean condition1, boolean condition2) { if (condition1) { // ... - } if (condition2) { // Noncompliant [[sc=7;ec=9;secondary=7]] {{Move this "if" to a new line or add the missing "else".}} + } if (condition2) { // Noncompliant {{Move this "if" to a new line or add the missing "else".}} +// ^^ +// ^@-1< //... } if (condition1) { // ... } else { - } if (condition2) { // Noncompliant [[sc=7;ec=9;secondary=14]] {{Move this "if" to a new line or add the missing "else".}} + } if (condition2) { // Noncompliant {{Move this "if" to a new line or add the missing "else".}} +// ^^ +// ^@-1< //... } @@ -19,7 +23,9 @@ void foo(boolean condition1, boolean condition2) { // ... } else if(condition2) { - } if (condition2) { // Noncompliant [[sc=7;ec=9;secondary=22]] {{Move this "if" to a new line or add the missing "else".}} + } if (condition2) { // Noncompliant {{Move this "if" to a new line or add the missing "else".}} +// ^^ +// ^@-1< //... } if (condition1) { @@ -38,7 +44,9 @@ void foo(boolean condition1, boolean condition2) { if (condition1) { - } if (condition1) { // Noncompliant [[sc=7;ec=9;secondary=41]] {{Move this "if" to a new line or add the missing "else".}} + } if (condition1) { // Noncompliant {{Move this "if" to a new line or add the missing "else".}} +// ^^ +// ^@-1< // ... } else { // ... @@ -48,7 +56,9 @@ void foo(boolean condition1, boolean condition2) { // ... } else { // ... - } if (condition1) { // Noncompliant [[sc=7;ec=9;secondary=51]] {{Move this "if" to a new line or add the missing "else".}} + } if (condition1) { // Noncompliant {{Move this "if" to a new line or add the missing "else".}} +// ^^ +// ^@-1< // ... } else { // ... @@ -58,7 +68,9 @@ void foo(boolean condition1, boolean condition2) { // ... } else if(condition2) { // ... - } if (condition1) { // Noncompliant [[sc=7;ec=9;secondary=61]] {{Move this "if" to a new line or add the missing "else".}} + } if (condition1) { // Noncompliant {{Move this "if" to a new line or add the missing "else".}} +// ^^ +// ^@-1< // ... } else { // ... diff --git a/java-checks-test-sources/default/src/main/java/checks/ConfigurationBeanNamesCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ConfigurationBeanNamesCheckSample.java index 4fe87ba6aa6..7609da5b04d 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ConfigurationBeanNamesCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ConfigurationBeanNamesCheckSample.java @@ -17,7 +17,8 @@ public User user() { } @Bean - public User user(String name) { // Noncompliant [[sc=17;ec=21]] {{Rename this bean method to prevent any conflict with other beans.}} + public User user(String name) { // Noncompliant {{Rename this bean method to prevent any conflict with other beans.}} +// ^^^^ return new User(); } } diff --git a/java-checks-test-sources/default/src/main/java/checks/ConfusingOverloadCheck.java b/java-checks-test-sources/default/src/main/java/checks/ConfusingOverloadCheck.java index a30d5ef384b..872cc007046 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ConfusingOverloadCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/ConfusingOverloadCheck.java @@ -18,7 +18,8 @@ private void privateMethod() { public class Child extends Parent { - public void doSomething(Fruit.Pear p) { // Noncompliant [[sc=17;ec=28]] {{Rename this method or correct the type of the argument(s) to override the parent class method.}} + public void doSomething(Fruit.Pear p) { // Noncompliant {{Rename this method or correct the type of the argument(s) to override the parent class method.}} +// ^^^^^^^^^^^ } public void doSomething(Fruit.Apple a) { diff --git a/java-checks-test-sources/default/src/main/java/checks/ConfusingVarargCheck.java b/java-checks-test-sources/default/src/main/java/checks/ConfusingVarargCheck.java index d00fddac740..5b37dd0cbef 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ConfusingVarargCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/ConfusingVarargCheck.java @@ -12,14 +12,17 @@ public static void main(String[] args) { Integer[] arrWrapper = {1, 2, 3}; Object nullObject = null; - new A(1, null); // Noncompliant [[sc=14;ec=18]] {{Cast this argument to 'String' to pass a single element to the vararg method.}} + new A(1, null); // Noncompliant {{Cast this argument to 'String' to pass a single element to the vararg method.}} +// ^^^^ new A(2, (String) null); new A(3, args); new A(4); - vararg(null); // Noncompliant [[sc=12;ec=16]] {{Cast this argument to 'Object' to pass a single element to the vararg method.}} + vararg(null); // Noncompliant {{Cast this argument to 'Object' to pass a single element to the vararg method.}} +// ^^^^ vararg((null)); // Noncompliant - vararg(arr); // Noncompliant [[sc=12;ec=15]] {{Use an array of 'Integer' instead of an array of 'int'.}} + vararg(arr); // Noncompliant {{Use an array of 'Integer' instead of an array of 'int'.}} +// ^^^ vararg((Object) null); vararg(arrWrapper); diff --git a/java-checks-test-sources/default/src/main/java/checks/ConstantMathCheck.java b/java-checks-test-sources/default/src/main/java/checks/ConstantMathCheck.java index f374c6ed9ef..6508b6c4439 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ConstantMathCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/ConstantMathCheck.java @@ -3,7 +3,8 @@ public class ConstantMathCheck { public void method(int a, Integer integer, Double doubleParam) { - byte b = (byte) (a % 1); // Noncompliant [[sc=24;ec=25]] {{Remove this computation of % 1, which always evaluates to zero.}} + byte b = (byte) (a % 1); // Noncompliant {{Remove this computation of % 1, which always evaluates to zero.}} +// ^ double v = 7.4d; double remainder = v % 1; // compliant, remainder is ~0.4 b = (byte) (integer % 1); // Noncompliant @@ -12,7 +13,8 @@ public void method(int a, Integer integer, Double doubleParam) { int d = a % a; // Compliant, currently not covered by this rule short s = 0x7fff; - Math.abs((double)' '); // Noncompliant [[sc=5;ec=13]] {{Remove this unnecessary call to "Math.abs"}} + Math.abs((double)' '); // Noncompliant {{Remove this unnecessary call to "Math.abs"}} +// ^^^^^^^^ Math.abs((float) 0); // Noncompliant {{Remove this unnecessary call to "Math.abs"}} Math.abs(0); // Noncompliant {{Remove this unnecessary call to "Math.abs"}} Math.abs(0L); // Noncompliant {{Remove this unnecessary call to "Math.abs"}} diff --git a/java-checks-test-sources/default/src/main/java/checks/ConstantMethodCheck.java b/java-checks-test-sources/default/src/main/java/checks/ConstantMethodCheck.java index 36d32764322..31fe8efd3cc 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ConstantMethodCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/ConstantMethodCheck.java @@ -5,18 +5,22 @@ public final class ConstantMethodCheck implements Comparable { int foo() { - return 1; // Noncompliant [[sc=12;ec=13]] {{Remove this method and declare a constant for this value.}} + return 1; // Noncompliant {{Remove this method and declare a constant for this value.}} +// ^ } boolean baz() { - return true; // Noncompliant [[sc=12;ec=16]] {{Remove this method and declare a constant for this value.}} + return true; // Noncompliant {{Remove this method and declare a constant for this value.}} +// ^^^^ } String bar() { - return ""; // Noncompliant [[sc=12;ec=14]] {{Remove this method and declare a constant for this value.}} + return ""; // Noncompliant {{Remove this method and declare a constant for this value.}} +// ^^ } char qix() { - return 'c'; // Noncompliant [[sc=12;ec=15]] {{Remove this method and declare a constant for this value.}} + return 'c'; // Noncompliant {{Remove this method and declare a constant for this value.}} +// ^^^ } Object lum() { return new Object(); // Compliant @@ -43,7 +47,8 @@ public int compareTo(@NotNull ConstantMethodCheck o) { return 0; // Compliant - method is an override } long gro() { - return 1L; // Noncompliant [[sc=12;ec=14]] {{Remove this method and declare a constant for this value.}} + return 1L; // Noncompliant {{Remove this method and declare a constant for this value.}} +// ^^ } @MyAnnotation @@ -84,7 +89,7 @@ final long finalMethod() { return 1L; // Noncompliant } String noFinalMethod() { - // Noncompliant@+1 + // Noncompliant@+1 return """ text block """; diff --git a/java-checks-test-sources/default/src/main/java/checks/ConstantsShouldBeStaticFinalCheck.java b/java-checks-test-sources/default/src/main/java/checks/ConstantsShouldBeStaticFinalCheck.java index 100bc578f2e..7f54facb762 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ConstantsShouldBeStaticFinalCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/ConstantsShouldBeStaticFinalCheck.java @@ -13,7 +13,8 @@ class Parent { abstract class A extends Parent { private final static int foo = 1; - private final int f1 = 0; // Noncompliant [[sc=23;ec=25]] {{Make this final field static too.}} + private final int f1 = 0; // Noncompliant {{Make this final field static too.}} +// ^^ private final static int f2 = 0; // Compliant private static final int f3 = 0; // Compliant public final int f4 = ConstantsShouldBeStaticFinalCheckEnumTest.MY_CONSTANT; // Noncompliant @@ -21,16 +22,16 @@ abstract class A extends Parent { private final int f6 = foo(); // Compliant private final int f62 = this.foo; // Compliant private final int f63 = super.foo; // Compliant - private final int f64 = foo; // Noncompliant + private final int f64 = foo; // Noncompliant private int f7 = 0; // Compliant private int f8; // Compliant private final int f9; // Compliant private final checks.ConstantsShouldBeStaticFinalCheck.A myA = this; // Compliant private final int - f10 = 0, // Noncompliant + f10 = 0, // Noncompliant f11, // Compliant f12 = foo(), // Compliant - f13 = MY_CONSTANT; // Noncompliant + f13 = MY_CONSTANT; // Noncompliant private final int[] newInt = new int[42]; // Compliant private final String[] NOT_POSSIBLE = {}; // compliant, array are not constants protected final Object [] a = new Object[] {"UTF-8", null}; // compliant, array are not constants diff --git a/java-checks-test-sources/default/src/main/java/checks/ControlCharacterInLiteralCheck.java b/java-checks-test-sources/default/src/main/java/checks/ControlCharacterInLiteralCheck.java index 7cbc7d535087ae82076982c3fb128122dc973ecf..43cf5f1e0e6c85dff42ce1ec1d5abfd49bdf9b79 100644 GIT binary patch delta 118 zcmew@(JQ&ZfpPMBM!Cs3jEVyK`U(nhNMLgh<0}rJtn}phTq=s_vPcRc%*}_mBp`;d a@+b;Im2)Wof%>C{2KC8?>|&E$dCUO#gCx`d delta 86 zcmeB`{4KG;fsr>lx;WX^)H*fU*3dk5@OrFA}viTO5 TI3o{2mjy%lGh1eZ7b9sf;R \t diff --git a/java-checks-test-sources/default/src/main/java/checks/CounterModeIVShouldNotBeReusedCheck.java b/java-checks-test-sources/default/src/main/java/checks/CounterModeIVShouldNotBeReusedCheck.java index 18924dfbe32..d0a3af983a8 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CounterModeIVShouldNotBeReusedCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/CounterModeIVShouldNotBeReusedCheck.java @@ -24,26 +24,43 @@ void testJca(String unknownString, byte[] unkownBytes) { char[] chars = "testme".toCharArray(); +// ^^^^^^^^^^^^^^^^^^^^^^> byte[] bytes = String.valueOf(chars).getBytes(utf8); +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^> GCMParameterSpec params5 = new GCMParameterSpec(128, bytes); - cipher.init(1, skeySpec, params5); // Noncompliant [[sc=14;ec=18;secondary=+0,-1,-2,-3]] +// ^^^^^> + cipher.init(1, skeySpec, params5); // Noncompliant +// ^^^^ ^^^^^^^< cipher.init(Cipher.DECRYPT_MODE, skeySpec, params5); // Compliant decrypt mode byte[] KEY_BYTES = {0x41, 0x70, 0x61, 0x63, 0x68, 0x65, 0x43, 0x6F, 0x6D, 0x6D, 0x6F, 0x6E, 0x73, 0x56, 0x46, 0x53}; +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^> GCMParameterSpec params4 = new GCMParameterSpec(128, KEY_BYTES); - cipher.init(1, skeySpec, params4); // Noncompliant [[sc=14;ec=18;secondary=+0,-1,-2]] +// ^^^^^^^^^> + cipher.init(1, skeySpec, params4); // Noncompliant +// ^^^^ ^^^^^^^< byte[] src = "7cVgr5cbdCZV".getBytes(utf8); +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^> GCMParameterSpec params = new GCMParameterSpec(128, src); - cipher.init(1, skeySpec, params); // Noncompliant [[secondary=+0,-1,-2]] {{Use a dynamically-generated initialization vector (IV) to avoid IV-key pair reuse.}} - cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new GCMParameterSpec(128, src)); // Noncompliant [[secondary=+0,-3]] +// ^^^> + cipher.init(1, skeySpec, params); // Noncompliant {{Use a dynamically-generated initialization vector (IV) to avoid IV-key pair reuse.}} +// ^^^^ ^^^^^^< + cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new GCMParameterSpec(128, src)); // Noncompliant +// ^^^^ ^^^< +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^@-7< cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new GCMParameterSpec(128, new byte[]{})); String staticPiece1 = "imjustthefirsthalf"; +// ^^^^^^^^^^^^^^^^^^^^> String staticPiece2 = "secondhalf"; +// ^^^^^^^^^^^^> byte[] bytes1 = (staticPiece1+staticPiece2).getBytes(); +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^> GCMParameterSpec gcm = new GCMParameterSpec(128, bytes1); - cipher.init(1, skeySpec, gcm); // Noncompliant [[secondary=+0,-1,-2,-3,-4]] +// ^^^^^^> + cipher.init(1, skeySpec, gcm); // Noncompliant +// ^^^^ ^^^< GCMParameterSpec gcm3 = new GCMParameterSpec(128, unkownBytes); cipher.init(1, skeySpec, gcm3); @@ -74,9 +91,12 @@ void bouncyCastle(byte[] byteArrayFromElsewhere, String stringFromSomewhere) { CCMBlockCipher ccmCipher = new CCMBlockCipher(engine); GCMBlockCipher gcmCipher = new GCMBlockCipher(engine); byte[] nonce = "7cVgr5cbdCZV".getBytes(utf8); // Secondary location: The initialization vector is a static value +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^> AEADParameters params = new AEADParameters(new KeyParameter(key), 128, nonce); // Secondary location: The initialization vector is configured here. +// ^^^^^> ccmCipher.init(true, params); // Noncompliant - gcmCipher.init(true, params); // Noncompliant [[sc=17;ec=21;secondary=+0,-2,-3]] + gcmCipher.init(true, params); // Noncompliant +// ^^^^ ^^^^^^< gcmCipher.init(false, params); // Compliant AEADParameters staticParams = new AEADParameters(new KeyParameter(key), 0, byteArrayFromElsewhere); diff --git a/java-checks-test-sources/default/src/main/java/checks/DanglingElseStatementsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/DanglingElseStatementsCheckSample.java index 4449c45edfe..d25307c9983 100644 --- a/java-checks-test-sources/default/src/main/java/checks/DanglingElseStatementsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/DanglingElseStatementsCheckSample.java @@ -47,7 +47,7 @@ else if (d > e) if (a) if (b) d++; - else // Noncompliant {{Add explicit curly braces to avoid dangling else.}} + else // Noncompliant {{Add explicit curly braces to avoid dangling else.}} e++; if (a || b) diff --git a/java-checks-test-sources/default/src/main/java/checks/DateFormatWeekYearCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/DateFormatWeekYearCheckSample.java index 188db22143b..7867a44f822 100644 --- a/java-checks-test-sources/default/src/main/java/checks/DateFormatWeekYearCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/DateFormatWeekYearCheckSample.java @@ -22,22 +22,28 @@ class DateFormatWeekYearCheckSample { void quickFixes() throws ParseException { Date date = new SimpleDateFormat("yyyy/MM/dd").parse("2015/12/31"); - String result = new SimpleDateFormat("YYYY/MM/dd").format(date); // Noncompliant [[sc=42;ec=54;quickfixes=qf1]] + String result = new SimpleDateFormat("YYYY/MM/dd").format(date); // Noncompliant [[quickfixes=qf1]] +// ^^^^^^^^^^^^ // fix@qf1 {{Replace year format}} // edit@qf1 [[sc=43;ec=47]] {{yyyy}} - result = new SimpleDateFormat("YYYY").format(date); // Noncompliant [[sc=35;ec=41;quickfixes=qf2]] + result = new SimpleDateFormat("YYYY").format(date); // Noncompliant [[quickfixes=qf2]] +// ^^^^^^ // fix@qf2 {{Replace year format}} // edit@qf2 [[sc=36;ec=40]] {{yyyy}} - result = new SimpleDateFormat(" Y/MM/dd").format(date); // Noncompliant [[sc=35;ec=46;quickfixes=qf3]] + result = new SimpleDateFormat(" Y/MM/dd").format(date); // Noncompliant [[quickfixes=qf3]] +// ^^^^^^^^^^^ // fix@qf3 {{Replace year format}} // edit@qf3 [[sc=38;ec=39]] {{y}} - DateTimeFormatter.ofPattern("YYYY"); // Noncompliant [[sc=33;ec=39;quickfixes=qf4]] + DateTimeFormatter.ofPattern("YYYY"); // Noncompliant [[quickfixes=qf4]] +// ^^^^^^ // fix@qf4 {{Replace year format}} // edit@qf4 [[sc=34;ec=38]] {{yyyy}} - DateTimeFormatter.ofPattern(" Y/MM/dd"); // Noncompliant [[sc=33;ec=44;quickfixes=qf5]] + DateTimeFormatter.ofPattern(" Y/MM/dd"); // Noncompliant [[quickfixes=qf5]] +// ^^^^^^^^^^^ // fix@qf5 {{Replace year format}} // edit@qf5 [[sc=36;ec=37]] {{y}} - DateTimeFormatter.ofPattern("YY"); // Noncompliant [[sc=33;ec=37;quickfixes=qf6]] + DateTimeFormatter.ofPattern("YY"); // Noncompliant [[quickfixes=qf6]] +// ^^^^ // fix@qf6 {{Replace year format}} // edit@qf6 [[sc=34;ec=36]] {{yy}} } @@ -46,9 +52,9 @@ void useSimpleDateFormat() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat(); sdf = new SimpleDateFormat(COMPLIANT_DATE_FORMAT); Date date = new SimpleDateFormat("yyyy/MM/dd").parse("2015/12/31"); - String result = new SimpleDateFormat("YYYY/MM/dd").format(date); // Noncompliant {{Make sure that week Year "YYYY" is expected here instead of Year "yyyy".}} - result = new SimpleDateFormat("YYYY").format(date); // Noncompliant {{Make sure that week Year "YYYY" is expected here instead of Year "yyyy".}} - result = new SimpleDateFormat(" Y/MM/dd").format(date); // Noncompliant {{Make sure that week Year "Y" is expected here instead of Year "y".}} + String result = new SimpleDateFormat("YYYY/MM/dd").format(date); // Noncompliant {{Make sure that week Year "YYYY" is expected here instead of Year "yyyy".}} + result = new SimpleDateFormat("YYYY").format(date); // Noncompliant {{Make sure that week Year "YYYY" is expected here instead of Year "yyyy".}} + result = new SimpleDateFormat(" Y/MM/dd").format(date); // Noncompliant {{Make sure that week Year "Y" is expected here instead of Year "y".}} result = new SimpleDateFormat("yyyy/MM/dd").format(date); //Yields '2015/12/31' as expected result = new SimpleDateFormat("YYYY-ww").format(date); //compliant, 'Week year' is used along with 'Week of year'. result = '2016-01' result = new SimpleDateFormat("ww-YYYY").format(date); //compliant, 'Week year' is used along with 'Week of year'. result = '2016-01' @@ -74,16 +80,26 @@ public void useDateTimeFormatter() { DateTimeFormatter.ofPattern("YYYY-ww", Locale.ENGLISH); // Compliant DateTimeFormatter.ofPattern(" YY/MM/dd ".trim(), Locale.ENGLISH); // Compliant FN patterns from method invocations are not processed - DateTimeFormatter.ofPattern("YYYY"); // Noncompliant [[sc=33;ec=39]] {{Make sure that week Year "YYYY" is expected here instead of Year "yyyy".}} - DateTimeFormatter.ofPattern(" Y/MM/dd"); // Noncompliant [[sc=33;ec=44]] {{Make sure that week Year "Y" is expected here instead of Year "y".}} - DateTimeFormatter.ofPattern("YY"); // Noncompliant [[sc=33;ec=37]] {{Make sure that week Year "YY" is expected here instead of Year "yy".}} - DateTimeFormatter.ofPattern("Y"); // Noncompliant [[sc=33;ec=36]] {{Make sure that week Year "Y" is expected here instead of Year "y".}} - DateTimeFormatter.ofPattern(NON_COMPLIANT_PATTERN); // Noncompliant [[sc=33;ec=54]] {{Make sure that week Year "YYYY" is expected here instead of Year "yyyy".}} - DateTimeFormatter.ofPattern("YYYY", Locale.ENGLISH); // Noncompliant [[sc=33;ec=39]] {{Make sure that week Year "YYYY" is expected here instead of Year "yyyy".}} - DateTimeFormatter.ofPattern(" Y/MM/dd", Locale.ENGLISH); // Noncompliant [[sc=33;ec=44]] {{Make sure that week Year "Y" is expected here instead of Year "y".}} - DateTimeFormatter.ofPattern("YY", Locale.ENGLISH); // Noncompliant [[sc=33;ec=37]] {{Make sure that week Year "YY" is expected here instead of Year "yy".}} - DateTimeFormatter.ofPattern("Y", Locale.ENGLISH); // Noncompliant [[sc=33;ec=36]] {{Make sure that week Year "Y" is expected here instead of Year "y".}} - DateTimeFormatter.ofPattern(NON_COMPLIANT_PATTERN, Locale.ENGLISH); // Noncompliant [[sc=33;ec=54]] {{Make sure that week Year "YYYY" is expected here instead of Year "yyyy".}} + DateTimeFormatter.ofPattern("YYYY"); // Noncompliant {{Make sure that week Year "YYYY" is expected here instead of Year "yyyy".}} +// ^^^^^^ + DateTimeFormatter.ofPattern(" Y/MM/dd"); // Noncompliant {{Make sure that week Year "Y" is expected here instead of Year "y".}} +// ^^^^^^^^^^^ + DateTimeFormatter.ofPattern("YY"); // Noncompliant {{Make sure that week Year "YY" is expected here instead of Year "yy".}} +// ^^^^ + DateTimeFormatter.ofPattern("Y"); // Noncompliant {{Make sure that week Year "Y" is expected here instead of Year "y".}} +// ^^^ + DateTimeFormatter.ofPattern(NON_COMPLIANT_PATTERN); // Noncompliant {{Make sure that week Year "YYYY" is expected here instead of Year "yyyy".}} +// ^^^^^^^^^^^^^^^^^^^^^ + DateTimeFormatter.ofPattern("YYYY", Locale.ENGLISH); // Noncompliant {{Make sure that week Year "YYYY" is expected here instead of Year "yyyy".}} +// ^^^^^^ + DateTimeFormatter.ofPattern(" Y/MM/dd", Locale.ENGLISH); // Noncompliant {{Make sure that week Year "Y" is expected here instead of Year "y".}} +// ^^^^^^^^^^^ + DateTimeFormatter.ofPattern("YY", Locale.ENGLISH); // Noncompliant {{Make sure that week Year "YY" is expected here instead of Year "yy".}} +// ^^^^ + DateTimeFormatter.ofPattern("Y", Locale.ENGLISH); // Noncompliant {{Make sure that week Year "Y" is expected here instead of Year "y".}} +// ^^^ + DateTimeFormatter.ofPattern(NON_COMPLIANT_PATTERN, Locale.ENGLISH); // Noncompliant {{Make sure that week Year "YYYY" is expected here instead of Year "yyyy".}} +// ^^^^^^^^^^^^^^^^^^^^^ } class CompliantChildOfSimpleDateFormat extends SimpleDateFormat { diff --git a/java-checks-test-sources/default/src/main/java/checks/DateTimeFormatterMismatch.java b/java-checks-test-sources/default/src/main/java/checks/DateTimeFormatterMismatch.java index c83fc80d2ee..8f762a285de 100644 --- a/java-checks-test-sources/default/src/main/java/checks/DateTimeFormatterMismatch.java +++ b/java-checks-test-sources/default/src/main/java/checks/DateTimeFormatterMismatch.java @@ -17,31 +17,39 @@ public class DateTimeFormatterMismatch { public void createUsingBuilder() { new DateTimeFormatterBuilder() - .appendValue(ChronoField.YEAR, 4) // Noncompliant [[sc=20;ec=36;secondary=+2]] {{Change this year format to use the week-based year instead (or the week format to Chronofield.ALIGNED_WEEK_OF_YEAR).}} + .appendValue(ChronoField.YEAR, 4) // Noncompliant {{Change this year format to use the week-based year instead (or the week format to Chronofield.ALIGNED_WEEK_OF_YEAR).}} +// ^^^^^^^^^^^^^^^^ .appendLiteral('-') .appendValue(WeekFields.ISO.weekOfWeekBasedYear(), 2) +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< .toFormatter(); new DateTimeFormatterBuilder() .appendValue(ChronoField.MONTH_OF_YEAR, 2) .appendLiteral("-") - .appendValue(ChronoField.YEAR, 4) // Noncompliant [[sc=20;ec=36;secondary=+2]] {{Change this year format to use the week-based year instead (or the week format to Chronofield.ALIGNED_WEEK_OF_YEAR).}} + .appendValue(ChronoField.YEAR, 4) // Noncompliant {{Change this year format to use the week-based year instead (or the week format to Chronofield.ALIGNED_WEEK_OF_YEAR).}} +// ^^^^^^^^^^^^^^^^ .appendLiteral('-') .appendValue(WeekFields.ISO.weekOfWeekBasedYear(), 2) +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< .toFormatter(); new DateTimeFormatterBuilder() .appendLiteral('[') - .appendValue(ChronoField.YEAR_OF_ERA, 4) // Noncompliant [[sc=20;ec=43;secondary=+3]] {{Change this year format to use the week-based year instead (or the week format to Chronofield.ALIGNED_WEEK_OF_YEAR).}} + .appendValue(ChronoField.YEAR_OF_ERA, 4) // Noncompliant {{Change this year format to use the week-based year instead (or the week format to Chronofield.ALIGNED_WEEK_OF_YEAR).}} +// ^^^^^^^^^^^^^^^^^^^^^^^ .appendLiteral(']') .appendLiteral('-') .appendValue(WeekFields.ISO.weekOfWeekBasedYear(), 2) +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< .toFormatter(); new DateTimeFormatterBuilder() - .appendValue(WeekFields.ISO.weekBasedYear(), 4) // Noncompliant [[sc=20;ec=50;secondary=+2]] {{Change this year format to use ChronoField.YEAR instead (or the week format to WeekFields.ISO.weekOfWeekBasedYear()).}} + .appendValue(WeekFields.ISO.weekBasedYear(), 4) // Noncompliant {{Change this year format to use ChronoField.YEAR instead (or the week format to WeekFields.ISO.weekOfWeekBasedYear()).}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .appendLiteral('-') .appendValue(ChronoField.ALIGNED_WEEK_OF_YEAR, 2) +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< .toFormatter(); new DateTimeFormatterBuilder() // Compliant @@ -63,8 +71,10 @@ public void createUsingBuilder() { .toFormatter(); DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder() - .appendValue(ChronoField.YEAR, 4) // Noncompliant [[sc=20;ec=36;secondary=+1]] {{Change this year format to use the week-based year instead (or the week format to Chronofield.ALIGNED_WEEK_OF_YEAR).}} + .appendValue(ChronoField.YEAR, 4) // Noncompliant {{Change this year format to use the week-based year instead (or the week format to Chronofield.ALIGNED_WEEK_OF_YEAR).}} +// ^^^^^^^^^^^^^^^^ .appendValue(WeekFields.ISO.weekOfWeekBasedYear(), 2) +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< .appendLiteral('-'); builder.toFormatter(); @@ -104,38 +114,48 @@ public void createUsingBuilder() { .toFormatter(); new DateTimeFormatterBuilder() - .appendValue(WeekFields.ISO.weekBasedYear(), 4) // Noncompliant [[sc=20;ec=50;secondary=+3]] {{Change this year format to use ChronoField.YEAR instead (or the week format to WeekFields.ISO.weekOfWeekBasedYear()).}} + .appendValue(WeekFields.ISO.weekBasedYear(), 4) // Noncompliant {{Change this year format to use ChronoField.YEAR instead (or the week format to WeekFields.ISO.weekOfWeekBasedYear()).}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .appendValue(ChronoField.YEAR_OF_ERA, 4) .appendLiteral('-') .appendValue(ChronoField.ALIGNED_WEEK_OF_YEAR, 2) +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< .toFormatter(); // Matches on appendValue methods with different parameter list new DateTimeFormatterBuilder() - .appendValue(ChronoField.YEAR) // Noncompliant [[sc=20;ec=36;secondary=+2]] {{Change this year format to use the week-based year instead (or the week format to Chronofield.ALIGNED_WEEK_OF_YEAR).}} + .appendValue(ChronoField.YEAR) // Noncompliant {{Change this year format to use the week-based year instead (or the week format to Chronofield.ALIGNED_WEEK_OF_YEAR).}} +// ^^^^^^^^^^^^^^^^ .appendLiteral('-') .appendValue(WeekFields.ISO.weekOfWeekBasedYear()) +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< .toFormatter(); new DateTimeFormatterBuilder() .appendValue(ChronoField.MONTH_OF_YEAR) .appendLiteral("-") - .appendValue(ChronoField.YEAR) // Noncompliant [[sc=20;ec=36;secondary=+2]] {{Change this year format to use the week-based year instead (or the week format to Chronofield.ALIGNED_WEEK_OF_YEAR).}} + .appendValue(ChronoField.YEAR) // Noncompliant {{Change this year format to use the week-based year instead (or the week format to Chronofield.ALIGNED_WEEK_OF_YEAR).}} +// ^^^^^^^^^^^^^^^^ .appendLiteral('-') .appendValue(WeekFields.ISO.weekOfWeekBasedYear(), 1, 2, SignStyle.NORMAL) +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< .toFormatter(); new DateTimeFormatterBuilder() - .appendValue(ChronoField.YEAR, 2, 4, SignStyle.NORMAL) // Noncompliant [[sc=20;ec=36;secondary=+2]] {{Change this year format to use the week-based year instead (or the week format to Chronofield.ALIGNED_WEEK_OF_YEAR).}} + .appendValue(ChronoField.YEAR, 2, 4, SignStyle.NORMAL) // Noncompliant {{Change this year format to use the week-based year instead (or the week format to Chronofield.ALIGNED_WEEK_OF_YEAR).}} +// ^^^^^^^^^^^^^^^^ .appendLiteral('-') .appendValue(WeekFields.ISO.weekOfWeekBasedYear(), 1, 2, SignStyle.NORMAL) +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< .toFormatter(); new DateTimeFormatterBuilder() .appendValue(ChronoField.MONTH_OF_YEAR, 2, 4, SignStyle.NORMAL) .appendLiteral("-") - .appendValue(ChronoField.YEAR, 4) // Noncompliant [[sc=20;ec=36;secondary=+2]] {{Change this year format to use the week-based year instead (or the week format to Chronofield.ALIGNED_WEEK_OF_YEAR).}} + .appendValue(ChronoField.YEAR, 4) // Noncompliant {{Change this year format to use the week-based year instead (or the week format to Chronofield.ALIGNED_WEEK_OF_YEAR).}} +// ^^^^^^^^^^^^^^^^ .appendLiteral('-') .appendValue(WeekFields.ISO.weekOfWeekBasedYear(), 1, 2, SignStyle.NORMAL) +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< .toFormatter(); new DateTimeFormatterBuilder() diff --git a/java-checks-test-sources/default/src/main/java/checks/DateUtilsTruncateCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/DateUtilsTruncateCheckSample.java index 8d0b70fe34a..6eec36a5b86 100644 --- a/java-checks-test-sources/default/src/main/java/checks/DateUtilsTruncateCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/DateUtilsTruncateCheckSample.java @@ -8,12 +8,13 @@ class DateUtilsTruncateCheckSample { public void foo(Date date, Calendar calendar, Object object, int field) { - DateUtils.truncate(date, field); // Noncompliant [[sc=15;ec=23]] {{Use "ZonedDateTime.truncatedTo" instead.}} - DateUtils.truncate(calendar, field); // Noncompliant - DateUtils.truncate(object, field); // Noncompliant - truncate(date, field); // Noncompliant - truncate(calendar, field); // Noncompliant - truncate(object, field); // Noncompliant + DateUtils.truncate(date, field); // Noncompliant {{Use "ZonedDateTime.truncatedTo" instead.}} +// ^^^^^^^^ + DateUtils.truncate(calendar, field); // Noncompliant + DateUtils.truncate(object, field); // Noncompliant + truncate(date, field); // Noncompliant + truncate(calendar, field); // Noncompliant + truncate(object, field); // Noncompliant } } diff --git a/java-checks-test-sources/default/src/main/java/checks/DateUtilsTruncateCheck_no_version.java b/java-checks-test-sources/default/src/main/java/checks/DateUtilsTruncateCheck_no_version.java index bd9b2061729..31b4091570c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/DateUtilsTruncateCheck_no_version.java +++ b/java-checks-test-sources/default/src/main/java/checks/DateUtilsTruncateCheck_no_version.java @@ -8,12 +8,12 @@ class DateUtilsTruncateCheck_no_version { public void foo(Date date, Calendar calendar, Object object, int field) { - DateUtils.truncate(date, field); // Noncompliant {{Use "ZonedDateTime.truncatedTo" instead. (sonar.java.source not set. Assuming 8 or greater.)}} - DateUtils.truncate(calendar, field); // Noncompliant - DateUtils.truncate(object, field); // Noncompliant - truncate(date, field); // Noncompliant - truncate(calendar, field); // Noncompliant - truncate(object, field); // Noncompliant + DateUtils.truncate(date, field); // Noncompliant {{Use "ZonedDateTime.truncatedTo" instead. (sonar.java.source not set. Assuming 8 or greater.)}} + DateUtils.truncate(calendar, field); // Noncompliant + DateUtils.truncate(object, field); // Noncompliant + truncate(date, field); // Noncompliant + truncate(calendar, field); // Noncompliant + truncate(object, field); // Noncompliant } } diff --git a/java-checks-test-sources/default/src/main/java/checks/DeadStoreCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/DeadStoreCheckSample.java index c8b268ac648..5edb93d2eec 100644 --- a/java-checks-test-sources/default/src/main/java/checks/DeadStoreCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/DeadStoreCheckSample.java @@ -14,15 +14,18 @@ int foo(int u) { int x = 0;// Compliant - default value x = 3; // Noncompliant x = 4; - int y = x + 1; // Noncompliant {{Remove this useless assignment to local variable "y".}} [[sc=11;ec=18]] - x = 2; // Noncompliant {{Remove this useless assignment to local variable "x".}} [[sc=7;ec=10]] + int y = x + 1; // Noncompliant {{Remove this useless assignment to local variable "y".}} +// ^^^^^^^ + x = 2; // Noncompliant {{Remove this useless assignment to local variable "x".}} +// ^^^ x = 3; y = 2; foo(y); foo(x); Object a = new Object(); System.out.println(a); - a = null; // Noncompliant [[sc=7;ec=13]] + a = null; // Noncompliant +// ^^^^^^ return 0; } @@ -127,7 +130,8 @@ int fun() { int increment_operator() { int i = 0; int b = 12; - ++b; // Noncompliant [[sc=5;ec=8]] + ++b; // Noncompliant +// ^^^ int c = 0; foo(++c); // compliant not last element of block int j = -1; @@ -144,13 +148,15 @@ int increment_operator() { void parenthesis_identifier_in_assignement() { int i = 0; System.out.println(i); - (i) = 12; // Noncompliant [[sc=9;ec=13]] + (i) = 12; // Noncompliant +// ^^^^ } int parenthesis_identifier_in_postfix_increment() { int j = 0; for (int i = 0; i < 10; ++j, ++i) ; int b = 0; - return (b)++; // Noncompliant [[sc=12;ec=17]] + return (b)++; // Noncompliant +// ^^^^^ } void foo() { int i = 0; @@ -234,8 +240,8 @@ private void foo3(int y) { class DeadStoreCheckSampleStuff { void foo(boolean b1, boolean b2) { boolean x = false; // Compliant - x = b1 && b2; // Noncompliant - ((x)) = b1 && b2; // Noncompliant + x = b1 && b2; // Noncompliant + ((x)) = b1 && b2; // Noncompliant } void assertStatement(boolean x) { @@ -250,14 +256,14 @@ class DeadStoreCheckSampleNoIssueOnInitializers { // no issue if variable initializer is 'true' or 'false' boolean testBoolean(boolean arg0) { boolean b1 = true; // Compliant - b1 = false; // Noncompliant + b1 = false; // Noncompliant b1 = arg0; boolean b2 = false; // Compliant - b2 = true; // Noncompliant + b2 = true; // Noncompliant b2 = arg0; - boolean b3 = arg0; // Noncompliant + boolean b3 = arg0; // Noncompliant b3 = arg0; return b1 && b2 && b3; @@ -267,7 +273,7 @@ boolean testBoolean(boolean arg0) { Object testNull(boolean b, Object o) { Object o1 = null; // Compliant o1 = new Object(); // Noncompliant - o1 = null; // Noncompliant + o1 = null; // Noncompliant o1 = o; Object o2 = o; // Noncompliant @@ -279,7 +285,7 @@ Object testNull(boolean b, Object o) { //no issue if initializer is the empty String String testNull(String s) { String s1 = ""; // Compliant - s1 = "yolo"; // Noncompliant + s1 = "yolo"; // Noncompliant s1 = "hello"; String s2 = "world"; // Noncompliant @@ -291,20 +297,20 @@ String testNull(String s) { // no issue if variable initializer is '-1', '0', or '1' int testIntLiterals() { - int a = +42; // Noncompliant + int a = +42; // Noncompliant int b = (0); // Compliant - b = -1; // Noncompliant - Only taken into consideration when used in initializer - b = 0; // Noncompliant - b = 1; // Noncompliant + b = -1; // Noncompliant + b = 0; // Noncompliant + b = 1; // Noncompliant int c = +1; // Compliant int d = (-1); // Compliant int e = -1; // Compliant // Only int literals are excluded - long myLong = -1L; // Noncompliant + long myLong = -1L; // Noncompliant double myDouble = -1.0d; // Noncompliant - float myFloat = -1.0f; // Noncompliant + float myFloat = -1.0f; // Noncompliant short myShort = -1; // Compliant byte myByte = 1; //Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/DefaultEncodingUsageCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/DefaultEncodingUsageCheckSample.java index 4f1080c645c..c6f45c06cd1 100644 --- a/java-checks-test-sources/default/src/main/java/checks/DefaultEncodingUsageCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/DefaultEncodingUsageCheckSample.java @@ -28,7 +28,8 @@ void myMethod(byte[] bytes, java.io.File file, OutputStream outputStream, java.i "".getBytes(0, 0, bytes, 0); // Noncompliant {{Remove this use of "getBytes".}} new java.io.ByteArrayOutputStream().toString(); // Noncompliant new FileReader("fileName"); // Noncompliant - new FileReader(file); // Noncompliant [[sc=9;ec=19]] + new FileReader(file); // Noncompliant +// ^^^^^^^^^^ new FileReader(new java.io.FileDescriptor()); // Noncompliant new FileWriter(file); // Noncompliant new FileWriter(file, true); // Noncompliant @@ -52,7 +53,8 @@ void myMethod(byte[] bytes, java.io.File file, OutputStream outputStream, java.i new Scanner(file); // Noncompliant new java.util.Scanner(new java.io.FileInputStream("")); // Noncompliant FileReader reader1 = null; // Compliant - FileReader reader2 = new FileReader(file); // Noncompliant [[sc=30;ec=40]] {{Remove this use of constructor "FileReader(File)".}} + FileReader reader2 = new FileReader(file); // Noncompliant {{Remove this use of constructor "FileReader(File)".}} +// ^^^^^^^^^^ FileReader reader3 = new FileReader(file, StandardCharsets.UTF_8); // Compliant FileReader reader4 = new FileReader(fileDescriptor); // Noncompliant {{Remove this use of constructor "FileReader(FileDescriptor)".}} FileReader reader5 = new FileReader("filename"); // Noncompliant {{Remove this use of constructor "FileReader(String)".}} @@ -60,7 +62,8 @@ void myMethod(byte[] bytes, java.io.File file, OutputStream outputStream, java.i java.io.Reader reader7 = fileReader(); // Compliant FileWriter writer1 = null; // Compliant java.io.Writer writer2 = fileWriter(); // Compliant - FileWriter writer3 = new FileWriter(file); // Noncompliant [[sc=30;ec=40]] {{Remove this use of constructor "FileWriter(File)".}} + FileWriter writer3 = new FileWriter(file); // Noncompliant {{Remove this use of constructor "FileWriter(File)".}} +// ^^^^^^^^^^ FileWriter writer4 = new FileWriter(fileDescriptor); // Noncompliant {{Remove this use of constructor "FileWriter(FileDescriptor)".}} FileWriter writer5 = new FileWriter(file, true); // Noncompliant {{Remove this use of constructor "FileWriter(File,boolean)".}} FileWriter writer6 = new FileWriter(file, StandardCharsets.UTF_8); // Compliant @@ -107,7 +110,8 @@ void commons_io(Reader reader, Writer writer, InputStream input, OutputStream ou } void commons_fileutils(File file, CharSequence charSequence) throws IOException { - FileUtils.readFileToString(file); // Noncompliant [[sc=15;ec=31]] {{Remove this use of "readFileToString".}} + FileUtils.readFileToString(file); // Noncompliant {{Remove this use of "readFileToString".}} +// ^^^^^^^^^^^^^^^^ FileUtils.readLines(file); // Noncompliant FileUtils.write(file, charSequence); // Noncompliant FileUtils.write(file, charSequence, false); // Noncompliant @@ -117,7 +121,8 @@ void commons_fileutils(File file, CharSequence charSequence) throws IOException void commons_io_with_null(Reader reader, Writer writer, InputStream input, OutputStream output, String s, CharSequence charSequence, byte[] bytes, java.net.URI uri, java.net.URL url, char[] chars, StringBuffer buffer, Collection lines) throws IOException { IOUtils.copy(input, writer, (String) null); // Noncompliant - IOUtils.copy(input, writer, ((String) (((null))))); // Noncompliant [[sc=33;ec=54]] {{Replace this "null" with actual charset.}} + IOUtils.copy(input, writer, ((String) (((null))))); // Noncompliant {{Replace this "null" with actual charset.}} +// ^^^^^^^^^^^^^^^^^^^^^ IOUtils.copy(reader, output, (String) null); // Noncompliant IOUtils.readLines(input, (String) null); // Noncompliant IOUtils.toByteArray(reader, (String) null); // Noncompliant @@ -136,7 +141,8 @@ void commons_io_with_null(Reader reader, Writer writer, InputStream input, Outpu } void commons_fileutils_with_null(File file, CharSequence charSequence) throws IOException { - FileUtils.readFileToString(file, (java.nio.charset.Charset) null); // Noncompliant [[sc=38;ec=69]] {{Replace this "null" with actual charset.}} + FileUtils.readFileToString(file, (java.nio.charset.Charset) null); // Noncompliant {{Replace this "null" with actual charset.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ FileUtils.readLines(file, (java.nio.charset.Charset) null); // Noncompliant FileUtils.write(file, charSequence, (java.nio.charset.Charset) null); // Noncompliant FileUtils.write(file, charSequence, (java.nio.charset.Charset) null, false); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/DefaultInitializedFieldCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/DefaultInitializedFieldCheckSample.java index 401de3aae21..303bfddbc39 100644 --- a/java-checks-test-sources/default/src/main/java/checks/DefaultInitializedFieldCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/DefaultInitializedFieldCheckSample.java @@ -26,7 +26,8 @@ class DefaultInitializedFieldCheckSample { double d2; double d3 = 0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001; // Compliant, not 0 char c = 0; // Noncompliant {{Remove this initialization to "0", the compiler will do that for you.}} - char c1 = '\u0000'; // Noncompliant [[sc=13;ec=21]] {{Remove this initialization to "'\u0000'", the compiler will do that for you.}} + char c1 = '\u0000'; // Noncompliant {{Remove this initialization to "'\u0000'", the compiler will do that for you.}} +// ^^^^^^^^ char c2 = '0'; char c3; char ch4 = '\0'; // Noncompliant {{Remove this initialization to "'\0'", the compiler will do that for you.}} @@ -38,7 +39,7 @@ class DefaultInitializedFieldCheckSample { String str = null; // Noncompliant {{Remove this initialization to "null", the compiler will do that for you.}} String str1 = "a"; String str2; - Integer int1 = null; // Noncompliant {{Remove this initialization to "null", the compiler will do that for you.}} + Integer int1 = null; // Noncompliant {{Remove this initialization to "null", the compiler will do that for you.}} Integer int2 = 0; byte castedByte = (byte) 0; // Noncompliant {{Remove this initialization to "0", the compiler will do that for you.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/DeprecatedArgumentsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/DeprecatedArgumentsCheckSample.java index 66bf0e8ea22..3d2b60d442b 100644 --- a/java-checks-test-sources/default/src/main/java/checks/DeprecatedArgumentsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/DeprecatedArgumentsCheckSample.java @@ -2,13 +2,15 @@ class DeprecatedArgumentsCheckSample { - @Deprecated // Noncompliant [[sc=3;ec=14]] {{Add 'since' and/or 'forRemoval' arguments to the @Deprecated annotation.}} + @Deprecated // Noncompliant {{Add 'since' and/or 'forRemoval' arguments to the @Deprecated annotation.}} +//^^^^^^^^^^^ public int lim; /** * @deprecated */ - @Deprecated // Noncompliant [[sc=3;ec=14]] {{Add 'since' and/or 'forRemoval' arguments to the @Deprecated annotation.}} + @Deprecated // Noncompliant {{Add 'since' and/or 'forRemoval' arguments to the @Deprecated annotation.}} +//^^^^^^^^^^^ public int foo; /** diff --git a/java-checks-test-sources/default/src/main/java/checks/DiamondOperatorCheck_java_7.java b/java-checks-test-sources/default/src/main/java/checks/DiamondOperatorCheck_java_7.java index f3cac6500b3..1cca7647a24 100644 --- a/java-checks-test-sources/default/src/main/java/checks/DiamondOperatorCheck_java_7.java +++ b/java-checks-test-sources/default/src/main/java/checks/DiamondOperatorCheck_java_7.java @@ -8,29 +8,36 @@ class DiamondOperatorCheck_java_7 { List myList1 = new ArrayList<>(); // Compliant - List myList2 = new ArrayList(); // Noncompliant [[sc=39;ec=47]] {{Replace the type specification in this constructor call with the diamond operator ("<>").}} + List myList2 = new ArrayList(); // Noncompliant {{Replace the type specification in this constructor call with the diamond operator ("<>").}} +// ^^^^^^^^ void foo() { List myList; myList = new ArrayList<>(); // Compliant - myList = new ArrayList(); // Noncompliant [[sc=27;ec=35]] + myList = new ArrayList(); // Noncompliant +// ^^^^^^^^ List strings1 = new ArrayList<>(); // Compliant - List strings2 = new ArrayList(); // Noncompliant [[sc=42;ec=50]] + List strings2 = new ArrayList(); // Noncompliant +// ^^^^^^^^ Map> map1 = new HashMap<>(); // Compliant - Map> map2 = new HashMap>(); // Noncompliant [[sc=49;ec=71]] + Map> map2 = new HashMap>(); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^ List myOtherList = new ArrayList(); // Compliant new DiamondOperatorCheck_java_7().myList1 = new ArrayList<>(); // Compliant - new DiamondOperatorCheck_java_7().myList1 = new ArrayList(); // Noncompliant [[sc=62;ec=70]] + new DiamondOperatorCheck_java_7().myList1 = new ArrayList(); // Noncompliant +// ^^^^^^^^ List[] myArrayOfList = new List[10]; myArrayOfList[0] = new ArrayList<>(); // Compliant - myArrayOfList[1] = new ArrayList(); // Noncompliant [[sc=37;ec=45]] + myArrayOfList[1] = new ArrayList(); // Noncompliant +// ^^^^^^^^ new ArrayList().add(new Object()); // Compliant - ((List) new ArrayList()).isEmpty(); // Noncompliant [[sc=34;ec=42]] + ((List) new ArrayList()).isEmpty(); // Noncompliant +// ^^^^^^^^ ((List) new ArrayList<>()).isEmpty(); // Compliant Iterator iterator = new Iterator() { // Compliant - anonymous classes requires to be typed @@ -51,6 +58,7 @@ List qix(boolean test) { if (test) { return new ArrayList<>(); // Compliant } - return new ArrayList(); // Noncompliant [[sc=25;ec=33]] + return new ArrayList(); // Noncompliant +// ^^^^^^^^ } } diff --git a/java-checks-test-sources/default/src/main/java/checks/DiamondOperatorCheck_java_8.java b/java-checks-test-sources/default/src/main/java/checks/DiamondOperatorCheck_java_8.java index 43182ef40fc..03274c67441 100644 --- a/java-checks-test-sources/default/src/main/java/checks/DiamondOperatorCheck_java_8.java +++ b/java-checks-test-sources/default/src/main/java/checks/DiamondOperatorCheck_java_8.java @@ -10,29 +10,36 @@ class DiamondOperatorCheck_java_8 { List myList1 = new ArrayList<>(); // Compliant - List myList2 = new ArrayList(); // Noncompliant [[sc=39;ec=47]] {{Replace the type specification in this constructor call with the diamond operator ("<>").}} + List myList2 = new ArrayList(); // Noncompliant {{Replace the type specification in this constructor call with the diamond operator ("<>").}} +// ^^^^^^^^ void foo() { List myList; myList = new ArrayList<>(); // Compliant - myList = new ArrayList(); // Noncompliant [[sc=27;ec=35]] + myList = new ArrayList(); // Noncompliant +// ^^^^^^^^ List strings1 = new ArrayList<>(); // Compliant - List strings2 = new ArrayList(); // Noncompliant [[sc=42;ec=50]] + List strings2 = new ArrayList(); // Noncompliant +// ^^^^^^^^ Map> map1 = new HashMap<>(); // Compliant - Map> map2 = new HashMap>(); // Noncompliant [[sc=49;ec=71]] + Map> map2 = new HashMap>(); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^ List myOtherList = new ArrayList(); // Compliant new DiamondOperatorCheck_java_8().myList1 = new ArrayList<>(); // Compliant - new DiamondOperatorCheck_java_8().myList1 = new ArrayList(); // Noncompliant [[sc=62;ec=70]] + new DiamondOperatorCheck_java_8().myList1 = new ArrayList(); // Noncompliant +// ^^^^^^^^ List[] myArrayOfList = new List[10]; myArrayOfList[0] = new ArrayList<>(); // Compliant - myArrayOfList[1] = new ArrayList(); // Noncompliant [[sc=37;ec=45]] + myArrayOfList[1] = new ArrayList(); // Noncompliant +// ^^^^^^^^ new ArrayList().add(new Object()); // Compliant - ((List) new ArrayList()).isEmpty(); // Noncompliant [[sc=34;ec=42]] + ((List) new ArrayList()).isEmpty(); // Noncompliant +// ^^^^^^^^ ((List) new ArrayList<>()).isEmpty(); // Compliant Iterator iterator = new Iterator() { // Compliant - anonymous classes requires to be typed @@ -47,13 +54,15 @@ void foo() { List qix(boolean test) { List myList = test ? new ArrayList<>() : // Compliant - new ArrayList(); // Noncompliant [[sc=22;ec=30]] + new ArrayList(); // Noncompliant +// ^^^^^^^^ myList = new ArrayList<>(test ? new ArrayList<>() : new ArrayList(5)); // Compliant if (test) { return new ArrayList<>(); // Compliant } - return new ArrayList(); // Noncompliant [[sc=25;ec=33]] + return new ArrayList(); // Noncompliant +// ^^^^^^^^ } public void assignmentOnMethodInvocation() { @@ -72,14 +81,17 @@ static class A { public A(X x) { } public void tst() { - bar(0, new ArrayList()); // Noncompliant [[sc=27;ec=35]] + bar(0, new ArrayList()); // Noncompliant +// ^^^^^^^^ foo(0, new ArrayList()); // Compliant qix(new ArrayList()); // Compliant gul(new ArrayList()); // Compliant A> als = - new A>( // Noncompliant [[sc=14;ec=28]] - new ArrayList()); // Noncompliant [[sc=24;ec=32]] + new A>( // Noncompliant +// ^^^^^^^^^^^^^^ + new ArrayList()); // Noncompliant +// ^^^^^^^^ List values = Arrays.asList("Stop", "pointing", "fingers", "steve"); new ArrayList(values); // FN - based on type inference diff --git a/java-checks-test-sources/default/src/main/java/checks/DiamondOperatorCheck_no_version.java b/java-checks-test-sources/default/src/main/java/checks/DiamondOperatorCheck_no_version.java index 61e56f539fa..3815328be34 100644 --- a/java-checks-test-sources/default/src/main/java/checks/DiamondOperatorCheck_no_version.java +++ b/java-checks-test-sources/default/src/main/java/checks/DiamondOperatorCheck_no_version.java @@ -8,37 +8,45 @@ class DiamonOperatorCheck_no_version { List myList1 = new ArrayList<>(); // Compliant - List myList2 = new ArrayList(); // Noncompliant [[sc=39;ec=47;quickfixes=qf1]] {{Replace the type specification in this constructor call with the diamond operator ("<>"). (sonar.java.source not set. Assuming 7 or greater.)}} + List myList2 = new ArrayList(); // Noncompliant {{Replace the type specification in this constructor call with the diamond operator ("<>"). (sonar.java.source not set. Assuming 7 or greater.)}} [[quickfixes=qf1]] +// ^^^^^^^^ // fix@qf1 {{Replace with <>}} // edit@qf1 [[sc=39;ec=47]] {{<>}} - List myList3 = new ArrayList< // Noncompliant [[sc=39;el=+2;ec=6;quickfixes=qf2]] + List myList3 = new ArrayList< // Noncompliant [[quickfixes=qf2]] +//^[sc=39;ec=5;el=+3] Object >(); // fix@qf2 {{Replace with <>}} - // edit@qf2 [[sc=39;el=+2;ec=6]] {{<>}} + // edit@qf2 [[sc=39;el=+3;ec=6]] {{<>}} void foo() { List myList; myList = new ArrayList<>(); // Compliant - myList = new ArrayList(); // Noncompliant [[sc=27;ec=35]] + myList = new ArrayList(); // Noncompliant +// ^^^^^^^^ List strings1 = new ArrayList<>(); // Compliant - List strings2 = new ArrayList(); // Noncompliant [[sc=42;ec=50]] + List strings2 = new ArrayList(); // Noncompliant +// ^^^^^^^^ Map> map1 = new HashMap<>(); // Compliant - Map> map2 = new HashMap>(); // Noncompliant [[sc=49;ec=71]] + Map> map2 = new HashMap>(); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^ List myOtherList = new ArrayList(); // Compliant new DiamonOperatorCheck_no_version().myList1 = new ArrayList<>(); // Compliant - new DiamonOperatorCheck_no_version().myList1 = new ArrayList(); // Noncompliant [[sc=65;ec=73]] + new DiamonOperatorCheck_no_version().myList1 = new ArrayList(); // Noncompliant +// ^^^^^^^^ List[] myArrayOfList = new List[10]; myArrayOfList[0] = new ArrayList<>(); // Compliant - myArrayOfList[1] = new ArrayList(); // Noncompliant [[sc=37;ec=45]] + myArrayOfList[1] = new ArrayList(); // Noncompliant +// ^^^^^^^^ new ArrayList().add(new Object()); // Compliant - ((List) new ArrayList()).isEmpty(); // Noncompliant [[sc=34;ec=42]] + ((List) new ArrayList()).isEmpty(); // Noncompliant +// ^^^^^^^^ ((List) new ArrayList<>()).isEmpty(); // Compliant Iterator iterator = new Iterator() { // Compliant - anonymous classes requires to be typed @@ -53,12 +61,14 @@ void foo() { List qix(boolean test) { List myList = test ? new ArrayList<>() : // Compliant - new ArrayList(); // Noncompliant [[sc=22;ec=30]] + new ArrayList(); // Noncompliant +// ^^^^^^^^ myList = new ArrayList<>(test ? new ArrayList<>() : new ArrayList(5)); // Compliant if (test) { return new ArrayList<>(); // Compliant } - return new ArrayList(); // Noncompliant [[sc=25;ec=33]] + return new ArrayList(); // Noncompliant +// ^^^^^^^^ } } diff --git a/java-checks-test-sources/default/src/main/java/checks/DisallowedConstructorCheck/detected_all_overload.java b/java-checks-test-sources/default/src/main/java/checks/DisallowedConstructorCheck/detected_all_overload.java index a522d7f3963..71935c18dc4 100644 --- a/java-checks-test-sources/default/src/main/java/checks/DisallowedConstructorCheck/detected_all_overload.java +++ b/java-checks-test-sources/default/src/main/java/checks/DisallowedConstructorCheck/detected_all_overload.java @@ -6,7 +6,8 @@ class A { A(){} void plop() { - new A(1,2,new String[]{"1"}); // Noncompliant [[sc=8;ec=9]] {{Remove this forbidden initialization}} + new A(1,2,new String[]{"1"}); // Noncompliant {{Remove this forbidden initialization}} +// ^ new A(); // Noncompliant } } diff --git a/java-checks-test-sources/default/src/main/java/checks/DisallowedThreadGroupCheck.java b/java-checks-test-sources/default/src/main/java/checks/DisallowedThreadGroupCheck.java index 713dfff0539..07bbbc75cf1 100644 --- a/java-checks-test-sources/default/src/main/java/checks/DisallowedThreadGroupCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/DisallowedThreadGroupCheck.java @@ -9,9 +9,10 @@ abstract class DisallowedThreadGroupCheck void foo( Object o, - ThreadGroup threadGroup) { // Noncompliant + ThreadGroup threadGroup) { // Noncompliant - ThreadGroup tg = // Noncompliant [[sc=5;ec=16]] {{Remove this use of "ThreadGroup". Prefer the use of "ThreadPoolExecutor".}} + ThreadGroup tg = // Noncompliant {{Remove this use of "ThreadGroup". Prefer the use of "ThreadPoolExecutor".}} +// ^^^^^^^^^^^ new ThreadGroup("DisallowedThreadGroupCheck"); // Compliant tg.activeCount(); // Compliant - not following method invocation, only declarations of ThreadGroup diff --git a/java-checks-test-sources/default/src/main/java/checks/DoubleBraceInitializationCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/DoubleBraceInitializationCheckSample.java index 527e85ed8ef..ea5eeedb78c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/DoubleBraceInitializationCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/DoubleBraceInitializationCheckSample.java @@ -4,13 +4,15 @@ import java.util.Map; class DoubleBraceInitializationCheckSample { - Map source = new HashMap() {{ // Noncompliant [[sc=46;el=+3;ec=5]] {{Use another way to initialize this instance.}} + Map source = new HashMap() {{ // Noncompliant {{Use another way to initialize this instance.}} +//^[sc=46;ec=4;sl=7;el=11] put("firstName", "John"); put("lastName", "Smith"); }}; DoubleBraceInitializationCheckSampleB b0 = new DoubleBraceInitializationCheckSampleB(); - DoubleBraceInitializationCheckSampleB b1 = new DoubleBraceInitializationCheckSampleB() {{ bar("hello"); }}; // Noncompliant [[sc=90;ec=109]] {{Use another way to initialize this instance.}} + DoubleBraceInitializationCheckSampleB b1 = new DoubleBraceInitializationCheckSampleB() {{ bar("hello"); }}; // Noncompliant {{Use another way to initialize this instance.}} +// ^^^^^^^^^^^^^^^^^^^ DoubleBraceInitializationCheckSampleB b2 = new DoubleBraceInitializationCheckSampleB() {{ field = -1; } diff --git a/java-checks-test-sources/default/src/main/java/checks/DoubleCheckedLockingAssignment.java b/java-checks-test-sources/default/src/main/java/checks/DoubleCheckedLockingAssignment.java index b9bbce1912c..64299ea9e5a 100644 --- a/java-checks-test-sources/default/src/main/java/checks/DoubleCheckedLockingAssignment.java +++ b/java-checks-test-sources/default/src/main/java/checks/DoubleCheckedLockingAssignment.java @@ -11,9 +11,12 @@ public List getStrings() { if (strings == null) { synchronized (this) { if (strings == null) { - strings = new ArrayList<>(); // Noncompliant [[sc=11;ec=38;secondary=15,16]] {{Fully initialize "strings" before assigning it.}} + strings = new ArrayList<>(); // Noncompliant {{Fully initialize "strings" before assigning it.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ strings.add("Hello"); +// ^^^^^^^< strings.add("World"); +// ^^^^^^^< } } } @@ -24,10 +27,13 @@ public List getStringsBis() { if (null == strings) { synchronized (this) { if (null == this.strings) { - strings = new ArrayList<>(); // Noncompliant [[sc=11;ec=38;secondary=28,30]] {{Fully initialize "strings" before assigning it.}} + strings = new ArrayList<>(); // Noncompliant {{Fully initialize "strings" before assigning it.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ strings.add("Hello"); +// ^^^^^^^< System.out.println(); strings.add("World"); +// ^^^^^^^< } } } diff --git a/java-checks-test-sources/default/src/main/java/checks/DoubleCheckedLockingCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/DoubleCheckedLockingCheckSample.java index 211f1321e2b..b1e85c62d20 100644 --- a/java-checks-test-sources/default/src/main/java/checks/DoubleCheckedLockingCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/DoubleCheckedLockingCheckSample.java @@ -4,8 +4,11 @@ class DoubleCheckedLockingCheckSample { public Helper classicCase() { if (helper == null) - synchronized (this) { // Noncompliant [[sc=7;ec=19;secondary=6,8]] {{Remove this dangerous instance of double-checked locking.}} +// ^^^^^^^^^^^^^^> + synchronized (this) { // Noncompliant {{Remove this dangerous instance of double-checked locking.}} +// ^^^^^^^^^^^^ if (helper == null) +// ^^^^^^^^^^^^^^< helper = new Helper(); } return helper; @@ -23,8 +26,11 @@ public Helper fieldIsNotActuallyInitializedHere() { public Helper memberSelectCondition() { if (this.helper == null) - synchronized (this) { // Noncompliant [[sc=7;ec=19;secondary=25,27]] {{Remove this dangerous instance of double-checked locking.}} +// ^^^^^^^^^^^^^^^^^^^> + synchronized (this) { // Noncompliant {{Remove this dangerous instance of double-checked locking.}} +// ^^^^^^^^^^^^ if (helper == null) +// ^^^^^^^^^^^^^^< this.helper = new Helper(); } return helper; @@ -32,8 +38,11 @@ public Helper memberSelectCondition() { public Helper memberSelectCondition2() { if (helper == null) - synchronized (this) { // Noncompliant [[sc=7;ec=19;secondary=34,36]] {{Remove this dangerous instance of double-checked locking.}} +// ^^^^^^^^^^^^^^> + synchronized (this) { // Noncompliant {{Remove this dangerous instance of double-checked locking.}} +// ^^^^^^^^^^^^ if (this.helper == null) +// ^^^^^^^^^^^^^^^^^^^< this.helper = new Helper(); } return helper; @@ -41,8 +50,11 @@ public Helper memberSelectCondition2() { public Helper memberSelectCondition3() { if (this.helper == null) - synchronized (this) { // Noncompliant [[sc=7;ec=19;secondary=43,45]] {{Remove this dangerous instance of double-checked locking.}} +// ^^^^^^^^^^^^^^^^^^^> + synchronized (this) { // Noncompliant {{Remove this dangerous instance of double-checked locking.}} +// ^^^^^^^^^^^^ if (this.helper == null) +// ^^^^^^^^^^^^^^^^^^^< this.helper = new Helper(); } return helper; @@ -50,8 +62,11 @@ public Helper memberSelectCondition3() { public Helper invertedConditions() { if (null == this.helper) - synchronized (this) { // Noncompliant [[sc=7;ec=19;secondary=52,54]] {{Remove this dangerous instance of double-checked locking.}} +// ^^^^^^^^^^^^^^^^^^^> + synchronized (this) { // Noncompliant {{Remove this dangerous instance of double-checked locking.}} +// ^^^^^^^^^^^^ if (null == helper) +// ^^^^^^^^^^^^^^< this.helper = new Helper(); } return helper; @@ -59,8 +74,11 @@ public Helper invertedConditions() { public Helper intializationViaMemberSelect2() { if (helper == null) - synchronized (this) { // Noncompliant [[sc=7;ec=19;secondary=61,63]] {{Remove this dangerous instance of double-checked locking.}} +// ^^^^^^^^^^^^^^> + synchronized (this) { // Noncompliant {{Remove this dangerous instance of double-checked locking.}} +// ^^^^^^^^^^^^ if (helper == null) +// ^^^^^^^^^^^^^^< this.helper = new Helper(); } return helper; @@ -71,8 +89,11 @@ public Helper intializationViaMemberSelect2() { public HelperInterface interfaceHelper() { if (helperInterface == null) - synchronized (this) { // Noncompliant [[sc=7;ec=19;secondary=73,75]] {{Remove this dangerous instance of double-checked locking.}} +// ^^^^^^^^^^^^^^^^^^^^^^^> + synchronized (this) { // Noncompliant {{Remove this dangerous instance of double-checked locking.}} +// ^^^^^^^^^^^^ if (helperInterface == null) +// ^^^^^^^^^^^^^^^^^^^^^^^< this.helperInterface = new Helper(); } return helperInterface; @@ -80,8 +101,11 @@ public HelperInterface interfaceHelper() { public AbstractHelper abstractHelper() { if (abstractHelper == null) - synchronized (this) { // Noncompliant [[sc=7;ec=19;secondary=82,84]] {{Remove this dangerous instance of double-checked locking.}} +// ^^^^^^^^^^^^^^^^^^^^^^> + synchronized (this) { // Noncompliant {{Remove this dangerous instance of double-checked locking.}} +// ^^^^^^^^^^^^ if (abstractHelper == null) +// ^^^^^^^^^^^^^^^^^^^^^^< this.abstractHelper = new Helper(); } return abstractHelper; @@ -114,13 +138,16 @@ class DoubleCheckedLockingCheckSampleNestedIfs { public Helper unrelatedNestedIfs() { if (null == helper) { +// ^^^^^^^^^^^^^^> if (sunIsUp) { doSomething(); } - synchronized (this) { // Noncompliant [[sc=7;ec=19;secondary=116,123]] {{Remove this dangerous instance of double-checked locking.}} + synchronized (this) { // Noncompliant {{Remove this dangerous instance of double-checked locking.}} +// ^^^^^^^^^^^^ if (sunIsDown) { doSomethingElse(); if (null == helper) +// ^^^^^^^^^^^^^^< helper = new Helper(); } } diff --git a/java-checks-test-sources/default/src/main/java/checks/DuplicateConditionIfElseIfCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/DuplicateConditionIfElseIfCheckSample.java index 6c2efeed938..98b0f5546c6 100644 --- a/java-checks-test-sources/default/src/main/java/checks/DuplicateConditionIfElseIfCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/DuplicateConditionIfElseIfCheckSample.java @@ -3,17 +3,23 @@ class DuplicateConditionIfElseIfCheckSample { void example(boolean condition1, boolean condition2, boolean condition3, int i1, int i2) { if (condition1) { - } else if (condition1) { // Noncompliant [[sc=16;ec=26;secondary=-1]] {{This branch can not be reached because the condition duplicates a previous condition in the same sequence of "if/else if" statements}} +// ^^^^^^^^^^> + } else if (condition1) { // Noncompliant {{This branch can not be reached because the condition duplicates a previous condition in the same sequence of "if/else if" statements}} +// ^^^^^^^^^^ } if (condition2) { } else if (condition1) { - } else if (condition1) { // Noncompliant [[secondary=-1]] {{This branch can not be reached because the condition duplicates a previous condition in the same sequence of "if/else if" statements}} +// ^^^^^^^^^^> + } else if (condition1) { // Noncompliant {{This branch can not be reached because the condition duplicates a previous condition in the same sequence of "if/else if" statements}} +// ^^^^^^^^^^ } if (condition1) { +// ^^^^^^^^^^> } else if (condition2) { - } else if (condition1) { // Noncompliant [[secondary=-2]] {{This branch can not be reached because the condition duplicates a previous condition in the same sequence of "if/else if" statements}} + } else if (condition1) { // Noncompliant {{This branch can not be reached because the condition duplicates a previous condition in the same sequence of "if/else if" statements}} +// ^^^^^^^^^^ } if (condition1) { diff --git a/java-checks-test-sources/default/src/main/java/checks/DynamicClassLoadCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/DynamicClassLoadCheckSample.java index e17f3b3f76f..b9487c9e3f2 100644 --- a/java-checks-test-sources/default/src/main/java/checks/DynamicClassLoadCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/DynamicClassLoadCheckSample.java @@ -4,7 +4,8 @@ class DynamicClassLoadCheckSample { public void method() throws ClassNotFoundException, IllegalAccessException, InstantiationException { String className = System.getProperty("messageClassName"); - Class clazz = Class.forName(className); // Noncompliant [[sc=25;ec=32]] + Class clazz = Class.forName(className); // Noncompliant +// ^^^^^^^ ClassLoader loader = null; Object main = loader.loadClass(className).newInstance(); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/EmptyFile.java b/java-checks-test-sources/default/src/main/java/checks/EmptyFile.java index be95decf8ec..902e455d928 100644 --- a/java-checks-test-sources/default/src/main/java/checks/EmptyFile.java +++ b/java-checks-test-sources/default/src/main/java/checks/EmptyFile.java @@ -1 +1,2 @@ -// this is an fully commented empty file \ No newline at end of file +// this is an fully commented empty file +// Noncompliant@0 {{Move this file to a named package.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/EmptyFileCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/EmptyFileCheckSample.java new file mode 100644 index 00000000000..4d29b5f67ba --- /dev/null +++ b/java-checks-test-sources/default/src/main/java/checks/EmptyFileCheckSample.java @@ -0,0 +1,2 @@ +// this is an fully commented empty file +// Noncompliant@0 {{This file has 0 lines of code.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/EmptyFileMissingNewLine.java b/java-checks-test-sources/default/src/main/java/checks/EmptyFileMissingNewLine.java new file mode 100644 index 00000000000..88ad0e8df07 --- /dev/null +++ b/java-checks-test-sources/default/src/main/java/checks/EmptyFileMissingNewLine.java @@ -0,0 +1,2 @@ +package checks;// this is an fully commented empty file +// Noncompliant@0 {{Add a new line at the end of this file.}} \ No newline at end of file diff --git a/java-checks-test-sources/default/src/main/java/checks/EmptyMethodsCheckNoSemantics.java b/java-checks-test-sources/default/src/main/java/checks/EmptyMethodsCheckNoSemantics.java index 91078b505d7..3f8c5890960 100644 --- a/java-checks-test-sources/default/src/main/java/checks/EmptyMethodsCheckNoSemantics.java +++ b/java-checks-test-sources/default/src/main/java/checks/EmptyMethodsCheckNoSemantics.java @@ -9,13 +9,14 @@ class A { public A() { } - // Noncompliant@+1 - if the constructor takes an argument it should do something with it (or explain why it doesn't) + // Noncompliant@+1 public A(int c) { } - // Noncompliant@+1 [[sc=18;ec=19]] {{Add a nested comment explaining why this method is empty, throw an UnsupportedOperationException or complete the implementation.}} + // Noncompliant@+1 {{Add a nested comment explaining why this method is empty, throw an UnsupportedOperationException or complete the implementation.}} private void f() { } +// ^@-1 // Compliant private void g() { @@ -161,23 +162,26 @@ void foo() { } class QuickFixes { - // Noncompliant@+1 [[sc=12;ec=22;quickfixes=qf0]] - public QuickFixes() {} + + public QuickFixes() {} // Noncompliant [[quickfixes=qf0]] +// ^^^^^^^^^^ // fix@qf0 {{Insert placeholder comment}} // edit@qf0 [[sc=26;ec=26]] {{ /* TODO document why this constructor is empty */ }} - // Noncompliant@+1 [[sc=18;ec=29;quickfixes=qf1]] + // Noncompliant@+1 [[quickfixes=qf1]] private void emptyMethod() { } +// ^^^^^^^^^^^@-1 // fix@qf1 {{Insert placeholder comment}} // edit@qf1 [[sl=+0;el=+1;sc=33;ec=5]] {{\n // TODO document why this method is empty\n }} - // Noncompliant@+1 [[sc=18;ec=30;quickfixes=qf2]] - private void emptyMethod2() { + // Noncompliant@+1 [[quickfixes=qf2]] + private void emptyMethod2() { } +// ^^^^^^^^^^^^@-1 // fix@qf2 {{Insert placeholder comment}} - // edit@qf2 [[sl=+0;el=+2;sc=34;ec=5]] {{\n // TODO document why this method is empty\n }} + // edit@qf2 [[sl=+0;el=+1;sc=34;ec=5]] {{\n // TODO document why this method is empty\n }} } private class ExceptionalCompliantCases { diff --git a/java-checks-test-sources/default/src/main/java/checks/EmptyMethodsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/EmptyMethodsCheckSample.java index 7ce4db5dfac..36755f832e8 100644 --- a/java-checks-test-sources/default/src/main/java/checks/EmptyMethodsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/EmptyMethodsCheckSample.java @@ -9,13 +9,14 @@ class A { public A() { } - // Noncompliant@+1 - if the constructor takes an argument it should do something with it (or explain why it doesn't) + // Noncompliant@+1 public A(int c) { } - // Noncompliant@+1 [[sc=18;ec=19]] {{Add a nested comment explaining why this method is empty, throw an UnsupportedOperationException or complete the implementation.}} + // Noncompliant@+1 {{Add a nested comment explaining why this method is empty, throw an UnsupportedOperationException or complete the implementation.}} private void f() { } +// ^@-1 // Compliant private void g() { @@ -32,7 +33,7 @@ private int i() { return 0; } - // Noncompliant@+1 + // Noncompliant@+1 private void j() { ; } @@ -43,7 +44,7 @@ class AwithGenerics { private AwithGenerics() { } - // Noncompliant@+1 + // Noncompliant@+1 private void f() { } } @@ -58,14 +59,14 @@ private void g() { } class C { - // Noncompliant@+1 + // Noncompliant@+1 private void g() { } } } IFoo bar = new IFoo() { - // Noncompliant@+1 + // Noncompliant@+1 public void f() { } }; @@ -74,7 +75,7 @@ public void f() { enum AEnum { ; - // Noncompliant@+1 + // Noncompliant@+1 public void f() { } @@ -87,7 +88,7 @@ class ANestedEnum { enum B { ; - // Noncompliant@+1 + // Noncompliant@+1 public void f() { } } @@ -96,7 +97,7 @@ public void f() { public interface IFoo { static IFoo FOO = new IFoo() { - // Noncompliant@+1 + // Noncompliant@+1 public void foo() { } @@ -111,7 +112,7 @@ public void bar() { enum Foo { FOO { - // Noncompliant@+1 + // Noncompliant@+1 public void foo() { } @@ -121,7 +122,7 @@ public int bar() { } }; - // Noncompliant@+1 + // Noncompliant@+1 public void foo() { } @@ -129,7 +130,7 @@ public void foo() { class Constructors { class C { - // Noncompliant@+1 + // Noncompliant@+1 public C() { } } @@ -155,29 +156,32 @@ public F(int i) { } record MyRecord() { - // Noncompliant@+1 + // Noncompliant@+1 void foo() { } } class QuickFixes { - // Noncompliant@+1 [[sc=12;ec=22;quickfixes=qf0]] - public QuickFixes() {} + + public QuickFixes() {} // Noncompliant [[quickfixes=qf0]] +// ^^^^^^^^^^ // fix@qf0 {{Insert placeholder comment}} // edit@qf0 [[sc=26;ec=26]] {{ /* TODO document why this constructor is empty */ }} - // Noncompliant@+1 [[sc=18;ec=29;quickfixes=qf1]] +// Noncompliant@+1 [[quickfixes=qf1]] private void emptyMethod() { } +// ^^^^^^^^^^^@-1 // fix@qf1 {{Insert placeholder comment}} // edit@qf1 [[sl=+0;el=+1;sc=33;ec=5]] {{\n // TODO document why this method is empty\n }} - // Noncompliant@+1 [[sc=18;ec=30;quickfixes=qf2]] - private void emptyMethod2() { +// Noncompliant@+1 [[quickfixes=qf2]] + private void emptyMethod2() { } +// ^^^^^^^^^^^^@-1 // fix@qf2 {{Insert placeholder comment}} - // edit@qf2 [[sl=+0;el=+2;sc=34;ec=5]] {{\n // TODO document why this method is empty\n }} + // edit@qf2 [[sl=+0;el=+1;sc=34;ec=5]] {{\n // TODO document why this method is empty\n }} } private class ExceptionalCompliantCases { diff --git a/java-checks-test-sources/default/src/main/java/checks/EmptyStatementUsageCheckOnyStatement.java b/java-checks-test-sources/default/src/main/java/checks/EmptyStatementUsageCheckOnyStatement.java index d60895feab5..20fee7503b5 100644 --- a/java-checks-test-sources/default/src/main/java/checks/EmptyStatementUsageCheckOnyStatement.java +++ b/java-checks-test-sources/default/src/main/java/checks/EmptyStatementUsageCheckOnyStatement.java @@ -1,4 +1,5 @@ -; -// Noncompliant@-1 [[sc=1;ec=2;quickfixes=qf_first_statement]] +; // Noncompliant [[quickfixes=qf_first_statement]] +//^[sc=1;ec=1] + // fix@qf_first_statement {{Remove this empty statement}} // edit@qf_first_statement [[sc=1;ec=2]] {{}} diff --git a/java-checks-test-sources/default/src/main/java/checks/EmptyStatementUsageCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/EmptyStatementUsageCheckSample.java index cccb712f539..9cd30cabf74 100644 --- a/java-checks-test-sources/default/src/main/java/checks/EmptyStatementUsageCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/EmptyStatementUsageCheckSample.java @@ -3,19 +3,21 @@ import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; -import java.util.Collection;; // Noncompliant [[sc=29;ec=30;quickfixes=qf1]] {{Remove this empty statement.}} - // fix@qf1 {{Remove this empty statement}} - // edit@qf1 [[sc=29;ec=30]] {{}} +import java.util.Collection; -; // Noncompliant [[sc=1;ec=2;quickfixes=qf2]] {{Remove this empty statement.}} +; +// Noncompliant@-1 {{Remove this empty statement.}} [[sc=1;ec=2;quickfixes=qf1]] +// fix@qf1 {{Remove this empty statement}} +// edit@qf1 [[sl=-2;sc=29;el=+0;ec=2]] {{}} +; // Noncompliant {{Remove this empty statement.}} [[sc=1;ec=2;quickfixes=qf2]] // fix@qf2 {{Remove this empty statement}} -// edit@qf2 [[sl=-4;sc=30;el=+0;ec=2]] {{}} +// edit@qf2 [[sl=-4;sc=2;el=+0;ec=2]] {{}} abstract class EmptyStatementUsageCheckSample { int a; // Compliant int b;; // Noncompliant {{Remove this empty statement.}} ; // Noncompliant {{Remove this empty statement.}} - + public EmptyStatementUsageCheckSample() { ; // Noncompliant {{Remove this empty statement.}} } @@ -30,7 +32,8 @@ void foo(boolean condition) { a = 42; // Compliant for (;;) { // Compliant - ; // Noncompliant [[sc=7;ec=8;quickfixes=qf3]] {{Remove this empty statement.}} + ; // Noncompliant {{Remove this empty statement.}} [[quickfixes=qf3]] +// ^ // fix@qf3 {{Remove this empty statement}} // edit@qf3 [[sl=-1;sc=15;el=+0;ec=8]] {{}} break; @@ -53,7 +56,7 @@ class myInnerClass {}; // Noncompliant {{Remove this empty statement.}} for (Object object : getCollection()) ; // compliant - + return; // Compliant } @@ -67,7 +70,8 @@ class Bar { } void somethingAfter() { - ;tul(); // Noncompliant [[sc=5;ec=6;quickfixes=qf4]] {{Remove this empty statement.}} + ;tul(); // Noncompliant {{Remove this empty statement.}} [[quickfixes=qf4]] +// ^ // fix@qf4 {{Remove this empty statement}} // edit@qf4 [[sc=5;ec=6]] {{}} } @@ -75,13 +79,13 @@ void somethingAfter() { class EmptyStatementUsageCheckSampleBar { public enum MyEnum { APPLICATION, HANDLER }; // Noncompliant {{Remove this empty statement.}} - + Closeable c = new Closeable() { @Override public void close() throws IOException { }; // Noncompliant {{Remove this empty statement.}} }; - + void foo (MyEnum scope) { switch (scope) { case APPLICATION: @@ -104,7 +108,7 @@ boolean foo() { ; // Noncompliant } -// Noncompliant@+3 [[sc=1;ec=2;quickfixes=qf_last_statement]] + // fix@qf_last_statement {{Remove this empty statement}} // edit@qf_last_statement [[sl=-4;sc=2;el=+0;ec=2]] {{}} -; +; // Noncompliant [[sc=1;ec=2;quickfixes=qf_last_statement]] diff --git a/java-checks-test-sources/default/src/main/java/checks/EnumMapCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/EnumMapCheckSample.java index bf7c63c690a..9997e41fdb4 100644 --- a/java-checks-test-sources/default/src/main/java/checks/EnumMapCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/EnumMapCheckSample.java @@ -13,14 +13,16 @@ public enum COLOR { Map moodMapWithNullKey = new HashMap(); // compliant because using null literal as a key. Map moodMapWithNullKey2 = new HashMap(); // compliant because using null literal as a key. public void noncompliant() { - Map moodMap = new HashMap(); // Noncompliant [[sc=34;ec=62]] + Map moodMap = new HashMap(); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ new HashMap(); // Noncompliant Map moodMap2 = new HashMap<>(); // Noncompliant Map moodMap3 = new HashMap(); // Noncompliant Map moodMap4 = (new HashMap()); // Noncompliant Map map; - map = new HashMap<>(); // Noncompliant [[sc=11;ec=26]] + map = new HashMap<>(); // Noncompliant +// ^^^^^^^^^^^^^^^ } public void compliant() { diff --git a/java-checks-test-sources/default/src/main/java/checks/EnumMutableFieldCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/EnumMutableFieldCheckSample.java index 6aa5e271bca..c7a1d2c4629 100644 --- a/java-checks-test-sources/default/src/main/java/checks/EnumMutableFieldCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/EnumMutableFieldCheckSample.java @@ -5,7 +5,8 @@ enum Continent { NORTH_AMERICA(23, 24709000), EUROPE(50, 39310000); - public int countryCount; // Noncompliant [[sc=3;ec=9]] {{Lower the visibility of this field.}} + public int countryCount; // Noncompliant {{Lower the visibility of this field.}} +//^^^^^^ public static int countryCount2; // compliant, static field private int landMass; public final com.google.common.collect.ImmutableList regions = null; // Compliant - immutable @@ -14,7 +15,8 @@ enum Continent { Continent(int countryCount, int landMass) { } - public void setLandMass1(int landMass) { // Noncompliant [[sc=3;ec=9]] {{Lower the visibility of this setter or remove it altogether.}} + public void setLandMass1(int landMass) { // Noncompliant {{Lower the visibility of this setter or remove it altogether.}} +//^^^^^^ this.landMass = landMass; } public void setLandMass2(int landMass) { // compliant: empty setter is harmless : this can be a pattern used when implementing singleton enums. diff --git a/java-checks-test-sources/default/src/main/java/checks/EnumSetCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/EnumSetCheckSample.java index 0fd913d1573..589a4f3c62d 100644 --- a/java-checks-test-sources/default/src/main/java/checks/EnumSetCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/EnumSetCheckSample.java @@ -26,17 +26,20 @@ abstract class ExtendedSet implements Set { } public void doSomething(Set param) { // compliant, we ignore parameters. - Set warm = new HashSet(); // Noncompliant [[sc=23;ec=43]] {{Convert this Set to an EnumSet.}} + Set warm = new HashSet(); // Noncompliant {{Convert this Set to an EnumSet.}} +// ^^^^^^^^^^^^^^^^^^^^ warm.add(COLOR.RED); warm.add(COLOR.ORANGE); Set foo = new HashSet(); SetString ss; ExtendedSet es; // Compliant, we check only initializer. - Set warm2 = new HashSet(); // Noncompliant [[sc=17;ec=37]] {{Convert this Set to an EnumSet.}} + Set warm2 = new HashSet(); // Noncompliant {{Convert this Set to an EnumSet.}} +// ^^^^^^^^^^^^^^^^^^^^ EnumSet warm3 = EnumSet.of(COLOR.RED, COLOR.ORANGE); Set warm4 = EnumSet.of(COLOR.RED, COLOR.ORANGE); Set ports2 = new HashSet<>(); - Set ports = new HashSet<>(); // Noncompliant [[sc=24;ec=39]] {{Convert this Set to an EnumSet.}} + Set ports = new HashSet<>(); // Noncompliant {{Convert this Set to an EnumSet.}} +// ^^^^^^^^^^^^^^^ Set ports4 = Sets.immutableEnumSet(COLOR.RED); // Compliant - guava use an enum set with constraint of immutability Set ports5 = Sets.immutableEnumSet(Lists.newArrayList(COLOR.RED)); // Compliant - guava use an enum set with constraint of immutability Set ports6 = Sets.newHashSet(COLOR.RED); // Noncompliant {{Convert this Set to an EnumSet.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/EqualsArgumentType.java b/java-checks-test-sources/default/src/main/java/checks/EqualsArgumentType.java index 4f3040c5aea..c00d847faa7 100644 --- a/java-checks-test-sources/default/src/main/java/checks/EqualsArgumentType.java +++ b/java-checks-test-sources/default/src/main/java/checks/EqualsArgumentType.java @@ -16,7 +16,8 @@ public boolean equals(Object that) { // Compliant public class TestClassInstanceof2 { @Override - public boolean equals(Object that) { // Noncompliant [[sc=20;ec=26]] {{Add a type test to this method.}} + public boolean equals(Object that) { // Noncompliant {{Add a type test to this method.}} +// ^^^^^^ if (this instanceof Object) { return ((Object) that) == null; } diff --git a/java-checks-test-sources/default/src/main/java/checks/EqualsNotOverriddenInSubclassCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/EqualsNotOverriddenInSubclassCheckSample.java index 70ca8e208a9..a5d5c47315f 100644 --- a/java-checks-test-sources/default/src/main/java/checks/EqualsNotOverriddenInSubclassCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/EqualsNotOverriddenInSubclassCheckSample.java @@ -18,7 +18,8 @@ public boolean equals(Object obj) { } } - class B extends A { // Noncompliant [[sc=9;ec=10]] {{Override the "equals" method in this class.}} + class B extends A { // Noncompliant {{Override the "equals" method in this class.}} +// ^ String s2; } diff --git a/java-checks-test-sources/default/src/main/java/checks/EqualsOnAtomicClassCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/EqualsOnAtomicClassCheckSample.java index fbb94360d82..e51e83b5daa 100644 --- a/java-checks-test-sources/default/src/main/java/checks/EqualsOnAtomicClassCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/EqualsOnAtomicClassCheckSample.java @@ -11,7 +11,8 @@ void method() { AtomicBoolean abool1 = new AtomicBoolean(true); AtomicBoolean abool2 = new AtomicBoolean(true); - isEqual = abool1.equals(abool2); // Noncompliant [[sc=22;ec=28]] {{Use ".get()" to retrieve the value and compare it instead.}} + isEqual = abool1.equals(abool2); // Noncompliant {{Use ".get()" to retrieve the value and compare it instead.}} +// ^^^^^^ AtomicInteger aInt1 = new AtomicInteger(0); AtomicInteger aInt2 = new AtomicInteger(0); diff --git a/java-checks-test-sources/default/src/main/java/checks/EqualsParametersMarkedNonNullCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/EqualsParametersMarkedNonNullCheckSample.java index df9f4276e81..2af27e753f7 100644 --- a/java-checks-test-sources/default/src/main/java/checks/EqualsParametersMarkedNonNullCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/EqualsParametersMarkedNonNullCheckSample.java @@ -5,7 +5,8 @@ public class EqualsParametersMarkedNonNullCheckSample { static class A { - public boolean equals(@Nonnull Object obj) { // Noncompliant [[sc=27;ec=35;quickfixes=qf1]] {{"equals" method parameters should not be marked "@Nonnull".}} + public boolean equals(@Nonnull Object obj) { // Noncompliant {{"equals" method parameters should not be marked "@Nonnull".}} [[quickfixes=qf1]] +// ^^^^^^^^ // fix@qf1 {{Remove "@Nonnull"}} // edit@qf1 [[sc=27;ec=36]] {{}} return true; @@ -42,10 +43,11 @@ public boolean equals(@Nonnull C c) { // Compliant static class F { public boolean equals( - @javax.validation.constraints.NotNull // Noncompliant [[sc=7;ec=44;el=+0;quickfixes=qf2]] {{"equals" method parameters should not be marked "@NotNull".}} + @javax.validation.constraints.NotNull // Noncompliant {{"equals" method parameters should not be marked "@NotNull".}} [[quickfixes=qf2]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ java.lang.Object object) { // fix@qf2 {{Remove "@NotNull"}} - // edit@qf2 [[sc=7;ec=7;el=+1]] {{}} + // edit@qf2 [[sc=7;ec=7;el=+2]] {{}} return false; } } diff --git a/java-checks-test-sources/default/src/main/java/checks/ErrorClassExtendedCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ErrorClassExtendedCheckSample.java index c774b5a5951..8abaa94621a 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ErrorClassExtendedCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ErrorClassExtendedCheckSample.java @@ -1,9 +1,11 @@ package checks; -class ErrorClassExtendedCheckSampleA extends Error { // Noncompliant [[sc=46;ec=51]] {{Extend "java.lang.Exception" or one of its subclasses.}} +class ErrorClassExtendedCheckSampleA extends Error { // Noncompliant {{Extend "java.lang.Exception" or one of its subclasses.}} +// ^^^^^ } -class ErrorClassExtendedCheckSampleB extends java.lang.Error { // Noncompliant [[sc=46;ec=61]] +class ErrorClassExtendedCheckSampleB extends java.lang.Error { // Noncompliant +// ^^^^^^^^^^^^^^^ } class ErrorClassExtendedCheckSampleC { // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/EscapedUnicodeCharactersCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/EscapedUnicodeCharactersCheckSample.java index e53e0806adc..8ccc07d0f7c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/EscapedUnicodeCharactersCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/EscapedUnicodeCharactersCheckSample.java @@ -2,15 +2,18 @@ class EscapedUnicodeCharactersCheckSample { void method() { - String prefix = "n\uuuu00E9e"; // Noncompliant [[sc=21;ec=34]] {{Remove this Unicode escape sequence and use the character instead.}} - String prefix2= "n\\\uuuu00E9e"; // Noncompliant [[sc=21;ec=36]] {{Remove this Unicode escape sequence and use the character instead.}} + String prefix = "n\uuuu00E9e"; // Noncompliant {{Remove this Unicode escape sequence and use the character instead.}} +// ^^^^^^^^^^^^^ + String prefix2= "n\\\uuuu00E9e"; // Noncompliant {{Remove this Unicode escape sequence and use the character instead.}} +// ^^^^^^^^^^^^^^^ prefix = "n\u00E9e\u0001v"; // Noncompliant // compliant, only escaped prefix = "\u00E9\u00E9\u00E9\u00E9"; // compliant, only unprintable prefix = "a\u0001b\u0002c\u00A0"; prefix = "\u007f"; - prefix = "a\u0080b\u0002c\u00A0\u0083\u0164"; // Noncompliant [[sc=14;ec=49]] + prefix = "a\u0080b\u0002c\u00A0\u0083\u0164"; // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ prefix = "n\\u00E9e"; prefix = "née"; prefix = ""; diff --git a/java-checks-test-sources/default/src/main/java/checks/ExpressionComplexityCheckCustom.java b/java-checks-test-sources/default/src/main/java/checks/ExpressionComplexityCheckCustom.java index f6024c72278..4fbc76508a0 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ExpressionComplexityCheckCustom.java +++ b/java-checks-test-sources/default/src/main/java/checks/ExpressionComplexityCheckCustom.java @@ -5,12 +5,12 @@ class ExpressionComplexityCheckCustom { int b = false ? (true ? (false ? (true ? 1 : 0) : 0) : 0) : 1; boolean c = true || false || true || false || false; - boolean d = true && false && true && false && true && true; // Noncompliant [[effortToFix=1]] {{Reduce the number of conditional operators (5) used in the expression (maximum allowed 4).}} + boolean d = true && false && true && false && true && true; // Noncompliant {{Reduce the number of conditional operators (5) used in the expression (maximum allowed 4).}} boolean e = true | false | true | false; void f() { - if ((true ? 0 : 1) == 0 || false || true && false && true || false) { // Noncompliant [[effortToFix=2]] {{Reduce the number of conditional operators (6) used in the expression (maximum allowed 4).}} + if ((true ? 0 : 1) == 0 || false || true && false && true || false) { // Noncompliant {{Reduce the number of conditional operators (6) used in the expression (maximum allowed 4).}} } } diff --git a/java-checks-test-sources/default/src/main/java/checks/ExpressionComplexityCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ExpressionComplexityCheckSample.java index a8ba2bf5a9f..e572428fadc 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ExpressionComplexityCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ExpressionComplexityCheckSample.java @@ -4,15 +4,16 @@ class ExpressionComplexityCheckSample { int a = false ? (true ? (false ? 1 : 0) : 0) : 1; - int b = false ? (true ? (false ? (true ? 1 : 0) : 0) : 0) : 1; // Noncompliant [[sc=11;ec=64;effortToFix=1]] {{Reduce the number of conditional operators (4) used in the expression (maximum allowed 3).}} + int b = false ? (true ? (false ? (true ? 1 : 0) : 0) : 0) : 1; // Noncompliant {{Reduce the number of conditional operators (4) used in the expression (maximum allowed 3).}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - boolean c = true || false || true || false || false; // Noncompliant [[effortToFix=1]] - boolean d = true && false && true && false && true && true; // Noncompliant [[effortToFix=2]] {{Reduce the number of conditional operators (5) used in the expression (maximum allowed 3).}} + boolean c = true || false || true || false || false; // Noncompliant + boolean d = true && false && true && false && true && true; // Noncompliant {{Reduce the number of conditional operators (5) used in the expression (maximum allowed 3).}} boolean e = true | false | true | false; void f() { - if ((true ? 0 : 1) == 0 || false || true && false && true || false) { // Noncompliant [[effortToFix=3]] {{Reduce the number of conditional operators (6) used in the expression (maximum allowed 3).}} + if ((true ? 0 : 1) == 0 || false || true && false && true || false) { // Noncompliant {{Reduce the number of conditional operators (6) used in the expression (maximum allowed 3).}} } } @@ -27,9 +28,10 @@ void g() { } void h() { - boolean foo = true && true && true && // Noncompliant [[sc=19;ec=11;effortToFix=1]] + boolean foo = true && true && true && // Noncompliant +// new ExpressionComplexityCheckSample() { - boolean a = true && true && true && false && false; // Noncompliant [[effortToFix=1]] + boolean a = true && true && true && false && false; // Noncompliant boolean a2 = true && true && true; }.someThing() && true; @@ -41,7 +43,7 @@ boolean someThing() { boolean[] foo = new boolean[] { true && true && true && true, - true && true && true && true && true // Noncompliant + true && true && true && true && true // Noncompliant }; record SD(String applicationName, String serverName, String serverClassPath, String serverArgs, String serverVmArgs) { } @@ -85,14 +87,14 @@ public boolean equals(Object o) { return true && true && true && false && false; // Compliant, the expression is inside equals method } - boolean afterEquals = true || false || true || false || false; // Noncompliant [[effortToFix=1]] + boolean afterEquals = true || false || true || false || false; // Noncompliant } class ExpressionComplexity2 { @Override public boolean equals(Object o) { class Local { - boolean insideLocal = true || false || true || false || false; // Noncompliant [[effortToFix=1]] + boolean insideLocal = true || false || true || false || false; // Noncompliant @Override public boolean equals(Object o) { return true && true && true && false && false; // Compliant, the expression is inside equals method @@ -105,10 +107,10 @@ public boolean equals(Object o) { enum AbbreviationOfDays{ VALUE; public boolean foo() { - return true || false || true || false || false; // Noncompliant [[effortToFix=1]] + return true || false || true || false || false; // Noncompliant } } record ExpressionComplexityRecord() { - static boolean b = true || false || true || false || false; // Noncompliant [[effortToFix=1]] {{Reduce the number of conditional operators (4) used in the expression (maximum allowed 3).}} + static boolean b = true || false || true || false || false; // Noncompliant {{Reduce the number of conditional operators (4) used in the expression (maximum allowed 3).}} } diff --git a/java-checks-test-sources/default/src/main/java/checks/FileHeaderCheck/Class1.java b/java-checks-test-sources/default/src/main/java/checks/FileHeaderCheck/Class1.java index 085296b4aa4..987c2d574e5 100644 --- a/java-checks-test-sources/default/src/main/java/checks/FileHeaderCheck/Class1.java +++ b/java-checks-test-sources/default/src/main/java/checks/FileHeaderCheck/Class1.java @@ -4,3 +4,5 @@ public class Class1 { } + +// Noncompliant@0 {{Add or update the header of this file.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/FileHeaderCheck/Class2.java b/java-checks-test-sources/default/src/main/java/checks/FileHeaderCheck/Class2.java index ac6e092e3aa..c9f79f05c65 100644 --- a/java-checks-test-sources/default/src/main/java/checks/FileHeaderCheck/Class2.java +++ b/java-checks-test-sources/default/src/main/java/checks/FileHeaderCheck/Class2.java @@ -5,3 +5,5 @@ public class Class2 { } + +// Noncompliant@0 {{Add or update the header of this file.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/FileHeaderCheck/Regex1.java b/java-checks-test-sources/default/src/main/java/checks/FileHeaderCheck/Regex1.java index fd9e1da7366..bbb1cf531ba 100644 --- a/java-checks-test-sources/default/src/main/java/checks/FileHeaderCheck/Regex1.java +++ b/java-checks-test-sources/default/src/main/java/checks/FileHeaderCheck/Regex1.java @@ -4,3 +4,5 @@ public class Regex1 { } + +// Noncompliant@0 {{Add or update the header of this file.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/FileHeaderCheck/Regex2.java b/java-checks-test-sources/default/src/main/java/checks/FileHeaderCheck/Regex2.java index ee79fbd5f6c..6ee7c67612c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/FileHeaderCheck/Regex2.java +++ b/java-checks-test-sources/default/src/main/java/checks/FileHeaderCheck/Regex2.java @@ -5,3 +5,5 @@ public class Regex2 { } + +// Noncompliant@0 {{Add or update the header of this file.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/FileHeaderCheck/Regex4.java b/java-checks-test-sources/default/src/main/java/checks/FileHeaderCheck/Regex4.java index 8c89a156c2b..64e4a915586 100644 --- a/java-checks-test-sources/default/src/main/java/checks/FileHeaderCheck/Regex4.java +++ b/java-checks-test-sources/default/src/main/java/checks/FileHeaderCheck/Regex4.java @@ -6,3 +6,5 @@ public class Regex4 { } + +// Noncompliant@0 {{Add or update the header of this file.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/FinalizeFieldsSetCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/FinalizeFieldsSetCheckSample.java index 802d1968f02..bfd0dabba04 100644 --- a/java-checks-test-sources/default/src/main/java/checks/FinalizeFieldsSetCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/FinalizeFieldsSetCheckSample.java @@ -8,7 +8,8 @@ class A { @Override protected void finalize() { - myString = null; // Noncompliant [[sc=18;ec=22]] {{Remove this nullification of "myString".}} + myString = null; // Noncompliant {{Remove this nullification of "myString".}} +// ^^^^ myInteger = null; // Noncompliant myObject = null; // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/FixmeTagPresenceCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/FixmeTagPresenceCheckSample.java index 96b7237e41d..76f3b3e2c95 100644 --- a/java-checks-test-sources/default/src/main/java/checks/FixmeTagPresenceCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/FixmeTagPresenceCheckSample.java @@ -1,21 +1,21 @@ // foo package checks; -// Noncompliant@+1 {{Take the required action to fix the issue indicated by this comment.}} + // Noncompliant@+1 {{Take the required action to fix the issue indicated by this comment.}} // fixME class FixmeTagPresenceCheckSample { -// Noncompliant@+5 -// Noncompliant@+3 + // Noncompliant@+5 + // Noncompliant@+3 /* fixme FixMe */ -// Noncompliant@+1 + // Noncompliant@+1 // FIXME -// Noncompliant@+1 + // Noncompliant@+1 // [FIXME] // PreFixMe diff --git a/java-checks-test-sources/default/src/main/java/checks/FloatEquality.java b/java-checks-test-sources/default/src/main/java/checks/FloatEquality.java index 4fc1d2bc0de..75cd035df59 100644 --- a/java-checks-test-sources/default/src/main/java/checks/FloatEquality.java +++ b/java-checks-test-sources/default/src/main/java/checks/FloatEquality.java @@ -5,10 +5,11 @@ void foo() { float f1 = 0.1f; float f2 = 0.1f; int i = 1; - if(f1 == f2) {} // Noncompliant [[sc=11;ec=13]] {{Equality tests should not be made with floating point values.}} - if( f1 != f2 ){}// Noncompliant {{Equality tests should not be made with floating point values.}} - if( f1 == i ){}// Noncompliant {{Equality tests should not be made with floating point values.}} - if( i == f1 ){}// Noncompliant + if(f1 == f2) {} // Noncompliant {{Equality tests should not be made with floating point values.}} +// ^^ + if( f1 != f2 ){} // Noncompliant {{Equality tests should not be made with floating point values.}} + if( f1 == i ){} // Noncompliant {{Equality tests should not be made with floating point values.}} + if( i == f1 ){} // Noncompliant if(f1 != f1){} //compliant NaN test @@ -16,9 +17,9 @@ void foo() { double a = 0.1d; double c = 0.1d; if( a == c ) {} // Noncompliant - if( a != c ){}// Noncompliant - if( a == i ){}// Noncompliant - if( i == a ){}// Noncompliant + if( a != c ){} // Noncompliant + if( a == i ){} // Noncompliant + if( i == a ){} // Noncompliant if( a != a ){} //compliant NaN test if(c <= a && a <= c) {} // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/ForLoopFalseConditionCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ForLoopFalseConditionCheckSample.java index ce84f29af2d..cf33f9e7e3d 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ForLoopFalseConditionCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ForLoopFalseConditionCheckSample.java @@ -3,14 +3,15 @@ public class ForLoopFalseConditionCheckSample { void myMethod(int x, int y, int z) { - for(int i = 0; i < ZERO; i++) {} // Noncompliant - for(int i = 1; i < 0 + 1; i++) {} // Noncompliant - for(int i = 10; i < 0 + 1 + 1; i++) {} // Noncompliant - for(int i = 0; i < 0 + 1 - 1; i++) {} // Noncompliant + for(int i = 0; i < ZERO; i++) {} // Noncompliant + for(int i = 1; i < 0 + 1; i++) {} // Noncompliant + for(int i = 10; i < 0 + 1 + 1; i++) {} // Noncompliant + for(int i = 0; i < 0 + 1 - 1; i++) {} // Noncompliant for(int i = 12; i > 1 + 2 * 5; i++) {} // Compliant - for(int i = 12; i > (1 + 2) * 5; i++) {} // Noncompliant + for(int i = 12; i > (1 + 2) * 5; i++) {} // Noncompliant for(int i = 2; i > (1 + 5) / 5; i++) {} // Compliant - for(int i = 2; i > 1 + 5 / 5; i++) {} // Noncompliant + for(int i = 2; i > 1 + 5 / 5; // Noncompliant + i++) {} int j = 0, k = 0; @@ -42,7 +43,7 @@ void myMethod(int x, int y, int z) { static final int ZERO = 0; void foo() { - for(int i = 0; i < 0; i++) {} // Noncompliant + for(int i = 0; i < 0; i++) {} // Noncompliant } } diff --git a/java-checks-test-sources/default/src/main/java/checks/ForLoopIncrementAndUpdateCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ForLoopIncrementAndUpdateCheckSample.java index c460e6fec65..0bc0130b2d4 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ForLoopIncrementAndUpdateCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ForLoopIncrementAndUpdateCheckSample.java @@ -9,8 +9,10 @@ Object foo() { A a = new A(), p, h = new A(); int[] m = new int[1000]; - for (i = 0; i< 10; j++, m[0]++) { // Noncompliant [[sc=5;ec=8;secondary=13]] {{Move the update of "i" into this loop's update clause.}} + for (i = 0; i< 10; j++, m[0]++) { // Noncompliant {{Move the update of "i" into this loop's update clause.}} +// ^^^ i++; +// ^^^< } for (i = 0; i< 10; j++) { // Compliant - i is updated multiple times if (blah()) { @@ -25,13 +27,18 @@ Object foo() { for (i = 0; k< 10 && l<10 ; l++) {} // Compliant condition is using one of the incrementer for (i = 0; k< 10 && l<10 ; i++, j++, l++) {} // Compliant for (i = 0; k< 10 ; i++, j++, l++) {} // Compliant - for (i = 0; k< 10 && l<10; i++, j++) { // Noncompliant [[secondary=30]] {{Move the update of "k" into this loop's update clause.}} + for (i = 0; k< 10 && l<10; i++, j++) { // Noncompliant {{Move the update of "k" into this loop's update clause.}} +// ^^^ l -= 42; k++; +// ^^^< } - for (i = 0; k< 10 && l<10; i++, j++) { // Noncompliant [[secondary=33,34]] {{Move the update of "k","l" into this loop's update clause.}} + for (i = 0; k< 10 && l<10; i++, j++) { // Noncompliant {{Move the update of "k","l" into this loop's update clause.}} +// ^^^ l--; +// ^^^< k++; +// ^^^< } for (i = 0; i< 10; i+= 2) {} // Compliant for (i = 0; i< 10; a.myField+= 2) {} // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/ForLoopVariableTypeCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ForLoopVariableTypeCheckSample.java index 98646b9e926..a790438423b 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ForLoopVariableTypeCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ForLoopVariableTypeCheckSample.java @@ -52,7 +52,8 @@ void doStuff() { } for (A a : listOfB) { } - for (A a : listOfB) { // Noncompliant [[sc=12;ec=13;secondary=+0]] {{Change "A" to the type handled by the Collection.}} + for (A a : listOfB) { // Noncompliant {{Change "A" to the type handled by the Collection.}} +// ^ ^^^^^^^< B b = (B) a; } for (Object o : listOfB) { diff --git a/java-checks-test-sources/default/src/main/java/checks/GarbageCollectorCalledCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/GarbageCollectorCalledCheckSample.java index 2e1b92fc0f6..65d86d4bb75 100644 --- a/java-checks-test-sources/default/src/main/java/checks/GarbageCollectorCalledCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/GarbageCollectorCalledCheckSample.java @@ -19,8 +19,10 @@ private Runtime foo() { } private void f() { - System.gc(); // Noncompliant [[sc=12;ec=14]] {{Don't try to be smarter than the JVM, remove this call to run the garbage collector.}} - System.runFinalization(); // Noncompliant [[sc=12;ec=27]] {{Don't try to be smarter than the JVM, remove this call to run the garbage collector.}} + System.gc(); // Noncompliant {{Don't try to be smarter than the JVM, remove this call to run the garbage collector.}} +// ^^ + System.runFinalization(); // Noncompliant {{Don't try to be smarter than the JVM, remove this call to run the garbage collector.}} +// ^^^^^^^^^^^^^^^ foo.gc(); // Compliant System.exit(0); // Compliant Runtime.getRuntime().gc(); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/GetClassLoaderCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/GetClassLoaderCheckSample.java index 4e21836b5fb..6fb807fbccf 100644 --- a/java-checks-test-sources/default/src/main/java/checks/GetClassLoaderCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/GetClassLoaderCheckSample.java @@ -3,6 +3,7 @@ class GetClassLoaderCheckSample { void foo(){ ClassLoader cl = this.getClass() - .getClassLoader(); // Noncompliant [[sc=8;ec=22]] {{Use "Thread.currentThread().getContextClassLoader()" instead.}} + .getClassLoader(); // Noncompliant {{Use "Thread.currentThread().getContextClassLoader()" instead.}} +// ^^^^^^^^^^^^^^ } } diff --git a/java-checks-test-sources/default/src/main/java/checks/GetRequestedSessionIdCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/GetRequestedSessionIdCheckSample.java index a0dbb4d678e..76f60f82f26 100644 --- a/java-checks-test-sources/default/src/main/java/checks/GetRequestedSessionIdCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/GetRequestedSessionIdCheckSample.java @@ -8,7 +8,8 @@ public class GetRequestedSessionIdCheckSample extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - String sessionId = request.getRequestedSessionId(); // Noncompliant [[sc=32;ec=53]] {{Remove use of this unsecured "getRequestedSessionId()" method}} + String sessionId = request.getRequestedSessionId(); // Noncompliant {{Remove use of this unsecured "getRequestedSessionId()" method}} +// ^^^^^^^^^^^^^^^^^^^^^ } protected void doPostJakarta(jakarta.servlet.http.HttpServletRequest request) { String sessionId = request.getRequestedSessionId(); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/HardCodedPasswordCheckCustom.java b/java-checks-test-sources/default/src/main/java/checks/HardCodedPasswordCheckCustom.java index 8e02a193dcc..e5478812b7a 100644 --- a/java-checks-test-sources/default/src/main/java/checks/HardCodedPasswordCheckCustom.java +++ b/java-checks-test-sources/default/src/main/java/checks/HardCodedPasswordCheckCustom.java @@ -11,11 +11,14 @@ private void a(char[] pwd, String var) { String variable2 = "login=a&password=xxx"; // Compliant String variable3 = "login=a&passwd=xxx"; // Compliant String variable4 = "login=a&pwd=xxx"; // Compliant - String variable5 = "login=a&marmalade=xxx"; // Noncompliant [[sc=24;ec=47]] {{'marmalade' detected in this expression, review this potentially hard-coded password.}} + String variable5 = "login=a&marmalade=xxx"; // Noncompliant {{'marmalade' detected in this expression, review this potentially hard-coded password.}} +// ^^^^^^^^^^^^^^^^^^^^^^^ String variable6 = "login=a&bazooka=xxx "; // Noncompliant - String variableNameWithBazookaInIt = "xxx"; // Noncompliant [[sc=12;ec=39]] - String variableNameWithmarMalAdeInIt = "xxx"; // Noncompliant [[sc=12;ec=41]] + String variableNameWithBazookaInIt = "xxx"; // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + String variableNameWithmarMalAdeInIt = "xxx"; // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ String variableNameWithPwdInIt = "xxx"; // Compliant String otherVariableNameWithPasswordInIt; fieldNameWithPasswordInIt = "xx"; // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/HardCodedPasswordCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/HardCodedPasswordCheckSample.java index 9a23d9bd4ed..52b0500fe6d 100644 --- a/java-checks-test-sources/default/src/main/java/checks/HardCodedPasswordCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/HardCodedPasswordCheckSample.java @@ -28,7 +28,8 @@ private void a(char[] pwd, String var) throws SQLException { // ========== 1. String literal ========== // The variable name does not influence the issue, only the string is considered. String variable1 = "blabla"; - String variable2 = "login=a&password=xxx"; // Noncompliant [[sc=24;ec=46]] {{'password' detected in this expression, review this potentially hard-coded password.}} + String variable2 = "login=a&password=xxx"; // Noncompliant {{'password' detected in this expression, review this potentially hard-coded password.}} +// ^^^^^^^^^^^^^^^^^^^^^^ String variable3 = "login=a&passwd=xxx"; // Noncompliant String variable4 = "login=a&pwd=xxx"; // Noncompliant String variable5 = "login=a&password="; @@ -73,16 +74,17 @@ private void a(char[] pwd, String var) throws SQLException { // ========== 1.2 Urls ========== // No exclusion is made when the password if found in an url String[] urls = { - "http://user:123456@server.com/path", // Noncompliant [[sc=7;ec=43]] {{Review this hard-coded URL, which may contain a password.}} + "http://user:123456@server.com/path", // Noncompliant {{Review this hard-coded URL, which may contain a password.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ "ftp://anonymous:anonymous@wustl.edu", // OK, user == password - "ftp://:anonymous@wustl.edu", // Noncompliant + "ftp://:anonymous@wustl.edu", // Noncompliant "http://admin:admin@server.com/path", // OK, user == password "http://user:@server.com/path", // OK, password is empty "http://user@server.com/path", // OK, no password "https://server:80/path", // OK, no user and password "http://server.com/path", // OK, no user and password - "http://:123456@server.com/path", // Noncompliant - "HTTPS://:token0932448209@server.com", // Noncompliant + "http://:123456@server.com/path", // Noncompliant + "HTTPS://:token0932448209@server.com", // Noncompliant "https://invalid::url::format", "too-long-url-scheme://user:123456@server.com", }; @@ -90,13 +92,18 @@ private void a(char[] pwd, String var) throws SQLException { // ========== 2. Variable declaration ========== // The variable name should contain a password word final String MY_PASSWORD = "1234"; // Noncompliant - String variableNameWithPasswordInIt = "xxx"; // Noncompliant [[sc=12;ec=40]] {{'Password' detected in this expression, review this potentially hard-coded password.}} - String variableNameWithPassphraseInIt = "xxx"; // Noncompliant [[sc=12;ec=42]] {{'Passphrase' detected in this expression, review this potentially hard-coded password.}} - String variableNameWithPasswdInIt = "xxx"; // Noncompliant [[sc=12;ec=38]] {{'Passwd' detected in this expression, review this potentially hard-coded password.}} - String variableNameWithPwdInIt = "xxx"; // Noncompliant [[sc=12;ec=35]] {{'Pwd' detected in this expression, review this potentially hard-coded password.}} + String variableNameWithPasswordInIt = "xxx"; // Noncompliant {{'Password' detected in this expression, review this potentially hard-coded password.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + String variableNameWithPassphraseInIt = "xxx"; // Noncompliant {{'Passphrase' detected in this expression, review this potentially hard-coded password.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + String variableNameWithPasswdInIt = "xxx"; // Noncompliant {{'Passwd' detected in this expression, review this potentially hard-coded password.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^ + String variableNameWithPwdInIt = "xxx"; // Noncompliant {{'Pwd' detected in this expression, review this potentially hard-coded password.}} +// ^^^^^^^^^^^^^^^^^^^^^^^ String passwordToString = "SuperSecure".toString(); // Compliant, FN, but will be reported when we remove "toString()" // Same constraints when "toCharArray" is called on the password - char[] passwordToChar = "SuperSecure".toCharArray(); // Noncompliant [[sc=12;ec=26]] + char[] passwordToChar = "SuperSecure".toCharArray(); // Noncompliant +// ^^^^^^^^^^^^^^ // Password with less than 2 characters are ignored String variableNameWithPasswordInItEmpty = ""; String variableNameWithPasswordInItOneChar = "X"; @@ -124,7 +131,8 @@ private void a(char[] pwd, String var) throws SQLException { // ========== 3. Assignment ========== // The variable name should contain a password word - fieldNameWithPasswordInIt = "xx"; // Noncompliant [[sc=5;ec=30]] {{'Password' detected in this expression, review this potentially hard-coded password.}} + fieldNameWithPasswordInIt = "xx"; // Noncompliant {{'Password' detected in this expression, review this potentially hard-coded password.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^ this.fieldNameWithPasswordInIt = "xx"; // Noncompliant // Password with less than 2 characters are ignored fieldNameWithPasswordInIt = "X"; @@ -149,9 +157,11 @@ private void a(char[] pwd, String var) throws SQLException { // ========== 4.1 Equals ========== // When one side of the equals contains a password word, report an issue String password = "123"; // Noncompliant - if(password.equals("whatever")) { // Noncompliant [[sc=8;ec=16]] + if(password.equals("whatever")) { // Noncompliant +// ^^^^^^^^ } - if("whatever".equals(password)) { // Noncompliant [[sc=26;ec=34]] + if("whatever".equals(password)) { // Noncompliant +// ^^^^^^^^ } if(PASSED.equals(password)) { // Noncompliant } @@ -187,7 +197,8 @@ private void a(char[] pwd, String var) throws SQLException { conn = DriverManager.getConnection("jdbc:mysql://xxx/", "root", PASSED); // Compliant, handled by S6437 conn = DriverManager.getConnection("jdbc:mysql://xxx/"); // Password not set as argument, but it is still detected in the string itself is detected thanks to (1.) - conn = DriverManager.getConnection("jdbc:db2://myhost:5021/mydb:user=dbadm;password=foo"); // Noncompliant [[sc=40;ec=93]] + conn = DriverManager.getConnection("jdbc:db2://myhost:5021/mydb:user=dbadm;password=foo"); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // ========== 4.3 Setting password ========== // When a method call has two arguments potentially containing String, we report an issue the same way we would with a variable declaration @@ -209,11 +220,13 @@ private void a(char[] pwd, String var) throws SQLException { // Other test cases myA.setProperty(12, "xxxxx"); myA.setProperty(new Object(), new Object()); - myA.setProperty("something", "else").setProperty("password", "xxxxx"); // Noncompliant [[sc=42;ec=53]] + myA.setProperty("something", "else").setProperty("password", "xxxxx"); // Noncompliant +// ^^^^^^^^^^^ // Same for code not user defined java.util.Properties props = new java.util.Properties(); - props.put(Context.SECURITY_CREDENTIALS, "1234"); // Noncompliant [[sc=11;ec=14]] + props.put(Context.SECURITY_CREDENTIALS, "1234"); // Noncompliant +// ^^^ props.put("java.naming.security.credentials", "1234"); // Noncompliant props.put("password", "whateverpassword"); // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/HardCodedSecretCheckCustom.java b/java-checks-test-sources/default/src/main/java/checks/HardCodedSecretCheckCustom.java index cc77b72d87d..de3033ae536 100644 --- a/java-checks-test-sources/default/src/main/java/checks/HardCodedSecretCheckCustom.java +++ b/java-checks-test-sources/default/src/main/java/checks/HardCodedSecretCheckCustom.java @@ -3,6 +3,7 @@ class HardCodedSecretCheckCustom { private void test() { String variable2 = "login=a&secret=aaaaaaaaaaaaaabcdefg"; // Compliant - String variable5 = "login=a&marmalade=aaaaaaaaaaaaaabcdefg"; // Noncompliant [[sc=24;ec=64]] {{'marmalade' detected in this expression, review this potentially hard-coded secret.}} + String variable5 = "login=a&marmalade=aaaaaaaaaaaaaabcdefg"; // Noncompliant {{'marmalade' detected in this expression, review this potentially hard-coded secret.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } } diff --git a/java-checks-test-sources/default/src/main/java/checks/HardCodedSecretCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/HardCodedSecretCheckSample.java index 019347a9b13..366b054468e 100644 --- a/java-checks-test-sources/default/src/main/java/checks/HardCodedSecretCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/HardCodedSecretCheckSample.java @@ -22,7 +22,8 @@ private void a(char[] secret, String var) throws SQLException { // ========== 1. String literal ========== // The variable name does not influence the issue, only the string is considered. String variable1 = "blabla"; - String variable2 = "login=a&secret=abcdefghijklmnopqrs"; // Noncompliant [[sc=24;ec=60]] {{'secret' detected in this expression, review this potentially hard-coded secret.}} + String variable2 = "login=a&secret=abcdefghijklmnopqrs"; // Noncompliant {{'secret' detected in this expression, review this potentially hard-coded secret.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ String variable3 = "login=a&token=abcdefghijklmnopqrs"; // Noncompliant String variable4 = "login=a&api_key=abcdefghijklmnopqrs"; // Noncompliant String variable5 = "login=a&api.key=abcdefghijklmnopqrs"; // Noncompliant @@ -81,13 +82,17 @@ private void a(char[] secret, String var) throws SQLException { // ========== 2. Variable declaration ========== // The variable name should contain a secret word final String MY_SECRET = "abcdefghijklmnopqrs"; // Noncompliant - String variableNameWithSecretInIt = "abcdefghijklmnopqrs"; // Noncompliant [[sc=12;ec=38]] - String variableNameWithSecretaryInIt = "abcdefghijklmnopqrs"; // Noncompliant, false-positive Secretary is not Secret - String variableNameWithAuthorshipInIt = "abcdefghijklmnopqrs"; // Noncompliant, false-positive Authorship is not Auth + String variableNameWithSecretInIt = "abcdefghijklmnopqrs"; // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^ + String variableNameWithSecretaryInIt = "abcdefghijklmnopqrs"; // Noncompliant + String variableNameWithAuthorshipInIt = "abcdefghijklmnopqrs"; // Noncompliant String variableNameWithTokenInIt = "abcdefghijklmnopqrs"; // Noncompliant - String variableNameWithApiKeyInIt = "abcdefghijklmnopqrs"; // Noncompliant [[sc=12;ec=38]] - String variableNameWithCredentialInIt = "abcdefghijklmnopqrs"; // Noncompliant [[sc=12;ec=42]] - String variableNameWithAuthInIt = "abcdefghijklmnopqrs"; // Noncompliant [[sc=12;ec=36]] + String variableNameWithApiKeyInIt = "abcdefghijklmnopqrs"; // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^ + String variableNameWithCredentialInIt = "abcdefghijklmnopqrs"; // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + String variableNameWithAuthInIt = "abcdefghijklmnopqrs"; // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^ // Secrets with less than 2 characters, explicitly "anonymous", are ignored String variableNameWithSecretInItEmpty = ""; String variableNameWithSecretInItOneChar = "X"; @@ -231,7 +236,8 @@ private void a(char[] secret, String var) throws SQLException { myA.setProperty(new Object(), new Object()); myA.setProperty("secret", "secret"); // Compliant myA.setProperty("secret", "auth"); // Compliant - myA.setProperty("something", "else").setProperty("secret", "abcdefghijklmnopqrs"); // Noncompliant [[sc=42;ec=53]] + myA.setProperty("something", "else").setProperty("secret", "abcdefghijklmnopqrs"); // Noncompliant +// ^^^^^^^^^^^ } private char[] getSecret(String s) { diff --git a/java-checks-test-sources/default/src/main/java/checks/HardcodedIpCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/HardcodedIpCheckSample.java index 25e7729fe92..2ed92726b16 100644 --- a/java-checks-test-sources/default/src/main/java/checks/HardcodedIpCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/HardcodedIpCheckSample.java @@ -1,8 +1,10 @@ package checks; class HardcodedIpCheckSample { - String ip = "10.0.0.0"; // Noncompliant [[sc=15;ec=25]] {{Make sure using this hardcoded IP address is safe here.}} - String ipAndPort = "10.0.0.0:0"; // Noncompliant [[sc=22;ec=34]] {{Make sure using this hardcoded IP address is safe here.}} + String ip = "10.0.0.0"; // Noncompliant {{Make sure using this hardcoded IP address is safe here.}} +// ^^^^^^^^^^ + String ipAndPort = "10.0.0.0:0"; // Noncompliant {{Make sure using this hardcoded IP address is safe here.}} +// ^^^^^^^^^^^^ String url = "http://192.168.0.1/admin.html"; // Noncompliant {{Make sure using this hardcoded IP address is safe here.}} String urlWithPort = "http://192.168.0.1:8000/admin.html"; // Noncompliant {{Make sure using this hardcoded IP address is safe here.}} String url2 = "http://www.example.org"; diff --git a/java-checks-test-sources/default/src/main/java/checks/HardcodedURICheckSample.java b/java-checks-test-sources/default/src/main/java/checks/HardcodedURICheckSample.java index 94021e13337..1a3a30b5ec4 100644 --- a/java-checks-test-sources/default/src/main/java/checks/HardcodedURICheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/HardcodedURICheckSample.java @@ -31,16 +31,22 @@ void foo(String s, String var) throws URISyntaxException { new URI(s); // Compliant new File(s); // Compliant new File("", s); // Compliant - new File("", s + "/" + s); // Noncompliant [[sc=22;ec=25]] {{Remove this hard-coded path-delimiter.}} + new File("", s + "/" + s); // Noncompliant {{Remove this hard-coded path-delimiter.}} +// ^^^ new URI("http:https"); // Compliant - new URI("http://www.mywebsite.com"); // Noncompliant [[sc=13;ec=39]] {{Refactor your code to get this URI from a customizable parameter.}} - new File("/home/path/to/my/file.txt"); // Noncompliant [[sc=14;ec=41]] {{Refactor your code to get this URI from a customizable parameter.}} - new File(s, "~\\blah\\blah\\blah.txt"); // Noncompliant [[sc=17;ec=42]] {{Refactor your code to get this URI from a customizable parameter.}} - new File("/Folder/", s); // Noncompliant [[sc=14;ec=24]] {{Refactor your code to get this URI from a customizable parameter.}} + new URI("http://www.mywebsite.com"); // Noncompliant {{Refactor your code to get this URI from a customizable parameter.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^ + new File("/home/path/to/my/file.txt"); // Noncompliant {{Refactor your code to get this URI from a customizable parameter.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + new File(s, "~\\blah\\blah\\blah.txt"); // Noncompliant {{Refactor your code to get this URI from a customizable parameter.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^ + new File("/Folder/", s); // Noncompliant {{Refactor your code to get this URI from a customizable parameter.}} +// ^^^^^^^^^^ String filename; - String path = "/home/path/to/my/file.txt"; // Noncompliant [[sc=19;ec=46]] {{Refactor your code to get this URI from a customizable parameter.}} + String path = "/home/path/to/my/file.txt"; // Noncompliant {{Refactor your code to get this URI from a customizable parameter.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ String fileName = "\\\\blah\\blah\\"; // Noncompliant {{Refactor your code to get this URI from a customizable parameter.}} String fileNAME = s; // Compliant String stuff = "/home/path/to/my/file.txt"; // Compliant - requires a variable with adequate name @@ -48,7 +54,7 @@ void foo(String s, String var) throws URISyntaxException { stuffs[0] = "/home/path/to/my/file.txt"; // Compliant - require a variable with adequate name fileNAME = s + "//" + s; // Noncompliant {{Remove this hard-coded path-delimiter.}} - fileNAME = s + "\\\\" + s; // Noncompliant {{Remove this hard-coded path-delimiter.}}t + fileNAME = s + "\\\\" + s; // Noncompliant {{Remove this hard-coded path-delimiter.}} fileNAME = s + "hello" + s; // Compliant fileNAME = "c:\\blah\\blah\\blah.txt"; // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/HasNextCallingNextCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/HasNextCallingNextCheckSample.java index 18e1311eae9..524a1b91a65 100644 --- a/java-checks-test-sources/default/src/main/java/checks/HasNextCallingNextCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/HasNextCallingNextCheckSample.java @@ -8,7 +8,8 @@ class HasNextCallingNextCheckSample implements Iterator { public boolean hasNext() { boolean b = false; - b = next() != null; // Noncompliant [[sc=9;ec=13]] {{Refactor the implementation of this "Iterator.hasNext()" method to not call "Iterator.next()".}} + b = next() != null; // Noncompliant {{Refactor the implementation of this "Iterator.hasNext()" method to not call "Iterator.next()".}} +// ^^^^ b = this.next() != null; // Noncompliant b = other.next() != null; b = next("a") != null; diff --git a/java-checks-test-sources/default/src/main/java/checks/HiddenFieldCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/HiddenFieldCheckSample.java index b576e61dd5d..4d4d1057d3b 100644 --- a/java-checks-test-sources/default/src/main/java/checks/HiddenFieldCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/HiddenFieldCheckSample.java @@ -6,7 +6,8 @@ public class HiddenFieldCheckSample extends MyBaseClass { public int bar; { - int foo = this.foo; // Noncompliant [[sc=9;ec=12]] {{Rename "foo" which hides the field declared at line 5.}} + int foo = this.foo; // Noncompliant {{Rename "foo" which hides the field declared at line 5.}} +// ^^^ int ok = 0; // Compliant System.out.println(foo + ok); } @@ -58,7 +59,7 @@ public static class MyInnerClass { int myInnerClass1; public void foo() { - int bar = 0; // Noncompliant {{Rename "bar" which hides the field declared at line 57.}} + int bar = 0; // Noncompliant {{Rename "bar" which hides the field declared at line 58.}} System.out.println(bar); } @@ -150,5 +151,5 @@ static void foo() { class FieldWithLambda { Object p; - java.util.function.Consumer f = p -> { }; // Noncompliant {{Rename "p" which hides the field declared at line 152.}} + java.util.function.Consumer f = p -> { }; // Noncompliant {{Rename "p" which hides the field declared at line 153.}} } diff --git a/java-checks-test-sources/default/src/main/java/checks/IdenticalCasesInSwitchCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/IdenticalCasesInSwitchCheckSample.java index d951804c7cb..ac24e37d797 100644 --- a/java-checks-test-sources/default/src/main/java/checks/IdenticalCasesInSwitchCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/IdenticalCasesInSwitchCheckSample.java @@ -4,18 +4,21 @@ class IdenticalCasesInSwitchCheckSample { void foo(){ switch (1) { case 1: +// ^[el=+4;ec=14]> System.out.println("plop"); System.out.println("plop"); break; case 2: System.out.println("bar"); //Compliant break; - case 3: // Noncompliant [[sc=7;el=+4;ec=15;secondary=-7]] {{This case's code block is the same as the block for the case on line 6.}} + case 3: // Noncompliant {{This case's code block is the same as the block for the case on line 6.}} +// ^[el=+5;ec=14] 1 case 4: System.out.println("plop"); System.out.println("plop"); break; - case 5: // Noncompliant [[sc=7;el=+3;ec=15;secondary=-12]] {{This case's code block is the same as the block for the case on line 6.}} + case 5: // Noncompliant {{This case's code block is the same as the block for the case on line 6.}} +// ^[el=+4;ec=14] System.out.println("plop"); System.out.println("plop"); break; @@ -32,19 +35,23 @@ void foo(){ switch (1) { case 1: +// ^[el=+2;ec=18]> trivial(); - case 2: // Noncompliant [[secondary=-2]] + case 2: // Noncompliant + //^[el=+2;ec=18] 1 trivial(); } switch (1) { case 1: +// ^[el=+3;ec=14]> trivial(); break; - case 2: // Noncompliant [[secondary=-3]] + case 2: // Noncompliant + //^[el=+3;ec=14] 1 trivial(); break; - case 3: // Noncompliant [[secondary=-6]] + case 3: // Noncompliant trivial(); break; } @@ -138,6 +145,7 @@ void ifStatement() { } if (true) { + //^[el=+4;ec=5]> {{Original}} System.out.println("foo"); System.out.println("foo"); } else if (true) { @@ -146,10 +154,12 @@ void ifStatement() { // skip empty blocks } else if (true) { System.out.println("bar"); - } else if (true) { // Noncompliant [[sc=22;el=+3;ec=6;secondary=-9]] {{This branch's code block is the same as the block for the branch on line 140.}} + } else if (true) { // Noncompliant {{This branch's code block is the same as the block for the branch on line 147.}} +// ^[el=+4;ec=5] 1 System.out.println("foo"); System.out.println("foo"); - } else { // Noncompliant [[sc=12;el=+3;ec=6;secondary=-12]] {{This branch's code block is the same as the block for the branch on line 140.}} + } else { // Noncompliant {{This branch's code block is the same as the block for the branch on line 147.}} +// ^[ec=5;el=+4] System.out.println("foo"); System.out.println("foo"); } @@ -165,21 +175,26 @@ void ifStatement() { else f(); if (true) f(); - else if (true) f(); // Noncompliant [[secondary=-1]] - +// ^^^^> + else if (true) f(); // Noncompliant +// ^^^^ if (true) { +// ^[el=+4;ec=5]> f(); f(); } - else if (true) { // Noncompliant [[secondary=-4]] + else if (true) { // Noncompliant + // ^[el=+4;ec=5] 1 f(); f(); } else if (true) { +// ^[el=+4;ec=5]> g(); g(); } - else if (true) { // Noncompliant [[secondary=-4]] + else if (true) { // Noncompliant + // ^[el=+4;ec=5] g(); g(); } diff --git a/java-checks-test-sources/default/src/main/java/checks/IdenticalOperandOnBinaryExpression.java b/java-checks-test-sources/default/src/main/java/checks/IdenticalOperandOnBinaryExpression.java index 081056bdc38..ebdb4cee1e7 100644 --- a/java-checks-test-sources/default/src/main/java/checks/IdenticalOperandOnBinaryExpression.java +++ b/java-checks-test-sources/default/src/main/java/checks/IdenticalOperandOnBinaryExpression.java @@ -3,18 +3,22 @@ class IdenticalOperandOnBinaryExpressionCheck { void foo(boolean a, boolean b, boolean c, boolean e) { if(a == b) { } - if(a == a) { } // Noncompliant [[sc=13;ec=14;secondary=+0]] {{Correct one of the identical sub-expressions on both sides of operator "=="}} - if(a != a) { } // Noncompliant [[sc=13;ec=14]] {{Correct one of the identical sub-expressions on both sides of operator "!="}} + if(a == a) { } // Noncompliant {{Correct one of the identical sub-expressions on both sides of operator "=="}} +// ^> ^ + + if(a != a) { } // Noncompliant {{Correct one of the identical sub-expressions on both sides of operator "!="}} +// ^ if(a || a) { } // Noncompliant if(a && a) { } // Noncompliant - if(a == b || a == b) {} // Noncompliant [[sc=18;ec=24]] + if(a == b || a == b) {} // Noncompliant +// ^^^^^^ if(a || b || a) {} // Noncompliant if(a || a || b) {} // Noncompliant if(a || b || c || e && a) {} - if(a && b && c && e && a) {} // Noncompliant [[sc=28;ec=29]] - if(b - || a - || a) {} // Noncompliant [[sc=12;ec=13;secondary=-1]] + if(a && b && c && e && a) {} // Noncompliant +// ^> ^ + if(b || a || a) {} // Noncompliant +// ^ double d = 0.0d; float f = 0.0f; @@ -28,7 +32,7 @@ void foo(boolean a, boolean b, boolean c, boolean e) { } void fun(Object a, Object b) { - a.equals(a); // Noncompliant {{Correct one of the identical sub-expressions on both sides of equals.}} + a.equals(a); // Noncompliant {{Correct one of the identical sub-expressions on both sides of equals.}} a.equals(b); equals(a); java.util.Objects.equals(a, a); // Noncompliant {{Correct one of the identical argument sub-expressions.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/IgnoredStreamReturnValueCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/IgnoredStreamReturnValueCheckSample.java index 50c73ac6b05..c29361a59ed 100644 --- a/java-checks-test-sources/default/src/main/java/checks/IgnoredStreamReturnValueCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/IgnoredStreamReturnValueCheckSample.java @@ -11,7 +11,8 @@ public void foo() throws Exception { byte[] buffer = new byte[1000]; long skipValue = 12L; - is.read(buffer); // Noncompliant [[sc=10;ec=14]] {{Check the return value of the "read" call to see how many bytes were read.}} + is.read(buffer); // Noncompliant {{Check the return value of the "read" call to see how many bytes were read.}} +// ^^^^ is.skip(skipValue); // Noncompliant getInputStream().read(buffer); // Noncompliant getInputStream().skip(skipValue); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/ImmediateReverseBoxingCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ImmediateReverseBoxingCheckSample.java index 8be9f49e17f..f31ac070b46 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ImmediateReverseBoxingCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ImmediateReverseBoxingCheckSample.java @@ -6,14 +6,17 @@ public void processInt(String s, int a) {} public void processInteger(String s, Integer... a) {} void intBoxingAndUnboxing(int int1, Integer integer1, String string, Double double1) { - new Integer(int1).intValue(); // Noncompliant [[sc=5;ec=22]] {{Remove the boxing of "int1".}} - new Integer(1 + 2).intValue(); // Noncompliant [[sc=5;ec=23]] {{Remove the boxing to "Integer".}} + new Integer(int1).intValue(); // Noncompliant {{Remove the boxing of "int1".}} +// ^^^^^^^^^^^^^^^^^ + new Integer(1 + 2).intValue(); // Noncompliant {{Remove the boxing to "Integer".}} +// ^^^^^^^^^^^^^^^^^^ Integer.valueOf(int1).intValue(); // Noncompliant Integer.valueOf(1 + 2).intValue(); // Noncompliant processInt(string, new Integer(int1)); // Noncompliant new Integer(int1).toString(); integer1.intValue(); - Integer.valueOf(integer1); // Noncompliant [[sc=5;ec=20]] {{Remove the boxing to "Integer"; The argument is already of the same type.}} + Integer.valueOf(integer1); // Noncompliant {{Remove the boxing to "Integer"; The argument is already of the same type.}} +// ^^^^^^^^^^^^^^^ Double.valueOf(double1); // Noncompliant {{Remove the boxing to "Double"; The argument is already of the same type.}} Long.valueOf(integer1); // Compliant int int2 = new Integer(1); // Noncompliant {{Remove the boxing to "Integer".}} @@ -25,7 +28,8 @@ void intBoxingAndUnboxing(int int1, Integer integer1, String string, Double doub void intUnboxingAndBoxing(int int1, Integer integer1, String string, Number number) { new Integer(integer1.intValue()); // Noncompliant {{Remove the unboxing of "integer1".}} - new Integer(integer1); // Noncompliant [[sc=9;ec=16]] {{Remove the boxing to "Integer"; The argument is already of the same type.}} + new Integer(integer1); // Noncompliant {{Remove the boxing to "Integer"; The argument is already of the same type.}} +// ^^^^^^^ new Long(integer1); // Compliant new Integer(int1); new Integer(string.length()); @@ -65,58 +69,70 @@ void otherThanInts(byte b, double d, float f, long l, short s, char c) { void quickFixes(int int1, Integer integer1, Double double1, double doublePrimitive) { // Visit METHOD_INVOCATION // valueOf - checkForUnboxing - Double.valueOf(double1.doubleValue()); // Noncompliant [[sc=20;ec=41;quickfixes=qf1]] {{Remove the unboxing of "double1".}} + Double.valueOf(double1.doubleValue()); // Noncompliant {{Remove the unboxing of "double1".}} [[quickfixes=qf1]] +// ^^^^^^^^^^^^^^^^^^^^^ // fix@qf1 {{Remove the unboxing}} // edit@qf1 [[sc=27;ec=41]] {{}} // valueOf - checkForUselessUnboxing - Double.valueOf(double1); // Noncompliant [[sc=5;ec=19;quickfixes=qf2]] + Double.valueOf(double1); // Noncompliant [[quickfixes=qf2]] +// ^^^^^^^^^^^^^^ // fix@qf2 {{Remove the boxing}} // edit@qf2 [[sc=5;ec=20]] {{}} // edit@qf2 [[sc=27;ec=28]] {{}} // isUnboxingMethodInvocation - checkForBoxing - new Integer(int1).intValue(); // Noncompliant [[sc=5;ec=22;quickfixes=qf3]] + new Integer(int1).intValue(); // Noncompliant [[quickfixes=qf3]] +// ^^^^^^^^^^^^^^^^^ // fix@qf3 {{Remove the boxing}} // edit@qf3 [[sc=5;ec=17]] {{}} // edit@qf3 [[sc=21;ec=33]] {{}} - Integer.valueOf(int1).intValue(); // Noncompliant [[sc=5;ec=26;quickfixes=qf4]] + Integer.valueOf(int1).intValue(); // Noncompliant [[quickfixes=qf4]] +// ^^^^^^^^^^^^^^^^^^^^^ // fix@qf4 {{Remove the boxing}} // edit@qf4 [[sc=5;ec=21]] {{}} // edit@qf4 [[sc=25;ec=37]] {{}} // else, checkMethodInvocationArguments - examineInt(Integer.valueOf(int1)); // Noncompliant [[sc=16;ec=37;quickfixes=qf5]] + examineInt(Integer.valueOf(int1)); // Noncompliant [[quickfixes=qf5]] +// ^^^^^^^^^^^^^^^^^^^^^ // fix@qf5 {{Remove the boxing}} // edit@qf5 [[sc=16;ec=32]] {{}} // edit@qf5 [[sc=36;ec=37]] {{}} - examineInteger(integer1.intValue()); // Noncompliant [[sc=20;ec=39;quickfixes=qf6]] + examineInteger(integer1.intValue()); // Noncompliant [[quickfixes=qf6]] +// ^^^^^^^^^^^^^^^^^^^ // fix@qf6 {{Remove the unboxing}} // edit@qf6 [[sc=28;ec=39]] {{}} // Visit VARIABLE - double d1 = Double.valueOf(doublePrimitive); // Noncompliant [[sc=17;ec=48;quickfixes=qf7]] + double d1 = Double.valueOf(doublePrimitive); // Noncompliant [[quickfixes=qf7]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf7 {{Remove the boxing}} // edit@qf7 [[sc=17;ec=32]] {{}} // edit@qf7 [[sc=47;ec=48]] {{}} - Double d2 = double1.doubleValue(); // Noncompliant [[sc=17;ec=38;quickfixes=qf8]] + Double d2 = double1.doubleValue(); // Noncompliant [[quickfixes=qf8]] +// ^^^^^^^^^^^^^^^^^^^^^ // fix@qf8 {{Remove the unboxing}} // edit@qf8 [[sc=24;ec=38]] {{}} // Visit ASSIGNMENT - d1 = Double.valueOf(doublePrimitive); // Noncompliant [[sc=10;ec=41;quickfixes=qf9]] + d1 = Double.valueOf(doublePrimitive); // Noncompliant [[quickfixes=qf9]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf9 {{Remove the boxing}} // edit@qf9 [[sc=10;ec=25]] {{}} // edit@qf9 [[sc=40;ec=41]] {{}} - d2 = double1.doubleValue(); // Noncompliant [[sc=10;ec=31;quickfixes=qf10]] + d2 = double1.doubleValue(); // Noncompliant [[quickfixes=qf10]] +// ^^^^^^^^^^^^^^^^^^^^^ // fix@qf10 {{Remove the unboxing}} // edit@qf10 [[sc=17;ec=31]] {{}} // Visit NEW_CLASS - new Integer(integer1.intValue()); // Noncompliant [[sc=17;ec=36;quickfixes=qf11]] + new Integer(integer1.intValue()); // Noncompliant [[quickfixes=qf11]] +// ^^^^^^^^^^^^^^^^^^^ // fix@qf11 {{Remove the unboxing}} // edit@qf11 [[sc=25;ec=36]] {{}} - new Integer(integer1); // Noncompliant [[sc=9;ec=16;quickfixes=qf12]] + new Integer(integer1); // Noncompliant [[quickfixes=qf12]] +// ^^^^^^^ // fix@qf12 {{Remove the boxing}} // edit@qf12 [[sc=5;ec=17]] {{}} // edit@qf12 [[sc=25;ec=26]] {{}} diff --git a/java-checks-test-sources/default/src/main/java/checks/ImmediatelyReturnedVariableCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ImmediatelyReturnedVariableCheckSample.java index e295bf130b1..e2f73f63f72 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ImmediatelyReturnedVariableCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ImmediatelyReturnedVariableCheckSample.java @@ -65,34 +65,38 @@ Object SuppressWarnings() { } public long testQuickFixes(long hours, long minutes, long seconds) { - long duration = (((hours * 60) + minutes) * 60 + seconds ) * 1000; // Noncompliant [[sc=21;ec=70;quickfixes=qf1]] + long duration = (((hours * 60) + minutes) * 60 + seconds ) * 1000; // Noncompliant [[quickfixes=qf1]] return duration; +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^@-1 // fix@qf1 {{Inline expression}} // edit@qf1 [[sc=5;ec=21]] {{return }} // edit@qf1 [[sc=71;el=+1;ec=21]] {{}} } public long testQuickFixesWithSpaces(long hours, long minutes, long seconds) { - long duration = (((hours * 60) + minutes) * 60 + seconds ) * 1000; // Noncompliant [[sc=21;ec=70;quickfixes=qf2]] + long duration = (((hours * 60) + minutes) * 60 + seconds ) * 1000; // Noncompliant [[quickfixes=qf2]] return duration; +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^@-3 // fix@qf2 {{Inline expression}} // edit@qf2 [[sc=5;ec=21]] {{return }} // edit@qf2 [[sc=71;el=+3;ec=21]] {{}} } public long testQuickFixesThrow() { - RuntimeException myException = new RuntimeException(); // Noncompliant [[sc=36;ec=58;quickfixes=qf3]] + RuntimeException myException = new RuntimeException(); // Noncompliant [[quickfixes=qf3]] throw myException; +// ^^^^^^^^^^^^^^^^^^^^^^@-1 // fix@qf3 {{Inline expression}} // edit@qf3 [[sc=5;ec=36]] {{throw }} // edit@qf3 [[sc=59;el=+1;ec=23]] {{}} } public long testQuickFixesWithFinalVariable(long hours) { - final long duration = hours * 60; // Noncompliant [[sc=27;ec=37;quickfixes=qf4]] + final long duration = hours * 60; // Noncompliant [[quickfixes=qf4]] return duration; +// ^^^^^^^^^^@-1 // fix@qf4 {{Inline expression}} // edit@qf4 [[sc=5;ec=27]] {{return }} // edit@qf4 [[sc=38;el=+1;ec=21]] {{}} @@ -100,8 +104,9 @@ public long testQuickFixesWithFinalVariable(long hours) { public long testQuickFixesInitOnNextLine(long hours) { final long duration = - hours * 60; // Noncompliant [[sc=7;ec=17;quickfixes=qf5]] + hours * 60; // Noncompliant [[quickfixes=qf5]] return duration; +// ^^^^^^^^^^@-1 // fix@qf5 {{Inline expression}} // edit@qf5 [[sl=-1;sc=5;ec=7]] {{return }} // edit@qf5 [[sc=18;el=+1;ec=21]] {{}} diff --git a/java-checks-test-sources/default/src/main/java/checks/ImplementsEnumerationCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ImplementsEnumerationCheckSample.java index d4c64008798..baeaf9e49af 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ImplementsEnumerationCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ImplementsEnumerationCheckSample.java @@ -4,7 +4,8 @@ import java.util.Iterator; class S1150_A implements S1150_Foo, - Enumeration, // Noncompliant [[sc=20;ec=31]] {{Implement Iterator rather than Enumeration.}} + Enumeration, // Noncompliant {{Implement Iterator rather than Enumeration.}} +// ^^^^^^^^^^^ Iterable { @Override public Iterator iterator() { return null; } diff --git a/java-checks-test-sources/default/src/main/java/checks/InappropriateRegexpCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/InappropriateRegexpCheckSample.java index 4d1e6f6ceb1..7d6f288bd5e 100644 --- a/java-checks-test-sources/default/src/main/java/checks/InappropriateRegexpCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/InappropriateRegexpCheckSample.java @@ -7,18 +7,24 @@ class InappropriateRegexpCheckSample { private static final String MY_REGEX = "."; void replaceAll() { - "".replaceAll(".", ""); // Noncompliant [[sc=19;ec=22]] {{Correct this regular expression.}} - "".replaceAll("|", "_");// Noncompliant [[sc=19;ec=22]] {{Correct this regular expression.}} - "".replaceAll(File.separator, ""); // Noncompliant [[sc=19;ec=33]] {{Correct this regular expression.}} + "".replaceAll(".", ""); // Noncompliant {{Correct this regular expression.}} +// ^^^ + "".replaceAll("|", "_"); // Noncompliant {{Correct this regular expression.}} +// ^^^ + "".replaceAll(File.separator, ""); // Noncompliant {{Correct this regular expression.}} +// ^^^^^^^^^^^^^^ "".replaceAll("\\.", ""); "".replaceAll("\\|", ""); "".replaceAll(MY_REGEX, ""); // Noncompliant } void replaceFirst() { - "".replaceFirst(".", ""); // Noncompliant [[sc=21;ec=24]] {{Correct this regular expression.}} - "".replaceFirst("|", "_");// Noncompliant [[sc=21;ec=24]] {{Correct this regular expression.}} - "".replaceFirst(File.separator, ""); // Noncompliant [[sc=21;ec=35]] {{Correct this regular expression.}} + "".replaceFirst(".", ""); // Noncompliant {{Correct this regular expression.}} +// ^^^ + "".replaceFirst("|", "_"); // Noncompliant {{Correct this regular expression.}} +// ^^^ + "".replaceFirst(File.separator, ""); // Noncompliant {{Correct this regular expression.}} +// ^^^^^^^^^^^^^^ "".replaceFirst("\\.", ""); "".replaceFirst("\\|", ""); } diff --git a/java-checks-test-sources/default/src/main/java/checks/IncorrectOrderOfMembersCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/IncorrectOrderOfMembersCheckSample.java index b295df016d8..eee115b9c2e 100644 --- a/java-checks-test-sources/default/src/main/java/checks/IncorrectOrderOfMembersCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/IncorrectOrderOfMembersCheckSample.java @@ -5,14 +5,16 @@ class FieldAfterConstructor { FieldAfterConstructor() { } - int field; // Noncompliant [[sc=9;ec=14]] {{Move this variable to comply with Java Code Conventions.}} + int field; // Noncompliant {{Move this variable to comply with Java Code Conventions.}} +// ^^^^^ } class ConstructorAfterMethod { void method() { } - ConstructorAfterMethod() { // Noncompliant [[sc=5;ec=27]] + ConstructorAfterMethod() { // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^ } } @@ -28,9 +30,11 @@ void method() { static class WrongVariablesOrdering { boolean locked; - private static String MESSAGE = "Static variables should be declared before instance variables"; // Noncompliant [[sc=27;ec=34]] {{Move this static variable to comply with Java Code Conventions.}} + private static String MESSAGE = "Static variables should be declared before instance variables"; // Noncompliant {{Move this static variable to comply with Java Code Conventions.}} +// ^^^^^^^ public int current; - protected static int counter = 0;// Noncompliant [[sc=26;ec=33]] {{Move this static variable to comply with Java Code Conventions.}} + protected static int counter = 0; // Noncompliant {{Move this static variable to comply with Java Code Conventions.}} +// ^^^^^^^ } // The visibility of variables is not taken into account diff --git a/java-checks-test-sources/default/src/main/java/checks/IndentationAfterConditionalCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/IndentationAfterConditionalCheckSample.java index d05b5a9ae11..8752f527cc6 100644 --- a/java-checks-test-sources/default/src/main/java/checks/IndentationAfterConditionalCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/IndentationAfterConditionalCheckSample.java @@ -7,13 +7,17 @@ class IndentationAfterConditionalCheckSample { public int foo() throws IOException { int i = 0; - if (i <= 1) // Noncompliant [[sc=5;ec=16;secondary=11]] {{Use indentation to denote the code conditionally executed by this "if".}} + if (i <= 1) // Noncompliant {{Use indentation to denote the code conditionally executed by this "if".}} +// ^^^^^^^^^^^ i = 1; +// ^^^^^^< i++; - if(i > 0) // Noncompliant [[sc=5;ec=14;secondary=16]] + if(i > 0) // Noncompliant +// ^^^^^^^^^ // ...... doTheOtherThing(); +// ^^^^^^^^^^^^^^^^^^< //..... doTheThing(); @@ -29,43 +33,47 @@ public int foo() throws IOException { if (i == 0) return 1; - if(i <= 11) // Noncompliant [[sc=5;ec=16;secondary=33]] + if(i <= 11) // Noncompliant +// ^^^^^^^^^^^ doTheThing(); +// ^^^^^^^^^^^^^< doTheOtherThing(); somethingElseEntirely(); if (i != 0) i++; - if(i <= 1) // Noncompliant + if(i <= 1) // Noncompliant i=1; i++; - if(i==10) // Noncompliant + if(i==10) // Noncompliant i=10; if (i == 5) // Noncompliant doTheThing(); - else if(i == 6) // Noncompliant + else if(i == 6) // Noncompliant somethingElseEntirely(); - else // Noncompliant + else // Noncompliant doTheThing(); doTheOtherThing(); - if(i == 0) // Noncompliant + if(i == 0) // Noncompliant doTheThing(); - else // Noncompliant [sc=7;ec=11;secondary=59] {{Use indentation to denote the code conditionally executed by this "else".}} + else // Noncompliant {{Use indentation to denote the code conditionally executed by this "else".}} doTheOtherThing(); if(i > 10) i =100; i++; - for (; i <= 1;) // Noncompliant [[sc=5;ec=20;secondary=68]] {{Use indentation to denote the code conditionally executed by this "for".}} + for (; i <= 1;) // Noncompliant {{Use indentation to denote the code conditionally executed by this "for".}} +// ^^^^^^^^^^^^^^^ i = 1; +// ^^^^^^< i++; for (; i <= 1;) { // Compliant @@ -84,34 +92,44 @@ else if(i == 6) // Noncompliant i += 10; } - while(i<=11) // Noncompliant [[sc=5;ec=17;secondary=88]] {{Use indentation to denote the code conditionally executed by this "while".}} + while(i<=11) // Noncompliant {{Use indentation to denote the code conditionally executed by this "while".}} +// ^^^^^^^^^^^^ i++; +// ^^^^< i+=10; List l=null; for(Integer ii : l) // Compliant return i; - for(Integer ii : l) // Noncompliant [[sc=5;ec=24;secondary=96]] {{Use indentation to denote the code conditionally executed by this "for".}} + for(Integer ii : l) // Noncompliant {{Use indentation to denote the code conditionally executed by this "for".}} +// ^^^^^^^^^^^^^^^^^^^ i=1; +// ^^^^< i=2; - for(Integer ii : l) // Noncompliant [[sc=5;ec=24;secondary=100]] {{Use indentation to denote the code conditionally executed by this "for".}} - if(ii == 1) // Noncompliant [[sc=4;ec=15;secondary=101] {{Use indentation to denote the code conditionally executed by this "if".}} + for(Integer ii : l) // Noncompliant {{Use indentation to denote the code conditionally executed by this "for".}} +// ^^^^^^^^^^^^^^^^^^^ + if(ii == 1) // Noncompliant {{Use indentation to denote the code conditionally executed by this "if".}} +// [^[el=+2;ec=7]< i++; i=2; - if(i ==1) // Noncompliant + if(i ==1) // Noncompliant i++; else i++; - for(i =0;i<10;i++) // Noncompliant [[sc=5;ec=23;secondary=110]] {{Use indentation to denote the code conditionally executed by this "for".}} + for(i =0;i<10;i++) // Noncompliant {{Use indentation to denote the code conditionally executed by this "for".}} +// ^^^^^^^^^^^^^^^^^^ if(i==1) +//^[el=+2;ec=8]< i++; if(i == 1) // Compliant - if(i == 2) // Noncompliant [[sc=7;ec=17;secondary=114]] {{Use indentation to denote the code conditionally executed by this "if".}} + if(i == 2) // Noncompliant {{Use indentation to denote the code conditionally executed by this "if".}} +// ^^^^^^^^^^ i++; +// ^^^^< i+=2; if(i == 0) @@ -120,13 +138,18 @@ else if(i == 1) i = 1; else if(i ==3) return i; - else // Noncompliant [[sc=5;ec=9;secondary=124]] {{Use indentation to denote the code conditionally executed by this "else".}} + else // Noncompliant {{Use indentation to denote the code conditionally executed by this "else".}} +// ^^^^ i=1; +// ^^^^< while(i<=0) - for(;i<10;) // Noncompliant [[sc=7;ec=18;secondary=128]] {{Use indentation to denote the code conditionally executed by this "for".}} - if(i<1) // Noncompliant [[sc=6;ec=13;secondary=129]] {{Use indentation to denote the code conditionally executed by this "if".}} + for(;i<10;) // Noncompliant {{Use indentation to denote the code conditionally executed by this "for".}} +// ^^^^^^^^^^^ + if(i<1) // Noncompliant {{Use indentation to denote the code conditionally executed by this "if".}} +// ^^^^^^^ return 2; +// ^^^^^^^^^< if(i == 1) return i; @@ -136,12 +159,14 @@ else if(i ==3) } while(i>1) - if(i==1) // Noncompliant + if(i==1) // Noncompliant return i; if (i < 2) { - if ((i > 0) && (i > 3)) // Noncompliant [[sc=7;ec=30;secondary=144]] {{Use indentation to denote the code conditionally executed by this "if".}} + if ((i > 0) && (i > 3)) // Noncompliant {{Use indentation to denote the code conditionally executed by this "if".}} +// ^^^^^^^^^^^^^^^^^^^^^^^ return i; +// ^^^^^^^^^< return 1; } @@ -152,13 +177,13 @@ else if(i ==3) while (n < len) { int count = System.in.read(b, off + n, len - n); - if (count < 0) // Noncompliant + if (count < 0) // Noncompliant throw new EOFException(); n += count; } if(true) { - if(i ==1) // Noncompliant + if(i ==1) // Noncompliant return 1; } if(i==0) @@ -168,8 +193,10 @@ else if(i==1) i++; else i++; - else if(i ==2) // Noncompliant [[sc=5;ec=19;secondary=172]] {{Use indentation to denote the code conditionally executed by this "if".}} + else if(i ==2) // Noncompliant {{Use indentation to denote the code conditionally executed by this "if".}} +// ^^^^^^^^^^^^^^ i+=2; +// ^^^^^< else if(i==1) return 1; diff --git a/java-checks-test-sources/default/src/main/java/checks/IndentationCheck_custom.java b/java-checks-test-sources/default/src/main/java/checks/IndentationCheck_custom.java index 081e64f477d..323475f543f 100644 --- a/java-checks-test-sources/default/src/main/java/checks/IndentationCheck_custom.java +++ b/java-checks-test-sources/default/src/main/java/checks/IndentationCheck_custom.java @@ -5,28 +5,28 @@ import java.util.stream.IntStream; class FooIdentation { - int a; // Noncompliant {{Make this line start after 4 spaces instead of 2 in order to indent the code consistently. (Indentation level is at 4.)}} + int a; // Noncompliant {{Make this line start after 4 spaces instead of 2 in order to indent the code consistently. (Indentation level is at 4.)}} int b; // Compliant - already reported int c; // Compliant - already reported public void foo1() { // Compliant - System.out.println(); // Noncompliant {{Make this line start after 8 spaces instead of 4 in order to indent the code consistently. (Indentation level is at 4.)}} + System.out.println(); // Noncompliant {{Make this line start after 8 spaces instead of 4 in order to indent the code consistently. (Indentation level is at 4.)}} } // Compliant public void foo2() { // Compliant - System.out.println("hehe"); // Noncompliant + System.out.println("hehe"); // Noncompliant System.out.println(); // Compliant - already reported } public void foo3() { // Compliant -System.out.println(); // Noncompliant +System.out.println(); // Noncompliant System.out.println(); // Compliant - already reported System.out.println(); // Compliant if (true) { // Compliant - System.out.println(); // Noncompliant {{Make this line start after 12 spaces instead of 2 in order to indent the code consistently. (Indentation level is at 4.)}} + System.out.println(); // Noncompliant {{Make this line start after 12 spaces instead of 2 in order to indent the code consistently. (Indentation level is at 4.)}} if (true) { // Compliant - System.out.println(); // Noncompliant {{Make this line start after 16 spaces instead of 8 in order to indent the code consistently. (Indentation level is at 4.)}} + System.out.println(); // Noncompliant {{Make this line start after 16 spaces instead of 8 in order to indent the code consistently. (Indentation level is at 4.)}} System.out.println(); // Compliant } @@ -34,11 +34,11 @@ public void foo3() { // Compliant } } - class Foo { // Noncompliant {{Make this line start after 4 spaces instead of 2 in order to indent the code consistently. (Indentation level is at 4.)}} + class Foo { // Noncompliant {{Make this line start after 4 spaces instead of 2 in order to indent the code consistently. (Indentation level is at 4.)}} int a; // Compliant - int b; // Noncompliant {{Make this line start after 8 spaces instead of 2 in order to indent the code consistently. (Indentation level is at 4.)}} + int b; // Noncompliant {{Make this line start after 8 spaces instead of 2 in order to indent the code consistently. (Indentation level is at 4.)}} } } @@ -48,7 +48,7 @@ enum BarIdentation { B, C; - public void foo1() { // Noncompliant {{Make this line start after 4 spaces instead of 2 in order to indent the code consistently. (Indentation level is at 4.)}} + public void foo1() { // Noncompliant {{Make this line start after 4 spaces instead of 2 in order to indent the code consistently. (Indentation level is at 4.)}} } public void foo2() { // Compliant @@ -57,7 +57,7 @@ public void foo2() { // Compliant interface QixIdentation { - void foo1(); // Noncompliant + void foo1(); // Noncompliant void foo2(); // Compliant @@ -65,11 +65,11 @@ interface QixIdentation { class BazIdentation { - void foo() { // Noncompliant {{Make this line start after 4 spaces instead of 2 in order to indent the code consistently. (Indentation level is at 4.)}} - new QixIdentation() { // Noncompliant {{Make this line start after 8 spaces instead of 4 in order to indent the code consistently. (Indentation level is at 4.)}} + void foo() { // Noncompliant {{Make this line start after 4 spaces instead of 2 in order to indent the code consistently. (Indentation level is at 4.)}} + new QixIdentation() { // Noncompliant {{Make this line start after 8 spaces instead of 4 in order to indent the code consistently. (Indentation level is at 4.)}} public void foo1() { // Compliant } - public void foo2() { // Noncompliant + public void foo2() { // Noncompliant } }; } @@ -81,9 +81,9 @@ public void foo2() { // Noncompliant } - class QizIndentation { // Noncompliant - public void foo(int foo) { // Noncompliant - switch (0) { // Noncompliant + class QizIndentation { // Noncompliant + public void foo(int foo) { // Noncompliant + switch (0) { // Noncompliant case 0: System.out.println(); System.out.println(); // Noncompliant break; @@ -100,7 +100,7 @@ public void foo(int foo) { // Noncompliant case 1: case 2: case 3: - break; // Noncompliant + break; // Noncompliant } switch (foo) { @@ -113,15 +113,15 @@ public void foo(int foo) { // Noncompliant static { try{ // Noncompliant {{Make this line start after 8 spaces instead of 4 in order to indent the code consistently. (Indentation level is at 4.)}} while (list.isEmpty()) { // Noncompliant {{Make this line start after 12 spaces instead of 7 in order to indent the code consistently. (Indentation level is at 4.)}} - int s = list.get(0); // Noncompliant {{Make this line start after 16 spaces instead of 8 in order to indent the code consistently. (Indentation level is at 4.)}} + int s = list.get(0); // Noncompliant {{Make this line start after 16 spaces instead of 8 in order to indent the code consistently. (Indentation level is at 4.)}} String k = "hello"; } } catch (NoSuchElementException e) { } } } @interface Example { - public static class Inner { // Noncompliant {{Make this line start after 4 spaces instead of 2 in order to indent the code consistently. (Indentation level is at 4.)}} - public static final String FOO = "foo"; // Noncompliant {{Make this line start after 8 spaces instead of 4 in order to indent the code consistently. (Indentation level is at 4.)}} + public static class Inner { // Noncompliant {{Make this line start after 4 spaces instead of 2 in order to indent the code consistently. (Indentation level is at 4.)}} + public static final String FOO = "foo"; // Noncompliant {{Make this line start after 8 spaces instead of 4 in order to indent the code consistently. (Indentation level is at 4.)}} } } diff --git a/java-checks-test-sources/default/src/main/java/checks/IndentationCheck_tab.java b/java-checks-test-sources/default/src/main/java/checks/IndentationCheck_tab.java index 910285d06fe..e3f9812ed1c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/IndentationCheck_tab.java +++ b/java-checks-test-sources/default/src/main/java/checks/IndentationCheck_tab.java @@ -2,7 +2,7 @@ class IndentationCheck_tab { int a; // Compliant - int b; // Noncompliant {{Make this line start after 2 spaces instead of 4 in order to indent the code consistently. (Indentation level is at 2.)}} + int b; // Noncompliant {{Make this line start after 2 spaces instead of 4 in order to indent the code consistently. (Indentation level is at 2.)}} int c; // Compliant - already reported void foo() { diff --git a/java-checks-test-sources/default/src/main/java/checks/IndexOfWithPositiveNumber.java b/java-checks-test-sources/default/src/main/java/checks/IndexOfWithPositiveNumber.java index 261deadb4bf..9138bed52fe 100644 --- a/java-checks-test-sources/default/src/main/java/checks/IndexOfWithPositiveNumber.java +++ b/java-checks-test-sources/default/src/main/java/checks/IndexOfWithPositiveNumber.java @@ -44,7 +44,8 @@ void method(int length, List strings, int literal3) { if ("".indexOf("") > -1) { // Compliant } - if ("".indexOf(' ') > 0) { // Noncompliant [[sc=9;ec=28]] {{0 is a valid index, but is ignored by this check.}} + if ("".indexOf(' ') > 0) { // Noncompliant {{0 is a valid index, but is ignored by this check.}} +// ^^^^^^^^^^^^^^^^^^^ } if ("".indexOf(" ") > 0) { // Noncompliant {{0 is a valid index, but is ignored by this check.}} } diff --git a/java-checks-test-sources/default/src/main/java/checks/InnerClassOfNonSerializableCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/InnerClassOfNonSerializableCheckSample.java index 0503d120c59..4a841b6181f 100644 --- a/java-checks-test-sources/default/src/main/java/checks/InnerClassOfNonSerializableCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/InnerClassOfNonSerializableCheckSample.java @@ -13,16 +13,19 @@ class X1 implements Serializable {} class InnerClassOfNonSerializableCheckSampleB { - Serializable Anon = new Serializable() {}; // Noncompliant [[sc=27;ec=39]] {{Make this inner class static}} + Serializable Anon = new Serializable() {}; // Noncompliant {{Make this inner class static}} +// ^^^^^^^^^^^^ class B1 {} class B2 implements Cloneable {} - class B3 implements Serializable {} // Noncompliant [[sc=9;ec=11]]{{Make this inner class static}} + class B3 implements Serializable {} // Noncompliant {{Make this inner class static}} +// ^^ class B4 extends B3 {} static class B5 implements Serializable {} void nonStaticMethod() { - class X1 implements Serializable {} // Noncompliant [[sc=11;ec=13]] {{Make "nonStaticMethod" static}} + class X1 implements Serializable {} // Noncompliant {{Make "nonStaticMethod" static}} +// ^^ Object o = new X1(){}; } diff --git a/java-checks-test-sources/default/src/main/java/checks/InnerClassOfSerializableCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/InnerClassOfSerializableCheckSample.java index df842098d83..d33bf6d7b48 100644 --- a/java-checks-test-sources/default/src/main/java/checks/InnerClassOfSerializableCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/InnerClassOfSerializableCheckSample.java @@ -15,12 +15,14 @@ class InnerClassOfSerializableCheckSampleB implements Serializable { class B1 {} class B2 implements Cloneable {} - class B3 implements Serializable {} // Noncompliant [[sc=9;ec=11]] {{Make this inner class static}} + class B3 implements Serializable {} // Noncompliant {{Make this inner class static}} +// ^^ class B4 extends B3 {} static class B5 implements Serializable {} void nonStaticMethod() { - class X1 implements Serializable {} // Noncompliant [[sc=11;ec=13]] {{Make "nonStaticMethod" static}} + class X1 implements Serializable {} // Noncompliant {{Make "nonStaticMethod" static}} +// ^^ Object o = new X1(){}; } diff --git a/java-checks-test-sources/default/src/main/java/checks/InsecureCreateTempFileCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/InsecureCreateTempFileCheckSample.java index f806ae429f9..84c834a8fd1 100644 --- a/java-checks-test-sources/default/src/main/java/checks/InsecureCreateTempFileCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/InsecureCreateTempFileCheckSample.java @@ -37,7 +37,7 @@ private void noncompliant() throws IOException { File tempDir; tempDir = (File.createTempFile("", ".")); tempDir.delete(); - tempDir.mkdir(); // Noncompliant {{Use "Files.createTempDirectory" to create this directory instead.}} + tempDir.mkdir(); // Noncompliant {{Use "Files.createTempDirectory" to create this directory instead.}} File tempDir2 = File.createTempFile("", "."); tempDir2.delete(); tempDir2.mkdir(); // Noncompliant @@ -50,7 +50,7 @@ private void noncompliant() throws IOException { private void noncompliant() throws IOException { b = File.createTempFile("", "."); b.delete(); - b.mkdir(); // Noncompliant + b.mkdir(); // Noncompliant } }; diff --git a/java-checks-test-sources/default/src/main/java/checks/InsecureCreateTempFileCheck_no_version.java b/java-checks-test-sources/default/src/main/java/checks/InsecureCreateTempFileCheck_no_version.java index 396ff3433c4..4ecdeb7f676 100644 --- a/java-checks-test-sources/default/src/main/java/checks/InsecureCreateTempFileCheck_no_version.java +++ b/java-checks-test-sources/default/src/main/java/checks/InsecureCreateTempFileCheck_no_version.java @@ -37,7 +37,8 @@ private void noncompliant() throws IOException { File tempDir; tempDir = (File.createTempFile("", ".")); tempDir.delete(); - tempDir.mkdir(); // Noncompliant [[sc=13;ec=18]] {{Use "Files.createTempDirectory" to create this directory instead. (sonar.java.source not set. Assuming 7 or greater.)}} + tempDir.mkdir(); // Noncompliant {{Use "Files.createTempDirectory" to create this directory instead. (sonar.java.source not set. Assuming 7 or greater.)}} +// ^^^^^ File tempDir2 = File.createTempFile("", "."); tempDir2.delete(); tempDir2.mkdir(); // Noncompliant @@ -50,7 +51,7 @@ private void noncompliant() throws IOException { private void noncompliant() throws IOException { b = File.createTempFile("", "."); b.delete(); - b.mkdir(); // Noncompliant + b.mkdir(); // Noncompliant } }; diff --git a/java-checks-test-sources/default/src/main/java/checks/InstanceOfPatternMatching.java b/java-checks-test-sources/default/src/main/java/checks/InstanceOfPatternMatching.java index 24ddcc41bd8..b3862541c96 100644 --- a/java-checks-test-sources/default/src/main/java/checks/InstanceOfPatternMatching.java +++ b/java-checks-test-sources/default/src/main/java/checks/InstanceOfPatternMatching.java @@ -5,8 +5,10 @@ public abstract class InstanceOfPatternMatching { int if1(Object o) { - if (o instanceof String) { // Noncompliant {{Replace this instanceof check and cast with 'instanceof String str'}} [[secondary=+1]] + if (o instanceof String) { // Noncompliant {{Replace this instanceof check and cast with 'instanceof String str'}} +// ^^^^^^^^^^^^^^^^^^^ String str = (String) o; +// ^^^^^^^^^^< return str.length(); } return 0; @@ -20,18 +22,22 @@ int if1Compliant(Object o) { } int if2(Object o) { - if (1 > 2 && o instanceof String && 3 > 4) { // Noncompliant {{Replace this instanceof check and cast with 'instanceof String str'}} [[secondary=+2]] + if (1 > 2 && o instanceof String && 3 > 4) { // Noncompliant {{Replace this instanceof check and cast with 'instanceof String str'}} +// ^^^^^^^^^^^^^^^^^^^ System.out.println("holla"); String str = (String) o; +// ^^^^^^^^^^< return str.length(); } return 0; } int if3(Object o) { - if (o instanceof String) { // Noncompliant {{Replace this instanceof check and cast with 'instanceof String str'}} [[secondary=+2]] + if (o instanceof String) { // Noncompliant {{Replace this instanceof check and cast with 'instanceof String str'}} +// ^^^^^^^^^^^^^^^^^^^ if (23 < 42) { String str = (String) o; +// ^^^^^^^^^^< return str.length(); } } @@ -40,8 +46,10 @@ int if3(Object o) { Object o; int if4() { - if (o instanceof String) { // Noncompliant {{Replace this instanceof check and cast with 'instanceof String str'}} [[secondary=+1]] + if (o instanceof String) { // Noncompliant {{Replace this instanceof check and cast with 'instanceof String str'}} +// ^^^^^^^^^^^^^^^^^^^ String str = (String) o; +// ^^^^^^^^^^< return str.length(); } return 0; @@ -57,8 +65,10 @@ int if4Compliant() { } int if5(Map map) { - if (map.get("hello") instanceof String) { // Noncompliant {{Replace this instanceof check and cast with 'instanceof String str'}} [[secondary=+1]] + if (map.get("hello") instanceof String) { // Noncompliant {{Replace this instanceof check and cast with 'instanceof String str'}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ String str = (String) map.get("hello"); +// ^^^^^^^^^^^^^^^^^^^^^^^^^< return str.length(); } return 0; @@ -75,9 +85,11 @@ int if5Compliant(Map map) { int if16(Object o) { // Since the assignment of the cast happens separately from the variable declaration, we don't use the variable name // in the error message - if (o instanceof String) { // Noncompliant {{Replace this instanceof check and cast with 'instanceof String string'}} [[secondary=+2]] + if (o instanceof String) { // Noncompliant {{Replace this instanceof check and cast with 'instanceof String string'}} +// ^^^^^^^^^^^^^^^^^^^ String str; str = (String) o; +// ^^^^^^^^^^< return str.length(); } return 0; @@ -119,9 +131,11 @@ int if10(Object o) { int ifElse1(Object o) { - if (!(o instanceof String)) { // Noncompliant {{Replace this instanceof check and cast with 'instanceof String str'}} [[secondary=+2]] + if (!(o instanceof String)) { // Noncompliant {{Replace this instanceof check and cast with 'instanceof String str'}} +// ^^^^^^^^^^^^^^^^^^^ } else { String str = (String) o; +// ^^^^^^^^^^< return str.length(); } return 0; @@ -137,9 +151,11 @@ int ifElse2(Object o) { } int ifElse3(Object o) { - if (!(o instanceof String || 1 < 2)) { // Noncompliant {{Replace this instanceof check and cast with 'instanceof String str'}} [[secondary=+2]] + if (!(o instanceof String || 1 < 2)) { // Noncompliant {{Replace this instanceof check and cast with 'instanceof String str'}} +// ^^^^^^^^^^^^^^^^^^^ } else { String str = (String) o; +// ^^^^^^^^^^< return str.length(); } return 0; @@ -164,16 +180,20 @@ int ifElse5(Object o) { } int ifElse6(Object o) { - if (!!!(o instanceof String)) { // Noncompliant {{Replace this instanceof check and cast with 'instanceof String str'}} [[secondary=+2]] + if (!!!(o instanceof String)) { // Noncompliant {{Replace this instanceof check and cast with 'instanceof String str'}} +// ^^^^^^^^^^^^^^^^^^^ } else { String str = (String) o; +// ^^^^^^^^^^< return str.length(); } return 0; } boolean and1(Object o) { - return (o instanceof String && ((String) o).length() > 0); // Noncompliant {{Replace this instanceof check and cast with 'instanceof String string'}} [[secondary=+0]] + return (o instanceof String && ((String) o).length() > 0); // Noncompliant {{Replace this instanceof check and cast with 'instanceof String string'}} +// ^^^^^^^^^^^^^^^^^^^ +// ^^^^^^^^^^@-1< } boolean and1Compliant(Object o) { @@ -181,7 +201,9 @@ boolean and1Compliant(Object o) { } boolean and2(Object o) { - return (1 < 4 && o instanceof String && ((String) o).length() > 0 && 23 < 42); // Noncompliant {{Replace this instanceof check and cast with 'instanceof String string'}} [[secondary=+0]] + return (1 < 4 && o instanceof String && ((String) o).length() > 0 && 23 < 42); // Noncompliant {{Replace this instanceof check and cast with 'instanceof String string'}} +// ^^^^^^^^^^^^^^^^^^^ +// ^^^^^^^^^^@-1< } boolean and3(Object o) { @@ -189,7 +211,9 @@ boolean and3(Object o) { } boolean or1(Object o) { - return (!(o instanceof String) || ((String) o).length() > 0); // Noncompliant {{Replace this instanceof check and cast with 'instanceof String string'}} [[secondary=+0]] + return (!(o instanceof String) || ((String) o).length() > 0); // Noncompliant {{Replace this instanceof check and cast with 'instanceof String string'}} +// ^^^^^^^^^^^^^^^^^^^ +// ^^^^^^^^^^@-1< } boolean or2(Object o) { @@ -198,7 +222,9 @@ boolean or2(Object o) { int ternary(Object o) { - return (o instanceof String) ? ((String) o).length() : 0; // Noncompliant {{Replace this instanceof check and cast with 'instanceof String string'}} [[secondary=+0]] + return (o instanceof String) ? ((String) o).length() : 0; // Noncompliant {{Replace this instanceof check and cast with 'instanceof String string'}} +// ^^^^^^^^^^^^^^^^^^^ +// ^^^^^^^^^^@-1< } int ternaryCompliant(Object o) { @@ -209,8 +235,10 @@ int ternaryCompliant(Object o) { void whileLoop1() { Object o = getNext(); - while (o instanceof String) { // Noncompliant {{Replace this instanceof check and cast with 'instanceof String str'}} [[secondary=+1]] + while (o instanceof String) { // Noncompliant {{Replace this instanceof check and cast with 'instanceof String str'}} +// ^^^^^^^^^^^^^^^^^^^ String str = (String) o; +// ^^^^^^^^^^< o = getNext(); } } @@ -232,8 +260,10 @@ void whileLoop3() { } void forLoop1() { - for (Object o = getNext(); o instanceof String; o = getNext()) { // Noncompliant {{Replace this instanceof check and cast with 'instanceof String str'}} [[secondary=+1]] + for (Object o = getNext(); o instanceof String; o = getNext()) { // Noncompliant {{Replace this instanceof check and cast with 'instanceof String str'}} +// ^^^^^^^^^^^^^^^^^^^ String str = (String) o; +// ^^^^^^^^^^< } } diff --git a/java-checks-test-sources/default/src/main/java/checks/InstanceofUsedOnExceptionCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/InstanceofUsedOnExceptionCheckSample.java index e0c4fc227bd..28d2acd550c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/InstanceofUsedOnExceptionCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/InstanceofUsedOnExceptionCheckSample.java @@ -26,7 +26,8 @@ private void withEalseIf() { private void f(MyException foo) { try { } catch (Exception e) { - if (e instanceof IOException) {} // Noncompliant [[sc=13;ec=23]] {{Replace the usage of the "instanceof" operator by a catch block.}} + if (e instanceof IOException) {} // Noncompliant {{Replace the usage of the "instanceof" operator by a catch block.}} +// ^^^^^^^^^^ } try { } catch (Exception e) { @@ -140,7 +141,7 @@ private void withElseIf() { private void withThrow() throws IllegalAccessException { try { } catch (Exception e) { - if (e instanceof IOException) {// Noncompliant + if (e instanceof IOException) { // Noncompliant throw new IllegalAccessException(""); } throw e; @@ -166,7 +167,7 @@ private void withThrow() throws IllegalAccessException { private int withReturn() { try { } catch (Exception e) { - if (e instanceof IOException) {// Noncompliant + if (e instanceof IOException) { // Noncompliant return 1; } return 2; diff --git a/java-checks-test-sources/default/src/main/java/checks/InterfaceAsConstantContainerCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/InterfaceAsConstantContainerCheckSample.java index bc193cdf6fe..8a0372cf015 100644 --- a/java-checks-test-sources/default/src/main/java/checks/InterfaceAsConstantContainerCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/InterfaceAsConstantContainerCheckSample.java @@ -3,9 +3,12 @@ interface InterfaceAsConstantContainerCheckSample { } -interface InterfaceAsConstantContainerCheckSampleA { // Noncompliant [[sc=11;ec=51;secondary=7,8]] {{Move constants defined in this interfaces to another class or enum.}} +interface InterfaceAsConstantContainerCheckSampleA { // Noncompliant {{Move constants defined in this interfaces to another class or enum.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ int a = 0; +// ^< int b = 0; +// ^< } interface InterfaceAsConstantContainerCheckSampleB { diff --git a/java-checks-test-sources/default/src/main/java/checks/InterfaceOrSuperclassShadowingCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/InterfaceOrSuperclassShadowingCheckSample.java index ce4e7cafcda..99954f19d66 100644 --- a/java-checks-test-sources/default/src/main/java/checks/InterfaceOrSuperclassShadowingCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/InterfaceOrSuperclassShadowingCheckSample.java @@ -11,16 +11,18 @@ class MyFile extends java.io.File { public MyFile(String pathname) { super(pathname); } } -class File extends java.io.File { // Noncompliant {{Rename this class.}} +class File extends java.io.File { // Noncompliant {{Rename this class.}} public File(String pathname) { super(pathname); } } abstract class MySerializable implements java.io.Serializable {} -abstract class Serializable implements java.io.Serializable {} // Noncompliant [[sc=16;ec=28]] {{Rename this class.}} +abstract class Serializable implements java.io.Serializable {} // Noncompliant {{Rename this class.}} +// ^^^^^^^^^^^^ abstract class MyFlushable implements java.io.Flushable {} abstract class Flushable extends MyFlushable {} -record Function () implements java.util.function.Function { // Noncompliant [[sc=8;ec=16]] {{Rename this record.}} +record Function () implements java.util.function.Function { // Noncompliant {{Rename this record.}} +// ^^^^^^^^ @Override public Object apply(Object t) { return null; } } diff --git a/java-checks-test-sources/default/src/main/java/checks/InterruptedExceptionCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/InterruptedExceptionCheckSample.java index e32b0f87140..d264419b1c0 100644 --- a/java-checks-test-sources/default/src/main/java/checks/InterruptedExceptionCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/InterruptedExceptionCheckSample.java @@ -24,7 +24,8 @@ public void run1 () { } }catch (java.io.IOException e) { LOGGER.log(Level.WARN, "Interrupted!", e); - }catch (InterruptedException e) { // Noncompliant [[sc=13;ec=35]] {{Either re-interrupt this method or rethrow the "InterruptedException" that can be caught here.}} + }catch (InterruptedException e) { // Noncompliant {{Either re-interrupt this method or rethrow the "InterruptedException" that can be caught here.}} +// ^^^^^^^^^^^^^^^^^^^^^^ LOGGER.log(Level.WARN, "Interrupted!", e); } } @@ -48,7 +49,8 @@ public void catchUnionType () { if (LOGGER != null) throw new IOException(""); throw new InterruptedException(""); } - } catch (InterruptedException | java.io.IOException e) { // Noncompliant [[sc=14;ec=58]] {{Either re-interrupt this method or rethrow the "InterruptedException" that can be caught here.}} + } catch (InterruptedException | java.io.IOException e) { // Noncompliant {{Either re-interrupt this method or rethrow the "InterruptedException" that can be caught here.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ LOGGER.log(Level.WARN, "Interrupted!", e); } } @@ -117,7 +119,7 @@ private static void cancelAllSubTasksAndInterrupt(Set subTasks) { private static void waitForNextExecution1(Set running, LongSupplier waitTimeoutMillis) { try { Thread.sleep(waitTimeoutMillis.getAsLong()); - } catch (InterruptedException e) { // Noncompliant, too many levels + } catch (InterruptedException e) { // Noncompliant cancelAllSubTasksAndInterrupt1(running); } } @@ -145,14 +147,18 @@ private static void cancelAllSubTasksAndInterrupt4(Set subTasks) { public void catchGenericException() throws InterruptedException { try { throwsInterruptedException(); - } catch (Exception e) { // Noncompliant [[sc=14;ec=25;secondary=-1]] {{Either re-interrupt this method or rethrow the "InterruptedException" that can be caught here.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^> + } catch (Exception e) { // Noncompliant {{Either re-interrupt this method or rethrow the "InterruptedException" that can be caught here.}} +// ^^^^^^^^^^^ LOGGER.log(Level.WARN, "Interrupted!", e); } try { throwsInterruptedException(); +// ^^^^^^^^^^^^^^^^^^^^^^^^^^> throwsException(); - } catch (Exception e) { // Noncompliant [[sc=14;ec=25;secondary=-2]] + } catch (Exception e) { // Noncompliant +// ^^^^^^^^^^^ LOGGER.log(Level.WARN, "Interrupted!", e); } @@ -222,7 +228,7 @@ public void throwNewInterruptedExceptionFromCatch() throws InterruptedException try { throwsInterruptedException(); - } catch (InterruptedException e) { // Noncompliant, RuntimeException is not an InterruptedException + } catch (InterruptedException e) { // Noncompliant throw new RuntimeException(); } } @@ -242,7 +248,7 @@ public void catchSubtypeOfInterruptedException() throws InterruptedException { try { throwsInterruptedException(); - } catch (CustomizedInterruptedException e) { // Noncompliant, RuntimeException is not an InterruptedException + } catch (CustomizedInterruptedException e) { // Noncompliant throw new RuntimeException(); } } @@ -269,7 +275,7 @@ public void throwNewInterruptedExceptionFromFunction() throws InterruptedExcepti try { throwsInterruptedException(); - } catch (CustomizedInterruptedException e) { // Noncompliant, too many levels + } catch (CustomizedInterruptedException e) { // Noncompliant interruptByThrowingInterruptedExceptionL1(); } } @@ -295,7 +301,7 @@ public void throwNewCustomizedInterruptedExceptionFromFunction() throws Interrup try { throwsInterruptedException(); - } catch (InterruptedException e) { // Noncompliant, too many levels + } catch (InterruptedException e) { // Noncompliant interruptByThrowingCustomizedInterruptedExceptionL1(); } } @@ -311,7 +317,7 @@ public void rethrowSameException() throws InterruptedException { RuntimeException re = new RuntimeException(); try { throwsInterruptedException(); - } catch (InterruptedException e) { // Noncompliant, re is not e + } catch (InterruptedException e) { // Noncompliant doSomething(); throw re; } @@ -325,7 +331,7 @@ public void rethrowSameException() throws InterruptedException { try { throwsInterruptedException(); - } catch (InterruptedException e) { // Noncompliant, a RuntimeException is thrown. + } catch (InterruptedException e) { // Noncompliant doSomething(); throw getRuntimeException(); } @@ -340,7 +346,7 @@ public void rethrowSameException() throws InterruptedException { public void cutControlFlow() throws InterruptedException { try { throwsInterruptedException(); - } catch (InterruptedException e) { // Noncompliant, because neither foo nor bar belong to the control flow of this catch block. + } catch (InterruptedException e) { // Noncompliant Object instance = new Object() { void foo() { @@ -355,7 +361,7 @@ void bar() throws InterruptedException { try { throwsInterruptedException(); - } catch (InterruptedException e) { // Noncompliant, because neither foo, nor bar belong to the control flow of this catch block. + } catch (InterruptedException e) { // Noncompliant Runnable foo = () -> Thread.currentThread().interrupt(); Action bar = () -> { throw new InterruptedException(); @@ -390,7 +396,7 @@ void falsePositivesSonarjava4406() { try { try { throwsInterruptedException(); - } catch (InterruptedException ie) { // Noncompliant, because interruption state is lost. + } catch (InterruptedException ie) { // Noncompliant } } catch (Exception e) { // Compliant, because inner try does not throw an InterruptedException } @@ -410,7 +416,7 @@ void falsePositivesSonarjava4406() { } catch (InterruptedException ie) { // Compliant throw new InterruptedException(); } - } catch (Exception e) { // Noncompliant, because inner try throws an InterruptedException + } catch (Exception e) { // Noncompliant } try { @@ -419,7 +425,7 @@ void falsePositivesSonarjava4406() { } catch (InterruptedException ie) { // Compliant throw new InterruptedException(); } - } catch (InterruptedException e) { // Noncompliant, because explicitly catch InterruptedException + } catch (InterruptedException e) { // Noncompliant } try { @@ -427,7 +433,7 @@ void falsePositivesSonarjava4406() { throwsInterruptedException(); } catch (RuntimeException ie) { // Compliant } - } catch (Exception e) { // Noncompliant, because inner try may throw an InterruptedException + } catch (Exception e) { // Noncompliant } } diff --git a/java-checks-test-sources/default/src/main/java/checks/InvalidDateValuesCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/InvalidDateValuesCheckSample.java index 10d4765cf5e..d6f0b7e7f05 100644 --- a/java-checks-test-sources/default/src/main/java/checks/InvalidDateValuesCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/InvalidDateValuesCheckSample.java @@ -11,9 +11,12 @@ class InvalidDateValuesCheckSample { int foo() { Date d = new Date(); d.setDate(25); - d.setDate(32);// Noncompliant [[sc=15;ec=17]] {{"32" is not a valid value for "setDate" method.}} - d.setDate(0);// Noncompliant [[sc=15;ec=16]] {{"0" is not a valid value for "setDate" method.}} - d.setDate(-1);// Noncompliant [[sc=15;ec=17]] {{"-1" is not a valid value for "setDate" method.}} + d.setDate(32); // Noncompliant {{"32" is not a valid value for "setDate" method.}} +// ^^ + d.setDate(0); // Noncompliant {{"0" is not a valid value for "setDate" method.}} +// ^ + d.setDate(-1); // Noncompliant {{"-1" is not a valid value for "setDate" method.}} +// ^^ d.setYear(2014); d.setMonth(11); d.setMonth(12); // Noncompliant {{"12" is not a valid value for "setMonth" method.}} @@ -22,42 +25,43 @@ int foo() { d.setMinutes(59); d.setMinutes(61); // Noncompliant {{"61" is not a valid value for "setMinutes" method.}} d.setSeconds(61); - d.setSeconds(63);// Noncompliant {{"63" is not a valid value for "setSeconds" method.}} - d.setSeconds(-1);// Noncompliant {{"-1" is not a valid value for "setSeconds" method.}} + d.setSeconds(63); // Noncompliant {{"63" is not a valid value for "setSeconds" method.}} + d.setSeconds(-1); // Noncompliant {{"-1" is not a valid value for "setSeconds" method.}} java.sql.Date d1 = new java.sql.Date(0L); d1.setHours(23); d1.setHours(24); // Noncompliant {{"24" is not a valid value for "setHours" method.}} d1.setMinutes(59); - d1.setMinutes(61);// Noncompliant {{"61" is not a valid value for "setMinutes" method.}} + d1.setMinutes(61); // Noncompliant {{"61" is not a valid value for "setMinutes" method.}} d1.setSeconds(61); - d1.setSeconds(63);// Noncompliant {{"63" is not a valid value for "setSeconds" method.}} + d1.setSeconds(63); // Noncompliant {{"63" is not a valid value for "setSeconds" method.}} Calendar cal = Calendar.getInstance(); cal.set(Calendar.MONTH, 11); - cal.set(Calendar.MONTH, 12);// Noncompliant {{"12" is not a valid value for setting "MONTH".}} - cal.set(MONTH, 12);// Noncompliant {{"12" is not a valid value for setting "MONTH".}} + cal.set(Calendar.MONTH, 12); // Noncompliant {{"12" is not a valid value for setting "MONTH".}} + cal.set(MONTH, 12); // Noncompliant {{"12" is not a valid value for setting "MONTH".}} cal.set(2, 12);// literal arguments aren't supported cal.set(Calendar.DAY_OF_MONTH, 11); - cal.set(Calendar.DAY_OF_MONTH, 32);// Noncompliant {{"32" is not a valid value for setting "DAY_OF_MONTH".}} + cal.set(Calendar.DAY_OF_MONTH, 32); // Noncompliant {{"32" is not a valid value for setting "DAY_OF_MONTH".}} cal.set(Calendar.HOUR_OF_DAY, 11); - cal.set(Calendar.HOUR_OF_DAY, 24);// Noncompliant {{"24" is not a valid value for setting "HOUR_OF_DAY".}} + cal.set(Calendar.HOUR_OF_DAY, 24); // Noncompliant {{"24" is not a valid value for setting "HOUR_OF_DAY".}} cal.set(Calendar.MINUTE, 59); - cal.set(Calendar.MINUTE, 61);// Noncompliant {{"61" is not a valid value for setting "MINUTE".}} + cal.set(Calendar.MINUTE, 61); // Noncompliant {{"61" is not a valid value for setting "MINUTE".}} cal.set(InvalidDateValuesCheckSample.MINUTE, 61);// support only Calendar members cal.set(Calendar.SECOND, 61); - cal.set(Calendar.SECOND, 63);// Noncompliant {{"63" is not a valid value for setting "SECOND".}} - cal.set(Calendar.HOUR_OF_DAY, -2);// Noncompliant {{"-2" is not a valid value for setting "HOUR_OF_DAY".}} + cal.set(Calendar.SECOND, 63); // Noncompliant {{"63" is not a valid value for setting "SECOND".}} + cal.set(Calendar.HOUR_OF_DAY, -2); // Noncompliant {{"-2" is not a valid value for setting "HOUR_OF_DAY".}} GregorianCalendar gc = new GregorianCalendar(); gc = new GregorianCalendar(2015, 11, 31); gc = new GregorianCalendar(2015, 12, 31); // Noncompliant {{"12" is not a valid value for setting "month".}} gc = new GregorianCalendar(2015, 11, 31); gc = new GregorianCalendar(2015, 11, 32); // Noncompliant {{"32" is not a valid value for setting "dayOfMonth".}} gc = new GregorianCalendar(2015, 11, 31, 23, 59); - gc = new GregorianCalendar(2015, 11, 31, 24, 60); // Noncompliant [[sc=46;ec=48]] {{"24" is not a valid value for setting "hourOfDay".}} + gc = new GregorianCalendar(2015, 11, 31, 24, 60); // Noncompliant {{"24" is not a valid value for setting "hourOfDay".}} +// ^^ gc = new GregorianCalendar(2015, 11, 31, 23, 59); gc = new GregorianCalendar(2015, 11, 31, 23, 61); // Noncompliant {{"61" is not a valid value for setting "minute".}} gc = new GregorianCalendar(2015, 11, 31, 23, 59, 61); gc = new GregorianCalendar(2015, 11, 31, 23, 59, 63); // Noncompliant {{"63" is not a valid value for setting "second".}} - // Noncompliant@+1 + // Noncompliant@+1 gc = new GregorianCalendar(2015, -1, 31, 23, 59, +63); // Noncompliant gc = new GregorianCalendar(2015, -foo(), 31, 23, 59, 63); // Noncompliant {{"63" is not a valid value for setting "second".}} @@ -74,7 +78,7 @@ int foo() { b = 32 == d.getDate(); // Noncompliant {{"32" is not a valid value for "getDate".}} b = -1 == d.getDate(); // Noncompliant {{"-1" is not a valid value for "getDate".}} b = 0 == d.getDate(); // Noncompliant {{"0" is not a valid value for "getDate".}} - b = d1.getSeconds() == -1;// Noncompliant {{"-1" is not a valid value for "getSeconds".}} + b = d1.getSeconds() == -1; // Noncompliant {{"-1" is not a valid value for "getSeconds".}} b = cal.get(Calendar.DST_OFFSET) == 0; return 0; } diff --git a/java-checks-test-sources/default/src/main/java/checks/IsInstanceMethodCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/IsInstanceMethodCheckSample.java index 8b66a161699..fa69b2000d7 100644 --- a/java-checks-test-sources/default/src/main/java/checks/IsInstanceMethodCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/IsInstanceMethodCheckSample.java @@ -2,7 +2,8 @@ public class IsInstanceMethodCheckSample { int noncompliant1(Object o) { - if (String.class.isInstance(o)) { // Noncompliant [[sc=9;ec=35]]{{Replace this usage of "String.class.isInstance()" with "instanceof String".}} + if (String.class.isInstance(o)) { // Noncompliant {{Replace this usage of "String.class.isInstance()" with "instanceof String".}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^ return 42; } return 0; @@ -17,7 +18,7 @@ int noncompliant2(Number n) { } - if (String.class.isInstance(n)) { // Noncompliant + if (String.class.isInstance(n)) { // Noncompliant return 42; } return 0; diff --git a/java-checks-test-sources/default/src/main/java/checks/IteratorNextExceptionCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/IteratorNextExceptionCheckSample.java index be76533554a..d9a235e1f50 100644 --- a/java-checks-test-sources/default/src/main/java/checks/IteratorNextExceptionCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/IteratorNextExceptionCheckSample.java @@ -9,7 +9,8 @@ class IteratorNextExceptionCheckSampleA implements Iterator { - public String next() { // Noncompliant [[sc=17;ec=21]] {{Add a "NoSuchElementException" for iteration beyond the end of the collection.}} + public String next() { // Noncompliant {{Add a "NoSuchElementException" for iteration beyond the end of the collection.}} +// ^^^^ if (!hasNext()){ return null; } diff --git a/java-checks-test-sources/default/src/main/java/checks/JacksonDeserializationCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/JacksonDeserializationCheckSample.java index 226e35c9c1c..b41a4cb40e7 100644 --- a/java-checks-test-sources/default/src/main/java/checks/JacksonDeserializationCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/JacksonDeserializationCheckSample.java @@ -10,12 +10,14 @@ class JacksonDeserializationCheckSample { public void enableDefaultTyping() { ObjectMapper mapper = new ObjectMapper(); - mapper.enableDefaultTyping(); // Noncompliant [[sc=5;ec=33]] {{Make sure using this Jackson deserialization configuration is safe here.}} + mapper.enableDefaultTyping(); // Noncompliant {{Make sure using this Jackson deserialization configuration is safe here.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } } -@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) // Noncompliant [[sc=21;ec=42]] {{Make sure using this Jackson deserialization configuration is safe here.}} +@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) // Noncompliant {{Make sure using this Jackson deserialization configuration is safe here.}} +// ^^^^^^^^^^^^^^^^^^^^^ abstract class JacksonDeserializationPhoneNumber { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) // Noncompliant {{Make sure using this Jackson deserialization configuration is safe here.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/JdbcDriverExplicitLoadingCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/JdbcDriverExplicitLoadingCheckSample.java index fa0f21c62af..b01e0d70fd9 100644 --- a/java-checks-test-sources/default/src/main/java/checks/JdbcDriverExplicitLoadingCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/JdbcDriverExplicitLoadingCheckSample.java @@ -4,7 +4,8 @@ class JdbcDriverExplicitLoadingCheckSample { private static final String DRIVER = "com.mysql.jdbc.Driver"; void doStuff() throws ClassNotFoundException { - Class.forName("org.h2.Driver"); // Noncompliant [[sc=11;ec=18]] {{Remove this "Class.forName()", it is useless.}} + Class.forName("org.h2.Driver"); // Noncompliant {{Remove this "Class.forName()", it is useless.}} +// ^^^^^^^ Class.forName("com.mysql.jdbc.Driver"); // Noncompliant Class.forName("oracle.jdbc.driver.OracleDriver"); // Noncompliant Class.forName("com.ibm.db2.jdbc.app.DB2Driver"); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/JdbcDriverExplicitLoadingCheck_no_version.java b/java-checks-test-sources/default/src/main/java/checks/JdbcDriverExplicitLoadingCheck_no_version.java index b6c24dbbcdf..4c17e1ad72d 100644 --- a/java-checks-test-sources/default/src/main/java/checks/JdbcDriverExplicitLoadingCheck_no_version.java +++ b/java-checks-test-sources/default/src/main/java/checks/JdbcDriverExplicitLoadingCheck_no_version.java @@ -2,7 +2,8 @@ class JdbcDriverExplicitLoadingCheck_no_version { void doStuff() throws ClassNotFoundException { - Class.forName("org.h2.Driver"); // Noncompliant [[sc=11;ec=18]] {{Remove this "Class.forName()", it is useless. (sonar.java.source not set. Assuming 6 or greater.)}} + Class.forName("org.h2.Driver"); // Noncompliant {{Remove this "Class.forName()", it is useless. (sonar.java.source not set. Assuming 6 or greater.)}} +// ^^^^^^^ Class.forName("java.lang.String"); } } diff --git a/java-checks-test-sources/default/src/main/java/checks/JpaEagerFetchTypeCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/JpaEagerFetchTypeCheckSample.java index 21fbcb349ed..ee5ac5557e0 100644 --- a/java-checks-test-sources/default/src/main/java/checks/JpaEagerFetchTypeCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/JpaEagerFetchTypeCheckSample.java @@ -22,7 +22,8 @@ private enum CustomFetchType { FetchType foo() default FetchType.LAZY; } - @Basic(fetch = FetchType.EAGER) // Noncompliant [[sc=28;ec=33]] {{Use lazy fetching instead.}} + @Basic(fetch = FetchType.EAGER) // Noncompliant {{Use lazy fetching instead.}} +// ^^^^^ private String foo; @javax.persistence.Basic(fetch = javax.persistence.FetchType.EAGER) // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/KeySetInsteadOfEntrySet.java b/java-checks-test-sources/default/src/main/java/checks/KeySetInsteadOfEntrySet.java index 457b7ffc8ab..5b21cf7e8d2 100644 --- a/java-checks-test-sources/default/src/main/java/checks/KeySetInsteadOfEntrySet.java +++ b/java-checks-test-sources/default/src/main/java/checks/KeySetInsteadOfEntrySet.java @@ -66,7 +66,8 @@ public void method() { for (String key4 : this.keySet()) { // Noncompliant {{Iterate over the "entrySet" instead of the "keySet".}} Object value = this.get(key4); } - for (String key5 : super.keySet()) { // Noncompliant [[sc=5;ec=8]] {{Iterate over the "entrySet" instead of the "keySet".}} + for (String key5 : super.keySet()) { // Noncompliant {{Iterate over the "entrySet" instead of the "keySet".}} +// ^^^ Object value = super.get(key5); } for (String key5 : map.keySet()) { // Noncompliant {{Iterate over the "entrySet" instead of the "keySet".}} diff --git a/java-checks-test-sources/default/src/main/java/checks/LabelsShouldNotBeUsedCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/LabelsShouldNotBeUsedCheckSample.java index a3456f10d12..bfb50d39ba5 100644 --- a/java-checks-test-sources/default/src/main/java/checks/LabelsShouldNotBeUsedCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/LabelsShouldNotBeUsedCheckSample.java @@ -8,7 +8,8 @@ void foo() { {7, 8, 9} }; - outer: for (int row = 0; row < matrix.length; row++) { // Noncompliant [[sc=7;ec=12]] {{Refactor the code to remove this label and the need for it.}} + outer: for (int row = 0; row < matrix.length; row++) { // Noncompliant {{Refactor the code to remove this label and the need for it.}} +// ^^^^^ for (int col = 0; col < matrix[row].length; col++) { if (col == row) { continue outer; diff --git a/java-checks-test-sources/default/src/main/java/checks/LambdaTooBigCheckCustom.java b/java-checks-test-sources/default/src/main/java/checks/LambdaTooBigCheckCustom.java index b0c7cb1f9e6..a62057d7cb3 100644 --- a/java-checks-test-sources/default/src/main/java/checks/LambdaTooBigCheckCustom.java +++ b/java-checks-test-sources/default/src/main/java/checks/LambdaTooBigCheckCustom.java @@ -12,7 +12,8 @@ private void f() { return 1; }; - Callable c1 = () -> { // Noncompliant [[sc=28;ec=33;secondary=22]] {{Reduce this lambda expression number of lines from 8 to at most 6.}} + Callable c1 = () -> { // Noncompliant {{Reduce this lambda expression number of lines from 8 to at most 6.}} +// ^^^^^ System.out.println(); System.out.println(); System.out.println(); @@ -20,16 +21,19 @@ private void f() { System.out.println(); return 1; }; +// ^< Callable c2 = () -> 1 + 2; - Callable c3 = () -> 1 + 2 + // Noncompliant [[sc=28;ec=33;secondary=32]] {{Reduce this lambda expression number of lines from 7 to at most 6.}} + Callable c3 = () -> 1 + 2 + // Noncompliant {{Reduce this lambda expression number of lines from 7 to at most 6.}} +// ^^^^^ 2 + 3 * 4 + 5 + 3 + 1 + 1; +// ^< Runnable r2 = () -> System.out.println("Hello world two!"); diff --git a/java-checks-test-sources/default/src/main/java/checks/LambdaTooBigCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/LambdaTooBigCheckSample.java index a3bffcdf1b0..f221a112385 100644 --- a/java-checks-test-sources/default/src/main/java/checks/LambdaTooBigCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/LambdaTooBigCheckSample.java @@ -4,7 +4,8 @@ class LambdaTooBigCheckSampleA { - Callable c1 = () -> { // Noncompliant [[sc=26;ec=31;secondary=17]] {{Reduce this lambda expression number of lines from 11 to at most 10.}} + Callable c1 = () -> { // Noncompliant {{Reduce this lambda expression number of lines from 11 to at most 10.}} +// ^^^^^ System.out.println(); System.out.println(); System.out.println(); @@ -15,6 +16,7 @@ class LambdaTooBigCheckSampleA { System.out.println(); return 1; }; +//^< Callable c2 = () -> { System.out.println(); diff --git a/java-checks-test-sources/default/src/main/java/checks/LazyArgEvaluationCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/LazyArgEvaluationCheckSample.java index d0a3b2641e2..1aa680860a0 100644 --- a/java-checks-test-sources/default/src/main/java/checks/LazyArgEvaluationCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/LazyArgEvaluationCheckSample.java @@ -30,7 +30,7 @@ String age(String age) { logger.log(Level.SEVERE, "Something went wrong: " + person.name()); // false-negative getter has not the same logic than identifier logger.log(Level.SEVERE, person.name()); // Compliant - getters are OK logger.log(Level.SEVERE, person.age()); // Compliant - getters are OK - logger.log(Level.SEVERE, person.age("12")); // Noncompliant - not a getter + logger.log(Level.SEVERE, person.age("12")); // Noncompliant } public static void main(String[] args) { @@ -38,17 +38,17 @@ public static void main(String[] args) { logger.log(Level.SEVERE, message); // Compliant - logger.log(Level.SEVERE, "Something went wrong: " + message); // Noncompliant {{Use the built-in formatting to construct this argument.}} + logger.log(Level.SEVERE, "Something went wrong: " + message); // Noncompliant {{Use the built-in formatting to construct this argument.}} logger.log(Level.SEVERE, () -> "Something went wrong: " + message); // since Java 8, we can use Supplier , which will be evaluated lazily - checkState(System.currentTimeMillis() == new Date().getTime(), "Arg must be positive, but got " + System.currentTimeMillis()); // Noncompliant {{Invoke method(s) only conditionally. Use the built-in formatting to construct this argument.}} + checkState(System.currentTimeMillis() == new Date().getTime(), "Arg must be positive, but got " + System.currentTimeMillis()); // Noncompliant {{Invoke method(s) only conditionally. Use the built-in formatting to construct this argument.}} - Preconditions.checkState(System.currentTimeMillis() > 0, formatMessage()); // Noncompliant {{Invoke method(s) only conditionally. }} + Preconditions.checkState(System.currentTimeMillis() > 0, formatMessage()); // Noncompliant {{Invoke method(s) only conditionally. }} - checkState(System.currentTimeMillis() > 0, "message: %s", formatMessage()); // Noncompliant {{Invoke method(s) only conditionally. }} + checkState(System.currentTimeMillis() > 0, "message: %s", formatMessage()); // Noncompliant {{Invoke method(s) only conditionally. }} - checkState(System.currentTimeMillis() > 0, "message: %s", LazyArgEvaluationCheckSample.formatMessage()); // Noncompliant {{Invoke method(s) only conditionally. }} + checkState(System.currentTimeMillis() > 0, "message: %s", LazyArgEvaluationCheckSample.formatMessage()); // Noncompliant {{Invoke method(s) only conditionally. }} } public static void cachingOnDisk(File path) { @@ -75,7 +75,7 @@ public void run() { } public void multiArgs() { - checkState(System.currentTimeMillis() > 0, "message: %s %s", formatMessage(), "Something went wrong: " + System.currentTimeMillis()); // Noncompliant + checkState(System.currentTimeMillis() > 0, "message: %s %s", formatMessage(), "Something went wrong: " + System.currentTimeMillis()); // Noncompliant } private static String formatMessage() { @@ -92,22 +92,22 @@ public String toString() { } void slf4j(String csvPath, boolean condition) { - slf4j.trace("Unable to open file " + csvPath, new RuntimeException()); // Noncompliant {{Use the built-in formatting to construct this argument.}} - slf4j.debug("Unable to open file " + csvPath, new RuntimeException()); // Noncompliant {{Use the built-in formatting to construct this argument.}} - slf4j.info("Unable to open file " + csvPath, new RuntimeException()); // Noncompliant {{Use the built-in formatting to construct this argument.}} - slf4j.warn("Unable to open file " + csvPath, new RuntimeException()); // Noncompliant {{Use the built-in formatting to construct this argument.}} - slf4j.error("Unable to open file " + csvPath, new RuntimeException()); // Noncompliant {{Use the built-in formatting to construct this argument.}} + slf4j.trace("Unable to open file " + csvPath, new RuntimeException()); // Noncompliant {{Use the built-in formatting to construct this argument.}} + slf4j.debug("Unable to open file " + csvPath, new RuntimeException()); // Noncompliant {{Use the built-in formatting to construct this argument.}} + slf4j.info("Unable to open file " + csvPath, new RuntimeException()); // Noncompliant {{Use the built-in formatting to construct this argument.}} + slf4j.warn("Unable to open file " + csvPath, new RuntimeException()); // Noncompliant {{Use the built-in formatting to construct this argument.}} + slf4j.error("Unable to open file " + csvPath, new RuntimeException()); // Noncompliant {{Use the built-in formatting to construct this argument.}} - slf4j.error("Unable to open file " + csvPath, new RuntimeException()); // Noncompliant - slf4j.error("Unable to open file " + csvPath, new RuntimeException(), 1); // Noncompliant - slf4j.error("Unable to open file " + csvPath, new RuntimeException(), 1, 2); // Noncompliant - slf4j.error("Unable to open file " + csvPath, new RuntimeException(), 1, "vargs", "vargs", "vargs FTW!"); // Noncompliant + slf4j.error("Unable to open file " + csvPath, new RuntimeException()); // Noncompliant + slf4j.error("Unable to open file " + csvPath, new RuntimeException(), 1); // Noncompliant + slf4j.error("Unable to open file " + csvPath, new RuntimeException(), 1, 2); // Noncompliant + slf4j.error("Unable to open file " + csvPath, new RuntimeException(), 1, "vargs", "vargs", "vargs FTW!"); // Noncompliant Marker confidentialMarker = MarkerFactory.getMarker("CONFIDENTIAL"); - slf4j.error(confidentialMarker, "Unable to open file " + csvPath, new RuntimeException()); // Noncompliant - slf4j.error(confidentialMarker, "Unable to open file " + csvPath, new RuntimeException(), 1); // Noncompliant - slf4j.error(confidentialMarker, "Unable to open file " + csvPath, new RuntimeException(), 1, 2); // Noncompliant - slf4j.error(confidentialMarker, "Unable to open file " + csvPath, new RuntimeException(), 1, "vargs", "vargs", "vargs FTW!"); // Noncompliant + slf4j.error(confidentialMarker, "Unable to open file " + csvPath, new RuntimeException()); // Noncompliant + slf4j.error(confidentialMarker, "Unable to open file " + csvPath, new RuntimeException(), 1); // Noncompliant + slf4j.error(confidentialMarker, "Unable to open file " + csvPath, new RuntimeException(), 1, 2); // Noncompliant + slf4j.error(confidentialMarker, "Unable to open file " + csvPath, new RuntimeException(), 1, "vargs", "vargs", "vargs FTW!"); // Noncompliant if (slf4j.isTraceEnabled()) { slf4j.trace("Unable to open file " + csvPath, new RuntimeException()); // Compliant - inside if test @@ -125,18 +125,18 @@ void slf4j(String csvPath, boolean condition) { slf4j.error("Unable to open file " + csvPath, new RuntimeException()); // Compliant - inside if test } if (condition) { - slf4j.error("Unable to open file " + csvPath, new RuntimeException()); // Noncompliant + slf4j.error("Unable to open file " + csvPath, new RuntimeException()); // Noncompliant } } void jul(String csvPath) { - logger.finest("Unable to open file " + csvPath); // Noncompliant {{Use the built-in formatting to construct this argument.}} - logger.finer("Unable to open file " + csvPath); // Noncompliant {{Use the built-in formatting to construct this argument.}} - logger.fine("Unable to open file " + csvPath); // Noncompliant {{Use the built-in formatting to construct this argument.}} - logger.config("Unable to open file " + csvPath); // Noncompliant {{Use the built-in formatting to construct this argument.}} - logger.info("Unable to open file " + csvPath); // Noncompliant {{Use the built-in formatting to construct this argument.}} - logger.warning("Unable to open file " + csvPath); // Noncompliant {{Use the built-in formatting to construct this argument.}} - logger.severe("Unable to open file " + csvPath); // Noncompliant {{Use the built-in formatting to construct this argument.}} + logger.finest("Unable to open file " + csvPath); // Noncompliant {{Use the built-in formatting to construct this argument.}} + logger.finer("Unable to open file " + csvPath); // Noncompliant {{Use the built-in formatting to construct this argument.}} + logger.fine("Unable to open file " + csvPath); // Noncompliant {{Use the built-in formatting to construct this argument.}} + logger.config("Unable to open file " + csvPath); // Noncompliant {{Use the built-in formatting to construct this argument.}} + logger.info("Unable to open file " + csvPath); // Noncompliant {{Use the built-in formatting to construct this argument.}} + logger.warning("Unable to open file " + csvPath); // Noncompliant {{Use the built-in formatting to construct this argument.}} + logger.severe("Unable to open file " + csvPath); // Noncompliant {{Use the built-in formatting to construct this argument.}} if (logger.isLoggable(Level.FINEST)) { logger.finest("Unable to open file " + csvPath); // Compliant - inside if test diff --git a/java-checks-test-sources/default/src/main/java/checks/LeftCurlyBraceEndLineCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/LeftCurlyBraceEndLineCheckSample.java index 686f1391973..8abaeabb9f0 100644 --- a/java-checks-test-sources/default/src/main/java/checks/LeftCurlyBraceEndLineCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/LeftCurlyBraceEndLineCheckSample.java @@ -11,15 +11,15 @@ class LeftCurlyBraceEndLineCheckSample { private static final int MY_CONST; static - { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} [[sc=3;ec=4]] + { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} +//^ MY_CONST = 0; } public enum MyEnum { A(1) // Duplicated issue... - // Noncompliant@+1 - { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} + { // Noncompliant 2 }, B(2), C(42) { // Compliant @@ -36,24 +36,24 @@ public LeftCurlyBraceEndLineCheckSample() { // Compliant } public void bar() throws Exception - { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} + { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} class InnerClass - { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} + { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} } } void doStuff(boolean test, MyEnum myEnum, List myList) throws IOException - { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} + { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} if (test) System.out.println(); if (test) { // Compliant } else - { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} + { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} } switch (myEnum) - { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} + { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} case A: break; default: @@ -64,34 +64,34 @@ void doStuff(boolean test, MyEnum myEnum, List myList) throws IOException } while(test); while (test) - { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} + { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} } for (int i = 0; i < 10; i++) - { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} + { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} } for (Object object : myList) { // Compliant } synchronized (myList) - { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} + { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} } try - { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} + { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} } catch(Exception e) - { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} + { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} } try (FileInputStream fis = new FileInputStream("")) - { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} + { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} } finally - { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} + { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} } Closeable c = new Closeable() - { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} + { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} @Override public void close() throws IOException { } @@ -105,21 +105,21 @@ public void close() throws IOException { }; LABEL: - { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} + { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} doSomethingElse(); } } public void myMethod(boolean something, boolean something3, boolean something4, boolean param1, boolean param2, boolean param3) { // Compliant if(something) - { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} + { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} doSomethingElse(); } else { // Compliant doSomethingElse(); } if( param1 && param2 && param3 && something3 && something4) - { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} + { // Noncompliant {{Move this left curly brace to the end of previous line of code.}} doSomethingElse(); } } @@ -144,15 +144,15 @@ class LeftCurlyBraceEndLineCheckSampleReBar extends checks.LeftCurlyBraceEndLine } abstract class Dul implements Closeable -{ // Noncompliant {{Move this left curly brace to the end of previous line of code.}} +{ // Noncompliant {{Move this left curly brace to the end of previous line of code.}} } class Goo -{ // Noncompliant {{Move this left curly brace to the end of previous line of code.}} +{ // Noncompliant {{Move this left curly brace to the end of previous line of code.}} } abstract class MyList implements List -{ // Noncompliant {{Move this left curly brace to the end of previous line of code.}} +{ // Noncompliant {{Move this left curly brace to the end of previous line of code.}} } @Properties( diff --git a/java-checks-test-sources/default/src/main/java/checks/LeftCurlyBraceStartLineCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/LeftCurlyBraceStartLineCheckSample.java index aff27b16ab7..00149e73a04 100644 --- a/java-checks-test-sources/default/src/main/java/checks/LeftCurlyBraceStartLineCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/LeftCurlyBraceStartLineCheckSample.java @@ -2,14 +2,15 @@ import org.sonar.api.Properties; -class LeftCurlyBraceStartLineCheckSample { // Noncompliant [[sc=42;ec=43]] {{Move this left curly brace to the beginning of next line of code.}} +class LeftCurlyBraceStartLineCheckSample { // Noncompliant {{Move this left curly brace to the beginning of next line of code.}} +// ^ class Gul { // Compliant } class - Doo { // Noncompliant {{Move this left curly brace to the beginning of next line of code.}} + Doo { // Noncompliant {{Move this left curly brace to the beginning of next line of code.}} } class Koo diff --git a/java-checks-test-sources/default/src/main/java/checks/LoggedRethrownExceptionsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/LoggedRethrownExceptionsCheckSample.java index 8c8dda1ab33..0d402e2aa75 100644 --- a/java-checks-test-sources/default/src/main/java/checks/LoggedRethrownExceptionsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/LoggedRethrownExceptionsCheckSample.java @@ -15,9 +15,12 @@ public void foo() throws Exception { Logger logger = java.util.logging.Logger.getAnonymousLogger(""); try { doSomething(); - } catch (SQLException e) { // Noncompliant [[secondary=19,20]] {{Either log this exception and handle it, or rethrow it with some contextual information.}} + } catch (SQLException e) { // Noncompliant {{Either log this exception and handle it, or rethrow it with some contextual information.}} +// ^^^^^^^^^^^^^^ logger.log(Level.ALL, "", e); +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< throw new MySQLException(contextInfo, e); +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< } try { diff --git a/java-checks-test-sources/default/src/main/java/checks/LongBitsToDoubleOnIntCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/LongBitsToDoubleOnIntCheckSample.java index c1d3b94fcc5..d48c2e804c4 100644 --- a/java-checks-test-sources/default/src/main/java/checks/LongBitsToDoubleOnIntCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/LongBitsToDoubleOnIntCheckSample.java @@ -4,7 +4,8 @@ class LongBitsToDoubleOnIntCheckSample { void foo() { byte b = 1; short s = 1; - Double.longBitsToDouble('c'); // Noncompliant [[sc=12;ec=28]] {{Remove this "Double.longBitsToDouble" call.}} + Double.longBitsToDouble('c'); // Noncompliant {{Remove this "Double.longBitsToDouble" call.}} +// ^^^^^^^^^^^^^^^^ Double.longBitsToDouble(s); // Noncompliant Double.longBitsToDouble(b); // Noncompliant Double.longBitsToDouble(1); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/MapKeyNotComparableCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/MapKeyNotComparableCheckSample.java index f01ec88f8bc..d777319dd99 100644 --- a/java-checks-test-sources/default/src/main/java/checks/MapKeyNotComparableCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/MapKeyNotComparableCheckSample.java @@ -36,7 +36,8 @@ public String toString() { } } - abstract class A implements Map { // Noncompliant [[sc=35;ec=48]] {{The key type should implement Comparable.}} + abstract class A implements Map { // Noncompliant {{The key type should implement Comparable.}} +// ^^^^^^^^^^^^^ } abstract static class ThreeTypeParams implements Map { @@ -50,15 +51,18 @@ static class FieldDecl { Map memberSelect = new HashMap<>(); // Noncompliant {{The key type should implement Comparable.}} Map wildCard = new HashMap<>(); ThreeTypeParams threeTypeParams = null; // compliant - HashMap nonInterface = new HashMap<>(); // Noncompliant [[sc=13;ec=26]] {{The key type should implement Comparable.}} + HashMap nonInterface = new HashMap<>(); // Noncompliant {{The key type should implement Comparable.}} +// ^^^^^^^^^^^^^ Map twoLines = // Noncompliant {{The key type should implement Comparable.}} new HashMap(); // Noncompliant {{The key type should implement Comparable.}} Object newMap = new HashMap(); // Noncompliant {{The key type should implement Comparable.}} - List> mapAsTypeParam = new LinkedList<>(); // Noncompliant [[sc=14;ec=27]] {{The key type should implement Comparable.}} + List> mapAsTypeParam = new LinkedList<>(); // Noncompliant {{The key type should implement Comparable.}} +// ^^^^^^^^^^^^^ } static class MethodDecl { - Map buildNonComparableMap() { // Noncompliant [[sc=9;ec=22]] {{The key type should implement Comparable.}} + Map buildNonComparableMap() { // Noncompliant {{The key type should implement Comparable.}} +// ^^^^^^^^^^^^^ return null; } @@ -66,12 +70,16 @@ Map buildComaparableMap() { return null; } - void highFunc(Function, String> f) { // Noncompliant [[sc=32;ec=45]] {{The key type should implement Comparable.}} + void highFunc(Function, String> f) { // Noncompliant {{The key type should implement Comparable.}} +// ^^^^^^^^^^^^^ } // Should throw twice because NomComparable and NonComparable2 are different - // Noncompliant@+1 [[sc=9;ec=22]] {{The key type should implement Comparable.}} - Map highFunc2(Function, String> f) { // Noncompliant [[sc=55;ec=69]] + Map highFunc2 // Noncompliant +// ^^^^^^^^^^^^^ + (Function, String> f) { // Noncompliant +// ^^^^^^^^^^^^^^ + return null; } } diff --git a/java-checks-test-sources/default/src/main/java/checks/MathClampMethodsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/MathClampMethodsCheckSample.java index af6bc840724..c97977263c7 100644 --- a/java-checks-test-sources/default/src/main/java/checks/MathClampMethodsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/MathClampMethodsCheckSample.java @@ -3,7 +3,8 @@ public class MathClampMethodsCheckSample { public void testNoncompliant(int min, int max, int value) { - int clampedValueConditional1 = value > max ? max : value < min ? min : value; // Noncompliant [[sc=36;ec=81]] {{Use "Math.clamp" instead of a conditional expression.}} + int clampedValueConditional1 = value > max ? max : value < min ? min : value; // Noncompliant {{Use "Math.clamp" instead of a conditional expression.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ int clampedValueConditional2 = value < min ? min : value > max ? max : value; // Noncompliant int clampedValueConditional4 = value > max ? max : Math.min(min, value); // Compliant @@ -14,7 +15,8 @@ public void testNoncompliant(int min, int max, int value) { int conditionalValue = value == max ? max : value; // Compliant int conditionalValue2 = value > max ? max : value; // Compliant - int clampedValueMethodInvocation1 = Math.min(min, Math.max(max, value)); // Noncompliant [[sc=41;ec=76]] {{Use "Math.clamp" instead of "Math.min" or "Math.max".}} + int clampedValueMethodInvocation1 = Math.min(min, Math.max(max, value)); // Noncompliant {{Use "Math.clamp" instead of "Math.min" or "Math.max".}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ int clampedValueMethodInvocation2 = Math.max(min, Math.min(max, value)); // Noncompliant int clampedValueMethodInvocation3 = Math.min(Math.min(min, value), max); // Compliant - FN @@ -58,7 +60,7 @@ private void testConditional(int min, int max, int value) { int b1 = value > max ? max : value; // Compliant int b2 = value > max ? value : value < min ? min : value; // Compliant - int b3 = value > max ? max : value > max ? value : max; // Noncompliant - stupid FP + int b3 = value > max ? max : value > max ? value : max; // Noncompliant int maxValue = value > min ? min : value > max ? max : value; // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/MathClampRangeCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/MathClampRangeCheckSample.java index 6aa8f7cb63b..5736a4b0d68 100644 --- a/java-checks-test-sources/default/src/main/java/checks/MathClampRangeCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/MathClampRangeCheckSample.java @@ -18,28 +18,31 @@ void test( Math.clamp(i1, 0, 10); // Compliant // equals - Math.clamp(d1, d2, d2); // Noncompliant [[sc=20;ec=22;quickfixes=!]] {{Change the "clamp(value,min,max)"'s arguments so "min" is not equals to "max".}} + Math.clamp(d1, d2, d2); // Noncompliant {{Change the "clamp(value,min,max)"'s arguments so "min" is not equals to "max".}} [[quickfixes=!]] +// ^^ Math.clamp(f1, f1, f3); // Noncompliant {{Change the "clamp(value,min,max)"'s arguments so "min" is not equals to "value".}} Math.clamp(l1, l2, l1); // Noncompliant {{Change the "clamp(value,min,max)"'s arguments so "max" is not equals to "value".}} Math.clamp(i1, i2, i1); // Noncompliant {{Change the "clamp(value,min,max)"'s arguments so "max" is not equals to "value".}} Math.clamp(d1, 5.0d, 5.0d); // Noncompliant {{Change the "clamp(value,min,max)"'s arguments so "min" is not equals to "max".}} Math.clamp(5.0f, 5.0f, f3); // Noncompliant {{Change the "clamp(value,min,max)"'s arguments so "min" is not equals to "value".}} - Math.clamp(10L, l2, 10L); // Noncompliant {{Change the "clamp(value,min,max)"'s arguments so "max" is not equals to "value".}} - Math.clamp(10, l2, 10); // Noncompliant {{Change the "clamp(value,min,max)"'s arguments so "max" is not equals to "value".}} + Math.clamp(10L, l2, 10L); // Noncompliant {{Change the "clamp(value,min,max)"'s arguments so "max" is not equals to "value".}} + Math.clamp(10, l2, 10); // Noncompliant {{Change the "clamp(value,min,max)"'s arguments so "max" is not equals to "value".}} Math.clamp(d1, (unknownValue() + 42) * 666, (unknownValue() + 42) * 666); // Noncompliant {{Change the "clamp(value,min,max)"'s arguments so "min" is not equals to "max".}} // less than Math.clamp(i1, i2, i3); // Compliant - Math.clamp(l1, 10L, 0L); // Noncompliant [[sc=25;ec=27;secondary=+0;quickfixes=qf1]] {{Change the "clamp(value,min,max)"'s arguments so "max" is not always less than "min".}} + Math.clamp(l1, 10L, 0L); // Noncompliant {{Change the "clamp(value,min,max)"'s arguments so "max" is not always less than "min".}} [[quickfixes=qf1]] +// ^^ +// ^^^@-1< // fix@qf1 {{Swap "max" and "min" arguments}} // edit@qf1 [[sc=25;ec=27]] {{10L}} // edit@qf1 [[sc=20;ec=23]] {{0L}} - Math.clamp(0, i2, 10); // Noncompliant {{Change the "clamp(value,min,max)"'s arguments so "value" is not always less than "max".}} - Math.clamp(10L, 0, l3); // Noncompliant {{Change the "clamp(value,min,max)"'s arguments so "min" is not always less than "value".}} + Math.clamp(0, i2, 10); // Noncompliant {{Change the "clamp(value,min,max)"'s arguments so "value" is not always less than "max".}} + Math.clamp(10L, 0, l3); // Noncompliant {{Change the "clamp(value,min,max)"'s arguments so "min" is not always less than "value".}} Math.clamp(d1, 10.0d, 0.0d); // FN limitation, ExpressionTree.asConstant() does not support "double" Math.clamp(0.0f, f2, 10.0f); // FN limitation, ExpressionTree.asConstant() does not support "float" diff --git a/java-checks-test-sources/default/src/main/java/checks/MathOnFloatCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/MathOnFloatCheckSample.java index f062eeb4096..e429f3c2ed1 100644 --- a/java-checks-test-sources/default/src/main/java/checks/MathOnFloatCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/MathOnFloatCheckSample.java @@ -5,13 +5,15 @@ class MathOnFloatCheckSample { void myMethod() { float a = 16777216.0f; float b = 1.0f; - float c = a + b; // Noncompliant {{Use a "double" or "BigDecimal" instead.}} yields 1.6777216E7 not 1.6777217E7 [[sc=15;ec=20]] + float c = a + b; // Noncompliant {{Use a "double" or "BigDecimal" instead.}} +// ^^^^^ - double d1 = a + b; // Noncompliant ; addition is still between 2 floats + double d1 = a + b; // Noncompliant double d2 = a - b; // Noncompliant double d3 = a * b; // Noncompliant double d4 = a / b; // Noncompliant - double d5 = a / b + b; // Noncompliant, only one issue should be reported [[sc=17;ec=26]] + double d5 = a / b + b; // Noncompliant +// ^^^^^^^^^ double d6 = a + d1; diff --git a/java-checks-test-sources/default/src/main/java/checks/MembersDifferOnlyByCapitalizationCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/MembersDifferOnlyByCapitalizationCheckSample.java index dc70fd2f0f3..6ee21215aef 100644 --- a/java-checks-test-sources/default/src/main/java/checks/MembersDifferOnlyByCapitalizationCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/MembersDifferOnlyByCapitalizationCheckSample.java @@ -6,22 +6,27 @@ abstract class A implements MyInterface { private static final long var1 = -9215047833775013803L; // Compliant public long var2 = 0L; - public void equAls(Object obj) {} // Noncompliant [[sc=15;ec=21]] {{Rename method "equAls" to prevent any misunderstanding/clash with method "equals" defined in superclass "java.lang.Object".}} + public void equAls(Object obj) {} // Noncompliant {{Rename method "equAls" to prevent any misunderstanding/clash with method "equals" defined in superclass "java.lang.Object".}} + protected void finaliZe() {} // Noncompliant {{Rename method "finaliZe" to prevent any misunderstanding/clash with method "finalize" defined in superclass "java.lang.Object".}} public void myMethod() {} public Object stuff; - public void stuff() {} // Noncompliant [[secondary=14]] {{Rename method "stuff" to prevent any misunderstanding/clash with field "stuff".}} - public void stuff(int i) {} // Noncompliant [[secondary=14]] {{Rename method "stuff" to prevent any misunderstanding/clash with field "stuff".}} +// ^^^^^> + public void stuff() {} // Noncompliant {{Rename method "stuff" to prevent any misunderstanding/clash with field "stuff".}} + // ^^^^^ + public void stuff(int i) {} // Noncompliant {{Rename method "stuff" to prevent any misunderstanding/clash with field "stuff".}} public void foo(int i) {} // Compliant public void foo(boolean i) {} // Compliant - public void myOtherMethoD() {} // Noncompliant [[secondary=41]] {{Rename method "myOtherMethoD" to prevent any misunderstanding/clash with method "myOtherMethod" defined in interface "checks.MembersDifferOnlyByCapitalizationCheckSample$MyInterface".}} - - private static void gUl() {} // Noncompliant [[secondary=24]] {{Rename method "gUl" to prevent any misunderstanding/clash with method "gul".}} + public void myOtherMethoD() {} // Noncompliant {{Rename method "myOtherMethoD" to prevent any misunderstanding/clash with method "myOtherMethod" defined in interface "checks.MembersDifferOnlyByCapitalizationCheckSample$MyInterface".}} +// ^^^^^^^^^^^^^ + private static void gUl() {} // Noncompliant {{Rename method "gUl" to prevent any misunderstanding/clash with method "gul".}} + //^^^ public void gul() {} // Compliant +// ^^^< private boolean qix; @@ -45,20 +50,24 @@ interface MyInterface { abstract class B extends A { private static final long var1 = -9215047833775013803L; // Compliant - public void var2() {}; // Noncompliant [[secondary=7]] - public void vAr2() {}; // Noncompliant [[secondary=48]] + public void var2() {}; // Noncompliant +// ^^^^> + public void vAr2() {}; // Noncompliant + //^^^^ - public void myMethoD() {} // Noncompliant [[secondary=12]] {{Rename method "myMethoD" to prevent any misunderstanding/clash with method "myMethod" defined in superclass "checks.MembersDifferOnlyByCapitalizationCheckSample$A".}} + public void myMethoD() {} // Noncompliant {{Rename method "myMethoD" to prevent any misunderstanding/clash with method "myMethod" defined in superclass "checks.MembersDifferOnlyByCapitalizationCheckSample$A".}} public Object qix; // Compliant - public void fOo(int i) {} // Noncompliant [[secondary=18]] + public void fOo(int i) {} // Noncompliant } class Visibility { public int tmp0; +// ^^^^> private void tmp0() {} - public void tmp0(int i) {} // Noncompliant [[secondary=59]] {{Rename method "tmp0" to prevent any misunderstanding/clash with field "tmp0".}} + public void tmp0(int i) {} // Noncompliant {{Rename method "tmp0" to prevent any misunderstanding/clash with field "tmp0".}} + // ^^^^ protected void tmp0(long l) {} void tmp0(short s) {} @@ -69,16 +78,20 @@ protected void tmp1(long l) {} void tmp1(short s) {} int tmp2; +// ^^^^> private void tmp2() {} public void tmp2(int i) {} protected void tmp2(long l) {} - void tmp2(short s) {} // Noncompliant [[secondary=71]] {{Rename method "tmp2" to prevent any misunderstanding/clash with field "tmp2".}} + void tmp2(short s) {} // Noncompliant {{Rename method "tmp2" to prevent any misunderstanding/clash with field "tmp2".}} + // ^^^^ protected int tmp3; +// ^^^^> private void tmp3() {} public void tmp3(int i) {} - protected void tmp3(long l) {} // Noncompliant [[secondary=77]] {{Rename method "tmp3" to prevent any misunderstanding/clash with field "tmp3".}} - void tmp3(short s) {} + protected void tmp3(long l) {} // Noncompliant {{Rename method "tmp3" to prevent any misunderstanding/clash with field "tmp3".}} + // ^^^^ + void tmp3(short s) {} } public enum MyEnum { @@ -91,6 +104,7 @@ public void foo() {} // Compliant class ABuilder { String name; String wrong; +// ^^^^^> String value; ABuilder name(String name) { // Compliant - exception for builder pattern @@ -98,7 +112,8 @@ ABuilder name(String name) { // Compliant - exception for builder pattern return this; } - ABuilder WRONG(String wrong) { // Noncompliant [[secondary=93]] + ABuilder WRONG(String wrong) { // Noncompliant + // ^^^^^ this.wrong = value; return this; } @@ -166,7 +181,7 @@ Object f3() { // Noncompliant record MyRecord(int intComponent, boolean bool) { - public static final boolean BooL = false; // Noncompliant {{Rename field "BooL" to prevent any misunderstanding/clash with field "bool".}} + public static final boolean BooL = false; // Noncompliant {{Rename field "BooL" to prevent any misunderstanding/clash with field "bool".}} @Override public boolean bool() { return bool; @@ -182,10 +197,12 @@ class subClass { } class NoDuplications { void Abcde(){ } - void aBcde(){ } // Noncompliant [[secondary=-1]] {{Rename method "aBcde" to prevent any misunderstanding/clash with method "Abcde".}} - void abCde(){ } // Noncompliant [[secondary=-2]] {{Rename method "abCde" to prevent any misunderstanding/clash with method "Abcde".}} - void abcDe(){ } // Noncompliant [[secondary=-3]] {{Rename method "abcDe" to prevent any misunderstanding/clash with method "Abcde".}} - void abcdE(){ } // Noncompliant [[secondary=-4]] {{Rename method "abcdE" to prevent any misunderstanding/clash with method "Abcde".}} +// ^^^^^> + void aBcde(){ } // Noncompliant {{Rename method "aBcde" to prevent any misunderstanding/clash with method "Abcde".}} + // ^^^^^ + void abCde(){ } // Noncompliant {{Rename method "abCde" to prevent any misunderstanding/clash with method "Abcde".}} + void abcDe(){ } // Noncompliant {{Rename method "abcDe" to prevent any misunderstanding/clash with method "Abcde".}} + void abcdE(){ } // Noncompliant {{Rename method "abcdE" to prevent any misunderstanding/clash with method "Abcde".}} } } diff --git a/java-checks-test-sources/default/src/main/java/checks/MethodOnlyCallsSuperCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/MethodOnlyCallsSuperCheckSample.java index e3ae155db20..2b9be29f6f6 100644 --- a/java-checks-test-sources/default/src/main/java/checks/MethodOnlyCallsSuperCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/MethodOnlyCallsSuperCheckSample.java @@ -31,7 +31,8 @@ public int f255() { return 0; } - public void f3() { // Noncompliant [[sc=17;ec=19]] {{Remove this method to simply inherit it.}} + public void f3() { // Noncompliant {{Remove this method to simply inherit it.}} +// ^^ super.f3(); } diff --git a/java-checks-test-sources/default/src/main/java/checks/MethodTooBigCheckCustom4.java b/java-checks-test-sources/default/src/main/java/checks/MethodTooBigCheckCustom4.java index 6d72b8d9516..902e838c184 100644 --- a/java-checks-test-sources/default/src/main/java/checks/MethodTooBigCheckCustom4.java +++ b/java-checks-test-sources/default/src/main/java/checks/MethodTooBigCheckCustom4.java @@ -1,7 +1,8 @@ package checks; class MethodTooBigCheckCustom4 { - public MethodTooBigCheckCustom4() { // Noncompliant [[sc=10;ec=34]] {{This method has 6 lines, which is greater than the 4 lines authorized. Split it into smaller methods.}} + public MethodTooBigCheckCustom4() { // Noncompliant {{This method has 6 lines, which is greater than the 4 lines authorized. Split it into smaller methods.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^ System.out.println(""); // This does not count as a line // This does not count as a line diff --git a/java-checks-test-sources/default/src/main/java/checks/MethodWithExcessiveReturnsCheckCustom.java b/java-checks-test-sources/default/src/main/java/checks/MethodWithExcessiveReturnsCheckCustom.java index 03f0fbbc4f1..2f7187c4b8c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/MethodWithExcessiveReturnsCheckCustom.java +++ b/java-checks-test-sources/default/src/main/java/checks/MethodWithExcessiveReturnsCheckCustom.java @@ -46,13 +46,20 @@ Object foo4(List bar) { if(false) return o2; return o1; }); - bar.sort((o1, o2)-> { // Noncompliant [[sc=22;ec=24;secondary=50,51,52,53,54,55]]]] {{This method has 6 returns, which is more than the 4 allowed.}} + bar.sort((o1, o2)-> { // Noncompliant {{This method has 6 returns, which is more than the 4 allowed.}} +// ^^ if(false) return o2; +// ^^^^^^< if(false) return o1; +// ^^^^^^< if(false) return o2; +// ^^^^^^< if(false) return o1; +// ^^^^^^< if(false) return o1; +// ^^^^^^< return o1; +// ^^^^^^< }); return null; } diff --git a/java-checks-test-sources/default/src/main/java/checks/MethodWithExcessiveReturnsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/MethodWithExcessiveReturnsCheckSample.java index 260ea181728..58041386f2a 100644 --- a/java-checks-test-sources/default/src/main/java/checks/MethodWithExcessiveReturnsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/MethodWithExcessiveReturnsCheckSample.java @@ -8,11 +8,16 @@ boolean foo1() { // Compliant return false; } - boolean foo2() { // Noncompliant [[sc=11;ec=15;secondary=12,13,14,15]] {{This method has 4 returns, which is more than the 3 allowed.}} + boolean foo2() { // Noncompliant {{This method has 4 returns, which is more than the 3 allowed.}} +// ^^^^ if (false) return true; +// ^^^^^^< if (false) return false; +// ^^^^^^< if (false) return true; +// ^^^^^^< return false; +// ^^^^^^< } void foo3() { // Noncompliant {{This method has 4 returns, which is more than the 3 allowed.}} @@ -20,12 +25,18 @@ void foo3() { // Noncompliant {{This method has 4 returns, which is more than th if (false) return; new MethodWithExcessiveReturnsCheckSample() { - public void f() { // Noncompliant [[sc=19;ec=20;secondary=24,25,26,27,28]] {{This method has 5 returns, which is more than the 3 allowed.}} + public void f() { // Noncompliant {{This method has 5 returns, which is more than the 3 allowed.}} +// ^ if (false) return; +// ^^^^^^< if (false) return; +// ^^^^^^< if (false) return; +// ^^^^^^< if (false) return; +// ^^^^^^< return; +// ^^^^^^< } public void g() { // Compliant @@ -57,7 +68,7 @@ public boolean equals(Object obj) { // Compliant because equals method is excemp return intMember == other.intMember && Objects.equals(stringMember, other.stringMember); } - public boolean equals(MethodWithExcessiveReturnsCheckSample obj) { // Noncompliant because this is not a proper equals method + public boolean equals(MethodWithExcessiveReturnsCheckSample obj) { // Noncompliant if (this == obj) { return true; } diff --git a/java-checks-test-sources/default/src/main/java/checks/MissingCurlyBraces.java b/java-checks-test-sources/default/src/main/java/checks/MissingCurlyBraces.java index 3653e8b1833..209e8e0b7a4 100644 --- a/java-checks-test-sources/default/src/main/java/checks/MissingCurlyBraces.java +++ b/java-checks-test-sources/default/src/main/java/checks/MissingCurlyBraces.java @@ -6,10 +6,12 @@ class MissingCurlyBraces { void method(boolean condition) { - if (condition) doSomething(); // Noncompliant [[sc=5;ec=7]] {{Missing curly brace.}} + if (condition) doSomething(); // Noncompliant {{Missing curly brace.}} +// ^^ if (condition) doSomething(); // Noncompliant - else doSomethingElse(); // Noncompliant [[sc=5;ec=9]] + else doSomethingElse(); // Noncompliant +// ^^^^ if (condition) { } else doSomething(); // Noncompliant @@ -25,13 +27,15 @@ void method(boolean condition) { } else if (condition) { } - for (int i = 0; i < 10; i++) doSomething(); // Noncompliant [[sc=5;ec=8]] + for (int i = 0; i < 10; i++) doSomething(); // Noncompliant +// ^^^ for (int i = 0; i < 10; i++) { } List list = new ArrayList<>(); - for (String s: list) doSomething(); // Noncompliant [[sc=5;ec=8]] + for (String s: list) doSomething(); // Noncompliant +// ^^^ while (condition) doSomething(); // Noncompliant @@ -65,8 +69,10 @@ int exceptions(boolean condition) { if (condition) return 1;something(); // Compliant, S2681 raises an issue here - if (condition) return 1; else { doSomethingElse(); }// Noncompliant [[sc=5;ec=7]] - if (condition) return 1; else if (condition) { doSomethingElse(); } // Noncompliant [[sc=5;ec=7]] + if (condition) return 1; else { doSomethingElse(); } // Noncompliant +// ^^ + if (condition) return 1; else if (condition) { doSomethingElse(); } // Noncompliant +// ^^ if (condition) return 1; // Noncompliant else doSomethingElse(); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/MissingDeprecatedCheckJava9.java b/java-checks-test-sources/default/src/main/java/checks/MissingDeprecatedCheckJava9.java index 15305b74170..b958f1828f0 100644 --- a/java-checks-test-sources/default/src/main/java/checks/MissingDeprecatedCheckJava9.java +++ b/java-checks-test-sources/default/src/main/java/checks/MissingDeprecatedCheckJava9.java @@ -3,7 +3,8 @@ class MissingDeprecatedCheckJava9 { @Deprecated - public int lim; // Noncompliant [[sc=14;ec=17]] {{Add the missing @deprecated Javadoc tag.}} + public int lim; // Noncompliant {{Add the missing @deprecated Javadoc tag.}} +// ^^^ /** * @deprecated diff --git a/java-checks-test-sources/default/src/main/java/checks/MissingDeprecatedCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/MissingDeprecatedCheckSample.java index cbb24e2315a..9dcfbc868ab 100644 --- a/java-checks-test-sources/default/src/main/java/checks/MissingDeprecatedCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/MissingDeprecatedCheckSample.java @@ -6,7 +6,8 @@ class MissingDeprecatedCheckSample { @Deprecated - public int foo; // Noncompliant [[sc=14;ec=17]] {{Add the missing @deprecated Javadoc tag.}} + public int foo; // Noncompliant {{Add the missing @deprecated Javadoc tag.}} +// ^^^ public void foo1() { } diff --git a/java-checks-test-sources/default/src/main/java/checks/MissingNewLineAtEndOfFile.java b/java-checks-test-sources/default/src/main/java/checks/MissingNewLineAtEndOfFile.java index 3626596ed7e..57a21264af5 100644 --- a/java-checks-test-sources/default/src/main/java/checks/MissingNewLineAtEndOfFile.java +++ b/java-checks-test-sources/default/src/main/java/checks/MissingNewLineAtEndOfFile.java @@ -1,4 +1,5 @@ package checks; class MissingNewlineAtEndOfFile { -} \ No newline at end of file +} +// Noncompliant@0 {{Add a new line at the end of this file.}} \ No newline at end of file diff --git a/java-checks-test-sources/default/src/main/java/checks/MissingOverridesInRecordWithArrayComponentCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/MissingOverridesInRecordWithArrayComponentCheckSample.java index 0ae52f7b720..04383658b9f 100644 --- a/java-checks-test-sources/default/src/main/java/checks/MissingOverridesInRecordWithArrayComponentCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/MissingOverridesInRecordWithArrayComponentCheckSample.java @@ -24,8 +24,10 @@ public String toString() { } } - record MissingEverything( // Noncompliant [[sc=10;ec=27;secondary=28]] {{Override equals, hashCode and toString to consider array's content in the method}} + record MissingEverything( // Noncompliant {{Override equals, hashCode and toString to consider array's content in the method}} +// ^^^^^^^^^^^^^^^^^ Object[] objects) { +// ^^^^^^^^^^^^^^^^< static Object defaultValue = null; void doNothing(){} } @@ -87,10 +89,13 @@ public int hashCode() { } } - record multipleArrays( // Noncompliant [[sc=10;ec=24;secondary=92,95]] + record multipleArrays( // Noncompliant +// ^^^^^^^^^^^^^^ Object a, int[] b, +// ^^^^^^^^< Object c, java.util.Collection d, // not an array int... e) {} +// ^^^^^^^^< } diff --git a/java-checks-test-sources/default/src/main/java/checks/MissingPathVariableAnnotationCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/MissingPathVariableAnnotationCheckSample.java index 9318f389576..d4283a9358f 100644 --- a/java-checks-test-sources/default/src/main/java/checks/MissingPathVariableAnnotationCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/MissingPathVariableAnnotationCheckSample.java @@ -24,7 +24,8 @@ public void handle(@PathVariable String name, @PathVariable String version, @Pat - @GetMapping("/{id}") // Noncompliant [[sc=3;ec=23]] {{Bind path variable "id" to a method parameter.}} + @GetMapping("/{id}") // Noncompliant {{Bind path variable "id" to a method parameter.}} +//^^^^^^^^^^^^^^^^^^^^ public String get(String id) { return "Hello World"; } @@ -212,7 +213,7 @@ public String get2(@PathVariable String age) { // compliant return "Hello World"; } - @GetMapping("/{id}/{name}/{age}") // Noncompliant {{Bind path variable "age" to a method parameter.}} + @GetMapping("/{id}/{name}/{age}") // Noncompliant {{Bind path variable "age" to a method parameter.}} public String get3() { return "Hello World"; } diff --git a/java-checks-test-sources/default/src/main/java/checks/ModifiersOrderCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ModifiersOrderCheckSample.java index 5e1c0dcb8e8..c0c73acce2c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ModifiersOrderCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ModifiersOrderCheckSample.java @@ -12,22 +12,25 @@ static public void otherMain(String[] args) { // Noncompliant public int a; - // Noncompliant@+3 [[sc=3;ec=15]] {{Reorder the modifiers to comply with the Java Language Specification.}} + @RequestMapping(value = "/restComTool", method = RequestMethod.GET) public - @Annotation1 + @Annotation1 // Noncompliant {{Reorder the modifiers to comply with the Java Language Specification.}} +// ^^^^^^^^^^^^ static Map> queries(@RequestParam(value = "id", required = true, defaultValue = "-1") final Long id, + @RequestParam(value = "q", required = false, defaultValue = "") final String query, @RequestParam(value = "callback", required = false, defaultValue = "") final String callback){ return null; } - // Noncompliant@+2 + // Noncompliant@+2 abstract public class A{} - private final static int CREATE = 0, FIND = 1, NEW = 2, RELEASE = 3, N_NAMES = 4; // Noncompliant [[sc=17;ec=23]] + private final static int CREATE = 0, FIND = 1, NEW = 2, RELEASE = 3, N_NAMES = 4; // Noncompliant +// ^^^^^^ interface Bar{ default void fun(){} diff --git a/java-checks-test-sources/default/src/main/java/checks/ModifiersOrderCheckWithQuickFixes.java b/java-checks-test-sources/default/src/main/java/checks/ModifiersOrderCheckWithQuickFixes.java index 11c48788803..b893942c521 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ModifiersOrderCheckWithQuickFixes.java +++ b/java-checks-test-sources/default/src/main/java/checks/ModifiersOrderCheckWithQuickFixes.java @@ -2,29 +2,33 @@ class ModifiersOrderCheckWithQuickFixes { - private final static int A = 0, B = 1; // Noncompliant [[sc=17;ec=23;quickfixes=qf1]] + private final static int A = 0, B = 1; // Noncompliant [[quickfixes=qf1]] +// ^^^^^^ // fix@qf1 {{Reorder modifiers}} // edit@qf1 [[sc=3;ec=23]] {{}} // edit@qf1 [[sc=3;ec=3]] {{private static final}} - static public void otherMain(String[] args) { } // Noncompliant [[sc=10;ec=16;quickfixes=qf2]] + static public void otherMain(String[] args) { } // Noncompliant [[quickfixes=qf2]] +// ^^^^^^ // fix@qf2 {{Reorder modifiers}} // edit@qf2 [[sc=3;ec=16]] {{}} // edit@qf2 [[sc=3;ec=3]] {{public static}} - // Noncompliant@+3 [[sc=3;ec=15;quickfixes=qf3]] + @Annotation0(p1 = "foo", p2 = false) final - @Annotation2 + @Annotation2 // Noncompliant [[quickfixes=qf3]] +//^^^^^^^^^^^^ static void foo() {} // fix@qf3 {{Reorder modifiers}} - // edit@qf3 [[sl=17;sc=3;el=18;ec=3]] {{}} - "final\n " - // edit@qf3 [[sl=19;sc=3;el=20;ec=3]] {{}} - "static\n " - // edit@qf3 [[sl=20;sc=3;el=20;ec=3]] {{static final }} + // edit@qf3 [[sl=19;sc=3;el=20;ec=3]] {{}} + // edit@qf3 [[sl=22;sc=3;el=23;ec=3]] {{}} + // edit@qf3 [[sl=23;sc=3;el=23;ec=3]] {{static final }} + - // Noncompliant@+1 [[sc=9;ec=15;quickfixes=qf4]] - final public native @Annotation2 synchronized static void bar(); + final public native @Annotation2 synchronized static void bar(); // Noncompliant [[quickfixes=qf4]] +// ^^^^^^ // fix@qf4 {{Reorder modifiers}} // edit@qf4 [[sc=3;ec=9]] {{}} - final // edit@qf4 [[sc=9;ec=16]] {{}} - public @@ -41,14 +45,16 @@ void foo() {} @interface Annotation2 {} @interface Annotation3 {} - final static @Annotation2 class Inner {} // Noncompliant [[sc=9;ec=15;quickfixes=qf5]] + final static @Annotation2 class Inner {} // Noncompliant [[quickfixes=qf5]] +// ^^^^^^ // fix@qf5 {{Reorder modifiers}} // edit@qf5 [[sc=3;ec=9]] {{}} - final // edit@qf5 [[sc=9;ec=16]] {{}} - static // edit@qf5 [[sc=29;ec=29]] {{static final }} @Annotation2 - final static class Inner2 {} // Noncompliant [[sc=9;ec=15;quickfixes=qf6]] + final static class Inner2 {} // Noncompliant [[quickfixes=qf6]] +// ^^^^^^ // fix@qf6 {{Reorder modifiers}} // edit@qf6 [[sc=3;ec=9]] {{}} - final // edit@qf6 [[sc=9;ec=16]] {{}} - static diff --git a/java-checks-test-sources/default/src/main/java/checks/ModulusEqualityCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ModulusEqualityCheckSample.java index 9190fd417d8..eca0f81c6bb 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ModulusEqualityCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ModulusEqualityCheckSample.java @@ -9,7 +9,8 @@ class ModulusEqualityCheckSample { boolean b; void myMethod(int x, int y, Integer z) { - b = x % 2 == 1; // Noncompliant [[sc=12;ec=13]] {{The results of this modulus operation may not be positive.}} + b = x % 2 == 1; // Noncompliant {{The results of this modulus operation may not be positive.}} +// ^ b = x % 2 == -1; // Noncompliant {{The results of this modulus operation may not be negative.}} b = 2 % x == 1; // Noncompliant {{The results of this modulus operation may not be positive.}} b = 1 == x % 2; // Noncompliant {{The results of this modulus operation may not be positive.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/MutableMembersUsageCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/MutableMembersUsageCheckSample.java index 92426a8319e..56fd37da6d2 100644 --- a/java-checks-test-sources/default/src/main/java/checks/MutableMembersUsageCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/MutableMembersUsageCheckSample.java @@ -126,11 +126,13 @@ public MutableMembersUsageCheckSample () { } public String [] getStrings() { - return strings; // Noncompliant [[sc=12;ec=19]] {{Return a copy of "strings".}} + return strings; // Noncompliant {{Return a copy of "strings".}} +// ^^^^^^^ } public void setStringsFromGiven(String [] given) { - strings = given; // Noncompliant [[sc=15;ec=20]] {{Store a copy of "given".}} + strings = given; // Noncompliant {{Store a copy of "given".}} +// ^^^^^ } public List getMutableList() { @@ -449,7 +451,7 @@ public int[][][] getValues2() { return EMPTY_SEVERAL_DIMS; } public int[] getValues3() { - return NOT_EMPTY;// Noncompliant + return NOT_EMPTY; // Noncompliant } public int[][][] getValues4() { return NOT_EMPTY_SEVERAL_DIMS; // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/NPEThrowCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/NPEThrowCheckSample.java index b199a92b117..44e52d6da24 100644 --- a/java-checks-test-sources/default/src/main/java/checks/NPEThrowCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/NPEThrowCheckSample.java @@ -1,7 +1,8 @@ package checks; class NPEThrowCheckSample { - void foo() throws NullPointerException { // Noncompliant [[sc=21;ec=41]] {{Throw some other exception here, such as "IllegalArgumentException".}} + void foo() throws NullPointerException { // Noncompliant {{Throw some other exception here, such as "IllegalArgumentException".}} +// ^^^^^^^^^^^^^^^^^^^^ } void bar() { throw new @@ -9,7 +10,8 @@ void bar() { (); } void baz() { - throw new java.lang.NullPointerException();// Noncompliant [[sc=15;ec=45]] {{Throw some other exception here, such as "IllegalArgumentException".}} + throw new java.lang.NullPointerException(); // Noncompliant {{Throw some other exception here, such as "IllegalArgumentException".}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } void qix() throws IllegalArgumentException { throw new IllegalArgumentException(); diff --git a/java-checks-test-sources/default/src/main/java/checks/NestedBlocksCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/NestedBlocksCheckSample.java index c9ec141e57f..02f245201d7 100644 --- a/java-checks-test-sources/default/src/main/java/checks/NestedBlocksCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/NestedBlocksCheckSample.java @@ -3,7 +3,8 @@ class NestedBlocksCheckSample { private void f(String s, boolean b) { if (false) { - { // Noncompliant [[sc=7;ec=8]] {{Extract this nested code block into a method.}} + { // Noncompliant {{Extract this nested code block into a method.}} +// ^ } } diff --git a/java-checks-test-sources/default/src/main/java/checks/NestedEnumStatic.java b/java-checks-test-sources/default/src/main/java/checks/NestedEnumStatic.java index e1f19435e6e..73751b3480c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/NestedEnumStatic.java +++ b/java-checks-test-sources/default/src/main/java/checks/NestedEnumStatic.java @@ -8,6 +8,7 @@ class NestedEnumStaticClass { enum MyNestedEnum { // Compliant } - static enum MyNestedStaticEnum { // Noncompliant [[sc=3;ec=9;secondary=11]] {{Remove this redundant "static" qualifier; nested enum types are implicitly static.}} + static enum MyNestedStaticEnum { // Noncompliant {{Remove this redundant "static" qualifier; nested enum types are implicitly static.}} +//^^^^^^ ^^^^< } } diff --git a/java-checks-test-sources/default/src/main/java/checks/NestedIfStatementsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/NestedIfStatementsCheckSample.java index 908e809ca9a..fa4c17540a6 100644 --- a/java-checks-test-sources/default/src/main/java/checks/NestedIfStatementsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/NestedIfStatementsCheckSample.java @@ -18,7 +18,8 @@ private void f(int foo, boolean cond) { if (true) { // Compliant - 2 } else { if (false) { // Compliant - 3 - if (true) { // Noncompliant [[sc=11;ec=13;secondary=-1,-3,-4]] {{Refactor this code to not nest more than 3 if/for/while/switch/try statements.}} + if (true) { // Noncompliant {{Refactor this code to not nest more than 3 if/for/while/switch/try statements.}} +// ^^ if (false) { // Compliant - 5 } } else if (true) { // Compliant - 4 @@ -74,7 +75,7 @@ private void f(int foo, boolean cond) { switch (foo) { // Noncompliant } - try { // Noncompliant + try { // Noncompliant } catch (Exception e) { } } diff --git a/java-checks-test-sources/default/src/main/java/checks/NestedSwitchStatementCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/NestedSwitchStatementCheckSample.java index 4d6722d1a90..b219c871f64 100644 --- a/java-checks-test-sources/default/src/main/java/checks/NestedSwitchStatementCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/NestedSwitchStatementCheckSample.java @@ -7,11 +7,12 @@ void foo() { int myVar = 0; switch (myVar) { // Compliant case 0: - switch (0) { // Noncompliant + switch (0) { // Noncompliant case 0: case 1: System.out.println(); - switch (1){ // Noncompliant [[sc=13;ec=19;el=+0]] {{Refactor the code to eliminate this nested "switch".}} + switch (1){ // Noncompliant {{Refactor the code to eliminate this nested "switch".}} +// ^^^^^^ case 0: case 1: break; @@ -37,7 +38,7 @@ void foo() { case 2: break; default:{ - switch(4) { // Noncompliant + switch(4) { // Noncompliant case 0: switch(5) { // Noncompliant default: @@ -45,7 +46,7 @@ void foo() { } break; case 1: { - switch (6) { // Noncompliant + switch (6) { // Noncompliant case 0: break; } diff --git a/java-checks-test-sources/default/src/main/java/checks/NestedTernaryOperatorsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/NestedTernaryOperatorsCheckSample.java index 9825ffbf6af..ccada9e7f5d 100644 --- a/java-checks-test-sources/default/src/main/java/checks/NestedTernaryOperatorsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/NestedTernaryOperatorsCheckSample.java @@ -4,10 +4,14 @@ class NestedTernaryOperatorsCheckSample { void foo(boolean b) { String res; res = b ? "yo" : "lo"; - res = (b ? b : !b) ? "yo" : "lo"; // Noncompliant [[sc=12;ec=22]] {{Extract this nested ternary operation into an independent statement.}} - res = b ? b ? "yo" : "lo" : "yolo"; // Noncompliant [[sc=15;ec=30]] - res = b ? "yo" : b ? "lo" : "yolo"; // Noncompliant [[sc=22;ec=39]] - res = b ? "yo" : "lo" + (b ? "ba" : "lo"); // Noncompliant [[sc=30;ec=45]] + res = (b ? b : !b) ? "yo" : "lo"; // Noncompliant {{Extract this nested ternary operation into an independent statement.}} +// ^^^^^^^^^^ + res = b ? b ? "yo" : "lo" : "yolo"; // Noncompliant +// ^^^^^^^^^^^^^^^ + res = b ? "yo" : b ? "lo" : "yolo"; // Noncompliant +// ^^^^^^^^^^^^^^^^^ + res = b ? "yo" : "lo" + (b ? "ba" : "lo"); // Noncompliant +// ^^^^^^^^^^^^^^^ NestedTernaryOperatorsCheckSample a = b ? new NestedTernaryOperatorsCheckSample() { @Override diff --git a/java-checks-test-sources/default/src/main/java/checks/NestedTryCatchCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/NestedTryCatchCheckSample.java index 97d1dc52721..0fc5c156f95 100644 --- a/java-checks-test-sources/default/src/main/java/checks/NestedTryCatchCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/NestedTryCatchCheckSample.java @@ -42,13 +42,15 @@ public void f() throws Exception { } try { - try { // Noncompliant {{Extract this nested try block into a separate method.}} +// ^^^> + try { // Noncompliant {{Extract this nested try block into a separate method.}} } catch (Exception e) { } - try { // Noncompliant + try { // Noncompliant } catch (Exception e) { - try { // Noncompliant [[sc=9;ec=12;secondary=44]] + try { // Noncompliant +// ^^^ } catch (Exception e1) { } diff --git a/java-checks-test-sources/default/src/main/java/checks/NoCheckstyleTagPresenceCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/NoCheckstyleTagPresenceCheckSample.java index 6b2a102bf97..36f0bdeb535 100644 --- a/java-checks-test-sources/default/src/main/java/checks/NoCheckstyleTagPresenceCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/NoCheckstyleTagPresenceCheckSample.java @@ -1,10 +1,10 @@ // foo -// Noncompliant@+1 -// Noncompliant@+1 {{Remove usage of this "CHECKSTYLE:OFF" suppression comment filter.}} + // Noncompliant@+1 + // Noncompliant@+1 {{Remove usage of this "CHECKSTYLE:OFF" suppression comment filter.}} // checkStyLe:off -// Noncompliant@+5 + // Noncompliant@+5 /* checkstyle:on @@ -12,10 +12,10 @@ cHeCkStyLE:OFF */ -// Noncompliant@+1 + // Noncompliant@+1 // CHECKSTYLE:OFF -// Noncompliant@+1 + // Noncompliant@+1 // [CHECKSTYLE:OFF] // PreCheckstyle:on diff --git a/java-checks-test-sources/default/src/main/java/checks/NoPmdTagPresenceCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/NoPmdTagPresenceCheckSample.java index 72401760c64..07812fa10e1 100644 --- a/java-checks-test-sources/default/src/main/java/checks/NoPmdTagPresenceCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/NoPmdTagPresenceCheckSample.java @@ -1,21 +1,21 @@ // foo -// Noncompliant@+1 -// Noncompliant@+1 {{Remove usage of this "NOPMD" suppression comment filter.}} + // Noncompliant@+1 + // Noncompliant@+1 {{Remove usage of this "NOPMD" suppression comment filter.}} // noPMD -// Noncompliant@+5 -// Noncompliant@+3 + // Noncompliant@+5 + // Noncompliant@+3 /* nopmd NoPmD */ -// Noncompliant@+1 + // Noncompliant@+1 // NOPMD -// Noncompliant@+1 + // Noncompliant@+1 // [NOPMD] // PreNoPmd diff --git a/java-checks-test-sources/default/src/main/java/checks/NonStaticClassInitializerCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/NonStaticClassInitializerCheckSample.java index f8c0cf5b8bf..74ab428f9ab 100644 --- a/java-checks-test-sources/default/src/main/java/checks/NonStaticClassInitializerCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/NonStaticClassInitializerCheckSample.java @@ -4,7 +4,8 @@ class NonStaticClassInitializerCheckSample { static { } - { // Noncompliant [[sc=3;ec=4]] {{Move the contents of this initializer to a standard constructor or to field initializers.}} + { // Noncompliant {{Move the contents of this initializer to a standard constructor or to field initializers.}} +//^ System.out.println(); } diff --git a/java-checks-test-sources/default/src/main/java/checks/NotifyCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/NotifyCheckSample.java index c844ad0aa86..e3a4e1587be 100644 --- a/java-checks-test-sources/default/src/main/java/checks/NotifyCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/NotifyCheckSample.java @@ -6,7 +6,8 @@ class MyThread extends Thread{ public void run(){ synchronized(this){ // ... - notify(); // Noncompliant [[sc=7;ec=13;quickfixes=qf1]] {{"notify" may not wake up the appropriate thread.}} + notify(); // Noncompliant {{"notify" may not wake up the appropriate thread.}} [[quickfixes=qf1]] +// ^^^^^^ // fix@qf1 {{Replace with "notifyAll()"}} // edit@qf1 [[sc=7;ec=13]] {{notifyAll}} notifyAll(); diff --git a/java-checks-test-sources/default/src/main/java/checks/NullCheckWithInstanceofCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/NullCheckWithInstanceofCheckSample.java index 0bc58b1bebe..bd4a7851e3c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/NullCheckWithInstanceofCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/NullCheckWithInstanceofCheckSample.java @@ -12,7 +12,8 @@ private A getObject(A a) { } void foo1(Object x) { - if (x != null && x instanceof A) { // Noncompliant [[sc=9;ec=18]] {{Remove this unnecessary null check; "instanceof" returns false for nulls.}} + if (x != null && x instanceof A) { // Noncompliant {{Remove this unnecessary null check; "instanceof" returns false for nulls.}} +// ^^^^^^^^^ } if (x instanceof A) { // Compliant } @@ -20,7 +21,8 @@ void foo1(Object x) { } if (x instanceof A || x == null) { // Compliant } - if (!(x instanceof A) || x == null) { // Noncompliant [[sc=30;ec=39]] {{Remove this unnecessary null check; "instanceof" returns false for nulls.}} + if (!(x instanceof A) || x == null) { // Noncompliant {{Remove this unnecessary null check; "instanceof" returns false for nulls.}} +// ^^^^^^^^^ } if (getObject((A) c) instanceof A) { // Compliant } @@ -42,7 +44,8 @@ void foo2(NullCheckWithInstanceofCheckSample a) { } else if (a.c != null) { // Compliant } else if (a != null && a.c instanceof NullCheckWithInstanceofCheckSample) { // Compliant } else if (null != a && a instanceof NullCheckWithInstanceofCheckSample) { // Noncompliant - } else if (null == a || !(a instanceof NullCheckWithInstanceofCheckSample)) { // Noncompliant [[sc=16;ec=25]] {{Remove this unnecessary null check; "instanceof" returns false for nulls.}} + } else if (null == a || !(a instanceof NullCheckWithInstanceofCheckSample)) { // Noncompliant {{Remove this unnecessary null check; "instanceof" returns false for nulls.}} +// ^^^^^^^^^ } else if (a.c != null && a.c instanceof NullCheckWithInstanceofCheckSample) { // Noncompliant } while (a != null && a instanceof NullCheckWithInstanceofCheckSample) { // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/NullReturnedOnComputeIfPresentOrAbsent.java b/java-checks-test-sources/default/src/main/java/checks/NullReturnedOnComputeIfPresentOrAbsent.java index d1748df793e..25f18571413 100644 --- a/java-checks-test-sources/default/src/main/java/checks/NullReturnedOnComputeIfPresentOrAbsent.java +++ b/java-checks-test-sources/default/src/main/java/checks/NullReturnedOnComputeIfPresentOrAbsent.java @@ -8,8 +8,10 @@ public class NullReturnedOnComputeIfPresentOrAbsent { public void badComputeIfPresent() { Map map = new HashMap<>(); - map.computeIfPresent("myKey", (key, value) -> // Noncompliant [[sc=9;ec=25;secondary=+1]] {{Use "Map.containsKey(key)" followed by "Map.put(key, null)" to add null values.}} + map.computeIfPresent("myKey", (key, value) -> // Noncompliant {{Use "Map.containsKey(key)" followed by "Map.put(key, null)" to add null values.}} +// ^^^^^^^^^^^^^^^^ null); +// ^^^^< map.computeIfPresent("myKey", NullReturnedOnComputeIfPresentOrAbsent::presentLambda); // Compliant uninteresting corner case @@ -27,8 +29,10 @@ public void badComputeIfPresent() { public void badComputeIfAbsent() { Map map = new HashMap<>(); - map.computeIfAbsent("myKey", key -> // Noncompliant [[sc=9;ec=24;secondary=+1]] {{Use "Map.containsKey(key)" followed by "Map.put(key, null)" to add null values.}} + map.computeIfAbsent("myKey", key -> // Noncompliant {{Use "Map.containsKey(key)" followed by "Map.put(key, null)" to add null values.}} +// ^^^^^^^^^^^^^^^ null); +// ^^^^< map.computeIfAbsent("myKey", NullReturnedOnComputeIfPresentOrAbsent::absentLambda); // Compliant uninteresting corner case String nullValue = null; diff --git a/java-checks-test-sources/default/src/main/java/checks/NullShouldNotBeUsedWithOptionalCheck_guava.java b/java-checks-test-sources/default/src/main/java/checks/NullShouldNotBeUsedWithOptionalCheck_guava.java index e1d4522432f..376a7fe31cb 100644 --- a/java-checks-test-sources/default/src/main/java/checks/NullShouldNotBeUsedWithOptionalCheck_guava.java +++ b/java-checks-test-sources/default/src/main/java/checks/NullShouldNotBeUsedWithOptionalCheck_guava.java @@ -7,7 +7,8 @@ interface NullShouldNotBeUsedWithOptionalCheck_guava { - @Nullable // Noncompliant [[sc=3;ec=12]] {{Methods with an "Optional" return type should not be "@Nullable".}} + @Nullable // Noncompliant {{Methods with an "Optional" return type should not be "@Nullable".}} +//^^^^^^^^^ public Optional getOptionalKo(); } @@ -17,9 +18,11 @@ class NullShouldNotBeUsedWithOptionalCheck_guavaClassA { public NullShouldNotBeUsedWithOptionalCheck_guavaClassA() { } - @Nullable // Noncompliant [[sc=3;ec=12]] {{Methods with an "Optional" return type should not be "@Nullable".}} + @Nullable // Noncompliant {{Methods with an "Optional" return type should not be "@Nullable".}} +//^^^^^^^^^ public Optional getOptionalKo() { - return null; // Noncompliant [[sc=12;ec=16]] {{Methods with an "Optional" return type should never return null.}} + return null; // Noncompliant {{Methods with an "Optional" return type should never return null.}} +// ^^^^ } public Optional getOptionalOk() { @@ -40,14 +43,17 @@ public String work() { } public int doSomething3(Optional arg) { - if (arg == null) { // Noncompliant [[sc=9;ec=20]] {{Ensure this "Optional" could never be null and remove this null-check.}} + if (arg == null) { // Noncompliant {{Ensure this "Optional" could never be null and remove this null-check.}} +// ^^^^^^^^^^^ return 0; } Optional optional = getOptionalOk(); - if (optional == null) { // Noncompliant [[sc=9;ec=25]] {{Ensure this "Optional" could never be null and remove this null-check.}} + if (optional == null) { // Noncompliant {{Ensure this "Optional" could never be null and remove this null-check.}} +// ^^^^^^^^^^^^^^^^ return 0; - } else if (null != optional) { // Noncompliant [[sc=16;ec=32]] {{Ensure this "Optional" could never be null and remove this null-check.}} + } else if (null != optional) { // Noncompliant {{Ensure this "Optional" could never be null and remove this null-check.}} +// ^^^^^^^^^^^^^^^^ return 0; } @@ -59,7 +65,8 @@ public int doSomething3(Optional arg) { } Optional optional3 = getOptionalOk(); - return optional3 == null ? 0 : 1; // Noncompliant [[sc=12;ec=29]] {{Ensure this "Optional" could never be null and remove this null-check.}} + return optional3 == null ? 0 : 1; // Noncompliant {{Ensure this "Optional" could never be null and remove this null-check.}} +// ^^^^^^^^^^^^^^^^^ } public Optional doSomething4(List myList) { @@ -74,17 +81,21 @@ public Optional doSomething4(List myList) { @Deprecated public Optional doSomething5(List myList) { - return myList.isEmpty() ? Optional.of("hello") : null; // Noncompliant [[sc=54;ec=58]] {{Methods with an "Optional" return type should never return null.}} + return myList.isEmpty() ? Optional.of("hello") : null; // Noncompliant {{Methods with an "Optional" return type should never return null.}} +// ^^^^ } - @Nullable // Noncompliant [[sc=3;ec=12]] {{"Optional" variables should not be "@Nullable".}} + @Nullable // Noncompliant {{"Optional" variables should not be "@Nullable".}} +//^^^^^^^^^ private Optional field; - public void doSomething6(@Nullable Optional arg) { // Noncompliant [[sc=28;ec=37]] {{"Optional" variables should not be "@Nullable".}} + public void doSomething6(@Nullable Optional arg) { // Noncompliant {{"Optional" variables should not be "@Nullable".}} +// ^^^^^^^^^ } public void doSomething7() { - @Nullable // Noncompliant [[sc=5;ec=14]] {{"Optional" variables should not be "@Nullable".}} + @Nullable // Noncompliant {{"Optional" variables should not be "@Nullable".}} +// ^^^^^^^^^ Optional var; } diff --git a/java-checks-test-sources/default/src/main/java/checks/NullShouldNotBeUsedWithOptionalCheck_jdk.java b/java-checks-test-sources/default/src/main/java/checks/NullShouldNotBeUsedWithOptionalCheck_jdk.java index 9faccaab23a..cf734a953be 100644 --- a/java-checks-test-sources/default/src/main/java/checks/NullShouldNotBeUsedWithOptionalCheck_jdk.java +++ b/java-checks-test-sources/default/src/main/java/checks/NullShouldNotBeUsedWithOptionalCheck_jdk.java @@ -8,7 +8,8 @@ interface NullShouldNotBeUsedWithOptionalCheck_jdk { - @Nullable // Noncompliant [[sc=3;ec=12]] {{Methods with an "Optional" return type should not be "@Nullable".}} + @Nullable // Noncompliant {{Methods with an "Optional" return type should not be "@Nullable".}} +//^^^^^^^^^ public Optional getOptionalKo(); } @@ -18,9 +19,11 @@ class NullShouldNotBeUsedWithOptionalCheck_jdkClassA { public NullShouldNotBeUsedWithOptionalCheck_jdkClassA() { } - @Nullable // Noncompliant [[sc=3;ec=12]] {{Methods with an "Optional" return type should not be "@Nullable".}} + @Nullable // Noncompliant {{Methods with an "Optional" return type should not be "@Nullable".}} +//^^^^^^^^^ public Optional getOptionalKo() { - return null; // Noncompliant [[sc=12;ec=16]] {{Methods with an "Optional" return type should never return null.}} + return null; // Noncompliant {{Methods with an "Optional" return type should never return null.}} +// ^^^^ } public Optional getOptionalOk() { @@ -41,20 +44,25 @@ public String work() { } public int doSomething3(Optional arg) { - if (arg == null) { // Noncompliant [[sc=9;ec=20]] {{Ensure this "Optional" could never be null and remove this null-check.}} + if (arg == null) { // Noncompliant {{Ensure this "Optional" could never be null and remove this null-check.}} +// ^^^^^^^^^^^ return 0; } Optional optional = getOptionalOk(); - if (optional == null) { // Noncompliant [[sc=9;ec=25]] {{Ensure this "Optional" could never be null and remove this null-check.}} + if (optional == null) { // Noncompliant {{Ensure this "Optional" could never be null and remove this null-check.}} +// ^^^^^^^^^^^^^^^^ return 0; - } else if (null != optional) { // Noncompliant [[sc=16;ec=32]] {{Ensure this "Optional" could never be null and remove this null-check.}} + } else if (null != optional) { // Noncompliant {{Ensure this "Optional" could never be null and remove this null-check.}} +// ^^^^^^^^^^^^^^^^ return 0; } - Optional optional2 = null; // Noncompliant [[sc=34;ec=38]] {{Replace this null literal by an "Optional" object.}} + Optional optional2 = null; // Noncompliant {{Replace this null literal by an "Optional" object.}} +// ^^^^ String notOptional = null; // Compliant - optional = null; // Noncompliant [[sc=16;ec=20]] {{Replace this null literal by an "Optional" object.}} + optional = null; // Noncompliant {{Replace this null literal by an "Optional" object.}} +// ^^^^ optional = Optional.empty(); // Compliant notOptional = null; // Compliant if (optional == optional2) { @@ -64,7 +72,8 @@ public int doSomething3(Optional arg) { } Optional optional3 = getOptionalOk(); - return optional3 == null ? 0 : 1; // Noncompliant [[sc=12;ec=29]] {{Ensure this "Optional" could never be null and remove this null-check.}} + return optional3 == null ? 0 : 1; // Noncompliant {{Ensure this "Optional" could never be null and remove this null-check.}} +// ^^^^^^^^^^^^^^^^^ } public Optional doSomething4(List myList) { @@ -79,32 +88,40 @@ public Optional doSomething4(List myList) { @Deprecated public Optional doSomething5(List myList) { - return myList.isEmpty() ? Optional.of("hello") : null; // Noncompliant [[sc=54;ec=58]] {{Methods with an "Optional" return type should never return null.}} + return myList.isEmpty() ? Optional.of("hello") : null; // Noncompliant {{Methods with an "Optional" return type should never return null.}} +// ^^^^ } - @Nullable // Noncompliant [[sc=3;ec=12]] {{"Optional" variables should not be "@Nullable".}} - private Optional field = null; // Noncompliant [[sc=36;ec=40]] {{Replace this null literal by an "Optional" object.}} + @Nullable // Noncompliant {{"Optional" variables should not be "@Nullable".}} +//^^^^^^^^^ + private Optional field = null; // Noncompliant {{Replace this null literal by an "Optional" object.}} +// ^^^^ - public void doSomething6(@Nullable Optional arg) { // Noncompliant [[sc=28;ec=37]] {{"Optional" variables should not be "@Nullable".}} + public void doSomething6(@Nullable Optional arg) { // Noncompliant {{"Optional" variables should not be "@Nullable".}} +// ^^^^^^^^^ } public void doSomething7() { - @Nullable // Noncompliant [[sc=5;ec=14]] {{"Optional" variables should not be "@Nullable".}} + @Nullable // Noncompliant {{"Optional" variables should not be "@Nullable".}} +// ^^^^^^^^^ Optional var; } public void NonnullWithArgument1() { - @javax.annotation.Nonnull(when= When.MAYBE) // Noncompliant [[sc=5;ec=48]] {{"Optional" variables should not be "@Nonnull(when=MAYBE)".}} + @javax.annotation.Nonnull(when= When.MAYBE) // Noncompliant {{"Optional" variables should not be "@Nonnull(when=MAYBE)".}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Optional var; } public void NonnullWithArgument2() { - @javax.annotation.Nonnull(when= When.NEVER) // Noncompliant [[sc=5;ec=48]] {{"Optional" variables should not be "@Nonnull(when=NEVER)".}} + @javax.annotation.Nonnull(when= When.NEVER) // Noncompliant {{"Optional" variables should not be "@Nonnull(when=NEVER)".}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Optional var; } public void NonnullWithArgument3() { - @javax.annotation.Nonnull(when= When.UNKNOWN) // Noncompliant [[sc=5;ec=50]] {{"Optional" variables should not be "@Nonnull(when=UNKNOWN)".}} + @javax.annotation.Nonnull(when= When.UNKNOWN) // Noncompliant {{"Optional" variables should not be "@Nonnull(when=UNKNOWN)".}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Optional var; } diff --git a/java-checks-test-sources/default/src/main/java/checks/OSCommandsPath.java b/java-checks-test-sources/default/src/main/java/checks/OSCommandsPath.java index 032b7f55806..fb01433e85d 100644 --- a/java-checks-test-sources/default/src/main/java/checks/OSCommandsPath.java +++ b/java-checks-test-sources/default/src/main/java/checks/OSCommandsPath.java @@ -75,14 +75,16 @@ public class OSCommandsPath { private static final List NULL_INITIALIZED_COMMAND_LIST = null; public void execString() throws IOException { - Runtime.getRuntime().exec(("make")); // Noncompliant [[sc=32;ec=38]] {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec("make"); // Noncompliant [[sc=31;ec=37]] {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec("usr/bin/make"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec("m./ake"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec("m../ake"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec("bin~/make"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec("7:\\\\../ake"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec("SERVER\\make"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(("make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^ + Runtime.getRuntime().exec("make"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^ + Runtime.getRuntime().exec("usr/bin/make"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec("m./ake"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec("m../ake"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec("bin~/make"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec("7:\\\\../ake"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec("SERVER\\make"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} Runtime.getRuntime().exec("/usr/bin/make"); Runtime.getRuntime().exec("/usr/bin/make -j8"); Runtime.getRuntime().exec("../make"); @@ -93,14 +95,15 @@ public void execString() throws IOException { Runtime.getRuntime().exec(".\\make"); Runtime.getRuntime().exec("\\\\SERVER\\make"); - Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND); // Noncompliant [[sc=31;ec=52]] {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_UNIX_PARENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_UNIX_CURRENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_UNIX_HOME); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_WINDOWS_ABSOLUTE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_WINDOWS_PARENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_WINDOWS_CURRENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_WINDOWS_NETWORK); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^^^^^^^^^^^^^^^^ + Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_UNIX_PARENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_UNIX_CURRENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_UNIX_HOME); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_WINDOWS_ABSOLUTE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_WINDOWS_PARENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_WINDOWS_CURRENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_WINDOWS_NETWORK); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} Runtime.getRuntime().exec(COMPLIANT_COMMAND_UNIX_ABSOLUTE); Runtime.getRuntime().exec(COMPLIANT_COMMAND_UNIX_PARENT); Runtime.getRuntime().exec(COMPLIANT_COMMAND_UNIX_CURRENT); @@ -111,29 +114,33 @@ public void execString() throws IOException { Runtime.getRuntime().exec(COMPLIANT_COMMAND_WINDOWS_NETWORK); - Runtime.getRuntime().exec("make", ENVIRONMENT); // Noncompliant [[sc=31;ec=37]] {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec("make", ENVIRONMENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^ Runtime.getRuntime().exec("/usr/bin/make", ENVIRONMENT); - Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND, ENVIRONMENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND, ENVIRONMENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} Runtime.getRuntime().exec(COMPLIANT_COMMAND_UNIX_ABSOLUTE, ENVIRONMENT); - Runtime.getRuntime().exec("make", ENVIRONMENT, FILE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec("make", ENVIRONMENT, FILE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} Runtime.getRuntime().exec("/usr/bin/make", ENVIRONMENT, FILE); - Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND, ENVIRONMENT, FILE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND, ENVIRONMENT, FILE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} Runtime.getRuntime().exec(COMPLIANT_COMMAND_UNIX_ABSOLUTE, ENVIRONMENT, FILE); } private void execArray() throws IOException { - Runtime.getRuntime().exec((new String[]{"make"})); // Noncompliant [[sc=32;ec=52]] {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec(new String[]{("make")}); // Noncompliant [[sc=31;ec=53]] {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec(new String[]{"make"}); // Noncompliant [[sc=31;ec=51]] {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec(new String[]{"usr/bin/make"}); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec(new String[]{"m./ake"}); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec(new String[]{"m../ake"}); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec(new String[]{"bin~/make"}); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec(new String[]{"7:\\\\../ake"}); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec(new String[]{"SERVER\\make"}); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec((new String[]{"make"})); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^^^^^^^^^^^^^^^ + Runtime.getRuntime().exec(new String[]{("make")}); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^^^^^^^^^^^^^^^^^ + Runtime.getRuntime().exec(new String[]{"make"}); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^^^^^^^^^^^^^^^ + Runtime.getRuntime().exec(new String[]{"usr/bin/make"}); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(new String[]{"m./ake"}); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(new String[]{"m../ake"}); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(new String[]{"bin~/make"}); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(new String[]{"7:\\\\../ake"}); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(new String[]{"SERVER\\make"}); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} Runtime.getRuntime().exec(new String[]{}); Runtime.getRuntime().exec(new String[]{"/usr/bin/make"}); Runtime.getRuntime().exec(new String[]{"/usr/bin/make", "-j8"}); @@ -147,14 +154,14 @@ private void execArray() throws IOException { Runtime.getRuntime().exec(new String[]{File.pathSeparator}); - Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_ARRAY); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_ARRAY_UNIX_PARENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_ARRAY_UNIX_CURRENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_ARRAY_UNIX_HOME); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_ARRAY_WINDOWS_ABSOLUTE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_ARRAY_WINDOWS_PARENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_ARRAY_WINDOWS_CURRENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_ARRAY_WINDOWS_NETWORK); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_ARRAY); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_ARRAY_UNIX_PARENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_ARRAY_UNIX_CURRENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_ARRAY_UNIX_HOME); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_ARRAY_WINDOWS_ABSOLUTE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_ARRAY_WINDOWS_PARENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_ARRAY_WINDOWS_CURRENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_ARRAY_WINDOWS_NETWORK); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} Runtime.getRuntime().exec(COMPLIANT_COMMAND_ARRAY_EMPTY); Runtime.getRuntime().exec(COMPLIANT_COMMAND_ARRAY); Runtime.getRuntime().exec(COMPLIANT_COMMAND_ARRAY_UNIX_PARENT); @@ -166,27 +173,31 @@ private void execArray() throws IOException { Runtime.getRuntime().exec(COMPLIANT_COMMAND_ARRAY_WINDOWS_NETWORK); String[] nonCompliantCommandArray = new String[]{"make"}; - Runtime.getRuntime().exec(nonCompliantCommandArray); // Noncompliant [[sc=31;ec=55]] {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(nonCompliantCommandArray); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^ String[] compliantCommandArray = new String[]{"/usr/bin/make"}; Runtime.getRuntime().exec(compliantCommandArray); - Runtime.getRuntime().exec(new String[]{"make"}, ENVIRONMENT); // Noncompliant [[sc=31;ec=51]] {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(new String[]{"make"}, ENVIRONMENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^^^^^^^^^^^^^^^ Runtime.getRuntime().exec(new String[]{"/usr/bin/make"}, ENVIRONMENT); - Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_ARRAY, ENVIRONMENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_ARRAY, ENVIRONMENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} Runtime.getRuntime().exec(COMPLIANT_COMMAND_ARRAY, ENVIRONMENT); // Compliant FN Cannot read from non-final variables - Runtime.getRuntime().exec(nonCompliantCommandArray, ENVIRONMENT); // Noncompliant [[sc=31;ec=55]] {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(nonCompliantCommandArray, ENVIRONMENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^ Runtime.getRuntime().exec(compliantCommandArray, ENVIRONMENT); - Runtime.getRuntime().exec(new String[]{"make"}, ENVIRONMENT, FILE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(new String[]{"make"}, ENVIRONMENT, FILE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} Runtime.getRuntime().exec(new String[]{"/usr/bin/make"}, ENVIRONMENT, FILE); - Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_ARRAY, ENVIRONMENT, FILE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(NON_COMPLIANT_COMMAND_ARRAY, ENVIRONMENT, FILE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} Runtime.getRuntime().exec(COMPLIANT_COMMAND_ARRAY, ENVIRONMENT, FILE); // Compliant FN Cannot read from non-final variables - Runtime.getRuntime().exec(nonCompliantCommandArray, ENVIRONMENT, FILE); // Noncompliant [[sc=31;ec=55]] {{Make sure the "PATH" used to find this command includes only what you intend.}} + Runtime.getRuntime().exec(nonCompliantCommandArray, ENVIRONMENT, FILE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^ Runtime.getRuntime().exec(compliantCommandArray, ENVIRONMENT, FILE); } @@ -194,14 +205,16 @@ private void command() { ProcessBuilder builder = new ProcessBuilder(); builder.command(); - builder.command(("make")); // Noncompliant [[sc=22;ec=28]] {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command("make"); // Noncompliant [[sc=21;ec=27]] {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command("usr/bin/make"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command("m./ake"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command("m../ake"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command("bin~/make"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command("7:\\\\../ake"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command("SERVER\\make"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(("make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^ + builder.command("make"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^ + builder.command("usr/bin/make"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command("m./ake"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command("m../ake"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command("bin~/make"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command("7:\\\\../ake"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command("SERVER\\make"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} builder.command("/usr/bin/make"); builder.command("/usr/bin/make -j8"); builder.command("/usr/bin/make", "-j8"); @@ -213,14 +226,15 @@ private void command() { builder.command(".\\make"); builder.command("\\\\SERVER\\make"); - builder.command(NON_COMPLIANT_COMMAND_ARRAY); // Noncompliant [[sc=21;ec=48]] {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(NON_COMPLIANT_COMMAND_ARRAY_UNIX_PARENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(NON_COMPLIANT_COMMAND_ARRAY_UNIX_CURRENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(NON_COMPLIANT_COMMAND_ARRAY_UNIX_HOME); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(NON_COMPLIANT_COMMAND_ARRAY_WINDOWS_ABSOLUTE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(NON_COMPLIANT_COMMAND_ARRAY_WINDOWS_PARENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(NON_COMPLIANT_COMMAND_ARRAY_WINDOWS_CURRENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(NON_COMPLIANT_COMMAND_ARRAY_WINDOWS_NETWORK); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(NON_COMPLIANT_COMMAND_ARRAY); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + builder.command(NON_COMPLIANT_COMMAND_ARRAY_UNIX_PARENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(NON_COMPLIANT_COMMAND_ARRAY_UNIX_CURRENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(NON_COMPLIANT_COMMAND_ARRAY_UNIX_HOME); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(NON_COMPLIANT_COMMAND_ARRAY_WINDOWS_ABSOLUTE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(NON_COMPLIANT_COMMAND_ARRAY_WINDOWS_PARENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(NON_COMPLIANT_COMMAND_ARRAY_WINDOWS_CURRENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(NON_COMPLIANT_COMMAND_ARRAY_WINDOWS_NETWORK); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} builder.command(COMPLIANT_COMMAND_ARRAY_EMPTY); builder.command(COMPLIANT_COMMAND_ARRAY); builder.command(COMPLIANT_COMMAND_ARRAY_UNIX_PARENT); @@ -234,16 +248,19 @@ private void command() { private void commandList() { ProcessBuilder builder = new ProcessBuilder(); - builder.command((Arrays.asList("make"))); // Noncompliant [[sc=22;ec=43]] {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(Arrays.asList(("make"))); // Noncompliant [[sc=21;ec=44]] {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(Arrays.asList("make")); // Noncompliant [[sc=21;ec=42]] {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(Arrays.asList("m../ake")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(Arrays.asList("mak./e")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(Arrays.asList("bin~/make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(Arrays.asList("7:\\\\make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(Arrays.asList("m..\\ake")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(Arrays.asList("ma.\\ke")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(Arrays.asList("SERVER\\make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command((Arrays.asList("make"))); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^^^^^^^^^^^^^^^^ + builder.command(Arrays.asList(("make"))); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^^^^^^^^^^^^^^^^^^ + builder.command(Arrays.asList("make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^^^^^^^^^^^^^^^^ + builder.command(Arrays.asList("m../ake")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(Arrays.asList("mak./e")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(Arrays.asList("bin~/make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(Arrays.asList("7:\\\\make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(Arrays.asList("m..\\ake")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(Arrays.asList("ma.\\ke")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(Arrays.asList("SERVER\\make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} builder.command(Arrays.asList("/usr/bin/make")); builder.command(Arrays.asList("/usr/bin/make -j8")); builder.command(Arrays.asList("/usr/bin/make", "-j8")); @@ -255,15 +272,15 @@ private void commandList() { builder.command(Arrays.asList(".\\make")); builder.command(Arrays.asList("\\\\SERVER\\make")); - builder.command(NON_COMPLIANT_COMMAND_LIST); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(NON_COMPLIANT_COMMAND_LIST_UNIX_PARENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(NON_COMPLIANT_COMMAND_LIST_UNIX_CURRENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(NON_COMPLIANT_COMMAND_LIST_UNIX_HOME); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(NON_COMPLIANT_COMMAND_LIST_WINDOWS_ABSOLUTE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(NON_COMPLIANT_COMMAND_LIST_WINDOWS_PARENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(NON_COMPLIANT_COMMAND_LIST_WINDOWS_CURRENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(NON_COMPLIANT_COMMAND_LIST_WINDOWS_NETWORK); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(NON_COMPLIANT_COMMAND_LIST_VARIABLE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(NON_COMPLIANT_COMMAND_LIST); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(NON_COMPLIANT_COMMAND_LIST_UNIX_PARENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(NON_COMPLIANT_COMMAND_LIST_UNIX_CURRENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(NON_COMPLIANT_COMMAND_LIST_UNIX_HOME); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(NON_COMPLIANT_COMMAND_LIST_WINDOWS_ABSOLUTE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(NON_COMPLIANT_COMMAND_LIST_WINDOWS_PARENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(NON_COMPLIANT_COMMAND_LIST_WINDOWS_CURRENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(NON_COMPLIANT_COMMAND_LIST_WINDOWS_NETWORK); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(NON_COMPLIANT_COMMAND_LIST_VARIABLE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} builder.command(COMPLIANT_COMMAND_LIST_UNIX); builder.command(COMPLIANT_COMMAND_LIST_UNIX_PARENT); builder.command(COMPLIANT_COMMAND_LIST_UNIX_CURRENT); @@ -273,14 +290,15 @@ private void commandList() { builder.command(COMPLIANT_COMMAND_LIST_WINDOWS_CURRENT); builder.command(COMPLIANT_COMMAND_LIST_WINDOWS_NETWORK); - builder.command(Collections.singletonList("make")); // Noncompliant [[sc=21;ec=54]] {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(Collections.singletonList("m../ake")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(Collections.singletonList("mak./e")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(Collections.singletonList("bin~/make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(Collections.singletonList("7:\\\\make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(Collections.singletonList("m..\\ake")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(Collections.singletonList("ma.\\ke")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - builder.command(Collections.singletonList("SERVER\\make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(Collections.singletonList("make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + builder.command(Collections.singletonList("m../ake")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(Collections.singletonList("mak./e")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(Collections.singletonList("bin~/make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(Collections.singletonList("7:\\\\make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(Collections.singletonList("m..\\ake")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(Collections.singletonList("ma.\\ke")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + builder.command(Collections.singletonList("SERVER\\make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} builder.command(Collections.singletonList("/usr/bin/make")); builder.command(Collections.singletonList("/usr/bin/make -j8")); builder.command(Collections.singletonList("../make")); @@ -293,15 +311,17 @@ private void commandList() { } private void processBuilder() { - new ProcessBuilder(("make")); // Noncompliant [[sc=25;ec=31]] {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder("make"); // Noncompliant [[sc=24;ec=30]] {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder("m../ake"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder("mak./e"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder("bin~/make"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder("7:\\\\make"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder("m..\\ake"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder("ma.\\ke"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder("SERVER\\make"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(("make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^ + new ProcessBuilder("make"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^ + new ProcessBuilder("m../ake"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder("mak./e"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder("bin~/make"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder("7:\\\\make"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder("m..\\ake"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder("ma.\\ke"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder("SERVER\\make"); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} new ProcessBuilder("/usr/bin/make"); new ProcessBuilder("/usr/bin/make -j8"); new ProcessBuilder("/usr/bin/make", "-j8"); @@ -313,14 +333,15 @@ private void processBuilder() { new ProcessBuilder(".\\make"); new ProcessBuilder("\\\\SERVER\\make"); - new ProcessBuilder(NON_COMPLIANT_COMMAND); // Noncompliant [[sc=24;ec=45]] {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(NON_COMPLIANT_COMMAND_UNIX_PARENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(NON_COMPLIANT_COMMAND_UNIX_CURRENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(NON_COMPLIANT_COMMAND_UNIX_HOME); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(NON_COMPLIANT_COMMAND_WINDOWS_ABSOLUTE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(NON_COMPLIANT_COMMAND_WINDOWS_PARENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(NON_COMPLIANT_COMMAND_WINDOWS_CURRENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(NON_COMPLIANT_COMMAND_WINDOWS_NETWORK); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(NON_COMPLIANT_COMMAND); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^^^^^^^^^^^^^^^^ + new ProcessBuilder(NON_COMPLIANT_COMMAND_UNIX_PARENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(NON_COMPLIANT_COMMAND_UNIX_CURRENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(NON_COMPLIANT_COMMAND_UNIX_HOME); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(NON_COMPLIANT_COMMAND_WINDOWS_ABSOLUTE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(NON_COMPLIANT_COMMAND_WINDOWS_PARENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(NON_COMPLIANT_COMMAND_WINDOWS_CURRENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(NON_COMPLIANT_COMMAND_WINDOWS_NETWORK); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} new ProcessBuilder(COMPLIANT_COMMAND_UNIX_ABSOLUTE); new ProcessBuilder(COMPLIANT_COMMAND_UNIX_PARENT); new ProcessBuilder(COMPLIANT_COMMAND_UNIX_CURRENT); @@ -332,16 +353,19 @@ private void processBuilder() { } private void processBuilderList() { - new ProcessBuilder((Arrays.asList("make"))); // Noncompliant [[sc=25;ec=46]] {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(Arrays.asList(("make"))); // Noncompliant [[sc=24;ec=47]] {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(Arrays.asList("make")); // Noncompliant [[sc=24;ec=45]] {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(Arrays.asList("m../ake")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(Arrays.asList("mak./e")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(Arrays.asList("bin~/make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(Arrays.asList("7:\\\\make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(Arrays.asList("m..\\ake")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(Arrays.asList("ma.\\ke")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(Arrays.asList("SERVER\\make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder((Arrays.asList("make"))); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^^^^^^^^^^^^^^^^ + new ProcessBuilder(Arrays.asList(("make"))); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^^^^^^^^^^^^^^^^^^ + new ProcessBuilder(Arrays.asList("make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^^^^^^^^^^^^^^^^ + new ProcessBuilder(Arrays.asList("m../ake")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(Arrays.asList("mak./e")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(Arrays.asList("bin~/make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(Arrays.asList("7:\\\\make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(Arrays.asList("m..\\ake")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(Arrays.asList("ma.\\ke")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(Arrays.asList("SERVER\\make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} new ProcessBuilder(Arrays.asList()); new ProcessBuilder(Arrays.asList("/usr/bin/make")); new ProcessBuilder(Arrays.asList("/usr/bin/make -j8")); @@ -354,15 +378,16 @@ private void processBuilderList() { new ProcessBuilder(Arrays.asList(".\\make")); new ProcessBuilder(Arrays.asList("\\\\SERVER\\make")); - new ProcessBuilder(NON_COMPLIANT_COMMAND_LIST); // Noncompliant [[sc=24;ec=50]] {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(NON_COMPLIANT_COMMAND_LIST_UNIX_PARENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(NON_COMPLIANT_COMMAND_LIST_UNIX_CURRENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(NON_COMPLIANT_COMMAND_LIST_UNIX_HOME); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(NON_COMPLIANT_COMMAND_LIST_WINDOWS_ABSOLUTE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(NON_COMPLIANT_COMMAND_LIST_WINDOWS_PARENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(NON_COMPLIANT_COMMAND_LIST_WINDOWS_CURRENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(NON_COMPLIANT_COMMAND_LIST_WINDOWS_NETWORK); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(NON_COMPLIANT_COMMAND_LIST_VARIABLE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(NON_COMPLIANT_COMMAND_LIST); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^ + new ProcessBuilder(NON_COMPLIANT_COMMAND_LIST_UNIX_PARENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(NON_COMPLIANT_COMMAND_LIST_UNIX_CURRENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(NON_COMPLIANT_COMMAND_LIST_UNIX_HOME); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(NON_COMPLIANT_COMMAND_LIST_WINDOWS_ABSOLUTE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(NON_COMPLIANT_COMMAND_LIST_WINDOWS_PARENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(NON_COMPLIANT_COMMAND_LIST_WINDOWS_CURRENT); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(NON_COMPLIANT_COMMAND_LIST_WINDOWS_NETWORK); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(NON_COMPLIANT_COMMAND_LIST_VARIABLE); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} new ProcessBuilder(COMPLIANT_COMMAND_LIST_UNIX); new ProcessBuilder(COMPLIANT_COMMAND_LIST_UNIX_PARENT); new ProcessBuilder(COMPLIANT_COMMAND_LIST_UNIX_CURRENT); @@ -372,14 +397,15 @@ private void processBuilderList() { new ProcessBuilder(COMPLIANT_COMMAND_LIST_WINDOWS_CURRENT); new ProcessBuilder(COMPLIANT_COMMAND_LIST_WINDOWS_NETWORK); - new ProcessBuilder(Collections.singletonList("make")); // Noncompliant [[sc=24;ec=57]] {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(Collections.singletonList("m../ake")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(Collections.singletonList("mak./e")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(Collections.singletonList("bin~/make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(Collections.singletonList("7:\\\\make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(Collections.singletonList("m..\\ake")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(Collections.singletonList("ma.\\ke")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} - new ProcessBuilder(Collections.singletonList("SERVER\\make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(Collections.singletonList("make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + new ProcessBuilder(Collections.singletonList("m../ake")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(Collections.singletonList("mak./e")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(Collections.singletonList("bin~/make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(Collections.singletonList("7:\\\\make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(Collections.singletonList("m..\\ake")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(Collections.singletonList("ma.\\ke")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} + new ProcessBuilder(Collections.singletonList("SERVER\\make")); // Noncompliant {{Make sure the "PATH" used to find this command includes only what you intend.}} new ProcessBuilder(Collections.singletonList("/usr/bin/make")); new ProcessBuilder(Collections.singletonList("/usr/bin/make -j8")); new ProcessBuilder(Collections.singletonList("../make")); diff --git a/java-checks-test-sources/default/src/main/java/checks/ObjectCreatedOnlyToCallGetClassCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ObjectCreatedOnlyToCallGetClassCheckSample.java index 72e3de2eb57..6aeb2a6d559 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ObjectCreatedOnlyToCallGetClassCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ObjectCreatedOnlyToCallGetClassCheckSample.java @@ -15,7 +15,8 @@ void foo() { getClass(); // Compliant new CallGetClassCheck_C().getClass(); // Noncompliant {{Remove this object instantiation and use "CallGetClassCheck_C.class" instead.}} - CallGetClassCheck_A a2 = new CallGetClassCheck_C(); // Noncompliant [[sc=30;ec=55]] {{Remove this object instantiation and use "CallGetClassCheck_C.class" instead.}} + CallGetClassCheck_A a2 = new CallGetClassCheck_C(); // Noncompliant {{Remove this object instantiation and use "CallGetClassCheck_C.class" instead.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^ a2.getClass(); CallGetClassCheck_A a3 = new CallGetClassCheck_A(); // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/ObjectFinalizeCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ObjectFinalizeCheckSample.java index 71311e6c799..781cd572d37 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ObjectFinalizeCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ObjectFinalizeCheckSample.java @@ -17,14 +17,15 @@ void finalize(int i) {} void foo() throws Throwable { Foo foo = new Foo(); - foo.finalize(); // Noncompliant [[sc=9;ec=17]] {{Remove this call to finalize().}} + foo.finalize(); // Noncompliant {{Remove this call to finalize().}} +// ^^^^^^^^ x = foo.finalize[0]; // Compliant foo.finalize(0); // Compliant foo.toString(); // Compliant x = foo.finalize; // Compliant - super.finalize(); // Noncompliant {{Remove this call to finalize().}} - this.finalize(); // Noncompliant {{Remove this call to finalize().}} - finalize(); // Noncompliant {{Remove this call to finalize().}} + super.finalize(); // Noncompliant {{Remove this call to finalize().}} + this.finalize(); // Noncompliant {{Remove this call to finalize().}} + finalize(); // Noncompliant {{Remove this call to finalize().}} } public int bar() { diff --git a/java-checks-test-sources/default/src/main/java/checks/ObjectFinalizeOverriddenCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ObjectFinalizeOverriddenCheckSample.java index 215ddb1f4f5..f67574fd624 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ObjectFinalizeOverriddenCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ObjectFinalizeOverriddenCheckSample.java @@ -24,7 +24,8 @@ class ObjectFinalizeOverriddenCheckSample { class Foo { @Override - protected void finalize() throws Throwable { // Noncompliant [[sc=20;ec=28]] {{Do not override the Object.finalize() method.}} + protected void finalize() throws Throwable { // Noncompliant {{Do not override the Object.finalize() method.}} +// ^^^^^^^^ } public void foo() { // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/ObjectFinalizeOverridenCallsSuperFinalizeCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ObjectFinalizeOverridenCallsSuperFinalizeCheckSample.java index 9dc23d867e2..fbe848c6863 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ObjectFinalizeOverridenCallsSuperFinalizeCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ObjectFinalizeOverridenCallsSuperFinalizeCheckSample.java @@ -11,14 +11,16 @@ protected void finalize() throws Throwable { // Compliant class S1114_Case_2 extends S1114_Class3 { @Override protected void finalize() throws Throwable { - super.finalize(); // Noncompliant [[sc=5;ec=21]] {{Move this super.finalize() call to the end of this Object.finalize() implementation.}} + super.finalize(); // Noncompliant {{Move this super.finalize() call to the end of this Object.finalize() implementation.}} +// ^^^^^^^^^^^^^^^^ System.out.println("foo"); } } class S1114_Case_3 extends S1114_Class3 { @Override - protected void finalize() throws Throwable { // Noncompliant [[sc=18;ec=26]] {{Add a call to super.finalize() at the end of this Object.finalize() implementation.}} + protected void finalize() throws Throwable { // Noncompliant {{Add a call to super.finalize() at the end of this Object.finalize() implementation.}} +// ^^^^^^^^ new S1114_MyObject().finalize(); System.out.println("foo"); } @@ -26,7 +28,7 @@ class S1114_Case_3 extends S1114_Class3 { class S1114_Case_4 extends S1114_Class3 { @Override - protected void finalize() throws Throwable { // Noncompliant {{Add a call to super.finalize() at the end of this Object.finalize() implementation.}} + protected void finalize() throws Throwable { // Noncompliant {{Add a call to super.finalize() at the end of this Object.finalize() implementation.}} S1114_MyObject object = new S1114_MyObject(); object.finalize(); System.out.println("foo"); @@ -35,7 +37,7 @@ protected void finalize() throws Throwable { // Noncompliant {{Add a call to su class S1114_Case_5 extends S1114_Class3 { @Override - protected void finalize() throws Throwable { // Noncompliant {{Add a call to super.finalize() at the end of this Object.finalize() implementation.}} + protected void finalize() throws Throwable { // Noncompliant {{Add a call to super.finalize() at the end of this Object.finalize() implementation.}} finalize(); System.out.println("foo"); } @@ -43,13 +45,13 @@ protected void finalize() throws Throwable { // Noncompliant {{Add a call to su class S1114_Case_6 extends S1114_Class3 { @Override - protected void finalize() throws Throwable { // Noncompliant {{Add a call to super.finalize() at the end of this Object.finalize() implementation.}} + protected void finalize() throws Throwable { // Noncompliant {{Add a call to super.finalize() at the end of this Object.finalize() implementation.}} } } class S1114_Case_7 extends S1114_Class3 { @Override - protected void finalize() throws Throwable { // Noncompliant + protected void finalize() throws Throwable { // Noncompliant System.out.println("foo"); super.foo(); } @@ -66,7 +68,7 @@ protected void finalize() throws Throwable { if (test) { super.finalize(); } else { - super.finalize(); // Noncompliant + super.finalize(); // Noncompliant } } } @@ -88,7 +90,7 @@ protected void finalize() throws Throwable { try { // ... } finally { - super.finalize(); // Noncompliant + super.finalize(); // Noncompliant System.out.println(); } } @@ -99,7 +101,7 @@ protected void finalize() throws Throwable { try { // ... } catch (Exception e) { - super.finalize(); // Noncompliant + super.finalize(); // Noncompliant } } @@ -114,7 +116,7 @@ public void finalize(Object object) { class S1114_Class2 extends S1114_Class1 { @Override - protected void finalize() throws Throwable { // Noncompliant {{Add a call to super.finalize() at the end of this Object.finalize() implementation.}} + protected void finalize() throws Throwable { // Noncompliant {{Add a call to super.finalize() at the end of this Object.finalize() implementation.}} } } @@ -142,7 +144,7 @@ protected void finalize() throws Throwable { class CutControlFlowInnerClass extends S1114_Class1 { @Override - protected void finalize() throws Throwable { // Noncompliant, there is no call to finalize here + protected void finalize() throws Throwable { // Noncompliant class InnerClass { void foo() throws Throwable { super.finalize(); @@ -153,7 +155,7 @@ void foo() throws Throwable { class CutControlFlowLambda extends S1114_Class1 { @Override - protected void finalize() throws Throwable { // Noncompliant, there is no call to finalize here + protected void finalize() throws Throwable { // Noncompliant ThrowingRunnable r = () -> super.finalize(); foo(); @@ -167,7 +169,7 @@ private static interface ThrowingRunnable { class ScanAlsoInnerClasses extends S1114_Class1 { @Override - protected void finalize() throws Throwable { // Noncompliant, there is no call to finalize here + protected void finalize() throws Throwable { // Noncompliant class InnerClassCompliant extends S1114_Class1 { @Override public void finalize() throws Throwable { // Compliant, this call is not inside the control flow of a finalize method @@ -177,7 +179,7 @@ public void finalize() throws Throwable { // Compliant, this call is not inside class InnerClassNonCompliant extends S1114_Class1 { @Override - public void finalize() throws Throwable { // Noncompliant, there is no call to finalize here + public void finalize() throws Throwable { // Noncompliant foo(); } } @@ -193,7 +195,7 @@ public void finalize() throws Throwable { // Compliant, this call is not inside class InnerClassNonCompliant extends S1114_Class1 { @Override - public void finalize() throws Throwable { // Noncompliant, there is no call to finalize here + public void finalize() throws Throwable { // Noncompliant foo(); } } @@ -208,7 +210,7 @@ public void finalize() throws Throwable { // Compliant, this call is not inside class InnerClassNonCompliant extends S1114_Class1 { @Override - public void finalize() throws Throwable { // Noncompliant, there is no call to finalize here + public void finalize() throws Throwable { // Noncompliant foo(); } } diff --git a/java-checks-test-sources/default/src/main/java/checks/ObjectFinalizeOverridenNotPublicCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ObjectFinalizeOverridenNotPublicCheckSample.java index aa4aafcaa43..647a2502ef2 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ObjectFinalizeOverridenNotPublicCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ObjectFinalizeOverridenNotPublicCheckSample.java @@ -2,7 +2,8 @@ class ObjectFinalizeOverridenNotPublicCheckSample_Noncompliant { @Override - public void finalize() throws Throwable { // Noncompliant [[sc=15;ec=23]] {{Make this finalize() method protected.}} + public void finalize() throws Throwable { // Noncompliant {{Make this finalize() method protected.}} +// ^^^^^^^^ } } diff --git a/java-checks-test-sources/default/src/main/java/checks/OmitPermittedTypesCheck/OmitPermittedTypesCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/OmitPermittedTypesCheck/OmitPermittedTypesCheckSample.java index 6b2082a56ec..c6251c4b927 100644 --- a/java-checks-test-sources/default/src/main/java/checks/OmitPermittedTypesCheck/OmitPermittedTypesCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/OmitPermittedTypesCheck/OmitPermittedTypesCheckSample.java @@ -1,12 +1,17 @@ package checks.OmitPermittedTypesCheck; -sealed class InSameFileA permits // Noncompliant [[sc=26;ec=33;secondary=+1,+2,+3,+4;quickfixes=qf0]] {{Remove this redundant permitted list.}} +sealed class InSameFileA permits // Noncompliant {{Remove this redundant permitted list.}} [[quickfixes=qf0]] +// ^^^^^^^ InSameFileB, +//^^^^^^^^^^^< InSameFileC, +//^^^^^^^^^^^< InSameFileD, +//^^^^^^^^^^^< InSameFileE {} +//^^^^^^^^^^^< // fix@qf0 {{Remove permitted list}} -// edit@qf0 [[sl=3;sc=26;el=7;ec=15]] {{}} +// edit@qf0 [[sl=3;sc=26;el=11;ec=15]] {{}} final class InSameFileB extends InSameFileA {} final class InSameFileC extends InSameFileA {} final class InSameFileD extends InSameFileA {} @@ -17,11 +22,13 @@ final class InSameClassB extends InSameClassA {} final class InSameClassC extends InSameClassA {} } -sealed class InSameFile2A permits InSameFile2B, InSameFile2C {} // Noncompliant [[sc=27;ec=34;quickfixes=qf1]] +sealed class InSameFile2A permits InSameFile2B, InSameFile2C {} // Noncompliant [[quickfixes=qf1]] +// ^^^^^^^ // fix@qf1 {{Remove permitted list}} // edit@qf1 [[sc=27;ec=62]] {{}} final class InSameFile2B extends InSameFile2A {} -sealed class InSameFile2C extends InSameFile2A permits InSameFile2D {} // Noncompliant [[sc=48;ec=55;quickfixes=qf2]] {{Remove this redundant permitted list.}} +sealed class InSameFile2C extends InSameFile2A permits InSameFile2D {} // Noncompliant {{Remove this redundant permitted list.}} [[quickfixes=qf2]] +// ^^^^^^^ // fix@qf2 {{Remove permitted list}} // edit@qf2 [[sc=48;ec=69]] {{}} non-sealed class InSameFile2D extends InSameFile2C {} diff --git a/java-checks-test-sources/default/src/main/java/checks/OneClassInterfacePerFileCheckNoncompliant.java b/java-checks-test-sources/default/src/main/java/checks/OneClassInterfacePerFileCheckNoncompliant.java index 016e03d2240..686bcd02ca4 100644 --- a/java-checks-test-sources/default/src/main/java/checks/OneClassInterfacePerFileCheckNoncompliant.java +++ b/java-checks-test-sources/default/src/main/java/checks/OneClassInterfacePerFileCheckNoncompliant.java @@ -11,3 +11,5 @@ enum OneClassInterfacePerFileCheckNoncompliantC { @interface OneClassInterfacePerFileCheckNoncompliantD { } + +// Noncompliant@0 {{There are 4 top-level types in this file; move all but one of them to other files.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/OneDeclarationPerLineCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/OneDeclarationPerLineCheckSample.java index dcc191a3862..3b970193f10 100644 --- a/java-checks-test-sources/default/src/main/java/checks/OneDeclarationPerLineCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/OneDeclarationPerLineCheckSample.java @@ -4,154 +4,8 @@ class OneDeclarationPerLineCheckSample { - interface MyInterface { - int a = 1, b = 1; // Noncompliant [[sc=16;ec=17]] {{Declare "b" on a separate line.}} - } - - enum MyEnum { - ONE, TWO; - int a, b; // Noncompliant - } - - @interface annotationType { - int a = 0, b = 0; // Noncompliant - } - - private static final int STATIC_FINAL_A = 1, STATIC_FINAL_B = 1; // Noncompliant {{Declare "STATIC_FINAL_B" on a separate line.}} - - static { - int staticA, staticB = 1; // Noncompliant {{Declare "staticB" on a separate line.}} - int staticC = 1; int staticD; // Noncompliant {{Declare "staticD" on a separate line.}} - } - - int a; int b; int c; int d; // Noncompliant [[sc=14;ec=15;secondary=+0,+0]] {{Declare "b" and all following declarations on a separate line.}} - int e; - - private int j1 = -1, j2 // Noncompliant [[sc=24;ec=26;secondary=+2,+4]] {{Declare "j2" and all following declarations on a separate line.}} - - , j3 = 1 - - , j4; - - private int i1 = -1, i2, i3 = 1; // Noncompliant [[sc=24;ec=26;secondary=+0]] {{Declare "i2" and all following declarations on a separate line.}} - - ; - - // For corner case test, please add a space before ; - Object o1, o2 ; // Noncompliant {{Declare "o2" on a separate line.}} - - private String s1; // Compliant, only one on the line - - OneDeclarationPerLineCheckSample(){ - int const1,const2; // Noncompliant {{Declare "const2" on a separate line.}} - } - - public void method() { - int i4 = 0, i5 = -1; // Noncompliant {{Declare "i5" on a separate line.}} - int i6 = 1; // Compliant, only one on the line - - for (int i = 0, j = 0; i < 1; i++) { // Compliant in statment declaration - int forA, forB; // Noncompliant {{Declare "forB" on a separate line.}} - forA = i; - forB = j; - int forAfterA = forA, forAfterB; // Noncompliant {{Declare "forAfterB" on a separate line.}} - int forAfterC; int forAfterD = forB; // Noncompliant {{Declare "forAfterD" on a separate line.}} - } - } - - public void cornerCase(int a, int b) { // should not raise an issue - try { - } catch(Exception e) { // NPE verify (variable w/o endToken) - } - - for (Object o : Collections.emptyList()) { // NPE verify (variable w/o endToken) - } - - - switch (2) { - case 1: - int a1, b1 = 0; // Noncompliant - break; - case 2: - break; - } - } - class reportedAfterMethod { - int i; int j; // Noncompliant - void f() {} - int k; int l; // Noncompliant - } - - void mixedAreReportedTogether() { - int k; int l; int m, n; // Noncompliant [[sc=16;ec=17;secondary=+0,+0;quickfixes=qf_mixed1]] - // fix@qf_mixed1 {{Declare on separated lines}} - // edit@qf_mixed1 [[sc=11;ec=12]] {{\n }} - // edit@qf_mixed1 [[sc=18;ec=19]] {{\n }} - // edit@qf_mixed1 [[sc=24;ec=26]] {{;\n int }} - - int k1; int l1, m1; int n1; // Noncompliant [[sc=17;ec=19;secondary=+0,+0;quickfixes=qf_mixed2]] - // fix@qf_mixed2 {{Declare on separated lines}} - // edit@qf_mixed2 [[sc=12;ec=13]] {{\n }} - // edit@qf_mixed2 [[sc=19;ec=21]] {{;\n int }} - // edit@qf_mixed2 [[sc=24;ec=25]] {{\n }} - } - - class TestQuickFix { - int i; int j; // Noncompliant [[sc=16;ec=17;quickfixes=qf1]] - // fix@qf1 {{Declare on separated lines}} - // edit@qf1 [[sc=11;ec=12]] {{\n }} - - int i2; int j2; int k2; int l2;// Noncompliant [[sc=17;ec=19;quickfixes=qf2]] - // fix@qf2 {{Declare on separated lines}} - // edit@qf2 [[sc=12;ec=13]] {{\n }} - // edit@qf2 [[sc=20;ec=25]] {{\n }} - // edit@qf2 [[sc=32;ec=36]] {{\n }} - - int i3, j3; // Noncompliant [[sc=13;ec=15;quickfixes=qf3]] - // fix@qf3 {{Declare on separated lines}} - // edit@qf3 [[sc=11;ec=13]] {{;\n int }} - - int i4, j4, k4, l4; // Noncompliant [[sc=13;ec=15;quickfixes=qf4]] - // fix@qf4 {{Declare on separated lines}} - // edit@qf4 [[sc=11;ec=13]] {{;\n int }} - // edit@qf4 [[sc=15;ec=17]] {{;\n int }} - // edit@qf4 [[sc=19;ec=21]] {{;\n int }} - - final int i5 = 1, j5 = 1; // Noncompliant [[sc=23;ec=25;quickfixes=qf5]] - // fix@qf5 {{Declare on separated lines}} - // edit@qf5 [[sc=21;ec=23]] {{;\n final int }} - - int i6, - - j6, // Noncompliant [[sc=5;ec=7;quickfixes=qf6]] - - - k6; - // fix@qf6 {{Declare on separated lines}} - // edit@qf6 [[sl=-2;sc=11;el=+0;ec=5]] {{;\n int }} - // edit@qf6 [[sl=+0;sc=7;el=+3;ec=8]] {{;\n int }} - - void m() { - int i7; m(); int j7; // Noncompliant [[sc=24;ec=26;quickfixes=qf17]] - // fix@qf17 {{Declare on separated lines}} - // edit@qf17 [[sc=19;ec=20]] {{\n }} - } - } - - int correct; int indentation; // Noncompliant [[sc=20;ec=31;quickfixes=qf_indentation]] - // fix@qf_indentation {{Declare on separated lines}} - // edit@qf_indentation [[sc=15;ec=16]] {{\n }} - -int no; int spaceBefore; // Noncompliant [[sc=13;ec=24;quickfixes=qf_indentation2]] + int no; int spaceBefore; // Noncompliant [[quickfixes=qf_indentation2]] +// ^^^^^^^^^^^ // fix@qf_indentation2 {{Declare on separated lines}} - // edit@qf_indentation2 [[sc=8;ec=9]] {{\n}} - - // Noncompliant@+1 {{Declare "i8" on a separate line.}} - int i7; int i8; - int i9, - i10; // Noncompliant {{Declare "i10" on a separate line.}} - // For corner case test, last variable must be a "dubble" declaration with no simple declaration after ; and end token on next line. - // Noncompliant@+1 {{Declare "i12" on a separate line.}} - int i11; int i12 - ; + // edit@qf_indentation2 [[sc=10;ec=11]] {{\n }} } diff --git a/java-checks-test-sources/default/src/main/java/checks/OptionalAsParameterCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/OptionalAsParameterCheckSample.java index 7a467f1aa47..1e92f958a0b 100644 --- a/java-checks-test-sources/default/src/main/java/checks/OptionalAsParameterCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/OptionalAsParameterCheckSample.java @@ -20,15 +20,22 @@ ResponseEntity getFoo(@PathVariable Optional id, @RequestParam(value void foo(@Nullable OptionalAsParameterCheckSample a) {} // Compliant - void foo(Optional a) {} // Noncompliant [[sc=12;ec=52]] {{Specify a "OptionalAsParameterCheckSample" parameter instead.}} - void bar(Optional o) {} // Noncompliant [[sc=12;ec=20]] {{Specify a type instead.}} - - void foo(com.google.common.base.Optional a) {} // Noncompliant [[sc=12;ec=75]] {{Specify a "OptionalAsParameterCheckSample" parameter instead.}} - void bar(com.google.common.base.Optional o) {} // Noncompliant [[sc=12;ec=43]] {{Specify a type instead.}} - - void foo(OptionalInt i) {} // Noncompliant [[sc=12;ec=23]] {{Specify a "int" parameter instead.}} - void foo(OptionalLong l) {} // Noncompliant [[sc=12;ec=24]] {{Specify a "long" parameter instead.}} - void foo(OptionalDouble d) {} // Noncompliant [[sc=12;ec=26]] {{Specify a "double" parameter instead.}} + void foo(Optional a) {} // Noncompliant {{Specify a "OptionalAsParameterCheckSample" parameter instead.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + void bar(Optional o) {} // Noncompliant {{Specify a type instead.}} +// ^^^^^^^^ + + void foo(com.google.common.base.Optional a) {} // Noncompliant {{Specify a "OptionalAsParameterCheckSample" parameter instead.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + void bar(com.google.common.base.Optional o) {} // Noncompliant {{Specify a type instead.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + void foo(OptionalInt i) {} // Noncompliant {{Specify a "int" parameter instead.}} +// ^^^^^^^^^^^ + void foo(OptionalLong l) {} // Noncompliant {{Specify a "long" parameter instead.}} +// ^^^^^^^^^^^^ + void foo(OptionalDouble d) {} // Noncompliant {{Specify a "double" parameter instead.}} +// ^^^^^^^^^^^^^^ } class Child extends OptionalAsParameterCheckSample { diff --git a/java-checks-test-sources/default/src/main/java/checks/OutputStreamOverrideWriteCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/OutputStreamOverrideWriteCheckSample.java index 3ea6ad94c6b..416c5810931 100644 --- a/java-checks-test-sources/default/src/main/java/checks/OutputStreamOverrideWriteCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/OutputStreamOverrideWriteCheckSample.java @@ -5,7 +5,8 @@ import java.io.IOException; import java.io.OutputStream; -class S4349 extends OutputStream { // Noncompliant [[sc=7;ec=12]]{{Provide an override of "write(byte[],int,int)" for this class.}} +class S4349 extends OutputStream { // Noncompliant {{Provide an override of "write(byte[],int,int)" for this class.}} +// ^^^^^ private FileOutputStream fout; public S4349(File file) throws IOException { diff --git a/java-checks-test-sources/default/src/main/java/checks/OverrideAnnotationCheck_QuickFixes.java b/java-checks-test-sources/default/src/main/java/checks/OverrideAnnotationCheck_QuickFixes.java index e5459c4ff7e..ac14e77af2d 100644 --- a/java-checks-test-sources/default/src/main/java/checks/OverrideAnnotationCheck_QuickFixes.java +++ b/java-checks-test-sources/default/src/main/java/checks/OverrideAnnotationCheck_QuickFixes.java @@ -10,7 +10,8 @@ interface I { } class B extends A implements I { - void foo() {} // Noncompliant [[sc=10;ec=13;quickfixes=qf1]] + void foo() {} // Noncompliant [[quickfixes=qf1]] +// ^^^ // fix@qf1 {{Add "@Override" annotation}} // edit@qf1 [[sc=5;ec=5]] {{@Override\n }} @@ -29,7 +30,8 @@ static class ExtendsAbstractClass extends AbstractClass { boolean foo() { return false; } // Compliant - overridee is abstract @Deprecated - public boolean bar() { return true; } // Noncompliant [[sc=22;ec=25;quickfixes=qf2]] + public boolean bar() { return true; } // Noncompliant [[quickfixes=qf2]] +// ^^^ // fix@qf2 {{Add "@Override" annotation}} // edit@qf2 [[sl=-1;sc=7;el=-1;ec=7]] {{@Override\n }} } @@ -37,7 +39,8 @@ static class ExtendsAbstractClass extends AbstractClass { abstract class ImplementsFromJDK8 implements java.lang.reflect.AnnotatedElement { - public A[] getAnnotationsByType(Class annotationClass) { return null; } // Noncompliant [[sc=60;ec=80;quickfixes=qf3]] + public A[] getAnnotationsByType(Class annotationClass) { return null; } // Noncompliant [[quickfixes=qf3]] +// ^^^^^^^^^^^^^^^^^^^^ // fix@qf3 {{Add "@Override" annotation}} // edit@qf3 [[sc=5;ec=5]] {{@Override\n }} } @@ -45,11 +48,13 @@ abstract class ImplementsFromJDK8 implements java.lang.reflect.AnnotatedElement @interface Annotation {} @interface OtherAnnotation {} - @OtherAnnotation public @Annotation synchronized void get() { } // Noncompliant [[sc=57;ec=60;quickfixes=qf4]] + @OtherAnnotation public @Annotation synchronized void get() { } // Noncompliant [[quickfixes=qf4]] +// ^^^ // fix@qf4 {{Add "@Override" annotation}} // edit@qf4 [[sc=3;ec=3]] {{@Override\n }} - static class InnerClassSingleLine extends OverrideAnnotationCheckSimple { public void get() { } } // Noncompliant [[sc=89;ec=92;quickfixes=qf5]] + static class InnerClassSingleLine extends OverrideAnnotationCheckSimple { public void get() { } } // Noncompliant [[quickfixes=qf5]] +// ^^^ // fix@qf5 {{Add "@Override" annotation}} // edit@qf5 [[sc=77;ec=77]] {{@Override }} } @@ -58,6 +63,7 @@ class OverrideAnnotationCheckSimple { void get() { } } -class AbstractOverrideAnnotationSingleLine extends OverrideAnnotationCheckSimple { public void get() { } } // Noncompliant [[sc=96;ec=99;quickfixes=qf6]] +class AbstractOverrideAnnotationSingleLine extends OverrideAnnotationCheckSimple { public void get() { } } // Noncompliant [[quickfixes=qf6]] +// ^^^ // fix@qf6 {{Add "@Override" annotation}} // edit@qf6 [[sc=84;ec=84]] {{@Override }} diff --git a/java-checks-test-sources/default/src/main/java/checks/PredictableSeedCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/PredictableSeedCheckSample.java index 2568d73e05b..89eedc17e60 100644 --- a/java-checks-test-sources/default/src/main/java/checks/PredictableSeedCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/PredictableSeedCheckSample.java @@ -9,7 +9,8 @@ class S4347 { private final byte[] arr4 = new byte[] {21, 12}; void fun(String param) throws Exception { - new SecureRandom().setSeed(123456L); // Noncompliant [[sc=32;ec=39]] {{Change this seed value to something unpredictable, or remove the seed.}} + new SecureRandom().setSeed(123456L); // Noncompliant {{Change this seed value to something unpredictable, or remove the seed.}} +// ^^^^^^^ new SecureRandom("abcdefghijklmnop".getBytes("us-ascii")); // Noncompliant new SecureRandom(param.getBytes("us-ascii")); diff --git a/java-checks-test-sources/default/src/main/java/checks/PreferStreamAnyMatch.java b/java-checks-test-sources/default/src/main/java/checks/PreferStreamAnyMatch.java index 8815cf53e5c..91948abec04 100644 --- a/java-checks-test-sources/default/src/main/java/checks/PreferStreamAnyMatch.java +++ b/java-checks-test-sources/default/src/main/java/checks/PreferStreamAnyMatch.java @@ -7,8 +7,10 @@ class PreferStreamAnyMatch { void test(Random r) { - IntStream.range(0, 10).filter(i -> true).findFirst().isPresent(); // Noncompliant [[sc=28;ec=67]] {{Replace this "filter().findFirst().isPresent()" chain with "anyMatch()".}} - IntStream.range(0, 10).filter(i -> true).findAny().isPresent(); // Noncompliant [[sc=28;ec=65]] {{Replace this "filter().findAny().isPresent()" chain with "anyMatch()".}} + IntStream.range(0, 10).filter(i -> true).findFirst().isPresent(); // Noncompliant {{Replace this "filter().findFirst().isPresent()" chain with "anyMatch()".}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + IntStream.range(0, 10).filter(i -> true).findAny().isPresent(); // Noncompliant {{Replace this "filter().findAny().isPresent()" chain with "anyMatch()".}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ LongStream.range(0, 10).filter(i -> true).findFirst().isPresent(); // Noncompliant LongStream.range(0, 10).filter(i -> true).findAny().isPresent(); // Noncompliant r.doubles(10).filter(i -> true).findFirst().isPresent(); // Noncompliant @@ -22,7 +24,8 @@ void test(Random r) { void anymatch(Stream stream) { boolean match = !stream.filter(o -> o instanceof PreferStreamAnyMatch).filter(o -> o != null).anyMatch(o -> true); // Noncompliant {{Replace this negation and "anyMatch()" with "noneMatch()".}} match = !stream.anyMatch(o -> !true); // Noncompliant {{Replace this double negation with "allMatch()" and positive predicate.}} - match = stream.map(o -> o.equals("")).anyMatch(Boolean::booleanValue); // Noncompliant [[sc=43;ec=51]] {{Use mapper from "map()" directly as predicate in "anyMatch()".}} + match = stream.map(o -> o.equals("")).anyMatch(Boolean::booleanValue); // Noncompliant {{Use mapper from "map()" directly as predicate in "anyMatch()".}} +// ^^^^^^^^ stream.anyMatch(o -> o != null); } diff --git a/java-checks-test-sources/default/src/main/java/checks/PreparedStatementAndResultSetCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/PreparedStatementAndResultSetCheckSample.java index abe7b87fe7c..23275de5ea0 100644 --- a/java-checks-test-sources/default/src/main/java/checks/PreparedStatementAndResultSetCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/PreparedStatementAndResultSetCheckSample.java @@ -23,8 +23,10 @@ abstract class PreparedStatementAndResultSetCheckSample { void foo(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement("SELECT fname, lname FROM employees where hireDate > ? and salary < ?"); - ps.setDate(0, new Date(0)); // Noncompliant [[sc=16;ec=17]] {{PreparedStatement indices start at 1.}} - ps.setDouble(3, 0.0); // Noncompliant [[sc=18;ec=19]] {{This "PreparedStatement" only has 2 parameters.}} + ps.setDate(0, new Date(0)); // Noncompliant {{PreparedStatement indices start at 1.}} +// ^ + ps.setDouble(3, 0.0); // Noncompliant {{This "PreparedStatement" only has 2 parameters.}} +// ^ ps.setString(getIntValue(), ""); // Compliant - first argument can not be evaluated ps.setInt(1, 0); // Compliant @@ -38,7 +40,8 @@ void bar(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement("SELECT fname, lname FROM employees where hireDate > 1986"); ps.setDate(0, new Date(0)); // Noncompliant {{PreparedStatement indices start at 1.}} - ps.setDouble(3, 0.0); // Noncompliant [[sc=18;ec=19]] {{This "PreparedStatement" has no parameters.}} + ps.setDouble(3, 0.0); // Noncompliant {{This "PreparedStatement" has no parameters.}} +// ^ } void dam(Connection connection, String query) throws SQLException { @@ -143,7 +146,7 @@ public void updateCoffeeSales(HashMap salesForWeek, Connection for (Map.Entry e : salesForWeek.entrySet()) { updateSales.setInt(1, e.getValue().intValue()); // Compliant - updateSales.setString(2, e.getKey()); // Noncompliant + updateSales.setString(2, e.getKey()); // Noncompliant updateTotal.setInt(1, e.getValue().intValue()); // Compliant updateTotal.setString(2, e.getKey()); // Compliant other.setInt(2, getIntValue()); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/PreparedStatementLoopInvariantCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/PreparedStatementLoopInvariantCheckSample.java index 7f2152e9f38..9cb9e0a8f21 100644 --- a/java-checks-test-sources/default/src/main/java/checks/PreparedStatementLoopInvariantCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/PreparedStatementLoopInvariantCheckSample.java @@ -12,7 +12,9 @@ public class PreparedStatementLoopInvariantCheckSample { public void basicCase1(PreparedStatement preparedStatement, List orders) throws SQLException { Date today = java.sql.Date.valueOf(LocalDate.now()); for(Order order: orders) { - preparedStatement.setDate(0, today); // Noncompliant [[sc=7;ec=42;secondary=-1]] {{Move this loop-invariant setter invocation out of this loop.}} +// ^[el=+5;ec=5]> + preparedStatement.setDate(0, today); // Noncompliant {{Move this loop-invariant setter invocation out of this loop.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ preparedStatement.executeUpdate(); } } @@ -94,30 +96,38 @@ public void nestedSample( Date dayAfterTomorrow ) throws SQLException { while(true) { - preparedStatement.setDate(0, yesterday); // Noncompliant [[secondary=-1]] +// ^[el=+39;ec=5]> + preparedStatement.setDate(0, yesterday); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ preparedStatement.setDate(0, today); // Compliant preparedStatement.setDate(0, tomorrow); // Compliant preparedStatement.setDate(0, dayAfterTomorrow); // Compliant today = java.sql.Date.valueOf(LocalDate.now()); if (condition1) do { - preparedStatement.setDate(0, yesterday); // Noncompliant [[secondary=-1]] - preparedStatement.setDate(0, today); // Noncompliant [[secondary=-2]] +// ^[el=+30;ec=21]> + preparedStatement.setDate(0, yesterday); // Noncompliant + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + preparedStatement.setDate(0, today); // Noncompliant preparedStatement.setDate(0, tomorrow); // Compliant preparedStatement.setDate(0, dayAfterTomorrow); // Compliant tomorrow = java.sql.Date.valueOf(LocalDate.now()); if (condition2) { for(Order order: orders) { - preparedStatement.setDate(0, yesterday); // Noncompliant [[secondary=-1]] - preparedStatement.setDate(0, today); // Noncompliant [[secondary=-2]] - preparedStatement.setDate(0, tomorrow); // Noncompliant [[secondary=-3]] +// ^[el=+8;ec=11]> + preparedStatement.setDate(0, yesterday); // Noncompliant + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + preparedStatement.setDate(0, today); // Noncompliant + preparedStatement.setDate(0, tomorrow); // Noncompliant preparedStatement.setDate(0, dayAfterTomorrow); // Compliant dayAfterTomorrow = java.sql.Date.valueOf(LocalDate.now()); } } for(int i = 0; i < 10; i++) { - preparedStatement.setDate(0, yesterday); // Noncompliant [[secondary=-1]] - preparedStatement.setDate(0, today); // Noncompliant [[secondary=-2]] - preparedStatement.setDate(0, tomorrow); // Noncompliant [[secondary=-3]] +// ^[el=+10;ec=9]> + preparedStatement.setDate(0, yesterday); // Noncompliant + //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + preparedStatement.setDate(0, today); // Noncompliant + preparedStatement.setDate(0, tomorrow); // Noncompliant preparedStatement.setDate(0, dayAfterTomorrow); // Compliant if (condition2) { dayAfterTomorrow = java.sql.Date.valueOf(LocalDate.now()); diff --git a/java-checks-test-sources/default/src/main/java/checks/PrimitiveWrappersInTernaryOperatorCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/PrimitiveWrappersInTernaryOperatorCheckSample.java index c8f432b2b8d..3ae1952ac68 100644 --- a/java-checks-test-sources/default/src/main/java/checks/PrimitiveWrappersInTernaryOperatorCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/PrimitiveWrappersInTernaryOperatorCheckSample.java @@ -8,7 +8,8 @@ void foo() { Float f1 = 1.0f; Object o1 = new Object(); A a2 = new A(); - Number n = true ? i1 : f1; // Noncompliant [[sc=21;ec=22]] {{Add an explicit cast to match types of operands.}} + Number n = true ? i1 : f1; // Noncompliant {{Add an explicit cast to match types of operands.}} +// ^ o1 = true ? o1 : a2; // Compliant o1 = true ? f1 : a2; // Compliant n = true ? (Number) i1 : f1; // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/PrimitivesMarkedNullableCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/PrimitivesMarkedNullableCheckSample.java index b1ecccfd69d..d662f341cef 100644 --- a/java-checks-test-sources/default/src/main/java/checks/PrimitivesMarkedNullableCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/PrimitivesMarkedNullableCheckSample.java @@ -14,7 +14,9 @@ abstract class PrimitivesMarkedNullableCheckSample { @CheckForNull - abstract int getInt0(); // Noncompliant [[sc=12;ec=15;secondary=-1]] {{"@CheckForNull" annotation should not be used on primitive types}} +//^^^^^^^^^^^^^> + abstract int getInt0(); // Noncompliant {{"@CheckForNull" annotation should not be used on primitive types}} +// ^^^ abstract int getInt1(); @@ -22,12 +24,14 @@ abstract class PrimitivesMarkedNullableCheckSample { abstract int getInt2(); @Nullable - protected abstract boolean isBool(); // Noncompliant [[sc=22;ec=29;quickfixes=qf1]] {{"@Nullable" annotation should not be used on primitive types}} + protected abstract boolean isBool(); // Noncompliant {{"@Nullable" annotation should not be used on primitive types}} [[quickfixes=qf1]] +// ^^^^^^^ // fix@qf1 {{Remove "@Nullable"}} // edit@qf1 [[sl=-1;el=+0;sc=3;ec=3]] {{}} @javax.annotation.CheckForNull - public double getDouble0() { return 0.0; } // Noncompliant [[sc=10;ec=16;quickfixes=qf2]] {{"@CheckForNull" annotation should not be used on primitive types}} + public double getDouble0() { return 0.0; } // Noncompliant {{"@CheckForNull" annotation should not be used on primitive types}} [[quickfixes=qf2]] +// ^^^^^^ // fix@qf2 {{Remove "@CheckForNull"}} // edit@qf2 [[sl=-1;el=+0;sc=3;ec=3]] {{}} @@ -56,7 +60,8 @@ abstract class PrimitivesMarkedNullableCheckSample { public Object getObj2() { return null; } - protected abstract @Nullable boolean isBool2(); // Noncompliant [[sc=32;ec=39;quickfixes=qf3]] {{"@Nullable" annotation should not be used on primitive types}} + protected abstract @Nullable boolean isBool2(); // Noncompliant {{"@Nullable" annotation should not be used on primitive types}} [[quickfixes=qf3]] +// ^^^^^^^ // fix@qf3 {{Remove "@Nullable"}} // edit@qf3 [[sc=22;ec=32]] {{}} diff --git a/java-checks-test-sources/default/src/main/java/checks/PrintfFailCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/PrintfFailCheckSample.java index a1cf736f23a..69b66002aff 100644 --- a/java-checks-test-sources/default/src/main/java/checks/PrintfFailCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/PrintfFailCheckSample.java @@ -17,19 +17,19 @@ void foo(Calendar c) throws java.io.IOException { Locale loc = Locale.US; // String format =================================================================================================== double value = 1.0; - String.format("The value of my integer is %d", "Hello World"); // Noncompliant {{An 'int' is expected rather than a String.}} + String.format("The value of my integer is %d", "Hello World"); // Noncompliant {{An 'int' is expected rather than a String.}} String.format("First {0} and then {1}", "foo", "bar"); - String.format("Duke's Birthday year is %tX", 12l); // Noncompliant {{X is not a supported time conversion character}} + String.format("Duke's Birthday year is %tX", 12l); // Noncompliant {{X is not a supported time conversion character}} String.format("Display %3$d and then %d", 1, 2, 3); String.format("Too many arguments %d and %d", 1, 2, 3); - String.format("Not enough arguments %d and %d", 1); // Noncompliant {{Not enough arguments.}} - String.format("%1$d %2$d %9$-3.3s", 1, 2, "hello"); // Noncompliant {{Not enough arguments to feed formater at index 9: '%9$'.}} - String.format("%12$s", 1, 2, "hello"); // Noncompliant {{Not enough arguments to feed formater at index 12: '%12$'.}} + String.format("Not enough arguments %d and %d", 1); // Noncompliant {{Not enough arguments.}} + String.format("%1$d %2$d %9$-3.3s", 1, 2, "hello"); // Noncompliant {{Not enough arguments to feed formater at index 9: '%9$'.}} + String.format("%12$s", 1, 2, "hello"); // Noncompliant {{Not enough arguments to feed formater at index 12: '%12$'.}} String.format("First Line\n %d", 1); String.format("First Line"); String.format("First Line%%"); String.format("First Line%n"); // Compliant - String.format("%< is equals to %d", 2); // Noncompliant {{The argument index '<' refers to the previous format specifier but there isn't one.}} + String.format("%< is equals to %d", 2); // Noncompliant {{The argument index '<' refers to the previous format specifier but there isn't one.}} String.format("Is myObject null ? %b", myObject); String.format("value is " + value); // Compliant String.format("string without arguments"); @@ -46,21 +46,21 @@ void foo(Calendar c) throws java.io.IOException { String.format("Result %s %s",new Exception(),new Exception()); // Compliant String.format("Result %s %s",new Object[] {new Exception(),new Exception()}); // Compliant String.format("Result %s %s",new Exception()); // Noncompliant {{Not enough arguments.}} - String.format("Result %s %s",new Object[] {new Exception()}); // Noncompliant {{Not enough arguments.}} + String.format("Result %s %s",new Object[] {new Exception()}); // Noncompliant {{Not enough arguments.}} String.format("%s " + value, new Exception()); // Compliant, reported by S3457 String.format("%s " + value); // Compliant, reported by S3457 String.format("Too many arguments %d and %d and %d", 1, 2, 3, 4); String.format("normal %d%% ", 1); //Compliant - String.format("Duke's Birthday year is %t", 12l); // Noncompliant {{Time conversion requires a second character.}} + String.format("Duke's Birthday year is %t", 12l); // Noncompliant {{Time conversion requires a second character.}} String.format("Duke's Birthday year is %tH", 12l); // Compliant String.format("Duke's Birthday year is %tH", Long.valueOf(12L)); // Compliant - String.format("Duke's Birthday year is %tH", loc); // Noncompliant {{Time argument is expected (long, Long, Calendar, Date and TemporalAccessor).}} + String.format("Duke's Birthday year is %tH", loc); // Noncompliant {{Time argument is expected (long, Long, Calendar, Date and TemporalAccessor).}} String.format("%08d%n", 1); GregorianCalendar gc = (GregorianCalendar) GregorianCalendar.getInstance(); String.format("Duke's Birthday year is %tH", gc); - // Noncompliant@+1 - String.format("Duke's Birthday year is %t", loc); // Noncompliant + // Noncompliant@+1 + String.format("Duke's Birthday year is %t", loc); // Noncompliant String.format("Accessed before %tF%n", java.time.LocalDate.now()); // Compliant System.out.printf("%1$ty_%1$tm_%1$td_%1$tH_%1$tM_%1$tS", java.time.LocalDateTime.now()); // Compliant @@ -71,14 +71,14 @@ void foo(Calendar c) throws java.io.IOException { String.format("%0$s", "tmp"); // Compliant, reported by S3457 // String.formatted ================================================================================================ - "The value of my integer is %d".formatted("Hello World"); // Noncompliant {{An 'int' is expected rather than a String.}} + "The value of my integer is %d".formatted("Hello World"); // Noncompliant {{An 'int' is expected rather than a String.}} "First {0} and then {1}".formatted("foo", "bar"); - "Duke's Birthday year is %tX".formatted(12l); // Noncompliant {{X is not a supported time conversion character}} + "Duke's Birthday year is %tX".formatted(12l); // Noncompliant {{X is not a supported time conversion character}} "Display %3$d and then %d".formatted(1, 2, 3); "Too many arguments %d and %d".formatted(1, 2, 3); - "Not enough arguments %d and %d".formatted(1); // Noncompliant {{Not enough arguments.}} - "%1$d %2$d %9$-3.3s".formatted(1, 2, "hello"); // Noncompliant {{Not enough arguments to feed formater at index 9: '%9$'.}} - "%12$s".formatted(1, 2, "hello"); // Noncompliant {{Not enough arguments to feed formater at index 12: '%12$'.}} + "Not enough arguments %d and %d".formatted(1); // Noncompliant {{Not enough arguments.}} + "%1$d %2$d %9$-3.3s".formatted(1, 2, "hello"); // Noncompliant {{Not enough arguments to feed formater at index 9: '%9$'.}} + "%12$s".formatted(1, 2, "hello"); // Noncompliant {{Not enough arguments to feed formater at index 12: '%12$'.}} "First Line\n %d".formatted(1); "First Line".formatted(); "First Line%%".formatted(); @@ -89,11 +89,11 @@ void foo(Calendar c) throws java.io.IOException { PrintStream ps = new PrintStream("file"); Formatter formatter = new Formatter(); - pr.format("The value of my integer is %d", "Hello World"); // Noncompliant {{An 'int' is expected rather than a String.}} - pr.printf("The value of my integer is %d", "Hello World"); // Noncompliant {{An 'int' is expected rather than a String.}} - ps.format("The value of my integer is %d", "Hello World"); // Noncompliant {{An 'int' is expected rather than a String.}} - ps.printf(loc, "The value of my integer is %d", "Hello World"); // Noncompliant {{An 'int' is expected rather than a String.}} - formatter.format("The value of my integer is %d", "Hello World"); // Noncompliant {{An 'int' is expected rather than a String.}} + pr.format("The value of my integer is %d", "Hello World"); // Noncompliant {{An 'int' is expected rather than a String.}} + pr.printf("The value of my integer is %d", "Hello World"); // Noncompliant {{An 'int' is expected rather than a String.}} + ps.format("The value of my integer is %d", "Hello World"); // Noncompliant {{An 'int' is expected rather than a String.}} + ps.printf(loc, "The value of my integer is %d", "Hello World"); // Noncompliant {{An 'int' is expected rather than a String.}} + formatter.format("The value of my integer is %d", "Hello World"); // Noncompliant {{An 'int' is expected rather than a String.}} pr.format("%s:\tintCompact %d\tintVal %d\tscale %d\tprecision %d%n","", 1, 1, 1, 1); pr.format("%s:\tintCompact %n%n%n%d\tintVal %d\tscale %d\tprecision %d%n","", 1, 1, 1, 1); pr.format("%TH", 1l); diff --git a/java-checks-test-sources/default/src/main/java/checks/PrintfMisuseCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/PrintfMisuseCheckSample.java index 46913f7de3b..08adab0ff67 100644 --- a/java-checks-test-sources/default/src/main/java/checks/PrintfMisuseCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/PrintfMisuseCheckSample.java @@ -27,21 +27,21 @@ void foo(Calendar c) throws IOException { Locale loc = Locale.US; // String format =================================================================================================== String.format("The value of my integer is %d", "Hello World"); - String.format("First {0} and then {1}", "foo", "bar"); // Noncompliant {{Looks like there is a confusion with the use of java.text.MessageFormat, parameters will be simply ignored here}} - String.format("{1}", "foo", "bar"); // Noncompliant + String.format("First {0} and then {1}", "foo", "bar"); // Noncompliant {{Looks like there is a confusion with the use of java.text.MessageFormat, parameters will be simply ignored here}} + String.format("{1}", "foo", "bar"); // Noncompliant String.format("Duke's Birthday year is %tX", 12l); - String.format("Display %3$d and then %d", 1, 2, 3); // Noncompliant {{2nd argument is not used.}} - String.format("Display %2$d and then %2$d", 1, 2); // Noncompliant {{first argument is not used.}} - String.format("Too many arguments %d and %d", 1, 2, 3); // Noncompliant {{3rd argument is not used.}} + String.format("Display %3$d and then %d", 1, 2, 3); // Noncompliant {{2nd argument is not used.}} + String.format("Display %2$d and then %2$d", 1, 2); // Noncompliant {{first argument is not used.}} + String.format("Too many arguments %d and %d", 1, 2, 3); // Noncompliant {{3rd argument is not used.}} String.format("Not enough arguments %d and %d", 1); String.format("%1$d %2$d %9$-3.3s", 1, 2, "hello"); // Compliant - not enough arguments but this will be caught by S2275 String.format("%12$s", 1, 2, "hello"); // Compliant - not enough arguments but this will be caught by S2275 String.format("First Line\n %d", 1); // Noncompliant {{%n should be used in place of \n to produce the platform-specific line separator.}} - String.format("First Line"); // Noncompliant {{String contains no format specifiers.}} + String.format("First Line"); // Noncompliant {{String contains no format specifiers.}} String.format("First Line%%"); // Noncompliant {{String contains no format specifiers.}} String.format("First Line%n"); // Compliant String.format("%< is equals to %d", 2); - String.format("Is myObject null ? %b", myObject); // Noncompliant {{Directly inject the boolean value.}} + String.format("Is myObject null ? %b", myObject); // Noncompliant {{Directly inject the boolean value.}} String.format("boolean are %b, %b, %b and %b", true, Boolean.TRUE, false, Boolean.FALSE); String.format("value is " + value); // Noncompliant {{Format specifiers should be used instead of string concatenation.}} String.format((String) ""); @@ -65,7 +65,7 @@ void foo(Calendar c) throws IOException { String.format("Result %s %s",new Exception()); // Compliant, reported by S2275 String.format("Result %s %s",new Object[] {new Exception()}); // Compliant, reported by S2275 - String.format("Too many arguments %d and %d and %d", 1, 2, 3, 4); // Noncompliant {{4th argument is not used.}} + String.format("Too many arguments %d and %d and %d", 1, 2, 3, 4); // Noncompliant {{4th argument is not used.}} String.format("normal %d%% ", 1); //Compliant String.format("Duke's Birthday year is %t", 12l); String.format("Duke's Birthday year is %tH", 12l); // Compliant @@ -85,17 +85,17 @@ void foo(Calendar c) throws IOException { // String.formatted ================================================================================================ "The value of my integer is %d".formatted("Hello World"); - "First {0} and then {1}".formatted("foo", "bar"); // Noncompliant {{Looks like there is a confusion with the use of java.text.MessageFormat, parameters will be simply ignored here}} - "{1}".formatted("foo", "bar"); // Noncompliant + "First {0} and then {1}".formatted("foo", "bar"); // Noncompliant {{Looks like there is a confusion with the use of java.text.MessageFormat, parameters will be simply ignored here}} + "{1}".formatted("foo", "bar"); // Noncompliant "Duke's Birthday year is %tX".formatted(12l); - "Display %3$d and then %d".formatted(1, 2, 3); // Noncompliant {{2nd argument is not used.}} - "Display %2$d and then %2$d".formatted(1, 2); // Noncompliant {{first argument is not used.}} - "Too many arguments %d and %d".formatted(1, 2, 3); // Noncompliant {{3rd argument is not used.}} + "Display %3$d and then %d".formatted(1, 2, 3); // Noncompliant {{2nd argument is not used.}} + "Display %2$d and then %2$d".formatted(1, 2); // Noncompliant {{first argument is not used.}} + "Too many arguments %d and %d".formatted(1, 2, 3); // Noncompliant {{3rd argument is not used.}} "Not enough arguments %d and %d".formatted(1); "%1$d %2$d %9$-3.3s".formatted(1, 2, "hello"); // Compliant - not enough arguments but this will be caught by S2275 "%12$s".formatted(1, 2, "hello"); // Compliant - not enough arguments but this will be caught by S2275 "First Line\n %d".formatted(1); // Noncompliant {{%n should be used in place of \n to produce the platform-specific line separator.}} - "First Line".formatted(); // Noncompliant {{String contains no format specifiers.}} + "First Line".formatted(); // Noncompliant {{String contains no format specifiers.}} // Print Writer / Stream / Formatter =============================================================================== @@ -114,16 +114,16 @@ void foo(Calendar c) throws IOException { pr.format("%d", new Long(12)); pr.format("%d", new java.math.BigInteger("12")); - pr.format("string without arguments"); // Noncompliant {{String contains no format specifiers.}} - pr.format(loc, "string without arguments"); // Noncompliant {{String contains no format specifiers.}} - pr.printf("string without arguments"); // Noncompliant {{String contains no format specifiers.}} - pr.printf(loc, "string without arguments"); // Noncompliant {{String contains no format specifiers.}} - ps.format("string without arguments"); // Noncompliant {{String contains no format specifiers.}} - ps.format(loc, "string without arguments"); // Noncompliant {{String contains no format specifiers.}} - ps.printf("string without arguments"); // Noncompliant {{String contains no format specifiers.}} - ps.printf(loc, "string without arguments"); // Noncompliant {{String contains no format specifiers.}} - formatter.format("string without arguments"); // Noncompliant {{String contains no format specifiers.}} - formatter.format(loc, "string without arguments"); // Noncompliant {{String contains no format specifiers.}} + pr.format("string without arguments"); // Noncompliant {{String contains no format specifiers.}} + pr.format(loc, "string without arguments"); // Noncompliant {{String contains no format specifiers.}} + pr.printf("string without arguments"); // Noncompliant {{String contains no format specifiers.}} + pr.printf(loc, "string without arguments"); // Noncompliant {{String contains no format specifiers.}} + ps.format("string without arguments"); // Noncompliant {{String contains no format specifiers.}} + ps.format(loc, "string without arguments"); // Noncompliant {{String contains no format specifiers.}} + ps.printf("string without arguments"); // Noncompliant {{String contains no format specifiers.}} + ps.printf(loc, "string without arguments"); // Noncompliant {{String contains no format specifiers.}} + formatter.format("string without arguments"); // Noncompliant {{String contains no format specifiers.}} + formatter.format(loc, "string without arguments"); // Noncompliant {{String contains no format specifiers.}} pr.format("value is " + value); // Noncompliant {{Format specifiers should be used instead of string concatenation.}} pr.format(loc, "value is " + value); // Noncompliant {{Format specifiers should be used instead of string concatenation.}} @@ -171,7 +171,7 @@ void foo(Calendar c) throws IOException { MessageFormat.format("Result {0, number, integer} and {1, number, integer}!", 14, 42); // compliant MessageFormat.format("Result {0} and {1}!", 14, 42, 128); // Noncompliant {{3rd argument is not used.}} MessageFormat.format("{0,number,#.#}{1}", new Object[] {0.07, "$"}); // Compliant - MessageFormat.format("{0,number,#.#}{1}", new Object[] {0.07}); // Noncompliant {{Not enough arguments.}} + MessageFormat.format("{0,number,#.#}{1}", new Object[] {0.07}); // Noncompliant {{Not enough arguments.}} MessageFormat.format("{0,number,#.#}{1}", objs); // Compliant - skipped as the array is not initialized in the method invocation MessageFormat.format("{0,number,#.#}{1}", new Object[42]); // Compliant - Not considered MessageFormat.format("value=\"'{'{0}'}'{1}\"", new Object[] {"value 1", "value 2"}); @@ -243,10 +243,10 @@ void foo(Calendar c) throws IOException { logger4.log(level, "message "); logger4.log(level, "message ", new Exception()); logger4.log(level, "message {0}", param1); - logger4.log(level, "message {1}", param1); // Noncompliant {{Not enough arguments.}} - logger4.log(level, "message {0}", new Exception()); // Noncompliant {{Not enough arguments.}} + logger4.log(level, "message {1}", param1); // Noncompliant {{Not enough arguments.}} + logger4.log(level, "message {0}", new Exception()); // Noncompliant {{Not enough arguments.}} logger4.log(level, "message {0}", new Object[] {param1}); - logger4.log(level, "message {1}", new Object[] {param1}); // Noncompliant {{Not enough arguments.}} + logger4.log(level, "message {1}", new Object[] {param1}); // Noncompliant {{Not enough arguments.}} logger4.log(level, "message {0}", new Object[] {param1, new Exception()}); // Noncompliant {{2nd argument is not used.}} logger4.log(level, "message {0} {1}", new Object[] {param1, param2}); logger4.log(level, "message {0} {1}", new Object[] {param1, param2, param3}); // Noncompliant {{3rd argument is not used.}} @@ -269,7 +269,7 @@ void foo(Calendar c) throws IOException { slf4jLog.debug(marker, "message ", 1); // Noncompliant {{String contains no format specifiers.}} slf4jLog.debug(marker, "message {}", 1); slf4jLog.debug(marker, "message {} - {}", 1, 2); - slf4jLog.debug(marker, "message {}", 1, 2);// Noncompliant {{2nd argument is not used.}} + slf4jLog.debug(marker, "message {}", 1, 2); // Noncompliant {{2nd argument is not used.}} slf4jLog.debug(marker, "message {} {} {}", 1, 2, 3); slf4jLog.debug(marker, "message {} {}", 1, 2, 3); // Noncompliant slf4jLog.debug(marker, "message {} {}", new Object[]{1, 2, 3}); // Noncompliant @@ -283,7 +283,7 @@ void foo(Calendar c) throws IOException { slf4jLog.debug("message ", 1); // Noncompliant {{String contains no format specifiers.}} slf4jLog.debug("message {}", 1); slf4jLog.debug("message {} - {}", 1, 2); - slf4jLog.debug("message {}", 1, 2);// Noncompliant {{2nd argument is not used.}} + slf4jLog.debug("message {}", 1, 2); // Noncompliant {{2nd argument is not used.}} slf4jLog.debug("message {} {} {}", 1, 2, 3); slf4jLog.debug("message {} {}", 1, 2, 3); // Noncompliant slf4jLog.debug("message {} {}", new Object[]{1, 2, 3}); // Noncompliant @@ -326,7 +326,7 @@ void foo(Calendar c) throws IOException { } slf4jLog.info("message {} - {}", 1, 2); - slf4jLog.info("message {}", 1, 2);// Noncompliant {{2nd argument is not used.}} + slf4jLog.info("message {}", 1, 2); // Noncompliant {{2nd argument is not used.}} slf4jLog.info("message {} {} {}", 1, 2, 3); slf4jLog.info("message ", new Exception()); slf4jLog.info("message {}", new Exception()); // Noncompliant {{Not enough arguments.}} @@ -355,14 +355,14 @@ void foo(Calendar c) throws IOException { org.apache.logging.log4j.Logger formatterLogger = LogManager.getFormatterLogger(); log4j.log(org.apache.logging.log4j.Level.DEBUG, "message"); // Compliant - log4j.log(org.apache.logging.log4j.Level.DEBUG, "message", 1); // Noncompliant {{String contains no format specifiers.}} - log4j.log(org.apache.logging.log4j.Level.DEBUG, "message {}"); // Noncompliant {{Not enough arguments.}} - log4j.log(org.apache.logging.log4j.Level.DEBUG, "message {}", new Exception()); // Noncompliant {{Not enough arguments.}} + log4j.log(org.apache.logging.log4j.Level.DEBUG, "message", 1); // Noncompliant {{String contains no format specifiers.}} + log4j.log(org.apache.logging.log4j.Level.DEBUG, "message {}"); // Noncompliant {{Not enough arguments.}} + log4j.log(org.apache.logging.log4j.Level.DEBUG, "message {}", new Exception()); // Noncompliant {{Not enough arguments.}} log4j.log(org.apache.logging.log4j.Level.DEBUG, "message {}", 1); // Compliant - log4j.log(org.apache.logging.log4j.Level.DEBUG, "message {} {}", 1); // Noncompliant {{Not enough arguments.}} - log4j.log(org.apache.logging.log4j.Level.DEBUG, "message {}", 1, "hello"); // Noncompliant + log4j.log(org.apache.logging.log4j.Level.DEBUG, "message {} {}", 1); // Noncompliant {{Not enough arguments.}} + log4j.log(org.apache.logging.log4j.Level.DEBUG, "message {}", 1, "hello"); // Noncompliant formatterLogger.log(org.apache.logging.log4j.Level.DEBUG, "message %d", 1); // Compliant - formatterLogger.log(org.apache.logging.log4j.Level.DEBUG, "message %d", 1, "hello"); // Noncompliant + formatterLogger.log(org.apache.logging.log4j.Level.DEBUG, "message %d", 1, "hello"); // Noncompliant log4j.debug("message"); // Compliant log4j.debug("message", 1); // Noncompliant @@ -387,12 +387,12 @@ void foo(Calendar c) throws IOException { formatterLogger.debug("message %s message %d", "hello", 42); // Compliant formatterLogger.debug("message %s message", "hello", 42); // Noncompliant {{2nd argument is not used.}} formatterLogger.debug("message %s {} message", "hello", 42); // Noncompliant {{2nd argument is not used.}} - formatterLogger.debug("message %s {} %s message", "hello", 42); // Noncompliant - false-positive, the rule doesn't know it's a "FormatterLogger" + formatterLogger.debug("message %s {} %s message", "hello", 42); // Noncompliant formatterLogger.printf(org.apache.logging.log4j.Level.DEBUG, "message %s {} %s message", "hello", 42); formatterLogger.debug("message %s {} {} message", "hello", 42); // false-negative, the rule doesn't know it's a "FormatterLogger" formatterLogger.printf(org.apache.logging.log4j.Level.DEBUG, "message %s {} {} message", "hello", 42); // Noncompliant {{2nd argument is not used.}} - log4j.printf(org.apache.logging.log4j.Level.DEBUG, "message"); // Noncompliant {{String contains no format specifiers.}} + log4j.printf(org.apache.logging.log4j.Level.DEBUG, "message"); // Noncompliant {{String contains no format specifiers.}} log4j.printf(org.apache.logging.log4j.Level.DEBUG, "message %s %d", "hello", 42); // Compliant - Java formatters log4j.printf(org.apache.logging.log4j.Level.DEBUG, "message %s", "hello", 42); // Noncompliant {{2nd argument is not used.}} formatterLogger.printf(org.apache.logging.log4j.Level.DEBUG, "message %s", "hello", 42); // Noncompliant {{2nd argument is not used.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/PseudoRandomCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/PseudoRandomCheckSample.java index 45063ac30b6..86a8946395b 100644 --- a/java-checks-test-sources/default/src/main/java/checks/PseudoRandomCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/PseudoRandomCheckSample.java @@ -16,7 +16,8 @@ void fun() { // Non static class, report only constructor // java.util.Random - Random random = new Random(); // Noncompliant [[sc=25;ec=31]] {{Make sure that using this pseudorandom number generator is safe here.}} + Random random = new Random(); // Noncompliant {{Make sure that using this pseudorandom number generator is safe here.}} +// ^^^^^^ byte[] bytes = new byte[20]; random.nextBytes(bytes); // Compliant @@ -26,11 +27,13 @@ void fun() { // Static class, don't report constructor, only usage // java.lang.Math. Report only Math.random() - double rand1 = Math.random(); // Noncompliant [[sc=25;ec=31]] + double rand1 = Math.random(); // Noncompliant +// ^^^^^^ double abs = Math.abs(12); // Compliant // java.util.concurrent.ThreadLocalRandom - int rand2 = ThreadLocalRandom.current().nextInt(); // Noncompliant [[sc=35;ec=42]] + int rand2 = ThreadLocalRandom.current().nextInt(); // Noncompliant +// ^^^^^^^ // org.apache.commons.lang.math.RandomUtils RandomUtils randomUtils = new RandomUtils(); @@ -47,9 +50,11 @@ void fun() { String rand8 = randomStringUtils.random(1); // Noncompliant String rand9 = RandomStringUtils.random(1); // Noncompliant rand9 = random(1); // Noncompliant - rand9 = RandomStringUtils.random(1, 0, 0, false, false, null); // Noncompliant [[sc=31;ec=37]] + rand9 = RandomStringUtils.random(1, 0, 0, false, false, null); // Noncompliant +// ^^^^^^ // Here we should raise an issue only on the `new Random`, not on the call to `random` itself - rand9 = RandomStringUtils.random(1, 0, 0, false, false, null, new Random()); // Noncompliant [[sc=71;ec=77]] + rand9 = RandomStringUtils.random(1, 0, 0, false, false, null, new Random()); // Noncompliant +// ^^^^^^ // Here there should be no issue because `random` will use the supplied secure source of randomness rand9 = RandomStringUtils.random(1, 0, 0, false, false, null, new SecureRandom()); // Compliant @@ -57,13 +62,16 @@ void fun() { org.apache.commons.lang3.RandomStringUtils randomStringUtils2 = new org.apache.commons.lang3.RandomStringUtils(); String rand10 = randomStringUtils.random(1); // Noncompliant String rand11 = org.apache.commons.lang3.RandomStringUtils.random(1); // Noncompliant - rand11 = org.apache.commons.lang3.RandomStringUtils.random(1, 0, 0, false, false, null); // Noncompliant [[sc=57;ec=63]] + rand11 = org.apache.commons.lang3.RandomStringUtils.random(1, 0, 0, false, false, null); // Noncompliant +// ^^^^^^ // Here we should raise an issue only on the `new Random`, not on the call to `random` itself - rand11 = org.apache.commons.lang3.RandomStringUtils.random(1, 0, 0, false, false, null, new Random()); // Noncompliant [[sc=97;ec=103]] + rand11 = org.apache.commons.lang3.RandomStringUtils.random(1, 0, 0, false, false, null, new Random()); // Noncompliant +// ^^^^^^ // Here there should be no issue because `random` will use the supplied secure source of randomness rand11 = org.apache.commons.lang3.RandomStringUtils.random(1, 0, 0, false, false, null, new SecureRandom()); // Compliant - String rand12 = random(42).toLowerCase(Locale.ROOT); // Noncompliant [[sc=21;ec=27]] + String rand12 = random(42).toLowerCase(Locale.ROOT); // Noncompliant +// ^^^^^^ } int nextInt() { diff --git a/java-checks-test-sources/default/src/main/java/checks/PublicConstructorInAbstractClassCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/PublicConstructorInAbstractClassCheckSample.java index 2a51c0894bf..957583cbd5c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/PublicConstructorInAbstractClassCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/PublicConstructorInAbstractClassCheckSample.java @@ -1,7 +1,9 @@ package checks; -abstract class AbstractClass1 { - public AbstractClass1 () { // Noncompliant[[sc=3;ec=9;secondary=3]]{{Change the visibility of this constructor to "protected".}} + abstract class AbstractClass1 { +//^^^^^^^^> + public AbstractClass1 () { // Noncompliant {{Change the visibility of this constructor to "protected".}} +//^^^^^^ //do sth here } } diff --git a/java-checks-test-sources/default/src/main/java/checks/PublicStaticMutableMembersCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/PublicStaticMutableMembersCheckSample.java index 67c9982de49..d3cb33228e8 100644 --- a/java-checks-test-sources/default/src/main/java/checks/PublicStaticMutableMembersCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/PublicStaticMutableMembersCheckSample.java @@ -24,8 +24,9 @@ import java.util.stream.Stream; public class PublicStaticMutableMembersCheckSample { - public static String [] strings1 = {"first","second"}; // Noncompliant [[sc=27;ec=35]] {{Make this member "protected".}} - public static String [] strings2 = {"first","second"}; // Noncompliant + public static String [] strings1 = {"first","second"}; // Noncompliant {{Make this member "protected".}} +// ^^^^^^^^ + public static String [] strings2 = {"first","second"}; // Noncompliant protected static final String [] strings3 = {"first","second"}; private static String [] strings4 = {"first","second"}; @@ -52,8 +53,8 @@ public static int getDim() { public static final int[] EMPTY_DATA_2 = {}; // Compliant public static final int[] EMPTY_DATA_3 = new int[]{}; // Compliant public static final int[] EMPTY_DATA_4 = EMPTY_DATA_3; // Compliant - public static final int[] NON_EMPTY_DATA_1 = new int[]{ 0 }; // Noncompliant - dim 1 array - public static final int[][] NON_EMPTY_DATA_2 = {new int[0], {}}; // Noncompliant - you can still modify sub array + public static final int[] NON_EMPTY_DATA_1 = new int[]{ 0 }; // Noncompliant + public static final int[][] NON_EMPTY_DATA_2 = {new int[0], {}}; // Noncompliant public static final int[] NON_EMPTY_DATA_3 = NON_EMPTY_DATA_1; // Noncompliant public static int[] data2 = new int[5]; // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/RandomFloatToIntCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/RandomFloatToIntCheckSample.java index d356370d041..7ef62706f55 100644 --- a/java-checks-test-sources/default/src/main/java/checks/RandomFloatToIntCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/RandomFloatToIntCheckSample.java @@ -9,53 +9,55 @@ class RandomFloatToIntCheckSample { //java.util.Random Random r = new Random(); - int rand = (int) r.nextDouble() * 50; // Noncompliant {{Use "nextInt()" instead.}} - int rand2 = (int) r.nextFloat() * 50; // Noncompliant + int rand = (int) r.nextDouble() * 50; // Noncompliant {{Use "nextInt()" instead.}} + int rand2 = (int) r.nextFloat() * 50; // Noncompliant float rand3 = (float)r.nextFloat(); int rand4 = (int) r.nextInt() * 50; - int rand5 = (int)r.nextFloat(); // Noncompliant; will always be 0; + int rand5 = (int)r.nextFloat(); // Noncompliant // java.lang.Math - int rand6 = (int) Math.random() * 50; // Noncompliant {{Use "java.util.Random.nextInt()" instead.}} + int rand6 = (int) Math.random() * 50; // Noncompliant {{Use "java.util.Random.nextInt()" instead.}} int rand7 = (int) new RandomFloatToIntCheckSampleFoo() { int foo() { - int a = (int) Math.random() * 50; // Noncompliant + int a = (int) Math.random() * 50; // Noncompliant return a; } }.foo(); // java.util.concurrent.ThreadLocalRandom - int rand8 = (int) ThreadLocalRandom.current().nextDouble() * 50; // Noncompliant {{Use "nextInt()" instead.}} - int rand9 = (int) ThreadLocalRandom.current().nextDouble(1.0) * 50; // Noncompliant - int rand10 = (int) ThreadLocalRandom.current().nextDouble(1.0, 2.0) * 50; // Noncompliant + int rand8 = (int) ThreadLocalRandom.current().nextDouble() * 50; // Noncompliant {{Use "nextInt()" instead.}} + int rand9 = (int) ThreadLocalRandom.current().nextDouble(1.0) * 50; // Noncompliant + int rand10 = (int) ThreadLocalRandom.current().nextDouble(1.0, 2.0) * 50; // Noncompliant // org.apache.commons.lang.math.JVMRandom JVMRandom jvmRandom = new JVMRandom(); - int rand11 = (int) jvmRandom.nextDouble() * 50; // Noncompliant {{Use "nextInt()" instead.}} - int rand12 = (int) jvmRandom.nextFloat() * 50; // Noncompliant + int rand11 = (int) jvmRandom.nextDouble() * 50; // Noncompliant {{Use "nextInt()" instead.}} + int rand12 = (int) jvmRandom.nextFloat() * 50; // Noncompliant float rand13 = (float)jvmRandom.nextFloat(); int rand14 = (int) jvmRandom.nextInt() * 50; - int rand15 = (int)jvmRandom.nextFloat(); // Noncompliant; will always be 0; + int rand15 = (int)jvmRandom.nextFloat(); // Noncompliant // org.apache.commons.lang.math.RandomUtils - int rand16 = (int) RandomUtils.nextDouble() * 50; // Noncompliant {{Use "nextInt()" instead.}} - int rand17 = (int) RandomUtils.nextFloat() * 50; // Noncompliant + int rand16 = (int) RandomUtils.nextDouble() * 50; // Noncompliant {{Use "nextInt()" instead.}} + int rand17 = (int) RandomUtils.nextFloat() * 50; // Noncompliant float rand18 = (float) RandomUtils.nextFloat(); int rand19 = (int) RandomUtils.nextInt() * 50; - int rand20 = (int) RandomUtils.nextFloat(); // Noncompliant; will always be 0; + int rand20 = (int) RandomUtils.nextFloat(); // Noncompliant // org.apache.commons.lang3.RandomUtils - int rand21 = (int) org.apache.commons.lang3.RandomUtils.nextDouble() * 50; // Noncompliant {{Use "nextInt()" instead.}} - int rand22 = (int) org.apache.commons.lang3.RandomUtils.nextFloat() * 50; // Noncompliant + int rand21 = (int) org.apache.commons.lang3.RandomUtils.nextDouble() * 50; // Noncompliant {{Use "nextInt()" instead.}} + int rand22 = (int) org.apache.commons.lang3.RandomUtils.nextFloat() * 50; // Noncompliant float rand23 = (float) org.apache.commons.lang3.RandomUtils.nextFloat(); int rand24 = (int) org.apache.commons.lang3.RandomUtils.nextInt() * 50; - int rand25 = (int)org.apache.commons.lang3.RandomUtils.nextFloat(); // Noncompliant; will always be 0; + int rand25 = (int)org.apache.commons.lang3.RandomUtils.nextFloat(); // Noncompliant void testLong(){ - int randInt = (int) r.nextDouble() * 50; // Noncompliant [[sc=25;ec=37]] - long randLong = (long) r.nextDouble() * 50; // Noncompliant [[sc=28;ec=40]] {{Use "nextLong()" instead.}} + int randInt = (int) r.nextDouble() * 50; // Noncompliant +// ^^^^^^^^^^^^ + long randLong = (long) r.nextDouble() * 50; // Noncompliant {{Use "nextLong()" instead.}} +// ^^^^^^^^^^^^ } } diff --git a/java-checks-test-sources/default/src/main/java/checks/RawByteBitwiseOperationsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/RawByteBitwiseOperationsCheckSample.java index bd669c27367..510c092553f 100644 --- a/java-checks-test-sources/default/src/main/java/checks/RawByteBitwiseOperationsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/RawByteBitwiseOperationsCheckSample.java @@ -9,10 +9,14 @@ void foo() { long longValue = 1L; byte b = 100; - value = (value << 8) + b; // Noncompliant [[sc=28;ec=29]] {{Prevent "int" promotion by adding "& 0xff" to this expression.}} - value = readByte() + (value << 8); // Noncompliant [[sc=13;ec=23]] {{Prevent "int" promotion by adding "& 0xff" to this expression.}} - value = b | (value << 8); // Noncompliant [[sc=13;ec=14]] {{Prevent "int" promotion by adding "& 0xff" to this expression.}} - value = (value << 8) | readByte(); // Noncompliant [[sc=28;ec=38]] {{Prevent "int" promotion by adding "& 0xff" to this expression.}} + value = (value << 8) + b; // Noncompliant {{Prevent "int" promotion by adding "& 0xff" to this expression.}} +// ^ + value = readByte() + (value << 8); // Noncompliant {{Prevent "int" promotion by adding "& 0xff" to this expression.}} +// ^^^^^^^^^^ + value = b | (value << 8); // Noncompliant {{Prevent "int" promotion by adding "& 0xff" to this expression.}} +// ^ + value = (value << 8) | readByte(); // Noncompliant {{Prevent "int" promotion by adding "& 0xff" to this expression.}} +// ^^^^^^^^^^ value = (value << 8) + (b & 0xff); // Compliant value = (0xff & readByte()) + (value << 8); // Compliant @@ -20,8 +24,10 @@ void foo() { value = (value << 8) | (readByte() & 0xff); // Compliant value = (value << 8) | (readByte() | 0xaa); // Compliant - longValue = (longValue << 8) + a.b; // Noncompliant [[sc=36;ec=39]] {{Prevent "int" promotion by adding "& 0xff" to this expression.}} - longValue = a.readByte() | (longValue << 8); // Noncompliant [[sc=17;ec=29]] {{Prevent "int" promotion by adding "& 0xff" to this expression.}} + longValue = (longValue << 8) + a.b; // Noncompliant {{Prevent "int" promotion by adding "& 0xff" to this expression.}} +// ^^^ + longValue = a.readByte() | (longValue << 8); // Noncompliant {{Prevent "int" promotion by adding "& 0xff" to this expression.}} +// ^^^^^^^^^^^^ value += b; // Compliant value += readByte(); // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/RawExceptionCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/RawExceptionCheckSample.java index 9545a98448a..b64e1de671b 100644 --- a/java-checks-test-sources/default/src/main/java/checks/RawExceptionCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/RawExceptionCheckSample.java @@ -2,7 +2,8 @@ public class RawExceptionCheckSample { - public void throws_Throwable() throws Throwable { // Noncompliant [[sc=41;ec=50]] + public void throws_Throwable() throws Throwable { // Noncompliant +// ^^^^^^^^^ throw new Throwable(); // Noncompliant } @@ -10,14 +11,17 @@ public void method_throwing_throwable() throws Throwable { // Compliant throwingExceptionMethod1(); } - private void throwingExceptionMethod1() throws Throwable { // Noncompliant [[sc=50;ec=59]] + private void throwingExceptionMethod1() throws Throwable { // Noncompliant +// ^^^^^^^^^ } - private void throwingExceptionMethod2() throws java.lang.Throwable { // Noncompliant [[sc=50;ec=69]] + private void throwingExceptionMethod2() throws java.lang.Throwable { // Noncompliant +// ^^^^^^^^^^^^^^^^^^^ } public void throws_Error() { - throw new Error(); // Noncompliant [[sc=15;ec=20]] + throw new Error(); // Noncompliant +// ^^^^^ } public void throws_Exception() throws Exception { // Noncompliant {{Define and throw a dedicated exception instead of using a generic one.}} @@ -57,11 +61,11 @@ public void exception() { } public RawExceptionCheckSample() throws - Throwable, // Noncompliant - Error, // Noncompliant - Exception { // Noncompliant {{Define and throw a dedicated exception instead of using a generic one.}} + Throwable, // Noncompliant + Error, // Noncompliant + Exception { // Noncompliant {{Define and throw a dedicated exception instead of using a generic one.}} throw new - Throwable(); // Noncompliant + Throwable(); // Noncompliant } diff --git a/java-checks-test-sources/default/src/main/java/checks/RawTypeCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/RawTypeCheckSample.java index 2486fe374d3..35df37f3dd0 100644 --- a/java-checks-test-sources/default/src/main/java/checks/RawTypeCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/RawTypeCheckSample.java @@ -5,9 +5,12 @@ public class RawTypeCheckSample { void foo() { - GenericClass v; // Noncompliant [[sc=5;ec=17]] {{Provide the parametrized type for this generic.}} - v = new GenericClass(); // Noncompliant [[sc=13;ec=25]] {{Provide the parametrized type for this generic.}} - v = new RawTypeCheckSample.GenericClass(); // Noncompliant [[sc=32;ec=44]] + GenericClass v; // Noncompliant {{Provide the parametrized type for this generic.}} +// ^^^^^^^^^^^^ + v = new GenericClass(); // Noncompliant {{Provide the parametrized type for this generic.}} +// ^^^^^^^^^^^^ + v = new RawTypeCheckSample.GenericClass(); // Noncompliant +// ^^^^^^^^^^^^ v = new GenericClass<>(); // Compliant v = new GenericClass(); // Compliant @@ -15,7 +18,7 @@ void foo() { RawTypeCheckSample t; @SuppressWarnings("rawtypes") - Optional o2; // Noncompliant - should be handled by SONARJAVA-2410 and filtered out + Optional o2; // Noncompliant Optional o1 = Optional.empty(); // Compliant } @@ -24,7 +27,8 @@ void foo() { static class GenericClass { } interface GenericInterface { } - abstract static class InnerClass1 extends GenericClass { // Noncompliant [[sc=45;ec=57]] {{Provide the parametrized type for this generic.}} + abstract static class InnerClass1 extends GenericClass { // Noncompliant {{Provide the parametrized type for this generic.}} +// ^^^^^^^^^^^^ abstract GenericClass bar(); // Noncompliant abstract void qix(GenericClass gc); // Noncompliant } @@ -34,7 +38,10 @@ static class InnerClass2 extends InnerClass1 { @Override void qix(GenericClass gc) { } // Compliant - override } - static class InnerClass3 implements GenericInterface { } // Noncompliant [[sc=39;ec=55]] {{Provide the parametrized type for this generic.}} - static class InnerClass4 implements GenericInterface {} // Noncompliant [[sc=56;ec=68]] - enum InnerEnum implements GenericInterface { } // Noncompliant [[sc=29;ec=45]] + static class InnerClass3 implements GenericInterface { } // Noncompliant {{Provide the parametrized type for this generic.}} +// ^^^^^^^^^^^^^^^^ + static class InnerClass4 implements GenericInterface {} // Noncompliant +// ^^^^^^^^^^^^ + enum InnerEnum implements GenericInterface { } // Noncompliant +// ^^^^^^^^^^^^^^^^ } diff --git a/java-checks-test-sources/default/src/main/java/checks/RecordDuplicatedGetterCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/RecordDuplicatedGetterCheckSample.java index 73d23c4d138..7e00854769d 100644 --- a/java-checks-test-sources/default/src/main/java/checks/RecordDuplicatedGetterCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/RecordDuplicatedGetterCheckSample.java @@ -10,15 +10,18 @@ record Being(String name, int age, double size, int friends, List ancesto private static final Being CTHULU = new Being("Cthulhu", Integer.MAX_VALUE, Double.MAX_VALUE, Integer.MIN_VALUE, Collections.emptyList(), true, Color.GREEN, 0); - public String getName() { return name.toUpperCase(Locale.ROOT); } // Noncompliant [[sc=19;ec=26]] {{Remove this getter 'getName()' from record and override an existing one 'name()'.}} - public boolean isAlive() { return CTHULU.alive; } // Noncompliant [[sc=20;ec=27]] {{Remove this getter 'isAlive()' from record and override an existing one 'alive()'.}} - public double getSize() { return Math.random(); } // Noncompliant - public int getTentacles() { return this.friends; } // Noncompliant - public void getAncestors() { assert(!ancestors.isEmpty()); } // Noncompliant + public String getName() { return name.toUpperCase(Locale.ROOT); } // Noncompliant {{Remove this getter 'getName()' from record and override an existing one 'name()'.}} +// ^^^^^^^ + public boolean isAlive() { return CTHULU.alive; } // Noncompliant {{Remove this getter 'isAlive()' from record and override an existing one 'alive()'.}} +// ^^^^^^^ + public double getSize() { return Math.random(); } // Noncompliant + public int getTentacles() { return this.friends; } // Noncompliant + public void getAncestors() { assert(!ancestors.isEmpty()); } // Noncompliant public Color getColor() { System.out.println("yellow"); return color(); } // Noncompliant @Override public int age() { return age; } - public int getAge() { return age + 42; } // Noncompliant [[sc=16;ec=22]] {{Remove this getter 'getAge()' from record and override an existing one 'age()'.}} + public int getAge() { return age + 42; } // Noncompliant {{Remove this getter 'getAge()' from record and override an existing one 'age()'.}} +// ^^^^^^ } record Person(String name, int age, double size, int friends, boolean alive, Color color, float power, int tentacles) { diff --git a/java-checks-test-sources/default/src/main/java/checks/RecordInsteadOfClassCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/RecordInsteadOfClassCheckSample.java index efb141bf570..fc737f4b6c3 100644 --- a/java-checks-test-sources/default/src/main/java/checks/RecordInsteadOfClassCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/RecordInsteadOfClassCheckSample.java @@ -15,7 +15,8 @@ public int getI() { } } - final class SimpleClass implements NotAClass { // Noncompliant [[sc=15;ec=26]] {{Refactor this class declaration to use 'record SimpleClass(int sum)'.}} + final class SimpleClass implements NotAClass { // Noncompliant {{Refactor this class declaration to use 'record SimpleClass(int sum)'.}} +// ^^^^^^^^^^^ private final int sum; public static final int VALUE = 42; @@ -25,7 +26,8 @@ final class SimpleClass implements NotAClass { // Noncompliant [[sc=15;ec=26]] { @Override public void foo() { } } - final class SimpleClass2 { // Noncompliant [[sc=15;ec=27]] {{Refactor this class declaration to use 'record SimpleClass2(boolean boom, int a)'.}} + final class SimpleClass2 { // Noncompliant {{Refactor this class declaration to use 'record SimpleClass2(boolean boom, int a)'.}} +// ^^^^^^^^^^^^ private final boolean boom; private final int a; diff --git a/java-checks-test-sources/default/src/main/java/checks/RecordPatternInsteadOfFieldAccessCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/RecordPatternInsteadOfFieldAccessCheckSample.java index 8bb4936af93..1371c2fa25d 100644 --- a/java-checks-test-sources/default/src/main/java/checks/RecordPatternInsteadOfFieldAccessCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/RecordPatternInsteadOfFieldAccessCheckSample.java @@ -35,9 +35,12 @@ int allComponentsPlusAMethod(Object obj){ } int nonCompliant(Object obj) { - if (obj instanceof Point p) { // Noncompliant [[sc=24;ec=31;secondary=+1,+2]] {{Use the record pattern instead of this pattern match variable.}} + if (obj instanceof Point p) { // Noncompliant {{Use the record pattern instead of this pattern match variable.}} +// ^^^^^^^ int x = p.x(); +// ^^^< int y = p.y(); +// ^^^< return x + y; } else if (obj instanceof String s) { return s.length(); @@ -56,15 +59,18 @@ int compliantSinceOnly1MemberUsed(Object obj) { int nonCompliantSwitch(Object o) { return switch (o) { - case Point p -> p.x() + p.y(); // Noncompliant [[secondary=+0,+0]] + case Point p -> p.x() + p.y(); // Noncompliant default -> 0; }; } int nonCompliantSwitchOnLine(Object obj) { - if (obj instanceof Line line) { // Noncompliant [[secondary=+1,+2]] + if (obj instanceof Line line) { // Noncompliant + // ^^^^^^^^^ int x = line.start().x(); +// ^^^^^^^^^^< int y = line.end().y(); +// ^^^^^^^^< return x + y; } return 0; diff --git a/java-checks-test-sources/default/src/main/java/checks/RedundantCloseCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/RedundantCloseCheckSample.java index a05ad22a193..8c05dc217a7 100644 --- a/java-checks-test-sources/default/src/main/java/checks/RedundantCloseCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/RedundantCloseCheckSample.java @@ -12,7 +12,8 @@ void foo(MyCloseable mc2) throws Exception { // java 9 mc2; this.mc3) { - mc1.close(); // Noncompliant [[sc=11;ec=18]] {{Remove this "close" call; closing the resource is handled automatically by the try-with-resources.}} + mc1.close(); // Noncompliant {{Remove this "close" call; closing the resource is handled automatically by the try-with-resources.}} +// ^^^^^^^ mc2.close(); // Noncompliant mc3.close(); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/RedundantModifierCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/RedundantModifierCheckSample.java index b98823a9473..9fb27262b0e 100644 --- a/java-checks-test-sources/default/src/main/java/checks/RedundantModifierCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/RedundantModifierCheckSample.java @@ -2,7 +2,8 @@ interface RedundantModifierInterface { void method1(); - public void method2(); // Noncompliant [[sc=3;ec=9]] {{"public" is redundant in this context.}} + public void method2(); // Noncompliant {{"public" is redundant in this context.}} +//^^^^^^ abstract void method3(); // Noncompliant {{"abstract" is redundant in this context.}} int field1 = 1; public int field2 = 1; // Noncompliant @@ -10,8 +11,10 @@ interface RedundantModifierInterface { final int field4 = 1; // Noncompliant {{"final" is redundant in this context.}} - static interface InnerInterface {} // Noncompliant [[sc=3;ec=9]] {{"static" is redundant in this context.}} - public interface InnerInterface2 {} // Noncompliant [[sc=3;ec=9]] {{"public" is redundant in this context.}} + static interface InnerInterface {} // Noncompliant {{"static" is redundant in this context.}} +//^^^^^^ + public interface InnerInterface2 {} // Noncompliant {{"public" is redundant in this context.}} +//^^^^^^ static final class InnerClass {} // Noncompliant {{"static" is redundant in this context.}} public final class InnerClass2 {} // Noncompliant {{"public" is redundant in this context.}} } @@ -19,15 +22,15 @@ public final class InnerClass2 {} // Noncompliant {{"public" is redundant in thi public @interface RedundantModifierCheckSample { String method1(); public String method2(); // Noncompliant - // Noncompliant@+1 + // Noncompliant@+1 public static class InnerClass {} // Noncompliant } @interface RedundantModifierAnnotation { String method1(); public String method2(); // Noncompliant - // Noncompliant@+1 - public static interface InnerInterface {} // Noncompliant + // Noncompliant@+1 + public static interface InnerInterface {} // Noncompliant } final class RedundantModifierClassFinal { @@ -45,7 +48,7 @@ final class InnerClass {} class RedundantModifierNonFinalClass { final void method2() {} - public static interface InnerInterface {} // Noncompliant {{"static" is redundant in this context.}} + public static interface InnerInterface {} // Noncompliant {{"static" is redundant in this context.}} public static final class NestedClass {} } enum RedundantModifierFoo { diff --git a/java-checks-test-sources/default/src/main/java/checks/RedundantRecordMethodsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/RedundantRecordMethodsCheckSample.java index 55c9b8d93c7..99688ef4905 100644 --- a/java-checks-test-sources/default/src/main/java/checks/RedundantRecordMethodsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/RedundantRecordMethodsCheckSample.java @@ -9,7 +9,8 @@ record RedundantConstructorAndGetters(String name, int age) { static Object variable = null; static Object someOtherVariable = null; - RedundantConstructorAndGetters(String name, int age) { // Noncompliant [[sc=5;ec=35]] {{Remove this redundant constructor which is the same as a default one.}} + RedundantConstructorAndGetters(String name, int age) { // Noncompliant {{Remove this redundant constructor which is the same as a default one.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ System.out.println("Just printing something..."); this.name = name; int x = 42; @@ -18,11 +19,13 @@ record RedundantConstructorAndGetters(String name, int age) { this.age = age; } - public String name() { // Noncompliant [[sc=19;ec=23]] {{Remove this redundant method which is the same as a default one.}} + public String name() { // Noncompliant {{Remove this redundant method which is the same as a default one.}} +// ^^^^ return this.name; } - public int age() { // Noncompliant [[sc=16;ec=19]] {{Remove this redundant method which is the same as a default one.}} + public int age() { // Noncompliant {{Remove this redundant method which is the same as a default one.}} +// ^^^ return age; } } @@ -33,11 +36,13 @@ record ConstructorAssignsWithRedundantCast(String name, int age) { this.age = age; } - public String name() { // Noncompliant [[sc=19;ec=23]] {{Remove this redundant method which is the same as a default one.}} + public String name() { // Noncompliant {{Remove this redundant method which is the same as a default one.}} +// ^^^^ return this.name; } - public int age() { // Noncompliant [[sc=16;ec=19]] {{Remove this redundant method which is the same as a default one.}} + public int age() { // Noncompliant {{Remove this redundant method which is the same as a default one.}} +// ^^^ return age; } } @@ -77,10 +82,12 @@ record ConstructorAssignsStaticValue(String name, int age) { } record EmptyConstructorAndRedundantGetter(String name, int age) { - EmptyConstructorAndRedundantGetter { // Noncompliant [[sc=5;ec=39]] {{Remove this redundant constructor which is the same as a default one.}} + EmptyConstructorAndRedundantGetter { // Noncompliant {{Remove this redundant constructor which is the same as a default one.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } - public String name() { // Noncompliant [[sc=19;ec=23]] {{Remove this redundant method which is the same as a default one.}} + public String name() { // Noncompliant {{Remove this redundant method which is the same as a default one.}} +// ^^^^ return name; } } diff --git a/java-checks-test-sources/default/src/main/java/checks/RedundantThrowsDeclarationCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/RedundantThrowsDeclarationCheckSample.java index 0e5bf361f31..5245cffe9e8 100644 --- a/java-checks-test-sources/default/src/main/java/checks/RedundantThrowsDeclarationCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/RedundantThrowsDeclarationCheckSample.java @@ -26,7 +26,8 @@ public void foo6() throws IllegalArgumentException { // Compliant public void foo7() throws MyRuntimeException { // Compliant } - public void foo8() throws MyException, Exception { // Noncompliant [[sc=29;ec=40;quickfixes=qf_first]] {{Remove the declaration of thrown exception 'checks.RedundantThrowsDeclarationCheckSample$MyException' which is a subclass of 'java.lang.Exception'.}} + public void foo8() throws MyException, Exception { // Noncompliant {{Remove the declaration of thrown exception 'checks.RedundantThrowsDeclarationCheckSample$MyException' which is a subclass of 'java.lang.Exception'.}} [[quickfixes=qf_first]] +// ^^^^^^^^^^^ // fix@qf_first {{Remove "MyException"}} // edit@qf_first [[sc=29;ec=42]] {{}} } @@ -72,7 +73,8 @@ abstract class MySuperClass { } abstract class ThrownCheckedExceptions extends MySuperClass { - public ThrownCheckedExceptions(String s) throws MyException { // Noncompliant [[sc=51;ec=62;quickfixes=qf_all_throws]] {{Remove the declaration of thrown exception 'checks.MyException', as it cannot be thrown from constructor's body.}} + public ThrownCheckedExceptions(String s) throws MyException { // Noncompliant {{Remove the declaration of thrown exception 'checks.MyException', as it cannot be thrown from constructor's body.}} [[quickfixes=qf_all_throws]] +// ^^^^^^^^^^^ // fix@qf_all_throws {{Remove "MyException"}} // edit@qf_all_throws [[sc=43;ec=62]] {{}} bar(); @@ -137,11 +139,11 @@ public int foo10() throws MyException { // Compliant - designed for extension throw new UnsupportedOperationException(); } - private int foo11() throws MyException { // Noncompliant - private + private int foo11() throws MyException { // Noncompliant return 0; } - Object foo12() throws MyException { // Noncompliant - only target litteral + Object foo12() throws MyException { // Noncompliant return new Object(); } @@ -173,7 +175,8 @@ void foo17(java.io.File file) throws java.io.IOException { // Compliant MyClosea } } - void foo18(java.io.File file) throws IOException, ParseException { // Noncompliant [[sc=53;ec=67;quickfixes=qf_last]] {{Remove the declaration of thrown exception 'java.text.ParseException', as it cannot be thrown from method's body.}} + void foo18(java.io.File file) throws IOException, ParseException { // Noncompliant {{Remove the declaration of thrown exception 'java.text.ParseException', as it cannot be thrown from method's body.}} [[quickfixes=qf_last]] +// ^^^^^^^^^^^^^^ // fix@qf_last {{Remove "ParseException"}} // edit@qf_last [[sc=51;ec=67]] {{}} try (MyCloseable mac = getMyCloseable(file)) { @@ -320,7 +323,8 @@ public void overrideableMethod4() throws MyException { // Noncompliant * @exception MyException proper javadoc description * @throws MyException2 proper javadoc description */ - public void missingJavadocForException() throws MyException, java.io.IOException, MyException2 { // Noncompliant [[sc=66;ec=85;quickfixes=qf_middle]] {{Remove the declaration of thrown exception 'java.io.IOException', as it cannot be thrown from method's body.}} + public void missingJavadocForException() throws MyException, java.io.IOException, MyException2 { // Noncompliant {{Remove the declaration of thrown exception 'java.io.IOException', as it cannot be thrown from method's body.}} [[quickfixes=qf_middle]] +// ^^^^^^^^^^^^^^^^^^^ // fix@qf_middle {{Remove "IOException"}} // edit@qf_middle [[sc=66;ec=87]] {{}} bar(); diff --git a/java-checks-test-sources/default/src/main/java/checks/RedundantTypeCastCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/RedundantTypeCastCheckSample.java index 0cc5172d5ee..f11c782852b 100644 --- a/java-checks-test-sources/default/src/main/java/checks/RedundantTypeCastCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/RedundantTypeCastCheckSample.java @@ -17,7 +17,8 @@ class ExtendedNested extends Nested { } List list; List foo() { Object obj = null; - Object o1 = (List) foo(); // Noncompliant [[sc=17;ec=31;quickfixes=qf1]] {{Remove this unnecessary cast to "List".}} + Object o1 = (List) foo(); // Noncompliant {{Remove this unnecessary cast to "List".}} [[quickfixes=qf1]] +// ^^^^^^^^^^^^^^ // fix@qf1 {{Remove the cast to "List"}} // edit@qf1 [[sc=17;ec=32]] {{}} Object o2 = (List) foo(); // Noncompliant {{Remove this unnecessary cast to "List".}} @@ -32,7 +33,8 @@ List foo() { fun((ExtendedNested) b); // Noncompliant fun(((ExtendedNested) b)); // Noncompliant fun((((ExtendedNested) b))); // Noncompliant - fun((Nested) a, (ExtendedNested) a); // Noncompliant [[sc=9;ec=17]] + fun((Nested) a, (ExtendedNested) a); // Noncompliant +// ^^^^^^^^ fun((Nested) b); // Compliant - exception to distinguish the method to call List bees = new java.util.ArrayList(); List aaas = (List) bees; diff --git a/java-checks-test-sources/default/src/main/java/checks/ReflectionOnNonRuntimeAnnotationCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ReflectionOnNonRuntimeAnnotationCheckSample.java index 10c5764f955..11cd6be496c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ReflectionOnNonRuntimeAnnotationCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ReflectionOnNonRuntimeAnnotationCheckSample.java @@ -11,7 +11,8 @@ class ReflectionOnNonRuntimeAnnotationCheckSample { private Class annotation; void foo(Method m, Class c) { - m.isAnnotationPresent(Override.class); // Noncompliant [[sc=27;ec=41]] {{"@Override" is not available at runtime and cannot be seen with reflection.}} + m.isAnnotationPresent(Override.class); // Noncompliant {{"@Override" is not available at runtime and cannot be seen with reflection.}} +// ^^^^^^^^^^^^^^ c.isAnnotationPresent(Override.class); // Noncompliant {{"@Override" is not available at runtime and cannot be seen with reflection.}} m.isAnnotationPresent(Deprecated.class); //Compliant, runtime retention m.isAnnotationPresent(bar()); //Compliant, we can't know what the bar method is returning. diff --git a/java-checks-test-sources/default/src/main/java/checks/ReplaceGuavaWithJavaCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ReplaceGuavaWithJavaCheckSample.java index a99d7c08b77..b9d2abc5c1e 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ReplaceGuavaWithJavaCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ReplaceGuavaWithJavaCheckSample.java @@ -7,7 +7,8 @@ import java.io.IOException; class ReplaceGuavaWithJavaCheckSample { - ReplaceGuavaWithJavaCheckSample(com.google.common.base.Predicate p) {} // Noncompliant [[sc=35;ec=67]] {{Use "java.util.function.Predicate" instead.}} + ReplaceGuavaWithJavaCheckSample(com.google.common.base.Predicate p) {} // Noncompliant {{Use "java.util.function.Predicate" instead.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ReplaceGuavaWithJavaCheckSample(com.google.common.base.Function f) {} // Noncompliant {{Use "java.util.function.Function" instead.}} ReplaceGuavaWithJavaCheckSample(com.google.common.base.Supplier s) {} // Noncompliant {{Use "java.util.function.Supplier" instead.}} ReplaceGuavaWithJavaCheckSample(com.google.common.base.Optional o) {} // Noncompliant {{Use "java.util.Optional" instead.}} @@ -40,7 +41,8 @@ void doZ() { } void doWithLambda(B> b) { - b.foo(o -> o.isPresent()); // Noncompliant [[sc=11;ec=12]] {{Use "java.util.Optional" instead.}} + b.foo(o -> o.isPresent()); // Noncompliant {{Use "java.util.Optional" instead.}} +// ^ } static class B { @@ -48,8 +50,10 @@ void foo(java.util.function.Predicate predicate) {} } void tempDir() throws IOException { - com.google.common.io.Files.createTempDir(); // Noncompliant [[sc=5;ec=47]] {{Use "java.nio.file.Files.createTempDirectory" instead.}} - Files.createTempDir(); // Noncompliant [[sc=5;ec=26]] {{Use "java.nio.file.Files.createTempDirectory" instead.}} + com.google.common.io.Files.createTempDir(); // Noncompliant {{Use "java.nio.file.Files.createTempDirectory" instead.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + Files.createTempDir(); // Noncompliant {{Use "java.nio.file.Files.createTempDirectory" instead.}} +// ^^^^^^^^^^^^^^^^^^^^^ java.nio.file.Files.createTempDirectory(""); // Compliant } diff --git a/java-checks-test-sources/default/src/main/java/checks/ReplaceGuavaWithJavaCheck_no_version.java b/java-checks-test-sources/default/src/main/java/checks/ReplaceGuavaWithJavaCheck_no_version.java index 7a9c78bc0a7..1788b9c800a 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ReplaceGuavaWithJavaCheck_no_version.java +++ b/java-checks-test-sources/default/src/main/java/checks/ReplaceGuavaWithJavaCheck_no_version.java @@ -1,5 +1,6 @@ package checks; class ReplaceGuavaWithJavaCheck_no_version { - ReplaceGuavaWithJavaCheck_no_version(com.google.common.base.Predicate p) {} // Noncompliant [[sc=40;ec=72]] {{Use "java.util.function.Predicate" instead. (sonar.java.source not set. Assuming 8 or greater.)}} + ReplaceGuavaWithJavaCheck_no_version(com.google.common.base.Predicate p) {} // Noncompliant {{Use "java.util.function.Predicate" instead. (sonar.java.source not set. Assuming 8 or greater.)}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } diff --git a/java-checks-test-sources/default/src/main/java/checks/ReplaceLambdaByMethodRefCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ReplaceLambdaByMethodRefCheckSample.java index b6f30056f84..60f197909ab 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ReplaceLambdaByMethodRefCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ReplaceLambdaByMethodRefCheckSample.java @@ -17,7 +17,8 @@ void fun() { run.run(); IntStream.range(1, 5) .map((x) -> x * x) - .map(x -> square(x)) // Noncompliant [[sc=16;ec=18]] {{Replace this lambda with method reference 'this::square'.}} + .map(x -> square(x)) // Noncompliant {{Replace this lambda with method reference 'this::square'.}} +// ^^ .map(x -> { // Noncompliant return square(x); }) @@ -288,58 +289,73 @@ void testCasts5(Object param) { void quickFixes(List strings) { IntStream.range(1, 5).forEach(x -> staticMethod(x)); // Compliant, shorter - IntStream.range(1, 5).forEach(x -> CastCheck.staticMethod(x)); // Noncompliant [[sc=37;ec=39;quickfixes=qf1]] {{Replace this lambda with method reference 'CastCheck::staticMethod'.}} + IntStream.range(1, 5).forEach(x -> CastCheck.staticMethod(x)); // Noncompliant {{Replace this lambda with method reference 'CastCheck::staticMethod'.}} [[quickfixes=qf1]] +// ^^ // fix@qf1 {{Replace with "CastCheck::staticMethod"}} // edit@qf1 [[sc=35;ec=65]] {{CastCheck::staticMethod}} - IntStream.range(1, 5).forEach(param -> staticMethod(param)); // Noncompliant [[sc=41;ec=43;quickfixes=qf2]] {{Replace this lambda with method reference 'CastCheck::staticMethod'.}} + IntStream.range(1, 5).forEach(param -> staticMethod(param)); // Noncompliant {{Replace this lambda with method reference 'CastCheck::staticMethod'.}} [[quickfixes=qf2]] +// ^^ // fix@qf2 {{Replace with "CastCheck::staticMethod"}} // edit@qf2 [[sc=35;ec=63]] {{CastCheck::staticMethod}} - IntStream.range(1, 5).forEach(x -> notStatic(x)); // Noncompliant [[sc=37;ec=39;quickfixes=qf3]] {{Replace this lambda with method reference 'this::notStatic'.}} + IntStream.range(1, 5).forEach(x -> notStatic(x)); // Noncompliant {{Replace this lambda with method reference 'this::notStatic'.}} [[quickfixes=qf3]] +// ^^ // fix@qf3 {{Replace with "this::notStatic"}} // edit@qf3 [[sc=35;ec=52]] {{this::notStatic}} Nested n = new Nested(1); - IntStream.range(1, 5).forEach(x -> n.takeInt(x)); // Noncompliant [[sc=37;ec=39;quickfixes=qf4]] {{Replace this lambda with method reference 'n::takeInt'.}} + IntStream.range(1, 5).forEach(x -> n.takeInt(x)); // Noncompliant {{Replace this lambda with method reference 'n::takeInt'.}} [[quickfixes=qf4]] +// ^^ // fix@qf4 {{Replace with "n::takeInt"}} // edit@qf4 [[sc=35;ec=52]] {{n::takeInt}} IntStream.range(1, 5).forEach(x -> NestedStatic.takeIntStatic(x)); // FN, do not report an issue because NestedStatic is not final - IntStream.range(1, 5).forEach(x -> new Nested(x)); // Noncompliant [[sc=37;ec=39;quickfixes=qf_new_class]] {{Replace this lambda with method reference 'Nested::new'.}} + IntStream.range(1, 5).forEach(x -> new Nested(x)); // Noncompliant {{Replace this lambda with method reference 'Nested::new'.}} [[quickfixes=qf_new_class]] +// ^^ // fix@qf_new_class {{Replace with "Nested::new"}} // edit@qf_new_class [[sc=35;ec=53]] {{Nested::new}} - IntStream.range(1, 5).forEach(x -> new CastCheck.Nested(x)); // Noncompliant [[sc=37;ec=39;quickfixes=qf_new_class2]] {{Replace this lambda with method reference 'CastCheck.Nested::new'.}} + IntStream.range(1, 5).forEach(x -> new CastCheck.Nested(x)); // Noncompliant {{Replace this lambda with method reference 'CastCheck.Nested::new'.}} [[quickfixes=qf_new_class2]] +// ^^ // fix@qf_new_class2 {{Replace with "CastCheck.Nested::new"}} // edit@qf_new_class2 [[sc=35;ec=63]] {{CastCheck.Nested::new}} - IntStream.range(1, 5).forEach(x -> new NestedStatic.NestedInNested(x)); // Noncompliant [[sc=37;ec=39;quickfixes=qf_new_class3]] {{Replace this lambda with method reference 'NestedStatic.NestedInNested::new'.}} + IntStream.range(1, 5).forEach(x -> new NestedStatic.NestedInNested(x)); // Noncompliant {{Replace this lambda with method reference 'NestedStatic.NestedInNested::new'.}} [[quickfixes=qf_new_class3]] +// ^^ // fix@qf_new_class3 {{Replace with "NestedStatic.NestedInNested::new"}} // edit@qf_new_class3 [[sc=35;ec=74]] {{NestedStatic.NestedInNested::new}} strings.stream() - .map(s -> s.toLowerCase()) // Noncompliant [[sc=14;ec=16;quickfixes=qf5]] {{Replace this lambda with method reference 'String::toLowerCase'.}} + .map(s -> s.toLowerCase()) // Noncompliant {{Replace this lambda with method reference 'String::toLowerCase'.}} [[quickfixes=qf5]] +// ^^ // fix@qf5 {{Replace with "String::toLowerCase"}} // edit@qf5 [[sc=12;ec=32]] {{String::toLowerCase}} - .map(s -> { // Noncompliant [[sc=14;ec=16;quickfixes=qf6]] + .map(s -> { // Noncompliant [[quickfixes=qf6]] +// ^^ return s.toLowerCase(); }) // fix@qf6 {{Replace with "String::toLowerCase"}} - // edit@qf6 [[sc=12;el=+2;ec=8]] {{String::toLowerCase}} - .forEach(x -> System.out.println(x)); // Noncompliant [[sc=18;ec=20;quickfixes=qf7]] {{Replace this lambda with method reference 'System.out::println'.}} + // edit@qf6 [[sc=12;el=+3;ec=8]] {{String::toLowerCase}} + .forEach(x -> System.out.println(x)); // Noncompliant {{Replace this lambda with method reference 'System.out::println'.}} [[quickfixes=qf7]] +// ^^ // fix@qf7 {{Replace with "System.out::println"}} // edit@qf7 [[sc=16;ec=42]] {{System.out::println}} - strings.stream().filter(string -> string != null); // Noncompliant [[sc=36;ec=38;quickfixes=qf_null1]] + strings.stream().filter(string -> string != null); // Noncompliant [[quickfixes=qf_null1]] +// ^^ // fix@qf_null1 {{Replace with "Objects::nonNull"}} // edit@qf_null1 [[sc=29;ec=53]] {{Objects::nonNull}} - strings.stream().filter(s -> (s) == null);// Noncompliant [[sc=31;ec=33;quickfixes=qf_null2]] + strings.stream().filter(s -> (s) == null); // Noncompliant [[quickfixes=qf_null2]] +// ^^ // fix@qf_null2 {{Replace with "Objects::isNull"}} // edit@qf_null2 [[sc=29;ec=45]] {{Objects::isNull}} - barbar((o) -> o instanceof String); // Noncompliant [[sc=16;ec=18;quickfixes=qf_instance_of]] + barbar((o) -> o instanceof String); // Noncompliant [[quickfixes=qf_instance_of]] +// ^^ // fix@qf_instance_of {{Replace with "String.class::isInstance"}} // edit@qf_instance_of [[sc=12;ec=38]] {{String.class::isInstance}} - bar((object) -> (String) object); // Noncompliant [[sc=18;ec=20;quickfixes=qf_cast1]] + bar((object) -> (String) object); // Noncompliant [[quickfixes=qf_cast1]] +// ^^ // fix@qf_cast1 {{Replace with "String.class::cast"}} // edit@qf_cast1 [[sc=9;ec=36]] {{String.class::cast}} - bar6((object) -> (TestA[][]) object); // Noncompliant [[sc=19;ec=21;quickfixes=qf_cast2]] + bar6((object) -> (TestA[][]) object); // Noncompliant [[quickfixes=qf_cast2]] +// ^^ // fix@qf_cast2 {{Replace with "TestA[][].class::cast"}} // edit@qf_cast2 [[sc=10;ec=40]] {{TestA[][].class::cast}} } @@ -354,12 +370,14 @@ static int staticMethod(int x) { class Nested { { - IntStream.range(1, 5).forEach(parameter -> takeInt(parameter)); // Noncompliant [[sc=47;ec=49;quickfixes=qf_init]] {{Replace this lambda with method reference 'Nested.this::takeInt'.}} + IntStream.range(1, 5).forEach(parameter -> takeInt(parameter)); // Noncompliant {{Replace this lambda with method reference 'Nested.this::takeInt'.}} [[quickfixes=qf_init]] +// ^^ // Could be simpler: "this::takeInt", but add the class name since we can not get the enclosing method // fix@qf_init {{Replace with "Nested.this::takeInt"}} // edit@qf_init [[sc=37;ec=68]] {{Nested.this::takeInt}} - IntStream.range(1, 5).forEach(parameter -> notStatic(parameter)); // Noncompliant [[sc=47;ec=49;quickfixes=qf_init2]] {{Replace this lambda with method reference 'CastCheck.this::notStatic'.}} + IntStream.range(1, 5).forEach(parameter -> notStatic(parameter)); // Noncompliant {{Replace this lambda with method reference 'CastCheck.this::notStatic'.}} [[quickfixes=qf_init2]] +// ^^ // fix@qf_init2 {{Replace with "CastCheck.this::notStatic"}} // edit@qf_init2 [[sc=37;ec=70]] {{CastCheck.this::notStatic}} } @@ -369,18 +387,21 @@ class Nested { } void quickFixInNestedClass() { - IntStream.range(1, 5).forEach(parameter -> notStatic(parameter)); // Noncompliant [[sc=47;ec=49;quickfixes=qf_this]] {{Replace this lambda with method reference 'CastCheck.this::notStatic'.}} + IntStream.range(1, 5).forEach(parameter -> notStatic(parameter)); // Noncompliant {{Replace this lambda with method reference 'CastCheck.this::notStatic'.}} [[quickfixes=qf_this]] +// ^^ // fix@qf_this {{Replace with "CastCheck.this::notStatic"}} // edit@qf_this [[sc=37;ec=70]] {{CastCheck.this::notStatic}} - IntStream.range(1, 5).forEach(parameter -> staticMethod(parameter)); // Noncompliant [[sc=47;ec=49;quickfixes=qf_this2]] {{Replace this lambda with method reference 'CastCheck::staticMethod'.}} + IntStream.range(1, 5).forEach(parameter -> staticMethod(parameter)); // Noncompliant {{Replace this lambda with method reference 'CastCheck::staticMethod'.}} [[quickfixes=qf_this2]] +// ^^ // fix@qf_this2 {{Replace with "CastCheck::staticMethod"}} // edit@qf_this2 [[sc=37;ec=73]] {{CastCheck::staticMethod}} } class NestedDeeper { void quickFixInNestedClass() { - IntStream.range(1, 5).forEach(parameter -> notStatic(parameter)); // Noncompliant [[sc=49;ec=51;quickfixes=qf_this3]] {{Replace this lambda with method reference 'CastCheck.this::notStatic'.}} + IntStream.range(1, 5).forEach(parameter -> notStatic(parameter)); // Noncompliant {{Replace this lambda with method reference 'CastCheck.this::notStatic'.}} [[quickfixes=qf_this3]] +// ^^ // fix@qf_this3 {{Replace with "CastCheck.this::notStatic"}} // edit@qf_this3 [[sc=39;ec=72]] {{CastCheck.this::notStatic}} } @@ -396,14 +417,17 @@ public int doSomething() { } void quickFixInNestedClass() { - Stream.of(new NestedExtend()).forEach(x -> x.doSomething()); // Noncompliant [[sc=45;ec=47;quickfixes=qf_method_override]] + Stream.of(new NestedExtend()).forEach(x -> x.doSomething()); // Noncompliant [[quickfixes=qf_method_override]] +// ^^ // fix@qf_method_override {{Replace with "Nested::doSomething"}} // edit@qf_method_override [[sc=43;ec=63]] {{Nested::doSomething}} - Stream.of(new NestedExtendOverrideTakeInt()).forEach(x -> x.doSomething()); // Noncompliant [[sc=60;ec=62;quickfixes=qf_method_override3]] + Stream.of(new NestedExtendOverrideTakeInt()).forEach(x -> x.doSomething()); // Noncompliant [[quickfixes=qf_method_override3]] +// ^^ // fix@qf_method_override3 {{Replace with "Nested::doSomething"}} // edit@qf_method_override3 [[sc=58;ec=78]] {{Nested::doSomething}} - Stream.of(new NestedExtendOverrideTakeInt()).forEach(parameterWithLongName -> parameterWithLongName.doSomething()); // Noncompliant [[sc=80;ec=82;quickfixes=qf_method_override2]] + Stream.of(new NestedExtendOverrideTakeInt()).forEach(parameterWithLongName -> parameterWithLongName.doSomething()); // Noncompliant [[quickfixes=qf_method_override2]] +// ^^ // fix@qf_method_override2 {{Replace with "Nested::doSomething"}} // edit@qf_method_override2 [[sc=58;ec=118]] {{Nested::doSomething}} } @@ -439,7 +463,8 @@ static class NestedInNested { class LambdaB { void intToString() { - apply((i, r) -> Integer.toString(i, r)); // Noncompliant [[sc=18;ec=20;quickfixes=qf_int_to_str2]] + apply((i, r) -> Integer.toString(i, r)); // Noncompliant [[quickfixes=qf_int_to_str2]] +// ^^ // fix@qf_int_to_str2 {{Replace with "Integer::toString"}} // edit@qf_int_to_str2 [[sc=11;ec=43]] {{Integer::toString}} } @@ -484,7 +509,8 @@ String foo() { } void test() { - Optional.of(new TestNumber()).map(testNumber -> testNumber.foo()); // Noncompliant [[sc=50;ec=52;quickfixes=qf_supertype]] + Optional.of(new TestNumber()).map(testNumber -> testNumber.foo()); // Noncompliant [[quickfixes=qf_supertype]] +// ^^ // fix@qf_supertype {{Replace with "TestObject::foo"}} // edit@qf_supertype [[sc=39;ec=69]] {{TestObject::foo}} } @@ -515,14 +541,16 @@ static void consumeBoth(BiConsumer bc) { } void test() { - Optional.of(new TestInteger()).map(testInteger -> testInteger.foo()); // Noncompliant [[sc=52;ec=54;quickfixes=qf_supertype2]] + Optional.of(new TestInteger()).map(testInteger -> testInteger.foo()); // Noncompliant [[quickfixes=qf_supertype2]] +// ^^ // fix@qf_supertype2 {{Replace with "TestObject::foo"}} // edit@qf_supertype2 [[sc=40;ec=72]] {{TestObject::foo}} Optional.of(new TestInteger()).map(testInteger -> TestNumber.foo(testInteger)); // Compliant, method reference is ambiguous Optional.of(new TestInteger()).map(testInteger -> testInteger.spam()); // Compliant, method reference is ambiguous Optional.of(new TestInteger()).map(testInteger -> (foo().length() % 23 == 0 ? testInteger : null).spam(testInteger)); // Compliant, method reference is ambiguous Optional.of(new TestInteger()).map(testInteger -> testInteger.eggs()); // Compliant, method reference is ambiguous - consumeBoth((testInteger, s) -> testInteger.bar(s)); // Noncompliant [[sc=34;ec=36;quickfixes=qf_2args]] + consumeBoth((testInteger, s) -> testInteger.bar(s)); // Noncompliant [[quickfixes=qf_2args]] +// ^^ // fix@qf_2args {{Replace with "TestInteger::bar"}} // edit@qf_2args [[sc=17;ec=55]] {{TestInteger::bar}} consumeBoth((testInteger, s) -> testInteger.bar("test")); // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/RestrictedIdentifiersUsageCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/RestrictedIdentifiersUsageCheckSample.java index a379923f1c7..15a8ad61755 100644 --- a/java-checks-test-sources/default/src/main/java/checks/RestrictedIdentifiersUsageCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/RestrictedIdentifiersUsageCheckSample.java @@ -3,7 +3,7 @@ public class RestrictedIdentifiersUsageCheckSample { void noncompliant() { - var var = "var"; // Noncompliant: compiles but this code is confusing + var var = "var"; // Noncompliant var = "what is this?"; } diff --git a/java-checks-test-sources/default/src/main/java/checks/ResultSetIsLastCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ResultSetIsLastCheckSample.java index 71988a1fb7b..e405ef72388 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ResultSetIsLastCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ResultSetIsLastCheckSample.java @@ -4,7 +4,8 @@ class ResultSetIsLastCheckSample { void foo(ResultSet rs) throws Exception { - rs.isLast(); // Noncompliant [[sc=8;ec=14]] {{Remove this call to "isLast()".}} + rs.isLast(); // Noncompliant {{Remove this call to "isLast()".}} +// ^^^^^^ rs.afterLast(); this.isLast(); // Compliant } diff --git a/java-checks-test-sources/default/src/main/java/checks/ReturnEmptyArrayNotNullCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ReturnEmptyArrayNotNullCheckSample.java index ace8a0f2945..2bd8d0d7b88 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ReturnEmptyArrayNotNullCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ReturnEmptyArrayNotNullCheckSample.java @@ -20,7 +20,8 @@ public void f1() { } public int[] f2() { - return null; // Noncompliant [[sc=12;ec=16]] {{Return an empty array instead of null.}} + return null; // Noncompliant {{Return an empty array instead of null.}} +// ^^^^ } public Object f3() { @@ -28,7 +29,7 @@ public Object f3() { } public Object f4()[] { - return null; // Noncompliant + return null; // Noncompliant } public int[] f5(boolean cond) { @@ -38,36 +39,36 @@ public Object g1() { } public int[] g2() { - return null; // Noncompliant + return null; // Noncompliant } }; if (cond) { return new int[0]; } - return null; // Noncompliant + return null; // Noncompliant } public List f6() { - return null; // Noncompliant + return null; // Noncompliant } public ArrayList f7() { - return null; // Noncompliant + return null; // Noncompliant } public Set f8(boolean cond) { if (cond) { return Collections.EMPTY_SET; } - return null; // Noncompliant {{Return an empty collection instead of null.}} + return null; // Noncompliant {{Return an empty collection instead of null.}} } public List[] f9() { - return null; // Noncompliant {{Return an empty array instead of null.}} + return null; // Noncompliant {{Return an empty array instead of null.}} } public java.util.Collection f10() { - return null; // Noncompliant + return null; // Noncompliant } } @@ -100,7 +101,7 @@ default int[] f(){ class ReturnEmptyArrayNotNullCheckSampleC { @SuppressWarnings("Something") public int[] gul() { - return null; // Noncompliant + return null; // Noncompliant } @Nullable diff --git a/java-checks-test-sources/default/src/main/java/checks/ReturnEmptyArrayNotNullCheckWithQuickFixes.java b/java-checks-test-sources/default/src/main/java/checks/ReturnEmptyArrayNotNullCheckWithQuickFixes.java index c299d3e21cf..10e24d4b123 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ReturnEmptyArrayNotNullCheckWithQuickFixes.java +++ b/java-checks-test-sources/default/src/main/java/checks/ReturnEmptyArrayNotNullCheckWithQuickFixes.java @@ -20,124 +20,142 @@ class ReturnEmptyArrayNotNullCheckWithQuickFixes { Object[] array1() { Object[] result = new Object[0]; - return null; // Noncompliant [[sc=12;ec=16;quickfixes=array]] {{Return an empty array instead of null.}} + return null; // Noncompliant {{Return an empty array instead of null.}} [[quickfixes=array]] +// ^^^^ // fix@array {{Replace "null" with an empty array}} // edit@array [[sc=12;ec=16]] {{new Object[0]}} } String[][] array2() { String[][] result = new String[0][0]; - return null; // Noncompliant [[sc=12;ec=16;quickfixes=multi_dim_array]] {{Return an empty array instead of null.}} + return null; // Noncompliant {{Return an empty array instead of null.}} [[quickfixes=multi_dim_array]] +// ^^^^ // fix@multi_dim_array {{Replace "null" with an empty array}} // edit@multi_dim_array [[sc=12;ec=16]] {{new String[0][0]}} } List[] array_generics() { List[] result = new List[0]; - return null; // Noncompliant [[sc=12;ec=16;quickfixes=array_generics]] {{Return an empty array instead of null.}} + return null; // Noncompliant {{Return an empty array instead of null.}} [[quickfixes=array_generics]] +// ^^^^ // fix@array_generics {{Replace "null" with an empty array}} // edit@array_generics [[sc=12;ec=16]] {{new List[0]}} } List>[]>[][] strange_array() { List>[]>[][] result = new List[0][0]; - return null; // Noncompliant [[sc=12;ec=16;quickfixes=strange_array]] {{Return an empty array instead of null.}} + return null; // Noncompliant {{Return an empty array instead of null.}} [[quickfixes=strange_array]] +// ^^^^ // fix@strange_array {{Replace "null" with an empty array}} // edit@strange_array [[sc=12;ec=16]] {{new List[0][0]}} } List list() { List result = Collections.emptyList(); - return null; // Noncompliant [[sc=12;ec=16;quickfixes=list]] {{Return an empty collection instead of null.}} + return null; // Noncompliant {{Return an empty collection instead of null.}} [[quickfixes=list]] +// ^^^^ // fix@list {{Replace "null" with an empty List}} // edit@list [[sc=12;ec=16]] {{Collections.emptyList()}} } ArrayList arraylist() { ArrayList result = new ArrayList<>(); - return null; // Noncompliant [[sc=12;ec=16;quickfixes=arraylist]] {{Return an empty collection instead of null.}} + return null; // Noncompliant {{Return an empty collection instead of null.}} [[quickfixes=arraylist]] +// ^^^^ // fix@arraylist {{Replace "null" with an empty ArrayList}} // edit@arraylist [[sc=12;ec=16]] {{new ArrayList<>()}} } LinkedList linkedlist() { LinkedList result = new LinkedList<>(); - return null; // Noncompliant [[sc=12;ec=16;quickfixes=linkedlist]] {{Return an empty collection instead of null.}} + return null; // Noncompliant {{Return an empty collection instead of null.}} [[quickfixes=linkedlist]] +// ^^^^ // fix@linkedlist {{Replace "null" with an empty LinkedList}} // edit@linkedlist [[sc=12;ec=16]] {{new LinkedList<>()}} } // we don't know if there is a constructor MyCustomList customList() { - return null; // Noncompliant [[sc=12;ec=16;quickfixes=!]] {{Return an empty collection instead of null.}} + return null; // Noncompliant {{Return an empty collection instead of null.}} [[quickfixes=!]] +// ^^^^ } Set set() { Set result = Collections.emptySet(); - return null; // Noncompliant [[sc=12;ec=16;quickfixes=set]] {{Return an empty collection instead of null.}} + return null; // Noncompliant {{Return an empty collection instead of null.}} [[quickfixes=set]] +// ^^^^ // fix@set {{Replace "null" with an empty Set}} // edit@set [[sc=12;ec=16]] {{Collections.emptySet()}} } HashSet hashset() { HashSet result = new HashSet<>(); - return null; // Noncompliant [[sc=12;ec=16;quickfixes=hashset]] {{Return an empty collection instead of null.}} + return null; // Noncompliant {{Return an empty collection instead of null.}} [[quickfixes=hashset]] +// ^^^^ // fix@hashset {{Replace "null" with an empty HashSet}} // edit@hashset [[sc=12;ec=16]] {{new HashSet<>()}} } TreeSet treeset() { TreeSet result = new TreeSet<>(); - return null; // Noncompliant [[sc=12;ec=16;quickfixes=treeset]] {{Return an empty collection instead of null.}} + return null; // Noncompliant {{Return an empty collection instead of null.}} [[quickfixes=treeset]] +// ^^^^ // fix@treeset {{Replace "null" with an empty TreeSet}} // edit@treeset [[sc=12;ec=16]] {{new TreeSet<>()}} } SortedSet sortedset() { SortedSet result = Collections.emptySortedSet(); - return null; // Noncompliant [[sc=12;ec=16;quickfixes=sortedset]] {{Return an empty collection instead of null.}} + return null; // Noncompliant {{Return an empty collection instead of null.}} [[quickfixes=sortedset]] +// ^^^^ // fix@sortedset {{Replace "null" with an empty SortedSet}} // edit@sortedset [[sc=12;ec=16]] {{Collections.emptySortedSet()}} } NavigableSet navigableset() { NavigableSet result = Collections.emptyNavigableSet(); - return null; // Noncompliant [[sc=12;ec=16;quickfixes=navigableset]] {{Return an empty collection instead of null.}} + return null; // Noncompliant {{Return an empty collection instead of null.}} [[quickfixes=navigableset]] +// ^^^^ // fix@navigableset {{Replace "null" with an empty NavigableSet}} // edit@navigableset [[sc=12;ec=16]] {{Collections.emptyNavigableSet()}} } Map map() { Map result = Collections.emptyMap(); - return null; // Noncompliant [[sc=12;ec=16;quickfixes=map]] {{Return an empty map instead of null.}} + return null; // Noncompliant {{Return an empty map instead of null.}} [[quickfixes=map]] +// ^^^^ // fix@map {{Replace "null" with an empty Map}} // edit@map [[sc=12;ec=16]] {{Collections.emptyMap()}} } HashMap hashmap() { HashMap result = new HashMap<>(); - return null; // Noncompliant [[sc=12;ec=16;quickfixes=hashmap]] {{Return an empty map instead of null.}} + return null; // Noncompliant {{Return an empty map instead of null.}} [[quickfixes=hashmap]] +// ^^^^ // fix@hashmap {{Replace "null" with an empty HashMap}} // edit@hashmap [[sc=12;ec=16]] {{new HashMap<>()}} } SortedMap sortedmap() { SortedMap result = Collections.emptySortedMap(); - return null; // Noncompliant [[sc=12;ec=16;quickfixes=sortedmap]] {{Return an empty map instead of null.}} + return null; // Noncompliant {{Return an empty map instead of null.}} [[quickfixes=sortedmap]] +// ^^^^ // fix@sortedmap {{Replace "null" with an empty SortedMap}} // edit@sortedmap [[sc=12;ec=16]] {{Collections.emptySortedMap()}} } NavigableMap navigableMap() { NavigableMap result = Collections.emptyNavigableMap(); - return null; // Noncompliant [[sc=12;ec=16;quickfixes=navigableMap]] {{Return an empty map instead of null.}} + return null; // Noncompliant {{Return an empty map instead of null.}} [[quickfixes=navigableMap]] +// ^^^^ // fix@navigableMap {{Replace "null" with an empty NavigableMap}} // edit@navigableMap [[sc=12;ec=16]] {{Collections.emptyNavigableMap()}} } Collection collection() { Collection result = Collections.emptyList(); - return null; // Noncompliant [[sc=12;ec=16;quickfixes=collection]] {{Return an empty collection instead of null.}} + return null; // Noncompliant {{Return an empty collection instead of null.}} [[quickfixes=collection]] +// ^^^^ // fix@collection {{Replace "null" with an empty Collection}} // edit@collection [[sc=12;ec=16]] {{Collections.emptyList()}} } @@ -145,7 +163,8 @@ Collection collection() { // using vectors triggers java:S1149 - so no quick-fix Vector vector() { Vector result = new Vector<>(); - return null; // Noncompliant [[sc=12;ec=16;quickfixes=!]] {{Return an empty collection instead of null.}} + return null; // Noncompliant {{Return an empty collection instead of null.}} [[quickfixes=!]] +// ^^^^ } abstract static class MyCustomList implements List { } diff --git a/java-checks-test-sources/default/src/main/java/checks/ReturnEmptyArrayNotNullCheckWithQuickFixesAndImports.java b/java-checks-test-sources/default/src/main/java/checks/ReturnEmptyArrayNotNullCheckWithQuickFixesAndImports.java index 30bd44b849e..9906c5ec30b 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ReturnEmptyArrayNotNullCheckWithQuickFixesAndImports.java +++ b/java-checks-test-sources/default/src/main/java/checks/ReturnEmptyArrayNotNullCheckWithQuickFixesAndImports.java @@ -6,27 +6,31 @@ class ReturnEmptyArrayNotNullCheckWithQuickFixesAndImports { java.util.List list() { - return null; // Noncompliant [[sc=12;ec=16;quickfixes=list]] {{Return an empty collection instead of null.}} + return null; // Noncompliant {{Return an empty collection instead of null.}} [[quickfixes=list]] +// ^^^^ // fix@list {{Replace "null" with an empty List}} // edit@list [[sc=12;ec=16]] {{Collections.emptyList()}} // edit@list [[sl=3;sc=1;el=3;ec=1]] {{import java.util.Collections;\n}} } java.util.LinkedList linkedList() { - return null; // Noncompliant [[sc=12;ec=16;quickfixes=linkedList]] {{Return an empty collection instead of null.}} + return null; // Noncompliant {{Return an empty collection instead of null.}} [[quickfixes=linkedList]] +// ^^^^ // fix@linkedList {{Replace "null" with an empty LinkedList}} // edit@linkedList [[sc=12;ec=16]] {{new LinkedList<>()}} // edit@linkedList [[sl=3;sc=26;el=3;ec=26]] {{\nimport java.util.LinkedList;}} } HashSet hashset() { - return null; // Noncompliant [[sc=12;ec=16;quickfixes=HashSet]] {{Return an empty collection instead of null.}} + return null; // Noncompliant {{Return an empty collection instead of null.}} [[quickfixes=HashSet]] +// ^^^^ // fix@HashSet {{Replace "null" with an empty HashSet}} // edit@HashSet [[sc=12;ec=16]] {{new HashSet<>()}} } Map map() { - return null; // Noncompliant [[sc=12;ec=16;quickfixes=map]] {{Return an empty map instead of null.}} + return null; // Noncompliant {{Return an empty map instead of null.}} [[quickfixes=map]] +// ^^^^ // fix@map {{Replace "null" with an empty Map}} // edit@map [[sc=12;ec=16]] {{Collections.emptyMap()}} // edit@map [[sl=3;sc=1;el=3;ec=1]] {{import java.util.Collections;\n}} diff --git a/java-checks-test-sources/default/src/main/java/checks/ReuseRandomCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ReuseRandomCheckSample.java index 5c1d59968a5..1ea43163dd0 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ReuseRandomCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ReuseRandomCheckSample.java @@ -13,7 +13,8 @@ public class ReuseRandomCheckSample { } void func(long seed, Random param) { - Random localVar1 = new Random(); // Noncompliant [[sc=28;ec=34]] {{Save and re-use this "Random".}} + Random localVar1 = new Random(); // Noncompliant {{Save and re-use this "Random".}} +// ^^^^^^ Random localVar2 = new Random(seed); // Compliant for Random(long seed) Object localVar3 = new Object(); @@ -33,7 +34,8 @@ void func(long seed, Random param) { func(12, new Random()); func(12, localVar1 = new Random()); - int usedDirectly = new Random().nextInt(); // Noncompliant [[sc=28;ec=34]] + int usedDirectly = new Random().nextInt(); // Noncompliant +// ^^^^^^ (new Random()).nextInt(); // Noncompliant } diff --git a/java-checks-test-sources/default/src/main/java/checks/ReverseSequencedCollectionCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ReverseSequencedCollectionCheckSample.java index 06f23b5ce06..b9cdaa0607b 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ReverseSequencedCollectionCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ReverseSequencedCollectionCheckSample.java @@ -12,7 +12,7 @@ class ReverseSequencedCollectionCheckSample { List test_read_only_usage_as_argument(List source) { var list = new ArrayList<>(source); - Collections.reverse(list); // Noncompliant, only readonly access after + Collections.reverse(list); // Noncompliant var list2 = new ArrayList<>(list); list2.addAll(list); return List.copyOf(list); diff --git a/java-checks-test-sources/default/src/main/java/checks/ReversedMethodSequencedCollectionCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ReversedMethodSequencedCollectionCheckSample.java index 06af41dde9d..2ca53f6e09f 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ReversedMethodSequencedCollectionCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ReversedMethodSequencedCollectionCheckSample.java @@ -6,7 +6,8 @@ public class ReversedMethodSequencedCollectionCheckSample { void printLastToFirst(List list, ListIterator listIterator) { - for (var it = list.listIterator(list.size()); it.hasPrevious(); ) { // Noncompliant[[sc=5;ec=8]] {{Use the "reversed()" method + for (var it = list.listIterator(list.size()); it.hasPrevious(); ) { // Noncompliant +// ^^^ // instead of manually iterating the list in reverse.}} var element = it.previous(); } @@ -69,7 +70,7 @@ void coverage(List list, ListIterator iterator) { for (var it = list.listIterator(list.size()); it.hasPrevious(); ) { // Noncompliant } - for (var it = list.listIterator(list.size()); it.hasPrevious(); ) { // Noncompliant - FP it.previous() is called more than once + for (var it = list.listIterator(list.size()); it.hasPrevious(); ) { // Noncompliant it.previous(); it.previous(); } diff --git a/java-checks-test-sources/default/src/main/java/checks/RightCurlyBraceSameLineAsNextBlockCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/RightCurlyBraceSameLineAsNextBlockCheckSample.java index a000e5ef64c..714701e98cf 100644 --- a/java-checks-test-sources/default/src/main/java/checks/RightCurlyBraceSameLineAsNextBlockCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/RightCurlyBraceSameLineAsNextBlockCheckSample.java @@ -7,7 +7,8 @@ public void myMethod(boolean something, boolean somethingElse) { } else if (somethingElse) { // Compliant doSomethingElse(); } - else { // Noncompliant [[sc=5;ec=9;quickfixes=qf1]] {{Move this "else" on the same line that the previous closing curly brace.}} + else { // Noncompliant {{Move this "else" on the same line that the previous closing curly brace.}} [[quickfixes=qf1]] +// ^^^^ // fix@qf1 {{Move to the same line as the closing curly brace}} // edit@qf1 [[sl=-1;sc=6;el=+0;ec=5]] {{ }} generateError(); @@ -26,7 +27,8 @@ public void myMethod(boolean something, boolean somethingElse) { try { generateOrder(); } - catch (RuntimeException e) { // Noncompliant [[sc=7;ec=12;quickfixes=qf2]] {{Move this "catch" on the same line that the previous closing curly brace.}} + catch (RuntimeException e) { // Noncompliant {{Move this "catch" on the same line that the previous closing curly brace.}} [[quickfixes=qf2]] +// ^^^^^ // fix@qf2 {{Move to the same line as the closing curly brace}} // edit@qf2 [[sl=-1;sc=8;el=+0;ec=7]] {{ }} log(e); @@ -35,7 +37,8 @@ public void myMethod(boolean something, boolean somethingElse) { } - finally { // Noncompliant [[sc=5;ec=12;quickfixes=qf3]] {{Move this "finally" on the same line that the previous closing curly brace.}} + finally { // Noncompliant {{Move this "finally" on the same line that the previous closing curly brace.}} [[quickfixes=qf3]] +// ^^^^^^^ // fix@qf3 {{Move to the same line as the closing curly brace}} // edit@qf3 [[sl=-3;sc=8;el=+0;ec=5]] {{ }} closeConnection(); @@ -46,7 +49,7 @@ public void myMethod(boolean something, boolean somethingElse) { try { generateOrder(); } - catch (Exception e) { // Noncompliant {{Move this "catch" on the same line that the previous closing curly brace.}} + catch (Exception e) { // Noncompliant {{Move this "catch" on the same line that the previous closing curly brace.}} log(e); } } diff --git a/java-checks-test-sources/default/src/main/java/checks/S1874_CallToDeprecatedMethod.java b/java-checks-test-sources/default/src/main/java/checks/S1874_CallToDeprecatedMethod.java index 25b30beb39c..866ac469605 100644 --- a/java-checks-test-sources/default/src/main/java/checks/S1874_CallToDeprecatedMethod.java +++ b/java-checks-test-sources/default/src/main/java/checks/S1874_CallToDeprecatedMethod.java @@ -6,8 +6,10 @@ class S1874_CallToDeprecatedMethod { public S1874_CallToDeprecatedMethod() { String string = new String("my string"); - string.getBytes(1, 1, new byte[3], 7); // Noncompliant [[sc=12;ec=20]] {{Remove this use of "getBytes"; it is deprecated.}} - new DeprecatedConstructor(); // Noncompliant [[sc=9;ec=30]] {{Remove this use of "DeprecatedConstructor"; it is deprecated.}} + string.getBytes(1, 1, new byte[3], 7); // Noncompliant {{Remove this use of "getBytes"; it is deprecated.}} +// ^^^^^^^^ + new DeprecatedConstructor(); // Noncompliant {{Remove this use of "DeprecatedConstructor"; it is deprecated.}} +// ^^^^^^^^^^^^^^^^^^^^^ new MyDeprecatedClass(); // Noncompliant old++; // Noncompliant MyDeprecatedClass.a++; // Noncompliant @@ -30,7 +32,8 @@ private static class MyDeprecatedClass { static int a; } - public static class ExtendsDeprecatedClass extends MyDeprecatedClass { // Noncompliant [[sc=54;ec=71]] {{Remove this use of "MyDeprecatedClass"; it is deprecated.}} + public static class ExtendsDeprecatedClass extends MyDeprecatedClass { // Noncompliant {{Remove this use of "MyDeprecatedClass"; it is deprecated.}} +// ^^^^^^^^^^^^^^^^^ } public static abstract class ClassWithDeprecatedMethods { @@ -50,7 +53,8 @@ public interface InterfaceWithDeprecatedMethods { } public static class ClassOverridingDeprecatedMethods extends ClassWithDeprecatedMethods implements InterfaceWithDeprecatedMethods { - public void deprecatedMethod1() { // Noncompliant [[sc=17;ec=34]] {{Don't override a deprecated method or explicitly mark it as "@Deprecated".}} + public void deprecatedMethod1() { // Noncompliant {{Don't override a deprecated method or explicitly mark it as "@Deprecated".}} +// ^^^^^^^^^^^^^^^^^ } @Deprecated public void deprecatedMethod2() { // Compliant, explicitely marked as "@Deprecated" @@ -119,7 +123,8 @@ class MyDeprecatedType { class MethodResolution { public static void test() { HasDeprecations.method(new ArrayList<>()); - HasDeprecations.method(new HashMap<>()); // Noncompliant [[sc=21;ec=27]] {{Remove this use of "method"; it is deprecated.}} + HasDeprecations.method(new HashMap<>()); // Noncompliant {{Remove this use of "method"; it is deprecated.}} +// ^^^^^^ } static class HasDeprecations { diff --git a/java-checks-test-sources/default/src/main/java/checks/S1874_CallToDeprecatedMethod_java9.java b/java-checks-test-sources/default/src/main/java/checks/S1874_CallToDeprecatedMethod_java9.java index 64ca8fd7475..a8854f04fdb 100644 --- a/java-checks-test-sources/default/src/main/java/checks/S1874_CallToDeprecatedMethod_java9.java +++ b/java-checks-test-sources/default/src/main/java/checks/S1874_CallToDeprecatedMethod_java9.java @@ -23,10 +23,10 @@ void test() { qix(); // Noncompliant {{Remove this use of "qix"; it is deprecated.}} new DeprecatedForRemoval(); - new DeprecatedDefault(); // Noncompliant {{Remove this use of "DeprecatedDefault", it has been marked for removal.} + new DeprecatedDefault(); // Noncompliant String s = - a // Noncompliant {{Remove this use of a "a"; it is deprecated.} + a // Noncompliant + b; } @@ -41,6 +41,6 @@ static class Extending extends S1874_CallToDeprecatedMethod_java9 { void foo() {} @Override - void bar() {} // Noncompliant {{Don't override a deprecated method or explicitly mark it as "@Deprecated".}} + void bar() {} // Noncompliant {{Don't override a deprecated method or explicitly mark it as "@Deprecated".}} } } diff --git a/java-checks-test-sources/default/src/main/java/checks/S2201_IgnoredReturnValueCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/S2201_IgnoredReturnValueCheckSample.java index b32841b29b3..955803c2a74 100644 --- a/java-checks-test-sources/default/src/main/java/checks/S2201_IgnoredReturnValueCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/S2201_IgnoredReturnValueCheckSample.java @@ -45,7 +45,8 @@ void foo() { new S2201_IgnoredReturnValueCheckSample().intMethod();// Compliant new S2201_IgnoredReturnValueCheckSample().voidMethod();// Compliant Integer.valueOf("1").byteValue(); // Noncompliant {{The return value of "byteValue" must be used.}} - "plop".replace('p', 'b'); // Noncompliant [[sc=12;ec=19]] {{The return value of "replace" must be used.}} + "plop".replace('p', 'b'); // Noncompliant {{The return value of "replace" must be used.}} +// ^^^^^^^ new RuntimeException("plop").getStackTrace()[0].getClassName(); // Noncompliant {{The return value of "getClassName" must be used.}} a++; list.stream().filter(s -> s.length() > 4).map(String::length).forEach(i -> {System.out.println(i);}); @@ -77,7 +78,7 @@ void foo() { Character c = Character.valueOf('c'); c.toChars(0, new char[42], 21); // Compliant - s.getBytes(java.nio.charset.Charset.forName("UTF-8")); // Noncompliant not within a try/catch + s.getBytes(java.nio.charset.Charset.forName("UTF-8")); // Noncompliant list.size(); // Noncompliant list.iterator(); // Noncompliant @@ -169,7 +170,7 @@ public Collection get() { Stream.of("a", "b", "c").collect(this::makeList, List::add, List::addAll); // FN because we don't follow methods to check whether they return a new or existing collection Collector collector = Collectors.toCollection(() -> myList); - Stream.of("a", "b", "c").collect(collector); // Noncompliant FP because we don't check collectors for exclusion if they aren't created directly as a method argument + Stream.of("a", "b", "c").collect(collector); // Noncompliant } List makeList() { diff --git a/java-checks-test-sources/default/src/main/java/checks/S2638_ChangeMethodContractCheck/noPackageInfo/ChangeMethodContractCheck.java b/java-checks-test-sources/default/src/main/java/checks/S2638_ChangeMethodContractCheck/noPackageInfo/ChangeMethodContractCheck.java index a45f0dae195..404e7e1c924 100644 --- a/java-checks-test-sources/default/src/main/java/checks/S2638_ChangeMethodContractCheck/noPackageInfo/ChangeMethodContractCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/S2638_ChangeMethodContractCheck/noPackageInfo/ChangeMethodContractCheck.java @@ -28,6 +28,7 @@ void argAnnotatedNonNull(@javax.annotation.Nonnull Object a, @javax.annotation.N @javax.annotation.CheckForNull String annotatedStrongNullable(Object a) { return null; } @javax.annotation.Nonnull +//^^^^^^^^^^^^^^^^^^^^^^^^^> String annotatedNonNull(Object a) { return ""; } } @@ -75,7 +76,9 @@ void argAnnotatedNonNull(@javax.annotation.Nonnull Object a, @javax.validation.c String annotatedWeakNullable(Object a) { return ""; } // Compliant: Weak Nullable to Nonnull @Deprecated @javax.annotation.Nullable - String annotatedNonNull(Object a) { return null; } // Noncompliant [[sc=3;ec=9;secondary=-1,30]] {{Fix the incompatibility of the annotation @Nullable to honor @Nonnull of the overridden method.}} +//^^^^^^^^^^^^^^^^^^^^^^^^^^> + String annotatedNonNull(Object a) { return null; } // Noncompliant {{Fix the incompatibility of the annotation @Nullable to honor @Nonnull of the overridden method.}} +//^^^^^^ public boolean equals(@javax.annotation.Nonnull Object o) { return false; } // Compliant, handled by by S4454. } @@ -90,6 +93,7 @@ class ChangeMethodContractCheck_WithMetaAnnotations { } @javax.annotation.CheckForNull +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^> public @interface MyCheckFroNullMetaAnnotation { } @@ -105,10 +109,17 @@ void argAnnotatedDirectlyNullable(@javax.annotation.CheckForNull Object a) { } String annotatedNonnullViaMetaAnnotation2(Object a) { return "null"; } @javax.annotation.Nonnull +// ^^^^^^^^^^^^^^^^^^^^^^^^^> String annotatedNonnullDirectly(Object a) { return "null"; } } class Child extends Parent { + @Override + // Parent directly annotated but Child with meta-annotations. + @MyCheckFroNullMetaAnnotation + String annotatedNonnullDirectly(Object a) { return "null"; } // Noncompliant {{Fix the incompatibility of the annotation @CheckForNull via meta-annotation to honor @Nonnull of the overridden method.}} + //^^^^^^ + // Parent and Child with meta-annotation. void argAnnotatedNullableViaMetaAnnotation(@MyNonnullMetaAnnotation Object a) { } // Noncompliant {{Fix the incompatibility of the annotation @Nonnull via meta-annotation to honor @CheckForNull via meta-annotation of the overridden method.}} // Parent with meta-annotation, then Child annotated directly works @@ -124,11 +135,6 @@ void argAnnotatedDirectlyNullable(@MyNonnullMetaAnnotation Object a) { } // Nonc // Parent with meta-annotation, then child annotated directly works @javax.annotation.CheckForNull String annotatedNonnullViaMetaAnnotation2(Object a) { return "null"; } // Noncompliant {{Fix the incompatibility of the annotation @CheckForNull to honor @Nonnull via meta-annotation of the overridden method.}} - - @Override - // Parent directly annotated but Child with meta-annotations. - @MyCheckFroNullMetaAnnotation - String annotatedNonnullDirectly(Object a) { return "null"; } // Noncompliant [[secondary=92,107]] {{Fix the incompatibility of the annotation @CheckForNull via meta-annotation to honor @Nonnull of the overridden method.}} } } @@ -207,7 +213,8 @@ class ImplementsFunction implements com.google.common.base.Function class ChangeMethodContractCheckAtClassLevel { void argAnnotatedNonNullViaClassAnnotation(Object a) { } } class ChangeMethodContractCheckAtClassLevel_Child extends ChangeMethodContractCheckAtClassLevel { @javax.annotation.Nullable +//^^^^^^^^^^^^^^^^^^^^^^^^^^> @Override - void argAnnotatedNonNullViaClassAnnotation(Object a) { } // Noncompliant [[secondary=-2,-8]] {{Fix the incompatibility of the annotation @Nullable to honor @NonNullByDefault at class level of the overridden method.}} + void argAnnotatedNonNullViaClassAnnotation(Object a) { } // Noncompliant {{Fix the incompatibility of the annotation @Nullable to honor @NonNullByDefault at class level of the overridden method.}} +//^^^^ } diff --git a/java-checks-test-sources/default/src/main/java/checks/S2638_ChangeMethodContractCheck/nullableApi/ChangeMethodContractCheck.java b/java-checks-test-sources/default/src/main/java/checks/S2638_ChangeMethodContractCheck/nullableApi/ChangeMethodContractCheck.java index 47d44959b33..ded618ce55d 100644 --- a/java-checks-test-sources/default/src/main/java/checks/S2638_ChangeMethodContractCheck/nullableApi/ChangeMethodContractCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/S2638_ChangeMethodContractCheck/nullableApi/ChangeMethodContractCheck.java @@ -11,16 +11,18 @@ void argAnnotatedNonNull(@Nonnull Object a) { } class ChangeMethodContractCheck_Child extends ChangeMethodContractCheck { @Override - void nullableArguments(@javax.annotation.Nonnull Object a) { } // Noncompliant [[sc=59;ec=60;secondary=+0]] {{Fix the incompatibility of the annotation @Nonnull to honor @ParametersAreNullableByDefault at package level of the overridden method.}} - + void nullableArguments(@javax.annotation.Nonnull Object a) { } // Noncompliant {{Fix the incompatibility of the annotation @Nonnull to honor @ParametersAreNullableByDefault at package level of the overridden method.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^> ^ 1 @Override void argAnnotatedNonNull(Object a) { } // Nonnull to Nullable is compliant } -@ParametersAreNonnullByDefault + @ParametersAreNonnullByDefault +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^> class ChangeMethodContractCheck_Child_Annotated extends ChangeMethodContractCheck { @Override - void nullableArguments(Object a) { } // Noncompliant [[secondary=-3]] {{Fix the incompatibility of the annotation @ParametersAreNonnullByDefault at class level to honor @ParametersAreNullableByDefault at package level of the overridden method.}} + void nullableArguments(Object a) { } // Noncompliant {{Fix the incompatibility of the annotation @ParametersAreNonnullByDefault at class level to honor @ParametersAreNullableByDefault at package level of the overridden method.}} +// ^ @Override void argAnnotatedNonNull(Object a) { } // Compliant: Nonnull to Nonnull diff --git a/java-checks-test-sources/default/src/main/java/checks/S3749_SpringComponentWithNonAutowiredMembersCheck/S3749_CustomAnnotations.java b/java-checks-test-sources/default/src/main/java/checks/S3749_SpringComponentWithNonAutowiredMembersCheck/S3749_CustomAnnotations.java index 7b86b988ae2..53e4da4fc26 100644 --- a/java-checks-test-sources/default/src/main/java/checks/S3749_SpringComponentWithNonAutowiredMembersCheck/S3749_CustomAnnotations.java +++ b/java-checks-test-sources/default/src/main/java/checks/S3749_SpringComponentWithNonAutowiredMembersCheck/S3749_CustomAnnotations.java @@ -27,7 +27,7 @@ public class S3749_CustomAnnotations { class ConstructorInjection { private String env; // Compliant private String yyyAdaptor; // Compliant - private String jaxbContext; // Noncompliant - not used in @Autowired constructor + private String jaxbContext; // Noncompliant @S3749_CustomAnnotations.MyInjectionAnnotation public ConstructorInjection(String env, String yyyAdaptor, diff --git a/java-checks-test-sources/default/src/main/java/checks/S3749_SpringComponentWithNonAutowiredMembersCheck/S3749_DefaultAnnotations.java b/java-checks-test-sources/default/src/main/java/checks/S3749_SpringComponentWithNonAutowiredMembersCheck/S3749_DefaultAnnotations.java index 2691b124567..c6efb36f66a 100644 --- a/java-checks-test-sources/default/src/main/java/checks/S3749_SpringComponentWithNonAutowiredMembersCheck/S3749_DefaultAnnotations.java +++ b/java-checks-test-sources/default/src/main/java/checks/S3749_SpringComponentWithNonAutowiredMembersCheck/S3749_DefaultAnnotations.java @@ -21,9 +21,12 @@ @Controller public class S3749_DefaultAnnotations { - private String name = null; // Noncompliant [[sc=18;ec=22]] {{Annotate this member with "@Autowired", "@Resource", "@Inject", or "@Value", or remove it.}} - public String address = null; // Noncompliant [[sc=17;ec=24]] {{Annotate this member with "@Autowired", "@Resource", "@Inject", or "@Value", or remove it.}} - String phone = null; // Noncompliant [[sc=10;ec=15]] {{Annotate this member with "@Autowired", "@Resource", "@Inject", or "@Value", or remove it.}} + private String name = null; // Noncompliant {{Annotate this member with "@Autowired", "@Resource", "@Inject", or "@Value", or remove it.}} +// ^^^^ + public String address = null; // Noncompliant {{Annotate this member with "@Autowired", "@Resource", "@Inject", or "@Value", or remove it.}} +// ^^^^^^^ + String phone = null; // Noncompliant {{Annotate this member with "@Autowired", "@Resource", "@Inject", or "@Value", or remove it.}} +// ^^^^^ @Autowired String email = null; // Compliant @@ -43,12 +46,14 @@ void someMethod(){} @Service class ServiceHelloWorld { - protected String name = null; // Noncompliant [[sc=20;ec=24]] {{Annotate this member with "@Autowired", "@Resource", "@Inject", or "@Value", or remove it.}} + protected String name = null; // Noncompliant {{Annotate this member with "@Autowired", "@Resource", "@Inject", or "@Value", or remove it.}} +// ^^^^ } @Repository class RepositoryHelloWorld { - protected String name = null; // Noncompliant [[sc=20;ec=24]] {{Annotate this member with "@Autowired", "@Resource", "@Inject", or "@Value", or remove it.}} + protected String name = null; // Noncompliant {{Annotate this member with "@Autowired", "@Resource", "@Inject", or "@Value", or remove it.}} +// ^^^^ } @RestController @@ -64,7 +69,8 @@ class RepositoryHelloWorld_Scoped { @Component class ComponentHelloWorld { - protected String name = null; // Noncompliant [[sc=20;ec=24]] {{Annotate this member with "@Autowired", "@Resource", "@Inject", or "@Value", or remove it.}} + protected String name = null; // Noncompliant {{Annotate this member with "@Autowired", "@Resource", "@Inject", or "@Value", or remove it.}} +// ^^^^ } @Scope("singleton") @@ -143,7 +149,7 @@ public DualConstructor(String name, String address) { class ConstructorInjection1 { private String env; // Compliant private String yyyAdaptor; // Compliant - private String jaxbContext; // Noncompliant - not used in @Autowired constructor + private String jaxbContext; // Noncompliant public ConstructorInjection1(String env, String yyyAdaptor, String jaxbContext) { this.env = env; diff --git a/java-checks-test-sources/default/src/main/java/checks/SQLInjection.java b/java-checks-test-sources/default/src/main/java/checks/SQLInjection.java index 321673e321c..43be49c99b3 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SQLInjection.java +++ b/java-checks-test-sources/default/src/main/java/checks/SQLInjection.java @@ -23,7 +23,7 @@ public void method(String param, String param2, EntityManager entityManager) { Connection conn = DriverManager.getConnection("url", "user1", "password"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT Lname FROM Customers WHERE Snum = 2001"); - rs = stmt.executeQuery("SELECT Lname FROM Customers WHERE Snum = "+param); // Noncompliant [[sc=30;ec=79]] {{Make sure using a dynamically formatted SQL query is safe here.}} + rs = stmt.executeQuery("SELECT Lname FROM Customers WHERE Snum = "+param); // Noncompliant {{Make sure using a dynamically formatted SQL query is safe here.}} [[sc=30;ec=79]] String query = "SELECT Lname FROM Customers WHERE Snum = "+param; rs = stmt.executeQuery(query); // Noncompliant @@ -118,15 +118,18 @@ void falseNegative(String param) throws SQLException { String s3; s3 = "SELECT"; s3 += param; - conn.prepareStatement(s3); // Noncompliant, true positive + conn.prepareStatement(s3); // Noncompliant } void testSecondaryLocations(String param) throws SQLException { Connection conn = DriverManager.getConnection("url", "user1", "password"); String query1 = "SELECT"; // secondary location + // ^^^^^^^^> query1 += param; // secondary location - conn.prepareStatement(query1); // Noncompliant [[secondary=128,127]]] + // ^^^^^> + conn.prepareStatement(query1); // Noncompliant + // ^^^^^^ boolean bool = false; diff --git a/java-checks-test-sources/default/src/main/java/checks/ScheduledThreadPoolExecutorZeroCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ScheduledThreadPoolExecutorZeroCheckSample.java index 5541daf81c3..05120d1a010 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ScheduledThreadPoolExecutorZeroCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ScheduledThreadPoolExecutorZeroCheckSample.java @@ -5,9 +5,11 @@ class ScheduledThreadPoolExecutorZeroCheckSample { private static final int POOL_SIZE = 42; public void foo() { - ScheduledThreadPoolExecutor stpe1 = new ScheduledThreadPoolExecutor(0); // Noncompliant [[sc=73;ec=74]] {{Increase the "corePoolSize".}} + ScheduledThreadPoolExecutor stpe1 = new ScheduledThreadPoolExecutor(0); // Noncompliant {{Increase the "corePoolSize".}} +// ^ ScheduledThreadPoolExecutor stpe2 = new ScheduledThreadPoolExecutor(POOL_SIZE); - stpe2.setCorePoolSize(0); // Noncompliant [[sc=27;ec=28]] {{Increase the "corePoolSize".}} + stpe2.setCorePoolSize(0); // Noncompliant {{Increase the "corePoolSize".}} +// ^ stpe2.setCorePoolSize(12); // Compliant } } diff --git a/java-checks-test-sources/default/src/main/java/checks/SelfAssignementCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/SelfAssignementCheckSample.java index b5a3e7e785b..1e9310b409d 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SelfAssignementCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/SelfAssignementCheckSample.java @@ -4,15 +4,17 @@ class SelfAssignementCheckSample { static int staticField = 0; static { - staticField = staticField; // Noncompliant + staticField = staticField; // Noncompliant } int a, c = 0; int[] b = {0}; - int m = a = a; // Noncompliant [[sc=13;ec=14;quickfixes=!]] + int m = a = a; // Noncompliant [[quickfixes=!]] +// ^ - int x = a = a = a; // Noncompliant [[sc=17;ec=18;quickfixes=!]] + int x = a = a = a; // Noncompliant [[quickfixes=!]] +// ^ int s = getS(); // Compliant @@ -21,9 +23,11 @@ int getS() { } void method() { - a = a; // Noncompliant [[sc=7;ec=8]] {{Remove or correct this useless self-assignment.}} + a = a; // Noncompliant {{Remove or correct this useless self-assignment.}} +// ^ this.a = this.a; // Noncompliant - this.a = a; // Noncompliant [[sc=12;ec=13]] {{Remove or correct this useless self-assignment.}} + this.a = a; // Noncompliant {{Remove or correct this useless self-assignment.}} +// ^ b[0] = b[0]; // Noncompliant a = c = c; // Noncompliant b[fun()] = b[fun()]; // Noncompliant @@ -63,7 +67,8 @@ class SelfAssignmentCheckC { String a; public SelfAssignmentCheckC(String a) { - a = a; // Noncompliant [[sc=7;ec=8;quickfixes=qf1]] {{Remove or correct this useless self-assignment.}} + a = a; // Noncompliant {{Remove or correct this useless self-assignment.}} [[quickfixes=qf1]] +// ^ // fix@qf1 {{Disambiguate this self-assignment}} // edit@qf1 [[sc=5;ec=5]] {{this.}} } @@ -76,19 +81,23 @@ class SelfAssignmentCheckD { String c; public SelfAssignmentCheckD(String a, String b, String d) { - a = a; // Noncompliant [[sc=7;ec=8;quickfixes=qf2]] {{Remove or correct this useless self-assignment.}} + a = a; // Noncompliant {{Remove or correct this useless self-assignment.}} [[quickfixes=qf2]] +// ^ // fix@qf2 {{Disambiguate this self-assignment}} // edit@qf2 [[sc=5;ec=5]] {{this.}} - c = c; // Noncompliant [[sc=7;ec=8;quickfixes=qf3]] {{Remove or correct this useless self-assignment.}} + c = c; // Noncompliant {{Remove or correct this useless self-assignment.}} [[quickfixes=qf3]] +// ^ // fix@qf3 {{Remove this useless self-assignment}} // edit@qf3 [[sc=5;ec=11]] {{}} - this.c = c; // Noncompliant [[sc=12;ec=13;quickfixes=qf4]] {{Remove or correct this useless self-assignment.}} + this.c = c; // Noncompliant {{Remove or correct this useless self-assignment.}} [[quickfixes=qf4]] +// ^ // fix@qf4 {{Remove this useless self-assignment}} // edit@qf4 [[sc=5;ec=16]] {{}} - d = d; // Noncompliant [[sc=7;ec=8;quickfixes=qf5]] {{Remove or correct this useless self-assignment.}} + d = d; // Noncompliant {{Remove or correct this useless self-assignment.}} [[quickfixes=qf5]] +// ^ // fix@qf5 {{Remove this useless self-assignment}} // edit@qf5 [[sc=5;ec=11]] {{}} diff --git a/java-checks-test-sources/default/src/main/java/checks/ServletInstanceFieldCheckJakarta.java b/java-checks-test-sources/default/src/main/java/checks/ServletInstanceFieldCheckJakarta.java index 3806ed8cbdb..f702fabd48d 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ServletInstanceFieldCheckJakarta.java +++ b/java-checks-test-sources/default/src/main/java/checks/ServletInstanceFieldCheckJakarta.java @@ -10,7 +10,8 @@ class HttpServletAJakarta { } class HttpServletBJakarta extends HttpServlet { - private String userName; // Noncompliant [[sc=18;ec=26]] {{Remove this misleading mutable servlet instance field or make it "static" and/or "final"}} + private String userName; // Noncompliant {{Remove this misleading mutable servlet instance field or make it "static" and/or "final"}} +// ^^^^^^^^ private static String staticVar; private final String finalVar; private String storageType; @@ -56,11 +57,12 @@ class HttpServletDJakarta extends HttpServlet { public class ServletInstanceFieldCheckJakarta extends HttpServlet { @org.springframework.beans.factory.annotation.Autowired - private javax.sql.DataSource myDB; // Noncompliant - filtered by the SpringFilter + private javax.sql.DataSource myDB; // Noncompliant } class HttpServletEJakarta extends HttpServlet { - private String userName; // Noncompliant [[sc=18;ec=26]] {{Remove this misleading mutable servlet instance field or make it "static" and/or "final"}} + private String userName; // Noncompliant {{Remove this misleading mutable servlet instance field or make it "static" and/or "final"}} +// ^^^^^^^^ private final String finalVar; private String storageType; // Compliant, initialized in init() method diff --git a/java-checks-test-sources/default/src/main/java/checks/ServletInstanceFieldCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ServletInstanceFieldCheckSample.java index 0a032a46b40..f93d086815b 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ServletInstanceFieldCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ServletInstanceFieldCheckSample.java @@ -12,7 +12,8 @@ class HttpServletA { } class HttpServletB extends HttpServlet { - private String userName; // Noncompliant [[sc=18;ec=26]] {{Remove this misleading mutable servlet instance field or make it "static" and/or "final"}} + private String userName; // Noncompliant {{Remove this misleading mutable servlet instance field or make it "static" and/or "final"}} +// ^^^^^^^^ private static String staticVar; private final String finalVar; private String storageType; @@ -58,11 +59,12 @@ class HttpServletD extends HttpServlet { public class ServletInstanceFieldCheckSample extends HttpServlet { @org.springframework.beans.factory.annotation.Autowired - private javax.sql.DataSource myDB; // Noncompliant - filtered by the SpringFilter + private javax.sql.DataSource myDB; // Noncompliant } class HttpServletE extends HttpServlet { - private String userName; // Noncompliant [[sc=18;ec=26]] {{Remove this misleading mutable servlet instance field or make it "static" and/or "final"}} + private String userName; // Noncompliant {{Remove this misleading mutable servlet instance field or make it "static" and/or "final"}} +// ^^^^^^^^ private final String finalVar; private String storageType; // Compliant, initialized in init() method diff --git a/java-checks-test-sources/default/src/main/java/checks/ServletMethodsExceptionsThrownCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ServletMethodsExceptionsThrownCheckSample.java index 4748fd08e5c..b6f0c1465c2 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ServletMethodsExceptionsThrownCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ServletMethodsExceptionsThrownCheckSample.java @@ -16,11 +16,13 @@ class ServletMethodsExceptionsThrownCheckSample extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String ip = request.getRemoteAddr(); - InetAddress addr = InetAddress.getByName(ip); // Noncompliant [[sc=36;ec=45]] {{Handle the following exception that could be thrown by "getByName": UnknownHostException.}} + InetAddress addr = InetAddress.getByName(ip); // Noncompliant {{Handle the following exception that could be thrown by "getByName": UnknownHostException.}} +// ^^^^^^^^^ try { addr = InetAddress.getByName(ip); } catch (IllegalArgumentException e) { - throw e; // Noncompliant [[sc=7;ec=15]] {{Handle the "IllegalArgumentException" thrown here in a "try/catch" block.}} + throw e; // Noncompliant {{Handle the "IllegalArgumentException" thrown here in a "try/catch" block.}} +// ^^^^^^^^ } catch (Exception e) { throw e; // Noncompliant {{Handle the "Exception" thrown here in a "try/catch" block.}} } @@ -41,7 +43,8 @@ public void bar(HttpServletRequest request, HttpServletResponse response) throws protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { - foo(request, response); // Noncompliant [[sc=7;ec=10]] {{Handle the following exceptions that could be thrown by "foo": IOException, ServletException.}} + foo(request, response); // Noncompliant {{Handle the following exceptions that could be thrown by "foo": IOException, ServletException.}} +// ^^^ } catch (NamingException ne) { throw new ServletException(ne); // Noncompliant {{Handle the "ServletException" thrown here in a "try/catch" block.}} } @@ -57,11 +60,13 @@ class JakartaServletMethodsExceptionsThrownCheckSample extends jakarta.servlet.h public void doGet(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response) throws IOException { String ip = request.getRemoteAddr(); - InetAddress addr = InetAddress.getByName(ip); // Noncompliant [[sc=36;ec=45]] {{Handle the following exception that could be thrown by "getByName": UnknownHostException.}} + InetAddress addr = InetAddress.getByName(ip); // Noncompliant {{Handle the following exception that could be thrown by "getByName": UnknownHostException.}} +// ^^^^^^^^^ try { addr = InetAddress.getByName(ip); } catch (IllegalArgumentException e) { - throw e; // Noncompliant [[sc=7;ec=15]] {{Handle the "IllegalArgumentException" thrown here in a "try/catch" block.}} + throw e; // Noncompliant {{Handle the "IllegalArgumentException" thrown here in a "try/catch" block.}} +// ^^^^^^^^ } catch (Exception e) { throw e; // Noncompliant {{Handle the "Exception" thrown here in a "try/catch" block.}} } @@ -82,7 +87,8 @@ public void bar(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet protected void doPut(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response) throws jakarta.servlet.ServletException, IOException { try { - foo(request, response); // Noncompliant [[sc=7;ec=10]] {{Handle the following exceptions that could be thrown by "foo": IOException, ServletException.}} + foo(request, response); // Noncompliant {{Handle the following exceptions that could be thrown by "foo": IOException, ServletException.}} +// ^^^ } catch (NamingException ne) { throw new jakarta.servlet.ServletException(ne); // Noncompliant {{Handle the "ServletException" thrown here in a "try/catch" block.}} } diff --git a/java-checks-test-sources/default/src/main/java/checks/ShiftOnIntOrLongCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ShiftOnIntOrLongCheckSample.java index eec52a9d23a..7e16baa7c6d 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ShiftOnIntOrLongCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ShiftOnIntOrLongCheckSample.java @@ -14,7 +14,8 @@ public int shift(int a) { b = a << 31; b = a >> -31; b = a << 32; // Noncompliant {{Remove this useless shift}} - b = a >> -32; // Noncompliant [[sc=11;ec=13]] {{Remove this useless shift}} + b = a >> -32; // Noncompliant {{Remove this useless shift}} +// ^^ b = a << 33; // Noncompliant {{Either make "a" a "long" or correct this shift to 1}} b = a >> -33; // Noncompliant {{Either make "a" a "long" or correct this shift to -1}} @@ -41,7 +42,8 @@ public long shift(long a) { a >>= 64; // Noncompliant a <<= -64; // Noncompliant a >>= 65; // Noncompliant - a <<= -65; // Noncompliant [[sc=7;ec=10]] + a <<= -65; // Noncompliant +// ^^^ return b >> +96; // Noncompliant } @@ -106,12 +108,12 @@ public long returnLong() { void aligned(byte b1, byte b2) { b1 = (byte) (value >> 8); b2 = (byte) (value >> 0); // Compliant - b2 = (byte) (value << 0); // Noncompliant - another type of shift + b2 = (byte) (value << 0); // Noncompliant System.out.println(); - b2 = (byte) (value >> 0); // Noncompliant - aligned but interrupted + b2 = (byte) (value >> 0); // Noncompliant System.out.println(); System.out.println(); - b2 = (byte) (value >> 0); // Noncompliant - aligned but interrupted - b2 = (byte) (value >> 0); // Noncompliant - aligned but interrupted + b2 = (byte) (value >> 0); // Noncompliant + b2 = (byte) (value >> 0); // Noncompliant } } diff --git a/java-checks-test-sources/default/src/main/java/checks/SillyEqualsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/SillyEqualsCheckSample.java index 527698b0cf2..ab57c574fd4 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SillyEqualsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/SillyEqualsCheckSample.java @@ -34,7 +34,8 @@ public void method() { // class vs array object.equals(arrayOfObjects); // Compliant arrayOfObjects.equals(object); // Compliant - integer.equals(arrayOfObjects); // Noncompliant [[sc=13;ec=19]] {{Remove this call to "equals"; comparisons between a type and an array always return false.}} + integer.equals(arrayOfObjects); // Noncompliant {{Remove this call to "equals"; comparisons between a type and an array always return false.}} +// ^^^^^^ arrayOfObjects.equals(integer); // Noncompliant {{Remove this call to "equals"; comparisons between an array and a type always return false.}} arrayOfIntegers.equals(arrayOfStrings); // Noncompliant {{Remove this call to "equals"; comparisons between unrelated arrays always return false.}} object.equals(1); // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/SillyStringOperationsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/SillyStringOperationsCheckSample.java index 2bfb4bf3f6a..795eef84889 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SillyStringOperationsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/SillyStringOperationsCheckSample.java @@ -4,76 +4,76 @@ class SillyStringOperationsCheckSample { void f(String str, String other, int from, int to) { "".contains("str"); - "".contains(""); // Noncompliant {{Remove this "contains" call; it has predictable results.}} - str.contains(str); // Noncompliant + "".contains(""); // Noncompliant {{Remove this "contains" call; it has predictable results.}} + str.contains(str); // Noncompliant str.contains(other); "".compareTo("str"); - "".compareTo(""); // Noncompliant {{Remove this "compareTo" call; it has predictable results.}} - str.compareTo(str); // Noncompliant + "".compareTo(""); // Noncompliant {{Remove this "compareTo" call; it has predictable results.}} + str.compareTo(str); // Noncompliant str.compareTo(other); "".compareToIgnoreCase("str"); - "".compareToIgnoreCase(""); // Noncompliant {{Remove this "compareToIgnoreCase" call; it has predictable results.}} - str.compareToIgnoreCase(str); // Noncompliant + "".compareToIgnoreCase(""); // Noncompliant {{Remove this "compareToIgnoreCase" call; it has predictable results.}} + str.compareToIgnoreCase(str); // Noncompliant str.compareToIgnoreCase(other); "".endsWith("str"); - "".endsWith(""); // Noncompliant {{Remove this "endsWith" call; it has predictable results.}} - str.endsWith(str); // Noncompliant + "".endsWith(""); // Noncompliant {{Remove this "endsWith" call; it has predictable results.}} + str.endsWith(str); // Noncompliant str.endsWith(other); "".indexOf("str"); - "".indexOf(""); // Noncompliant {{Remove this "indexOf" call; it has predictable results.}} - str.indexOf(str); // Noncompliant + "".indexOf(""); // Noncompliant {{Remove this "indexOf" call; it has predictable results.}} + str.indexOf(str); // Noncompliant str.indexOf(other); "".indexOf("str", from); - "".indexOf("", from); // Noncompliant {{Remove this "indexOf" call; it has predictable results.}} - str.indexOf(str, from); // Noncompliant + "".indexOf("", from); // Noncompliant {{Remove this "indexOf" call; it has predictable results.}} + str.indexOf(str, from); // Noncompliant str.indexOf(other, from); "".lastIndexOf("str"); - "".lastIndexOf(""); // Noncompliant {{Remove this "lastIndexOf" call; it has predictable results.}} - str.lastIndexOf(str); // Noncompliant + "".lastIndexOf(""); // Noncompliant {{Remove this "lastIndexOf" call; it has predictable results.}} + str.lastIndexOf(str); // Noncompliant str.lastIndexOf(other); "".lastIndexOf("str", from); - "".lastIndexOf("", from); // Noncompliant {{Remove this "lastIndexOf" call; it has predictable results.}} - str.lastIndexOf(str, from); // Noncompliant + "".lastIndexOf("", from); // Noncompliant {{Remove this "lastIndexOf" call; it has predictable results.}} + str.lastIndexOf(str, from); // Noncompliant str.lastIndexOf(other, from); "".matches("str"); - "".matches(""); // Noncompliant {{Remove this "matches" call; it has predictable results.}} - str.matches(str); // Noncompliant + "".matches(""); // Noncompliant {{Remove this "matches" call; it has predictable results.}} + str.matches(str); // Noncompliant str.matches(other); "".split("str"); - "".split(""); // Noncompliant {{Remove this "split" call; it has predictable results.}} - str.split(str); // Noncompliant + "".split(""); // Noncompliant {{Remove this "split" call; it has predictable results.}} + str.split(str); // Noncompliant str.split(other); "".startsWith("str"); - "".startsWith(""); // Noncompliant {{Remove this "startsWith" call; it has predictable results.}} - str.startsWith(str); // Noncompliant + "".startsWith(""); // Noncompliant {{Remove this "startsWith" call; it has predictable results.}} + str.startsWith(str); // Noncompliant str.startsWith(other); "".replaceFirst("str", ""); - "".replaceFirst("", "str"); // Noncompliant {{Remove this "replaceFirst" call; it has predictable results.}} - "".replaceFirst("str", "str"); // Noncompliant - "".replaceFirst(other, other); // Noncompliant + "".replaceFirst("", "str"); // Noncompliant {{Remove this "replaceFirst" call; it has predictable results.}} + "".replaceFirst("str", "str"); // Noncompliant + "".replaceFirst(other, other); // Noncompliant "".replaceFirst("str", ""); - str.replaceFirst(str, "str"); // Noncompliant + str.replaceFirst(str, "str"); // Noncompliant str.replaceFirst("str", "str"); // Noncompliant str.replaceFirst(other, other); // Noncompliant - "".substring(0); // Noncompliant {{Remove this "substring" call; it has predictable results.}} + "".substring(0); // Noncompliant {{Remove this "substring" call; it has predictable results.}} "".substring(from); "".substring("".length()); "".substring(other.length()); - str.substring(0); // Noncompliant + str.substring(0); // Noncompliant str.substring(from); - str.substring(str.length()); // Noncompliant + str.substring(str.length()); // Noncompliant str.substring(other.length()); "".substring(0, "".length()); @@ -81,10 +81,10 @@ void f(String str, String other, int from, int to) { "".substring(1, to); "".substring("".length(), to); "".substring(from, "".length()); - str.substring(0, str.length()); // Noncompliant {{Remove this "substring" call; it has predictable results.}} + str.substring(0, str.length()); // Noncompliant {{Remove this "substring" call; it has predictable results.}} str.substring(0, other.length()); str.substring(1, to); - str.substring(str.length(), to); // Noncompliant + str.substring(str.length(), to); // Noncompliant str.substring(from, str.length()); } } diff --git a/java-checks-test-sources/default/src/main/java/checks/SimpleClassNameCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/SimpleClassNameCheckSample.java index ac925fc38a7..a1161f328a2 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SimpleClassNameCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/SimpleClassNameCheckSample.java @@ -9,18 +9,18 @@ class SimpleClass { void notWildcardImport() { - com.google.common.collect.ImmutableList list; // Noncompliant - com.google.common.collect.ImmutableList.Builder builder = // Noncompliant [[startColumn=5;endColumn=44]] + com.google.common.collect.ImmutableList list; // Noncompliant + com.google.common.collect.ImmutableList.Builder builder = // Noncompliant com.google.common.collect.ImmutableList.builder(); // Noncompliant {{Replace this fully qualified name with "ImmutableList"}} - System.out.println(com.google.common.collect.ImmutableList.class); // Noncompliant [[startColumn=24;endColumn=63]] + System.out.println(com.google.common.collect.ImmutableList.class); // Noncompliant ImmutableList.builder(); ImmutableList anotherList; } void wildcardImport() { - java.util.List myList = // Noncompliant {{Replace this fully qualified name with "List"}} - new java.util.ArrayList(); // Noncompliant [[startColumn=11;endColumn=30]] + java.util.List myList = // Noncompliant {{Replace this fully qualified name with "List"}} + new java.util.ArrayList(); // Noncompliant List myList2 = // Compliant new ArrayList(); diff --git a/java-checks-test-sources/default/src/main/java/checks/SimpleStringLiteralForSingleLineStringsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/SimpleStringLiteralForSingleLineStringsCheckSample.java index 8c40d3d60cb..4c08a6949bd 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SimpleStringLiteralForSingleLineStringsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/SimpleStringLiteralForSingleLineStringsCheckSample.java @@ -2,7 +2,7 @@ public class SimpleStringLiteralForSingleLineStringsCheckSample { - public void str() { // Noncompliant@+1 [[sc=23;endColumn=43]]{{Use simple literal for a single-line string.}} + public void str() { // Noncompliant@+1 {{Use simple literal for a single-line string.}} String question = """ What's the point, really?"""; @@ -13,7 +13,7 @@ public class SimpleStringLiteralForSingleLineStringsCheckSample { ?"""; // Compliant, 3 lines String question3 = """ - What's the point, really\n?"""; // Noncompliant@-1 [[sc=24;endColumn=45]]{{Use simple literal for a single-line string.}} + What's the point, really\n?"""; // Noncompliant@-1 {{Use simple literal for a single-line string.}} } } diff --git a/java-checks-test-sources/default/src/main/java/checks/SingleIfInsteadOfPatternMatchGuardCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/SingleIfInsteadOfPatternMatchGuardCheckSample.java index bbb28c285a4..4932b343a07 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SingleIfInsteadOfPatternMatchGuardCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/SingleIfInsteadOfPatternMatchGuardCheckSample.java @@ -8,7 +8,7 @@ public class SingleIfInsteadOfPatternMatchGuardCheckSample { void conditionsShouldBeMerged(Object o) { switch (o) { case String s when s.startsWith("a") -> { - // Noncompliant@+1 [[sl=+1;el=+3;sc=9;ec=10;quickfixes=qf3]] {{Merge this "if" statement with the enclosing pattern match guard.}} + // Noncompliant@+1 [[quickfixes=qf3]] if (s.length() == 2) { System.out.println("two"); } @@ -17,7 +17,6 @@ void conditionsShouldBeMerged(Object o) { } } } - // fix@qf1 {{Replace this "if" statement with a pattern match guard.}} // edit@qf1 [[sl=+0;el=+0;sc=9;ec=32]] {{{}}} // edit@qf1 [[sl=-2;el=-2;sc=21;ec=21]] {{ when s.length() == 2 }} @@ -94,7 +93,7 @@ void foo(Object o) { case Integer i -> { } case String s -> { - if (s.length() == 2) { // Noncompliant {Replace this "if" statement with a pattern match guard.} + if (s.length() == 2) { // Noncompliant {{Replace this "if" statement with a pattern match guard.}} System.out.println("two"); } } diff --git a/java-checks-test-sources/default/src/main/java/checks/SingletonUsageCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/SingletonUsageCheckSample.java index 0a28f99e6c5..392f8c184f5 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SingletonUsageCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/SingletonUsageCheckSample.java @@ -5,12 +5,15 @@ // TODO: check code snippet license public class SingletonUsageCheckSample { - public static class EagerInitializedSingleton { // Noncompliant [[sc=23;ec=48;secondary=+2,+5]] {{A Singleton implementation was detected. Make sure the use of the Singleton pattern is required and the implementation is the right one for the context.}} + public static class EagerInitializedSingleton { // Noncompliant {{A Singleton implementation was detected. Make sure the use of the Singleton pattern is required and the implementation is the right one for the context.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^ private static final EagerInitializedSingleton instance = new EagerInitializedSingleton(); +// ^^^^^^^^< // private constructor to avoid client applications using the constructor private EagerInitializedSingleton(){} +// ^^^^^^^^^^^^^^^^^^^^^^^^^< public static EagerInitializedSingleton getInstance() { return instance; @@ -21,16 +24,20 @@ public boolean foo() { } } - public static class StaticBlockSingleton { // Noncompliant [[sc=23;ec=43;secondary=+2,+4,+9]] + public static class StaticBlockSingleton { // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^ private static StaticBlockSingleton instance; +// ^^^^^^^^< private StaticBlockSingleton(){} +// ^^^^^^^^^^^^^^^^^^^^< // static block initialization for exception handling static { try { instance = new StaticBlockSingleton(); +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< } catch (Exception e) { throw new RuntimeException("Exception occurred in creating singleton instance"); } @@ -99,7 +106,8 @@ public boolean foo() { } } - public enum EnumSingleton { // Noncompliant [[sc=15;ec=28]] {{An Enum-based Singleton implementation was detected. Make sure the use of the Singleton pattern is required and an Enum-based implementation is the right one for the context.}} + public enum EnumSingleton { // Noncompliant {{An Enum-based Singleton implementation was detected. Make sure the use of the Singleton pattern is required and an Enum-based implementation is the right one for the context.}} +// ^^^^^^^^^^^^^ INSTANCE; diff --git a/java-checks-test-sources/default/src/main/java/checks/SpecializedFunctionalInterfacesCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/SpecializedFunctionalInterfacesCheckSample.java index 1376447ab34..0e2f5b6e23b 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SpecializedFunctionalInterfacesCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/SpecializedFunctionalInterfacesCheckSample.java @@ -20,7 +20,8 @@ public class SpecializedFunctionalInterfacesCheckSample { - static class A implements Supplier { // Noncompliant [[sc=16;ec=17]] {{Refactor this code to use the more specialised Functional Interface 'IntSupplier'}} + static class A implements Supplier { // Noncompliant {{Refactor this code to use the more specialised Functional Interface 'IntSupplier'}} +// ^ @Override public Integer get() { return null; @@ -28,12 +29,14 @@ public Integer get() { static class AA implements Consumer { // Noncompliant - Consumer a1 = new Consumer() { // Noncompliant [[sc=7;ec=24]] {{Refactor this code to use the more specialised Functional Interface 'IntConsumer'}} + Consumer a1 = new Consumer() { // Noncompliant {{Refactor this code to use the more specialised Functional Interface 'IntConsumer'}} +// ^^^^^^^^^^^^^^^^^ @Override public void accept(Integer t) { } }; - Consumer a2 = new Consumer() { // Noncompliant [[sc=7;ec=23]] {{Refactor this code to use the more specialised Functional Interface 'DoubleConsumer'}} + Consumer a2 = new Consumer() { // Noncompliant {{Refactor this code to use the more specialised Functional Interface 'DoubleConsumer'}} +// ^^^^^^^^^^^^^^^^ @Override public void accept(Double t) { } @@ -50,9 +53,11 @@ public void accept(Long t) { Predicate a8 = (double1) -> true; // Noncompliant Predicate a9 = (long1) -> true; // Noncompliant UnaryOperator a5 = (int1) -> int1; // Noncompliant - UnaryOperator a10 = (double1) -> double1; // Noncompliant [[sc=7;ec=28]] {{Refactor this code to use the more specialised Functional Interface 'DoubleUnaryOperator'}} + UnaryOperator a10 = (double1) -> double1; // Noncompliant {{Refactor this code to use the more specialised Functional Interface 'DoubleUnaryOperator'}} +// ^^^^^^^^^^^^^^^^^^^^^ UnaryOperator a11 = long1 -> long1; // Noncompliant - BiConsumer a12 = (aaa, int1) -> {}; // Noncompliant [[sc=7;ec=29]] {{Refactor this code to use the more specialised Functional Interface 'ObjIntConsumer'}} + BiConsumer a12 = (aaa, int1) -> {}; // Noncompliant {{Refactor this code to use the more specialised Functional Interface 'ObjIntConsumer'}} +// ^^^^^^^^^^^^^^^^^^^^^^ BiConsumer a13 = (aaa, long1) -> {}; // Noncompliant {{Refactor this code to use the more specialised Functional Interface 'ObjLongConsumer'}} BiConsumer a14 = (aaa, double1) -> {}; // Noncompliant {{Refactor this code to use the more specialised Functional Interface 'ObjDoubleConsumer'}} BiConsumer compl1 = (a, aa) -> {}; // Compliant @@ -165,7 +170,8 @@ public Long apply(Long t, Long u) { }; } - private static class A4 implements Function>, Entry>> { // Noncompliant [[sc=26;ec=28]] + private static class A4 implements Function>, Entry>> { // Noncompliant +// ^^ @Override public Entry> apply(Entry> t) { return null; @@ -198,7 +204,9 @@ public Object apply(Object t) { } - static class MySupplier implements Supplier { // Noncompliant [[sc=16;ec=26;secondary=201]] + static class MySupplier implements Supplier { // Noncompliant +// ^^^^^^^^^^ +// ^^^^^^^^^^^^^^^^^@-1< Supplier mySupplier = new MySupplier(); // Compliant @Override @@ -207,7 +215,9 @@ public Integer get() { } } - static class MySupplier1 implements Supplier, Runnable { // Noncompliant [sc=16;ec=27;secondary=191] {{Refactor this code to use the more specialised Functional Interface 'IntSupplier'}} + static class MySupplier1 implements Supplier, Runnable { // Noncompliant {{Refactor this code to use the more specialised Functional Interface 'IntSupplier'}} +// ^^^^^^^^^^^ +// ^^^^^^^^^^^^^^^^^@-1< Supplier mySupplier = new MySupplier1(); // Compliant @Override @@ -220,7 +230,10 @@ public void run() { } } - static class MySupplier2 implements Supplier, Consumer { // Noncompliant [[sc=16;ec=27;secondary=223, 223]] {{Refactor this code to use the more specialised Functional Interfaces 'IntSupplier', 'DoubleConsumer'}} + static class MySupplier2 implements Supplier, Consumer { // Noncompliant {{Refactor this code to use the more specialised Functional Interfaces 'IntSupplier', 'DoubleConsumer'}} +// ^^^^^^^^^^^ +// ^^^^^^^^^^^^^^^^^@-1< +// ^^^^^^^^^^^^^^^^@-2< Supplier mySupplier = new MySupplier2(); // Compliant @Override @@ -233,7 +246,10 @@ public void accept(Double t) { } } - static class MySupplier3 implements Supplier, Runnable, Consumer { // Noncompliant [[sc=16;ec=27;secondary=236, 236]] {{Refactor this code to use the more specialised Functional Interfaces 'IntSupplier', 'DoubleConsumer'}} + static class MySupplier3 implements Supplier, Runnable, Consumer { // Noncompliant {{Refactor this code to use the more specialised Functional Interfaces 'IntSupplier', 'DoubleConsumer'}} +// ^^^^^^^^^^^ +// ^^^^^^^^^^^^^^^^^@-1< +// ^^^^^^^^^^^^^^^^@-2< Supplier mySupplier = new MySupplier2(); // Compliant @Override diff --git a/java-checks-test-sources/default/src/main/java/checks/StandardCharsetsConstantsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/StandardCharsetsConstantsCheckSample.java index 6b753ca6611..3b743fadf0a 100644 --- a/java-checks-test-sources/default/src/main/java/checks/StandardCharsetsConstantsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/StandardCharsetsConstantsCheckSample.java @@ -43,7 +43,8 @@ class StandardCharsetsConstantsCheckSample { private ReadableByteChannel readableByteChannel; void myMethod() throws Exception { - charset = com.google.common.base.Charsets.ISO_8859_1; // Noncompliant {{Replace "com.google.common.base.Charsets.ISO_8859_1" with "StandardCharsets.ISO_8859_1".}} [[sc=47;ec=57]] + charset = com.google.common.base.Charsets.ISO_8859_1; // Noncompliant {{Replace "com.google.common.base.Charsets.ISO_8859_1" with "StandardCharsets.ISO_8859_1".}} +// ^^^^^^^^^^ charset = com.google.common.base.Charsets.US_ASCII; // Noncompliant {{Replace "com.google.common.base.Charsets.US_ASCII" with "StandardCharsets.US_ASCII".}} charset = com.google.common.base.Charsets.UTF_16; // Noncompliant {{Replace "com.google.common.base.Charsets.UTF_16" with "StandardCharsets.UTF_16".}} charset = com.google.common.base.Charsets.UTF_16BE; // Noncompliant {{Replace "com.google.common.base.Charsets.UTF_16BE" with "StandardCharsets.UTF_16BE".}} @@ -51,7 +52,8 @@ void myMethod() throws Exception { charset = com.google.common.base.Charsets.UTF_8; // Noncompliant {{Replace "com.google.common.base.Charsets.UTF_8" with "StandardCharsets.UTF_8".}} // Canonical names of java.nio API and java.io/java.lang API - Charset.forName("ISO-8859-1"); // Noncompliant {{Replace Charset.forName() call with StandardCharsets.ISO_8859_1}} [[sc=5;ec=34]] + Charset.forName("ISO-8859-1"); // Noncompliant {{Replace Charset.forName() call with StandardCharsets.ISO_8859_1}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Charset.forName("ISO_8859_1"); // Noncompliant {{Replace Charset.forName() call with StandardCharsets.ISO_8859_1}} Charset.forName("US-ASCII"); // Noncompliant {{Replace Charset.forName() call with StandardCharsets.US_ASCII}} Charset.forName("ASCII"); // Noncompliant {{Replace Charset.forName() call with StandardCharsets.US_ASCII}} @@ -65,14 +67,20 @@ void myMethod() throws Exception { Charset.forName("utf-8"); // Noncompliant {{Replace Charset.forName() call with StandardCharsets.UTF_8}} Charset.forName("Utf-8"); // Noncompliant {{Replace Charset.forName() call with StandardCharsets.UTF_8}} - org.apache.commons.codec.Charsets.toCharset("UTF-8"); // Noncompliant {{Replace Charsets.toCharset() call with StandardCharsets.UTF_8}} [[sc=5;ec=57]] + org.apache.commons.codec.Charsets.toCharset("UTF-8"); // Noncompliant {{Replace Charsets.toCharset() call with StandardCharsets.UTF_8}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - org.apache.commons.io.Charsets.toCharset("UTF-8"); // Noncompliant {{Replace Charsets.toCharset() call with StandardCharsets.UTF_8}} [[sc=5;ec=54]] + org.apache.commons.io.Charsets.toCharset("UTF-8"); // Noncompliant {{Replace Charsets.toCharset() call with StandardCharsets.UTF_8}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - org.apache.commons.io.IOUtils.toString(bytes, "UTF-8"); // Noncompliant {{Replace IOUtils.toString() call with new String(..., StandardCharsets.UTF_8);}} [[sc=5;ec=59]] - org.apache.commons.io.IOUtils.toString(inputStream, "UTF-8"); // Noncompliant {{Replace charset name argument with StandardCharsets.UTF_8}} [[sc=57;ec=64]] - org.apache.commons.io.IOUtils.toString(uri, "UTF-8"); // Noncompliant {{Replace charset name argument with StandardCharsets.UTF_8}} [[sc=49;ec=56]] - org.apache.commons.io.IOUtils.toString(url, "UTF-8"); // Noncompliant {{Replace charset name argument with StandardCharsets.UTF_8}} [[sc=49;ec=56]] + org.apache.commons.io.IOUtils.toString(bytes, "UTF-8"); // Noncompliant {{Replace IOUtils.toString() call with new String(..., StandardCharsets.UTF_8);}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + org.apache.commons.io.IOUtils.toString(inputStream, "UTF-8"); // Noncompliant {{Replace charset name argument with StandardCharsets.UTF_8}} +// ^^^^^^^ + org.apache.commons.io.IOUtils.toString(uri, "UTF-8"); // Noncompliant {{Replace charset name argument with StandardCharsets.UTF_8}} +// ^^^^^^^ + org.apache.commons.io.IOUtils.toString(url, "UTF-8"); // Noncompliant {{Replace charset name argument with StandardCharsets.UTF_8}} +// ^^^^^^^ "".getBytes("UTF-8"); // Noncompliant {{Replace charset name argument with StandardCharsets.UTF_8}} @@ -86,11 +94,13 @@ void myMethod() throws Exception { new org.apache.commons.codec.net.QuotedPrintableCodec("UTF-8"); // Noncompliant org.apache.commons.io.FileUtils.readFileToString(file, "UTF-8"); // Noncompliant - org.apache.commons.io.FileUtils.readLines(file, "UTF-8"); // Noncompliant + org.apache.commons.io.FileUtils.readLines(file, "UTF-8"); // Noncompliant org.apache.commons.io.FileUtils.write(file, charSequence, "UTF-8"); // Noncompliant org.apache.commons.io.FileUtils.write(file, charSequence, "UTF-8", append); // Noncompliant - org.apache.commons.io.FileUtils.writeStringToFile(file, dataString, "UTF-8"); // Noncompliant [[sc=73;ec=80]] - org.apache.commons.io.FileUtils.writeStringToFile(file, dataString, "UTF-8", append); // Noncompliant [[sc=73;ec=80]] + org.apache.commons.io.FileUtils.writeStringToFile(file, dataString, "UTF-8"); // Noncompliant +// ^^^^^^^ + org.apache.commons.io.FileUtils.writeStringToFile(file, dataString, "UTF-8", append); // Noncompliant +// ^^^^^^^ org.apache.commons.io.IOUtils.copy(inputStream, writer, "UTF-8"); // Noncompliant org.apache.commons.io.IOUtils.copy(reader, outputStream, "UTF-8"); // Noncompliant org.apache.commons.io.IOUtils.lineIterator(inputStream, "UTF-8"); // Noncompliant @@ -98,20 +108,24 @@ void myMethod() throws Exception { org.apache.commons.io.IOUtils.toByteArray(reader, "UTF-8"); // Noncompliant org.apache.commons.io.IOUtils.toCharArray(inputStream, "UTF-8"); // Noncompliant org.apache.commons.io.IOUtils.toInputStream(charSequence, "UTF-8"); // Noncompliant - org.apache.commons.io.IOUtils.toInputStream(inputString, "UTF-8"); // Noncompliant [[sc=62;ec=69]] + org.apache.commons.io.IOUtils.toInputStream(inputString, "UTF-8"); // Noncompliant +// ^^^^^^^ org.apache.commons.io.IOUtils.write(bytes, writer, "UTF-8"); // Noncompliant org.apache.commons.io.IOUtils.write(chars, outputStream, "UTF-8"); // Noncompliant org.apache.commons.io.IOUtils.write(charSequence, outputStream, "UTF-8"); // Noncompliant - org.apache.commons.io.IOUtils.write(dataString, outputStream, "UTF-8"); // Noncompliant [[sc=67;ec=74]] + org.apache.commons.io.IOUtils.write(dataString, outputStream, "UTF-8"); // Noncompliant +// ^^^^^^^ org.apache.commons.io.IOUtils.write(stringBuffer, outputStream, "UTF-8"); // Noncompliant - org.apache.commons.io.IOUtils.writeLines(collection, lineEndingString, outputStream, "UTF-8"); // Noncompliant [[sc=90;ec=97]] + org.apache.commons.io.IOUtils.writeLines(collection, lineEndingString, outputStream, "UTF-8"); // Noncompliant +// ^^^^^^^ new org.apache.commons.io.input.CharSequenceInputStream(charSequence, "UTF-8"); // Noncompliant new org.apache.commons.io.input.CharSequenceInputStream(charSequence, "UTF-8", bufferSize); // Noncompliant new org.apache.commons.io.input.ReaderInputStream(reader, "UTF-8"); // Noncompliant new org.apache.commons.io.input.ReaderInputStream(reader, "UTF-8", bufferSize); // Noncompliant new org.apache.commons.io.input.ReversedLinesFileReader(file, blockSize, "UTF-8"); // Noncompliant new org.apache.commons.io.output.LockableFileWriter(file, "UTF-8"); // Noncompliant - new org.apache.commons.io.output.LockableFileWriter(file, "UTF-8", append, lockDirString); // Noncompliant [[sc=63;ec=70]] + new org.apache.commons.io.output.LockableFileWriter(file, "UTF-8", append, lockDirString); // Noncompliant +// ^^^^^^^ new org.apache.commons.io.output.WriterOutputStream(writer, "UTF-8"); // Noncompliant new org.apache.commons.io.output.WriterOutputStream(writer, "UTF-8", bufferSize, writeImmediately); // Noncompliant @@ -137,81 +151,100 @@ void myMethod() throws Exception { } void quickfixes() throws Exception { - charset = com.google.common.base.Charsets.ISO_8859_1; // Noncompliant [[sc=47;ec=57;quickfixes=qf1]] + charset = com.google.common.base.Charsets.ISO_8859_1; // Noncompliant [[quickfixes=qf1]] +// ^^^^^^^^^^ // fix@qf1 {{Replace with "StandardCharsets.ISO_8859_1"}} // edit@qf1 [[sc=15;ec=46]] {{StandardCharsets}} // edit@qf1 [[sl=13;sc=33;el=13;ec=33]] {{\nimport java.nio.charset.StandardCharsets;}} - charset = com.google.common.base.Charsets.US_ASCII; // Noncompliant [[sc=47;ec=55;quickfixes=qf2]] + charset = com.google.common.base.Charsets.US_ASCII; // Noncompliant [[quickfixes=qf2]] +// ^^^^^^^^ // fix@qf2 {{Replace with "StandardCharsets.US_ASCII"}} // edit@qf2 [[sc=15;ec=46]] {{StandardCharsets}} // edit@qf2 [[sl=13;sc=33;el=13;ec=33]] {{\nimport java.nio.charset.StandardCharsets;}} - charset = com.google.common.base.Charsets.UTF_16; // Noncompliant [[sc=47;ec=53;quickfixes=qf3]] + charset = com.google.common.base.Charsets.UTF_16; // Noncompliant [[quickfixes=qf3]] +// ^^^^^^ // fix@qf3 {{Replace with "StandardCharsets.UTF_16"}} // edit@qf3 [[sc=15;ec=46]] {{StandardCharsets}} // edit@qf3 [[sl=13;sc=33;el=13;ec=33]] {{\nimport java.nio.charset.StandardCharsets;}} - charset = com.google.common.base.Charsets.UTF_16BE; // Noncompliant [[sc=47;ec=55;quickfixes=qf4]] + charset = com.google.common.base.Charsets.UTF_16BE; // Noncompliant [[quickfixes=qf4]] +// ^^^^^^^^ // fix@qf4 {{Replace with "StandardCharsets.UTF_16BE"}} // edit@qf4 [[sc=15;ec=46]] {{StandardCharsets}} // edit@qf4 [[sl=13;sc=33;el=13;ec=33]] {{\nimport java.nio.charset.StandardCharsets;}} - charset = com.google.common.base.Charsets.UTF_16LE; // Noncompliant [[sc=47;ec=55;quickfixes=qf5]] + charset = com.google.common.base.Charsets.UTF_16LE; // Noncompliant [[quickfixes=qf5]] +// ^^^^^^^^ // fix@qf5 {{Replace with "StandardCharsets.UTF_16LE"}} // edit@qf5 [[sc=15;ec=46]] {{StandardCharsets}} // edit@qf5 [[sl=13;sc=33;el=13;ec=33]] {{\nimport java.nio.charset.StandardCharsets;}} - charset = com.google.common.base.Charsets.UTF_8; // Noncompliant [[sc=47;ec=52;quickfixes=qf6]] + charset = com.google.common.base.Charsets.UTF_8; // Noncompliant [[quickfixes=qf6]] +// ^^^^^ // fix@qf6 {{Replace with "StandardCharsets.UTF_8"}} // edit@qf6 [[sc=15;ec=46]] {{StandardCharsets}} // edit@qf6 [[sl=13;sc=33;el=13;ec=33]] {{\nimport java.nio.charset.StandardCharsets;}} - Charset.forName("ISO-8859-1"); // Noncompliant [[sc=5;ec=34;quickfixes=qf7]] + Charset.forName("ISO-8859-1"); // Noncompliant [[quickfixes=qf7]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf7 {{Replace with "StandardCharsets.ISO_8859_1"}} // edit@qf7 [[sc=5;ec=34]] {{StandardCharsets.ISO_8859_1}} // edit@qf7 [[sl=13;sc=33;el=13;ec=33]] {{\nimport java.nio.charset.StandardCharsets;}} - Charset.forName("ISO_8859_1"); // Noncompliant [[sc=5;ec=34;quickfixes=qf8]] + Charset.forName("ISO_8859_1"); // Noncompliant [[quickfixes=qf8]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf8 {{Replace with "StandardCharsets.ISO_8859_1"}} // edit@qf8 [[sc=5;ec=34]] {{StandardCharsets.ISO_8859_1}} // edit@qf8 [[sl=13;sc=33;el=13;ec=33]] {{\nimport java.nio.charset.StandardCharsets;}} - Charset.forName("UTF8"); // Noncompliant [[sc=5;ec=28;quickfixes=qf9]] + Charset.forName("UTF8"); // Noncompliant [[quickfixes=qf9]] +// ^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf9 {{Replace with "StandardCharsets.UTF_8"}} // edit@qf9 [[sc=5;ec=28]] {{StandardCharsets.UTF_8}} // edit@qf9 [[sl=13;sc=33;el=13;ec=33]] {{\nimport java.nio.charset.StandardCharsets;}} - Charset.forName("utf-8"); // Noncompliant [[sc=5;ec=29;quickfixes=qf10]] + Charset.forName("utf-8"); // Noncompliant [[quickfixes=qf10]] +// ^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf10 {{Replace with "StandardCharsets.UTF_8"}} // edit@qf10 [[sc=5;ec=29]] {{StandardCharsets.UTF_8}} // edit@qf10 [[sl=13;sc=33;el=13;ec=33]] {{\nimport java.nio.charset.StandardCharsets;}} - Charset.forName("UTF-16LE"); // Noncompliant [[sc=5;ec=32;quickfixes=qf11]] + Charset.forName("UTF-16LE"); // Noncompliant [[quickfixes=qf11]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf11 {{Replace with "StandardCharsets.UTF_16LE"}} // edit@qf11 [[sc=5;ec=32]] {{StandardCharsets.UTF_16LE}} // edit@qf11 [[sl=13;sc=33;el=13;ec=33]] {{\nimport java.nio.charset.StandardCharsets;}} - Charset.forName("UnicodeLittleUnmarked"); // Noncompliant [[sc=5;ec=45;quickfixes=qf12]] + Charset.forName("UnicodeLittleUnmarked"); // Noncompliant [[quickfixes=qf12]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf12 {{Replace with "StandardCharsets.UTF_16LE"}} // edit@qf12 [[sc=5;ec=45]] {{StandardCharsets.UTF_16LE}} // edit@qf12 [[sl=13;sc=33;el=13;ec=33]] {{\nimport java.nio.charset.StandardCharsets;}} - org.apache.commons.codec.Charsets.toCharset("UTF-8"); // Noncompliant [[sc=5;ec=57;quickfixes=qf13]] + org.apache.commons.codec.Charsets.toCharset("UTF-8"); // Noncompliant [[quickfixes=qf13]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf13 {{Replace with "StandardCharsets.UTF_8"}} // edit@qf13 [[sc=5;ec=57]] {{StandardCharsets.UTF_8}} // edit@qf13 [[sl=13;sc=33;el=13;ec=33]] {{\nimport java.nio.charset.StandardCharsets;}} - org.apache.commons.io.IOUtils.toString(inputStream, "UTF-8"); // Noncompliant [[sc=57;ec=64;quickfixes=qf14]] + org.apache.commons.io.IOUtils.toString(inputStream, "UTF-8"); // Noncompliant [[quickfixes=qf14]] +// ^^^^^^^ // fix@qf14 {{Replace with "StandardCharsets.UTF_8"}} // edit@qf14 [[sc=57;ec=64]] {{StandardCharsets.UTF_8}} // edit@qf14 [[sl=13;sc=33;el=13;ec=33]] {{\nimport java.nio.charset.StandardCharsets;}} - "".getBytes("UTF-8"); // Noncompliant [[sc=17;ec=24;quickfixes=qf15]] + "".getBytes("UTF-8"); // Noncompliant [[quickfixes=qf15]] +// ^^^^^^^ // fix@qf15 {{Replace with "StandardCharsets.UTF_8"}} // edit@qf15 [[sc=17;ec=24]] {{StandardCharsets.UTF_8}} // edit@qf15 [[sl=13;sc=33;el=13;ec=33]] {{\nimport java.nio.charset.StandardCharsets;}} - new String(bytes, offset, length, org.apache.commons.lang.CharEncoding.UTF_8); // Noncompliant [[sc=39;ec=81;quickfixes=qf16]] + new String(bytes, offset, length, org.apache.commons.lang.CharEncoding.UTF_8); // Noncompliant [[quickfixes=qf16]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf16 {{Replace with "StandardCharsets.UTF_8"}} // edit@qf16 [[sc=39;ec=81]] {{StandardCharsets.UTF_8}} // edit@qf16 [[sl=13;sc=33;el=13;ec=33]] {{\nimport java.nio.charset.StandardCharsets;}} - org.apache.commons.io.FileUtils.write(file, charSequence, "UTF-8"); // Noncompliant [[sc=63;ec=70;quickfixes=qf17]] + org.apache.commons.io.FileUtils.write(file, charSequence, "UTF-8"); // Noncompliant [[quickfixes=qf17]] +// ^^^^^^^ // fix@qf17 {{Replace with "StandardCharsets.UTF_8"}} // edit@qf17 [[sc=63;ec=70]] {{StandardCharsets.UTF_8}} // edit@qf17 [[sl=13;sc=33;el=13;ec=33]] {{\nimport java.nio.charset.StandardCharsets;}} - org.apache.commons.io.IOUtils.toCharArray(inputStream, "UTF-8"); // Noncompliant [[sc=61;ec=68;quickfixes=qf18]] + org.apache.commons.io.IOUtils.toCharArray(inputStream, "UTF-8"); // Noncompliant [[quickfixes=qf18]] +// ^^^^^^^ // fix@qf18 {{Replace with "StandardCharsets.UTF_8"}} // edit@qf18 [[sc=61;ec=68]] {{StandardCharsets.UTF_8}} // edit@qf18 [[sl=13;sc=33;el=13;ec=33]] {{\nimport java.nio.charset.StandardCharsets;}} - new org.apache.commons.io.input.ReaderInputStream(reader, "ISO-8859-1", bufferSize); // Noncompliant [[sc=63;ec=75;quickfixes=qf19]] + new org.apache.commons.io.input.ReaderInputStream(reader, "ISO-8859-1", bufferSize); // Noncompliant [[quickfixes=qf19]] +// ^^^^^^^^^^^^ // fix@qf19 {{Replace with "StandardCharsets.ISO_8859_1"}} // edit@qf19 [[sc=63;ec=75]] {{StandardCharsets.ISO_8859_1}} // edit@qf19 [[sl=13;sc=33;el=13;ec=33]] {{\nimport java.nio.charset.StandardCharsets;}} diff --git a/java-checks-test-sources/default/src/main/java/checks/StaticFieldUpateCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/StaticFieldUpateCheckSample.java index c1d5ed9d85c..31f4f052bf6 100644 --- a/java-checks-test-sources/default/src/main/java/checks/StaticFieldUpateCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/StaticFieldUpateCheckSample.java @@ -10,7 +10,8 @@ class StaticFieldUpateCheckSample { private static int[] staticArray; public void nonCompliantAssignments() { - staticValue = value + 1; // Noncompliant [[sc=5;ec=16]] {{Make the enclosing method "static" or remove this set.}} + staticValue = value + 1; // Noncompliant {{Make the enclosing method "static" or remove this set.}} +// ^^^^^^^^^^^ staticValue += value; // Noncompliant {{Make the enclosing method "static" or remove this set.}} staticValue++; // Noncompliant {{Make the enclosing method "static" or remove this set.}} ++staticValue; // Noncompliant {{Make the enclosing method "static" or remove this set.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/StaticFieldUpdateInConstructorCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/StaticFieldUpdateInConstructorCheckSample.java index 5af605d98af..35f85dcb546 100644 --- a/java-checks-test-sources/default/src/main/java/checks/StaticFieldUpdateInConstructorCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/StaticFieldUpdateInConstructorCheckSample.java @@ -3,19 +3,28 @@ class StaticFieldUpdateInConstructorCheckSample { String field; static String staticField; +//^^^^^^^^^^^^^^^^^^^^^^^^^^> static String[] words = {"yolo", "fun"}; static int value = 14; StaticFieldUpdateInConstructorCheckSample() { field = "world"; // Compliant - staticField = "hello"; // Noncompliant [[sc=5;ec=16;secondary=5]] {{Remove this assignment of "staticField".}} - StaticFieldUpdateInConstructorCheckSample.staticField = "again"; // Noncompliant [[sc=47;ec=58;secondary=5]] {{Remove this assignment of "staticField".}} - words[0] = "noFun"; // Noncompliant [[sc=5;ec=10;secondary=6]] {{Remove this assignment of "words".}} - value = 42; // Noncompliant [[sc=5;ec=10;secondary=7]] {{Remove this assignment of "value".}} - value += 1; // Noncompliant [[sc=5;ec=10;secondary=7]] {{Remove this assignment of "value".}} + staticField = "hello"; // Noncompliant {{Remove this assignment of "staticField".}} +// ^^^^^^^^^^^ + StaticFieldUpdateInConstructorCheckSample.staticField = "again"; // Noncompliant {{Remove this assignment of "staticField".}} +// ^^^^^^^^^^^ + words[0] = "noFun"; // Noncompliant {{Remove this assignment of "words".}} +// ^^^^^ +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^@-10< + value = 42; // Noncompliant {{Remove this assignment of "value".}} +// ^^^^^ +//^^^^^^^^^^^^^^^^^^^^^^@-12< + value += 1; // Noncompliant {{Remove this assignment of "value".}} +// ^^^^^ String var = "boom"; - field = staticField = var = "why so mean, java"; // Noncompliant [[sc=13;ec=24;secondary=5]] {{Remove this assignment of "staticField".}} + field = staticField = var = "why so mean, java"; // Noncompliant {{Remove this assignment of "staticField".}} +// ^^^^^^^^^^^ value++; // Compliant - postfix/prefix increment/decrement not taken into account diff --git a/java-checks-test-sources/default/src/main/java/checks/StaticMemberAccess.java b/java-checks-test-sources/default/src/main/java/checks/StaticMemberAccess.java index ae699660282..f1b4b442714 100644 --- a/java-checks-test-sources/default/src/main/java/checks/StaticMemberAccess.java +++ b/java-checks-test-sources/default/src/main/java/checks/StaticMemberAccess.java @@ -14,7 +14,7 @@ static void foo() { class StaticMemberAccessChild extends StaticMemberAccessParent { public StaticMemberAccessChild() { - StaticMemberAccessChild.counter++; // Noncompliant {{Use static access with "checks.StaticMemberAccessParent" for "counter".}} + StaticMemberAccessChild.counter++; // Noncompliant {{Use static access with "checks.StaticMemberAccessParent" for "counter".}} StaticMemberAccessParent.counter++; // Compliant StaticMemberAccessChild.foo(); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/StaticMemberAccessQuickFixes.java b/java-checks-test-sources/default/src/main/java/checks/StaticMemberAccessQuickFixes.java index bfcf3bdfba6..7237fd80bfa 100644 --- a/java-checks-test-sources/default/src/main/java/checks/StaticMemberAccessQuickFixes.java +++ b/java-checks-test-sources/default/src/main/java/checks/StaticMemberAccessQuickFixes.java @@ -8,7 +8,8 @@ static class InnerClass extends StaticMemberAccessQuickFixes { public static int otherCounter; void bar() { - InnerClass.counter++; // Noncompliant [[sc=18;ec=25;quickfixes=qf1]] {{Use static access with "checks.StaticMemberAccessQuickFixes" for "counter".}} + InnerClass.counter++; // Noncompliant {{Use static access with "checks.StaticMemberAccessQuickFixes" for "counter".}} [[quickfixes=qf1]] +// ^^^^^^^ // fix@qf1 {{Use "StaticMemberAccessQuickFixes" instead of "InnerClass"}} // edit@qf1 [[sc=7;ec=17]] {{StaticMemberAccessQuickFixes}} } @@ -16,7 +17,8 @@ void bar() { static class SecondInnerClass extends InnerClass { void qix() { - SecondInnerClass.otherCounter++; // Noncompliant [[sc=24;ec=36;quickfixes=qf2]] {{Use static access with "checks.StaticMemberAccessQuickFixes$InnerClass" for "otherCounter".}} + SecondInnerClass.otherCounter++; // Noncompliant {{Use static access with "checks.StaticMemberAccessQuickFixes$InnerClass" for "otherCounter".}} [[quickfixes=qf2]] +// ^^^^^^^^^^^^ // fix@qf2 {{Use "InnerClass" instead of "SecondInnerClass"}} // edit@qf2 [[sc=7;ec=23]] {{InnerClass}} } @@ -25,13 +27,15 @@ void qix() { class StaticMemberAccessQuickFixesChild extends StaticMemberAccessQuickFixes { void bar() { - StaticMemberAccessQuickFixesChild.counter++; // Noncompliant [[sc=39;ec=46;quickfixes=qf3]] {{Use static access with "checks.StaticMemberAccessQuickFixes" for "counter".}} + StaticMemberAccessQuickFixesChild.counter++; // Noncompliant {{Use static access with "checks.StaticMemberAccessQuickFixes" for "counter".}} [[quickfixes=qf3]] +// ^^^^^^^ // fix@qf3 {{Use "StaticMemberAccessQuickFixes" instead of "StaticMemberAccessQuickFixesChild"}} // edit@qf3 [[sc=5;ec=38]] {{StaticMemberAccessQuickFixes}} StaticMemberAccessQuickFixes.counter++; // Compliant - StaticMemberAccessQuickFixesChild.foo(); // Noncompliant [[sc=39;ec=42;quickfixes=qf4]] {{Use static access with "checks.StaticMemberAccessQuickFixes" for "foo".}} + StaticMemberAccessQuickFixesChild.foo(); // Noncompliant {{Use static access with "checks.StaticMemberAccessQuickFixes" for "foo".}} [[quickfixes=qf4]] +// ^^^ // fix@qf4 {{Use "StaticMemberAccessQuickFixes" instead of "StaticMemberAccessQuickFixesChild"}} // edit@qf4 [[sc=5;ec=38]] {{StaticMemberAccessQuickFixes}} diff --git a/java-checks-test-sources/default/src/main/java/checks/StaticMembersAccessCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/StaticMembersAccessCheckSample.java index 6973aaacea4..04ac3b36899 100644 --- a/java-checks-test-sources/default/src/main/java/checks/StaticMembersAccessCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/StaticMembersAccessCheckSample.java @@ -36,23 +36,28 @@ public StaticMembersAccessCheckSampleA.StaticMembersAccessCheckSampleD d() { } public void noncompliant() { - first.counter ++; // Noncompliant [[sc=5;ec=10;quickfixes=qf1]] {{Change this instance-reference to a static reference.}} + first.counter ++; // Noncompliant {{Change this instance-reference to a static reference.}} [[quickfixes=qf1]] +// ^^^^^ // fix@qf1 {{Replace "first" by "StaticMembersAccessCheckSampleA"}} // edit@qf1 [[sc=5;ec=10]] {{StaticMembersAccessCheckSampleA}} second.counter ++; // Noncompliant - second.method(); // Noncompliant [[sc=5;ec=11;quickfixes=qf2]] + second.method(); // Noncompliant [[quickfixes=qf2]] +// ^^^^^^ // fix@qf2 {{Replace "second" by "StaticMembersAccessCheckSampleA"}} // edit@qf2 [[sc=5;ec=11]] {{StaticMembersAccessCheckSampleA}} third.counter ++; // Noncompliant first.d.counter++; // Noncompliant - first.c.d.counter++; // Noncompliant [[sc=5;ec=14;quickfixes=qf3]] + first.c.d.counter++; // Noncompliant [[quickfixes=qf3]] +// ^^^^^^^^^ // fix@qf3 {{Replace the expression by "StaticMembersAccessCheckSampleD"}} // edit@qf3 [[sc=5;ec=14]] {{StaticMembersAccessCheckSampleD}} - first.d().counter++; // Noncompliant [[sc=5;ec=14;quickfixes=qf4]] + first.d().counter++; // Noncompliant [[quickfixes=qf4]] +// ^^^^^^^^^ // fix@qf4 {{Replace the expression by "StaticMembersAccessCheckSampleD"}} // edit@qf4 [[sc=5;ec=14]] {{StaticMembersAccessCheckSampleD}} d().counter++; // Noncompliant - // Noncompliant@+1 [[sc=5;el=+3;ec=6;quickfixes=qf5]] + + // Noncompliant@+1 [[sl=+0;el=+2;sc=5;ec=6;quickfixes=qf5]] ( (StaticMembersAccessCheckSampleA.StaticMembersAccessCheckSampleD) d() ).counter++; @@ -60,11 +65,13 @@ public void noncompliant() { // edit@qf5 [[sc=5;el=+2;ec=6]] {{StaticMembersAccessCheckSampleD}} (d()).counter++; // Noncompliant StaticMembersAccessCheckSampleA.StaticMembersAccessCheckSampleD[] darray = new StaticMembersAccessCheckSampleA.StaticMembersAccessCheckSampleD[1]; - darray[0].counter++; // Noncompliant [[sc=5;ec=14;quickfixes=qf6]] + darray[0].counter++; // Noncompliant [[quickfixes=qf6]] +// ^^^^^^^^^ // fix@qf6 {{Replace the expression by "StaticMembersAccessCheckSampleD"}} // edit@qf6 [[sc=5;ec=14]] {{StaticMembersAccessCheckSampleD}} Path path = Paths.get("abc"); - char separator = path.toFile().separatorChar; // Noncompliant [[sc=22;ec=35;quickfixes=qf7]] + char separator = path.toFile().separatorChar; // Noncompliant [[quickfixes=qf7]] +// ^^^^^^^^^^^^^ // fix@qf7 {{Replace the expression by "File"}} // edit@qf7 [[sc=22;ec=35]] {{File}} // edit@qf7 [[sl=3;sc=1;el=3;ec=1]] {{import java.io.File;\n}} diff --git a/java-checks-test-sources/default/src/main/java/checks/StaticMethodCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/StaticMethodCheckSample.java index 9745778e1ad..23d5c25838b 100644 --- a/java-checks-test-sources/default/src/main/java/checks/StaticMethodCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/StaticMethodCheckSample.java @@ -19,14 +19,16 @@ private void register(final Class clazz, final Object converter) { otherWord = ""; } - private String getMagicWord() { // Noncompliant [[sc=18;ec=30]] {{Make "getMagicWord" a "static" method.}} + private String getMagicWord() { // Noncompliant {{Make "getMagicWord" a "static" method.}} +// ^^^^^^^^^^^^ return magicWord; } private static String getMagicWordOK() { return magicWord; } - public final String magicWord() { // Noncompliant [[sc=23;ec=32]] {{Make "magicWord" a "static" method.}} + public final String magicWord() { // Noncompliant {{Make "magicWord" a "static" method.}} +// ^^^^^^^^^ return magicWord; } @@ -74,15 +76,15 @@ private void setOtherWord(String value) { otherWord = value; } - private int useOnlyArguments(int a, int b) { // Noncompliant + private int useOnlyArguments(int a, int b) { // Noncompliant return a + b; } - private String methodOnlyOnArgument(Object obj) { // Noncompliant + private String methodOnlyOnArgument(Object obj) { // Noncompliant return (obj == null ? null : obj.toString()); } - private String attributeOnArgument(Utilities obj) { // Noncompliant + private String attributeOnArgument(Utilities obj) { // Noncompliant return obj.otherWord; } @@ -177,7 +179,7 @@ static class FooBar { enum MyEnum{ FOO; } - private void plop() { // Noncompliant enum is static and enum constants are static + private void plop() { // Noncompliant Object o = MyEnum.FOO; } int myHash() { @@ -278,19 +280,22 @@ public int getMagicNumber() { // OK, overrides parent method final class FinalClass { static int magicNumber = 42; - public int getMagicNumber() { // Noncompliant [[sc=14;ec=28;quickfixes=qf_public_in_final]] {{Make "getMagicNumber" a "static" method.}} + public int getMagicNumber() { // Noncompliant {{Make "getMagicNumber" a "static" method.}} [[quickfixes=qf_public_in_final]] +// ^^^^^^^^^^^^^^ // fix@qf_public_in_final {{Make static}} // edit@qf_public_in_final [[sc=10;ec=10]]{{static }} return magicNumber; } - int getMagicNumber2() { // Noncompliant [[sc=7;ec=22;quickfixes=qf_public_in_final2]] + int getMagicNumber2() { // Noncompliant [[quickfixes=qf_public_in_final2]] +// ^^^^^^^^^^^^^^^ // fix@qf_public_in_final2 {{Make static}} // edit@qf_public_in_final2 [[sc=3;ec=3]]{{static }} return magicNumber; } - synchronized int getMagicNumber3() { // Noncompliant [[sc=20;ec=35;quickfixes=qf_public_in_final3]] + synchronized int getMagicNumber3() { // Noncompliant [[quickfixes=qf_public_in_final3]] +// ^^^^^^^^^^^^^^^ // fix@qf_public_in_final3 {{Make static}} // edit@qf_public_in_final3 [[sc=3;ec=3]]{{static }} return magicNumber; @@ -314,39 +319,45 @@ final SomeEnum getOne() { class StaticMethodCheckSampleQuickFix { private static String magicWord = "magic"; - private String getMagicWord() { // Noncompliant [[sc=18;ec=30;quickfixes=qf_private]] + private String getMagicWord() { // Noncompliant [[quickfixes=qf_private]] +// ^^^^^^^^^^^^ // fix@qf_private {{Make static}} // edit@qf_private [[sc=11;ec=11]]{{static }} return magicWord; } @Nullable - private String getMagicWord2() { // Noncompliant [[sc=18;ec=31;quickfixes=qf_private2]] + private String getMagicWord2() { // Noncompliant [[quickfixes=qf_private2]] +// ^^^^^^^^^^^^^ // fix@qf_private2 {{Make static}} // edit@qf_private2 [[sc=11;ec=11]]{{static }} return magicWord; } - public final String magicWord() { // Noncompliant [[sc=23;ec=32;quickfixes=qf_public_final]] + public final String magicWord() { // Noncompliant [[quickfixes=qf_public_final]] +// ^^^^^^^^^ // fix@qf_public_final {{Make static}} // edit@qf_public_final [[sc=10;ec=10]]{{static }} return magicWord; } - private synchronized String magicWordSynchronized() { // Noncompliant [[sc=31;ec=52;quickfixes=qf_private_synchronized]] + private synchronized String magicWordSynchronized() { // Noncompliant [[quickfixes=qf_private_synchronized]] +// ^^^^^^^^^^^^^^^^^^^^^ // fix@qf_private_synchronized {{Make static}} // edit@qf_private_synchronized [[sc=11;ec=11]]{{static }} return magicWord; } // Order is not following the convention: add it before the first modifier that should come after static - synchronized private String magicWordSynchronized2() { // Noncompliant [[sc=31;ec=53;quickfixes=qf_private_synchronized2]] + synchronized private String magicWordSynchronized2() { // Noncompliant [[quickfixes=qf_private_synchronized2]] +// ^^^^^^^^^^^^^^^^^^^^^^ // fix@qf_private_synchronized2 {{Make static}} // edit@qf_private_synchronized2 [[sc=3;ec=3]]{{static }} return magicWord; } - private @Nullable synchronized String magicWordSynchronized3() { // Noncompliant [[sc=41;ec=63;quickfixes=qf_private_synchronized3]] + private @Nullable synchronized String magicWordSynchronized3() { // Noncompliant [[quickfixes=qf_private_synchronized3]] +// ^^^^^^^^^^^^^^^^^^^^^^ // fix@qf_private_synchronized3 {{Make static}} // edit@qf_private_synchronized3 [[sc=21;ec=21]]{{static }} return magicWord; diff --git a/java-checks-test-sources/default/src/main/java/checks/StaticMultithreadedUnsafeFields.java b/java-checks-test-sources/default/src/main/java/checks/StaticMultithreadedUnsafeFields.java index 5eefa786332..99a71e5dc22 100644 --- a/java-checks-test-sources/default/src/main/java/checks/StaticMultithreadedUnsafeFields.java +++ b/java-checks-test-sources/default/src/main/java/checks/StaticMultithreadedUnsafeFields.java @@ -27,9 +27,12 @@ public static class ConcreteCalendar extends java.util.Calendar { private static int field; // Compliant private java.text.SimpleDateFormat format1; // Compliant - private static java.text.SimpleDateFormat format2; // Noncompliant [[sc=45;ec=52]] {{Make "format2" an instance variable.}} - private static java.text.SimpleDateFormat format3; // Noncompliant [[sc=45;ec=52]] {{Make "format3" an instance variable.}} - public static java.text.SimpleDateFormat format4; // Noncompliant [[sc=44;ec=51]] {{Make "format4" an instance variable.}} + private static java.text.SimpleDateFormat format2; // Noncompliant {{Make "format2" an instance variable.}} +// ^^^^^^^ + private static java.text.SimpleDateFormat format3; // Noncompliant {{Make "format3" an instance variable.}} +// ^^^^^^^ + public static java.text.SimpleDateFormat format4; // Noncompliant {{Make "format4" an instance variable.}} +// ^^^^^^^ private static java.text.DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); // Noncompliant private static java.text.DateFormat dateFormat2 = null; diff --git a/java-checks-test-sources/default/src/main/java/checks/StreamPeekCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/StreamPeekCheckSample.java index 84a34296a86..0b7e6bccd4b 100644 --- a/java-checks-test-sources/default/src/main/java/checks/StreamPeekCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/StreamPeekCheckSample.java @@ -9,7 +9,8 @@ class StreamPeekCheckSample { void foo(){ Stream.of("one", "two", "three", "four") .filter(e -> e.length() > 3) - .peek(e -> System.out.println("Filtered value: " + e)); // Noncompliant [[sc=8;ec=12]] {{Remove this use of "Stream.peek".}} + .peek(e -> System.out.println("Filtered value: " + e)); // Noncompliant {{Remove this use of "Stream.peek".}} +// ^^^^ IntStream.of(1, 2, 3) .peek(e -> System.out.println(e)); // Noncompliant LongStream.of(1, 2, 3) diff --git a/java-checks-test-sources/default/src/main/java/checks/StringBufferAndBuilderWithCharCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/StringBufferAndBuilderWithCharCheckSample.java index e359e7d100b..01eaad8372e 100644 --- a/java-checks-test-sources/default/src/main/java/checks/StringBufferAndBuilderWithCharCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/StringBufferAndBuilderWithCharCheckSample.java @@ -3,8 +3,9 @@ class StringBufferAndBuilderWithCharCheckSample { public void f() { - StringBuffer foo = new java.lang.StringBuffer('x'); // Noncompliant [[sc=51;ec=54]] {{Replace the constructor character parameter 'x' with string parameter "x".}} - StringBuilder foo2 = new StringBuilder('x'); // Noncompliant {{Replace the constructor character parameter 'x' with string parameter "x".}} + StringBuffer foo = new java.lang.StringBuffer('x'); // Noncompliant {{Replace the constructor character parameter 'x' with string parameter "x".}} +// ^^^ + StringBuilder foo2 = new StringBuilder('x'); // Noncompliant {{Replace the constructor character parameter 'x' with string parameter "x".}} StringBuffer foo3 = new StringBuffer("x"); // OK StringBuilder foo4 = new StringBuilder("x"); // OK diff --git a/java-checks-test-sources/default/src/main/java/checks/StringConcatToTextBlockCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/StringConcatToTextBlockCheckSample.java index 4b49cf76508..410ea6c7a11 100644 --- a/java-checks-test-sources/default/src/main/java/checks/StringConcatToTextBlockCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/StringConcatToTextBlockCheckSample.java @@ -6,7 +6,8 @@ public class StringConcatToTextBlockCheckSample { public static void main(String[] args) { - String s = "\n" + // Noncompliant [[sc=16;ec=25]] {{Replace this String concatenation with Text block.}} + String s = "\n" + // Noncompliant {{Replace this String concatenation with Text block.}} +// ^[el=+6;ec=24] " \n" + " \n" + " \n" + @@ -20,21 +21,24 @@ public static void main(String[] args) { " \\n" + ""; - String s1 = "\n" + // Noncompliant [[sc=17;ec=25]] {{Replace this String concatenation with Text block.}} + String s1 = "\n" + // Noncompliant {{Replace this String concatenation with Text block.}} +// ^[el=+6;ec=24] " " + " " + " " + " \n" + ""; - String s2 = "" + // Noncompliant [[sc=17;ec=25]] {{Replace this String concatenation with Text block.}} + String s2 = "" + // Noncompliant {{Replace this String concatenation with Text block.}} +// ^[el=+6;ec=24] " \n" + " " + " " + " \n" + ""; - String s3 = "" + // Noncompliant [[sc=17;ec=25]] {{Replace this String concatenation with Text block.}} + String s3 = "" + // Noncompliant {{Replace this String concatenation with Text block.}} +// ^[el=+7;ec=24] " \n" + " " + 123 + diff --git a/java-checks-test-sources/default/src/main/java/checks/StringConcatenationInLoopCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/StringConcatenationInLoopCheckSample.java index 5da6dfddf53..53926389ef4 100644 --- a/java-checks-test-sources/default/src/main/java/checks/StringConcatenationInLoopCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/StringConcatenationInLoopCheckSample.java @@ -14,7 +14,7 @@ void method(String[] array, java.util.List list) { int i = 0; for (; i < 10; i++) { s = i + " : " + s; // Noncompliant {{Use a StringBuilder instead.}} - s += i;// Noncompliant {{Use a StringBuilder instead.}} + s += i; // Noncompliant {{Use a StringBuilder instead.}} inner.s1 = i + " : " + inner.s1; // Noncompliant {{Use a StringBuilder instead.}} } for (Object j : list) { diff --git a/java-checks-test-sources/default/src/main/java/checks/StringIndexOfRangesCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/StringIndexOfRangesCheckSample.java index b0089a21203..e0a504d6018 100644 --- a/java-checks-test-sources/default/src/main/java/checks/StringIndexOfRangesCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/StringIndexOfRangesCheckSample.java @@ -7,27 +7,35 @@ int foo(){ String hello = "Hello, world!"; int index = 0; - index += hello.indexOf('o', 11, 7); // Noncompliant [[sc=33;ec=35]] {{Begin index should not be larger than endIndex.}} + index += hello.indexOf('o', 11, 7); // Noncompliant {{Begin index should not be larger than endIndex.}} +// ^^ index += hello.indexOf('o', 7, 11); // Compliant - index += hello.indexOf('o', -1, 11); // Noncompliant [[sc=33;ec=35]] {{Begin index should be non-negative.}} + index += hello.indexOf('o', -1, 11); // Noncompliant {{Begin index should be non-negative.}} +// ^^ index += hello.indexOf('o', 0, 11); // Compliant - index += hello.indexOf("o", 11, 7); // Noncompliant [[sc=33;ec=35]] {{Begin index should not be larger than endIndex.}} + index += hello.indexOf("o", 11, 7); // Noncompliant {{Begin index should not be larger than endIndex.}} +// ^^ index += hello.indexOf("llo", 7, 11); // Compliant - index += hello.indexOf("world", -1, 11); // Noncompliant [[sc=37;ec=39]] {{Begin index should be non-negative.}} + index += hello.indexOf("world", -1, 11); // Noncompliant {{Begin index should be non-negative.}} +// ^^ index += hello.indexOf("!", 0, 11); // Compliant index += hello.indexOf("!", 0, hello.length()); // Compliant - index += "Hi".indexOf('i', 2, 3); // Noncompliant [[sc=32;ec=33]] {{Begin index should be smaller than the length of the string.}} - index += "Hi".indexOf('i', 0, 3); // Noncompliant [[sc=35;ec=36]] {{End index should be at most the length of the string.}} + index += "Hi".indexOf('i', 2, 3); // Noncompliant {{Begin index should be smaller than the length of the string.}} +// ^ + index += "Hi".indexOf('i', 0, 3); // Noncompliant {{End index should be at most the length of the string.}} +// ^ var i = 2; index += "Hi".indexOf('i', i, 2); // Compliant index += "Hi".indexOf('i', 0, i); // Compliant - index += hello.indexOf('o', 0, hello.length() + 1); // Noncompliant [[sc=36;ec=54]] {{End index should be at most the length of the string.}} - index += hello.indexOf('o', 0, 1 + hello.length()); // Noncompliant [[sc=36;ec=54]] {{End index should be at most the length of the string.}} + index += hello.indexOf('o', 0, hello.length() + 1); // Noncompliant {{End index should be at most the length of the string.}} +// ^^^^^^^^^^^^^^^^^^ + index += hello.indexOf('o', 0, 1 + hello.length()); // Noncompliant {{End index should be at most the length of the string.}} +// ^^^^^^^^^^^^^^^^^^ index += hello.indexOf('o', 0, hello.length() + 1 - 5 + 2 + 3); // Compliant index += hello.indexOf('o', 0, 1 + hello.length() + 1 - 2 + 5*4); // Compliant index += hello.indexOf('o', 0, hello.length() + i); // Compliant @@ -39,10 +47,12 @@ int foo(){ index += hello.indexOf('o', 215 - hello.length(), 0); // Compliant index += hello.indexOf('o', 0, hello.length() * hello.length()); // Compliant - index += hello.indexOf('o', hello.length() - 2, hello.length() - 5); // Noncompliant [[sc=33;ec=51]] {{Begin index should not be larger than endIndex.}} + index += hello.indexOf('o', hello.length() - 2, hello.length() - 5); // Noncompliant {{Begin index should not be larger than endIndex.}} +// ^^^^^^^^^^^^^^^^^^ index += hello.indexOf('o', hello.length() - 5, hello.length() - 2); // Compliant - index += hello.indexOf('o', hello.length(), hello.length() - 2); // Noncompliant [[sc=33;ec=47]] {{Begin index should be smaller than the length of the string.}} + index += hello.indexOf('o', hello.length(), hello.length() - 2); // Noncompliant {{Begin index should be smaller than the length of the string.}} +// ^^^^^^^^^^^^^^ index += hello.indexOf('o', hello.length() - 2, hello.hashCode() - 5); // Compliant index += hello.indexOf('o', 0, hello.hashCode() + 1); // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/StringLiteralDuplicatedCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/StringLiteralDuplicatedCheckSample.java index 0bee87c8efe..406d7363f3e 100644 --- a/java-checks-test-sources/default/src/main/java/checks/StringLiteralDuplicatedCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/StringLiteralDuplicatedCheckSample.java @@ -37,8 +37,10 @@ class ConstantAlreadyDefined { private static final String REPORT_WITHOUT_THRESHOLD = "blabla"; void test() { - System.out.println("constant"); // Noncompliant [[secondary=+1]] {{Use already-defined constant 'A' instead of duplicating its value here.}} + System.out.println("constant"); // Noncompliant {{Use already-defined constant 'A' instead of duplicating its value here.}} +// ^^^^^^^^^^ System.out.println("constant"); +// ^^^^^^^^^^< System.out.println("blabla"); // Noncompliant {{Use already-defined constant 'REPORT_WITHOUT_THRESHOLD' instead of duplicating its value here.}} } @@ -70,7 +72,7 @@ public Object key() { } class CompleteCoverage { - private final String notConstant = "blablah"; // Noncompliant {{Define a constant instead of duplicating this literal "blablah" 3 times.}} + private final String notConstant = "blablah"; // Noncompliant {{Define a constant instead of duplicating this literal "blablah" 3 times.}} private final String notConstant2 = "blablah"; static String notConstant3 = "blablah"; String notConstant4; diff --git a/java-checks-test-sources/default/src/main/java/checks/StringLiteralInsideEqualsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/StringLiteralInsideEqualsCheckSample.java index f4d8a94ff04..437f749869f 100644 --- a/java-checks-test-sources/default/src/main/java/checks/StringLiteralInsideEqualsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/StringLiteralInsideEqualsCheckSample.java @@ -3,14 +3,15 @@ public class StringLiteralInsideEqualsCheckSample { public String foo(String param, String foo, String bar) { - foo.equals("qux"); // Noncompliant [[sc=16;ec=21]] {{Move the "qux" string literal on the left side of this string comparison.}} + foo.equals("qux"); // Noncompliant {{Move the "qux" string literal on the left side of this string comparison.}} +// ^^^^^ "foo".equals(bar); foo.equals("bar".length()); foo.equalsIgnoreCase(""); // Noncompliant {{Move the "" string literal on the left side of this string comparison.}} foo("","","") .equals - (""); // Noncompliant + (""); // Noncompliant //coverage "foo".equals("bar"); // Compliant @@ -33,18 +34,21 @@ class Covrg { class StringLiteralInsideEqualsCheckSampleQF{ void goo(String foooo) { - foooo.equals("bar"); // Noncompliant [[sc=18;ec=23;quickfixes=qf1]] + foooo.equals("bar"); // Noncompliant [[quickfixes=qf1]] +// ^^^^^ // fix@qf1 {{Move "bar" on the left side of .equals}} // edit@qf1 [[sc=18;ec=23]] {{foooo}} // edit@qf1 [[sc=5;ec=10]] {{"bar"}} - foooo.equals("probably too long to put in context menu"); // Noncompliant [[sc=18;ec=60;quickfixes=qf2]] + foooo.equals("probably too long to put in context menu"); // Noncompliant [[quickfixes=qf2]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf2 {{Move "probably "... on the left side of .equals}} // edit@qf2 [[sc=18;ec=60]] {{foooo}} // edit@qf2 [[sc=5;ec=10]] {{"probably too long to put in context menu"}} - foooo.equalsIgnoreCase(""); // Noncompliant [[sc=28;ec=30;quickfixes=qf3]] + foooo.equalsIgnoreCase(""); // Noncompliant [[quickfixes=qf3]] +// ^^ // fix@qf3 {{Move "" on the left side of .equals}} // edit@qf3 [[sc=28;ec=30]] {{foooo}} // edit@qf3 [[sc=5;ec=10]] {{""}} @@ -52,7 +56,8 @@ void goo(String foooo) { foo() .bar(). equals - (""); // Noncompliant [[sc=6;ec=8;quickfixes=qf4]] + (""); // Noncompliant [[quickfixes=qf4]] +// ^^ // fix@qf4 {{Move "" on the left side of .equals}} // edit@qf4 [[sc=6;ec=8]] {{foo()\n .bar()}} // edit@qf4 [[sl=-3;el=-2;sc=5;ec=11]] {{""}} @@ -60,7 +65,8 @@ void goo(String foooo) { } boolean doesNotHaveWings(String s, boolean isMammal, boolean exp) { - return (isMammal && s != null && s.equals("bat")) ? false : exp; // Noncompliant [[sc=47;ec=52;quickfixes=qf5]] + return (isMammal && s != null && s.equals("bat")) ? false : exp; // Noncompliant [[quickfixes=qf5]] +// ^^^^^ // fix@qf5 {{Move "bat" on the left side of .equals}} // edit@qf5 [[sc=47;ec=52]] {{s}} // edit@qf5 [[sc=38;ec=39]] {{"bat"}} @@ -76,4 +82,4 @@ public String bar() { } } -} \ No newline at end of file +} diff --git a/java-checks-test-sources/default/src/main/java/checks/StringMethodsWithLocaleCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/StringMethodsWithLocaleCheckSample.java index ebbde22efe9..44e6a6b9934 100644 --- a/java-checks-test-sources/default/src/main/java/checks/StringMethodsWithLocaleCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/StringMethodsWithLocaleCheckSample.java @@ -8,7 +8,8 @@ class StringMethodsWithLocaleCheckSample { void foo(java.util.Date date) { String myString =""; - myString.toLowerCase(); // Noncompliant [[sc=14;ec=25]] + myString.toLowerCase(); // Noncompliant +// ^^^^^^^^^^^ myString.toUpperCase(); // Noncompliant myString.toLowerCase(java.util.Locale.US); myString.toUpperCase(java.util.Locale.US); @@ -19,9 +20,11 @@ void foo(java.util.Date date) { format("foo"); // Compliant // dates - myString.format("%t", date); // Noncompliant [[sc=14;ec=20]] + myString.format("%t", date); // Noncompliant +// ^^^^^^ myString.format(java.util.Locale.US, "%T", date); // Compliant - format("%t" + 42, date); // Noncompliant [[sc=5;ec=11]] + format("%t" + 42, date); // Noncompliant +// ^^^^^^ format("%1$tDc", date); // Noncompliant // integer values : only when comma is used diff --git a/java-checks-test-sources/default/src/main/java/checks/StringOffsetMethodsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/StringOffsetMethodsCheckSample.java index 2857e8baa95..83c0b4091d6 100644 --- a/java-checks-test-sources/default/src/main/java/checks/StringOffsetMethodsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/StringOffsetMethodsCheckSample.java @@ -3,21 +3,26 @@ class StringOffsetMethodsCheckSample { String field; void test(String str, char char1, int beginIndex, String str2) { - str.substring(beginIndex).indexOf(char1); // Noncompliant [[sc=9;ec=45]] {{Replace "indexOf" with the overload that accepts an offset parameter.}} + str.substring(beginIndex).indexOf(char1); // Noncompliant {{Replace "indexOf" with the overload that accepts an offset parameter.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ str.indexOf(char1, beginIndex); this.field.indexOf(char1); this.fun().indexOf(char1); - str.substring(beginIndex).indexOf(str2); // Noncompliant [[sc=9;ec=44]] + str.substring(beginIndex).indexOf(str2); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ str.indexOf(str2, beginIndex); - str.substring(beginIndex).lastIndexOf(char1); // Noncompliant [[sc=9;ec=49]] + str.substring(beginIndex).lastIndexOf(char1); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ str.lastIndexOf(char1, beginIndex); - str.substring(beginIndex).lastIndexOf(str2); // Noncompliant [[sc=9;ec=48]] {{Replace "lastIndexOf" with the overload that accepts an offset parameter.}} + str.substring(beginIndex).lastIndexOf(str2); // Noncompliant {{Replace "lastIndexOf" with the overload that accepts an offset parameter.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ str.lastIndexOf(str2, beginIndex); - str.substring(beginIndex).startsWith(str2); // Noncompliant [[sc=9;ec=47]] {{Replace "startsWith" with the overload that accepts an offset parameter.}} + str.substring(beginIndex).startsWith(str2); // Noncompliant {{Replace "startsWith" with the overload that accepts an offset parameter.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ str.startsWith(str2, beginIndex); } String fun() {return "";} diff --git a/java-checks-test-sources/default/src/main/java/checks/StringPrimitiveConstructorCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/StringPrimitiveConstructorCheckSample.java index 0659f77b380..ea0fa98c131 100644 --- a/java-checks-test-sources/default/src/main/java/checks/StringPrimitiveConstructorCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/StringPrimitiveConstructorCheckSample.java @@ -6,18 +6,27 @@ class StringPrimitiveConstructorCheckSample { void bar(char[] chars, String str) { - String empty = new String(); // Noncompliant [[sc=24;ec=30]] {{Remove this "String" constructor}} + String empty = new String(); // Noncompliant {{Remove this "String" constructor}} +// ^^^^^^ String nonempty = new String("Hello world"); // Noncompliant nonempty = new String(chars); - Double myDouble = new Double(1.1); // Noncompliant [[sc=27;ec=33]] {{Remove this "Double" constructor}} - Integer integer = new Integer(1); // Noncompliant [[sc=27;ec=34]] {{Remove this "Integer" constructor}} - Boolean bool = new Boolean(true); // Noncompliant [[sc=24;ec=31]] {{Remove this "Boolean" constructor}} - Character myChar = new Character('c'); // Noncompliant [[sc=28;ec=37]] {{Remove this "Character" constructor}} - Long myLong = new Long(1L); // Noncompliant [[sc=23;ec=27]] {{Remove this "Long" constructor}} + Double myDouble = new Double(1.1); // Noncompliant {{Remove this "Double" constructor}} +// ^^^^^^ + Integer integer = new Integer(1); // Noncompliant {{Remove this "Integer" constructor}} +// ^^^^^^^ + Boolean bool = new Boolean(true); // Noncompliant {{Remove this "Boolean" constructor}} +// ^^^^^^^ + Character myChar = new Character('c'); // Noncompliant {{Remove this "Character" constructor}} +// ^^^^^^^^^ + Long myLong = new Long(1L); // Noncompliant {{Remove this "Long" constructor}} +// ^^^^ byte b = 0; - Byte myByte = new Byte(b); // Noncompliant [[sc=23;ec=27]] {{Remove this "Byte" constructor}} - Short myShort = new Short((short) 0); // Noncompliant [[sc=25;ec=30]] {{Remove this "Short" constructor}} - Float myFloat = new Float(1.0f); // Noncompliant [[sc=25;ec=30]] {{Remove this "Float" constructor}} + Byte myByte = new Byte(b); // Noncompliant {{Remove this "Byte" constructor}} +// ^^^^ + Short myShort = new Short((short) 0); // Noncompliant {{Remove this "Short" constructor}} +// ^^^^^ + Float myFloat = new Float(1.0f); // Noncompliant {{Remove this "Float" constructor}} +// ^^^^^ BigInteger bigInteger0 = new BigInteger(str); BigInteger bigInteger1 = new BigInteger("1"); // Noncompliant {{Remove this "BigInteger" constructor}} BigInteger bigInteger2 = new BigInteger("9223372036854775807"); // Noncompliant @@ -52,52 +61,64 @@ void foo() { class QuickFixes { - String empty = new String(); // Noncompliant [[sc=22;ec=28;quickfixes=qf1]] + String empty = new String(); // Noncompliant [[quickfixes=qf1]] +// ^^^^^^ // fix@qf1 {{Replace this "String" constructor with an empty string ""}} // edit@qf1 [[sc=18;ec=30]] {{""}} - String nonempty = new String("Hello world"); // Noncompliant [[sc=25;ec=31;quickfixes=qf2]] + String nonempty = new String("Hello world"); // Noncompliant [[quickfixes=qf2]] +// ^^^^^^ // fix@qf2 {{Replace this "String" constructor with the string literal passed as parameter}} // edit@qf2 [[sc=21;ec=46]] {{"Hello world"}} - Double myDouble = new Double(1.1); // Noncompliant [[sc=25;ec=31;quickfixes=qf3]] + Double myDouble = new Double(1.1); // Noncompliant [[quickfixes=qf3]] +// ^^^^^^ // fix@qf3 {{Replace this "Double" constructor with the double literal passed as parameter}} // edit@qf3 [[sc=21;ec=36]] {{1.1}} - Integer integer = new Integer(1); // Noncompliant [[sc=25;ec=32;quickfixes=qf4]] + Integer integer = new Integer(1); // Noncompliant [[quickfixes=qf4]] +// ^^^^^^^ // fix@qf4 {{Replace this "Integer" constructor with the int literal passed as parameter}} // edit@qf4 [[sc=21;ec=35]] {{1}} - Boolean bool = new Boolean(true); // Noncompliant [[sc=22;ec=29;quickfixes=qf5]] + Boolean bool = new Boolean(true); // Noncompliant [[quickfixes=qf5]] +// ^^^^^^^ // fix@qf5 {{Replace this "Boolean" constructor with the boolean literal passed as parameter}} // edit@qf5 [[sc=18;ec=35]] {{true}} - Character myChar = new Character('c'); // Noncompliant [[sc=26;ec=35;quickfixes=qf6]] + Character myChar = new Character('c'); // Noncompliant [[quickfixes=qf6]] +// ^^^^^^^^^ // fix@qf6 {{Replace this "Character" constructor with the char literal passed as parameter}} // edit@qf6 [[sc=22;ec=40]] {{'c'}} - Long myLong = new Long(1L); // Noncompliant [[sc=21;ec=25;quickfixes=qf7]] + Long myLong = new Long(1L); // Noncompliant [[quickfixes=qf7]] +// ^^^^ // fix@qf7 {{Replace this "Long" constructor with the long literal passed as parameter}} // edit@qf7 [[sc=17;ec=29]] {{1L}} byte b = 0; - Byte myByte = new Byte(b); // Noncompliant [[sc=21;ec=25;quickfixes=qf8]] + Byte myByte = new Byte(b); // Noncompliant [[quickfixes=qf8]] +// ^^^^ // fix@qf8 {{Replace this "Byte" constructor with the byte literal passed as parameter}} // edit@qf8 [[sc=17;ec=28]] {{b}} - Short myShort = new Short((short) 0); // Noncompliant [[sc=23;ec=28;quickfixes=qf9]] + Short myShort = new Short((short) 0); // Noncompliant [[quickfixes=qf9]] +// ^^^^^ // fix@qf9 {{Replace this "Short" constructor with the short literal passed as parameter}} // edit@qf9 [[sc=19;ec=39]] {{(short) 0}} - Float myFloat = new Float(1.0f); // Noncompliant [[sc=23;ec=28;quickfixes=qf10]] + Float myFloat = new Float(1.0f); // Noncompliant [[quickfixes=qf10]] +// ^^^^^ // fix@qf10 {{Replace this "Float" constructor with the float literal passed as parameter}} // edit@qf10 [[sc=19;ec=34]] {{1.0f}} - BigInteger bigInteger1 = new BigInteger("1"); // Noncompliant [[sc=32;ec=42;quickfixes=qf11]] + BigInteger bigInteger1 = new BigInteger("1"); // Noncompliant [[quickfixes=qf11]] +// ^^^^^^^^^^ // fix@qf11 {{Replace this "BigInteger" constructor with "BigInteger.valueOf()" static method}} // edit@qf11 [[sc=28;ec=47]] {{BigInteger.valueOf(1L)}} - BigInteger bigInteger2 = new BigInteger("9223372036854775807"); // Noncompliant [[sc=32;ec=42;quickfixes=qf12]] + BigInteger bigInteger2 = new BigInteger("9223372036854775807"); // Noncompliant [[quickfixes=qf12]] +// ^^^^^^^^^^ // fix@qf12 {{Replace this "BigInteger" constructor with "BigInteger.valueOf()" static method}} // edit@qf12 [[sc=28;ec=65]] {{BigInteger.valueOf(9223372036854775807L)}} } diff --git a/java-checks-test-sources/default/src/main/java/checks/StringToPrimitiveConversionCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/StringToPrimitiveConversionCheckSample.java index af0710ed1f2..93016971fc6 100644 --- a/java-checks-test-sources/default/src/main/java/checks/StringToPrimitiveConversionCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/StringToPrimitiveConversionCheckSample.java @@ -4,7 +4,8 @@ class StringToPrimitiveConversionCheckSample { void ints(Integer integerParam) { - int i1 = new Integer("42").intValue(); // Noncompliant [[sc=14;ec=31]] {{Use "Integer.parseInt" for this string-to-int conversion.}} + int i1 = new Integer("42").intValue(); // Noncompliant {{Use "Integer.parseInt" for this string-to-int conversion.}} +// ^^^^^^^^^^^^^^^^^ new Integer("42").intValue(); // Noncompliant int i2 = new Integer("42"); // Noncompliant int i3 = Integer.valueOf("42").intValue(); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/StringToString.java b/java-checks-test-sources/default/src/main/java/checks/StringToString.java index 25817f39e93..eab30177560 100644 --- a/java-checks-test-sources/default/src/main/java/checks/StringToString.java +++ b/java-checks-test-sources/default/src/main/java/checks/StringToString.java @@ -14,22 +14,26 @@ InnerClass inner() { InnerClass inner; - String string = "hello".toString(); // Noncompliant [[sc=19;ec=26]] {{there's no need to call "toString()" on a string literal.}} + String string = "hello".toString(); // Noncompliant {{there's no need to call "toString()" on a string literal.}} +// ^^^^^^^ Object object = new Object(); public void method() { object.toString(); // Compliant new Object().toString(); // Compliant - ((String) object).toString(); // Noncompliant [[sc=15;ec=21]] {{"object" is already a string, there's no need to call "toString()" on it.}} - array[0].toString(); // Noncompliant [[sc=5;ec=10]] {{"array" is an array of strings, there's no need to call "toString()".}} + ((String) object).toString(); // Noncompliant {{"object" is already a string, there's no need to call "toString()" on it.}} +// ^^^^^^ + array[0].toString(); // Noncompliant {{"array" is an array of strings, there's no need to call "toString()".}} +// ^^^^^ string.toString(); // Noncompliant {{"string" is already a string, there's no need to call "toString()" on it.}} string.toUpperCase().toString(); // Noncompliant {{"toUpperCase" returns a string, there's no need to call "toString()".}} this.inner.field.toString(); // Noncompliant {{"field" is already a string, there's no need to call "toString()" on it.}} toString(); // Compliant - foo()[0].toString(); // Noncompliant [[sc=5;ec=10]] {{There's no need to call "toString()" on an array of String.}} + foo()[0].toString(); // Noncompliant {{There's no need to call "toString()" on an array of String.}} +// ^^^^^ bar()[0][0].toString(); // Noncompliant {{There's no need to call "toString()" on an array of String.}} (object.equals("") ? "a" : "b").toString(); // Compliant, FN, report only clear issues @@ -39,27 +43,33 @@ public void method() { String[][] bar() {return null;} void quickFixes() { - String string = "hello".toString(); // Noncompliant [[sc=21;ec=28;quickfixes=qf1]] + String string = "hello".toString(); // Noncompliant [[quickfixes=qf1]] +// ^^^^^^^ // fix@qf1 {{Remove "toString()"}} // edit@qf1 [[sc=28;ec=39]] {{}} - string.toUpperCase().toString(); // Noncompliant [[sc=12;ec=23;quickfixes=qf2]] + string.toUpperCase().toString(); // Noncompliant [[quickfixes=qf2]] +// ^^^^^^^^^^^ // fix@qf2 {{Remove "toString()"}} // edit@qf2 [[sc=25;ec=36]] {{}} - string = string.toString().toUpperCase(); // Noncompliant [[sc=14;ec=20;quickfixes=qf3]] + string = string.toString().toUpperCase(); // Noncompliant [[quickfixes=qf3]] +// ^^^^^^ // fix@qf3 {{Remove "toString()"}} // edit@qf3 [[sc=20;ec=31]] {{}} - foo()[0].toString(); // Noncompliant [[sc=5;ec=10;quickfixes=qf4]] + foo()[0].toString(); // Noncompliant [[quickfixes=qf4]] +// ^^^^^ // fix@qf4 {{Remove "toString()"}} // edit@qf4 [[sc=13;ec=24]] {{}} - ((String) object).toString(); // Noncompliant [[sc=15;ec=21;quickfixes=qf5]] + ((String) object).toString(); // Noncompliant [[quickfixes=qf5]] +// ^^^^^^ // fix@qf5 {{Remove "toString()"}} // edit@qf5 [[sc=22;ec=33]] {{}} - string = ((string)).toString(); // Noncompliant [[sc=16;ec=22;quickfixes=qf6]] + string = ((string)).toString(); // Noncompliant [[quickfixes=qf6]] +// ^^^^^^ // fix@qf6 {{Remove "toString()"}} // edit@qf6 [[sc=24;ec=35]] {{}} } diff --git a/java-checks-test-sources/default/src/main/java/checks/StrongCipherAlgorithmCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/StrongCipherAlgorithmCheckSample.java index 33c5456e1da..4cc7f8aa1cc 100644 --- a/java-checks-test-sources/default/src/main/java/checks/StrongCipherAlgorithmCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/StrongCipherAlgorithmCheckSample.java @@ -16,11 +16,13 @@ class StrongCipherAlgorithmCheckSample { private final static String DES = "DES"; void foo() throws NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException { - Cipher.getInstance("DESede/ECB/PKCS5Padding"); // Noncompliant [[sc=24;ec=49]] {{Use a strong cipher algorithm.}} - Cipher.getInstance("DES/ECB/PKCS5Padding");// Noncompliant + Cipher.getInstance("DESede/ECB/PKCS5Padding"); // Noncompliant {{Use a strong cipher algorithm.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^ + Cipher.getInstance("DES/ECB/PKCS5Padding"); // Noncompliant Cipher.getInstance("RC2/ECB/PKCS5Padding"); // Noncompliant Cipher.getInstance("AES/GCM/NoPadding");//Compliant - new NullCipher(); // Noncompliant [[sc=9;ec=19]] {{Use a strong cipher algorithm.}} + new NullCipher(); // Noncompliant {{Use a strong cipher algorithm.}} +// ^^^^^^^^^^ new javax.crypto.NullCipher(); // Noncompliant new MyCipher(); diff --git a/java-checks-test-sources/default/src/main/java/checks/SubClassStaticReferenceCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/SubClassStaticReferenceCheckSample.java index 4ce43f4fe9e..b9f37c1296a 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SubClassStaticReferenceCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/SubClassStaticReferenceCheckSample.java @@ -2,7 +2,8 @@ class ParentS2390 { static final Class IMPL = ChildS2390.class; // Compliant - static int childVersion1 = ChildS2390.version; // Noncompliant [[sc=30;ec=40]] {{Remove this reference to "ChildS2390".}} + static int childVersion1 = ChildS2390.version; // Noncompliant {{Remove this reference to "ChildS2390".}} +// ^^^^^^^^^^ static int childVersion2 = ChildS2390.getVersion(); // Noncompliant static ChildS2390 value; static { diff --git a/java-checks-test-sources/default/src/main/java/checks/SuspiciousListRemove.java b/java-checks-test-sources/default/src/main/java/checks/SuspiciousListRemove.java index 4aa0889bcfd..b6a319b2f1c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SuspiciousListRemove.java +++ b/java-checks-test-sources/default/src/main/java/checks/SuspiciousListRemove.java @@ -12,7 +12,7 @@ void removeFrom(List list) { for (int i = 0; i < list.size(); i++) { if (list.get(i).isEmpty()) { // actual: remaining elements are shifted, so the one immediately following will be skipped - list.remove(i); // Noncompliant {{Verify that "remove()" is used correctly.}} + list.remove(i); // Noncompliant {{Verify that "remove()" is used correctly.}} } } } @@ -89,7 +89,7 @@ List controlFlowReturn3(List list) { List deleted = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { if (list.get(i).isEmpty()) { - deleted.add(list.remove(i)); // Noncompliant + deleted.add(list.remove(i)); // Noncompliant } } return deleted; // "return" is outside the loop diff --git a/java-checks-test-sources/default/src/main/java/checks/SwitchCaseTooBigCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/SwitchCaseTooBigCheckSample.java index eafcacfdaae..e1c5afc74c1 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SwitchCaseTooBigCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/SwitchCaseTooBigCheckSample.java @@ -9,7 +9,8 @@ void f(int myVariable) { System.out.println(); // 3 System.out.println(); // 4 System.out.println(); // 5 - case 1: // Noncompliant [[sc=7;ec=14]] {{Reduce this switch case number of lines from 7 to at most 5, for example by extracting code into methods.}} + case 1: // Noncompliant {{Reduce this switch case number of lines from 7 to at most 5, for example by extracting code into methods.}} +// ^^^^^^^ System.out.println(); // 1 System.out.println(); // 2 System.out.println(); // 3 @@ -17,7 +18,7 @@ void f(int myVariable) { System.out.println(); // 5 System.out.println(); // 6 break; // 7 - case 2: { System.out.println(); // Noncompliant 1 + case 2: { System.out.println(); // Noncompliant System.out.println(); // 2 System.out.println(); // 3 System.out.println(); // 4 diff --git a/java-checks-test-sources/default/src/main/java/checks/SwitchCasesShouldBeCommaSeparatedCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/SwitchCasesShouldBeCommaSeparatedCheckSample.java index 128fb3bf78e..094147790f4 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SwitchCasesShouldBeCommaSeparatedCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/SwitchCasesShouldBeCommaSeparatedCheckSample.java @@ -9,7 +9,9 @@ public void nonCompliant(String mode) { doSomething(); break; case "b": - case "c": // Noncompliant [[sc=7;ec=16;secondary=-1]] {{Merge the previous cases into this one using comma-separated label.}} +// ^^^^^^^^^> + case "c": // Noncompliant {{Merge the previous cases into this one using comma-separated label.}} +// ^^^^^^^^^ doSomething(); doSomethingElse(); break; @@ -20,12 +22,17 @@ public void nonCompliant(String mode) { // Switch Statement with multiple issues switch (mode) { case "a": +// ^^^^^^^^^> case "b": - case "c": // Noncompliant [[sc=7;ec=16;secondary=-1,-2]] {{Merge the previous cases into this one using comma-separated label.}} +// ^^^^^^^^^> + case "c": // Noncompliant {{Merge the previous cases into this one using comma-separated label.}} +// ^^^^^^^^^ doSomething(); break; case "d": - case "e": // Noncompliant [[sc=7;ec=16;secondary=-1]] {{Merge the previous cases into this one using comma-separated label.}} +// ^^^^^^^^^> + case "e": // Noncompliant {{Merge the previous cases into this one using comma-separated label.}} +// ^^^^^^^^^ default: doSomethingElse(); } diff --git a/java-checks-test-sources/default/src/main/java/checks/SwitchDefaultLastCaseCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/SwitchDefaultLastCaseCheckSample.java index 1166f634864..5081534408c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SwitchDefaultLastCaseCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/SwitchDefaultLastCaseCheckSample.java @@ -5,7 +5,8 @@ class SwitchDefaultLastCaseCheckSample { void foo() { switch (0) { case 0: - default: // Noncompliant [[sc=7;ec=15]] {{Move this default to the end of the switch.}} + default: // Noncompliant {{Move this default to the end of the switch.}} +// ^^^^^^^^ break; case 1: break; diff --git a/java-checks-test-sources/default/src/main/java/checks/SwitchInsteadOfIfSequenceCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/SwitchInsteadOfIfSequenceCheckSample.java index 667c5dceee5..bfd14b1d1ae 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SwitchInsteadOfIfSequenceCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/SwitchInsteadOfIfSequenceCheckSample.java @@ -8,7 +8,8 @@ String myStringMethod(){ return ""; } void foo() { - if ("red".equals(choice)) { // Noncompliant [[sc=9;ec=29]] {{Convert this "if/else if" structure into a "switch". (sonar.java.source not set. Assuming 7 or greater.)}} + if ("red".equals(choice)) { // Noncompliant {{Convert this "if/else if" structure into a "switch". (sonar.java.source not set. Assuming 7 or greater.)}} +// ^^^^^^^^^^^^^^^^^^^^ dispenseRed(); } else if ("blue".equals(choice)) { dispenseBlue(); @@ -32,7 +33,8 @@ private void dispenseRed() { } void foobis() { - if ("red" == choice) { // Noncompliant [[sc=9;ec=24]] {{Convert this "if/else if" structure into a "switch". (sonar.java.source not set. Assuming 7 or greater.)}} + if ("red" == choice) { // Noncompliant {{Convert this "if/else if" structure into a "switch". (sonar.java.source not set. Assuming 7 or greater.)}} +// ^^^^^^^^^^^^^^^ dispenseRed(); } else if ("blue" == choice) { dispenseBlue(); @@ -55,7 +57,7 @@ void foo2() { } void foo3() { - if ("red".equals(choice)) { // Noncompliant {{Convert this "if/else if" structure into a "switch". (sonar.java.source not set. Assuming 7 or greater.)}} + if ("red".equals(choice)) { // Noncompliant {{Convert this "if/else if" structure into a "switch". (sonar.java.source not set. Assuming 7 or greater.)}} dispenseRed(); } else if (choice.equals("blue")) { dispenseBlue(); @@ -122,7 +124,7 @@ void foo6() { } void no_else_statement() { - if ("red".equals(choice)) { // Noncompliant + if ("red".equals(choice)) { // Noncompliant dispenseRed(); } else if ("blue".equals(choice)) { dispenseBlue(); diff --git a/java-checks-test-sources/default/src/main/java/checks/SwitchLastCaseIsDefaultCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/SwitchLastCaseIsDefaultCheckSample.java index 194f95a4b4c..dbd765ca05f 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SwitchLastCaseIsDefaultCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/SwitchLastCaseIsDefaultCheckSample.java @@ -12,7 +12,8 @@ void foo(MyEnum myEnum, DayOfWeek dow) { break; } - switch (0) { // Noncompliant [[sc=5;ec=11]] {{Add a default case to this switch.}} + switch (0) { // Noncompliant {{Add a default case to this switch.}} +// ^^^^^^ } switch (0) { // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/SwitchRedundantKeywordCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/SwitchRedundantKeywordCheckSample.java index 9b2437c81b9..257f8d79f8e 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SwitchRedundantKeywordCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/SwitchRedundantKeywordCheckSample.java @@ -5,8 +5,11 @@ public class SwitchRedundantKeywordCheckSample { int switchExpression(String mode) { int nonCompliant = switch (mode) { case "a" -> { - yield 1; // Noncompliant [[sc=9;ec=14;secondary=-1,+1]] {{Remove this redundant block and "yield".}} +// ^> + yield 1; // Noncompliant {{Remove this redundant block and "yield".}} +// ^^^^^ } +// ^< default -> { yield 2; // Noncompliant {{Remove this redundant block and "yield".}} } @@ -67,9 +70,12 @@ int switchStatement(String mode) { switch (mode) { case "a" -> { +// ^> result = 1; - break; // Noncompliant [[sc=9;ec=15;secondary=-2,+1]] {{Remove this redundant block and "break".}} + break; // Noncompliant {{Remove this redundant block and "break".}} +// ^^^^^^ } +// ^< case "b" -> { result = 2; break; // Noncompliant {{Remove this redundant block and "break".}} @@ -77,7 +83,8 @@ int switchStatement(String mode) { default -> { doSomethingElse(); result = 3; - break; // Noncompliant [[sc=9;ec=15]] {{Remove this redundant "break".}} + break; // Noncompliant {{Remove this redundant "break".}} +// ^^^^^^ } } @@ -94,9 +101,11 @@ int switchStatement(String mode) { switch (mode) { case "a" -> result = 1; // Compliant - case "b" -> { // Noncompliant [[sc=19;ec=20;secondary=+2]] {{Remove this redundant block.}} + case "b" -> { // Noncompliant {{Remove this redundant block.}} +// ^ result = 2; } +// ^< case "c" -> { // Compliant, probably not the best code, but no choice to add an empty block if you want a case that does nothing. } default -> { // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/SwitchWithTooManyCasesCheckCustom.java b/java-checks-test-sources/default/src/main/java/checks/SwitchWithTooManyCasesCheckCustom.java index d67e9c27694..cf48de16037 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SwitchWithTooManyCasesCheckCustom.java +++ b/java-checks-test-sources/default/src/main/java/checks/SwitchWithTooManyCasesCheckCustom.java @@ -2,7 +2,8 @@ class SwitchWithTooManyCasesCheckCustom { void foo() { - switch (1) { // Noncompliant [[sc=5;ec=11]] {{Reduce the number of non-empty switch cases from 35 to at most 5.}} + switch (1) { // Noncompliant {{Reduce the number of non-empty switch cases from 35 to at most 5.}} +// ^^^^^^ case 1: System.out.println(""); case 2: @@ -79,18 +80,25 @@ void foo() { default: System.out.println(""); } - switch (1) { // Noncompliant [[secondary=+1,+3,+5,+7,+9,+11]] + switch (1) { // Noncompliant + //^^^^^^ case 1: +// ^^^^^^^< break; case 2: +// ^^^^^^^< break; case 3: +// ^^^^^^^< System.out.println(""); case 4: +// ^^^^^^^< break; case 5: +// ^^^^^^^< break; case 6: +// ^^^^^^^< case 7: System.out.println(""); } diff --git a/java-checks-test-sources/default/src/main/java/checks/SwitchWithTooManyCasesCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/SwitchWithTooManyCasesCheckSample.java index c8cb6dfc728..2086e6fb161 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SwitchWithTooManyCasesCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/SwitchWithTooManyCasesCheckSample.java @@ -2,7 +2,8 @@ class SwitchWithTooManyCasesCheckSample { void foo() { - switch (1) { // Noncompliant [[sc=5;ec=11]] {{Reduce the number of non-empty switch cases from 35 to at most 30.}} + switch (1) { // Noncompliant {{Reduce the number of non-empty switch cases from 35 to at most 30.}} +// ^^^^^^ case 1: System.out.println(""); case 2: diff --git a/java-checks-test-sources/default/src/main/java/checks/SyncGetterAndSetterCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/SyncGetterAndSetterCheckSample.java index 357b7dde765..d19162651c7 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SyncGetterAndSetterCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/SyncGetterAndSetterCheckSample.java @@ -12,11 +12,11 @@ public synchronized void setName(String name) { this.name = name; } - public String getName() { // Noncompliant + public String getName() { // Noncompliant return this.name; } - public void setAge(int age) { // Noncompliant + public void setAge(int age) { // Noncompliant this.age = age; } @@ -129,4 +129,4 @@ public boolean isYoung() { // Noncompliant public synchronized void setYoung(boolean young) { this.young = young; } -} \ No newline at end of file +} diff --git a/java-checks-test-sources/default/src/main/java/checks/SynchronizationOnStringOrBoxedCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/SynchronizationOnStringOrBoxedCheckSample.java index cb7957c06b0..0e2cf810259 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SynchronizationOnStringOrBoxedCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/SynchronizationOnStringOrBoxedCheckSample.java @@ -22,28 +22,29 @@ public class SynchronizationOnStringOrBoxedCheckSample { void method1() { - synchronized(bLock) { // Noncompliant [[sc=18;ec=23]] {{Synchronize on a new "Object" instead.}} + synchronized(bLock) { // Noncompliant {{Synchronize on a new "Object" instead.}} +// ^^^^^ // ... } - synchronized(iLock) { // Noncompliant + synchronized(iLock) { // Noncompliant // ... } - synchronized(sLock) { // Noncompliant + synchronized(sLock) { // Noncompliant // ... } - synchronized(opLock) { // Noncompliant + synchronized(opLock) { // Noncompliant // ... } - synchronized(opIntLock) { // Noncompliant + synchronized(opIntLock) { // Noncompliant // ... } - synchronized(opLongLock) { // Noncompliant + synchronized(opLongLock) { // Noncompliant // ... } - synchronized(opDoubleLock) { // Noncompliant + synchronized(opDoubleLock) { // Noncompliant // ... } - synchronized(zoneId) { // Noncompliant + synchronized(zoneId) { // Noncompliant // ... } synchronized(oLock) { diff --git a/java-checks-test-sources/default/src/main/java/checks/SynchronizedClassUsageCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/SynchronizedClassUsageCheckSample.java index 38e25d0c4d4..be32fe087bb 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SynchronizedClassUsageCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/SynchronizedClassUsageCheckSample.java @@ -14,30 +14,35 @@ public class SynchronizedClassUsageCheckSample { public SynchronizedClassUsageCheckSample() {} interface IA { - // Noncompliant@+2 {{Replace the synchronized class "Vector" by an unsynchronized one such as "ArrayList" or "LinkedList".}} - // Noncompliant@+1 {{Replace the synchronized class "Vector" by an unsynchronized one such as "ArrayList" or "LinkedList".}} + // Noncompliant@+2 {{Replace the synchronized class "Vector" by an unsynchronized one such as "ArrayList" or "LinkedList".}} + // Noncompliant@+1 {{Replace the synchronized class "Vector" by an unsynchronized one such as "ArrayList" or "LinkedList".}} Vector f3(Vector a); } class A implements IA { - List a = new Vector(); // Noncompliant [[sc=14;ec=26]] {{Replace the synchronized class "Vector" by an unsynchronized one such as "ArrayList" or "LinkedList".}} - // Noncompliant@+2 [[sc=5;ec=11]] {{Replace the synchronized class "Vector" by an unsynchronized one such as "ArrayList" or "LinkedList".}} - // Noncompliant@+1 [[sc=17;ec=29]] {{Replace the synchronized class "Vector" by an unsynchronized one such as "ArrayList" or "LinkedList".}} - Vector a1 = new Vector(); - // Noncompliant@+2 [[sc=5;ec=14]] {{Replace the synchronized class "Hashtable" by an unsynchronized one such as "HashMap".}} - // Noncompliant@+1 [[sc=20;ec=35]] {{Replace the synchronized class "Hashtable" by an unsynchronized one such as "HashMap".}} - Hashtable a2 = new Hashtable(); - Map a3 = new Hashtable(); // Noncompliant {{Replace the synchronized class "Hashtable" by an unsynchronized one such as "HashMap".}} - Hashtable a4 = foo(); // Noncompliant {{Replace the synchronized class "Hashtable" by an unsynchronized one such as "HashMap".}} + List a = new Vector(); // Noncompliant {{Replace the synchronized class "Vector" by an unsynchronized one such as "ArrayList" or "LinkedList".}} +// ^^^^^^^^^^^^ + +// Noncompliant@+1 + Vector a1 = new Vector(); // Noncompliant +// ^^^^^^ + + +// Noncompliant@+1 + Hashtable a2 = new Hashtable(); // Noncompliant + + Map a3 = new Hashtable(); // Noncompliant {{Replace the synchronized class "Hashtable" by an unsynchronized one such as "HashMap".}} + Hashtable a4 = foo(); // Noncompliant {{Replace the synchronized class "Hashtable" by an unsynchronized one such as "HashMap".}} HashMap a5 = new HashMap(); // Compliant ArrayList a6 = new ArrayList(); // Compliant - Vector a7; // Noncompliant {{Replace the synchronized class "Vector" by an unsynchronized one such as "ArrayList" or "LinkedList".}} - // Noncompliant@+2 [[sc=5;ec=17]] {{Replace the synchronized class "StringBuffer" by an unsynchronized one such as "StringBuilder".}} - // Noncompliant@+1 [[sc=23;ec=41]] {{Replace the synchronized class "StringBuffer" by an unsynchronized one such as "StringBuilder".}} - StringBuffer a8 = new StringBuffer(); - // Noncompliant@+2 [[sc=5;ec=20]] {{Replace the synchronized class "Stack" by an unsynchronized one such as "Deque".}} - // Noncompliant@+1 [[sc=26;ec=47]] {{Replace the synchronized class "Stack" by an unsynchronized one such as "Deque".}} - java.util.Stack a9 = new java.util.Stack(); + Vector a7; // Noncompliant {{Replace the synchronized class "Vector" by an unsynchronized one such as "ArrayList" or "LinkedList".}} + +// Noncompliant@+1 + StringBuffer a8 = new StringBuffer(); // Noncompliant + +// Noncompliant@+1 + java.util.Stack a9 = new java.util.Stack(); // Noncompliant + List l = null; // Compliant List listeners = getVector(); // Compliant @@ -57,7 +62,8 @@ private void f() { List result2 = new java.util.Vector(); // Noncompliant } - private Vector getVector() { // Noncompliant [[sc=13;ec=19]]{{Replace the synchronized class "Vector" by an unsynchronized one such as "ArrayList" or "LinkedList".}} + private Vector getVector() { // Noncompliant {{Replace the synchronized class "Vector" by an unsynchronized one such as "ArrayList" or "LinkedList".}} +// ^^^^^^ return new Vector(); } @@ -67,7 +73,8 @@ public java.util.Stack f2() { // Noncompliant {{Replace the synchronized class " return null; } - public void f(Vector a) { // Noncompliant [[sc=19;ec=25]] {{Replace the synchronized class "Vector" by an unsynchronized one such as "ArrayList" or "LinkedList".}} + public void f(Vector a) { // Noncompliant {{Replace the synchronized class "Vector" by an unsynchronized one such as "ArrayList" or "LinkedList".}} +// ^^^^^^ } @Override @@ -92,8 +99,8 @@ public void f(Integer i) { // Compliant } interface AInterface { - // Noncompliant@+1 - Vector a(Vector a); // Noncompliant {{Replace the synchronized class "Vector" by an unsynchronized one such as "ArrayList" or "LinkedList".}} + // Noncompliant@+1 + Vector a(Vector a); // Noncompliant } enum AEnum implements AInterface { @@ -126,9 +133,9 @@ void foo(Vector> v) { // Noncompliant Collections.sort(v, (s1, s2) -> -1); Collections.sort(v, (Vector s1, Vector s2) -> -1); Collections.sort(v, (Vector s1, Vector s2) -> { - // Noncompliant@+2 [[sc=9;ec=23]] - // Noncompliant@+1 [[sc=28;ec=30]] - Vector x = s1; + +// Noncompliant@+1 + Vector x = s1; // Noncompliant return -1; }); } @@ -137,9 +144,9 @@ class InvokeStringBufferMethod { String fComponents[] = new String[]{"Hello"}; public String toString() { - // Noncompliant@+2 [[sc=7;ec=19]] - // Noncompliant@+1 [[sc=26;ec=44]] - StringBuffer buf = new StringBuffer(); + +// Noncompliant@+1 + StringBuffer buf = new StringBuffer(); // Noncompliant for (int i = 0; i < fComponents.length; i++) { buf.append(fComponents[i]); diff --git a/java-checks-test-sources/default/src/main/java/checks/SynchronizedLockCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/SynchronizedLockCheckSample.java index fd773387b47..ecb8eb4112f 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SynchronizedLockCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/SynchronizedLockCheckSample.java @@ -7,7 +7,8 @@ class SynchronizedLockCheckSample { void foo() { Lock lock = new MyLockImpl(); - synchronized (lock) { // Noncompliant [[sc=19;ec=23]] {{Synchronize on this "Lock" object using "acquire/release".}} + synchronized (lock) { // Noncompliant {{Synchronize on this "Lock" object using "acquire/release".}} +// ^^^^ } synchronized (new MyLockImpl()) { // Noncompliant {{Synchronize on this "Lock" object using "acquire/release".}} } diff --git a/java-checks-test-sources/default/src/main/java/checks/SynchronizedOverrideCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/SynchronizedOverrideCheckSample.java index fbb0a12f4d6..26ec46062df 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SynchronizedOverrideCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/SynchronizedOverrideCheckSample.java @@ -2,18 +2,20 @@ class SynchronizedOverrideCheckSample { public synchronized void f1(){} +// ^^> public void f2(){} public synchronized void f3(){} } class SynchronizedOverrideCheckSample_B extends SynchronizedOverrideCheckSample { @Override - public void f1(){} // Noncompliant [[sc=15;ec=17]] {{Make this method "synchronized" to match the parent class implementation.}} + public void f1(){} // Noncompliant {{Make this method "synchronized" to match the parent class implementation.}} +// ^^ @Override public void f2(){} // Compliant - public void f3(){} // Noncompliant [[secondary=6]] {{Make this method "synchronized" to match the parent class implementation.}} + public void f3(){} // Noncompliant {{Make this method "synchronized" to match the parent class implementation.}} } class SynchronizedOverrideCheckSample_C extends SynchronizedOverrideCheckSample_B { diff --git a/java-checks-test-sources/default/src/main/java/checks/SystemOutOrErrUsageCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/SystemOutOrErrUsageCheckSample.java index 447145f52ca..b4efafdf7b4 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SystemOutOrErrUsageCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/SystemOutOrErrUsageCheckSample.java @@ -5,18 +5,20 @@ class SystemOutOrErrUsageCheckSample { void f() { - System.out.println(""); // Noncompliant {{Replace this use of System.out by a logger.}} - System.err.println(""); // Noncompliant [[sc=5;ec=15]] {{Replace this use of System.err by a logger.}} + System.out.println(""); // Noncompliant {{Replace this use of System.out by a logger.}} + System.err.println(""); // Noncompliant {{Replace this use of System.err by a logger.}} +// ^^^^^^^^^^ K.out(); K.err(); - g(System.out); // Noncompliant + g(System.out); // Noncompliant System.arraycopy(null, 0, null, 0, 0); // Compliant - java.lang.System.out.println(""); // Noncompliant [[sc=5;ec=25]] - java.lang. // Noncompliant [[sc=5;el=+1;ec=17]] - System.out.println(""); + java.lang.System.out.println(""); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^ + java.lang.System.out.println(""); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^ } void g(PrintStream stream){ diff --git a/java-checks-test-sources/default/src/main/java/checks/TabCharacter.java b/java-checks-test-sources/default/src/main/java/checks/TabCharacter.java index 1b56ddd30c7..5cf5666071c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/TabCharacter.java +++ b/java-checks-test-sources/default/src/main/java/checks/TabCharacter.java @@ -4,3 +4,5 @@ class TabCharacter { void method() { } } + +// Noncompliant@0 {{Replace all tab characters in this file by sequences of white-spaces.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/TestsInProductionFile.java b/java-checks-test-sources/default/src/main/java/checks/TestsInProductionFile.java index b7bd877d289..c7f7903b234 100644 --- a/java-checks-test-sources/default/src/main/java/checks/TestsInProductionFile.java +++ b/java-checks-test-sources/default/src/main/java/checks/TestsInProductionFile.java @@ -2,7 +2,8 @@ import org.junit.jupiter.api.Test; -public class TestsInProductionFile { // Noncompliant [[sc=14;ec=35]] {{Move this test class to the test folder in current project.}} +public class TestsInProductionFile { // Noncompliant {{Move this test class to the test folder in current project.}} +// ^^^^^^^^^^^^^^^^^^^^^ @Test public void test(){} diff --git a/java-checks-test-sources/default/src/main/java/checks/TextBlockToString.java b/java-checks-test-sources/default/src/main/java/checks/TextBlockToString.java index f6e017a6864..4fa704db2de 100644 --- a/java-checks-test-sources/default/src/main/java/checks/TextBlockToString.java +++ b/java-checks-test-sources/default/src/main/java/checks/TextBlockToString.java @@ -6,7 +6,8 @@ public class TextBlockToString { hello - """.toString(); // Noncompliant@-4 [[sc=19;ec=6;el=9;quickfixes=qf1]] {{there's no need to call "toString()" on a text block.}} + """.toString(); // Noncompliant@-4 {{there's no need to call "toString()" on a text block.}} [[quickfixes=qf1]] +//^[sc=19;ec=5;sl=5;el=9] // fix@qf1 {{Remove "toString()"}} // edit@qf1 [[sl=9;sc=6;el=9;ec=17]] {{}} diff --git a/java-checks-test-sources/default/src/main/java/checks/TextBlocksInComplexExpressionsCheckCustom.java b/java-checks-test-sources/default/src/main/java/checks/TextBlocksInComplexExpressionsCheckCustom.java index c7ab351fa07..37322d78ccf 100644 --- a/java-checks-test-sources/default/src/main/java/checks/TextBlocksInComplexExpressionsCheckCustom.java +++ b/java-checks-test-sources/default/src/main/java/checks/TextBlocksInComplexExpressionsCheckCustom.java @@ -26,7 +26,7 @@ class TextBlocksInComplexExpressionsCheckCustom { void fun(List listOfStrings) { listOfStrings.stream() - // Noncompliant@+1 + // Noncompliant@+1 .map(str -> !""" 4.0.0 diff --git a/java-checks-test-sources/default/src/main/java/checks/TextBlocksInComplexExpressionsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/TextBlocksInComplexExpressionsCheckSample.java index 42304baeed2..cac867c39c6 100644 --- a/java-checks-test-sources/default/src/main/java/checks/TextBlocksInComplexExpressionsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/TextBlocksInComplexExpressionsCheckSample.java @@ -24,7 +24,8 @@ class TextBlocksInComplexExpressionsCheckSample { void fun(List listOfStrings) { listOfStrings.stream() - .map(str -> { // Noncompliant@+1 [[sc=18;ec=14;el=+14]]{{Move this text block out of the lambda body and refactor it to a local variable or a static final field.}} + .map(str -> { // Noncompliant@+2 {{Move this text block out of the lambda body and refactor it to a local variable or a static final field.}} +//^[sc=18;ec=13;sl=29;el=42] var b = !""" 4.0.0 @@ -48,7 +49,7 @@ void fun(List listOfStrings) { }); listOfStrings.stream() - // Noncompliant@+1 + // Noncompliant@+1 .map(str -> !""" 4.0.0 diff --git a/java-checks-test-sources/default/src/main/java/checks/ThreadAsRunnableArgumentCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ThreadAsRunnableArgumentCheckSample.java index 795eacbc611..98591375904 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ThreadAsRunnableArgumentCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ThreadAsRunnableArgumentCheckSample.java @@ -10,9 +10,11 @@ class ThreadAsRunnableArgumentCheckSample { public void foo() { Thread t = new Thread() { }; - new Thread(t).start(); // Noncompliant [[sc=16;ec=17]] {{Replace this Thread instance with an instance of Runnable.}} + new Thread(t).start(); // Noncompliant {{Replace this Thread instance with an instance of Runnable.}} +// ^ - new Thread(bar()).start(); // Noncompliant [[sc=16;ec=21]] + new Thread(bar()).start(); // Noncompliant +// ^^^^^ MyThread myThread = new MyThread(); new Thread(myThread).start(); // Noncompliant @@ -29,9 +31,10 @@ public void run() { MyClass m = new MyClass(myThread); // Noncompliant m.foo(myThread); // Noncompliant m = new MyClass(0, new MyThread()); // Noncompliant - // Noncompliant@+1 - m = new MyClass(0, myThread, r, new MyThread()); // Noncompliant because of arg1 and arg3 - m = new MyClass(0, new Thread[] {myThread, new MyThread()}); // Noncompliant [[sc=24;ec=63]] {{Replace this Thread[] instance with an instance of Runnable[].}} + // Noncompliant@+1 + m = new MyClass(0, myThread, r, new MyThread()); // Noncompliant + m = new MyClass(0, new Thread[] {myThread, new MyThread()}); // Noncompliant {{Replace this Thread[] instance with an instance of Runnable[].}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ m = new MyClass(0); // Compliant m = new MyClass(0, new Runnable[] {}); // Compliant m = new MyClass(0, null, r, null); // Compliant @@ -205,7 +208,7 @@ private void yield1(int code, Thread t, Runnable r) { Runnable result4 = switch (code) { case 0 -> r; - case 1 -> t; // Noncompliant, common supertype is Runnable + case 1 -> t; // Noncompliant default -> null; }; @@ -213,7 +216,7 @@ private void yield1(int code, Thread t, Runnable r) { case 0 -> r; case 1 -> { System.out.println(); - yield t; // Noncompliant, common supertype is Runnable + yield t; // Noncompliant } default -> null; }; diff --git a/java-checks-test-sources/default/src/main/java/checks/ThreadLocalCleanup.java b/java-checks-test-sources/default/src/main/java/checks/ThreadLocalCleanup.java index c3fdc4fe46e..8cafc5fe284 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ThreadLocalCleanup.java +++ b/java-checks-test-sources/default/src/main/java/checks/ThreadLocalCleanup.java @@ -18,11 +18,13 @@ public void set(UserSession session) { } public void incorrectCleanup() { - DELEGATE.set(null); // Noncompliant [[sc=5;ec=23;quickfixes=qf1]] {{Use "remove()" instead of "set(null)".}} + DELEGATE.set(null); // Noncompliant {{Use "remove()" instead of "set(null)".}} [[quickfixes=qf1]] +// ^^^^^^^^^^^^^^^^^^ // fix@qf1 {{Replace with "remove()"}} // edit@qf1 [[sc=14;ec=23]] {{remove()}} - this.DELEGATE.set(null); // Noncompliant [[sc=5;ec=28;quickfixes=qf2]] + this.DELEGATE.set(null); // Noncompliant [[quickfixes=qf2]] +// ^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf2 {{Replace with "remove()"}} // edit@qf2 [[sc=19;ec=28]] {{remove()}} } @@ -69,7 +71,7 @@ void clean() { class AnonymousSubclass { - private static ThreadLocal DEST_TL = new ThreadLocal() { // Noncompliant + private static ThreadLocal DEST_TL = new ThreadLocal() { // Noncompliant private final ThreadLocal delegate = new ThreadLocal<>(); // Compliant, inside a class subtype of ThreadLocal @Override protected char[] initialValue() { @@ -92,7 +94,8 @@ class ThreadLocalCleanupExtends extends ThreadLocal { private static final ThreadLocal DELEGATE = new ThreadLocal<>(); // Compliant, extends ThreadLocal public void quickFixInThreadLocal() { - set(null); // Noncompliant [[sc=5;ec=14;quickfixes=qf3]] + set(null); // Noncompliant [[quickfixes=qf3]] +// ^^^^^^^^^ // fix@qf3 {{Replace with "remove()"}} // edit@qf3 [[sc=5;ec=14]] {{remove()}} } diff --git a/java-checks-test-sources/default/src/main/java/checks/ThreadOverridesRunCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ThreadOverridesRunCheckSample.java index a94cc70a5a8..d4bbe22a2cd 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ThreadOverridesRunCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ThreadOverridesRunCheckSample.java @@ -2,7 +2,8 @@ class ThreadOverridesRunCheckSample { -class A extends Thread{ // Noncompliant [[sc=7;ec=8]] {{Don't extend "Thread", since the "run" method is not overridden.}} +class A extends Thread{ // Noncompliant {{Don't extend "Thread", since the "run" method is not overridden.}} +// ^ int run; void run(Object stuff) { // not the run() method @@ -17,7 +18,8 @@ public void run() { } } class D { void foo(Runnable r){ - Thread t1 = new Thread() { };// Noncompliant [[sc=21;ec=27]] {{Don't extend "Thread", since the "run" method is not overridden.}} + Thread t1 = new Thread() { }; // Noncompliant {{Don't extend "Thread", since the "run" method is not overridden.}} +// ^^^^^^ Thread t2 = new Thread() {//Compliant @Override public void run() { diff --git a/java-checks-test-sources/default/src/main/java/checks/ThreadRunCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ThreadRunCheckSample.java index 3ccfb4850ce..bb606c51c26 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ThreadRunCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ThreadRunCheckSample.java @@ -13,7 +13,8 @@ public static void main(String[] args) { Runnable runnable = null; Thread myThread = new Thread(runnable); - myThread.run(); // Noncompliant [[sc=14;ec=17]] {{Call the method Thread.start() to execute the content of the run() method in a dedicated thread.}} + myThread.run(); // Noncompliant {{Call the method Thread.start() to execute the content of the run() method in a dedicated thread.}} +// ^^^ Thread myThread2 = new Thread(runnable); myThread2.start(); @@ -76,7 +77,8 @@ static class F extends E { void quickFix() { Runnable runnable = null; Thread myThread = new Thread(runnable); - myThread.run(); // Noncompliant [[sc=14;ec=17;quickfixes=qf1]] + myThread.run(); // Noncompliant [[quickfixes=qf1]] +// ^^^ // fix@qf1 {{Replace run() with start()}} // edit@qf1 [[sc=14;ec=17]] {{start}} } diff --git a/java-checks-test-sources/default/src/main/java/checks/ThreadSleepCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ThreadSleepCheckSample.java index d5bf9305c76..da49174005a 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ThreadSleepCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ThreadSleepCheckSample.java @@ -12,7 +12,8 @@ void foo() throws InterruptedException { Thread.sleep(12, 13); synchronized (monitor) { while (notReady()) { - Thread.sleep(200); // Noncompliant [[sc=18;ec=23]] {{Replace the call to "Thread.sleep(...)" with a call to "wait(...)".}} + Thread.sleep(200); // Noncompliant {{Replace the call to "Thread.sleep(...)" with a call to "wait(...)".}} +// ^^^^^ Thread.sleep(200, 12); // Noncompliant } process(); @@ -27,7 +28,7 @@ private boolean notReady() { } synchronized void foo2() throws InterruptedException { - Thread.sleep(200); // Noncompliant + Thread.sleep(200); // Noncompliant Thread.sleep(200, 12); // Noncompliant } } @@ -62,7 +63,8 @@ public synchronized Consumer get2() { return s -> { synchronized (new Object()) { try { - Thread.sleep(200); // Noncompliant [[sc=20;ec=25]] {{Replace the call to "Thread.sleep(...)" with a call to "wait(...)".}} + Thread.sleep(200); // Noncompliant {{Replace the call to "Thread.sleep(...)" with a call to "wait(...)".}} +// ^^^^^ } catch (InterruptedException e) { e.printStackTrace(); } diff --git a/java-checks-test-sources/default/src/main/java/checks/ThreadStartedInConstructor.java b/java-checks-test-sources/default/src/main/java/checks/ThreadStartedInConstructor.java index 1800929a1ac..0ff4dc11a64 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ThreadStartedInConstructor.java +++ b/java-checks-test-sources/default/src/main/java/checks/ThreadStartedInConstructor.java @@ -26,7 +26,8 @@ abstract static class TestClass1 { TestClass1() { toString(); // Compliant - new Thread((Runnable) null).start(); // Noncompliant [[sc=35;ec=40]] {{Move this "start" call to another method.}} + new Thread((Runnable) null).start(); // Noncompliant {{Move this "start" call to another method.}} +// ^^^^^ new ExtendsThread().start(); // Noncompliant {{Move this "start" call to another method.}} } diff --git a/java-checks-test-sources/default/src/main/java/checks/ThreadWaitCallCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ThreadWaitCallCheckSample.java index 24ad1044933..791f6f3896d 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ThreadWaitCallCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ThreadWaitCallCheckSample.java @@ -13,7 +13,8 @@ void foo() throws InterruptedException { new A().notifyAll(); new B().wait(); // Noncompliant {{Refactor the synchronisation mechanism to not use a Thread instance as a monitor}} - new B().wait(1000); // Noncompliant [[sc=13;ec=17]] + new B().wait(1000); // Noncompliant +// ^^^^ new B().wait(12,12); // Noncompliant new B().notify(); // Noncompliant new B().notifyAll(); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/ThrowsFromFinallyCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ThrowsFromFinallyCheckSample.java index 5506c2f8744..5c023bab5a0 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ThrowsFromFinallyCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ThrowsFromFinallyCheckSample.java @@ -26,7 +26,8 @@ public void f() { } catch (Exception e) { throw new IllegalAccessError(); } finally { - throw new IllegalAccessError(); // Noncompliant {{Refactor this code to not throw exceptions in finally blocks.}} [[sc=7;ec=38]] + throw new IllegalAccessError(); // Noncompliant {{Refactor this code to not throw exceptions in finally blocks.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } } diff --git a/java-checks-test-sources/default/src/main/java/checks/ToArrayCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ToArrayCheckSample.java index 63e7a81a6de..e233f6f4aa3 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ToArrayCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ToArrayCheckSample.java @@ -6,19 +6,23 @@ class ToArrayCheckSample { Object[] foo(List listOfString, List listOfNumber, Set rawSet, Collection col) { - String[] a1 = (String[]) listOfString.toArray(); // Noncompliant [[sc=30;ec=52;quickfixes=qf1]] {{Pass "new String[0]" as argument to "toArray".}} + String[] a1 = (String[]) listOfString.toArray(); // Noncompliant {{Pass "new String[0]" as argument to "toArray".}} [[quickfixes=qf1]] +// ^^^^^^^^^^^^^^^^^^^^^^ // fix@qf1 {{Pass "new String[0]" as argument}} // edit@qf1 [[sc=51;ec=51]] {{new String[0]}} // edit@qf1 [[sc=19;ec=30]] {{}} - Number[] a21 = (Number[]) listOfNumber.toArray(); // Noncompliant [[sc=37;ec=59;quickfixes=qf2]] {{Pass "new Number[0]" as argument to "toArray".}} + Number[] a21 = (Number[]) listOfNumber.toArray(); // Noncompliant {{Pass "new Number[0]" as argument to "toArray".}} [[quickfixes=qf2]] +// ^^^^^^^^^^^^^^^^^^^^^^ // fix@qf2 {{Pass "new Number[0]" as argument}} // edit@qf2 [[sc=58;ec=58]] {{new Number[0]}} // edit@qf2 [[sc=20;ec=37]] {{}} - Number[] a22 = (Number[]) rawSet.toArray(); // Noncompliant [[sc=31;ec=47;quickfixes=qf3]] {{Pass "new Number[0]" as argument to "toArray".}} + Number[] a22 = (Number[]) rawSet.toArray(); // Noncompliant {{Pass "new Number[0]" as argument to "toArray".}} [[quickfixes=qf3]] +// ^^^^^^^^^^^^^^^^ // fix@qf3 {{Pass "new Number[0]" as argument}} // edit@qf3 [[sc=46;ec=46]] {{new Number[0]}} // Only one edit, can not remove cast without compilation error - Number[] a23 = (Number[]) col.toArray(); // Noncompliant [[sc=31;ec=44;quickfixes=qf4]] {{Pass "new Number[0]" as argument to "toArray".}} + Number[] a23 = (Number[]) col.toArray(); // Noncompliant {{Pass "new Number[0]" as argument to "toArray".}} [[quickfixes=qf4]] +// ^^^^^^^^^^^^^ // fix@qf4 {{Pass "new Number[0]" as argument}} // edit@qf4 [[sc=43;ec=43]] {{new Number[0]}} // edit@qf4 [[sc=20;ec=31]] {{}} diff --git a/java-checks-test-sources/default/src/main/java/checks/ToStringReturningNullCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ToStringReturningNullCheckSample.java index 63dface90eb..dbdd18e196b 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ToStringReturningNullCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ToStringReturningNullCheckSample.java @@ -20,26 +20,30 @@ public String toString() { class ToStringReturningNullCheckSampleC { public String toString() { - return (null); // Noncompliant [[sc=13;ec=17]] + return (null); // Noncompliant +// ^^^^ } } class ToStringReturningNullCheckSampleD { protected Object clone() { - return null; // Noncompliant [[sc=12;ec=16;quickfixes=!]] {{Return a non null object.}} + return null; // Noncompliant {{Return a non null object.}} [[quickfixes=!]] +// ^^^^ } } class QuickFixesA{ public String toString() { - return (null); // Noncompliant [[sc=13;ec=17;quickfixes=qf1]] + return (null); // Noncompliant [[quickfixes=qf1]] +// ^^^^ // fix@qf1 {{Replace null with an empty string}} // edit@qf1 [[sc=12;ec=18]] {{""}} } } class QuickFixesB{ public String toString() { - return null; // Noncompliant [[sc=12;ec=16;quickfixes=qf2]] + return null; // Noncompliant [[quickfixes=qf2]] +// ^^^^ // fix@qf2 {{Replace null with an empty string}} // edit@qf2 [[sc=12;ec=16]] {{""}} } @@ -47,7 +51,8 @@ public String toString() { class QuickFixesC{ public String toString() { if(someCondition()) { - return null; // Noncompliant [[sc=14;ec=18;quickfixes=qf3]] + return null; // Noncompliant [[quickfixes=qf3]] +// ^^^^ // fix@qf3 {{Replace null with an empty string}} // edit@qf3 [[sc=14;ec=18]] {{""}} } diff --git a/java-checks-test-sources/default/src/main/java/checks/ToStringUsingBoxingCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/ToStringUsingBoxingCheckSample.java index d20f9cd6c3e..b856a02cae6 100644 --- a/java-checks-test-sources/default/src/main/java/checks/ToStringUsingBoxingCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/ToStringUsingBoxingCheckSample.java @@ -2,7 +2,8 @@ class ToStringUsingBoxingCheckSample { private void f() { - new Byte((byte) 12).toString(); // Noncompliant [[sc=5;ec=35]] {{Call the static method Byte.toString(...) instead of instantiating a temporary object.}} + new Byte((byte) 12).toString(); // Noncompliant {{Call the static method Byte.toString(...) instead of instantiating a temporary object.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ new Short((short) 0).toString(); // Noncompliant {{Call the static method Short.toString(...) instead of instantiating a temporary object.}} new Integer(0).toString(); // Noncompliant {{Call the static method Integer.toString(...) instead of instantiating a temporary object.}} new java.lang.Integer(0).toString(); // Noncompliant {{Call the static method Integer.toString(...) instead of instantiating a temporary object.}} @@ -19,7 +20,8 @@ private void f() { int myInt = 4; new Integer(myInt).toString(); // Noncompliant {{Call the static method Integer.toString(...) instead of instantiating a temporary object.}} new Integer(myInt).compareTo(0); // Noncompliant {{Call the static method Integer.compare(...) instead of instantiating a temporary object.}} - Integer.valueOf(myInt).compareTo(0); // Noncompliant [[sc=5;ec=40]] {{Call the static method Integer.compare(...) instead of instantiating a temporary object.}} + Integer.valueOf(myInt).compareTo(0); // Noncompliant {{Call the static method Integer.compare(...) instead of instantiating a temporary object.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Integer.toString(0); // Compliant Integer.toString(0, 2); // Compliant @@ -70,33 +72,40 @@ private void trueNegative(String[] array, int i) { } private void quickFixes(boolean myBoolean) { - new Byte((byte) 1).toString(); // Noncompliant [[sc=5;ec=34;quickfixes=qf1]] + new Byte((byte) 1).toString(); // Noncompliant [[quickfixes=qf1]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf1 {{Use Byte.toString(...) instead}} // edit@qf1 [[sc=5;ec=14]] {{Byte.toString(}} // edit@qf1 [[sc=22;ec=34]] {{)}} - new Short((short) 0).toString(); // Noncompliant [[sc=5;ec=36;quickfixes=qf2]] + new Short((short) 0).toString(); // Noncompliant [[quickfixes=qf2]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf2 {{Use Short.toString(...) instead}} // edit@qf2 [[sc=5;ec=15]] {{Short.toString(}} // edit@qf2 [[sc=24;ec=36]] {{)}} - new java.lang.Integer(0).toString(); // Noncompliant [[sc=5;ec=40;quickfixes=qf3]] + new java.lang.Integer(0).toString(); // Noncompliant [[quickfixes=qf3]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf3 {{Use Integer.toString(...) instead}} // edit@qf3 [[sc=5;ec=27]] {{Integer.toString(}} // edit@qf3 [[sc=28;ec=40]] {{)}} - new Integer(0).compareTo(1); // Noncompliant [[sc=5;ec=32;quickfixes=qf4]] + new Integer(0).compareTo(1); // Noncompliant [[quickfixes=qf4]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf4 {{Use Integer.compare(...) instead}} // edit@qf4 [[sc=5;ec=17]] {{Integer.compare(}} // edit@qf4 [[sc=18;ec=30]] {{, }} - Boolean.valueOf(myBoolean).compareTo(false);// Noncompliant [[sc=5;ec=48;quickfixes=qf5]] + Boolean.valueOf(myBoolean).compareTo(false); // Noncompliant [[quickfixes=qf5]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf5 {{Use Boolean.compare(...) instead}} // edit@qf5 [[sc=5;ec=21]] {{Boolean.compare(}} // edit@qf5 [[sc=30;ec=42]] {{, }} // Special cases, the creation of Integer is in fact completely useless. - new Integer(0).toString(1); // Noncompliant [[sc=5;ec=31;quickfixes=qf6]] + new Integer(0).toString(1); // Noncompliant [[quickfixes=qf6]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf6 {{Use Integer.toString(...) instead}} // edit@qf6 [[sc=5;ec=19]] {{Integer}} - new Integer(0).toString(1, 2); // Noncompliant [[sc=5;ec=34;quickfixes=qf7]] + new Integer(0).toString(1, 2); // Noncompliant [[quickfixes=qf7]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf7 {{Use Integer.toString(...) instead}} // edit@qf7 [[sc=5;ec=19]] {{Integer}} } diff --git a/java-checks-test-sources/default/src/main/java/checks/TodoTagPresenceCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/TodoTagPresenceCheckSample.java index 1dff89061a0..ae282f7fcfb 100644 --- a/java-checks-test-sources/default/src/main/java/checks/TodoTagPresenceCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/TodoTagPresenceCheckSample.java @@ -1,24 +1,24 @@ // foo -// Noncompliant@+1 -// Noncompliant@+1 {{Complete the task associated to this TODO comment.}} + // Noncompliant@+1 + // Noncompliant@+1 {{Complete the task associated to this TODO comment.}} // toDO -// Noncompliant@+5 -// Noncompliant@+3 + // Noncompliant@+5 + // Noncompliant@+3 /* todo ToDo */ -// Noncompliant@+1 + // Noncompliant@+1 // TODO -// Noncompliant@+1 + // Noncompliant@+1 // TODO Explenation -// Noncompliant@+1 + // Noncompliant@+1 // [TODO] // PreTodo diff --git a/java-checks-test-sources/default/src/main/java/checks/TooLongLine_S103_Check/LineLengthLinkOrSee.java b/java-checks-test-sources/default/src/main/java/checks/TooLongLine_S103_Check/LineLengthLinkOrSee.java index c7395302854..dd6786fedab 100644 --- a/java-checks-test-sources/default/src/main/java/checks/TooLongLine_S103_Check/LineLengthLinkOrSee.java +++ b/java-checks-test-sources/default/src/main/java/checks/TooLongLine_S103_Check/LineLengthLinkOrSee.java @@ -1,5 +1,5 @@ package checks.TooLongLine_S103_Check; -// Noncompliant@+4 {{Split this 217 characters long line (which is greater than 100 authorized).}} + // Noncompliant@+4 {{Split this 217 characters long line (which is greater than 100 authorized).}} /** * Example of usage: *
@@ -7,12 +7,12 @@
  * 
*/ -// Noncompliant@+1 {{Split this 211 characters long line (which is greater than 100 authorized).}} + // Noncompliant@+1 {{Split this 211 characters long line (which is greater than 100 authorized).}} // Long link, but also long text on the same line, longer than the marker line above.............. See {@link HTTP/1.1 documentation}. -// Noncompliant@+6 {{Split this 206 characters long line (which is greater than 100 authorized).}} -// Noncompliant@+6 {{Split this 138 characters long line (which is greater than 100 authorized).}} -// Noncompliant@+6 {{Split this 134 characters long line (which is greater than 100 authorized).}} + // Noncompliant@+6 {{Split this 206 characters long line (which is greater than 100 authorized).}} + // Noncompliant@+6 {{Split this 138 characters long line (which is greater than 100 authorized).}} + // Noncompliant@+6 {{Split this 134 characters long line (which is greater than 100 authorized).}} /** * Example of usage: *
@@ -22,16 +22,16 @@
  * 
*/ -// Noncompliant@+1 {{Split this 206 characters long line (which is greater than 100 authorized).}} + // Noncompliant@+1 {{Split this 206 characters long line (which is greater than 100 authorized).}} // Long see, but also long text on the same line, longer than the marker line above.................. @see HTTP/1.1 documentation -// Noncompliant@+1 {{Split this 138 characters long line (which is greater than 100 authorized).}} + // Noncompliant@+1 {{Split this 138 characters long line (which is greater than 100 authorized).}} // Long see, but also long text on the same line, longer than the marker line above.................. @see "The Java Programming Language" -// Noncompliant@+1 {{Split this 134 characters long line (which is greater than 100 authorized).}} + // Noncompliant@+1 {{Split this 134 characters long line (which is greater than 100 authorized).}} // Long see, but also long text on the same line, longer than the marker line above.................. @see package.class#member label class LineLengthLinkOrSee { - // Noncompliant@+1 {{Split this 115 characters long line (which is greater than 100 authorized).}} + // Noncompliant@+1 {{Split this 115 characters long line (which is greater than 100 authorized).}} String s = "The @see in here will not be ignored because it's not inside a comment xxxxxxxxxxxxxxxxxxxxxxxxxxxx"; - // Noncompliant@+1 {{Split this 115 characters long line (which is greater than 100 authorized).}} + // Noncompliant@+1 {{Split this 115 characters long line (which is greater than 100 authorized).}} String t = "Same for this {@link xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}"; } diff --git a/java-checks-test-sources/default/src/main/java/checks/TooManyLinesOfCode.java b/java-checks-test-sources/default/src/main/java/checks/TooManyLinesOfCode.java index 99b4ba8713c..bbb58dddc4e 100644 --- a/java-checks-test-sources/default/src/main/java/checks/TooManyLinesOfCode.java +++ b/java-checks-test-sources/default/src/main/java/checks/TooManyLinesOfCode.java @@ -20,4 +20,4 @@ class TooManyLinesOfCode { int field7; // This line does not count -} +} // Noncompliant@0 diff --git a/java-checks-test-sources/default/src/main/java/checks/TooManyMethodsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/TooManyMethodsCheckSample.java index 261673e1e14..9b37bbc4a9a 100644 --- a/java-checks-test-sources/default/src/main/java/checks/TooManyMethodsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/TooManyMethodsCheckSample.java @@ -1,21 +1,35 @@ package checks; -class TooManyMethodsCheckSample { // Noncompliant [[sc=7;ec=32;secondary=+1,+2,+3,+4,+5,+6]] {{class "TooManyMethodsCheckSample" has 6 methods, which is greater than the 4 authorized. Split it into smaller classes.}} +class TooManyMethodsCheckSample { // Noncompliant {{class "TooManyMethodsCheckSample" has 6 methods, which is greater than the 4 authorized. Split it into smaller classes.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^ TooManyMethodsCheckSample () {} +//^^^^^^^^^^^^^^^^^^^^^^^^^< void method1() {} +// ^^^^^^^< public void method2() {} +// ^^^^^^^< void method3() {} +// ^^^^^^^< public void method4() {} +// ^^^^^^^< void method5() {} +// ^^^^^^^< } -record TooManyMethodsRecord() { // Noncompliant [[sc=8;ec=28;secondary=+1,+2,+3,+4,+5,+6]] {{record "TooManyMethodsRecord" has 6 methods, which is greater than the 4 authorized. Split it into smaller records.}} +record TooManyMethodsRecord() { // Noncompliant {{record "TooManyMethodsRecord" has 6 methods, which is greater than the 4 authorized. Split it into smaller records.}} +// ^^^^^^^^^^^^^^^^^^^^ TooManyMethodsRecord {} +//^^^^^^^^^^^^^^^^^^^^< void m1() {} +// ^^< void m2() {} +// ^^< void m3() {} +// ^^< void m4() {} +// ^^< void m5() {} +// ^^< } class TooManyMethodsCheckSampleA { diff --git a/java-checks-test-sources/default/src/main/java/checks/TooManyParametersCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/TooManyParametersCheckSample.java index d3405a52cdd..b4f75a9f366 100644 --- a/java-checks-test-sources/default/src/main/java/checks/TooManyParametersCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/TooManyParametersCheckSample.java @@ -16,7 +16,8 @@ public class TooManyParametersCheckSample { TooManyParametersCheckSample(int p1, int p2, int p3, int p4, int p5, int p6, int p7, int p8) { // Noncompliant {{Constructor has 8 parameters, which is greater than 7 authorized.}} } - void method(int p1, int p2, int p3, int p4, int p5, int p6, int p7, int p8) { // Noncompliant [[sc=8;ec=14]] {{Method has 8 parameters, which is greater than 7 authorized.}} + void method(int p1, int p2, int p3, int p4, int p5, int p6, int p7, int p8) { // Noncompliant {{Method has 8 parameters, which is greater than 7 authorized.}} +// ^^^^^^ } void otherMethod(int p1) {} diff --git a/java-checks-test-sources/default/src/main/java/checks/TooManyParametersCustom.java b/java-checks-test-sources/default/src/main/java/checks/TooManyParametersCustom.java index 6df8a561812..81b109206a8 100644 --- a/java-checks-test-sources/default/src/main/java/checks/TooManyParametersCustom.java +++ b/java-checks-test-sources/default/src/main/java/checks/TooManyParametersCustom.java @@ -12,8 +12,8 @@ void method(int p1, int p2, int p3, int p4, int p5, int p6, int p7, int p8, int class MethodsUsingSpringRequestMappingCustom { @org.springframework.web.bind.annotation.RequestMapping - void foo(String p1, String p2, String p3, String p4, String p5, String p6, String p7, String p8, String p9) {} // Noncompliant - filtered out by SpringFilter + void foo(String p1, String p2, String p3, String p4, String p5, String p6, String p7, String p8, String p9) {} // Noncompliant @RequestMapping - void bar(String p1, String p2, String p3, String p4, String p5, String p6, String p7, String p8, String p9) {} // Noncompliant - filtered out by SpringFilter + void bar(String p1, String p2, String p3, String p4, String p5, String p6, String p7, String p8, String p9) {} // Noncompliant } diff --git a/java-checks-test-sources/default/src/main/java/checks/TrailingCommentCheckCustom.java b/java-checks-test-sources/default/src/main/java/checks/TrailingCommentCheckCustom.java index cb14e7ad0f1..78505589e67 100644 --- a/java-checks-test-sources/default/src/main/java/checks/TrailingCommentCheckCustom.java +++ b/java-checks-test-sources/default/src/main/java/checks/TrailingCommentCheckCustom.java @@ -2,18 +2,18 @@ class TrailingCommentCheckCustom { int i = 0, - // Noncompliant@+1 + // Noncompliant@+1 j = 0, // This is non-compliant k = 0; // This is compliant - // Noncompliant@+1 + // Noncompliant@+1 int a = 0; // Compliant - // Noncompliant@+1 + // Noncompliant@+1 int b = 0; /* Compliant */ - // Noncompliant@+1 + // Noncompliant@+1 int c = 0; // This is non-compliant - // Noncompliant@+1 + // Noncompliant@+1 int d = 0; // This is also non-compliant int e = /* Compliant */ 0; @@ -25,7 +25,7 @@ class TrailingCommentCheckCustom { void foo() { int[] m = new int[2]; - // Noncompliant@+1 + // Noncompliant@+1 if (i == 0) { // This is non-compliant m[0] = 1; } diff --git a/java-checks-test-sources/default/src/main/java/checks/TrailingCommentCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/TrailingCommentCheckSample.java index cd8d573ca5f..2e7a325f9ae 100644 --- a/java-checks-test-sources/default/src/main/java/checks/TrailingCommentCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/TrailingCommentCheckSample.java @@ -9,7 +9,7 @@ class TrailingCommentCheckSample { int a = 0; // Compliant int b = 0; /* Compliant */ int c = 0; // Noncompliant {{Move this trailing comment on the previous empty line.}} - int d = 0; // Noncompliant This is also non-compliant + int d = 0; int e = /* Compliant */ 0; int f = 0; // NOSONAR @@ -21,7 +21,7 @@ class TrailingCommentCheckSample { void foo() { int[] m = new int[2]; - if (i == 0) { // Noncompliant This is non-compliant + if (i == 0) { m[0] = 1; } } diff --git a/java-checks-test-sources/default/src/main/java/checks/TransientFieldInNonSerializableCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/TransientFieldInNonSerializableCheckSample.java index 8cd7cc284cc..877c530b46a 100644 --- a/java-checks-test-sources/default/src/main/java/checks/TransientFieldInNonSerializableCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/TransientFieldInNonSerializableCheckSample.java @@ -10,7 +10,8 @@ class A implements Serializable { } class B { - transient String x; // Noncompliant [[sc=5;ec=14]] {{Remove the "transient" modifier from this field.}} + transient String x; // Noncompliant {{Remove the "transient" modifier from this field.}} +// ^^^^^^^^^ String y; void myMethod() {} } diff --git a/java-checks-test-sources/default/src/main/java/checks/TryWithResourcesCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/TryWithResourcesCheckSample.java index 9d5c256b42e..3ca298b3bfa 100644 --- a/java-checks-test-sources/default/src/main/java/checks/TryWithResourcesCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/TryWithResourcesCheckSample.java @@ -8,9 +8,12 @@ class TryWithResourcesCheckSample { String foo(String fileName) { FileReader fr = null; BufferedReader br = null; - try { // Noncompliant [[sc=5;ec=8;secondary=12,13]] {{Change this "try" to a try-with-resources.}} + try { // Noncompliant {{Change this "try" to a try-with-resources.}} +// ^^^ fr = new FileReader(fileName); +// ^^^^^^^^^^^^^^^^^^^^^^^^< br = new BufferedReader(fr); +// ^^^^^^^^^^^^^^^^^^^^^^< return br.readLine(); } catch (Exception e) { } finally { @@ -43,8 +46,11 @@ String foo(String fileName) { void newJustBeforeTryStatement() { Auto a1 = new Auto(); +// ^^^^^^^^^^> Auto a2 = new Auto(); - try { // Noncompliant [[sc=5;ec=8;secondary=45,46]] {{Change this "try" to a try-with-resources.}} +// ^^^^^^^^^^> + try { // Noncompliant {{Change this "try" to a try-with-resources.}} +// ^^^ a1.doSomething(); } finally { a1.close(); @@ -55,8 +61,11 @@ void newJustBeforeTryStatement() { void newJustBeforeAndAfterTryStatement() { Auto a1 = null; Auto a2 = new Auto(); - try { // Noncompliant [[sc=5;ec=8;secondary=57,59]] {{Change this "try" to a try-with-resources.}} +// ^^^^^^^^^^> + try { // Noncompliant {{Change this "try" to a try-with-resources.}} +// ^^^ a1 = new Auto(); +// ^^^^^^^^^^< a1.doSomething(); } finally { a1.close(); @@ -108,9 +117,12 @@ void newJustBeforeTryWithResource() { void enclosedTryWithFinallyStatements() { Auto a1 = new Auto(); - try { // Noncompliant [[sc=5;ec=8;secondary=110,113]] {{Change this "try" to a try-with-resources.}} +// ^^^^^^^^^^> + try { // Noncompliant {{Change this "try" to a try-with-resources.}} +// ^^^ a1.doSomething(); Auto a2 = new Auto(); +// ^^^^^^^^^^< try { a2.doSomething(); } finally { @@ -123,9 +135,12 @@ void enclosedTryWithFinallyStatements() { void enclosedTryStatements() { Auto a1 = new Auto(); - try { // Noncompliant [[sc=5;ec=8;secondary=125,128]] {{Change this "try" to a try-with-resources.}} +// ^^^^^^^^^^> + try { // Noncompliant {{Change this "try" to a try-with-resources.}} +// ^^^ a1.doSomething(); Auto a2 = new Auto(); +// ^^^^^^^^^^< try { a2.doSomething(); a2.close(); diff --git a/java-checks-test-sources/default/src/main/java/checks/TryWithResourcesCheck_no_java_version.java b/java-checks-test-sources/default/src/main/java/checks/TryWithResourcesCheck_no_java_version.java index db25bebd137..61be4e1c5ec 100644 --- a/java-checks-test-sources/default/src/main/java/checks/TryWithResourcesCheck_no_java_version.java +++ b/java-checks-test-sources/default/src/main/java/checks/TryWithResourcesCheck_no_java_version.java @@ -8,9 +8,12 @@ class TryWithResourcesCheck_no_java_version { String foo(String fileName) { FileReader fr = null; BufferedReader br = null; - try { // Noncompliant [[sc=5;ec=8;secondary=12,13]] {{Change this "try" to a try-with-resources. (sonar.java.source not set. Assuming 7 or greater.)}} + try { // Noncompliant {{Change this "try" to a try-with-resources. (sonar.java.source not set. Assuming 7 or greater.)}} +// ^^^ fr = new FileReader(fileName); +// ^^^^^^^^^^^^^^^^^^^^^^^^< br = new BufferedReader(fr); +// ^^^^^^^^^^^^^^^^^^^^^^< return br.readLine(); } catch (Exception e) { } finally { diff --git a/java-checks-test-sources/default/src/main/java/checks/TwoLocksWaitCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/TwoLocksWaitCheckSample.java index 273d68294be..45caf48d0b7 100644 --- a/java-checks-test-sources/default/src/main/java/checks/TwoLocksWaitCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/TwoLocksWaitCheckSample.java @@ -6,16 +6,22 @@ class TwoLocksWaitCheckSample { public TwoLocksWaitCheckSample() throws Exception { synchronized (this.mon1) { +// ^^^^^^^^^^^^> System.out.println("Hello"); synchronized (this.mon2) { - this.mon2.wait(); // Noncompliant [[sc=9;ec=25;secondary=8,10]] {{Don't use "wait()" here; multiple locks are held.}} +// ^^^^^^^^^^^^> + this.mon2.wait(); // Noncompliant {{Don't use "wait()" here; multiple locks are held.}} +// ^^^^^^^^^^^^^^^^ } } } public synchronized void method() throws Exception { +// ^^^^^^^^^^^^> synchronized (this.mon2) { - this.mon2.wait(); // Noncompliant [[sc=7;ec=23;secondary=16,17]] {{Don't use "wait()" here; multiple locks are held.}} +// ^^^^^^^^^^^^> + this.mon2.wait(); // Noncompliant {{Don't use "wait()" here; multiple locks are held.}} +// ^^^^^^^^^^^^^^^^ } } diff --git a/java-checks-test-sources/default/src/main/java/checks/TypeParametersShadowingCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/TypeParametersShadowingCheckSample.java index b1673b636f1..ecec2ed0aa0 100644 --- a/java-checks-test-sources/default/src/main/java/checks/TypeParametersShadowingCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/TypeParametersShadowingCheckSample.java @@ -5,13 +5,18 @@ public class TypeParametersShadowingCheckSample { class TypeParameterHidesAnotherType { - public class Inner { // Noncompliant [[sc=24;ec=25;secondary=-1]] {{Rename "T" which hides a type parameter from the outer scope.}} +// ^> + public class Inner { // Noncompliant {{Rename "T" which hides a type parameter from the outer scope.}} +// ^ //... } - public class Inner2 { // Noncompliant [[secondary=-5]] {{Rename "T0" which hides a type parameter from the outer scope.}} + public class Inner2 { // Noncompliant {{Rename "T0" which hides a type parameter from the outer scope.}} +// ^^ +// ^^@-8< //... } - private T method() { // Noncompliant [[sc=14;ec=15;secondary=-7]] {{Rename "T" which hides a type parameter from the outer scope.}} + private T method() { // Noncompliant {{Rename "T" which hides a type parameter from the outer scope.}} +// ^ return null; } } @@ -29,21 +34,26 @@ private V method() { // Compliant } class MultipleHiding { - public class Inner { // Noncompliant [[sc=24;ec=25;secondary=-1]] {{Rename "T" which hides a type parameter from the outer scope.}} - private T method2() { // Noncompliant [[secondary=-2]] {{Rename "T" which hides a type parameter from the outer scope.}} + public class Inner { // Noncompliant {{Rename "T" which hides a type parameter from the outer scope.}} +// ^ + private T method2() { // Noncompliant {{Rename "T" which hides a type parameter from the outer scope.}} return null; } - private T method() { // Noncompliant [[sc=16;ec=17;secondary=-5]] {{Rename "Q" which hides a type parameter from the outer scope.}} + private T method() { // Noncompliant {{Rename "Q" which hides a type parameter from the outer scope.}} +// ^ +// ^@-7< return null; } } - private T method2() { // Noncompliant [[secondary=-9]] + private T method2() { // Noncompliant return null; } } class TypeExtend, Q> { - public class Inner { // Noncompliant [[sc=24;ec=25;secondary=-1]] {{Rename "E" which hides a type parameter from the outer scope.}} +// ^> + public class Inner { // Noncompliant {{Rename "E" which hides a type parameter from the outer scope.}} +// ^ } public class Inner2

{ // Compliant } @@ -53,13 +63,19 @@ class DeeplyNestedIntoAnonymousClass { public class Inner { // Compliant private T method() { // Compliant new Function() { - class InnerAnonymousHidingT { // Noncompliant [[secondary=-4]] + class InnerAnonymousHidingT { // Noncompliant +// ^ +// ^@-5< //... } - class InnerAnonymousHidingS { // Noncompliant [[secondary=-6]] + class InnerAnonymousHidingS { // Noncompliant +// ^ +// ^@-9< //... } - class InnerAnonymousHidingQ { // Noncompliant [[secondary=-8]] + class InnerAnonymousHidingQ { // Noncompliant +// ^ +// ^@-13< //... } @Override @@ -77,16 +93,18 @@ private static T0 methodBefore() { // Compliant, static member, T0 is not h return null; } public static class Inner { // Compliant, static member, T0 is not hiding anything - private Q method2() { // Noncompliant [[secondary=-1]] + private Q method2() { // Noncompliant return null; } // Actually hiding the one from the static class - private Q method3() { // Noncompliant [[secondary=-5]] + private Q method3() { // Noncompliant return null; } private static

P method1() { // Compliant, static member, not hiding anything new Function() { - class InnerAnonymousHidingT

{ // Noncompliant [[secondary=-2]] + class InnerAnonymousHidingT

{ // Noncompliant +// ^ +// ^@-3< //... } @Override diff --git a/java-checks-test-sources/default/src/main/java/checks/TypeUpperBoundNotFinalCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/TypeUpperBoundNotFinalCheckSample.java index c5672b9a9ae..27d830f168b 100644 --- a/java-checks-test-sources/default/src/main/java/checks/TypeUpperBoundNotFinalCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/TypeUpperBoundNotFinalCheckSample.java @@ -34,25 +34,32 @@ static abstract class AbstractClass { public static void boundedWildcard(Collection c) { } // Noncompliant - public static class FinalAndNonFinalBounds { } // Noncompliant [[sc=46;ec=79]] + public static class FinalAndNonFinalBounds { } // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @Nullable public static T multipleBounds() { // Noncompliant return null; } - public static > void finalParameterizedBound() { } // Noncompliant [[sc=18;ec=41]] + public static > void finalParameterizedBound() { } // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^ - public static > void finalInnerBound() { } // Noncompliant [[sc=42;ec=62]] + public static > void finalInnerBound() { } // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^ - public static > void complexFinalInnerBound() { } // Noncompliant [[sc=63;ec=83]] + public static > void complexFinalInnerBound() { } // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^ - public static void multipleTypeParams() { } // Noncompliant [[sc=43;ec=63]] + public static void multipleTypeParams() { } // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^ - public static NonFinalClass> methodReturn() { return null; } // Noncompliant [[sc=31;ec=54]] + public static NonFinalClass> methodReturn() { return null; } // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^ public static final class ImmutableClass { - public NonFinalClass extendsClass(Map, ? extends T> map) { return null; } // Noncompliant [[sc=60;ec=88]] + public NonFinalClass extendsClass(Map, ? extends T> map) { return null; } // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } diff --git a/java-checks-test-sources/default/src/main/java/checks/URLHashCodeAndEqualsCheck.java b/java-checks-test-sources/default/src/main/java/checks/URLHashCodeAndEqualsCheck.java index 25fc949db59..b2488392fc5 100644 --- a/java-checks-test-sources/default/src/main/java/checks/URLHashCodeAndEqualsCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/URLHashCodeAndEqualsCheck.java @@ -9,11 +9,13 @@ class URLHashCodeAndEqualsCheck { public void foo(URL url) throws Exception { - Map sites = new HashMap<>(); // Noncompliant [[sc=5;ec=22]] {{Use the URI class instead.}} + Map sites = new HashMap<>(); // Noncompliant {{Use the URI class instead.}} +// ^^^^^^^^^^^^^^^^^ Set otherSites = new HashSet<>(); // Noncompliant {{Use the URI class instead.}} URL homepage = new URL("http://sonarsource.com"); // Compliant - homepage.equals(url); // Noncompliant [[sc=5;ec=25]] {{Use the URI class instead.}} + homepage.equals(url); // Noncompliant {{Use the URI class instead.}} +// ^^^^^^^^^^^^^^^^^^^^ homepage.hashCode(); // Noncompliant {{Use the URI class instead.}} homepage.getPath(); // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/UnnecessaryBitOperationCheck.java b/java-checks-test-sources/default/src/main/java/checks/UnnecessaryBitOperationCheck.java index 17d9b524f72..9e4ff80418f 100644 --- a/java-checks-test-sources/default/src/main/java/checks/UnnecessaryBitOperationCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/UnnecessaryBitOperationCheck.java @@ -6,11 +6,13 @@ private void foo() { int bitMask = 0x000F; result = bitMask & -1; // Noncompliant {{Remove this unnecessary bit operation.}} - result = bitMask | 0; // Noncompliant [[sc=22;ec=23]] {{Remove this unnecessary bit operation.}} - result = bitMask ^ 0; // Noncompliant {{Remove this unnecessary bit operation.}} - result &= -1; // Noncompliant [[sc=12;ec=14]] {{Remove this unnecessary bit operation.}} - result |= 0; // Noncompliant {{Remove this unnecessary bit operation.}} - result ^= 0; // Noncompliant {{Remove this unnecessary bit operation.}} + result = bitMask | 0; // Noncompliant {{Remove this unnecessary bit operation.}} +// ^ + result = bitMask ^ 0; // Noncompliant {{Remove this unnecessary bit operation.}} + result &= -1; // Noncompliant {{Remove this unnecessary bit operation.}} +// ^^ + result |= 0; // Noncompliant {{Remove this unnecessary bit operation.}} + result ^= 0; // Noncompliant {{Remove this unnecessary bit operation.}} result = bitMask & 1; // Compliant result = bitMask | 1; // compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/UnreachableCatchCheck.java b/java-checks-test-sources/default/src/main/java/checks/UnreachableCatchCheck.java index 7801b7866f9..9a7725298bb 100644 --- a/java-checks-test-sources/default/src/main/java/checks/UnreachableCatchCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/UnreachableCatchCheck.java @@ -12,16 +12,20 @@ void unreachable(boolean cond) { try { throwExtendsCustomException(); } catch (ExtendsCustomException e) { +// ^^^^^^^^^^^^^^^^^^^^^^> // ... - } catch (CustomException e) { // Noncompliant [[sc=7;ec=12;secondary=14]] {{Remove or refactor this catch clause because it is unreachable, hidden by previous catch block(s).}} + } catch (CustomException e) { // Noncompliant {{Remove or refactor this catch clause because it is unreachable, hidden by previous catch block(s).}} +// ^^^^^ // ... } try { throw new ExtendsCustomException(); } catch (ExtendsCustomException e) { +// ^^^^^^^^^^^^^^^^^^^^^^> // ... - } catch (CustomException|IllegalStateException e) { // Noncompliant [[sc=14;ec=29;secondary=22]] {{Remove this type because it is unreachable, hidden by previous catch block(s).}} + } catch (CustomException|IllegalStateException e) { // Noncompliant {{Remove this type because it is unreachable, hidden by previous catch block(s).}} +// ^^^^^^^^^^^^^^^ // ... } @@ -29,10 +33,13 @@ void unreachable(boolean cond) { if (true) throw new ExtendsExtendsCustomException(); throw new ExtendsOtherExtendsCustomException(); } catch (ExtendsExtendsCustomException e) { +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^> // ... } catch (ExtendsOtherExtendsCustomException e) { +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^> // ... - } catch (ExtendsCustomException | OtherExtendsCustomException e) { // Noncompliant [[sc=7;ec=12;secondary=31,33]] {{Remove or refactor this catch clause because it is unreachable, hidden by previous catch block(s).}} + } catch (ExtendsCustomException | OtherExtendsCustomException e) { // Noncompliant {{Remove or refactor this catch clause because it is unreachable, hidden by previous catch block(s).}} +// ^^^^^ // ... } @@ -56,9 +63,9 @@ void unreachable(boolean cond) { throwExtendsExtendsCustomException(); } catch (ExtendsExtendsCustomException e) { // ... - } catch (ExtendsCustomException e) { // Noncompliant [[secondary=57]] + } catch (ExtendsCustomException e) { // Noncompliant // ... - } catch (CustomException e) { // Noncompliant [[secondary=57,59]] + } catch (CustomException e) { // Noncompliant // ... } @@ -68,7 +75,7 @@ void unreachable(boolean cond) { // ... } catch (ExtendsCustomException e) { // ... - } catch (CustomException e) { // Noncompliant [[secondary=67,69]] + } catch (CustomException e) { // Noncompliant // ... } @@ -79,7 +86,7 @@ void unreachable(boolean cond) { // ... } catch (IOException e) { // Compliant // ... - } catch (CustomException e) { // Noncompliant [[secondary=78]] + } catch (CustomException e) { // Noncompliant // ... } @@ -87,9 +94,10 @@ void unreachable(boolean cond) { throwExtendsExtendsCustomException(); throwIOException(); } catch (ExtendsCustomException | IOException e) { +// ^^^^^^^^^^^^^^^^^^^^^^> // ... - } catch (CustomException e) { // Noncompliant [[secondary=89]] - // ... + } catch (CustomException e) { // Noncompliant + //^^^^^ } try { @@ -212,7 +220,7 @@ public void close() throws FileNotFoundException { try (B a = new B()) { } catch (FileNotFoundException e) { e.printStackTrace(); - } catch (IOException e) { // Noncompliant - this can happen only if the class implementing Closable specify a subtype of IOException in the declaration. + } catch (IOException e) { // Noncompliant e.printStackTrace(); } diff --git a/java-checks-test-sources/default/src/main/java/checks/UnusedPrivateClass.java b/java-checks-test-sources/default/src/main/java/checks/UnusedPrivateClass.java index f6022bb7098..9ab9d5c1f77 100644 --- a/java-checks-test-sources/default/src/main/java/checks/UnusedPrivateClass.java +++ b/java-checks-test-sources/default/src/main/java/checks/UnusedPrivateClass.java @@ -2,7 +2,8 @@ public class UnusedPrivateClass { - private class Unused {} // Noncompliant {{Remove this unused private "Unused" class.}} [[sc=17;ec=23]] + private class Unused {} // Noncompliant {{Remove this unused private "Unused" class.}} +// ^^^^^^ private class Used {} // compliant private class Used2 {} // compliant @@ -14,14 +15,17 @@ void fun() { @AnnotationUsed Object o = MyUsedEnum.QIX; } - private interface IUnused {} // Noncompliant {{Remove this unused private "IUnused" class.}} [[sc=21;ec=28]] + private interface IUnused {} // Noncompliant {{Remove this unused private "IUnused" class.}} +// ^^^^^^^ private interface IUsed {} - private enum MyUnusedEnum { // Noncompliant {{Remove this unused private "MyUnusedEnum" class.}} [[sc=16;ec=28]] + private enum MyUnusedEnum { // Noncompliant {{Remove this unused private "MyUnusedEnum" class.}} +// ^^^^^^^^^^^^ FOO, BAR;} private enum MyUsedEnum {QIX, PLOP;} - private @interface AnnotationUnused {} // Noncompliant {{Remove this unused private "AnnotationUnused" class.}} [[sc=22;ec=38]] + private @interface AnnotationUnused {} // Noncompliant {{Remove this unused private "AnnotationUnused" class.}} +// ^^^^^^^^^^^^^^^^ private @interface AnnotationUsed {} } diff --git a/java-checks-test-sources/default/src/main/java/checks/UnusedPrivateMethod.java b/java-checks-test-sources/default/src/main/java/checks/UnusedPrivateMethod.java index 0013ce7d3d4..5e59983de88 100644 --- a/java-checks-test-sources/default/src/main/java/checks/UnusedPrivateMethod.java +++ b/java-checks-test-sources/default/src/main/java/checks/UnusedPrivateMethod.java @@ -23,7 +23,8 @@ private void jakartaInit(@jakarta.enterprise.event.Observes Object object) {} // private void initNc(@AnotherAnnotation Object object) {} // Noncompliant private UnusedPrivateMethodCheck() {} - private UnusedPrivateMethodCheck(int a) {} // Noncompliant [[sc=11;ec=35;quickfixes=qf_constructor]] + private UnusedPrivateMethodCheck(int a) {} // Noncompliant [[quickfixes=qf_constructor]] +// ^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf_constructor {{Remove the unused constructor}} // edit@qf_constructor [[sl=-1;sc=40;el=+0;ec=45]] {{}} @@ -100,14 +101,17 @@ public void bar() { } // This comment will be deleted by the quick fix. - private void testQuickFix1() { // Noncompliant [[sc=16;ec=29;quickfixes=qf1]] + private void testQuickFix1() { // Noncompliant [[quickfixes=qf1]] +// ^^^^^^^^^^^^^ // fix@qf1 {{Remove the unused method}} - // edit@qf1 [[sl=-3;sc=4;el=+4;ec=7]] {{}} + // edit@qf1 [[sl=-3;sc=4;el=+5;ec=4]] {{}} int i = 12; - } - private void testQuickFix2() { // Noncompliant [[sc=16;ec=29;quickfixes=qf2]] + } + + private void testQuickFix2() { // Noncompliant [[quickfixes=qf2]] +// ^^^^^^^^^^^^^ // fix@qf2 {{Remove the unused method}} - // edit@qf2 [[sl=-1;sc=7;el=+5;ec=4]] {{}} + // edit@qf2 [[sl=-2;sc=4;el=+6;ec=4]] {{}} int i = 12; int j = 12; } @@ -316,7 +320,7 @@ private void foo55(int value) {} // Noncompliant abstract static class Coverage1 { - private void foo6() {} // Noncompliant, text blocks are ignored + private void foo6() {} // Noncompliant @ProxyMethod(""" foo6""") diff --git a/java-checks-test-sources/default/src/main/java/checks/UseMotionSensorWithoutGyroscopeCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/UseMotionSensorWithoutGyroscopeCheckSample.java index b9d6b225722..ce6d995d1c7 100644 --- a/java-checks-test-sources/default/src/main/java/checks/UseMotionSensorWithoutGyroscopeCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/UseMotionSensorWithoutGyroscopeCheckSample.java @@ -7,9 +7,11 @@ public class UseMotionSensorWithoutGyroscopeCheckSample { void nonCompliant(SensorManager sensorManager) { sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR); // Noncompliant {{Replace `TYPE_ROTATION_VECTOR` (11) with `TYPE_GEOMAGNETIC_ROTATION_VECTOR` (20) to optimize battery life.}} - sensorManager.getDefaultSensor(11); // Noncompliant [[sc=5;ec=39]] + sensorManager.getDefaultSensor(11); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR, true); // Noncompliant - sensorManager.getDefaultSensor(11, false); // Noncompliant [[sc=5;ec=46]] + sensorManager.getDefaultSensor(11, false); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } void compliant(SensorManager sensorManager, int type) { diff --git a/java-checks-test-sources/default/src/main/java/checks/UselessExtendsCheck.java b/java-checks-test-sources/default/src/main/java/checks/UselessExtendsCheck.java index 27df7ffb904..6877733e78a 100644 --- a/java-checks-test-sources/default/src/main/java/checks/UselessExtendsCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/UselessExtendsCheck.java @@ -6,7 +6,7 @@ interface I2 {} class A implements I1 {} class B extends A implements I1 {} // Noncompliant {{"I1" is implemented by a super class; there is no need to implement it here.}} - class C extends B implements I1 {} // Noncompliant {{"I1" is implemented by a super class; there is no need to implement it here.}} + class C extends B implements I1 {} // Noncompliant {{"I1" is implemented by a super class; there is no need to implement it here.}} interface I3 {} class C1 {} @@ -32,6 +32,8 @@ class H3 implements I9, I8, I7 {} // Noncompliant {{"I7" is already extended by enum E1 implements I7, I8 {} // Noncompliant {{"I7" is already extended by "I8"; there is no need to implement it here.}} - class L extends Object {} // Noncompliant [[sc=19;ec=25]] {{"Object" should not be explicitly extended.}} - class M extends java.lang.Object {} // Noncompliant [[sc=19;ec=35]] {{"Object" should not be explicitly extended.}} + class L extends Object {} // Noncompliant {{"Object" should not be explicitly extended.}} +// ^^^^^^ + class M extends java.lang.Object {} // Noncompliant {{"Object" should not be explicitly extended.}} +// ^^^^^^^^^^^^^^^^ } diff --git a/java-checks-test-sources/default/src/main/java/checks/UselessImportCheck/WithQuickFixes.java b/java-checks-test-sources/default/src/main/java/checks/UselessImportCheck/WithQuickFixes.java index ff4f77c3282..088d1ff6501 100644 --- a/java-checks-test-sources/default/src/main/java/checks/UselessImportCheck/WithQuickFixes.java +++ b/java-checks-test-sources/default/src/main/java/checks/UselessImportCheck/WithQuickFixes.java @@ -2,36 +2,43 @@ import java.util.Map; // fix@qf1 {{Remove the import}} -// edit@qf1 [[sl=6;sc=1;el=7;ec=1]] ̣{{}} -import a.b.c.NotReferencedFromJavadoc; // Noncompliant [[sc=8;ec=38;quickfixes=qf1]] +// edit@qf1 [[sl=6;sc=1;el=8;ec=1]] ̣{{}} +import a.b.c.NotReferencedFromJavadoc; // Noncompliant {{Remove this unused import 'a.b.c.NotReferencedFromJavadoc'.}} [[quickfixes=qf1]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ import java.util.List; import javax.annotation.Nonnull; //fix@qf2 {{Remove the import}} -//edit@qf2 [[sl=11;sc=1;el=12;ec=1]] ̣{{}} -import java.lang.String; // Noncompliant [[sc=8;ec=24;quickfixes=qf2]] {{Remove this unnecessary import: java.lang classes are always implicitly imported.}} -import java.lang.*; // Noncompliant [[sc=8;ec=19;quickfixes=qf3]] {{Remove this unnecessary import: java.lang classes are always implicitly imported.}} +//edit@qf2 [[sl=12;sc=1;el=14;ec=1]] ̣{{}} +import java.lang.String; // Noncompliant {{Remove this unnecessary import: java.lang classes are always implicitly imported.}} [[quickfixes=qf2]] +// ^^^^^^^^^^^^^^^^ +import java.lang.*; // Noncompliant {{Remove this unnecessary import: java.lang classes are always implicitly imported.}} [[quickfixes=qf3]] +// ^^^^^^^^^^^ //fix@qf3 {{Remove the import}} -//edit@qf3 [[sl=12;sc=1;el=15;ec=1]] ̣{{}} +//edit@qf3 [[sl=14;sc=1;el=18;ec=1]] ̣{{}} import javax.annotation.Nullable; import a.b.c.Foo; -import a.b.c.Foo; // Noncompliant [[sc=8;ec=17;quickfixes=qf4]] {{Remove this duplicated import.}} +import a.b.c.Foo; // Noncompliant {{Remove this duplicated import.}} [[quickfixes=qf4]] +// ^^^^^^^^^ //fix@qf4 {{Remove the import}} -//edit@qf4 [[sl=17;sc=1;el=21;ec=1]] ̣{{}} +//edit@qf4 [[sl=20;sc=1;el=25;ec=1]] ̣{{}} -import checks.UselessImportCheck.*; // Noncompliant [[sc=8;ec=35;quickfixes=qf5]] {{Remove this unnecessary import: same package classes are always implicitly imported.}} +import checks.UselessImportCheck.*; // Noncompliant [[quickfixes=qf5]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ //fix@qf5 {{Remove the import}} -//edit@qf5 [[sl=21;sc=1;el=25;ec=1]] ̣{{}} +//edit@qf5 [[sl=25;sc=1;el=30;ec=1]] ̣{{}} import java.util.ArrayList; import java.util.HashMap; -import static checks.UselessImportCheck.SomeEntity.FIND_BY_AGE; // Noncompliant [[sc=15;ec=63;quickfixes=qf6]] +import static checks.UselessImportCheck.SomeEntity.FIND_BY_AGE; // Noncompliant [[quickfixes=qf6]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ //fix@qf6 {{Remove the static import}} -//edit@qf6 [[sl=28;sc=1;el=31;ec=1]] ̣{{}} +//edit@qf6 [[sl=33;sc=1;el=37;ec=1]] ̣{{}} import static checks.UselessImportCheck.Foo2WithQuickFixes.A.FLUP; // compliant, used outside of owning class -import static checks.UselessImportCheck.Foo2WithQuickFixes.A.qix; // Noncompliant [[sc=15;ec=65;quickfixes=qf7]] +import static checks.UselessImportCheck.Foo2WithQuickFixes.A.qix; // Noncompliant [[quickfixes=qf7]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ //fix@qf7 {{Remove the static import}} -//edit@qf7 [[sl=31;sc=67;el=32;ec=66]] ̣{{}} +//edit@qf7 [[sl=37;sc=67;el=38;ec=66]] ̣{{}} class Foo2WithQuickFixes extends Foo { diff --git a/java-checks-test-sources/default/src/main/java/checks/UselessImportCheck/WithQuickFixesSingleImport.java b/java-checks-test-sources/default/src/main/java/checks/UselessImportCheck/WithQuickFixesSingleImport.java index 2e44960d439..c58a6e03948 100644 --- a/java-checks-test-sources/default/src/main/java/checks/UselessImportCheck/WithQuickFixesSingleImport.java +++ b/java-checks-test-sources/default/src/main/java/checks/UselessImportCheck/WithQuickFixesSingleImport.java @@ -1,7 +1,7 @@ package checks.UselessImportCheck; -import java.util.List; // Noncompliant [[sc=8;ec=22;quickfixes=qf1]] - +import java.util.List; // Noncompliant [[quickfixes=qf1]] +// ^^^^^^^^^^^^^^ //fix@qf1 {{Remove the import}} //edit@qf1 [[sl=3;sc=1;el=3;ec=23]] ̣{{}} class WithQuicFixesSingleImport { diff --git a/java-checks-test-sources/default/src/main/java/checks/UselessImportCheck/WithinPackage.java b/java-checks-test-sources/default/src/main/java/checks/UselessImportCheck/WithinPackage.java index 5280ce39508..d5669b937c7 100644 --- a/java-checks-test-sources/default/src/main/java/checks/UselessImportCheck/WithinPackage.java +++ b/java-checks-test-sources/default/src/main/java/checks/UselessImportCheck/WithinPackage.java @@ -14,14 +14,17 @@ import a.b.c.MyAnnotation1; import a.b.c.MyAnnotation2; import a.b.c.MyAnnotation3; -import java.lang.String; // Noncompliant [[sc=8;ec=24]] {{Remove this unnecessary import: java.lang classes are always implicitly imported.}} -import java.lang.*; // Noncompliant [[sc=8;ec=19]] {{Remove this unnecessary import: java.lang classes are always implicitly imported.}} -import a.b.c.Foo; // Noncompliant [[sc=8;ec=17]] {{Remove this duplicated import.}} +import java.lang.String; // Noncompliant {{Remove this unnecessary import: java.lang classes are always implicitly imported.}} +// ^^^^^^^^^^^^^^^^ +import java.lang.*; // Noncompliant {{Remove this unnecessary import: java.lang classes are always implicitly imported.}} +// ^^^^^^^^^^^ +import a.b.c.Foo; // Noncompliant {{Remove this duplicated import.}} +// ^^^^^^^^^ -import checks.UselessImportCheck.*; // Noncompliant {{Remove this unnecessary import: same package classes are always implicitly imported.}} +import checks.UselessImportCheck.*; // Noncompliant {{Remove this unnecessary import: same package classes are always implicitly imported.}} import com.google.common.collect.ImmutableList; -import pkg.NonCompliant1; // Noncompliant +import pkg.NonCompliant1; // Noncompliant import javax.annotation.ParametersAreNonnullByDefault; // Noncompliant import pkg.CompliantClass1; import pkg.CompliantClass2; diff --git a/java-checks-test-sources/default/src/main/java/checks/UselessIncrementCheck.java b/java-checks-test-sources/default/src/main/java/checks/UselessIncrementCheck.java index 19452b322df..e1e2bee6595 100644 --- a/java-checks-test-sources/default/src/main/java/checks/UselessIncrementCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/UselessIncrementCheck.java @@ -12,9 +12,11 @@ public int pickNumber() { return UselessIncrementCheck.var++; } i = i++; // Noncompliant {{Remove this increment or correct the code not to waste it.}} - UselessIncrementCheck.var = UselessIncrementCheck.var++; // Noncompliant [[sc=58;ec=60]] {{Remove this increment or correct the code not to waste it.}} + UselessIncrementCheck.var = UselessIncrementCheck.var++; // Noncompliant {{Remove this increment or correct the code not to waste it.}} +// ^^ UselessIncrementCheck.var = i++; - return j++; // Noncompliant [[sc=13;ec=15]] {{Remove this increment or correct the code not to waste it.}} + return j++; // Noncompliant {{Remove this increment or correct the code not to waste it.}} +// ^^ } public int pickNumber2() { diff --git a/java-checks-test-sources/default/src/main/java/checks/UselessPackageInfoCheck/packageWithNoOtherFiles/package-info.java b/java-checks-test-sources/default/src/main/java/checks/UselessPackageInfoCheck/packageWithNoOtherFiles/package-info.java index ff43da33e03..42e2b4ac036 100644 --- a/java-checks-test-sources/default/src/main/java/checks/UselessPackageInfoCheck/packageWithNoOtherFiles/package-info.java +++ b/java-checks-test-sources/default/src/main/java/checks/UselessPackageInfoCheck/packageWithNoOtherFiles/package-info.java @@ -1 +1,2 @@ package checks.UselessPackageInfoCheck.packageWithNoOtherFiles; +// Noncompliant@0 {{Remove this package.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/UtilityClassWithPublicConstructorCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/UtilityClassWithPublicConstructorCheckSample.java index dedc6062caf..462b2c94300 100644 --- a/java-checks-test-sources/default/src/main/java/checks/UtilityClassWithPublicConstructorCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/UtilityClassWithPublicConstructorCheckSample.java @@ -55,7 +55,8 @@ public void foo() { } } - class Foo3 { // Noncompliant [[sc=9;ec=13]] {{Add a private constructor to hide the implicit public one.}} + class Foo3 { // Noncompliant {{Add a private constructor to hide the implicit public one.}} +// ^^^^ public static void foo() { } } @@ -145,7 +146,8 @@ private Foo13() { ; } - class Foo14 { // Noncompliant [[sc=9;ec=14]] {{Add a private constructor to hide the implicit public one.}} + class Foo14 { // Noncompliant {{Add a private constructor to hide the implicit public one.}} +// ^^^^^ static { } } diff --git a/java-checks-test-sources/default/src/main/java/checks/VarArgCheck.java b/java-checks-test-sources/default/src/main/java/checks/VarArgCheck.java index d22bd6a0967..d9c9ac4f882 100644 --- a/java-checks-test-sources/default/src/main/java/checks/VarArgCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/VarArgCheck.java @@ -1,9 +1,11 @@ package checks; class VarArgCheck { - void nok(int... p) { // Noncompliant [[sc=15;ec=18]] {{Do not use varargs.}} + void nok(int... p) { // Noncompliant {{Do not use varargs.}} +// ^^^ } - void nok(String foo, int... p) { // Noncompliant [[sc=27;ec=30]] {{Do not use varargs.}} + void nok(String foo, int... p) { // Noncompliant {{Do not use varargs.}} +// ^^^ } void ok() { } diff --git a/java-checks-test-sources/default/src/main/java/checks/VarCanBeUsedCheck.java b/java-checks-test-sources/default/src/main/java/checks/VarCanBeUsedCheck.java index f72ef6677c9..2da59e72197 100644 --- a/java-checks-test-sources/default/src/main/java/checks/VarCanBeUsedCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/VarCanBeUsedCheck.java @@ -22,7 +22,8 @@ void f(int[] array) { String undefinedString; String s = "ABC"; // Noncompliant - String s1 = new String("ABC"); // Noncompliant [[sc=12;ec=14]] {{Declare this local variable with "var" instead.}} + String s1 = new String("ABC"); // Noncompliant {{Declare this local variable with "var" instead.}} +// ^^ int i = 10; // Noncompliant long l = 10L; // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/VirtualThreadNotSynchronizedCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/VirtualThreadNotSynchronizedCheckSample.java index cd4ec8afcd0..e486106090e 100644 --- a/java-checks-test-sources/default/src/main/java/checks/VirtualThreadNotSynchronizedCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/VirtualThreadNotSynchronizedCheckSample.java @@ -6,8 +6,10 @@ public class VirtualThreadNotSynchronizedCheckSample { void smoketest() { - Thread.startVirtualThread(() -> { // Noncompliant[[sc=5;ec=30;secondary=10]] {{Use a platform thread instead of a virtual thread}} + Thread.startVirtualThread(() -> { // Noncompliant {{Use a platform thread instead of a virtual thread}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^ synchronized(this) { +// ^^^^^^^^^^^^< System.out.println(); } }); @@ -21,7 +23,8 @@ void runnableToCheckForSynchronized() { Thread.Builder builderToCheck = Thread.ofVirtual(); // Secondary builderToCheck.start(() -> synchronizedMethod()); // Noncompliant - Executors.newVirtualThreadPerTaskExecutor().execute(() -> synchronizedMethod()); // Noncompliant[[sc=5;ec=56;secondary=24]] + Executors.newVirtualThreadPerTaskExecutor().execute(() -> synchronizedMethod()); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^< ExecutorService executorToCheck = Executors.newVirtualThreadPerTaskExecutor(); executorToCheck.execute(() -> synchronizedMethod()); // Noncompliant executorToCheck.submit(() -> synchronizedMethod()); // Noncompliant @@ -63,6 +66,7 @@ private void nonSynchronizedMethod() {} private void methodWithSynchronizedBlock() { synchronized (this) {} +// ^^^^^^^^^^^^> } private void methodInvokingSynchronizedBlockL2() { @@ -90,6 +94,7 @@ void testPropagationOfSynchronizedAttribute(boolean condition) { }); Thread.startVirtualThread(() -> { // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^ methodWithSynchronizedBlock(); }); @@ -116,7 +121,8 @@ void testPropagationOfSynchronizedAttribute(boolean condition) { } }); - Thread.startVirtualThread(() -> { // Noncompliant[[sc=5;ec=30;secondary=65]] + Thread.startVirtualThread(() -> { // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^ methodInvokingSynchronizedBlockL4(); }); } diff --git a/java-checks-test-sources/default/src/main/java/checks/VirtualThreadUnsupportedMethodsSample.java b/java-checks-test-sources/default/src/main/java/checks/VirtualThreadUnsupportedMethodsSample.java index 3aa1caefc4a..df0b51db10c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/VirtualThreadUnsupportedMethodsSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/VirtualThreadUnsupportedMethodsSample.java @@ -23,13 +23,18 @@ public class VirtualThreadUnsupportedMethodsSample extends VirtualThreadUnsuppor void noncompliant(Thread.Builder.OfVirtual builder) { var vt = builder.unstarted(() -> { +// ^^^^^^^^^> }); - vt.setDaemon(true); // Noncompliant [[secondary=-2]] - vt.setPriority(1); // Noncompliant [[secondary=-3]] - vt.getThreadGroup(); // Noncompliant [[secondary=-4]] - + vt.setDaemon(true); // Noncompliant +// ^^^^^^^^^ + vt.setPriority(1); // Noncompliant +// ^^^^^^^^^^^ + vt.getThreadGroup(); // Noncompliant +// ^^^^^^^^^^^^^^ Thread.startVirtualThread(() -> { - }).setDaemon(true); // Noncompliant [[secondary=-1]] +// ^^^^^^^^^^^^^^^^^^> + }).setDaemon(true); // Noncompliant +// ^^^^^^^^^ var newBuilder = Thread.ofVirtual(); var vt1 = newBuilder.unstarted(() -> { diff --git a/java-checks-test-sources/default/src/main/java/checks/VisibleForTestingUsageCheck/Service.java b/java-checks-test-sources/default/src/main/java/checks/VisibleForTestingUsageCheck/Service.java index 8de98a1f02c..6c01989ce42 100644 --- a/java-checks-test-sources/default/src/main/java/checks/VisibleForTestingUsageCheck/Service.java +++ b/java-checks-test-sources/default/src/main/java/checks/VisibleForTestingUsageCheck/Service.java @@ -14,15 +14,20 @@ public String f(int param) { String foo = new MyObj().bar; // False negative MyObj and Service are in the same file but if 'bar' is private it wouldn't be visible here) - MyObject myObject = new MyObject(123); // Noncompliant[[sc=29;ec=37;secondary=19,21]]{{Remove this usage of "MyObject", it is annotated with @VisibleForTesting and should not be accessed from production code.}} + MyObject myObject = new MyObject(123); // Noncompliant {{Remove this usage of "MyObject", it is annotated with @VisibleForTesting and should not be accessed from production code.}} +// ^^^^^^^^ MyObject myObject2 = new MyObject(456); // Already reported in line 17 - String foo1 = new MyObject(42).foo;// Noncompliant[[sc=36;ec=39;secondary=25]]{{Remove this usage of "foo", it is annotated with @VisibleForTesting and should not be accessed from production code.}} + + String foo1 = new MyObject(42).foo; // Noncompliant {{Remove this usage of "foo", it is annotated with @VisibleForTesting and should not be accessed from production code.}} +// ^^^ + String bar = new MyObj().bar; return new MyObject().foo; // Already reported in line 21 + } public int g(@Deprecated int param) { diff --git a/java-checks-test-sources/default/src/main/java/checks/VolatileNonPrimitiveFieldCheck.java b/java-checks-test-sources/default/src/main/java/checks/VolatileNonPrimitiveFieldCheck.java index 504c16edfa1..2b0ccbbc4b2 100644 --- a/java-checks-test-sources/default/src/main/java/checks/VolatileNonPrimitiveFieldCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/VolatileNonPrimitiveFieldCheck.java @@ -33,11 +33,16 @@ class VolatileNonPrimitiveFieldCheck { private volatile int vInts0; - private volatile int [] vInts; // Noncompliant [[sc=11;ec=26]] {{Use an "AtomicIntegerArray" instead.}} - private volatile long [] vLongs; // Noncompliant [[sc=11;ec=27]] {{Use an "AtomicLongArray" instead.}} - private volatile Object [] vObjects; // Noncompliant [[sc=11;ec=29]] {{Use an "AtomicReferenceArray" instead.}} - private volatile VolatileNonPrimitiveFieldCheckObj myObj; // Noncompliant [[sc=11;ec=53]] {{Use a thread-safe type; adding "volatile" is not enough to make this field thread-safe.}} - private volatile Date myDate; // Noncompliant [[sc=11;ec=24]] {{Use a thread-safe type; adding "volatile" is not enough to make this field thread-safe.}} + private volatile int [] vInts; // Noncompliant {{Use an "AtomicIntegerArray" instead.}} +// ^^^^^^^^^^^^^^^ + private volatile long [] vLongs; // Noncompliant {{Use an "AtomicLongArray" instead.}} +// ^^^^^^^^^^^^^^^^ + private volatile Object [] vObjects; // Noncompliant {{Use an "AtomicReferenceArray" instead.}} +// ^^^^^^^^^^^^^^^^^^ + private volatile VolatileNonPrimitiveFieldCheckObj myObj; // Noncompliant {{Use a thread-safe type; adding "volatile" is not enough to make this field thread-safe.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + private volatile Date myDate; // Noncompliant {{Use a thread-safe type; adding "volatile" is not enough to make this field thread-safe.}} +// ^^^^^^^^^^^^^ private AtomicIntegerArray vInts2; private VolatileNonPrimitiveFieldCheckObj myObj2; // enums are considered as immutable @@ -93,8 +98,10 @@ void foo(){} enum VolatileNonPrimitiveFieldCheckEnum { FOO; private volatile int vInts0; - private volatile int [] vInts; // Noncompliant [[sc=11;ec=26]] {{Use an "AtomicIntegerArray" instead.}} - private volatile VolatileNonPrimitiveFieldCheckObj myObj; // Noncompliant [[sc=11;ec=53]] {{Use a thread-safe type; adding "volatile" is not enough to make this field thread-safe.}} + private volatile int [] vInts; // Noncompliant {{Use an "AtomicIntegerArray" instead.}} +// ^^^^^^^^^^^^^^^ + private volatile VolatileNonPrimitiveFieldCheckObj myObj; // Noncompliant {{Use a thread-safe type; adding "volatile" is not enough to make this field thread-safe.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ private AtomicIntegerArray vInts2; private VolatileNonPrimitiveFieldCheckObj myObj2; diff --git a/java-checks-test-sources/default/src/main/java/checks/VolatileVariablesOperationsCheck.java b/java-checks-test-sources/default/src/main/java/checks/VolatileVariablesOperationsCheck.java index ed8813f9155..422ddfa8695 100644 --- a/java-checks-test-sources/default/src/main/java/checks/VolatileVariablesOperationsCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/VolatileVariablesOperationsCheck.java @@ -49,10 +49,10 @@ public void decrementCounts() { } public boolean toggleBooleans(){ - boo1 = !boo1; // Noncompliant {{Use an "AtomicBoolean" for this field; its operations are atomic.}} - boo1 = (!boo1); // Noncompliant - boo1 = !(boo1); // Noncompliant - this.boo1 = (!this.boo1); // Noncompliant + boo1 = !boo1; // Noncompliant {{Use an "AtomicBoolean" for this field; its operations are atomic.}} + boo1 = (!boo1); // Noncompliant + boo1 = !(boo1); // Noncompliant + this.boo1 = (!this.boo1); // Noncompliant boo2 = !boo2; boo2 = !boo1; this.boo2 = (!this.boo1); diff --git a/java-checks-test-sources/default/src/main/java/checks/WaitOnConditionCheck.java b/java-checks-test-sources/default/src/main/java/checks/WaitOnConditionCheck.java index 23694c5bbf6..d06a16abfc7 100644 --- a/java-checks-test-sources/default/src/main/java/checks/WaitOnConditionCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/WaitOnConditionCheck.java @@ -9,10 +9,12 @@ void foo() throws InterruptedException { new C().wait(); new C().wait(1); new C().wait(1, 3); - new B().wait(); // Noncompliant [[sc=13;ec=17]] {{The "Condition.await(...)" method should be used instead of "Object.wait(...)"}} - MyFunctionalInterface r = new B()::wait; // Noncompliant [[sc=40;ec=44]] {{The "Condition.await(...)" method should be used instead of "Object.wait(...)"}} - new B().wait(1); // Noncompliant - new B().wait(1, 3); // Noncompliant + new B().wait(); // Noncompliant {{The "Condition.await(...)" method should be used instead of "Object.wait(...)"}} +// ^^^^ + MyFunctionalInterface r = new B()::wait; // Noncompliant {{The "Condition.await(...)" method should be used instead of "Object.wait(...)"}} +// ^^^^ + new B().wait(1); // Noncompliant + new B().wait(1, 3); // Noncompliant } class B implements Condition { diff --git a/java-checks-test-sources/default/src/main/java/checks/WeakSSLContextCheck.java b/java-checks-test-sources/default/src/main/java/checks/WeakSSLContextCheck.java index 8fd215d7f21..2288b96dc85 100644 --- a/java-checks-test-sources/default/src/main/java/checks/WeakSSLContextCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/WeakSSLContextCheck.java @@ -16,7 +16,8 @@ class WeakSSLContextCheck { void foo(String protocol, String provider) throws NoSuchAlgorithmException, NoSuchProviderException { bar(SSLContext.getInstance(protocol)); - bar(SSLContext.getInstance("SSL")); // Noncompliant [[sc=32;ec=37]] {{Change this code to use a stronger protocol.}} + bar(SSLContext.getInstance("SSL")); // Noncompliant {{Change this code to use a stronger protocol.}} +// ^^^^^ bar(SSLContext.getInstance("SSLv2")); // Noncompliant bar(SSLContext.getInstance("SSLv3")); // Noncompliant bar(SSLContext.getInstance("TLS")); // Noncompliant @@ -42,11 +43,13 @@ void bar(SSLContext ctx) { void okHttp(String argumentVersion) { ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) - .tlsVersions(TlsVersion.TLS_1_0) // Noncompliant [[sc=20;ec=38]] {{Change this code to use a stronger protocol.}} + .tlsVersions(TlsVersion.TLS_1_0) // Noncompliant {{Change this code to use a stronger protocol.}} +// ^^^^^^^^^^^^^^^^^^ .build(); ConnectionSpec spec2 = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) - .tlsVersions(TLS_1_1) // Noncompliant [[sc=20;ec=27]] {{Change this code to use a stronger protocol.}} + .tlsVersions(TLS_1_1) // Noncompliant {{Change this code to use a stronger protocol.}} +// ^^^^^^^ .build(); ConnectionSpec spec3 = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) @@ -62,7 +65,8 @@ void okHttp(String argumentVersion) { .build(); ConnectionSpec specWithString = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) - .tlsVersions("TLSv1") // Noncompliant [[sc=20;ec=27]] + .tlsVersions("TLSv1") // Noncompliant +// ^^^^^^^ .build(); ConnectionSpec specWithString2 = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) @@ -74,17 +78,22 @@ void okHttp(String argumentVersion) { .build(); ConnectionSpec specWithMultipleVersions = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) - .tlsVersions(TlsVersion.TLS_1_3, TlsVersion.TLS_1_1) // Noncompliant [[sc=40;ec=58]] + .tlsVersions(TlsVersion.TLS_1_3, TlsVersion.TLS_1_1) // Noncompliant +// ^^^^^^^^^^^^^^^^^^ .build(); ConnectionSpec specWithMultipleWeakVersions = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) - .tlsVersions(TlsVersion.TLS_1_0, // Noncompliant [[sc=20;ec=38;secondary=+1]] + .tlsVersions(TlsVersion.TLS_1_0, // Noncompliant +// ^^^^^^^^^^^^^^^^^^ TlsVersion.TLS_1_1) +// ^^^^^^^^^^^^^^^^^^< .build(); ConnectionSpec specWithMultipleWeakVersions2 = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) - .tlsVersions("TLSv1", // Noncompliant [[sc=20;ec=27;secondary=+1]] + .tlsVersions("TLSv1", // Noncompliant +// ^^^^^^^ "TLSv1.1") +// ^^^^^^^^^< .build(); ConnectionSpec specWithUnknownValue = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) diff --git a/java-checks-test-sources/default/src/main/java/checks/WeakSSLContextCheckJava8.java b/java-checks-test-sources/default/src/main/java/checks/WeakSSLContextCheckJava8.java index c4340b0c619..84729c67acc 100644 --- a/java-checks-test-sources/default/src/main/java/checks/WeakSSLContextCheckJava8.java +++ b/java-checks-test-sources/default/src/main/java/checks/WeakSSLContextCheckJava8.java @@ -9,7 +9,8 @@ class WeakSSLContextCheckJava8 { void foo(String protocol, String provider) throws NoSuchAlgorithmException, NoSuchProviderException { bar(SSLContext.getInstance(protocol)); - bar(SSLContext.getInstance("SSL")); // Noncompliant [[sc=32;ec=37]] {{Change this code to use a stronger protocol.}} + bar(SSLContext.getInstance("SSL")); // Noncompliant {{Change this code to use a stronger protocol.}} +// ^^^^^ bar(SSLContext.getInstance("SSLv2")); // Noncompliant bar(SSLContext.getInstance("SSLv3")); // Noncompliant bar(SSLContext.getInstance("TLS")); // compliant, refer to latest version of protocol diff --git a/java-checks-test-sources/default/src/main/java/checks/WildcardImportsShouldNotBeUsedCheck.java b/java-checks-test-sources/default/src/main/java/checks/WildcardImportsShouldNotBeUsedCheck.java index ee9bf0d231b..9df263ffe28 100644 --- a/java-checks-test-sources/default/src/main/java/checks/WildcardImportsShouldNotBeUsedCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/WildcardImportsShouldNotBeUsedCheck.java @@ -1,7 +1,8 @@ package checks; -import java.io.*; // Noncompliant [[sc=8;ec=17]] {{Explicitly import the specific classes needed.}} -import java.util.*; // Noncompliant {{Explicitly import the specific classes needed.}} +import java.io.*; // Noncompliant {{Explicitly import the specific classes needed.}} +// ^^^^^^^^^ +import java.util.*; // Noncompliant {{Explicitly import the specific classes needed.}} import org.apache.commons.io.*; // Noncompliant {{Explicitly import the specific classes needed.}} import java.sql.Date; // Not used in code but at least one non static import import static java.util.Arrays.*; // Compliant, exception with static imports diff --git a/java-checks-test-sources/default/src/main/java/checks/WildcardReturnParameterTypeCheck.java b/java-checks-test-sources/default/src/main/java/checks/WildcardReturnParameterTypeCheck.java index c21979416b1..cecae6e05c0 100644 --- a/java-checks-test-sources/default/src/main/java/checks/WildcardReturnParameterTypeCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/WildcardReturnParameterTypeCheck.java @@ -8,7 +8,7 @@ class WildcardReturnParameterTypeCheck { class Animal { - public List getAnimals() { // Noncompliant + public List getAnimals() { // Noncompliant Collection c = new ArrayList(); // Compliant return null; } @@ -19,7 +19,8 @@ public List getAnimals2() { // Compliant } class Cat extends Animal { - public List getCats() { // Noncompliant [[sc=17;ec=18]] + public List getCats() { // Noncompliant +// ^ return null; } } @@ -57,11 +58,11 @@ private List getCats() { //Compliant private method are ignored public Collector getCollector2() { // Noncompliant + ?> getCollector2() { // Noncompliant return null; } - public MyCollector getMyCollector() { // Noncompliant + public MyCollector getMyCollector() { // Noncompliant return null; } diff --git a/java-checks-test-sources/default/src/main/java/checks/WrongAssignmentOperatorCheck.java b/java-checks-test-sources/default/src/main/java/checks/WrongAssignmentOperatorCheck.java index 3055c8b1ce8..c2a08e254fb 100644 --- a/java-checks-test-sources/default/src/main/java/checks/WrongAssignmentOperatorCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/WrongAssignmentOperatorCheck.java @@ -6,14 +6,16 @@ class WrongAssignmentOperatorCheck { int num = 3; void fun() { - target =-num; // Noncompliant {{Was "-=" meant instead?}} [[sc=12;ec=14]] + target =-num; // Noncompliant {{Was "-=" meant instead?}} +// ^^ target = -num; target = -num; // Compliant intent to assign inverse value of num is clear target =--num; target += num; - target =+ num; // Noncompliant {{Was "+=" meant instead?}} [[sc=12;ec=14]] + target =+ num; // Noncompliant {{Was "+=" meant instead?}} +// ^^ target = + num; target = @@ -23,7 +25,8 @@ void fun() { target=+num; // Compliant - no spaces between variable, operator and expression a = b != c; - a = b =! c; // Noncompliant {{Was "!=" meant instead?}} [[sc=11;ec=13]] + a = b =! c; // Noncompliant {{Was "!=" meant instead?}} +// ^^ a = b =!! c; // Noncompliant a = b = !c; a =! c; // Noncompliant {{Add a space between "=" and "!" to avoid confusion.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/design/ClassImportCouplingCheck.java b/java-checks-test-sources/default/src/main/java/checks/design/ClassImportCouplingCheck.java index a823e3a196e..c4a16de59ed 100644 --- a/java-checks-test-sources/default/src/main/java/checks/design/ClassImportCouplingCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/design/ClassImportCouplingCheck.java @@ -7,38 +7,60 @@ import org.sonar.api.SonarProduct; ; -class ClassImportCouplingCheck { // Noncompliant [[sc=7;ec=31;secondary=15, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 40, 40, 40, 41, 48, 57, 74, 74, 79, 81, 87]] {{Split this “Monster Class” into smaller and more specialized ones to reduce its dependencies on other classes from 23 to the maximum authorized 20 or less.}} - +class ClassImportCouplingCheck { // Noncompliant {{Split this “Monster Class” into smaller and more specialized ones to reduce its dependencies on other classes from 23 to the maximum authorized 20 or less.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^ List a = new ArrayList<>(); SonarProduct sonarProduct; TestClass test; - +//^^^^^^^^^< List someList; - +// ^^^^^^^^^< T1 t1; +//^^< T2 t2; +//^^< T3 t3; +//^^< T4 t4; +//^^< T5 t5; +//^^< T6 t6; +//^^< T7 t7; +//^^< T8 t8; +//^^< T9 t9; +//^^< T10 t10; +//^^^< T11 t11; +//^^^< T12 t12; +//^^^< T13 t13; +//^^^< T14 t14; +//^^^< T15 t15; +//^^^< T16 t16; +//^^^< T17 t17; +//^^^< T18 t18; +//^^^< T19 t19; +//^^^< T20 t20; +//^^^< public TestClass2 method(Math math, TestClass testClass, TestClass2 testClass2) { +// ^^^^^^^^^^< ^^^^^^^^^< ^^^^^^^^^^< TestClass2 t2 = new TestClass2(); +// ^^^^^^^^^^< if (t2.equals(new Object())) { } Assertions.assertTrue(true); @@ -46,6 +68,7 @@ public TestClass2 method(Math math, TestClass testClass, TestClass2 testClass2) } TestAbstract testAbstract = new TestAbstract() { +//^^^^^^^^^^^^< @Override void t() { @@ -55,6 +78,7 @@ void t() { enum Qax { ; T1 foo() { +// ^^< return null; } } @@ -72,19 +96,23 @@ void m() { Object o; checks.design.T1 t1 = (checks.design.T1) o; +// ^^^^^^^^^^^^^^^^< ^^^^^^^^^^^^^^^^< java.util.Collections collections; } String producerExtends(List elements) { +// ^^< StringBuilder builder = new StringBuilder(); for (T1 element : elements) { +// ^^< builder.append(element.toString()); } return builder.toString(); } String consumerSupers(List elements) { +// ^^< StringBuilder builder = new StringBuilder(); for (var element : elements) { builder.append(element.toString()); diff --git a/java-checks-test-sources/default/src/main/java/checks/emptyclass/EmptyClass.java b/java-checks-test-sources/default/src/main/java/checks/emptyclass/EmptyClass.java index 9521cd0e114..f03f352e1b4 100644 --- a/java-checks-test-sources/default/src/main/java/checks/emptyclass/EmptyClass.java +++ b/java-checks-test-sources/default/src/main/java/checks/emptyclass/EmptyClass.java @@ -4,7 +4,8 @@ class A { int field; } -class B { // Noncompliant [[sc=7;ec=8]] {{Remove this empty class, write its code or make it an "interface".}} +class B { // Noncompliant {{Remove this empty class, write its code or make it an "interface".}} +// ^ } class C { I i = new I() {}; diff --git a/java-checks-test-sources/default/src/main/java/checks/naming/BadClassNameNoncompliant.java b/java-checks-test-sources/default/src/main/java/checks/naming/BadClassNameNoncompliant.java index 34d87783dfb..efe4888477e 100644 --- a/java-checks-test-sources/default/src/main/java/checks/naming/BadClassNameNoncompliant.java +++ b/java-checks-test-sources/default/src/main/java/checks/naming/BadClassNameNoncompliant.java @@ -3,7 +3,8 @@ import java.util.ResourceBundle; class BadClassNameNoncompliant { - class badClassName { } // Noncompliant [[sc=9;ec=21]] {{Rename this class name to match the regular expression '^[A-Z][a-zA-Z0-9]*$'.}} + class badClassName { } // Noncompliant {{Rename this class name to match the regular expression '^[A-Z][a-zA-Z0-9]*$'.}} +// ^^^^^^^^^^^^ class GoodClassName { } // Compliant interface should_not_be_checked_interface { } // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/naming/BadFieldName.java b/java-checks-test-sources/default/src/main/java/checks/naming/BadFieldName.java index b45f69c2d3e..9abec87ffdf 100644 --- a/java-checks-test-sources/default/src/main/java/checks/naming/BadFieldName.java +++ b/java-checks-test-sources/default/src/main/java/checks/naming/BadFieldName.java @@ -1,7 +1,8 @@ package checks.naming; class BadFieldName { - public int BAD_FIELD_NAME; // Noncompliant [[sc=14;ec=28]] {{Rename this field "BAD_FIELD_NAME" to match the regular expression '^[a-z][a-zA-Z0-9]*$'.}} + public int BAD_FIELD_NAME; // Noncompliant {{Rename this field "BAD_FIELD_NAME" to match the regular expression '^[a-z][a-zA-Z0-9]*$'.}} +// ^^^^^^^^^^^^^^ public int goodFieldName; public static int STATIC; diff --git a/java-checks-test-sources/default/src/main/java/checks/naming/BadInterfaceNameNoncompliant.java b/java-checks-test-sources/default/src/main/java/checks/naming/BadInterfaceNameNoncompliant.java index 13af4c0ecd8..03228466410 100644 --- a/java-checks-test-sources/default/src/main/java/checks/naming/BadInterfaceNameNoncompliant.java +++ b/java-checks-test-sources/default/src/main/java/checks/naming/BadInterfaceNameNoncompliant.java @@ -1,6 +1,7 @@ package checks.naming; -interface badInterfaceName { // Noncompliant [[sc=11;ec=27]] {{Rename this interface name to match the regular expression '^[A-Z][a-zA-Z0-9]*$'.}} +interface badInterfaceName { // Noncompliant {{Rename this interface name to match the regular expression '^[A-Z][a-zA-Z0-9]*$'.}} +// ^^^^^^^^^^^^^^^^ } interface GoodInterfaceName { diff --git a/java-checks-test-sources/default/src/main/java/checks/naming/BadRecordNameNoncompliant.java b/java-checks-test-sources/default/src/main/java/checks/naming/BadRecordNameNoncompliant.java index 9c65aa02629..007275415e5 100644 --- a/java-checks-test-sources/default/src/main/java/checks/naming/BadRecordNameNoncompliant.java +++ b/java-checks-test-sources/default/src/main/java/checks/naming/BadRecordNameNoncompliant.java @@ -2,6 +2,7 @@ public class BadRecordNameNoncompliant { - record badRecordName() { } // Noncompliant [[sc=10;ec=23]] {{Rename this record name to match the regular expression '^[A-Z][a-zA-Z0-9]*$'.}} + record badRecordName() { } // Noncompliant {{Rename this record name to match the regular expression '^[A-Z][a-zA-Z0-9]*$'.}} +// ^^^^^^^^^^^^^ record GoodRecordName() { } } diff --git a/java-checks-test-sources/default/src/main/java/checks/naming/ClassNamedLikeExceptionCheck.java b/java-checks-test-sources/default/src/main/java/checks/naming/ClassNamedLikeExceptionCheck.java index 0095b513fb5..4c0d7e178af 100644 --- a/java-checks-test-sources/default/src/main/java/checks/naming/ClassNamedLikeExceptionCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/naming/ClassNamedLikeExceptionCheck.java @@ -2,9 +2,11 @@ class ClassNamedLikeExceptionCheck { - class AException {} // Noncompliant [[sc=9;ec=19]] {{Rename this class to remove "Exception" or correct its inheritance.}} + class AException {} // Noncompliant {{Rename this class to remove "Exception" or correct its inheritance.}} +// ^^^^^^^^^^ class BException extends NullPointerException {} class EException extends Exception {} // Compliant - class FException extends AException {} // Noncompliant [[sc=9;ec=19]] + class FException extends AException {} // Noncompliant +// ^^^^^^^^^^ class ExceptionHandler {} } diff --git a/java-checks-test-sources/default/src/main/java/checks/naming/FieldNameMatchingTypeNameCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/naming/FieldNameMatchingTypeNameCheckSample.java index e676958319f..b7bb7841826 100644 --- a/java-checks-test-sources/default/src/main/java/checks/naming/FieldNameMatchingTypeNameCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/naming/FieldNameMatchingTypeNameCheckSample.java @@ -1,7 +1,8 @@ package checks.naming; class A { - String A; // Noncompliant {{Rename field "A"}} [[sc=10;ec=11]] + String A; // Noncompliant {{Rename field "A"}} +// ^ public String B; void A() { } @@ -9,7 +10,8 @@ void A() { class B extends A { } class aClass { - String AcLass; // Noncompliant [[sc=10;ec=16]] + String AcLass; // Noncompliant +// ^^^^^^ aClass AClass; // Noncompliant void method() { String AcLaSS; diff --git a/java-checks-test-sources/default/src/main/java/checks/naming/MethodNamedHashcodeOrEqualCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/naming/MethodNamedHashcodeOrEqualCheckSample.java index a93626dccc1..7ebb7fb0725 100644 --- a/java-checks-test-sources/default/src/main/java/checks/naming/MethodNamedHashcodeOrEqualCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/naming/MethodNamedHashcodeOrEqualCheckSample.java @@ -13,7 +13,8 @@ int hashcode(int a, int b) { // Noncompliant return a + b; } - void equal() { // Noncompliant [[sc=8;ec=13]] {{Either override Object.equals(Object obj), or totally rename the method to prevent any confusion.}} + void equal() { // Noncompliant {{Either override Object.equals(Object obj), or totally rename the method to prevent any confusion.}} +// ^^^^^ } int equal(Object obj) { // Noncompliant @@ -24,7 +25,8 @@ public boolean equals(Object obj) { return false; } - void tostring() { // Noncompliant [[sc=8;ec=16]] {{Either override Object.toString(), or totally rename the method to prevent any confusion.}} + void tostring() { // Noncompliant {{Either override Object.toString(), or totally rename the method to prevent any confusion.}} +// ^^^^^^^^ } public String toString() { // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/AbstractRegexCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/regex/AbstractRegexCheckSample.java index 00d30fe3118..f945bda2c2d 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/AbstractRegexCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/AbstractRegexCheckSample.java @@ -69,15 +69,15 @@ void test(String regex) { // org.apache.commons.lang3.RegExUtils Pattern pattern = Pattern.compile(regex); f(RegExUtils.removeAll("text", pattern)); - f(RegExUtils.removeAll("text", "regex")); // Noncompliant {{regex}} + f(RegExUtils.removeAll("text", "regex")); // Noncompliant {{regex}} f(RegExUtils.removeFirst("text", pattern)); - f(RegExUtils.removeFirst("text", "regex")); // Noncompliant {{regex}} + f(RegExUtils.removeFirst("text", "regex")); // Noncompliant {{regex}} f(RegExUtils.replaceAll("text", pattern, "text")); - f(RegExUtils.replaceAll("text", "regex", "text")); // Noncompliant {{regex}} + f(RegExUtils.replaceAll("text", "regex", "text")); // Noncompliant {{regex}} f(RegExUtils.replaceFirst("text", pattern, "text")); - f(RegExUtils.replaceFirst("text", "regex", "text")); // Noncompliant {{regex}} - f(RegExUtils.removePattern("text", "regex")); // Noncompliant {{regex,initialFlags=32}} - f(RegExUtils.replacePattern("text", "regex", "text")); // Noncompliant {{regex,initialFlags=32}} + f(RegExUtils.replaceFirst("text", "regex", "text")); // Noncompliant {{regex}} + f(RegExUtils.removePattern("text", "regex")); // Noncompliant {{regex,initialFlags=32}} + f(RegExUtils.replacePattern("text", "regex", "text")); // Noncompliant {{regex,initialFlags=32}} } abstract void f(boolean x); diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/AnchorPrecedenceCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/regex/AnchorPrecedenceCheckSample.java index e729f34479d..5ce2de7e54a 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/AnchorPrecedenceCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/AnchorPrecedenceCheckSample.java @@ -4,20 +4,29 @@ public class AnchorPrecedenceCheckSample { - @Email(regexp = "^a|b|c$") // Noncompliant [[sc=20;ec=27]] + @Email(regexp = "^a|b|c$") // Noncompliant +// ^^^^^^^ String email; - @jakarta.validation.constraints.Email(regexp = "^a|b|c$") // Noncompliant [[sc=51;ec=58]] + @jakarta.validation.constraints.Email(regexp = "^a|b|c$") // Noncompliant +// ^^^^^^^ String email2; void noncompliant(String str) { - str.matches("^a|b|c$"); // Noncompliant [[sc=18;ec=25]] {{Group parts of the regex together to make the intended operator precedence explicit.}} - str.matches("^a|b|cd"); // Noncompliant [[sc=18;ec=25]] - str.matches("(?i)^a|b|cd"); // Noncompliant [[sc=18;ec=29]] - str.matches("(?i:^a|b|cd)"); // Noncompliant [[sc=22;ec=29]] - str.matches("a|b|c$"); // Noncompliant [[sc=18;ec=24]] - str.matches("\\Aa|b|c\\Z"); // Noncompliant [[sc=18;ec=29]] - str.matches("\\Aa|b|c\\z"); // Noncompliant [[sc=18;ec=29]] + str.matches("^a|b|c$"); // Noncompliant {{Group parts of the regex together to make the intended operator precedence explicit.}} +// ^^^^^^^ + str.matches("^a|b|cd"); // Noncompliant +// ^^^^^^^ + str.matches("(?i)^a|b|cd"); // Noncompliant +// ^^^^^^^^^^^ + str.matches("(?i:^a|b|cd)"); // Noncompliant +// ^^^^^^^ + str.matches("a|b|c$"); // Noncompliant +// ^^^^^^ + str.matches("\\Aa|b|c\\Z"); // Noncompliant +// ^^^^^^^^^^^ + str.matches("\\Aa|b|c\\z"); // Noncompliant +// ^^^^^^^^^^^ } void compliant(String str) { diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/CanonEqFlagInRegexCheck.java b/java-checks-test-sources/default/src/main/java/checks/regex/CanonEqFlagInRegexCheck.java index 36c1a69f7c5..ebd6656116e 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/CanonEqFlagInRegexCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/CanonEqFlagInRegexCheck.java @@ -6,20 +6,25 @@ public class CanonEqFlagInRegexCheck { - @Email(regexp = "éeéc") // Noncompliant [[sc=20;ec=24;secondary=9,9]] {{Use the CANON_EQ flag with this pattern.}} + @Email(regexp = "éeéc") // Noncompliant {{Use the CANON_EQ flag with this pattern.}} +// ^^^^ + // ^@-1< + // ^@-2< String email1; @Email(regexp = "éeéc", flags = Flag.CANON_EQ) // Compliant String email2; - @jakarta.validation.constraints.Email(regexp = "éeéc") // Noncompliant [[sc=51;ec=55;secondary=15,15]] {{Use the CANON_EQ flag with this pattern.}} + @jakarta.validation.constraints.Email(regexp = "éeéc") // Noncompliant {{Use the CANON_EQ flag with this pattern.}} +// ^^^^ String email3; @jakarta.validation.constraints.Email(regexp = "éeéc", flags = jakarta.validation.constraints.Pattern.Flag.CANON_EQ) // Compliant String email4; void noncompliant(String str) { - Pattern.compile("éeéc"); // Noncompliant [[sc=22;ec=26;secondary=22,22]] {{Use the CANON_EQ flag with this pattern.}} + Pattern.compile("éeéc"); // Noncompliant {{Use the CANON_EQ flag with this pattern.}} +// ^^^^ Pattern.compile("é"); // Noncompliant Pattern.compile("é|è"); // Noncompliant Pattern.compile("à"); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/DuplicatesInCharacterClassCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/regex/DuplicatesInCharacterClassCheckSample.java index 434fb651832..6c15b2aa9df 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/DuplicatesInCharacterClassCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/DuplicatesInCharacterClassCheckSample.java @@ -4,46 +4,91 @@ public class DuplicatesInCharacterClassCheckSample { void nonCompliant() { String str = "123"; - str.matches("[0-99]"); // Noncompliant [[sc=19;ec=22;secondary=7]] {{Remove duplicates in this character class.}} - str.matches("[90-9]"); // Noncompliant [[sc=19;ec=20;secondary=8]] - str.matches("[0-73-9]"); // Noncompliant [[sc=19;ec=22]] - str.matches("[0-93-57]"); // Noncompliant [[sc=19;ec=22;secondary=10,10]] - str.matches("[4-92-68]"); // Noncompliant [[sc=19;ec=22;secondary=11,11]] - str.matches("[0-33-9]"); // Noncompliant [[sc=19;ec=22]] - str.matches("[0-70-9]"); // Noncompliant [[sc=19;ec=22]] - str.matches("[3-90-7]"); // Noncompliant [[sc=19;ec=22]] - str.matches("[3-50-9]"); // Noncompliant [[sc=19;ec=22]] - str.matches("[xxx]"); // Noncompliant [[sc=19;ec=20;secondary=16,16]] - str.matches("[A-z_]"); // Noncompliant [[sc=19;ec=22]] - str.matches("(?i)[A-Za-z]"); // Noncompliant [[sc=23;ec=26]] - str.matches("(?i)[A-_d]"); // Noncompliant [[sc=23;ec=26]] - str.matches("(?iu)[Ä-Üä]"); // Noncompliant [[sc=24;ec=27]] - str.matches("(?iu)[a-Öö]");// Noncompliant [[sc=24;ec=27]] - str.matches("[ ]"); // Noncompliant [[sc=19;ec=20]] - str.matches("(?i)[ ]"); // Noncompliant [[sc=23;ec=24]] - str.matches("(?iu)[ ]"); // Noncompliant [[sc=24;ec=25]] - str.matches("(?i)[A-_D]"); // Noncompliant [[sc=23;ec=26]] - str.matches("(?iu)[A-_D]"); // Noncompliant [[sc=24;ec=27]] - str.matches("(?i)[xX]"); // Noncompliant [[sc=23;ec=24]] - str.matches("(?iu)[äÄ]"); // Noncompliant [[sc=24;ec=25]] - str.matches("(?iU)[äÄ]"); // Noncompliant [[sc=24;ec=25]] - str.matches("(?iu)[xX]"); // Noncompliant [[sc=24;ec=25]] - str.matches("[\\\"\\\".]"); // Noncompliant [[sc=19;ec=23]] - str.matches("[\\x{1F600}-\\x{1F637}\\x{1F608}]"); // Noncompliant [[sc=19;ec=40]] - str.matches("[\\Qxx\\E]"); // Noncompliant [[sc=22;ec=23]] - str.matches("[[a][a]]"); // Noncompliant [[sc=20;ec=21]] - str.matches("[[abc][b]]"); // Noncompliant [[sc=20;ec=21]] - str.matches("[[^a]b]"); // Noncompliant [[sc=19;ec=23]] - str.matches("[[^a]z]"); // Noncompliant [[sc=19;ec=23]] - str.matches("[a[^z]]"); // Noncompliant [[sc=19;ec=20]] - str.matches("[z[^a]]"); // Noncompliant [[sc=19;ec=20]] - str.matches("[\\s\\Sx]"); // Noncompliant [[sc=22;ec=25]] - str.matches("(?U)[\\s\\Sx]"); // Noncompliant [[sc=26;ec=29]] - str.matches("[\\w\\d]"); // Noncompliant [[sc=19;ec=22]] - str.matches("[\\wa]"); // Noncompliant [[sc=19;ec=22]] - str.matches("[\\d1]"); // Noncompliant [[sc=19;ec=22]] - str.matches("[\\d1-3]"); // Noncompliant [[sc=19;ec=22]] - str.matches("(?U)[\\wa]"); // Noncompliant [[sc=23;ec=26]] + str.matches("[0-99]"); // Noncompliant {{Remove duplicates in this character class.}} +// ^^^ +// ^@-1< + str.matches("[90-9]"); // Noncompliant +// ^ +// ^^^@-1< + str.matches("[0-73-9]"); // Noncompliant +// ^^^ + str.matches("[0-93-57]"); // Noncompliant +// ^^^ ^< +// ^^^@-1< + str.matches("[4-92-68]"); // Noncompliant +// ^^^ + str.matches("[0-33-9]"); // Noncompliant +// ^^^ + str.matches("[0-70-9]"); // Noncompliant +// ^^^ + str.matches("[3-90-7]"); // Noncompliant +// ^^^ + str.matches("[3-50-9]"); // Noncompliant +// ^^^ + str.matches("[xxx]"); // Noncompliant +// ^ +// ^@-1< +// ^@-2< + str.matches("[A-z_]"); // Noncompliant +// ^^^ + str.matches("(?i)[A-Za-z]"); // Noncompliant +// ^^^ + str.matches("(?i)[A-_d]"); // Noncompliant +// ^^^ + str.matches("(?iu)[Ä-Üä]"); // Noncompliant +// ^^^ + str.matches("(?iu)[a-Öö]"); // Noncompliant +// ^^^ + str.matches("[ ]"); // Noncompliant +// ^ + str.matches("(?i)[ ]"); // Noncompliant +// ^ + str.matches("(?iu)[ ]"); // Noncompliant +// ^ + str.matches("(?i)[A-_D]"); // Noncompliant +// ^^^ + str.matches("(?iu)[A-_D]"); // Noncompliant +// ^^^ + str.matches("(?i)[xX]"); // Noncompliant +// ^ + str.matches("(?iu)[äÄ]"); // Noncompliant +// ^ + str.matches("(?iU)[äÄ]"); // Noncompliant +// ^ + str.matches("(?iu)[xX]"); // Noncompliant +// ^ + str.matches("[\\\"\\\".]"); // Noncompliant +// ^^^^ + str.matches("[\\x{1F600}-\\x{1F637}\\x{1F608}]"); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^ + str.matches("[\\Qxx\\E]"); // Noncompliant +// ^ + str.matches("[[a][a]]"); // Noncompliant +// ^ + str.matches("[[abc][b]]"); // Noncompliant +// ^ + str.matches("[[^a]b]"); // Noncompliant +// ^^^^ + str.matches("[[^a]z]"); // Noncompliant +// ^^^^ + str.matches("[a[^z]]"); // Noncompliant +// ^ + str.matches("[z[^a]]"); // Noncompliant +// ^ + str.matches("[\\s\\Sx]"); // Noncompliant +// ^^^ + str.matches("(?U)[\\s\\Sx]"); // Noncompliant +// ^^^ + str.matches("[\\w\\d]"); // Noncompliant +// ^^^ + str.matches("[\\wa]"); // Noncompliant +// ^^^ + str.matches("[\\d1]"); // Noncompliant +// ^^^ + str.matches("[\\d1-3]"); // Noncompliant +// ^^^ + str.matches("(?U)[\\wa]"); // Noncompliant +// ^^^ str.matches("(?U)[\\s\\u0085" + // Noncompliant "\\u2028" + "\\u2029]"); @@ -51,33 +96,76 @@ void nonCompliant() { "9]"); str.matches("[a-b" + - "0-9" + // Noncompliant [[sc=8;ec=11;secondary=56]] + "0-9" + // Noncompliant +// ^^^ "d-e" + "9]"); - str.matches("[a-z" + // Noncompliant [[sc=19;ec=22;secondary=58,59,60]] +// ^< + str.matches("[a-z" + // Noncompliant +// ^^^ "0-9" + +// ^^^< "b" + +// ^< "9]"); - str.matches("[a-z" + // Noncompliant [[sc=19;ec=22;secondary=62,63,64,65]] +// ^< + str.matches("[a-z" + // Noncompliant +// ^^^ "0-9" + +// ^^^< "b" + +// ^< "c" + +// ^< "9]"); - str.matches("[ba-zc]"); // Noncompliant [[sc=19;ec=20;secondary=66,66]] +// ^< + str.matches("[ba-zc]"); // Noncompliant +// ^ ^< +// ^^^@-1< // Miss "b" in secondary locations - str.matches("[aba-z]"); // Noncompliant [[sc=19;ec=20;secondary=68,68]] - str.matches("[aba-zc]"); // Noncompliant [[sc=19;ec=20;secondary=69,69,69]] - str.matches("[a-c" + // Noncompliant [[sc=19;ec=22;secondary=71,72,73]] + str.matches("[aba-z]"); // Noncompliant +// ^ +// ^@-1< +// ^^^@-2< + str.matches("[aba-zc]"); // Noncompliant +// ^ ^< +// ^@-1< +// ^^^@-2< + str.matches("[a-c" + // Noncompliant +// ^^^ "b" + +// ^< "a-z" + +// ^^^< "d]"); - str.matches("[0-54-6]"); // Noncompliant [[sc=19;ec=22;secondary=74]] - str.matches("[0-352-6]"); // Noncompliant [[sc=19;ec=22;secondary=75,75]] - str.matches("[0-392-43-54-65-76-87-9]"); // Noncompliant [[sc=19;ec=22;secondary=76,76,76,76,76,76,76]] - str.matches("[0-397-96-85-72-44-63-5]"); // Noncompliant [[sc=22;ec=23;secondary=77,77,77,77,77,77,77]] - str.matches("[0-397-96-8" + // Noncompliant [[sc=22;ec=23;secondary=78,78,78,80,80,80,80]] +// ^< + str.matches("[0-54-6]"); // Noncompliant +// ^^^ +// ^^^@-1< + str.matches("[0-352-6]"); // Noncompliant +// ^^^ +// ^@-1< +// ^^^@-2< + str.matches("[0-392-43-54-65-76-87-9]"); // Noncompliant +// ^^^ ^^^< +// ^@-1< +// ^^^@-2< +// ^^^@-3< +// ^^^@-4< +// ^^^@-5< +// ^^^@-6< + str.matches("[0-397-96-85-72-44-63-5]"); // Noncompliant + str.matches("[0-397-96-8" + // Noncompliant +// ^ +// ^^^@-1< +// ^^^@-2< +// ^^^@-3< "a" + // not included "5-72-44-63-5]"); +// ^^^< +// ^^^@-1< +// ^^^@-2< +// ^^^@-3< } void compliant() { @@ -121,7 +209,8 @@ void compliant() { str.matches("[\\p{IsLatin}x]"); // FN because we don't support \p at the moment } - @javax.validation.constraints.Email(regexp = "[0-99]") // Noncompliant [[sc=50;ec=53]] {{Remove duplicates in this character class.}} + @javax.validation.constraints.Email(regexp = "[0-99]") // Noncompliant {{Remove duplicates in this character class.}} +// ^^^ String email; void emoji(String str) { diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/EmptyLineRegexCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/regex/EmptyLineRegexCheckSample.java index ad065e5af8d..52e0e13ca44 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/EmptyLineRegexCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/EmptyLineRegexCheckSample.java @@ -9,11 +9,15 @@ public class EmptyLineRegexCheckSample { private static final String MY_FIELD_STRING = ""; void non_compliant_pattern_assigned(String str) { - Pattern p1 = Pattern.compile("^$", Pattern.MULTILINE); // Noncompliant [[sc=34;ec=38;secondary=13,14]] {{Remove MULTILINE mode or change the regex.}} + Pattern p1 = Pattern.compile("^$", Pattern.MULTILINE); // Noncompliant {{Remove MULTILINE mode or change the regex.}} +// ^^^^ p1.matcher(str).find(); +// ^^^< p1.matcher((str)).find(); +// ^^^^^< - Pattern p2 = Pattern.compile("(?m)^$"); // Noncompliant [[sc=34;ec=42]] + Pattern p2 = Pattern.compile("(?m)^$"); // Noncompliant +// ^^^^^^^^ p2.matcher(str).find(); Pattern p3 = Pattern.compile("(?m)^$", Pattern.MULTILINE); // Noncompliant @@ -21,7 +25,8 @@ void non_compliant_pattern_assigned(String str) { } void non_compliant_pattern_directly_used(String str) { - Pattern.compile("^$", Pattern.MULTILINE).matcher(str).find(); // Noncompliant [[sc=21;ec=25]] + Pattern.compile("^$", Pattern.MULTILINE).matcher(str).find(); // Noncompliant +// ^^^^ ^^^< Pattern.compile("(^$)", Pattern.MULTILINE).matcher(str).find(); // Noncompliant Pattern.compile("(?:^$)", Pattern.MULTILINE).matcher(str).find(); // Noncompliant Pattern.compile("(?m)^$").matcher(str).find(); // Noncompliant @@ -40,9 +45,11 @@ void non_compliant_pattern_directly_used(String str) { void nonCompliantOnString(String str) { Pattern.compile("^$", Pattern.MULTILINE).matcher("").find(); // Noncompliant - Pattern p1 = Pattern.compile("^$", Pattern.MULTILINE); // Noncompliant [[secondary=45]] + Pattern p1 = Pattern.compile("^$", Pattern.MULTILINE); // Noncompliant +// ^^^^ boolean b1 = p1.matcher("notEmpty").find(); boolean b2 = p1.matcher("").find(); +// ^^< } void not_used_in_problematic_situations(String str) { @@ -128,12 +135,14 @@ boolean tested_for_emptiness_4(String str) { } boolean not_tested_for_emptiness(String str1, String str2) { - Pattern p4 = Pattern.compile("(?m)^$"); // Noncompliant [[secondary=136]] + Pattern p4 = Pattern.compile("(?m)^$"); // Noncompliant +// ^^^^^^^^ if (str1.isEmpty()) { return false; } return p4.matcher(str1).find() && p4.matcher(str2).find(); +// ^^^^< } void not_identifier(String str1) { @@ -156,7 +165,8 @@ void from_variable_compliant() { } void in_replace(String str) { - String s1 = str.replaceAll("(?m)^$", "Empty"); // Noncompliant [[sc=32;ec=40]] + String s1 = str.replaceAll("(?m)^$", "Empty"); // Noncompliant +// ^^^^^^^^ String s2 = str.replaceAll("^$", "Empty"); // Compliant String s3 = "".replaceAll("(?m)^$", "Empty"); // Noncompliant String s4 = (str).replaceAll("(?m)^$", "Empty"); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/EmptyRegexGroupCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/regex/EmptyRegexGroupCheckSample.java index 6d179d0cb9d..08471d8bd86 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/EmptyRegexGroupCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/EmptyRegexGroupCheckSample.java @@ -5,22 +5,28 @@ public class EmptyRegexGroupCheckSample { void nonCompliant() { - Pattern.compile("foo()bar"); // Noncompliant [[sc=25;ec=27]] {{Remove this empty group.}} - Pattern.compile("foo(?:)bar"); // Noncompliant [[sc=25;ec=29]] - Pattern.compile("foo(?>)bar"); // Noncompliant - Pattern.compile("foo(?=)bar"); // Noncompliant - Pattern.compile("foo(?!)bar"); // Noncompliant - Pattern.compile("foo(?<=)bar"); // Noncompliant - Pattern.compile("foo(?)bar"); // Noncompliant + Pattern.compile("foo(?=)bar"); // Noncompliant + Pattern.compile("foo(?!)bar"); // Noncompliant + Pattern.compile("foo(?<=)bar"); // Noncompliant + Pattern.compile("foo(?)bar"); // Noncompliant - Pattern.compile("(foo()bar)"); // Noncompliant [[sc=26;ec=28]] - Pattern.compile("(foo(?:)bar)"); // Noncompliant [[sc=26;ec=30]] - Pattern.compile("(foo(?>)bar)"); // Noncompliant - Pattern.compile("(foo(?=)bar)"); // Noncompliant - Pattern.compile("(foo(?!)bar)"); // Noncompliant - Pattern.compile("(foo(?<=)bar)"); // Noncompliant [[sc=26;ec=31]] - Pattern.compile("(foo(?)bar)"); // Noncompliant + Pattern.compile("(foo(?=)bar)"); // Noncompliant + Pattern.compile("(foo(?!)bar)"); // Noncompliant + Pattern.compile("(foo(?<=)bar)"); // Noncompliant +// ^^^^^ + Pattern.compile("(foo(?)bar"); // Noncompliant } diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/EmptyStringRepetitionCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/regex/EmptyStringRepetitionCheckSample.java index 52982726be0..16064a671eb 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/EmptyStringRepetitionCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/EmptyStringRepetitionCheckSample.java @@ -6,17 +6,20 @@ class EmptyStringRepetitionCheckSample { private static final String REPLACEMENT = "empty"; - @URL(regexp = "(?:)*") // Noncompliant [[sc=18;ec=22]] {{Rework this part of the regex to not match the empty string.}} + @URL(regexp = "(?:)*") // Noncompliant {{Rework this part of the regex to not match the empty string.}} +// ^^^^ String url; void noncompliant(String input) { - input.replaceFirst("(?:)*", REPLACEMENT); // Noncompliant [[sc=25;ec=29]] {{Rework this part of the regex to not match the empty string.}} + input.replaceFirst("(?:)*", REPLACEMENT); // Noncompliant {{Rework this part of the regex to not match the empty string.}} +// ^^^^ input.replaceFirst("(?:)?", REPLACEMENT); // Noncompliant input.replaceFirst("(?:)+", REPLACEMENT); // Noncompliant input.replaceFirst("()*", REPLACEMENT); // Noncompliant input.replaceFirst("()?", REPLACEMENT); // Noncompliant input.replaceFirst("()+", REPLACEMENT); // Noncompliant - input.replaceFirst("xyz|(?:)*", REPLACEMENT); // Noncompliant [[sc=29;ec=33]] + input.replaceFirst("xyz|(?:)*", REPLACEMENT); // Noncompliant +// ^^^^ input.replaceFirst("(?:|x)*", REPLACEMENT); // Noncompliant input.replaceFirst("(?:x|)*", REPLACEMENT); // Noncompliant input.replaceFirst("(?:x|y*)*", REPLACEMENT); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/EscapeSequenceControlCharacterCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/regex/EscapeSequenceControlCharacterCheckSample.java index 22db4e1cf13..02d96ced4c8 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/EscapeSequenceControlCharacterCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/EscapeSequenceControlCharacterCheckSample.java @@ -6,8 +6,10 @@ public class EscapeSequenceControlCharacterCheckSample { void nonCompliant() { - Pattern.compile("\\ca"); // Noncompliant [[sc=22;ec=26]] {{Remove or replace this problematic use of \c.}} - Pattern.compile("ab\\cbde"); // Noncompliant [[sc=24;ec=28]] + Pattern.compile("\\ca"); // Noncompliant {{Remove or replace this problematic use of \c.}} +// ^^^^ + Pattern.compile("ab\\cbde"); // Noncompliant +// ^^^^ Pattern.compile("\\cb"); // Noncompliant Pattern.compile("\\cx"); // Noncompliant Pattern.compile("\\c!"); // Noncompliant @@ -30,7 +32,8 @@ void compliant() { Pattern.compile("\\\\ca"); } - @Email(regexp = "\\ca") // Noncompliant [[sc=20;ec=24]] + @Email(regexp = "\\ca") // Noncompliant +// ^^^^ String email; } diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/GraphemeClustersInClassesCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/regex/GraphemeClustersInClassesCheckSample.java index 4e6cab2d3a0..2dca06c6a9c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/GraphemeClustersInClassesCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/GraphemeClustersInClassesCheckSample.java @@ -5,13 +5,21 @@ public class GraphemeClustersInClassesCheckSample { void noncompliant(String str) { - Pattern.compile("[aaaèaaa]"); // Noncompliant [[sc=22;ec=32;secondary=8]] {{Extract 1 Grapheme Cluster(s) from this character class.}} - Pattern.compile("[0Ṩ0]"); // Noncompliant [[sc=22;ec=29;secondary=9]] {{Extract 1 Grapheme Cluster(s) from this character class.}} + Pattern.compile("[aaaèaaa]"); // Noncompliant {{Extract 1 Grapheme Cluster(s) from this character class.}} +// ^^^^^^^^^^ +// ^@-1< + Pattern.compile("[0Ṩ0]"); // Noncompliant {{Extract 1 Grapheme Cluster(s) from this character class.}} +// ^^^^^^^ +// ^@-1< Pattern.compile("aaa[è]aaa"); // Noncompliant // two secondary per line: one for the regex location, and one for the cluster location - Pattern.compile("[èaèaè]"); // Noncompliant [[sc=22;ec=32;secondary=12,12,12]] {{Extract 3 Grapheme Cluster(s) from this character class.}} + Pattern.compile("[èaèaè]"); // Noncompliant {{Extract 3 Grapheme Cluster(s) from this character class.}} +// ^^^^^^^^^^ +// ^^@-1< +// ^^@-2< +// ^^@-3< Pattern.compile("[èa-dä]"); // Noncompliant - Pattern.compile("[èa]" + // Noncompliant + Pattern.compile("[èa]" + // Noncompliant "aaa" + "[dè]"); // Noncompliant @@ -33,7 +41,8 @@ void compliant(String str) { Pattern.compile("ä"); // Compliant, not in a class } - @org.hibernate.validator.constraints.URL(regexp = "[èaèaè]") // Noncompliant [[sc=54;ec=64]] {{Extract 3 Grapheme Cluster(s) from this character class.}} + @org.hibernate.validator.constraints.URL(regexp = "[èaèaè]") // Noncompliant {{Extract 3 Grapheme Cluster(s) from this character class.}} +// ^^^^^^^^^^ String url; diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/ImpossibleBackReferenceCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/regex/ImpossibleBackReferenceCheckSample.java index d27320788b2..fc82da84511 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/ImpossibleBackReferenceCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/ImpossibleBackReferenceCheckSample.java @@ -3,17 +3,26 @@ public class ImpossibleBackReferenceCheckSample { void noncompliant(String str) { - str.matches("\\1" + // Noncompliant [[sc=18;ec=21;secondary=7]] {{Fix this backreference, so that it refers to a group that can be matched before it.}} + str.matches("\\1" + // Noncompliant {{Fix this backreference, so that it refers to a group that can be matched before it.}} +// ^^^ "(.)"); - str.matches("\\k" + // Noncompliant [[sc=18;ec=27;secondary=9]] {{Fix this backreference, so that it refers to a group that can be matched before it.}} +// ^^^< + str.matches("\\k" + // Noncompliant {{Fix this backreference, so that it refers to a group that can be matched before it.}} +// ^^^^^^^^^ "(?.)"); +// ^^^^^^^^^^< str.matches("(.)|" + - "\\1"); // Noncompliant [[sc=8;ec=11;secondary=10]] - str.matches("\\1"); // Noncompliant [[sc=18;ec=21]] {{Fix this backreference - it refers to a capturing group that doesn't exist.}} - str.matches("\\2(.)"); // Noncompliant [[sc=18;ec=21]] {{Fix this backreference - it refers to a capturing group that doesn't exist.}} + + "\\1"); // Noncompliant +// ^^^ + str.matches("\\1"); // Noncompliant {{Fix this backreference - it refers to a capturing group that doesn't exist.}} +// ^^^ + str.matches("\\2(.)"); // Noncompliant {{Fix this backreference - it refers to a capturing group that doesn't exist.}} +// ^^^ str.matches("(.)\\2(.)"); // Noncompliant {{Fix this backreference, so that it refers to a group that can be matched before it.}} str.matches("(?.)\\k(?.)"); // Noncompliant {{Fix this backreference, so that it refers to a group that can be matched before it.}} - str.matches("(?)\\k"); // Noncompliant [[sc=33;ec=42]] {{Fix this backreference - it refers to a capturing group that doesn't exist.}} + str.matches("(?)\\k"); // Noncompliant {{Fix this backreference - it refers to a capturing group that doesn't exist.}} +// ^^^^^^^^^ str.matches("\\k(?.)"); // Noncompliant str.matches("(?.)|\\k"); // Noncompliant str.matches("(?:\\1(.))*"); // Noncompliant @@ -46,7 +55,8 @@ void compliant(String str) { str.matches("(1)(2)(3)(4)(5)(6)(7)(8)(9)(a)(b)\\11"); // Compliant, backreference is \11 because group 11 exists at this point in the regex } - @org.hibernate.validator.constraints.URL(regexp = "\\1(.)") // Noncompliant [[sc=54;ec=57;secondary=+0]] {{Fix this backreference, so that it refers to a group that can be matched before it.}} + @org.hibernate.validator.constraints.URL(regexp = "\\1(.)") // Noncompliant {{Fix this backreference, so that it refers to a group that can be matched before it.}} +// ^^^ String url; } diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/ImpossibleBoundariesCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/regex/ImpossibleBoundariesCheckSample.java index c592e55126d..c730972ffa5 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/ImpossibleBoundariesCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/ImpossibleBoundariesCheckSample.java @@ -5,29 +5,47 @@ public class ImpossibleBoundariesCheckSample { - @Email(regexp = "$USER") // Noncompliant [[sc=20;ec=21]] {{Remove or replace this boundary that will never match because it appears before mandatory input.}} + @Email(regexp = "$USER") // Noncompliant {{Remove or replace this boundary that will never match because it appears before mandatory input.}} +// ^ String email; void noncompliant(String str) { - // Noncompliant@+1 [[sc=18;ec=19]] {{Remove or replace this boundary that will never match because it appears before mandatory input.}} - str.matches("$[a-z]^"); // Noncompliant [[sc=24;ec=25]] {{Remove or replace this boundary that will never match because it appears after mandatory input.}} - str.matches("$[a-z]"); // Noncompliant [[sc=18;ec=19]] {{Remove or replace this boundary that will never match because it appears before mandatory input.}} - str.matches("$(abc)"); // Noncompliant [[sc=18;ec=19]] - str.matches("[a-z]^"); // Noncompliant [[sc=23;ec=24]] - str.matches("\\Z[a-z]"); // Noncompliant [[sc=18;ec=21]] - str.matches("\\z[a-z]"); // Noncompliant [[sc=18;ec=21]] - str.matches("[a-z]\\A"); // Noncompliant [[sc=23;ec=26]] - str.matches("($)a"); // Noncompliant [[sc=19;ec=20]] - str.matches("a$|$a"); // Noncompliant [[sc=21;ec=22]] - str.matches("^a|a^"); // Noncompliant [[sc=22;ec=23]] - str.matches("a(b|^)"); // Noncompliant [[sc=22;ec=23]] - str.matches("(?=abc^)"); // Noncompliant [[sc=24;ec=25]] - str.matches("(?!abc^)"); // Noncompliant [[sc=24;ec=25]] - str.matches("abc(?=^abc)"); // Noncompliant [[sc=24;ec=25]] - str.matches("abc(?<=$abc)"); // Noncompliant [[sc=25;ec=26]] - str.matches("abc(?<=abc$)def"); // Noncompliant [[sc=28;ec=29]] - str.matches("abc(?\\w+)-\\k"); } - @javax.validation.constraints.Pattern(regexp = "(") // Noncompliant [[sc=52;ec=53;secondary=38]] {{Fix the syntax error inside this regex.}} + @javax.validation.constraints.Pattern(regexp = "(") // Noncompliant {{Fix the syntax error inside this regex.}} +// ^ +// ^@-1< String pattern; void unicode16(String str) { diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/MultipleWhitespaceCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/regex/MultipleWhitespaceCheckSample.java index d5616bb2574..e311b46eb54 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/MultipleWhitespaceCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/MultipleWhitespaceCheckSample.java @@ -5,9 +5,10 @@ public class MultipleWhitespaceCheckSample { void noncompliant() { - Pattern.compile("Hello, world!"); // Noncompliant [[sc=29;ec=31]] {{Replace spaces with quantifier `{3}`.}} - Pattern.compile("Hello, world!"); // Noncompliant {{Replace spaces with quantifier `{2}`.}} - Pattern.compile("Hello, world! "); // Noncompliant {{Replace spaces with quantifier `{6}`.}} + Pattern.compile("Hello, world!"); // Noncompliant {{Replace spaces with quantifier `{3}`.}} +// ^^ + Pattern.compile("Hello, world!"); // Noncompliant {{Replace spaces with quantifier `{2}`.}} + Pattern.compile("Hello, world! "); // Noncompliant {{Replace spaces with quantifier `{6}`.}} } void compliant() { diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/PossessiveQuantifierContinuationCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/regex/PossessiveQuantifierContinuationCheckSample.java index 3482ffda5c2..a9402ae0ea5 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/PossessiveQuantifierContinuationCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/PossessiveQuantifierContinuationCheckSample.java @@ -9,21 +9,32 @@ public class PossessiveQuantifierContinuationCheckSample { public void f(Pattern pattern) { f(compile("a+abc")); f(compile("a+?abc")); - f(compile("a++abc")); // Noncompliant [[sc=19;ec=20;secondary=12]] {{Change this impossible to match sub-pattern that conflicts with the previous possessive quantifier.}} - f(compile("\\d*+[02468]")); // Noncompliant [[sc=21;ec=28]] - f(compile("(\\d)*+([02468])")); // Noncompliant [[sc=23;ec=32]] + f(compile("a++abc")); // Noncompliant {{Change this impossible to match sub-pattern that conflicts with the previous possessive quantifier.}} +// ^ +// ^^^@-1< + f(compile("\\d*+[02468]")); // Noncompliant +// ^^^^^^^ + f(compile("(\\d)*+([02468])")); // Noncompliant +// ^^^^^^^^^ f(compile("\\d++(?:[eE][+-]?\\d++)?[fFdD]?")); f(compile("a*+\\s")); f(compile("[+-]?(?:NaN|Infinity|(?:\\d++(?:\\.\\d*+)?|\\.\\d++)(?:[eE][+-]?\\d++)?[fFdD]?|0[xX](?:\\p{XDigit}++(?:\\.\\p{XDigit}*+)?|\\.\\p{XDigit}++)[pP][+-]?\\d++[fFdD]?)")); f(compile("aa++bc")); f(compile("\\d*+(?<=[02468])")); - f(compile("(xx++)+x")); // Noncompliant [[sc=23;ec=24]] - f(compile("(bx++)+x")); // Noncompliant [[sc=23;ec=24]] - f(compile("(?:xx++)+x")); // Noncompliant [[sc=25;ec=26]] - f(compile("(xx++)x")); // Noncompliant [[sc=22;ec=23]] - f(compile(".*+\\w")); // Noncompliant [[sc=19;ec=22]] - f(compile(".*+\\w+")); // Noncompliant [[sc=19;ec=23]] - f(compile("(a|b|c)*+(a|b)")); // Noncompliant [[sc=25;ec=30]] + f(compile("(xx++)+x")); // Noncompliant +// ^ + f(compile("(bx++)+x")); // Noncompliant +// ^ + f(compile("(?:xx++)+x")); // Noncompliant +// ^ + f(compile("(xx++)x")); // Noncompliant +// ^ + f(compile(".*+\\w")); // Noncompliant +// ^^^ + f(compile(".*+\\w+")); // Noncompliant +// ^^^^ + f(compile("(a|b|c)*+(a|b)")); // Noncompliant +// ^^^^^ f(compile("(:[0-9])?+(:[0-9])?+")); } diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/RedosCheckJava8.java b/java-checks-test-sources/default/src/main/java/checks/regex/RedosCheckJava8.java index 3a3bc9b8bcb..b78cd77226b 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/RedosCheckJava8.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/RedosCheckJava8.java @@ -4,14 +4,17 @@ public class RedosCheckJava8 { - @Email(regexp = "(.*-)*@.*") // Noncompliant [[sc=4;ec=9]] {{Make sure the regex used here, which is vulnerable to exponential runtime due to backtracking, cannot lead to denial of service.}} + @Email(regexp = "(.*-)*@.*") // Noncompliant {{Make sure the regex used here, which is vulnerable to exponential runtime due to backtracking, cannot lead to denial of service.}} +// ^^^^^ String email; - @jakarta.validation.constraints.Email(regexp = "(.*-)*@.*") // Noncompliant [[sc=4;ec=40]] {{Make sure the regex used here, which is vulnerable to exponential runtime due to backtracking, cannot lead to denial of service.}} + @jakarta.validation.constraints.Email(regexp = "(.*-)*@.*") // Noncompliant {{Make sure the regex used here, which is vulnerable to exponential runtime due to backtracking, cannot lead to denial of service.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ String email2; void alwaysExponential(String str) { - str.matches("(.*,)*?"); // Noncompliant [[sc=9;ec=16]] {{Make sure the regex used here, which is vulnerable to exponential runtime due to backtracking, cannot lead to denial of service.}} + str.matches("(.*,)*?"); // Noncompliant {{Make sure the regex used here, which is vulnerable to exponential runtime due to backtracking, cannot lead to denial of service.}} +// ^^^^^^^ str.matches("(.?,)*?"); // Noncompliant {{Make sure the regex used here, which is vulnerable to exponential runtime due to backtracking, cannot lead to denial of service.}} str.matches("(a|.a)*?"); // Noncompliant {{Make sure the regex used here, which is vulnerable to exponential runtime due to backtracking, cannot lead to denial of service.}} str.matches("(.*,)*X\\1"); // Noncompliant {{Make sure the regex used here, which is vulnerable to exponential runtime due to backtracking, cannot lead to denial of service.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/RedosCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/regex/RedosCheckSample.java index c1f440a8f27..dbdd3f2cb7c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/RedosCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/RedosCheckSample.java @@ -5,10 +5,12 @@ public class RedosCheckSample { - @Email(regexp = "(.*-)*@.*") // Noncompliant [[sc=4;ec=9]] {{Make sure the regex used here, which is vulnerable to polynomial runtime due to backtracking, cannot lead to denial of service.}} + @Email(regexp = "(.*-)*@.*") // Noncompliant {{Make sure the regex used here, which is vulnerable to polynomial runtime due to backtracking, cannot lead to denial of service.}} +// ^^^^^ String email; - @jakarta.validation.constraints.Email(regexp = "(.*-)*@.*") // Noncompliant [[sc=4;ec=40]] {{Make sure the regex used here, which is vulnerable to polynomial runtime due to backtracking, cannot lead to denial of service.}} + @jakarta.validation.constraints.Email(regexp = "(.*-)*@.*") // Noncompliant {{Make sure the regex used here, which is vulnerable to polynomial runtime due to backtracking, cannot lead to denial of service.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ String email2; void realWorldExamples(String str) { @@ -27,7 +29,8 @@ void fullAndPartialMatches(String str) { } void alwaysExponential(String str) { - str.matches("(.*,)*?"); // Noncompliant [[sc=9;ec=16]] {{Make sure the regex used here, which is vulnerable to exponential runtime due to backtracking, cannot lead to denial of service.}} + str.matches("(.*,)*?"); // Noncompliant {{Make sure the regex used here, which is vulnerable to exponential runtime due to backtracking, cannot lead to denial of service.}} +// ^^^^^^^ str.matches("(.?,)*?"); // Noncompliant {{Make sure the regex used here, which is vulnerable to exponential runtime due to backtracking, cannot lead to denial of service.}} str.matches("(a|.a)*?"); // Noncompliant {{Make sure the regex used here, which is vulnerable to exponential runtime due to backtracking, cannot lead to denial of service.}} str.matches("(?:.*,)*(X)\\1"); // Noncompliant {{Make sure the regex used here, which is vulnerable to exponential runtime due to backtracking, cannot lead to denial of service.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/RedundantRegexAlternativesCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/regex/RedundantRegexAlternativesCheckSample.java index e0e667a6bae..f43fedc8692 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/RedundantRegexAlternativesCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/RedundantRegexAlternativesCheckSample.java @@ -9,7 +9,7 @@ public class RedundantRegexAlternativesCheckSample { public void f(Pattern pattern) { f(compile("" + "." + - "|a")); // Noncompliant [[sc=9;ec=10;secondary=-1]] {{Remove or rework this redundant alternative.}} + "|a")); // Noncompliant {{Remove or rework this redundant alternative.}} [[sc=9;ec=10;secondary=-1]] f(compile("" + "a" + // Noncompliant [[sc=8;ec=9;secondary=+1]] "|.")); diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/RegexComplexityCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/regex/RegexComplexityCheckSample.java index 2aace05ef39..6611340c7ac 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/RegexComplexityCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/RegexComplexityCheckSample.java @@ -8,24 +8,23 @@ public class RegexComplexityCheckSample { // Since this check is sensitive to comments, all comments that mark a regex as non-compliant or that explain // why it is (non-)compliant should not be on the same line as the regex or on the line before it. - // Noncompliant@+2 [[sc=21;ec=22]] {{Simplify this regular expression to reduce its complexity from 3557 to the 20 allowed.}} + private static final Pattern VALID_EMAIL_ADDRESS_REGEX = - Pattern.compile("(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*:(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)(?:,\\s*(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*))*)?;\\s*)"); + Pattern.compile("(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*:(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)(?:,\\s*(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*))*)?;\\s*)"); // Noncompliant {{Simplify this regular expression to reduce its complexity from 3557 to the 20 allowed.}} +// ^ + - // Noncompliant@+1 [[sc=19;ec=20]] {{Simplify this regular expression to reduce its complexity from 95 to the 20 allowed.}} - @Email(regexp = "((((a|b)|(c|d))+|((e|f)|(g|h))+)+|(((h|i)|(j|j))+|((k|l)|(m|n))+)+)") + @Email(regexp = "((((a|b)|(c|d))+|((e|f)|(g|h))+)+|(((h|i)|(j|j))+|((k|l)|(m|n))+)+)") // Noncompliant {{Simplify this regular expression to reduce its complexity from 95 to the 20 allowed.}} +// ^ private String email; - // Noncompliant@+1 + // Noncompliant@+1 @jakarta.validation.constraints.Email(regexp = "((((a|b)|(c|d))+|((e|f)|(g|h))+)+|(((h|i)|(j|j))+|((k|l)|(m|n))+)+)") private String emailJakarta; void noncompliant(String str) { - // Noncompliant@+2 [[sc=7;ec=8]] {{Simplify this regular expression to reduce its complexity from 106 to the 20 allowed.}} - str.matches( - "^(?:(?:31(\\/|-|\\.)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)(\\/|-|\\.)(?:0?[13-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|" + - ("^(?:29(\\/|-|\\.)0?2\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|" + - "^(?:0?[1-9]|1\\d|2[0-8])(\\/|-|\\.)(?:(?:0?[1-9])|(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$")); + + str.matches("^(?:(?:31(\\/|-|\\.)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)(\\/|-|\\.)(?:0?[13-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:29(\\/|-|\\.)0?2\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\\d|2[0-8])(\\/|-|\\.)(?:(?:0?[1-9])|(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$"); // Noncompliant {{Simplify this regular expression to reduce its complexity from 106 to the 20 allowed.}} } void compliantFromSonar() { @@ -42,7 +41,7 @@ Pattern compliantFromGuava() { } Pattern guavaNonCompliantVersion() { - // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 58 to the 20 allowed.}} + // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 58 to the 20 allowed.}} String fpPattern = "[+-]?(?:NaN|Infinity|(?:\\d++(?:\\.\\d*+)?|\\.\\d++)(?:[eE][+-]?\\d++)?[fFdD]?|" + "0[xX](?:\\p{XDigit}++(?:\\.\\p{XDigit}*+)?|\\.\\p{XDigit}++)[pP][+-]?\\d++[fFdD]?)"; diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/RegexComplexityCheckWithThreshold0.java b/java-checks-test-sources/default/src/main/java/checks/regex/RegexComplexityCheckWithThreshold0.java index d61332cb42f..299376c2841 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/RegexComplexityCheckWithThreshold0.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/RegexComplexityCheckWithThreshold0.java @@ -15,65 +15,65 @@ void compliant(String str) { } void nonCompliant(String str) { - // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 1 to the 0 allowed.}} + // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 1 to the 0 allowed.}} str.matches( "(?=abc)" ); - // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 1 to the 0 allowed.}} + // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 1 to the 0 allowed.}} str.matches( "(?i:abc)" ); - // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 3 to the 0 allowed.}} + // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 3 to the 0 allowed.}} str.matches( "(?i:a(?-i:bc))" ); - // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 1 to the 0 allowed.}} + // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 1 to the 0 allowed.}} str.matches( "(?i)abc" ); - // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 1 to the 0 allowed.}} + // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 1 to the 0 allowed.}} str.matches( "[a-z0-9]]" ); - // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 2 to the 0 allowed.}} + // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 2 to the 0 allowed.}} str.matches( "[a-z&&0-9]]" ); - // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 3 to the 0 allowed.}} + // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 3 to the 0 allowed.}} str.matches( "[a-z&&0-9&&b-d]]" ); - // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 1 to the 0 allowed.}} + // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 1 to the 0 allowed.}} str.matches( "x*" ); - // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 1 to the 0 allowed.}} + // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 1 to the 0 allowed.}} str.matches( "(?:abc)*" ); - // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 1 to the 0 allowed.}} + // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 1 to the 0 allowed.}} str.matches( "((?:abc)*)" ); - // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 3 to the 0 allowed.}} + // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 3 to the 0 allowed.}} str.matches( "((?:abc)*)?" ); - // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 1 to the 0 allowed.}} + // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 1 to the 0 allowed.}} str.matches( "a|b" ); - // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 2 to the 0 allowed.}} + // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 2 to the 0 allowed.}} str.matches( "a|b|c" ); - // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 3 to the 0 allowed.}} + // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 3 to the 0 allowed.}} str.matches( "(?:a|b)*" ); - // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 4 to the 0 allowed.}} + // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 4 to the 0 allowed.}} str.matches( "(?:a|b|c)*" ); diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/RegexComplexityCheckWithThreshold1.java b/java-checks-test-sources/default/src/main/java/checks/regex/RegexComplexityCheckWithThreshold1.java index 5852ef0c30e..f399e412b74 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/RegexComplexityCheckWithThreshold1.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/RegexComplexityCheckWithThreshold1.java @@ -14,15 +14,15 @@ void compliant(String str) { } void nonCompliant(String str) { - // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 2 to the 1 allowed.}} + // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 2 to the 1 allowed.}} str.matches( "x*y+" ); - // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 2 to the 1 allowed.}} + // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 2 to the 1 allowed.}} String pattern1 = "x*" + "y+"; - // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 2 to the 1 allowed.}} + // Noncompliant@+2 {{Simplify this regular expression to reduce its complexity from 2 to the 1 allowed.}} String pattern2 = "a*" + "b+"; @@ -67,15 +67,15 @@ void compliantBecauseOfComments(String str) { } void noncompliantDespiteComments(String str) { - // Noncompliant@+3 {{Simplify this regular expression to reduce its complexity from 2 to the 1 allowed.}} - // Noncompliant@+3 {{Simplify this regular expression to reduce its complexity from 2 to the 1 allowed.}} + // Noncompliant@+3 {{Simplify this regular expression to reduce its complexity from 2 to the 1 allowed.}} + // Noncompliant@+3 {{Simplify this regular expression to reduce its complexity from 2 to the 1 allowed.}} str.matches( "x*y+" + // lots of xs and ys "a*b+" // lots of as and bs ); - // Noncompliant@+3 {{Simplify this regular expression to reduce its complexity from 2 to the 1 allowed.}} - // Noncompliant@+3 {{Simplify this regular expression to reduce its complexity from 2 to the 1 allowed.}} + // Noncompliant@+3 {{Simplify this regular expression to reduce its complexity from 2 to the 1 allowed.}} + // Noncompliant@+3 {{Simplify this regular expression to reduce its complexity from 2 to the 1 allowed.}} String pattern = "x*y+ # lots of xs and ys" + "a*b+ # lots of as and bs"; diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/RegexLookaheadCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/regex/RegexLookaheadCheckSample.java index 50539f9758d..a603605cf6c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/RegexLookaheadCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/RegexLookaheadCheckSample.java @@ -9,7 +9,8 @@ public class RegexLookaheadCheckSample { public void test(String str) { // Positive lookahead - compile("(?=a)b"); // Noncompliant [[sc=14;ec=19]] {{Remove or fix this lookahead assertion that can never be true.}} + compile("(?=a)b"); // Noncompliant {{Remove or fix this lookahead assertion that can never be true.}} +// ^^^^^ compile("(?=ac)ab"); // Noncompliant compile("(?=a)bc"); // Noncompliant compile("(?=a)a"); @@ -20,7 +21,7 @@ public void test(String str) { compile("(?=abc)abcd"); // Negative Lookahead - compile("(?!a)a"); // Noncompliant - support negative lookahead + compile("(?!a)a"); // Noncompliant compile("(?!ab)ab"); // Noncompliant compile("(?!a)ab").matcher(str).find(); // Noncompliant compile("(?!abc)abcd"); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/RegexStackOverflowCheckWithHighStackConsumption.java b/java-checks-test-sources/default/src/main/java/checks/regex/RegexStackOverflowCheckWithHighStackConsumption.java index 2c628b21bde..1867a860a16 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/RegexStackOverflowCheckWithHighStackConsumption.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/RegexStackOverflowCheckWithHighStackConsumption.java @@ -5,9 +5,12 @@ class RegexStackOverflowCheckWithHighStackConsumption { Pattern[] patterns = new Pattern[] { - Pattern.compile("(a|b)*"), // Noncompliant [[sc=22;ec=28]] {{Refactor this repetition that can lead to a stack overflow for large inputs.}} + Pattern.compile("(a|b)*"), // Noncompliant {{Refactor this repetition that can lead to a stack overflow for large inputs.}} +// ^^^^^^ Pattern.compile("(.|\n)*?"), // Noncompliant - Pattern.compile("(.|\n)*?(.|\n)*"), // Noncompliant [[sc=22;ec=30;secondary=+0]] + Pattern.compile("(.|\n)*?(.|\n)*"), // Noncompliant +// ^^^^^^^^ +// ^^^^^^^@-1< Pattern.compile("(.|\n)*?"), // Noncompliant Pattern.compile("(ab?){42,}"), // Noncompliant Pattern.compile("(a|hello world)*"), // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/ReluctantQuantifierCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/regex/ReluctantQuantifierCheckSample.java index dfa89312819..8b630dfc7fd 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/ReluctantQuantifierCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/ReluctantQuantifierCheckSample.java @@ -4,58 +4,86 @@ public class ReluctantQuantifierCheckSample { - @URL(regexp = "<.+?>") // Noncompliant [[sc=19;ec=22]] {{Replace this use of a reluctant quantifier with "[^>]++".}} + @URL(regexp = "<.+?>") // Noncompliant {{Replace this use of a reluctant quantifier with "[^>]++".}} +// ^^^ String url; void noncompliant(String str) { - str.matches("<.+?>"); // Noncompliant [[sc=19;ec=22]] {{Replace this use of a reluctant quantifier with "[^>]++".}} - str.matches("<\\S+?>"); // Noncompliant [[sc=19;ec=24]] {{Replace this use of a reluctant quantifier with "[^>\\s]++".}} - str.matches("<\\D+?>"); // Noncompliant [[sc=19;ec=24]] {{Replace this use of a reluctant quantifier with "[^>\\d]++".}} - str.matches("<\\W+?>"); // Noncompliant [[sc=19;ec=24]] {{Replace this use of a reluctant quantifier with "[^>\\w]++".}} - - str.matches("<.{2,5}?>"); // Noncompliant [[sc=19;ec=26]] {{Replace this use of a reluctant quantifier with "[^>]{2,5}+".}} - str.matches("<\\S{2,5}?>"); // Noncompliant [[sc=19;ec=28]] {{Replace this use of a reluctant quantifier with "[^>\\s]{2,5}+".}} - str.matches("<\\D{2,5}?>"); // Noncompliant [[sc=19;ec=28]] {{Replace this use of a reluctant quantifier with "[^>\\d]{2,5}+".}} - str.matches("<\\W{2,5}?>"); // Noncompliant [[sc=19;ec=28]] {{Replace this use of a reluctant quantifier with "[^>\\w]{2,5}+".}} - - str.matches("<.{2,}?>"); // Noncompliant [[sc=19;ec=25]] {{Replace this use of a reluctant quantifier with "[^>]{2,}+".}} - str.matches("\".*?\""); // Noncompliant [[sc=20;ec=23]] {{Replace this use of a reluctant quantifier with "[^\"]*+".}} - str.matches(".*?\\w"); // Noncompliant [[sc=18;ec=21]] {{Replace this use of a reluctant quantifier with "\\W*+".}} - str.matches(".*?\\W"); // Noncompliant [[sc=18;ec=21]] {{Replace this use of a reluctant quantifier with "\\w*+".}} - str.matches(".*?\\p{L}"); // Noncompliant [[sc=18;ec=21]] {{Replace this use of a reluctant quantifier with "\\P{L}*+".}} - str.matches(".*?\\P{L}"); // Noncompliant [[sc=18;ec=21]] {{Replace this use of a reluctant quantifier with "\\p{L}*+".}} - str.matches("\\[.*?\\]"); // Noncompliant [[sc=21;ec=24]] {{Replace this use of a reluctant quantifier with "[^\\]]*+".}} - str.matches(".+?[abc]"); // Noncompliant [[sc=18;ec=21]] {{Replace this use of a reluctant quantifier with "[^abc]++".}} + str.matches("<.+?>"); // Noncompliant {{Replace this use of a reluctant quantifier with "[^>]++".}} +// ^^^ + str.matches("<\\S+?>"); // Noncompliant {{Replace this use of a reluctant quantifier with "[^>\\s]++".}} +// ^^^^^ + str.matches("<\\D+?>"); // Noncompliant {{Replace this use of a reluctant quantifier with "[^>\\d]++".}} +// ^^^^^ + str.matches("<\\W+?>"); // Noncompliant {{Replace this use of a reluctant quantifier with "[^>\\w]++".}} +// ^^^^^ + str.matches("<.{2,5}?>"); // Noncompliant {{Replace this use of a reluctant quantifier with "[^>]{2,5}+".}} +// ^^^^^^^ + str.matches("<\\S{2,5}?>"); // Noncompliant {{Replace this use of a reluctant quantifier with "[^>\\s]{2,5}+".}} +// ^^^^^^^^^ + str.matches("<\\D{2,5}?>"); // Noncompliant {{Replace this use of a reluctant quantifier with "[^>\\d]{2,5}+".}} +// ^^^^^^^^^ + str.matches("<\\W{2,5}?>"); // Noncompliant {{Replace this use of a reluctant quantifier with "[^>\\w]{2,5}+".}} +// ^^^^^^^^^ + + str.matches("<.{2,}?>"); // Noncompliant {{Replace this use of a reluctant quantifier with "[^>]{2,}+".}} +// ^^^^^^ + str.matches("\".*?\""); // Noncompliant {{Replace this use of a reluctant quantifier with "[^\"]*+".}} +// ^^^ + str.matches(".*?\\w"); // Noncompliant {{Replace this use of a reluctant quantifier with "\\W*+".}} +// ^^^ + str.matches(".*?\\W"); // Noncompliant {{Replace this use of a reluctant quantifier with "\\w*+".}} +// ^^^ + str.matches(".*?\\p{L}"); // Noncompliant {{Replace this use of a reluctant quantifier with "\\P{L}*+".}} +// ^^^ + str.matches(".*?\\P{L}"); // Noncompliant {{Replace this use of a reluctant quantifier with "\\p{L}*+".}} +// ^^^ + str.matches("\\[.*?\\]"); // Noncompliant {{Replace this use of a reluctant quantifier with "[^\\]]*+".}} +// ^^^ + str.matches(".+?[abc]"); // Noncompliant {{Replace this use of a reluctant quantifier with "[^abc]++".}} +// ^^^ str.matches("(?-U:\\s)*?\\S"); - str.matches("(?U:\\s)*?\\S"); // Noncompliant [[sc=18;ec=28]] {{Replace this use of a reluctant quantifier with "[\\s\\S]*+".}} + str.matches("(?U:\\s)*?\\S"); // Noncompliant {{Replace this use of a reluctant quantifier with "[\\s\\S]*+".}} +// ^^^^^^^^^^ str.matches("(?U:a|\\s)*?\\S"); str.matches("\\S*?\\s"); str.matches("\\S*?(?-U:\\s)"); - str.matches("\\S*?(?U:\\s)"); // Noncompliant [[sc=18;ec=23]] {{Replace this use of a reluctant quantifier with "[\\S\\s]*+".}} - str.matches("\\S*?(?U)\\s"); // Noncompliant [[sc=18;ec=23]] {{Replace this use of a reluctant quantifier with "[\\S\\s]*+".}} + str.matches("\\S*?(?U:\\s)"); // Noncompliant {{Replace this use of a reluctant quantifier with "[\\S\\s]*+".}} +// ^^^^^ + str.matches("\\S*?(?U)\\s"); // Noncompliant {{Replace this use of a reluctant quantifier with "[\\S\\s]*+".}} +// ^^^^^ // coverage str.matches("(?:(?m))*?a"); str.matches("(?:(?m:.))*?(?:(?m))"); // This replacement might not be equivalent in case of full match, but is equivalent in case of split - str.matches(".+?[^abc]"); // Noncompliant [[sc=18;ec=21]] {{Replace this use of a reluctant quantifier with "[abc]++".}} - - str.matches(".+?\\x{1F4A9}"); // Noncompliant [[sc=18;ec=21]] {{Replace this use of a reluctant quantifier with "[^\\x{1F4A9}]++".}} - str.matches(""); // Noncompliant [[sc=22;ec=25]] {{Replace this use of a reluctant quantifier with "[^>]*+".}} - str.matches("<.+?>|otherstuff"); // Noncompliant [[sc=19;ec=22]] {{Replace this use of a reluctant quantifier with "[^>]++".}} - str.matches("(<.+?>)*"); // Noncompliant [[sc=20;ec=23]] {{Replace this use of a reluctant quantifier with "[^>]++".}} - - str.matches("\\S+?[abc]"); // Noncompliant [[sc=18;ec=23]] {{Replace this use of a reluctant quantifier with "[^abc\\s]++".}} - str.matches("\\D+?[abc]"); // Noncompliant [[sc=18;ec=23]] {{Replace this use of a reluctant quantifier with "[^abc\\d]++".}} - str.matches("\\w+?[abc]"); // Noncompliant [[sc=18;ec=23]] {{Replace this use of a reluctant quantifier with "[^abc\\W]++".}} - - str.matches("\\S*?[abc]"); // Noncompliant [[sc=18;ec=23]] {{Replace this use of a reluctant quantifier with "[^abc\\s]*+".}} - str.matches("\\D*?[abc]"); // Noncompliant [[sc=18;ec=23]] {{Replace this use of a reluctant quantifier with "[^abc\\d]*+".}} - str.matches("\\w*?[abc]"); // Noncompliant [[sc=18;ec=23]] {{Replace this use of a reluctant quantifier with "[^abc\\W]*+".}} - - str.matches("\\S+?[^abc]"); // Noncompliant [[sc=18;ec=23]] {{Replace this use of a reluctant quantifier with "[abc\\S]++".}} - str.matches("\\s+?[^abc]"); // Noncompliant [[sc=18;ec=23]] {{Replace this use of a reluctant quantifier with "[abc\\s]++".}} + str.matches(".+?[^abc]"); // Noncompliant {{Replace this use of a reluctant quantifier with "[abc]++".}} +// ^^^ + str.matches(".+?\\x{1F4A9}"); // Noncompliant {{Replace this use of a reluctant quantifier with "[^\\x{1F4A9}]++".}} +// ^^^ + str.matches(""); // Noncompliant {{Replace this use of a reluctant quantifier with "[^>]*+".}} +// ^^^ + str.matches("<.+?>|otherstuff"); // Noncompliant {{Replace this use of a reluctant quantifier with "[^>]++".}} +// ^^^ + str.matches("(<.+?>)*"); // Noncompliant {{Replace this use of a reluctant quantifier with "[^>]++".}} +// ^^^ + str.matches("\\S+?[abc]"); // Noncompliant {{Replace this use of a reluctant quantifier with "[^abc\\s]++".}} +// ^^^^^ + str.matches("\\D+?[abc]"); // Noncompliant {{Replace this use of a reluctant quantifier with "[^abc\\d]++".}} +// ^^^^^ + str.matches("\\w+?[abc]"); // Noncompliant {{Replace this use of a reluctant quantifier with "[^abc\\W]++".}} +// ^^^^^ + str.matches("\\S*?[abc]"); // Noncompliant {{Replace this use of a reluctant quantifier with "[^abc\\s]*+".}} +// ^^^^^ + str.matches("\\D*?[abc]"); // Noncompliant {{Replace this use of a reluctant quantifier with "[^abc\\d]*+".}} +// ^^^^^ + str.matches("\\w*?[abc]"); // Noncompliant {{Replace this use of a reluctant quantifier with "[^abc\\W]*+".}} +// ^^^^^ + str.matches("\\S+?[^abc]"); // Noncompliant {{Replace this use of a reluctant quantifier with "[abc\\S]++".}} +// ^^^^^ + str.matches("\\s+?[^abc]"); // Noncompliant {{Replace this use of a reluctant quantifier with "[abc\\s]++".}} +// ^^^^^ } void compliant(String str) { diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/ReluctantQuantifierWithEmptyContinuationCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/regex/ReluctantQuantifierWithEmptyContinuationCheckSample.java index 6ade5070b8c..52f5665908a 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/ReluctantQuantifierWithEmptyContinuationCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/ReluctantQuantifierWithEmptyContinuationCheckSample.java @@ -14,7 +14,8 @@ void noncompliant(String str) { Pattern.compile(".+?").matcher(str).find(); // Noncompliant {{Fix this reluctant quantifier that will only ever match 1 repetition.}} Pattern.compile(".{4}?").matcher(str).find(); // Noncompliant {{Fix this reluctant quantifier that will only ever match 4 repetitions.}} Pattern.compile(".{2,4}?").matcher(str).find(); // Noncompliant {{Fix this reluctant quantifier that will only ever match 2 repetitions.}} - Pattern.compile(".*?x?").matcher(str).find(); // Noncompliant [[sc=22;ec=25]] {{Fix this reluctant quantifier that will only ever match 0 repetitions.}} + Pattern.compile(".*?x?").matcher(str).find(); // Noncompliant {{Fix this reluctant quantifier that will only ever match 0 repetitions.}} +// ^^^ Pattern.compile(".*?()").matcher(str).find(); // Noncompliant {{Fix this reluctant quantifier that will only ever match 0 repetitions.}} Pattern.compile(".*?x?^").matcher(str).find(); // Noncompliant {{Fix this reluctant quantifier that will only ever match 0 repetitions.}} str.split(".*?x?^"); // Noncompliant {{Fix this reluctant quantifier that will only ever match 0 repetitions.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/SingleCharCharacterClassCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/regex/SingleCharCharacterClassCheckSample.java index 8d0d575dfcd..393031ae25c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/SingleCharCharacterClassCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/SingleCharCharacterClassCheckSample.java @@ -5,12 +5,14 @@ public class SingleCharCharacterClassCheckSample { void nonCompliant() { - Pattern.compile("[0]"); // Noncompliant {{Replace this character class by the character itself.}} - Pattern.compile("a[b]c"); // Noncompliant [[sc=24;ec=25]] - Pattern.compile("[ ]"); // Noncompliant + Pattern.compile("[0]"); // Noncompliant {{Replace this character class by the character itself.}} + Pattern.compile("a[b]c"); // Noncompliant +// ^ + Pattern.compile("[ ]"); // Noncompliant // Nested character classes - Pattern.compile("[ab[c]de]"); // Noncompliant [[sc=26;ec=27]] + Pattern.compile("[ab[c]de]"); // Noncompliant +// ^ Pattern.compile("[[0]]"); // Noncompliant } @@ -37,10 +39,10 @@ void compliant() { // "\", "^" and "[" can not be inside characters classes without escaping, the character class is redundant Pattern.compile("[\\\\]"); // Noncompliant - Pattern.compile("[\\^]"); // Noncompliant - Pattern.compile("[\\[]"); // Noncompliant + Pattern.compile("[\\^]"); // Noncompliant + Pattern.compile("[\\[]"); // Noncompliant // "]" does not need to be escaped - Pattern.compile("[]]"); // Noncompliant + Pattern.compile("[]]"); // Noncompliant Pattern.compile("a]b"); } } diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/SingleCharacterAlternationCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/regex/SingleCharacterAlternationCheckSample.java index 178a844621e..21940079294 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/SingleCharacterAlternationCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/SingleCharacterAlternationCheckSample.java @@ -4,21 +4,27 @@ public class SingleCharacterAlternationCheckSample { - @Pattern(regexp = "x|y|z") // Noncompliant [[sc=22;ec=27]] {{Replace this alternation with a character class.}} + @Pattern(regexp = "x|y|z") // Noncompliant {{Replace this alternation with a character class.}} +// ^^^^^ String pattern; - @jakarta.validation.constraints.Pattern(regexp = "x|y|z") // Noncompliant [[sc=53;ec=58]] {{Replace this alternation with a character class.}} + @jakarta.validation.constraints.Pattern(regexp = "x|y|z") // Noncompliant {{Replace this alternation with a character class.}} +// ^^^^^ String jakartaPattern; void nonCompliant() { String str = "abc123"; - str.matches("a|b|c"); // Noncompliant [[sc=18;ec=23]] {{Replace this alternation with a character class.}} - str.matches("a|(b|c)"); // Noncompliant [[sc=21;ec=24]] - str.matches("abcd|(e|f)gh"); // Noncompliant [[sc=24;ec=27]] - str.matches("(a|b|c)*"); // Noncompliant [[sc=19;ec=24]] - str.matches("\\d|x"); // Noncompliant [sc=18;ec=23]] - str.matches("\\P{L}|\\d"); // Noncompliant [sc=18;ec=28]] - str.matches("\\u1234|\\x{12345}"); // Noncompliant [sc=18;ec=36]] + str.matches("a|b|c"); // Noncompliant {{Replace this alternation with a character class.}} +// ^^^^^ + str.matches("a|(b|c)"); // Noncompliant +// ^^^ + str.matches("abcd|(e|f)gh"); // Noncompliant +// ^^^ + str.matches("(a|b|c)*"); // Noncompliant +// ^^^^^ + str.matches("\\d|x"); // Noncompliant + str.matches("\\P{L}|\\d"); // Noncompliant + str.matches("\\u1234|\\x{12345}"); // Noncompliant str.matches("😂|😊"); // Noncompliant str.matches("\ud800\udc00|\udbff\udfff"); // Noncompliant str.matches("[😂😊]"); // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/StringReplace.java b/java-checks-test-sources/default/src/main/java/checks/regex/StringReplace.java index 9150af9ce65..f1e73826ff4 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/StringReplace.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/StringReplace.java @@ -11,8 +11,10 @@ public class StringReplace { public void foo(String r) { String init = "Bob is a Bird... Bob is a Plane... Bob is Superman!"; - String changed = init.replaceAll("Bob is", "It's"); // Noncompliant [[sc=27;ec=37]] {{Replace this call to "replaceAll()" by a call to the "replace()" method.}} - changed = init.replaceAll(PLANE, "UFO"); // Noncompliant [[sc=20;ec=30]] + String changed = init.replaceAll("Bob is", "It's"); // Noncompliant {{Replace this call to "replaceAll()" by a call to the "replace()" method.}} +// ^^^^^^^^^^ + changed = init.replaceAll(PLANE, "UFO"); // Noncompliant +// ^^^^^^^^^^ changed = init.replaceAll("\\.\\.\\.", ";"); // Noncompliant changed = init.replaceAll("\\Q...\\E", ";"); // Noncompliant changed = init.replaceAll("\\\\", "It's"); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/SuperfluousCurlyBraceCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/regex/SuperfluousCurlyBraceCheckSample.java index d5793d8a479..db0057ea837 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/SuperfluousCurlyBraceCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/SuperfluousCurlyBraceCheckSample.java @@ -5,10 +5,14 @@ public class SuperfluousCurlyBraceCheckSample { void noncompliant() { - compile("ab{1,1}c"); // Noncompliant [[sc=16;ec=21]] {{Remove this unnecessary quantifier.}} - compile("ab{1}c"); // Noncompliant [[sc=16;ec=19]] {{Remove this unnecessary quantifier.}} - compile("ab{0,0}c"); // Noncompliant [[sc=15;ec=21]] {{Remove this unnecessarily quantified expression.}} - compile("ab{0}c"); // Noncompliant [[sc=15;ec=19]] {{Remove this unnecessarily quantified expression.}} + compile("ab{1,1}c"); // Noncompliant {{Remove this unnecessary quantifier.}} +// ^^^^^ + compile("ab{1}c"); // Noncompliant {{Remove this unnecessary quantifier.}} +// ^^^ + compile("ab{0,0}c"); // Noncompliant {{Remove this unnecessarily quantified expression.}} +// ^^^^^^ + compile("ab{0}c"); // Noncompliant {{Remove this unnecessarily quantified expression.}} +// ^^^^ } void compliant() { diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/UnicodeAwareCharClassesCheckTest.java b/java-checks-test-sources/default/src/main/java/checks/regex/UnicodeAwareCharClassesCheckTest.java index 9fb1e56e013..1deae03dc5f 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/UnicodeAwareCharClassesCheckTest.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/UnicodeAwareCharClassesCheckTest.java @@ -26,10 +26,13 @@ public class UnicodeAwareCharClassesCheckTest { - @Email(regexp = "[a-z]") // Noncompliant [[sc=21;ec=24]] {{Replace this character range with a Unicode-aware character class.}} + @Email(regexp = "[a-z]") // Noncompliant {{Replace this character range with a Unicode-aware character class.}} +// ^^^ String email; - @URL(regexp = "\\p{Lower}", flags = jakarta.validation.constraints.Pattern.Flag.DOTALL) // Noncompliant [[sc=4;ec=7;secondary=32]] {{Enable the "(?U)" flag or use a Unicode-aware alternative.}} + @URL(regexp = "\\p{Lower}", flags = jakarta.validation.constraints.Pattern.Flag.DOTALL) // Noncompliant {{Enable the "(?U)" flag or use a Unicode-aware alternative.}} +// ^^^ +// ^^^^^^^^^^@-1< String url1; @URL(regexp = "(?U)\\p{Lower}") // Compliant @@ -39,18 +42,25 @@ public class UnicodeAwareCharClassesCheckTest { String url3; void NoncompliantCharRanges() { - Pattern.compile("[a-z]"); // Noncompliant [[sc=23;ec=26]] {{Replace this character range with a Unicode-aware character class.}} + Pattern.compile("[a-z]"); // Noncompliant {{Replace this character range with a Unicode-aware character class.}} +// ^^^ Pattern.compile("[A-Z]"); // Noncompliant Pattern.compile("[0-9a-z]"); // Noncompliant Pattern.compile("[abcA-Zdef]"); // Noncompliant - Pattern.compile("[\\x{61}-\\x{7A}]"); // Noncompliant [[sc=23;ec=38]] - Pattern.compile("[a-zA-Z]"); // Noncompliant [[sc=22;ec=30;secondary=47,47]] {{Replace these character ranges with Unicode-aware character classes.}} + Pattern.compile("[\\x{61}-\\x{7A}]"); // Noncompliant +// ^^^^^^^^^^^^^^^ + Pattern.compile("[a-zA-Z]"); // Noncompliant {{Replace these character ranges with Unicode-aware character classes.}} +// ^^^^^^^^ +// ^^^@-1< +// ^^^@-2< String regex = "[a-zA-Z]"; // Noncompliant Pattern.compile(regex + regex); } void NoncompliantPredefinedPosixClasses() { - Pattern.compile("\\p{Lower}"); // Noncompliant [[sc=13;ec=20;secondary=53]] {{Enable the "UNICODE_CHARACTER_CLASS" flag or use a Unicode-aware alternative.}} + Pattern.compile("\\p{Lower}"); // Noncompliant {{Enable the "UNICODE_CHARACTER_CLASS" flag or use a Unicode-aware alternative.}} +// ^^^^^^^ +// ^^^^^^^^^^@-1< Pattern.compile("\\p{Alnum}"); // Noncompliant Pattern.compile("\\p{Space}"); // Noncompliant Pattern.compile("\\s"); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/UnicodeCaseCheck.java b/java-checks-test-sources/default/src/main/java/checks/regex/UnicodeCaseCheck.java index c5c5af36dd7..2782f7d02d2 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/UnicodeCaseCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/UnicodeCaseCheck.java @@ -8,7 +8,8 @@ public class UnicodeCaseCheck { @Email( regexp = "söme pättern", - flags = Flag.CASE_INSENSITIVE // Noncompliant [[sc=13;ec=34]] {{Also use "Flag.UNICODE_CASE" to correctly handle non-ASCII letters.}} + flags = Flag.CASE_INSENSITIVE // Noncompliant {{Also use "Flag.UNICODE_CASE" to correctly handle non-ASCII letters.}} +// ^^^^^^^^^^^^^^^^^^^^^ ) String email1; @@ -19,22 +20,30 @@ public class UnicodeCaseCheck { String email2; void noncompliant(String str) { - Pattern.compile("söme pättern", Pattern.CASE_INSENSITIVE); // Noncompliant [[sc=37;ec=61]] {{Also use "Pattern.UNICODE_CASE" to correctly handle non-ASCII letters.}} + Pattern.compile("söme pättern", Pattern.CASE_INSENSITIVE); // Noncompliant {{Also use "Pattern.UNICODE_CASE" to correctly handle non-ASCII letters.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^ Pattern.compile("s\u00F6me", Pattern.CASE_INSENSITIVE); // Noncompliant Pattern.compile("s\\u00F6me", Pattern.CASE_INSENSITIVE); // Noncompliant Pattern.compile("s\\xF6me", Pattern.CASE_INSENSITIVE); // Noncompliant - Pattern.compile("söme pättern", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); // Noncompliant [[sc=37;ec=81]] {{Also use "Pattern.UNICODE_CASE" to correctly handle non-ASCII letters.}} - str.matches("(?i)söme pättern"); // Noncompliant [[sc=20;ec=21]] {{Also use the "u" flag to correctly handle non-ASCII letters.}} - str.matches("(?i:söme) pättern"); // Noncompliant [[sc=20;ec=21]] {{Also use the "u" flag to correctly handle non-ASCII letters.}} + Pattern.compile("söme pättern", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); // Noncompliant {{Also use "Pattern.UNICODE_CASE" to correctly handle non-ASCII letters.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + str.matches("(?i)söme pättern"); // Noncompliant {{Also use the "u" flag to correctly handle non-ASCII letters.}} +// ^ + str.matches("(?i:söme) pättern"); // Noncompliant {{Also use the "u" flag to correctly handle non-ASCII letters.}} +// ^ - String regexPart1 = "(?i:söme)"; // Noncompliant [[sc=28;ec=29]] {{Also use the "u" flag to correctly handle non-ASCII letters.}} - String regexPart2 = "(?i:pättern)"; // Noncompliant [[sc=28;ec=29]] {{Also use the "u" flag to correctly handle non-ASCII letters.}} + String regexPart1 = "(?i:söme)"; // Noncompliant {{Also use the "u" flag to correctly handle non-ASCII letters.}} +// ^ + String regexPart2 = "(?i:pättern)"; // Noncompliant {{Also use the "u" flag to correctly handle non-ASCII letters.}} +// ^ str.matches(regexPart1 + regexPart2); // In these cases the location of the issue is a bit confusing, but code like this will probably not occur in the wild - str.matches("(?iu)söme (?-u)pättern"); // Noncompliant [[sc=20;ec=21]] {{Also use the "u" flag to correctly handle non-ASCII letters.}} - str.matches("(?iu)söme (?-U)pättern"); // Noncompliant [[sc=20;ec=21]] {{Also use the "u" flag to correctly handle non-ASCII letters.}} + str.matches("(?iu)söme (?-u)pättern"); // Noncompliant {{Also use the "u" flag to correctly handle non-ASCII letters.}} +// ^ + str.matches("(?iu)söme (?-U)pättern"); // Noncompliant {{Also use the "u" flag to correctly handle non-ASCII letters.}} +// ^ } void compliant(String str) { @@ -52,7 +61,8 @@ void compliant(String str) { @jakarta.validation.constraints.Email( regexp = "söme pättern", - flags = jakarta.validation.constraints.Pattern.Flag.CASE_INSENSITIVE // Noncompliant [[sc=13;ec=73]] {{Also use "Flag.UNICODE_CASE" to correctly handle non-ASCII letters.}} + flags = jakarta.validation.constraints.Pattern.Flag.CASE_INSENSITIVE // Noncompliant {{Also use "Flag.UNICODE_CASE" to correctly handle non-ASCII letters.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ) String jakartaEmail1; diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/UnquantifiedNonCapturingGroupCheck.java b/java-checks-test-sources/default/src/main/java/checks/regex/UnquantifiedNonCapturingGroupCheck.java index 9fe4c5e5393..b472e233b86 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/UnquantifiedNonCapturingGroupCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/UnquantifiedNonCapturingGroupCheck.java @@ -5,12 +5,15 @@ public class UnquantifiedNonCapturingGroupCheck { void nonCompliant() { - Pattern.compile("(?:number)"); // Noncompliant [[sc=22;ec=32]] {{Unwrap this unnecessarily grouped subpattern.}} - Pattern.compile("(?:number)\\d{2}"); // Noncompliant - Pattern.compile("(?:number(?:two){2})"); // Noncompliant [[sc=22;ec=42]] - Pattern.compile("(?:number(?:two)){2}"); // Noncompliant [[sc=31;ec=38]] - Pattern.compile("foo(?:number)bar"); // Noncompliant - Pattern.compile("(?:)"); // Noncompliant + Pattern.compile("(?:number)"); // Noncompliant {{Unwrap this unnecessarily grouped subpattern.}} +// ^^^^^^^^^^ + Pattern.compile("(?:number)\\d{2}"); // Noncompliant + Pattern.compile("(?:number(?:two){2})"); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^ + Pattern.compile("(?:number(?:two)){2}"); // Noncompliant +// ^^^^^^^ + Pattern.compile("foo(?:number)bar"); // Noncompliant + Pattern.compile("(?:)"); // Noncompliant } void compliant() { diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/UnusedGroupNamesCheck.java b/java-checks-test-sources/default/src/main/java/checks/regex/UnusedGroupNamesCheck.java index c1cd3cebfb6..92db8079448 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/UnusedGroupNamesCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/UnusedGroupNamesCheck.java @@ -6,30 +6,39 @@ abstract class UnusedGroupNamesCheck { private final Pattern p0 = Pattern.compile("(?[0-9]{2})"); - +// ^^^^^^^^^^^^^^^> void noncompliant(String input) { Matcher m0 = p0.matcher(input); if (m0.matches()) { - m0.group(1); // Noncompliant [[secondary=-6]] {{Directly use 'g1' instead of its group number.}} - m0.start(1); // Noncompliant [[secondary=-7]] {{Directly use 'g1' instead of its group number.}} - m0.end(1); // Noncompliant [[secondary=-8]] {{Directly use 'g1' instead of its group number.}} + m0.group(1); // Noncompliant {{Directly use 'g1' instead of its group number.}} +// ^ + m0.start(1); // Noncompliant {{Directly use 'g1' instead of its group number.}} +// ^ + m0.end(1); // Noncompliant {{Directly use 'g1' instead of its group number.}} +// ^ } Pattern p1 = Pattern .compile( "(?[0-9]+)" +// ^^^^^^^^^^^^^> + ":" + "(?[0-9]+)"); +// ^^^^^^^^^^^^^> Matcher m1 = p1.matcher(input); if (m1.matches()) { - m1.group("g3"); // Noncompliant [[secondary=-3,-5]] {{There is no group named 'g3' in the regular expression.}} - m1.start("g3"); // Noncompliant [[secondary=-4,-6]] {{There is no group named 'g3' in the regular expression.}} - m1.end("g3"); // Noncompliant [[secondary=-5,-7]] {{There is no group named 'g3' in the regular expression.}} + m1.group("g3"); // Noncompliant {{There is no group named 'g3' in the regular expression.}} +// ^^^^ + m1.start("g3"); // Noncompliant {{There is no group named 'g3' in the regular expression.}} +// ^^^^ + m1.end("g3"); // Noncompliant {{There is no group named 'g3' in the regular expression.}} +// ^^^^ } Matcher m2 = Pattern.compile( "(?[0-9]{2})" +// ^^^^^^^^^^^^^^^^^^> + "/" + "(?[0-9]{2})") .matcher(input); @@ -37,16 +46,14 @@ void noncompliant(String input) { // type of println is Object, not Matcher, so we can assume that it won't be used as a matcher new Bar(m2); // Same. Bar takes Object as its argument type if (m2.matches()) { - m2.group( - 1 // Noncompliant [[secondary=-9]] {{Directly use 'month' instead of its group number.}} - ); - m2.group( - 2 // Noncompliant [[secondary=-10]] {{Directly use 'year' instead of its group number.}} - ); + m2.group(1); // Noncompliant {{Directly use 'month' instead of its group number.}} +// ^ + m2.group(2); // Noncompliant {{Directly use 'year' instead of its group number.}} +// ^ } Pattern p3 = Pattern.compile( - "(?[a-z]+)" // Noncompliant [[secondary=+0,+2,+4]] {{Use the named groups of this regex or remove the names.}} + "(?[a-z]+)" // Noncompliant {{Use the named groups of this regex or remove the names.}} + ":" + "(?[0-9]+)" + "=" @@ -282,7 +289,7 @@ static class UsingFields2 { } void useMatcher() { - matcher.group(1); // Noncompliant [[secondary=-8]] {{Directly use 'group' instead of its group number.}} + matcher.group(1); // Noncompliant {{Directly use 'group' instead of its group number.}} } } diff --git a/java-checks-test-sources/default/src/main/java/checks/regex/VerboseRegexCheck.java b/java-checks-test-sources/default/src/main/java/checks/regex/VerboseRegexCheck.java index 0663b1fca2b..27a476b51bd 100644 --- a/java-checks-test-sources/default/src/main/java/checks/regex/VerboseRegexCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/regex/VerboseRegexCheck.java @@ -5,22 +5,23 @@ public class VerboseRegexCheck { void nonCompliant() { Pattern.compile("[0-9]"); // Noncompliant {{Use concise character class syntax '\\d' instead of '[0-9]'.}} - Pattern.compile("[^0-9]"); // Noncompliant {{Use concise character class syntax '\\D' instead of '[^0-9]'.}} - Pattern.compile("something[0-9]somethingElse"); // Noncompliant [[sc=31;ec=36]] {{Use concise character class syntax '\\d' instead of '[0-9]'.}} + Pattern.compile("[^0-9]"); // Noncompliant {{Use concise character class syntax '\\D' instead of '[^0-9]'.}} + Pattern.compile("something[0-9]somethingElse"); // Noncompliant {{Use concise character class syntax '\\d' instead of '[0-9]'.}} +// ^^^^^ - Pattern.compile("[A-Za-z0-9_]"); // Noncompliant {{Use concise character class syntax '\\w' instead of '[A-Za-z0-9_]'.}} - Pattern.compile("[0-9_A-Za-z]"); // Noncompliant - Pattern.compile("[^A-Za-z0-9_]"); // Noncompliant {{Use concise character class syntax '\\W' instead of '[^A-Za-z0-9_]'.}} - Pattern.compile("[^0-9_A-Za-z]"); // Noncompliant + Pattern.compile("[A-Za-z0-9_]"); // Noncompliant {{Use concise character class syntax '\\w' instead of '[A-Za-z0-9_]'.}} + Pattern.compile("[0-9_A-Za-z]"); // Noncompliant + Pattern.compile("[^A-Za-z0-9_]"); // Noncompliant {{Use concise character class syntax '\\W' instead of '[^A-Za-z0-9_]'.}} + Pattern.compile("[^0-9_A-Za-z]"); // Noncompliant - Pattern.compile("x{0,1}"); // Noncompliant {{Use concise quantifier syntax '?' instead of '{0,1}'.}} - Pattern.compile("x{0,1}?"); // Noncompliant {{Use concise quantifier syntax '?' instead of '{0,1}'.}} - Pattern.compile("x{0,}"); // Noncompliant {{Use concise quantifier syntax '*' instead of '{0,}'.}} - Pattern.compile("x{0,}?"); // Noncompliant {{Use concise quantifier syntax '*' instead of '{0,}'.}} - Pattern.compile("x{1,}"); // Noncompliant {{Use concise quantifier syntax '+' instead of '{1,}'.}} - Pattern.compile("x{1,}?"); // Noncompliant {{Use concise quantifier syntax '+' instead of '{1,}'.}} - Pattern.compile("x{2,2}"); // Noncompliant {{Use concise quantifier syntax '{2}' instead of '{2,2}'.}} - Pattern.compile("x{2,2}?"); // Noncompliant {{Use concise quantifier syntax '{2}' instead of '{2,2}'.}} + Pattern.compile("x{0,1}"); // Noncompliant {{Use concise quantifier syntax '?' instead of '{0,1}'.}} + Pattern.compile("x{0,1}?"); // Noncompliant {{Use concise quantifier syntax '?' instead of '{0,1}'.}} + Pattern.compile("x{0,}"); // Noncompliant {{Use concise quantifier syntax '*' instead of '{0,}'.}} + Pattern.compile("x{0,}?"); // Noncompliant {{Use concise quantifier syntax '*' instead of '{0,}'.}} + Pattern.compile("x{1,}"); // Noncompliant {{Use concise quantifier syntax '+' instead of '{1,}'.}} + Pattern.compile("x{1,}?"); // Noncompliant {{Use concise quantifier syntax '+' instead of '{1,}'.}} + Pattern.compile("x{2,2}"); // Noncompliant {{Use concise quantifier syntax '{2}' instead of '{2,2}'.}} + Pattern.compile("x{2,2}?"); // Noncompliant {{Use concise quantifier syntax '{2}' instead of '{2,2}'.}} Pattern.compile("[\\W\\w]"); // Noncompliant {{Use concise character class syntax '.' instead of '[\\W\\w]'.}} Pattern.compile("[\\d\\D]"); // Noncompliant {{Use concise character class syntax '.' instead of '[\\d\\D]'.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/security/AndroidBiometricAuthWithoutCryptoCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/security/AndroidBiometricAuthWithoutCryptoCheckSample.java index 2e412dedf28..897c2a4530a 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/AndroidBiometricAuthWithoutCryptoCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/AndroidBiometricAuthWithoutCryptoCheckSample.java @@ -12,7 +12,8 @@ void android_no_crypto( Executor executor, BiometricPrompt.AuthenticationCallback callback) { - bp.authenticate(cancel, executor, callback); // Noncompliant [[sc=8;ec=20]] {{Make sure performing a biometric authentication without a "CryptoObject" is safe here.}} + bp.authenticate(cancel, executor, callback); // Noncompliant {{Make sure performing a biometric authentication without a "CryptoObject" is safe here.}} +// ^^^^^^^^^^^^ } void android_crypto( @@ -28,7 +29,8 @@ void android_crypto( void androidx_no_crypto( androidx.biometric.BiometricPrompt bp, androidx.biometric.BiometricPrompt.PromptInfo info) { - bp.authenticate(info); // Noncompliant [[sc=8;ec=20]] {{Make sure performing a biometric authentication without a "CryptoObject" is safe here.}} + bp.authenticate(info); // Noncompliant {{Make sure performing a biometric authentication without a "CryptoObject" is safe here.}} +// ^^^^^^^^^^^^ } void androidx_crypto( diff --git a/java-checks-test-sources/default/src/main/java/checks/security/AndroidMobileDatabaseEncryptionKeysCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/security/AndroidMobileDatabaseEncryptionKeysCheckSample.java index 6ddb6437c5d..3bca025db58 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/AndroidMobileDatabaseEncryptionKeysCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/AndroidMobileDatabaseEncryptionKeysCheckSample.java @@ -21,6 +21,7 @@ void changePassword(String pwd) { void SQLiteDatabase_openOrCreateDatabase(String databasePath, SQLiteDatabaseHook hook, SQLiteDatabase.CursorFactory cursorFactory) { String password = "pwd"; +// ^^^^^> SQLiteDatabase database; database = new SQLiteDatabase("path", "pwd".toCharArray(), cursorFactory, 0); // Noncompliant @@ -29,7 +30,8 @@ void SQLiteDatabase_openOrCreateDatabase(String databasePath, SQLiteDatabaseHook char[] charArray = "pwd".toCharArray(); database = new SQLiteDatabase("path", charArray, cursorFactory, 0); // Noncompliant - database = SQLiteDatabase.openOrCreateDatabase(databasePath, password, null, hook); // Noncompliant [[sc=66;ec=74;secondary=23]] {{The "password" parameter should not be hardcoded.}} + database = SQLiteDatabase.openOrCreateDatabase(databasePath, password, null, hook); // Noncompliant {{The "password" parameter should not be hardcoded.}} +// ^^^^^^^^ database = SQLiteDatabase.openOrCreateDatabase(databasePath, "test123", null); // Noncompliant database = SQLiteDatabase.openDatabase(databasePath, password, cursorFactory, 0); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/security/AndroidNonAuthenticatedUsersCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/security/AndroidNonAuthenticatedUsersCheckSample.java index 165c9431698..3c5cb688a75 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/AndroidNonAuthenticatedUsersCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/AndroidNonAuthenticatedUsersCheckSample.java @@ -8,7 +8,8 @@ public class AndroidNonAuthenticatedUsersCheckSample { KeyGenParameterSpec.Builder builderField; void f(boolean cond) { - new KeyGenParameterSpec.Builder("test_secret_key_noncompliant", // Noncompliant [[sc=9;ec=36]] {{Make sure authorizing non-authenticated users to use this key is safe here.}} + new KeyGenParameterSpec.Builder("test_secret_key_noncompliant", // Noncompliant {{Make sure authorizing non-authenticated users to use this key is safe here.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_GCM) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) @@ -34,7 +35,7 @@ void f(boolean cond) { .setUserAuthenticationRequired(true); builderInProgress2.build(); - // Noncompliant@+1 + // Noncompliant@+1 KeyGenParameterSpec.Builder builderInProgress3 = new KeyGenParameterSpec.Builder("test_secret_key", KeyProperties.PURPOSE_ENCRYPT); builderInProgress3 .setBlockModes(KeyProperties.BLOCK_MODE_GCM) @@ -47,7 +48,7 @@ void f(boolean cond) { builderInProgress4.setBlockModes(KeyProperties.BLOCK_MODE_GCM); builderInProgress4.build(); - // Noncompliant@+1 + // Noncompliant@+1 KeyGenParameterSpec.Builder builderInProgress5 = new KeyGenParameterSpec.Builder("test_secret_key", KeyProperties.PURPOSE_ENCRYPT) .setUserAuthenticationRequired(false); builderInProgress5.setBlockModes(KeyProperties.BLOCK_MODE_GCM); @@ -60,7 +61,7 @@ void f(boolean cond) { } builderConditionallyAuthenticated.build(); - // Noncompliant@+1 + // Noncompliant@+1 KeyGenParameterSpec.Builder builderNotAuthenticated = new KeyGenParameterSpec.Builder("test_secret_key", KeyProperties.PURPOSE_ENCRYPT); builderNotAuthenticated.build(); @@ -94,7 +95,7 @@ void f(boolean cond) { } void valueAsArgument(boolean arg) { - // Noncompliant@+1 + // Noncompliant@+1 new KeyGenParameterSpec.Builder("test_secret_key", KeyProperties.PURPOSE_ENCRYPT) // Corner case: can not guarantee that the value is always true, we still report an issue. .setUserAuthenticationRequired(arg) diff --git a/java-checks-test-sources/default/src/main/java/checks/security/AndroidUnencryptedDatabaseCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/security/AndroidUnencryptedDatabaseCheckSample.java index 6462ac503ed..61c49d7df54 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/AndroidUnencryptedDatabaseCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/AndroidUnencryptedDatabaseCheckSample.java @@ -13,25 +13,29 @@ public class AndroidUnencryptedDatabaseCheckSample { RealmConfiguration.Builder builderAsField; void testSharedPreferences(Activity activity, Context context, PreferenceManager preferenceManager) { - activity.getPreferences(1); // Noncompliant [[sc=14;ec=28]] {{Make sure using an unencrypted database is safe here.}} + activity.getPreferences(1); // Noncompliant {{Make sure using an unencrypted database is safe here.}} +// ^^^^^^^^^^^^^^ activity().getPreferences(2); // Noncompliant myActivity().getPreferences(3); // Noncompliant myActivity().getPreferences(3, 4); // Compliant, unrelated method - context.getSharedPreferences(new File(""), 1); // Noncompliant [[sc=13;ec=33]] {{Make sure using an unencrypted database is safe here.}} + context.getSharedPreferences(new File(""), 1); // Noncompliant {{Make sure using an unencrypted database is safe here.}} +// ^^^^^^^^^^^^^^^^^^^^ context.getSharedPreferences("file", 1); // Noncompliant PreferenceManager.getDefaultSharedPreferences(context); // Noncompliant } void testSQLiteDatabase(Context context, SQLiteDatabase.CursorFactory cursorFactory, DatabaseErrorHandler databaseErrorHandler) { - context.openOrCreateDatabase("name", 1, cursorFactory); // Noncompliant [[sc=13;ec=33]] {{Make sure using an unencrypted database is safe here.}} + context.openOrCreateDatabase("name", 1, cursorFactory); // Noncompliant {{Make sure using an unencrypted database is safe here.}} +// ^^^^^^^^^^^^^^^^^^^^ context.openOrCreateDatabase("name", 1, cursorFactory, databaseErrorHandler); // Noncompliant } void testRealm() { new RealmConfiguration.Builder() - .build(); // Noncompliant [[sc=8;ec=13]] + .build(); // Noncompliant +// ^^^^^ new RealmConfiguration.Builder() .name("") diff --git a/java-checks-test-sources/default/src/main/java/checks/security/AndroidUnencryptedFilesCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/security/AndroidUnencryptedFilesCheckSample.java index 8111c702bd6..d06dcbc0011 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/AndroidUnencryptedFilesCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/AndroidUnencryptedFilesCheckSample.java @@ -11,16 +11,19 @@ public class AndroidUnencryptedFilesCheckSample { void fileWrite(Path path) throws IOException { - Files.write(path, "content".getBytes()); // Noncompliant [[sc=11;ec=16]] {{Make sure using unencrypted files is safe here.}} + Files.write(path, "content".getBytes()); // Noncompliant {{Make sure using unencrypted files is safe here.}} +// ^^^^^ } void fileOutputStreamWrite(File file) throws IOException { - FileOutputStream out = new FileOutputStream(file); // Noncompliant [[sc=32;ec=48]] {{Make sure using unencrypted files is safe here.}} + FileOutputStream out = new FileOutputStream(file); // Noncompliant {{Make sure using unencrypted files is safe here.}} +// ^^^^^^^^^^^^^^^^ out.write("content".getBytes()); } void fileOutputStreamWrite(Writer writer) throws IOException { - FileWriter fw = new FileWriter("outfilename", true); // Noncompliant [[sc=25;ec=35]] {{Make sure using unencrypted files is safe here.}} + FileWriter fw = new FileWriter("outfilename", true); // Noncompliant {{Make sure using unencrypted files is safe here.}} +// ^^^^^^^^^^ BufferedWriter output = new BufferedWriter(fw); // Compliant, reported on output.write("some test content..."); } diff --git a/java-checks-test-sources/default/src/main/java/checks/security/AuthorizationsStrongDecisionsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/security/AuthorizationsStrongDecisionsCheckSample.java index d9297a02421..1cea2deabb0 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/AuthorizationsStrongDecisionsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/AuthorizationsStrongDecisionsCheckSample.java @@ -15,7 +15,8 @@ public class AuthorizationsStrongDecisionsCheckSample { class WeakNightVoter implements AccessDecisionVoter { @Override - public int vote(Authentication authentication, Object object, Collection collection) { // Noncompliant [[sc=16;ec=20]] {{"vote" method should return at least one time ACCESS_DENIED.}} + public int vote(Authentication authentication, Object object, Collection collection) { // Noncompliant {{"vote" method should return at least one time ACCESS_DENIED.}} +// ^^^^ Calendar calendar = Calendar.getInstance(); int currentHour = calendar.get(Calendar.HOUR_OF_DAY); if(currentHour >= 8 && currentHour <= 19) { @@ -173,7 +174,8 @@ public int vote(Authentication authentication, Object object, Collection collect class MyPermissionEvaluatorNonCompliant implements PermissionEvaluator { @Override - public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) { // Noncompliant [[sc=20;ec=33]] {{"hasPermission" method should return at least one time false.}} + public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) { // Noncompliant {{"hasPermission" method should return at least one time false.}} +// ^^^^^^^^^^^^^ Object user = authentication.getPrincipal(); if(user.equals(permission)) { return true; diff --git a/java-checks-test-sources/default/src/main/java/checks/security/CipherBlockChainingCheck.java b/java-checks-test-sources/default/src/main/java/checks/security/CipherBlockChainingCheck.java index cbdc5513a9b..a2aa514e711 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/CipherBlockChainingCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/CipherBlockChainingCheck.java @@ -28,11 +28,12 @@ void foo1() void foo2() throws UnsupportedEncodingException { byte[] bytes = "111".getBytes("UTF-8"); - IvParameterSpec iv = new IvParameterSpec(bytes); // Noncompliant [[sc=26;ec=52]] {{Use a dynamically-generated, random IV.}} + IvParameterSpec iv = new IvParameterSpec(bytes); // Noncompliant {{Use a dynamically-generated, random IV.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^ } void foo3() { - IvParameterSpec iv = new IvParameterSpec(bytes2); // Noncompliant FN, will be fixed with SE engine + IvParameterSpec iv = new IvParameterSpec(bytes2); // Noncompliant } void foo4() throws UnsupportedEncodingException { @@ -90,14 +91,14 @@ void foo11() throws UnsupportedEncodingException { void foo12() throws UnsupportedEncodingException { byte[] bytes = "111".getBytes("UTF-8"); random.nextBytes(bytes); - IvParameterSpec iv = new IvParameterSpec(null); // Noncompliant Coverage reasons + IvParameterSpec iv = new IvParameterSpec(null); // Noncompliant } void foo13() throws UnsupportedEncodingException { byte[] bytes = "111".getBytes("UTF-8"); random.nextBytes(bytes); byte[] bytes2 = "111222".getBytes("UTF-8"); - IvParameterSpec iv = new IvParameterSpec(bytes2); // Noncompliant Coverage reasons + IvParameterSpec iv = new IvParameterSpec(bytes2); // Noncompliant } void foo14() throws UnsupportedEncodingException { @@ -167,7 +168,7 @@ static void decryptImpl2(byte[] biv, SecretKeySpec ks) throws Exception { } static void decryptImpl3(SecretKeySpec ks) throws Exception { - new IvParameterSpec("111".getBytes("UTF-8")); // Noncompliant - not used + new IvParameterSpec("111".getBytes("UTF-8")); // Noncompliant Cipher .getInstance(OPERATION_MODE, "BC") .init(Cipher.DECRYPT_MODE, ks); @@ -175,21 +176,21 @@ static void decryptImpl3(SecretKeySpec ks) throws Exception { static void decryptImpl4(SecretKeySpec ks) throws Exception { byte[] biv = new byte[IV_SIZE]; - IvParameterSpec iv = new IvParameterSpec(biv); // Noncompliant - not random + IvParameterSpec iv = new IvParameterSpec(biv); // Noncompliant Cipher .getInstance(OPERATION_MODE, "BC") .init(Cipher.ENCRYPT_MODE, ks, iv); } static void decryptImpl5(SecretKeySpec ks, IvParameterSpec iv) throws Exception { - new IvParameterSpec("111".getBytes("UTF-8")); // Noncompliant - not used + new IvParameterSpec("111".getBytes("UTF-8")); // Noncompliant Cipher .getInstance(OPERATION_MODE, "BC") .init(Cipher.DECRYPT_MODE, ks, iv); } static void decryptImpl6(SecretKeySpec ks, IvParameterSpec iv) throws Exception { - IvParameterSpec iv2 = new IvParameterSpec("111".getBytes("UTF-8")); // Noncompliant - not used + IvParameterSpec iv2 = new IvParameterSpec("111".getBytes("UTF-8")); // Noncompliant Cipher .getInstance(OPERATION_MODE, "BC") .init(Cipher.DECRYPT_MODE, ks, iv); diff --git a/java-checks-test-sources/default/src/main/java/checks/security/ClearTextProtocol.java b/java-checks-test-sources/default/src/main/java/checks/security/ClearTextProtocol.java index 5dfbee99a32..135b2000a41 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/ClearTextProtocol.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/ClearTextProtocol.java @@ -14,7 +14,8 @@ public class ClearTextProtocol { void noncompliant() { - new FTPClient(); // Noncompliant [[sc=9;ec=18]] {{Using FTP protocol is insecure. Use SFTP, SCP or FTPS instead.}} + new FTPClient(); // Noncompliant {{Using FTP protocol is insecure. Use SFTP, SCP or FTPS instead.}} +// ^^^^^^^^^ new TelnetClient(); // Noncompliant {{Using Telnet protocol is insecure. Use SSH instead.}} new SMTPClient(); // Noncompliant {{Using clear-text SMTP protocol is insecure. Use SMTP over SSL/TLS or SMTP with STARTTLS instead.}} new SMTPClient("UTF-8"); // Noncompliant {{Using clear-text SMTP protocol is insecure. Use SMTP over SSL/TLS or SMTP with STARTTLS instead.}} @@ -27,14 +28,17 @@ void compliant() { void okHttp() { OkHttpClient client1 = new OkHttpClient.Builder() - .connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.CLEARTEXT)) // Noncompliant [[sc=80;ec=89]] {{Using HTTP protocol is insecure. Use HTTPS instead.}} + .connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.CLEARTEXT)) // Noncompliant {{Using HTTP protocol is insecure. Use HTTPS instead.}} +// ^^^^^^^^^ .build(); OkHttpClient client15 = new OkHttpClient.Builder() - .connectionSpecs(Collections.singletonList(ConnectionSpec.CLEARTEXT)) // Noncompliant [[sc=65;ec=74]] {{Using HTTP protocol is insecure. Use HTTPS instead.}} + .connectionSpecs(Collections.singletonList(ConnectionSpec.CLEARTEXT)) // Noncompliant {{Using HTTP protocol is insecure. Use HTTPS instead.}} +// ^^^^^^^^^ .build(); - ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.CLEARTEXT) // Noncompliant [[sc=69;ec=78]] {{Using HTTP protocol is insecure. Use HTTPS instead.}} + ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.CLEARTEXT) // Noncompliant {{Using HTTP protocol is insecure. Use HTTPS instead.}} +// ^^^^^^^^^ .build(); OkHttpClient client2 = new OkHttpClient.Builder() @@ -59,7 +63,8 @@ void okHttp() { } void androidWebSettings(WebSettings settings, int value) { - settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); // Noncompliant [[sc=34;ec=72]] {{Using a relaxed mixed content policy is security-sensitive.}} + settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); // Noncompliant {{Using a relaxed mixed content policy is security-sensitive.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ settings.setMixedContentMode(0); // Noncompliant settings.setMixedContentMode(value); // Compliant settings.setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW); // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/security/CookieHttpOnlyCheck.java b/java-checks-test-sources/default/src/main/java/checks/security/CookieHttpOnlyCheck.java index f17c5c77451..68ae4ec175a 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/CookieHttpOnlyCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/CookieHttpOnlyCheck.java @@ -23,7 +23,8 @@ class CookieHttpOnlyCheck { void servletCookie(boolean param, Cookie c0) { - c0.setHttpOnly(false); // Noncompliant [[sc=19;ec=26]] {{Make sure creating this cookie without the "HttpOnly" flag is safe.}} + c0.setHttpOnly(false); // Noncompliant {{Make sure creating this cookie without the "HttpOnly" flag is safe.}} +// ^^^^^^^ field6.setHttpOnly(false); // Noncompliant Cookie c1 = new Cookie("name", "value"); @@ -34,7 +35,8 @@ void servletCookie(boolean param, Cookie c0) { c1.setHttpOnly(true); } - Cookie c2 = new Cookie("name", "value"); // Noncompliant [[sc=21;ec=27]] + Cookie c2 = new Cookie("name", "value"); // Noncompliant +// ^^^^^^ Cookie c3 = new Cookie("name", "value"); c3.setHttpOnly(false); // Noncompliant @@ -56,7 +58,7 @@ void servletCookie(boolean param, Cookie c0) { c9.setHttpOnly(false); // Noncompliant Cookie c10; - c10 = new Cookie("name", "value"); // Noncompliant + c10 = new Cookie("name", "value"); // Noncompliant Cookie c11; c11 = new Cookie("name", "value"); @@ -71,7 +73,8 @@ void servletCookie(boolean param, Cookie c0) { } Cookie getC1() { - return new Cookie("name", "value"); // Noncompliant [[sc=16;ec=22]] + return new Cookie("name", "value"); // Noncompliant +// ^^^^^^ } Cookie returnHttpCookie(HttpServletResponse response) { @@ -287,7 +290,8 @@ class JakartaCookieHttpOnlyCheckCookieACookieHttpOnlyCheck { jakarta.ws.rs.core.Cookie field3 = new jakarta.ws.rs.core.Cookie("name", "value"); // FN jakarta.servlet.http.Cookie field6; void servletCookie(boolean param, jakarta.servlet.http.Cookie c0) { - c0.setHttpOnly(false); // Noncompliant [[sc=19;ec=26]] {{Make sure creating this cookie without the "HttpOnly" flag is safe.}} + c0.setHttpOnly(false); // Noncompliant {{Make sure creating this cookie without the "HttpOnly" flag is safe.}} +// ^^^^^^^ field6.setHttpOnly(false); // Noncompliant jakarta.servlet.http.Cookie c1 = new jakarta.servlet.http.Cookie("name", "value"); @@ -297,7 +301,8 @@ void servletCookie(boolean param, jakarta.servlet.http.Cookie c0) { c1.setHttpOnly(true); } - jakarta.servlet.http.Cookie c2 = new jakarta.servlet.http.Cookie("name", "value"); // Noncompliant [[sc=42;ec=69]] + jakarta.servlet.http.Cookie c2 = new jakarta.servlet.http.Cookie("name", "value"); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ c1.setHttpOnly(false); // Noncompliant @@ -319,7 +324,8 @@ void servletCookie(boolean param, jakarta.servlet.http.Cookie c0) { } jakarta.servlet.http.Cookie getC1() { - return new jakarta.servlet.http.Cookie("name", "value"); // Noncompliant [[sc=16;ec=43]] + return new jakarta.servlet.http.Cookie("name", "value"); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ } jakarta.servlet.http.Cookie returnHttpCookie(jakarta.servlet.http.HttpServletResponse response) { diff --git a/java-checks-test-sources/default/src/main/java/checks/security/CryptographicKeySizeCheck.java b/java-checks-test-sources/default/src/main/java/checks/security/CryptographicKeySizeCheck.java index aa99f672ea4..9090b5547c3 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/CryptographicKeySizeCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/CryptographicKeySizeCheck.java @@ -11,7 +11,8 @@ class CryptographicKeySizeCheckRSA { public void key_variable() throws NoSuchAlgorithmException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); - keyGen.initialize(1024); // Noncompliant [[sc=5;ec=28]] {{Use a key length of at least 2048 bits for RSA cipher algorithm.}} + keyGen.initialize(1024); // Noncompliant {{Use a key length of at least 2048 bits for RSA cipher algorithm.}} +// ^^^^^^^^^^^^^^^^^^^^^^^ } public void key_variable_assign_after_decl() throws NoSuchAlgorithmException { @@ -114,7 +115,8 @@ interface CryptographicKeySizeCheckI { class CryptographicKeySizeCheckDH { public void key_variable_DH() throws NoSuchAlgorithmException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH"); - keyGen.initialize(1024); // Noncompliant [[sc=5;ec=28]] {{Use a key length of at least 2048 bits for DH cipher algorithm.}} + keyGen.initialize(1024); // Noncompliant {{Use a key length of at least 2048 bits for DH cipher algorithm.}} +// ^^^^^^^^^^^^^^^^^^^^^^^ } public void key_variable_compliant_DH() throws NoSuchAlgorithmException { @@ -124,7 +126,8 @@ public void key_variable_compliant_DH() throws NoSuchAlgorithmException { public void key_variable() throws NoSuchAlgorithmException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DiffieHellman"); - keyGen.initialize(1024); // Noncompliant [[sc=5;ec=28]] {{Use a key length of at least 2048 bits for DiffieHellman cipher algorithm.}} + keyGen.initialize(1024); // Noncompliant {{Use a key length of at least 2048 bits for DiffieHellman cipher algorithm.}} +// ^^^^^^^^^^^^^^^^^^^^^^^ } public void key_variable_compliant() throws NoSuchAlgorithmException { @@ -136,7 +139,8 @@ public void key_variable_compliant() throws NoSuchAlgorithmException { class CryptographicKeySizeCheckDSA { public void key_variable_DSA() throws NoSuchAlgorithmException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA"); - keyGen.initialize(1024, new SecureRandom()); // Noncompliant [[sc=5;ec=48]] {{Use a key length of at least 2048 bits for DSA cipher algorithm.}} + keyGen.initialize(1024, new SecureRandom()); // Noncompliant {{Use a key length of at least 2048 bits for DSA cipher algorithm.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } public void key_variable_compliant_DSA() throws NoSuchAlgorithmException { @@ -148,7 +152,8 @@ public void key_variable_compliant_DSA() throws NoSuchAlgorithmException { class CryptographicKeySizeCheckAES { public void key_variable() throws NoSuchAlgorithmException { KeyGenerator keyGen1 = KeyGenerator.getInstance("AES"); - keyGen1.init(64); // Noncompliant [[sc=5;ec=21]] {{Use a key length of at least 128 bits for AES cipher algorithm.}} + keyGen1.init(64); // Noncompliant {{Use a key length of at least 128 bits for AES cipher algorithm.}} +// ^^^^^^^^^^^^^^^^ } public void key_variable_compliant() throws NoSuchAlgorithmException { @@ -160,7 +165,8 @@ public void key_variable_compliant() throws NoSuchAlgorithmException { class CryptographicKeySizeCheckEC { public void key_EC() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException { KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("EC"); - ECGenParameterSpec ecSpec1 = new ECGenParameterSpec("secp112r1"); // Noncompliant [[sc=34;ec=69]] {{Use a key length of at least 224 bits for EC cipher algorithm.}} + ECGenParameterSpec ecSpec1 = new ECGenParameterSpec("secp112r1"); // Noncompliant {{Use a key length of at least 224 bits for EC cipher algorithm.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ keyPairGen.initialize(ecSpec1); ECGenParameterSpec ecSpec2 = new ECGenParameterSpec("secp112r2"); // Noncompliant keyPairGen.initialize(ecSpec2); diff --git a/java-checks-test-sources/default/src/main/java/checks/security/DataHashingCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/security/DataHashingCheckSample.java index aad6cae6266..38d847125e6 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/DataHashingCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/DataHashingCheckSample.java @@ -26,10 +26,12 @@ class HashMethodsCheck { void myMethod(String algorithm, Provider provider, Properties props) throws NoSuchAlgorithmException, NoSuchProviderException { MessageDigest md = null; - md = MessageDigest.getInstance("MD2"); // Noncompliant [[sc=24;ec=35]] {{Make sure this weak hash algorithm is not used in a sensitive context here.}} + md = MessageDigest.getInstance("MD2"); // Noncompliant {{Make sure this weak hash algorithm is not used in a sensitive context here.}} +// ^^^^^^^^^^^ md = MessageDigest.getInstance("MD4"); // Noncompliant {{Make sure this weak hash algorithm is not used in a sensitive context here.}} md = MessageDigest.getInstance("MD6"); // Noncompliant {{Make sure this weak hash algorithm is not used in a sensitive context here.}} - md = MessageDigest.getInstance("MD5"); // Noncompliant [[sc=24;ec=35]] {{Make sure this weak hash algorithm is not used in a sensitive context here.}} + md = MessageDigest.getInstance("MD5"); // Noncompliant {{Make sure this weak hash algorithm is not used in a sensitive context here.}} +// ^^^^^^^^^^^ md = MessageDigest.getInstance("HAVAL-128"); // Noncompliant {{Make sure this weak hash algorithm is not used in a sensitive context here.}} md = MessageDigest.getInstance("HMAC-MD5"); // Noncompliant {{Make sure this weak hash algorithm is not used in a sensitive context here.}} md = MessageDigest.getInstance("RIPEMD"); // Noncompliant {{Make sure this weak hash algorithm is not used in a sensitive context here.}} diff --git a/java-checks-test-sources/default/src/main/java/checks/security/DebugFeatureEnabledCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/security/DebugFeatureEnabledCheckSample.java index 1e84268b6b6..17a5dadde91 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/DebugFeatureEnabledCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/DebugFeatureEnabledCheckSample.java @@ -19,7 +19,7 @@ private void f(Throwable e, MyException e1) { } private void androidWebView(WebViewFactoryProvider.Statics statics) { - WebView.setWebContentsDebuggingEnabled(true); // Noncompliant [[sc=13;ec=43] {{Make sure this debug feature is deactivated before delivering the code in production.}} + WebView.setWebContentsDebuggingEnabled(true); // Noncompliant {{Make sure this debug feature is deactivated before delivering the code in production.}} WebView.setWebContentsDebuggingEnabled(false); statics.setWebContentsDebuggingEnabled(true); // Noncompliant statics.setWebContentsDebuggingEnabled(false); @@ -64,13 +64,13 @@ void fun() { } void foo(WebSecurity web, boolean cond){ - web.debug(true); // Noncompliant [sc=9;ec=14] {{Make sure this debug feature is deactivated before delivering the code in production.}} + web.debug(true); // Noncompliant {{Make sure this debug feature is deactivated before delivering the code in production.}} web.debug(false); web.debug(cond); } public WebSecurityCustomizer debugCustomizer() { - return (web) -> web.debug(true); // Noncompliant [sc=25;ec=30] {{Make sure this debug feature is deactivated before delivering the code in production.}} + return (web) -> web.debug(true); // Noncompliant {{Make sure this debug feature is deactivated before delivering the code in production.}} } public WebSecurityCustomizer nonDebugCustomizer() { diff --git a/java-checks-test-sources/default/src/main/java/checks/security/DisableAutoEscapingCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/security/DisableAutoEscapingCheckSample.java index 1cace899887..2c179bea2f4 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/DisableAutoEscapingCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/DisableAutoEscapingCheckSample.java @@ -22,7 +22,8 @@ public class DisableAutoEscapingCheckSample { */ public void jMustache(boolean arg) { Mustache.compiler() - .escapeHTML(false) // Noncompliant [[sc=19;ec=24]] {{Make sure disabling auto-escaping feature is safe here.}} + .escapeHTML(false) // Noncompliant {{Make sure disabling auto-escaping feature is safe here.}} +// ^^^^^ .compile(template) .execute(context); @@ -37,7 +38,8 @@ public void jMustache(boolean arg) { .execute(context); Mustache.compiler() - .withEscaper(Escapers.NONE) // Noncompliant [[sc=20;ec=33]] {{Make sure disabling auto-escaping feature is safe here.}} + .withEscaper(Escapers.NONE) // Noncompliant {{Make sure disabling auto-escaping feature is safe here.}} +// ^^^^^^^^^^^^^ .compile(template) .execute(context); @@ -117,7 +119,8 @@ public void jMustache(boolean arg) { * https://freemarker.apache.org/ */ public void freemarker(freemarker.template.Configuration config) { - config.setAutoEscapingPolicy(DISABLE_AUTO_ESCAPING_POLICY); // Noncompliant [[sc=34;ec=62]] {{Make sure disabling auto-escaping feature is safe here.}} + config.setAutoEscapingPolicy(DISABLE_AUTO_ESCAPING_POLICY); // Noncompliant {{Make sure disabling auto-escaping feature is safe here.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ config.setAutoEscapingPolicy(freemarker.template.Configuration.DISABLE_AUTO_ESCAPING_POLICY); // Noncompliant config.setAutoEscapingPolicy(MyConstant.DISABLE_AUTO_ESCAPING_POLICY); // Compliant, user defined constant config.setAutoEscapingPolicy(ENABLE_IF_SUPPORTED_AUTO_ESCAPING_POLICY); // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/security/DisclosingTechnologyFingerprints.java b/java-checks-test-sources/default/src/main/java/checks/security/DisclosingTechnologyFingerprints.java index dbf82a0cf09..bfc683c2e43 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/DisclosingTechnologyFingerprints.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/DisclosingTechnologyFingerprints.java @@ -17,29 +17,32 @@ public class DisclosingTechnologyFingerprints { public String noncompliants5689httpservletresponse(HttpServletResponse response) { - response.addHeader("x-powered-by", "myproduct"); // Noncompliant [[sc=5;ec=52]] {{Make sure disclosing version information of this web technology is safe here.}} - response.addHeader("Server", "apache"); // Noncompliant [[sc=5;ec=43]] {{Make sure disclosing version information of this web technology is safe here.}} + response.addHeader("x-powered-by", "myproduct"); // Noncompliant {{Make sure disclosing version information of this web technology is safe here.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + response.addHeader("Server", "apache"); // Noncompliant {{Make sure disclosing version information of this web technology is safe here.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ return "thymeleaf/welcome"; } public ResponseEntity noncompliants5689responseentity() { HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.set("x-powered-by", "myproduct"); // Noncompliant [[sc=5;ec=53]] {{Make sure disclosing version information of this web technology is safe here.}} + responseHeaders.set("x-powered-by", "myproduct"); // Noncompliant {{Make sure disclosing version information of this web technology is safe here.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ return new ResponseEntity("Hello World", responseHeaders, HttpStatus.CREATED); } public ResponseEntity noncompliants5689responseentitybuilder() throws URISyntaxException { ResponseEntity.BodyBuilder location = ResponseEntity.created(new URI("location")); - return location.header("server", "apache").body("Hello World"); // Noncompliant + return location.header("server", "apache").body("Hello World"); // Noncompliant } public ResponseEntity noncompliants5689responseentitybuilderhttpheaders() { HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.set("x-powered-by", "myproduct"); // Noncompliant - responseHeaders.add("Server", "myproduct"); // Noncompliant + responseHeaders.set("x-powered-by", "myproduct"); // Noncompliant + responseHeaders.add("Server", "myproduct"); // Noncompliant return ResponseEntity.ok().headers(responseHeaders).body("Hello World"); } diff --git a/java-checks-test-sources/default/src/main/java/checks/security/EmptyDatabasePasswordCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/security/EmptyDatabasePasswordCheckSample.java index 59a48586989..f0de303a3d3 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/EmptyDatabasePasswordCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/EmptyDatabasePasswordCheckSample.java @@ -10,23 +10,29 @@ class EmptyDatabasePasswordCheckSample { void foo(Properties connectionProps, String unknown) throws SQLException { - DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "AppLogin", ""); // Noncompliant [[sc=5;ec=86]] {{Add password protection to this database.}} + DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "AppLogin", ""); // Noncompliant {{Add password protection to this database.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "AppLogin", "Foo"); String pwd = ""; - DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "AppLogin", pwd); // Noncompliant [[secondary=-1]] +// ^^> + DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "AppLogin", pwd); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ String pwd2 = "foo"; DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "AppLogin", pwd2); String pRef = ""; +// ^^> String pwd3 = pRef; - - DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "AppLogin", pwd3); // Noncompliant [[secondary=-3,-2]] +// ^^^^> + DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "AppLogin", pwd3); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "AppLogin", getPassword()); - DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "AppLogin", EMPTY_PASSWORD); // Noncompliant [[sc=5;ec=98]] + DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "AppLogin", EMPTY_PASSWORD); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "AppLogin", NON_EMPTY_PASSWORD); DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "AppLogin", unknown); diff --git a/java-checks-test-sources/default/src/main/java/checks/security/EncryptionAlgorithmCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/security/EncryptionAlgorithmCheckSample.java index 199e99d164e..3a74827fb4d 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/EncryptionAlgorithmCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/EncryptionAlgorithmCheckSample.java @@ -9,6 +9,7 @@ abstract class EncryptionAlgorithmCheckSample { static final String RSA = "RSA"; static final String NO_PADDING = "/NONE/NoPadding"; static final String RSA_NO_PADDING = RSA + NO_PADDING; +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^> public void foo(java.util.Properties props) { /* @@ -20,8 +21,13 @@ public void foo(java.util.Properties props) { */ try { + + Cipher.getInstance(RSA_NO_PADDING); // Noncompliant +// ^^^^^^^^^^^^^^ + // First case - Cipher.getInstance("AES"); // Noncompliant [[sc=26;ec=31]] {{Use a secure padding scheme.}} + Cipher.getInstance("AES"); // Noncompliant {{Use a secure padding scheme.}} +// ^^^^^ Cipher.getInstance("AES/ECB/NoPadding"); // Noncompliant {{Use a secure cipher mode.}} Cipher.getInstance("AES" + "/ECB/NoPadding"); // Noncompliant @@ -60,14 +66,19 @@ public void foo(java.util.Properties props) { Cipher.getInstance(null); // Compliant Cipher.getInstance(""); // Noncompliant String algo = props.getProperty("myAlgo", "AES/ECB/PKCS5Padding"); - Cipher.getInstance(algo); // Noncompliant [[sc=26;ec=30;secondary=62]] +// ^^^^^^^^^^^^^^^^^^^^^^> + Cipher.getInstance(algo); // Noncompliant +// ^^^^ String s = "RSA/NONE/NoPadding"; // Compliant - Cipher.getInstance(s); // Noncompliant [[sc=26;ec=27;secondary=64]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^> + Cipher.getInstance(s); // Noncompliant +// ^ String sPlus = "RSA" + "/NONE/NoPadding"; // Compliant - Cipher.getInstance(sPlus); // Noncompliant [[sc=26;ec=31;secondary=67]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^> + Cipher.getInstance(sPlus); // Noncompliant +// ^^^^^ - Cipher.getInstance(RSA_NO_PADDING); // Noncompliant [[sc=26;ec=40;secondary=11]] Cipher.getInstance(separator); // Compliant, can not resolve the declaration, for coverage @@ -78,7 +89,9 @@ public void foo(java.util.Properties props) { Cipher.getInstance("DES/CBC/NOPADDING"); // Compliant Cipher.getInstance("RSA/NONE/OAEPWITHSHA-1AndMGF1Padding"); // Compliant String algoUpperCase = props.getProperty("myAlgo", "AES/ECB/PKCS5PADDING"); - Cipher.getInstance(algoUpperCase); // Noncompliant [[sc=26;ec=39;secondary=80]] +// ^^^^^^^^^^^^^^^^^^^^^^> + Cipher.getInstance(algoUpperCase); // Noncompliant +// ^^^^^^^^^^^^^ } catch (Exception e) { } diff --git a/java-checks-test-sources/default/src/main/java/checks/security/ExcessiveContentRequestCheck/ExcessiveContentRequestCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/security/ExcessiveContentRequestCheck/ExcessiveContentRequestCheckSample.java index bae07183e18..3677d40e9bb 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/ExcessiveContentRequestCheck/ExcessiveContentRequestCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/ExcessiveContentRequestCheck/ExcessiveContentRequestCheckSample.java @@ -17,7 +17,8 @@ public class ExcessiveContentRequestCheckSample { void springCommonsMultipartResolver() { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); - multipartResolver.setMaxUploadSize(8388609); // Noncompliant [[sc=5;ec=48]] {{The content length limit of 8388609 bytes is greater than the defined limit of 8388608; make sure it is safe here.}} + multipartResolver.setMaxUploadSize(8388609); // Noncompliant {{The content length limit of 8388609 bytes is greater than the defined limit of 8388608; make sure it is safe here.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ multipartResolver.setMaxUploadSize(8388609l); // Noncompliant multipartResolver.setMaxUploadSize(8388609L); // Noncompliant multipartResolver.setMaxUploadSize(10); // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/security/ExcessiveContentRequestCheck/ExcessiveContentRequestCheck_max8000000.java b/java-checks-test-sources/default/src/main/java/checks/security/ExcessiveContentRequestCheck/ExcessiveContentRequestCheck_max8000000.java index d0a5e4e3d63..7bbbdcc021c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/ExcessiveContentRequestCheck/ExcessiveContentRequestCheck_max8000000.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/ExcessiveContentRequestCheck/ExcessiveContentRequestCheck_max8000000.java @@ -36,7 +36,8 @@ void setSizeViaDataSizeOf(MultipartProperties multipartProperties) { void springCommonsMultipartResolver() { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); - multipartResolver.setMaxUploadSize(8000001); // Noncompliant [[sc=5;ec=48]] {{The content length limit of 8000001 bytes is greater than the defined limit of 8000000; make sure it is safe here.}} + multipartResolver.setMaxUploadSize(8000001); // Noncompliant {{The content length limit of 8000001 bytes is greater than the defined limit of 8000000; make sure it is safe here.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ multipartResolver.setMaxUploadSize(8000000); // Compliant } @@ -47,7 +48,8 @@ void springMultipartConfigFactory() { factory.setMaxFileSize(8000000); // Compliant // The prefix used is the binary prefix (power of two). - factory.setMaxFileSize("8MB"); // Noncompliant [[sc=5;ec=34]] {{The content length limit of 8388608 bytes is greater than the defined limit of 8000000; make sure it is safe here.}} + factory.setMaxFileSize("8MB"); // Noncompliant {{The content length limit of 8388608 bytes is greater than the defined limit of 8000000; make sure it is safe here.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ factory.setMaxFileSize("8000KB"); // Noncompliant // 7900KB = 8089600 bytes factory.setMaxFileSize("7900KB"); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/security/ExcessiveContentRequestCheck/ExcessiveContentRequestCheck_sizeNotSet.java b/java-checks-test-sources/default/src/main/java/checks/security/ExcessiveContentRequestCheck/ExcessiveContentRequestCheck_sizeNotSet.java index ac753f74fd2..cf0a9e8302c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/ExcessiveContentRequestCheck/ExcessiveContentRequestCheck_sizeNotSet.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/ExcessiveContentRequestCheck/ExcessiveContentRequestCheck_sizeNotSet.java @@ -6,12 +6,14 @@ public class ExcessiveContentRequestCheck_sizeNotSet { public static CommonsMultipartResolver getCommonsMultipartResolver() { - CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); // Noncompliant [[sc=50;ec=80]] {{Make sure not setting any maximum content length limit is safe here.}} + CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); // Noncompliant {{Make sure not setting any maximum content length limit is safe here.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ return multipartResolver; } public static MultipartConfigFactory getMultipartConfigElement() { - MultipartConfigFactory factory = new MultipartConfigFactory(); // Noncompliant [[sc=38;ec=66]] {{Make sure not setting any maximum content length limit is safe here.}} + MultipartConfigFactory factory = new MultipartConfigFactory(); // Noncompliant {{Make sure not setting any maximum content length limit is safe here.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ return factory; } } diff --git a/java-checks-test-sources/default/src/main/java/checks/security/FilePermissionsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/security/FilePermissionsCheckSample.java index 23988be2087..1fd93562458 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/FilePermissionsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/FilePermissionsCheckSample.java @@ -38,7 +38,8 @@ public void setPermissionsFromString(Path filePath, String permissions) throws E public void setOthersPermissionsHardCoded(Path filePath) throws Exception { Files.setPosixFilePermissions(filePath, PosixFilePermissions.fromString("rwxrwx---")); // Compliant - Files.setPosixFilePermissions(filePath, PosixFilePermissions.fromString("rwxrwxr--")); // Noncompliant [[sc=77;ec=88]] {{Make sure this permission is safe.}} + Files.setPosixFilePermissions(filePath, PosixFilePermissions.fromString("rwxrwxr--")); // Noncompliant {{Make sure this permission is safe.}} +// ^^^^^^^^^^^ Files.setPosixFilePermissions(filePath, PosixFilePermissions.fromString("rwxrwx-w-")); // Noncompliant Files.setPosixFilePermissions(filePath, PosixFilePermissions.fromString("rwxrwx--x")); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/security/JWTWithStrongCipherCheck/JWTWithStrongCipherCheckAuth0Test.java b/java-checks-test-sources/default/src/main/java/checks/security/JWTWithStrongCipherCheck/JWTWithStrongCipherCheckAuth0Test.java index 8a86889ff8a..753c9230361 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/JWTWithStrongCipherCheck/JWTWithStrongCipherCheckAuth0Test.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/JWTWithStrongCipherCheck/JWTWithStrongCipherCheckAuth0Test.java @@ -22,7 +22,8 @@ public class JWTWithStrongCipherCheckAuth0Test { private static final String LOGIN = "login"; public void auth0JWT() { - JWTVerifier nonCompliantVerifier = JWT.require(Algorithm.none()) // Noncompliant [[sc=52;ec=68]] {{Use only strong cipher algorithms when verifying the signature of this JWT.}} + JWTVerifier nonCompliantVerifier = JWT.require(Algorithm.none()) // Noncompliant {{Use only strong cipher algorithms when verifying the signature of this JWT.}} +// ^^^^^^^^^^^^^^^^ .withSubject(LOGIN) .build(); @@ -46,7 +47,8 @@ public void auth0JWT() { .withSubject(LOGIN) .withExpiresAt(addMinutes(new Date(), 20)) .withIssuedAt(new Date()) - .sign(Algorithm.none()); // Noncompliant [[sc=13;ec=29]] {{Use only strong cipher algorithms when signing this JWT.}} + .sign(Algorithm.none()); // Noncompliant {{Use only strong cipher algorithms when signing this JWT.}} +// ^^^^^^^^^^^^^^^^ String tokenSigned = JWT.create() .withSubject(LOGIN) diff --git a/java-checks-test-sources/default/src/main/java/checks/security/JWTWithStrongCipherCheck/JWTWithStrongCipherCheckJwtkTest.java b/java-checks-test-sources/default/src/main/java/checks/security/JWTWithStrongCipherCheck/JWTWithStrongCipherCheckJwtkTest.java index d1d27f544ab..eaaede0e6fd 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/JWTWithStrongCipherCheck/JWTWithStrongCipherCheckJwtkTest.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/JWTWithStrongCipherCheck/JWTWithStrongCipherCheckJwtkTest.java @@ -31,11 +31,13 @@ public void jwtkJWT() { String tokenSigned = getTokenSigned(); // PARSE WITHOUT SIGNATURE TESTCASES - Object body1 = Jwts.parser().parse(tokenNotSigned).getBody(); // Noncompliant [[sc=34;ec=39]] {{The JWT signature (JWS) should be verified before using this token.}} + Object body1 = Jwts.parser().parse(tokenNotSigned).getBody(); // Noncompliant {{The JWT signature (JWS) should be verified before using this token.}} +// ^^^^^ Object body2 = Jwts.parser().parse(tokenSigned).getBody(); // Noncompliant // Despite the fact that we set a signing key, parse is subject to the none algorithm. See rule description. - Object body3 = Jwts.parser().setSigningKey(SECRET_KEY).parse(tokenNotSigned).getBody(); // Noncompliant [[sc=60;ec=65]] {{The JWT signature (JWS) should be verified before using this token.}} + Object body3 = Jwts.parser().setSigningKey(SECRET_KEY).parse(tokenNotSigned).getBody(); // Noncompliant {{The JWT signature (JWS) should be verified before using this token.}} +// ^^^^^ Object body4 = Jwts.parser().setSigningKey(SECRET_KEY).parse(tokenSigned).getBody(); // Noncompliant // parseClaimsJws WITH SIGNATURE TESTCASES @@ -74,7 +76,8 @@ private static String getTokenNotSigned() { .setSubject(LOGIN) .setIssuedAt(new Date()) .setExpiration(addMinutes(new Date(), 20)) - .compact(); // Noncompliant [[sc=8;ec=15]] {{Sign this token using a strong cipher algorithm.}} + .compact(); // Noncompliant {{Sign this token using a strong cipher algorithm.}} +// ^^^^^^^ } private String getTokenSignedWithNone() throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException { diff --git a/java-checks-test-sources/default/src/main/java/checks/security/LogConfigurationCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/security/LogConfigurationCheckSample.java index 82aec14eb63..eff591d0895 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/LogConfigurationCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/LogConfigurationCheckSample.java @@ -31,11 +31,13 @@ class Log4J2 { Filter filter; // Questionable: creating a new custom configuration - abstract class CustomConfigFactory extends ConfigurationFactory { } // Noncompliant [[sc=46;ec=66]] {{Make sure that this logger's configuration is safe.}} + abstract class CustomConfigFactory extends ConfigurationFactory { } // Noncompliant {{Make sure that this logger's configuration is safe.}} +// ^^^^^^^^^^^^^^^^^^^^ void fun() throws Exception { // Questionable: creating a new custom configuration - ConfigurationBuilderFactory.newConfigurationBuilder(); // Noncompliant [[sc=5;ec=58]] {{Make sure that this logger's configuration is safe.}} + ConfigurationBuilderFactory.newConfigurationBuilder(); // Noncompliant {{Make sure that this logger's configuration is safe.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // Questionable: setting loggers level can result in writing sensitive information in production Configurator.setAllLevels("com.example", Level.DEBUG); // Noncompliant @@ -44,16 +46,16 @@ void fun() throws Exception { Configurator.setRootLevel(Level.DEBUG); // Noncompliant // Questionable: this modifies the configuration - config.addAppender(appender); // Noncompliant + config.addAppender(appender); // Noncompliant - context.setConfigLocation(uri); // Noncompliant + context.setConfigLocation(uri); // Noncompliant // Questionable: Load the configuration from a stream or file new ConfigurationSource(stream); // Noncompliant - new ConfigurationSource(stream, file);// Noncompliant - new ConfigurationSource(stream, url);// Noncompliant - ConfigurationSource.fromResource("source", loader);// Noncompliant - ConfigurationSource.fromUri(uri);// Noncompliant + new ConfigurationSource(stream, file); // Noncompliant + new ConfigurationSource(stream, url); // Noncompliant + ConfigurationSource.fromResource("source", loader); // Noncompliant + ConfigurationSource.fromUri(uri); // Noncompliant LoggerConfig loggerConfig = config.getRootLogger(); loggerConfig.addAppender(appender, level, filter); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/security/PasswordEncoder.java b/java-checks-test-sources/default/src/main/java/checks/security/PasswordEncoder.java index 8ba750bf484..1bd935435ba 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/PasswordEncoder.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/PasswordEncoder.java @@ -38,7 +38,7 @@ public void configureGlobal(AuthenticationManagerBuilder auth, DataSource dataSo @Autowired public void jdbcAuthentication(AuthenticationManagerBuilder auth, DataSource dataSource, UserDetailsService userDetailsService) throws Exception { - auth.jdbcAuthentication() // Noncompliant {{Don't use the default "PasswordEncoder" relying on plain-text.}} + auth.jdbcAuthentication() // Noncompliant {{Don't use the default "PasswordEncoder" relying on plain-text.}} .dataSource(dataSource) .usersByUsernameQuery("SELECT * FROM users WHERE username = ?"); } @@ -53,7 +53,7 @@ public void jdbcAuthenticationCompliant(AuthenticationManagerBuilder auth, DataS @Autowired public void userDetailsService(AuthenticationManagerBuilder auth, DataSource dataSource, UserDetailsService userDetailsService) throws Exception { - auth.userDetailsService(userDetailsService); // Noncompliant {Don't use the default "PasswordEncoder" relying on plain-text.}} + auth.userDetailsService(userDetailsService); // Noncompliant } @Autowired diff --git a/java-checks-test-sources/default/src/main/java/checks/security/PubliclyWritableDirectories.java b/java-checks-test-sources/default/src/main/java/checks/security/PubliclyWritableDirectories.java index d87c5d91b14..e942c7a5e0b 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/PubliclyWritableDirectories.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/PubliclyWritableDirectories.java @@ -19,19 +19,23 @@ public class PubliclyWritableDirectories { public String noncompliant() throws IOException { - File f1 = File.createTempFile("prefix", "suffix"); // Noncompliant [[sc=15;ec=54]] {{Make sure publicly writable directories are used safely here.}} + File f1 = File.createTempFile("prefix", "suffix"); // Noncompliant {{Make sure publicly writable directories are used safely here.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ f1.deleteOnExit(); - File f2 = new File("/var/tmp"); // Noncompliant [[sc=15;ec=35]] + File f2 = new File("/var/tmp"); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^ File f3 = File.createTempFile("prefix", "suffix", f2); // Already reported in line 25 f3.deleteOnExit(); - File f4 = File.createTempFile("prefix", "suffix", new File("/tmp")); // Noncompliant [[sc=55;ec=71]] + File f4 = File.createTempFile("prefix", "suffix", new File("/tmp")); // Noncompliant +// ^^^^^^^^^^^^^^^^ f4.deleteOnExit(); File f5 = File.createTempFile("prefix", "suffix", new File(PATH_NAME)); // Noncompliant f5.deleteOnExit(); // Files library: https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html - Path p1 = Files.createTempDirectory("prefix"); // Noncompliant [[sc=15;ec=50]] {{Make sure publicly writable directories are used safely here.}} + Path p1 = Files.createTempDirectory("prefix"); // Noncompliant {{Make sure publicly writable directories are used safely here.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ p1.toFile().deleteOnExit(); Path p2 = Files.createTempFile("prefix", "suffix"); // Noncompliant {{Make sure publicly writable directories are used safely here.}} p2.toFile().deleteOnExit(); @@ -61,13 +65,15 @@ public String noncompliant() throws IOException { // Get from environment variable Map env = System.getenv(); - String env1 = env.get("TMP"); // Noncompliant [[sc=19;ec=33]] {{Make sure publicly writable directories are used safely here.}} - String env2 = env.get("TMPDIR"); // Noncompliant [[sc=19;ec=36]] {{Make sure publicly writable directories are used safely here.}} + String env1 = env.get("TMP"); // Noncompliant {{Make sure publicly writable directories are used safely here.}} +// ^^^^^^^^^^^^^^ + String env2 = env.get("TMPDIR"); // Noncompliant {{Make sure publicly writable directories are used safely here.}} +// ^^^^^^^^^^^^^^^^^ File f6 = new File(env1); File f7 = new File(env2); - File f8 = new File("/tmp/my.txt"); // Noncompliant + File f8 = new File("/tmp/my.txt"); // Noncompliant File f88 = new File("/var/tmp/my.txt"); // Noncompliant File f888 = new File("/usr/tmp/my.txt"); // Noncompliant File f8888 = new File("/dev/shm/my.txt"); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/security/SecureCookieCheckJakarta.java b/java-checks-test-sources/default/src/main/java/checks/security/SecureCookieCheckJakarta.java index 8ac1b72d466..a31be60b58f 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/SecureCookieCheckJakarta.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/SecureCookieCheckJakarta.java @@ -25,7 +25,8 @@ Cookie servletCookie( Cookie secondParam, Cookie thirdParam, boolean param) { - firstParam.setSecure(false); // Noncompliant [[sc=25;ec=32]] {{Make sure creating this cookie without the "secure" flag is safe here.}} + firstParam.setSecure(false); // Noncompliant {{Make sure creating this cookie without the "secure" flag is safe here.}} +// ^^^^^^^ secondParam.setSecure(true); field5.setSecure(false); // Noncompliant @@ -34,10 +35,11 @@ Cookie servletCookie( Cookie cookie = new Cookie("name", "value"); cookie.setSecure(true); - Cookie cookie2 = new Cookie("name", "value"); // Noncompliant [[sc=26;ec=32]] {{Make sure creating this cookie without the "secure" flag is safe here.}} + Cookie cookie2 = new Cookie("name", "value"); // Noncompliant {{Make sure creating this cookie without the "secure" flag is safe here.}} +// ^^^^^^ Cookie cookie3 = new Cookie("name", "value"); - cookie3.setSecure(false); // Noncompliant {{Make sure creating this cookie without the "secure" flag is safe here.}} + cookie3.setSecure(false); // Noncompliant {{Make sure creating this cookie without the "secure" flag is safe here.}} Cookie cookie5 = new Cookie("name", "value"); cookie5.setSecure(FALSE_CONSTANT); // Noncompliant @@ -51,7 +53,7 @@ Cookie servletCookie( Cookie c7 = new Cookie("name", "value"); boolean b = false; - c7.setSecure(b); // Noncompliant [[secondary=-1]] + c7.setSecure(b); // Noncompliant Cookie c8 = new Cookie("name", "value"); c8.setSecure(param); @@ -63,7 +65,8 @@ Cookie servletCookie( c10.setSecure(true); Object c12; - c12 = new Cookie("name", "value"); // Noncompliant [[sc=15;ec=21]] {{Make sure creating this cookie without the "secure" flag is safe here.}} + c12 = new Cookie("name", "value"); // Noncompliant {{Make sure creating this cookie without the "secure" flag is safe here.}} +// ^^^^^^ Cookie c13 = new Cookie("name", "value"); boolean value = false; @@ -83,12 +86,12 @@ NewCookie jaxRsNewCookie(jakarta.ws.rs.core.Cookie cookie) { NewCookie c7 = new NewCookie("1", "2", "3", "4", "5", 6, false, true); // Noncompliant NewCookie c8 = new NewCookie("1", "2", "3", "4", "5", 6, true, true); - NewCookie c9 = new NewCookie("1", "2", "3", "4", 5, "6", 7, new Date(), false, true); // Noncompliant + NewCookie c9 = new NewCookie("1", "2", "3", "4", 5, "6", 7, new Date(), false, true); // Noncompliant NewCookie c10 = new NewCookie("1", "2", "3", "4", 5, "6", 7, new Date(), true, false); NewCookie c11 = new NewCookie("1", "2", "3", "4", "5", 6, true); NewCookie c12 = new NewCookie("1", "2", "3", "4", "5", 6, false); // Noncompliant - NewCookie c13 = new NewCookie("1", "2", "3", "4", "5", 6, false, false); // Noncompliant + NewCookie c13 = new NewCookie("1", "2", "3", "4", "5", 6, false, false); // Noncompliant NewCookie c14 = new NewCookie("1", "2", "3", "4", "5", 6, true, false); return new NewCookie(cookie); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/security/SecureCookieCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/security/SecureCookieCheckSample.java index e9d760eda7e..9191d438124 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/SecureCookieCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/SecureCookieCheckSample.java @@ -34,7 +34,8 @@ Cookie servletCookie( Cookie secondParam, Cookie thirdParam, boolean param) { - firstParam.setSecure(false); // Noncompliant [[sc=25;ec=32]] {{Make sure creating this cookie without the "secure" flag is safe here.}} + firstParam.setSecure(false); // Noncompliant {{Make sure creating this cookie without the "secure" flag is safe here.}} +// ^^^^^^^ secondParam.setSecure(true); field5.setSecure(false); // Noncompliant @@ -43,10 +44,11 @@ Cookie servletCookie( Cookie cookie = new Cookie("name", "value"); cookie.setSecure(true); - Cookie cookie2 = new Cookie("name", "value"); // Noncompliant [[sc=26;ec=32]] {{Make sure creating this cookie without the "secure" flag is safe here.}} + Cookie cookie2 = new Cookie("name", "value"); // Noncompliant {{Make sure creating this cookie without the "secure" flag is safe here.}} +// ^^^^^^ Cookie cookie3 = new Cookie("name", "value"); - cookie3.setSecure(false); // Noncompliant {{Make sure creating this cookie without the "secure" flag is safe here.}} + cookie3.setSecure(false); // Noncompliant {{Make sure creating this cookie without the "secure" flag is safe here.}} Cookie cookie5 = new Cookie("name", "value"); cookie5.setSecure(FALSE_CONSTANT); // Noncompliant @@ -61,7 +63,7 @@ Cookie servletCookie( Cookie c7 = new Cookie("name", "value"); boolean b = false; - c7.setSecure(b); // Noncompliant [[secondary=-1]] + c7.setSecure(b); // Noncompliant Cookie c8 = new Cookie("name", "value"); c8.setSecure(param); @@ -73,7 +75,8 @@ Cookie servletCookie( c10.setSecure(true); Object c12; - c12 = new Cookie("name", "value"); // Noncompliant [[sc=15;ec=21]] {{Make sure creating this cookie without the "secure" flag is safe here.}} + c12 = new Cookie("name", "value"); // Noncompliant {{Make sure creating this cookie without the "secure" flag is safe here.}} +// ^^^^^^ Cookie c13 = new Cookie("name", "value"); boolean value = false; @@ -96,7 +99,7 @@ HttpCookie getHttpCookie() { HttpCookie c5; c5 = new HttpCookie("name", "value"); - c5.setSecure(false); // Noncompliant + c5.setSecure(false); // Noncompliant return new HttpCookie("name", "value"); // Noncompliant } @@ -112,12 +115,12 @@ NewCookie jaxRsNewCookie(javax.ws.rs.core.Cookie cookie) { NewCookie c7 = new NewCookie("1", "2", "3", "4", "5", 6, false, true); // Noncompliant NewCookie c8 = new NewCookie("1", "2", "3", "4", "5", 6, true, true); - NewCookie c9 = new NewCookie("1", "2", "3", "4", 5, "6", 7, new Date(), false, true); // Noncompliant + NewCookie c9 = new NewCookie("1", "2", "3", "4", 5, "6", 7, new Date(), false, true); // Noncompliant NewCookie c10 = new NewCookie("1", "2", "3", "4", 5, "6", 7, new Date(), true, false); NewCookie c11 = new NewCookie("1", "2", "3", "4", "5", 6, true); NewCookie c12 = new NewCookie("1", "2", "3", "4", "5", 6, false); // Noncompliant - NewCookie c13 = new NewCookie("1", "2", "3", "4", "5", 6, false, false); // Noncompliant + NewCookie c13 = new NewCookie("1", "2", "3", "4", "5", 6, false, false); // Noncompliant NewCookie c14 = new NewCookie("1", "2", "3", "4", "5", 6, true, false); return new NewCookie(cookie); // Noncompliant @@ -128,7 +131,7 @@ SimpleCookie apacheShiro(SimpleCookie unknownCookie) { SimpleCookie c2 = new SimpleCookie(); c2.setSecure(false); // Noncompliant SimpleCookie c3 = new SimpleCookie(); // Noncompliant - SimpleCookie c4 = new SimpleCookie("name"); // Noncompliant + SimpleCookie c4 = new SimpleCookie("name"); // Noncompliant SimpleCookie c5 = new SimpleCookie("name"); c5.setSecure(true); return new SimpleCookie(); // Noncompliant @@ -149,7 +152,7 @@ void playFw(play.mvc.Http.Cookie.SameSite sameSite) { play.mvc.Http.Cookie c4; c4 = new play.mvc.Http.Cookie("1", "2", 3, "4", "5", true, true); CookieBuilder cb1 = play.mvc.Http.Cookie.builder("1", "2"); - cb1.withSecure(false); // Noncompliant + cb1.withSecure(false); // Noncompliant CookieBuilder cb2 = play.mvc.Http.Cookie.builder("1", "2"); cb2.withSecure(true); play.mvc.Http.Cookie.builder("1", "2") @@ -157,7 +160,8 @@ void playFw(play.mvc.Http.Cookie.SameSite sameSite) { .withPath("x") .withDomain("x") .withSecure(true) - .withSecure(false) // Noncompliant [[sc=20;ec=27]] {{Make sure creating this cookie without the "secure" flag is safe here.}} + .withSecure(false) // Noncompliant {{Make sure creating this cookie without the "secure" flag is safe here.}} +// ^^^^^^^ .withSecure(true) .build(); play.mvc.Http.Cookie c5 = play.mvc.Http.Cookie.builder("theme", "blue").withSecure(true).build(); @@ -221,7 +225,7 @@ class JavaNet2 { void httpCookie() { HttpCookie cookie = getCookie(); if (cookie == null) { - cookie = new HttpCookie("name", "value"); // Noncompliant + cookie = new HttpCookie("name", "value"); // Noncompliant } } } diff --git a/java-checks-test-sources/default/src/main/java/checks/security/ServerCertificatesCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/security/ServerCertificatesCheckSample.java index 5b21bbc4712..85de1a42943 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/ServerCertificatesCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/ServerCertificatesCheckSample.java @@ -95,22 +95,22 @@ public X509Certificate[] getAcceptedIssuers() { } class EmptyX509ExtendedTrustManager extends X509ExtendedTrustManager { @Override - public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {} // Noncompliant An empty implementation is not considered valid + public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {} // Noncompliant @Override - public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {} // Noncompliant An empty implementation is not considered valid + public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {} // Noncompliant @Override - public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {} // Noncompliant An empty implementation is not considered valid + public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {} // Noncompliant @Override - public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {} // Noncompliant An empty implementation is not considered valid + public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {} // Noncompliant @Override - public void checkServerTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException {} // Noncompliant An empty implementation is not considered valid + public void checkServerTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException {} // Noncompliant @Override - public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {} // Noncompliant An empty implementation is not considered valid + public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {} // Noncompliant @Override public X509Certificate[] getAcceptedIssuers() { diff --git a/java-checks-test-sources/default/src/main/java/checks/security/UnpredictableSaltCheck.java b/java-checks-test-sources/default/src/main/java/checks/security/UnpredictableSaltCheck.java index 947d1674a7b..ca12aa525a6 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/UnpredictableSaltCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/UnpredictableSaltCheck.java @@ -15,10 +15,14 @@ public void testPBESpec(char[] chars, byte[] salt) throws NoSuchAlgorithmExcepti public void testNonRandomPBESpec(char[] chars, String str) throws NoSuchAlgorithmException { byte[] salt = "notrandom".getBytes(); // secondary location - PBEKeySpec spec = new PBEKeySpec(chars, salt, 1); // Noncompliant [[sc=23;ec=53;secondary=-1]] {{Make this salt unpredictable.}} +// ^^^^^^^^^^^^^^^^^^^^^^> + PBEKeySpec spec = new PBEKeySpec(chars, salt, 1); // Noncompliant {{Make this salt unpredictable.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ final byte[] finalSalt = "notrandom".getBytes(); //secondary location - PBEKeySpec specFinal = new PBEKeySpec(chars, finalSalt, 1); // Noncompliant [[sc=28;ec=63;secondary=-1]] {{Make this salt unpredictable.}} +// ^^^^^^^^^^^^^^^^^^^^^^> + PBEKeySpec specFinal = new PBEKeySpec(chars, finalSalt, 1); // Noncompliant {{Make this salt unpredictable.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ byte[] salt1 = this.secureSalt(); PBEKeySpec spec2 = new PBEKeySpec(chars, salt1, 2); // Compliant @@ -38,9 +42,11 @@ public void testNonRandomPBESpec(char[] chars, String str) throws NoSuchAlgorith PBEKeySpec spec6 = new PBEKeySpec(chars, new MyMessageDigest("").engineDigest(), 2); // Compliant PBEKeySpec spec666 = new PBEKeySpec(chars, str.getBytes(), 2); // Compliant - new PBEParameterSpec("notrandom".getBytes(), 10000); // Noncompliant {{Make this salt unpredictable.}} - new PBEParameterSpec(salt, 10000); // Noncompliant [[sc=5;ec=38;secondary=17]] - new PBEParameterSpec(finalSalt, 10000); // Noncompliant [[sc=5;ec=43;secondary=20]] + new PBEParameterSpec("notrandom".getBytes(), 10000); // Noncompliant {{Make this salt unpredictable.}} + new PBEParameterSpec(salt, 10000); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + new PBEParameterSpec(finalSalt, 10000); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } private byte[] secureSalt() { diff --git a/java-checks-test-sources/default/src/main/java/checks/security/VerifiedServerHostnamesCheck/ApacheCommonEmail.java b/java-checks-test-sources/default/src/main/java/checks/security/VerifiedServerHostnamesCheck/ApacheCommonEmail.java index d1733337699..4c533150eaa 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/VerifiedServerHostnamesCheck/ApacheCommonEmail.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/VerifiedServerHostnamesCheck/ApacheCommonEmail.java @@ -13,7 +13,8 @@ class ApacheEmail { public void foo() { Email email = new SimpleEmail(); - email.setSSLOnConnect(true); // Noncompliant [[sc=5;ec=32]] {{Enable server hostname verification on this SSL/TLS connection.}} + email.setSSLOnConnect(true); // Noncompliant {{Enable server hostname verification on this SSL/TLS connection.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ } public void foo2() { @@ -30,7 +31,7 @@ public void foo3() { public void foo4() { Email email = new SimpleEmail(); - email.setSSLOnConnect(true); // Noncompliant + email.setSSLOnConnect(true); // Noncompliant email.setSSLCheckServerIdentity(false); } @@ -53,28 +54,28 @@ public void foo7(boolean flag) { public void foo8() { Email email = new SimpleEmail(); - email.setSSL(true); // Noncompliant + email.setSSL(true); // Noncompliant } public void foo9() { Email email = new SimpleEmail(); - email.setTLS(true); // Noncompliant + email.setTLS(true); // Noncompliant } public void foo10() { Email email = new SimpleEmail(); - email.setStartTLSEnabled(true); // Noncompliant + email.setStartTLSEnabled(true); // Noncompliant } public void foo11() { Email email = new SimpleEmail(); - email.setStartTLSRequired(true); // Noncompliant + email.setStartTLSRequired(true); // Noncompliant } public void foo12(boolean cond) { if (cond) { Email email = new SimpleEmail(); - email.setSSLOnConnect(true); // Noncompliant + email.setSSLOnConnect(true); // Noncompliant email.setSSLCheckServerIdentity(false); } else { Email email = new SimpleEmail(); diff --git a/java-checks-test-sources/default/src/main/java/checks/security/VerifiedServerHostnamesCheck/JavaMailSession.java b/java-checks-test-sources/default/src/main/java/checks/security/VerifiedServerHostnamesCheck/JavaMailSession.java index 8f5a927cc75..f4226eeed38 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/VerifiedServerHostnamesCheck/JavaMailSession.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/VerifiedServerHostnamesCheck/JavaMailSession.java @@ -6,7 +6,8 @@ public class JavaMailSession { public void foo() { Properties props = new Properties(); - props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");// Noncompliant [[sc=5;ec=81]] {{Enable server hostname verification on this SSL/TLS connection, by setting "mail.smtp.ssl.checkserveridentity" to true.}} + props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // Noncompliant {{Enable server hostname verification on this SSL/TLS connection, by setting "mail.smtp.ssl.checkserveridentity" to true.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } public void foo2() { @@ -56,7 +57,7 @@ public void foo8(boolean cond) { public void foo9() { Properties props = new Properties(); - props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");// Noncompliant + props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // Noncompliant anotherUnrelatedCall(); } diff --git a/java-checks-test-sources/default/src/main/java/checks/security/WebViewJavaScriptSupportCheck.java b/java-checks-test-sources/default/src/main/java/checks/security/WebViewJavaScriptSupportCheck.java index 35aa8961905..2d5171390bb 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/WebViewJavaScriptSupportCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/WebViewJavaScriptSupportCheck.java @@ -4,7 +4,8 @@ class WebViewJavaScriptSupportCheck { void foo(WebSettings settings, boolean value) { - settings.setJavaScriptEnabled(true); // Noncompliant [[sc=35;ec=39]] {{Make sure that enabling JavaScript support is safe here.}} + settings.setJavaScriptEnabled(true); // Noncompliant {{Make sure that enabling JavaScript support is safe here.}} +// ^^^^ settings.setJavaScriptEnabled(false); // Compliant settings.setJavaScriptEnabled(value); // Compliant } diff --git a/java-checks-test-sources/default/src/main/java/checks/security/WebViewsFileAccessCheck.java b/java-checks-test-sources/default/src/main/java/checks/security/WebViewsFileAccessCheck.java index 242d71137c3..91db11de052 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/WebViewsFileAccessCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/WebViewsFileAccessCheck.java @@ -4,19 +4,23 @@ class WebViewsFileAccessCheck { void foo(WebSettings settings, boolean value) { - settings.setAllowFileAccess(true); // Noncompliant [[sc=33;ec=37]] {{Make sure that enabling file access is safe here.}} + settings.setAllowFileAccess(true); // Noncompliant {{Make sure that enabling file access is safe here.}} +// ^^^^ settings.setAllowFileAccess(false); // Compliant settings.setAllowFileAccess(value); // Compliant - settings.setAllowContentAccess(true); // Noncompliant [[sc=36;ec=40]] {{Make sure that enabling file access is safe here.}} + settings.setAllowContentAccess(true); // Noncompliant {{Make sure that enabling file access is safe here.}} +// ^^^^ settings.setAllowContentAccess(false); // Compliant settings.setAllowContentAccess(value); // Compliant - settings.setAllowFileAccessFromFileURLs(true); // Noncompliant [[sc=45;ec=49]] {{Make sure that enabling file access is safe here.}} + settings.setAllowFileAccessFromFileURLs(true); // Noncompliant {{Make sure that enabling file access is safe here.}} +// ^^^^ settings.setAllowFileAccessFromFileURLs(false); // Compliant settings.setAllowFileAccessFromFileURLs(value); // Compliant - settings.setAllowUniversalAccessFromFileURLs(true); // Noncompliant [[sc=50;ec=54]] {{Make sure that enabling file access is safe here.}} + settings.setAllowUniversalAccessFromFileURLs(true); // Noncompliant {{Make sure that enabling file access is safe here.}} +// ^^^^ settings.setAllowUniversalAccessFromFileURLs(false); // Compliant settings.setAllowUniversalAccessFromFileURLs(value); // Compliant } diff --git a/java-checks-test-sources/default/src/main/java/checks/security/XxeActiveMQCheck.java b/java-checks-test-sources/default/src/main/java/checks/security/XxeActiveMQCheck.java index 4dc537aa175..440706d1159 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/XxeActiveMQCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/XxeActiveMQCheck.java @@ -42,14 +42,14 @@ ActiveMQConnectionFactory trust_all_packages() { } ActiveMQConnectionFactory trust_all_packages_true_with_restrict_packages() { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); // Noncompliant + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); // Noncompliant factory.setTrustAllPackages(BOOLEAN_TRUE); factory.setTrustedPackages(packages); return factory; } ActiveMQConnectionFactory trust_all_packages_false_without_restrict_packages() { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); // Noncompliant + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); // Noncompliant factory.setTrustAllPackages(false); return factory; } @@ -93,7 +93,7 @@ void chained_and_secured(boolean condition) { } void chained_and_not_secured(boolean condition) throws JMSException { - new ActiveMQConnectionFactory("tcp://localhost:61616").createConnection(); // Noncompliant + new ActiveMQConnectionFactory("tcp://localhost:61616").createConnection(); // Noncompliant } void cannot_resolved_symbol(boolean condition) throws JMSException { @@ -110,7 +110,7 @@ void conditional_2_different_factory_one_chained(boolean condition) { } ActiveMQConnectionFactory trust_all_packages_using_placeholder() { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); // Noncompliant + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); // Noncompliant factory.setTrustedPackages(Arrays.asList("*")); return factory; } diff --git a/java-checks-test-sources/default/src/main/java/checks/security/ZipEntryCheck.java b/java-checks-test-sources/default/src/main/java/checks/security/ZipEntryCheck.java index 64648e3b9b4..2f0471fc4e2 100644 --- a/java-checks-test-sources/default/src/main/java/checks/security/ZipEntryCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/security/ZipEntryCheck.java @@ -39,7 +39,8 @@ public ZipEntry noncompliant2(ZipInputStream zis) throws Exception { } public JarEntry noncompliant3(JarFile file) { - return file.entries().nextElement(); // Noncompliant [[sc=17;ec=24]] + return file.entries().nextElement(); // Noncompliant +// ^^^^^^^ } public String compliant() throws java.lang.Exception { diff --git a/java-checks-test-sources/default/src/main/java/checks/serialization/ExternalizableClassConstructorCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/serialization/ExternalizableClassConstructorCheckSample.java index fa60e26166e..d9e430b3b2c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/serialization/ExternalizableClassConstructorCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/serialization/ExternalizableClassConstructorCheckSample.java @@ -5,7 +5,8 @@ import java.io.ObjectInput; import java.io.ObjectOutput; -class S2060_A implements Externalizable { // Noncompliant [[sc=7;ec=14]] {{Add a no-arg constructor to this class.}} +class S2060_A implements Externalizable { // Noncompliant {{Add a no-arg constructor to this class.}} +// ^^^^^^^ public S2060_A(String color, int weight) {} @Override public void writeExternal(ObjectOutput out) throws IOException { } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { } @@ -37,7 +38,8 @@ class S2060_D implements S2060_I { // Compliant @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { } } -class S2060_E implements S2060_I { // Noncompliant [[sc=7;ec=14]] {{Add a no-arg constructor to this class.}} +class S2060_E implements S2060_I { // Noncompliant {{Add a no-arg constructor to this class.}} +// ^^^^^^^ public S2060_E(String color, int weight) {} @Override public void writeExternal(ObjectOutput out) throws IOException { } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { } @@ -54,19 +56,22 @@ public CtorVisibility_A() {} // Compliant } class CtorVisibility_B implements Externalizable { // Compliant - protected CtorVisibility_B() {} // Noncompliant [[sc=13;ec=29]] {{Declare this no-arg constructor public.}} + protected CtorVisibility_B() {} // Noncompliant {{Declare this no-arg constructor public.}} +// ^^^^^^^^^^^^^^^^ @Override public void writeExternal(ObjectOutput out) throws IOException { } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { } } class CtorVisibility_C implements Externalizable { // Compliant - CtorVisibility_C() {} // Noncompliant [[sc=3;ec=19]] + CtorVisibility_C() {} // Noncompliant +//^^^^^^^^^^^^^^^^ @Override public void writeExternal(ObjectOutput out) throws IOException { } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { } } class CtorVisibility_D implements Externalizable { // Compliant - private CtorVisibility_D() {} // Noncompliant [[sc=11;ec=27]] + private CtorVisibility_D() {} // Noncompliant +// ^^^^^^^^^^^^^^^^ @Override public void writeExternal(ObjectOutput out) throws IOException { } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { } } diff --git a/java-checks-test-sources/default/src/main/java/checks/serialization/NonSerializableWriteCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/serialization/NonSerializableWriteCheckSample.java index bd47b697097..54f978104e8 100644 --- a/java-checks-test-sources/default/src/main/java/checks/serialization/NonSerializableWriteCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/serialization/NonSerializableWriteCheckSample.java @@ -40,7 +40,8 @@ void myMethod(ObjectOutputStream out, Object x, byte[] array) throws IOException out.writeObject(myNonSerializable2); } if (x.toString() instanceof Serializable) { - out.writeObject(new MyNonSerializable()); // Noncompliant [[sc=23;ec=46]] {{Make the "checks.serialization.MyNonSerializable" class "Serializable" or don't write it.}} + out.writeObject(new MyNonSerializable()); // Noncompliant {{Make the "checks.serialization.MyNonSerializable" class "Serializable" or don't write it.}} +// ^^^^^^^^^^^^^^^^^^^^^^^ } out.writeObject(array); diff --git a/java-checks-test-sources/default/src/main/java/checks/serialization/RecordSerializationIgnoredMembersCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/serialization/RecordSerializationIgnoredMembersCheckSample.java index 07698c33052..2883019cbf6 100644 --- a/java-checks-test-sources/default/src/main/java/checks/serialization/RecordSerializationIgnoredMembersCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/serialization/RecordSerializationIgnoredMembersCheckSample.java @@ -13,9 +13,11 @@ public class RecordSerializationIgnoredMembersCheckSample { record NoncompliantRecord() implements Serializable, Externalizable { - private static final ObjectStreamField[] serialPersistentFields = new ObjectStreamField[0]; // Noncompliant [[sc=46;ec=68]] {{Remove this field that will be ignored during record serialization.}} + private static final ObjectStreamField[] serialPersistentFields = new ObjectStreamField[0]; // Noncompliant {{Remove this field that will be ignored during record serialization.}} +// ^^^^^^^^^^^^^^^^^^^^^^ - private void writeObject(ObjectOutputStream out) throws IOException { } // Noncompliant [[sc=18;ec=29]] {{Remove this method that will be ignored during record serialization.}} + private void writeObject(ObjectOutputStream out) throws IOException { } // Noncompliant {{Remove this method that will be ignored during record serialization.}} +// ^^^^^^^^^^^ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { } // Noncompliant private void readObjectNoData() throws ObjectStreamException { } // Noncompliant @Override public void writeExternal(ObjectOutput out) throws IOException { } // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/serialization/SerialVersionUidCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/serialization/SerialVersionUidCheckSample.java index f58e2f6c27b..32a00208143 100644 --- a/java-checks-test-sources/default/src/main/java/checks/serialization/SerialVersionUidCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/serialization/SerialVersionUidCheckSample.java @@ -7,13 +7,15 @@ class SerialVersionUidCheckSampleA implements Cloneable {} class SerialVersionUidCheckSampleB implements Serializable { private static final long serialVersionUID = 1L; } -class SerialVersionUidCheckSampleC implements Serializable {} // Noncompliant [[sc=7;ec=35]] {{Add a "static final long serialVersionUID" field to this class.}} +class SerialVersionUidCheckSampleC implements Serializable {} // Noncompliant {{Add a "static final long serialVersionUID" field to this class.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ class SerialVersionUidCheckSampleD extends SerialVersionUidCheckSampleC {} // Noncompliant {{Add a "static final long serialVersionUID" field to this class.}} class SerialVersionUidCheckSampleE implements Serializable { private final long serialVersionUID = 1L; // Noncompliant {{Make this "serialVersionUID" field "static".}} } class SerialVersionUidCheckSampleF implements Serializable { - private static long serialVersionUID = 1L; // Noncompliant [[sc=23;ec=39]] {{Make this "serialVersionUID" field "final".}} + private static long serialVersionUID = 1L; // Noncompliant {{Make this "serialVersionUID" field "final".}} +// ^^^^^^^^^^^^^^^^ } class SerialVersionUidCheckSampleG implements Serializable { private static int serialVersionUID = 1; // Noncompliant {{Make this "serialVersionUID" field "final long".}} @@ -34,7 +36,7 @@ class SerialVersionUidCheckSampleInner implements Serializable {} // Noncomplian } @SuppressWarnings("serial") -class SerialVersionUidCheckSampleJ implements Serializable {} // Noncompliant, this issue will be filtered by the supress warning filter +class SerialVersionUidCheckSampleJ implements Serializable {} // Noncompliant enum SerialVersionUidCheckSampleMyEnum { FOO { diff --git a/java-checks-test-sources/default/src/main/java/checks/serialization/SerializableFieldInSerializableClassCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/serialization/SerializableFieldInSerializableClassCheckSample.java index 768149d800f..3bcd7678f3a 100644 --- a/java-checks-test-sources/default/src/main/java/checks/serialization/SerializableFieldInSerializableClassCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/serialization/SerializableFieldInSerializableClassCheckSample.java @@ -30,7 +30,8 @@ class Address { } class Person implements Serializable { - Address address; // Noncompliant [[sc=11;ec=18]] {{Make "address" transient or serializable.}} + Address address; // Noncompliant {{Make "address" transient or serializable.}} +// ^^^^^^^ SerializableFieldInSerializableClassCheckSampleA a; static Address address2;//Compliant : static field transient Address address3; @@ -234,13 +235,13 @@ public JakartaPerson777(Address _address) { } class IncompleteSerializableMethods1 implements Serializable { - Address address; // Noncompliant - read/write methods are not exactly matching signatures (throwing wrong types) + Address address; // Noncompliant private void writeObject(java.io.ObjectOutputStream out) {} private void readObject(java.io.ObjectInputStream in) throws java.io.IOException {} } class IncompleteSerializableMethods2 implements Serializable { - Address address; // Noncompliant - write methods is wrongly implemented + Address address; // Noncompliant private void writeObject(java.io.ObjectOutputStream out) throws ClassCastException {} // wrong thrown type private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {} } @@ -456,7 +457,7 @@ class A implements java.io.Serializable { private final NonSerializableInterface field1 = new SerializableImpl(); // Compliant, is final private NonSerializableInterface field2; // Noncompliant private NonSerializableInterface field3 = init(); // Noncompliant - private NonSerializableInterface field4 = initWithSerializable(); // Noncompliant, is not final + private NonSerializableInterface field4 = initWithSerializable(); // Noncompliant private final NonSerializableInterface field5 = initWithSerializable(); // Compliant, is final private final NonSerializableInterface field6 = init(); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/serialization/SerializableObjectInSessionCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/serialization/SerializableObjectInSessionCheckSample.java index 6ea439e1859..a56f73edc17 100644 --- a/java-checks-test-sources/default/src/main/java/checks/serialization/SerializableObjectInSessionCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/serialization/SerializableObjectInSessionCheckSample.java @@ -30,7 +30,8 @@ class SerializableObjectInSessionCheckSample { void foo(HttpServletRequest request) { HttpSession session = request.getSession(); - session.setAttribute("address", new Address()); // Noncompliant [[sc=37;ec=50]] {{Make "Address" serializable or don't store it in the session.}} + session.setAttribute("address", new Address()); // Noncompliant {{Make "Address" serializable or don't store it in the session.}} +// ^^^^^^^^^^^^^ session.setAttribute("person", new Person()); // Noncompliant {{Make "Person" serializable or don't store it in the session.}} session.setAttribute("person", 1); session.setAttribute("person", new Integer(1)); diff --git a/java-checks-test-sources/default/src/main/java/checks/serialization/SerializableSuperConstructorCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/serialization/SerializableSuperConstructorCheckSample.java index 1851cb69b09..0a08d107b20 100644 --- a/java-checks-test-sources/default/src/main/java/checks/serialization/SerializableSuperConstructorCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/serialization/SerializableSuperConstructorCheckSample.java @@ -19,7 +19,8 @@ private NonSerializableWithoutAccessibleNoArgConstructor() {} class S2055_A extends NonSerializableWithoutConstructor implements Serializable {} class S2055_B extends NonSerializableWithAccessibleNoArgConstructor implements Serializable {} -class S2055_C1 extends NonSerializableWithoutAccessibleNoArgConstructor implements Serializable { // Noncompliant [[sc=24;ec=72]] {{Add a no-arg constructor to "NonSerializableWithoutAccessibleNoArgConstructor".}} +class S2055_C1 extends NonSerializableWithoutAccessibleNoArgConstructor implements Serializable { // Noncompliant {{Add a no-arg constructor to "NonSerializableWithoutAccessibleNoArgConstructor".}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ S2055_C1(String arg1) { super(arg1); } } class S2055_C2 extends NonSerializableWithoutAccessibleNoArgConstructor implements Serializable { // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/AsyncMethodsCalledViaThisCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/AsyncMethodsCalledViaThisCheckSample.java index a5d397c3954..693527a28d5 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/AsyncMethodsCalledViaThisCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/AsyncMethodsCalledViaThisCheckSample.java @@ -23,7 +23,8 @@ void normal() { } void asyncNoncompliant1() { - asyncMethod(); // Noncompliant [[sc=5;ec=18]] {{Call async methods via an injected dependency instead of directly via 'this'.}} + asyncMethod(); // Noncompliant {{Call async methods via an injected dependency instead of directly via 'this'.}} +// ^^^^^^^^^^^^^ } void asyncNoncompliant2() { diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/AsyncMethodsOnConfigurationClassCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/AsyncMethodsOnConfigurationClassCheckSample.java index caa1e090c9f..9ccdd5d33f0 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/AsyncMethodsOnConfigurationClassCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/AsyncMethodsOnConfigurationClassCheckSample.java @@ -7,7 +7,8 @@ @Configuration public class AsyncMethodsOnConfigurationClassCheckSample { - @Async // Noncompliant [[sc=3;ec=9;quickfixes=qf1]] {{Remove this "@Async" annotation from this method.}} + @Async // Noncompliant {{Remove this "@Async" annotation from this method.}} [[quickfixes=qf1]] +//^^^^^^ // fix@qf1 {{Remove "@Async"}} // edit@qf1 [[sc=3;ec=9]] {{}} public void asyncMethod() { diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/AsyncMethodsReturnTypeCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/AsyncMethodsReturnTypeCheckSample.java index daf062f8a66..08afcbbbac9 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/AsyncMethodsReturnTypeCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/AsyncMethodsReturnTypeCheckSample.java @@ -9,7 +9,8 @@ public class AsyncMethodsReturnTypeCheckSample { @Async - String asyncString() { // Noncompliant [[sc=3;ec=9]] {{Async methods should return 'void' or a 'Future' type.}} + String asyncString() { // Noncompliant {{Async methods should return 'void' or a 'Future' type.}} +//^^^^^^ return null; } diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/AutowiredOnConstructorWhenMultipleConstructorsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/AutowiredOnConstructorWhenMultipleConstructorsCheckSample.java index baaf4cd924d..f56a5e2ea27 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/AutowiredOnConstructorWhenMultipleConstructorsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/AutowiredOnConstructorWhenMultipleConstructorsCheckSample.java @@ -16,7 +16,8 @@ public AutowiredOnConstructorWhenMultipleConstructorsCheckSample(String s) { } @Component - class SpringComponent { // Noncompliant [[sc=9;ec=24]] {{Add @Autowired to one of the constructors.}} + class SpringComponent { // Noncompliant {{Add @Autowired to one of the constructors.}} +// ^^^^^^^^^^^^^^^ public SpringComponent() { } diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/AutowiredOnMultipleConstructorsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/AutowiredOnMultipleConstructorsCheckSample.java index 8194ab0152f..52b701be8f4 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/AutowiredOnMultipleConstructorsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/AutowiredOnMultipleConstructorsCheckSample.java @@ -18,7 +18,8 @@ public AutowiredOnMultipleConstructorsCheckSample(Object myService) { this.myService = myService; } - @Autowired // Noncompliant [[sc=3;ec=13]] {{Remove this "@Autowired" annotation.}} + @Autowired // Noncompliant {{Remove this "@Autowired" annotation.}} +//^^^^^^^^^^ public AutowiredOnMultipleConstructorsCheckSample(List list, Object myService) { // ... this.myService = myService; diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/AvoidQualifierOnBeanMethodsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/AvoidQualifierOnBeanMethodsCheckSample.java index 76b4e33d2bb..bda94733d5d 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/AvoidQualifierOnBeanMethodsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/AvoidQualifierOnBeanMethodsCheckSample.java @@ -13,7 +13,8 @@ public class AvoidQualifierOnBeanMethodsCheckSample { @Configuration class Configuration1 { @Bean - @Qualifier("foo") // Noncompliant, [[sc=5;ec=22;quickfixes=qf1]] {{Remove this redundant "@Qualifier" annotation and rely on the @Bean method.}} + @Qualifier("foo") // Noncompliant {{Remove this redundant "@Qualifier" annotation and rely on the @Bean method.}} [[quickfixes=qf1]] +// ^^^^^^^^^^^^^^^^^ // fix@qf1 {{Remove "@Qualifier"}} // edit@qf1 [[sc=5;ec=22]] {{}} public String foo() { @@ -60,7 +61,8 @@ public String foo() { } @Bean(name = "bar") - @Qualifier // Noncompliant, [[sc=5;ec=15;quickfixes=qf3]] {{Remove this redundant "@Qualifier" annotation and rely on the @Bean method.}} + @Qualifier // Noncompliant {{Remove this redundant "@Qualifier" annotation and rely on the @Bean method.}} [[quickfixes=qf3]] +// ^^^^^^^^^^ // fix@qf3 {{Remove "@Qualifier"}} // edit@qf3 [[sc=5;ec=15]] {{}} public String bar() { diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/ControllerWithRestControllerReplacementCheck.java b/java-checks-test-sources/default/src/main/java/checks/spring/ControllerWithRestControllerReplacementCheck.java index bb7d314bb0a..b9ee1a79c39 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/ControllerWithRestControllerReplacementCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/ControllerWithRestControllerReplacementCheck.java @@ -7,15 +7,17 @@ public class ControllerWithRestControllerReplacementCheck { - @Controller // Noncompliant [[sc=3;ec=14;secondary=16;quickfixes=qf1,qf2]] {{Replace the "@Controller" annotation by "@RestController" and remove all + @Controller // Noncompliant [[quickfixes=qf1,qf2]] +//^^^^^^^^^^^ // "@ResponseBody" annotations.}} // fix@qf2 {{Replace "@Controller" by "@RestController".}} // edit@qf2 [[sl=10;el=10;sc=3;ec=14]] {{@RestController}} class ClassOne { @ResponseBody +// ^^^^^^^^^^^^^< // fix@qf1 {{Remove "@ResponseBody" annotations.}} - // edit@qf1 [[sl=16;el=16;sc=5;ec=18]] {{}} + // edit@qf1 [[sl=17;el=17;sc=5;ec=18]] {{}} public void m() { } } @@ -62,21 +64,24 @@ public void m() { } } - @Controller // Noncompliant [[sc=3;ec=14;secondary=71,77;quickfixes=qf3,qf4]] {{Replace the "@Controller" annotation by "@RestController" and remove all + @Controller // Noncompliant [[quickfixes=qf3,qf4]] +//^^^^^^^^^^^ // "@ResponseBody" annotations.}} // fix@qf4 {{Replace "@Controller" by "@RestController".}} - // edit@qf4 [[sl=65;el=65;sc=3;ec=14]] {{@RestController}} + // edit@qf4 [[sl=67;el=67;sc=3;ec=14]] {{@RestController}} class ClassSeven { @ResponseBody +// ^^^^^^^^^^^^^< // fix@qf3 {{Remove "@ResponseBody" annotations.}} - // edit@qf3 [[sl=71;el=71;sc=5;ec=18]] {{}} + // edit@qf3 [[sl=74;el=74;sc=5;ec=18]] {{}} public void m() { } @ResponseBody +// ^^^^^^^^^^^^^< // fix@qf3 {{Remove "@ResponseBody" annotations.}} - // edit@qf3 [[sl=77;el=77;sc=5;ec=18]] {{}} + // edit@qf3 [[sl=81;el=81;sc=5;ec=18]] {{}} public void m2() { } } diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/ControllerWithSessionAttributesCheck.java b/java-checks-test-sources/default/src/main/java/checks/spring/ControllerWithSessionAttributesCheck.java index a913584b871..1f668c48fc6 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/ControllerWithSessionAttributesCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/ControllerWithSessionAttributesCheck.java @@ -9,7 +9,8 @@ import org.springframework.web.bind.support.SessionStatus; @Controller -@SessionAttributes("foo") // Noncompliant [[sc=2;ec=19]] {{Add a call to "setComplete()" on the SessionStatus object in a "@RequestMapping" method.}} + @SessionAttributes("foo") // Noncompliant {{Add a call to "setComplete()" on the SessionStatus object in a "@RequestMapping" method.}} +//^^^^^^^^^^^^^^^^^ class S3753 { private int field; @@ -84,7 +85,7 @@ public void end(SessionStatus status) { } @Controller -@SessionAttributes("foo") // Noncompliant, FP +@SessionAttributes("foo") // Noncompliant class S3753_ResultControllerHosting extends S3753_AbstractController { } class S3753_X { // not a controller diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/DirectBeanMethodInvocationWithoutProxyCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/DirectBeanMethodInvocationWithoutProxyCheckSample.java index b9a6443032d..8b508a4127f 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/DirectBeanMethodInvocationWithoutProxyCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/DirectBeanMethodInvocationWithoutProxyCheckSample.java @@ -19,7 +19,8 @@ public SimpleBean simpleBean() { @Bean public CompositeBean compositeBean() { - return new CompositeBean(simpleBean()); // Noncompliant [[sc=32;ec=44]] {{Replace this bean method invocation with a dependency injection.}} + return new CompositeBean(simpleBean()); // Noncompliant {{Replace this bean method invocation with a dependency injection.}} +// ^^^^^^^^^^^^ } @Bean @@ -30,7 +31,8 @@ public SimpleBean anotherSimpleBean() { @Bean public CompositeBean anotherCompositeBean() { - return new CompositeBean(anotherSimpleBean()); // Noncompliant [[sc=32;ec=51]] {{Replace this bean method invocation with a dependency injection.}} + return new CompositeBean(anotherSimpleBean()); // Noncompliant {{Replace this bean method invocation with a dependency injection.}} +// ^^^^^^^^^^^^^^^^^^^ } @Bean @@ -41,7 +43,8 @@ public SimpleBean yetAnotherSimpleBean() { @Bean public CompositeBean yetAnotherCompositeBean() { - return new CompositeBean(yetAnotherSimpleBean()); // Noncompliant [[sc=32;ec=54]] {{Replace this bean method invocation with a dependency injection.}} + return new CompositeBean(yetAnotherSimpleBean()); // Noncompliant {{Replace this bean method invocation with a dependency injection.}} +// ^^^^^^^^^^^^^^^^^^^^^^ } } diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/FieldDependencyInjectionCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/FieldDependencyInjectionCheckSample.java index 2d9018c59bb..35ce1503c35 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/FieldDependencyInjectionCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/FieldDependencyInjectionCheckSample.java @@ -7,7 +7,8 @@ @Component public class FieldDependencyInjectionCheckSample { - @Autowired // Noncompliant [[sc=3;ec=13]] {{Remove this field injection and use constructor injection instead.}} + @Autowired // Noncompliant {{Remove this field injection and use constructor injection instead.}} +//^^^^^^^^^^ private String autowired; @Inject // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/ModelAttributeNamingConventionForSpELCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/ModelAttributeNamingConventionForSpELCheckSample.java index 0b3122d121a..4b1fc31b1f1 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/ModelAttributeNamingConventionForSpELCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/ModelAttributeNamingConventionForSpELCheckSample.java @@ -32,7 +32,8 @@ public void foo(org.springframework.ui.Model model) { model.addAllAttributes(Map.ofEntries(Map.entry(" m", 42), Map.entry(" a", 22))); // Noncompliant model.addAttribute("", 5); // Noncompliant - model.addAttribute(" a", ""); // Noncompliant [[sc=24;ec=28]] {{Attribute names must begin with a letter (a-z, A-Z), underscore (_), or dollar sign ($) and can be + model.addAttribute(" a", ""); // Noncompliant +// ^^^^ // followed by letters, digits, underscores, or dollar signs.}} model.addAttribute("a-b", ""); // Noncompliant model.addAttribute("1c", 42); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/NonSingletonAutowiredInSingletonCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/NonSingletonAutowiredInSingletonCheckSample.java index 284b7b5ae97..a6d38a64046 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/NonSingletonAutowiredInSingletonCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/NonSingletonAutowiredInSingletonCheckSample.java @@ -16,7 +16,8 @@ public class NonSingletonAutowiredInSingletonCheckSample { public class SingletonBean { @Autowired - private RequestBean1 requestBean1; // Noncompliant, [[sc=13;ec=25]] {{Don't auto-wire this non-Singleton bean into a Singleton bean (autowired field).}} + private RequestBean1 requestBean1; // Noncompliant {{Don't auto-wire this non-Singleton bean into a Singleton bean (autowired field).}} +// ^^^^^^^^^^^^ @Autowired private PrototypeBean1 prototypeBean1; // Noncompliant @Autowired @@ -24,8 +25,9 @@ public class SingletonBean { @Autowired private PrototypeBean3 prototypeBean3; // Noncompliant - @Autowired // Noncompliant@+1 - public SingletonBean(RequestBean1 requestBean1) { // Noncompliant, [[sc=26;ec=38]] {{Don't auto-wire this non-Singleton bean into a Singleton bean (autowired constructor).}} + @Autowired + public SingletonBean(RequestBean1 requestBean1) { // Noncompliant 2 +// ^^^^^^^^^^^^ } @Autowired // Noncompliant@+1 @@ -40,11 +42,13 @@ public SingletonBean(RequestBean1 requestBean1, // Noncompliant } @Autowired - public void setRequestBean1(RequestBean1 requestBean1) { // Noncompliant, [[sc=33;ec=45]] {{Don't auto-wire this non-Singleton bean into a Singleton bean (autowired setter method).}} + public void setRequestBean1(RequestBean1 requestBean1) { // Noncompliant {{Don't auto-wire this non-Singleton bean into a Singleton bean (autowired setter method).}} +// ^^^^^^^^^^^^ this.requestBean1 = requestBean1; } - public void setPrototypeBean1(@Autowired PrototypeBean1 prototypeBean1) { // Noncompliant, [[sc=46;ec=60]] {{Don't auto-wire this non-Singleton bean into a Singleton bean (autowired parameter).}} + public void setPrototypeBean1(@Autowired PrototypeBean1 prototypeBean1) { // Noncompliant {{Don't auto-wire this non-Singleton bean into a Singleton bean (autowired parameter).}} +// ^^^^^^^^^^^^^^ this.prototypeBean1 = prototypeBean1; } @@ -72,7 +76,7 @@ private SingletonBean2(@Autowired SingletonBean singletonBean) {// Compliant, si this.singletonBean = singletonBean; } - @Autowired // Noncompliant@+1 + @Autowired // Noncompliant@+1 public SingletonBean2(RequestBean1 requestBean1) { // Noncompliant this.requestBean1 = requestBean1; } @@ -87,9 +91,9 @@ public class SingletonBean3 { @Autowired private PrototypeBean1 prototypeBean1; // Noncompliant - // Noncompliant@+2 Autowired constructor - @Autowired // Noncompliant@+1 Autowired constructor parameter - public SingletonBean3(@Autowired RequestBean1 requestBean1) { // Noncompliant, single parameter constructor + // Noncompliant@+2 + @Autowired // Noncompliant@+1 + public SingletonBean3(@Autowired RequestBean1 requestBean1) { // Noncompliant } } diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/NullableInjectedFieldsHaveDefaultValueSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/NullableInjectedFieldsHaveDefaultValueSample.java index e081e76619c..03b81bc499e 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/NullableInjectedFieldsHaveDefaultValueSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/NullableInjectedFieldsHaveDefaultValueSample.java @@ -6,10 +6,10 @@ public class NullableInjectedFieldsHaveDefaultValueSample { @Nullable - @Value("${my.property}") // Noncompliant [[sc=3;ec=27;secondary=-1]] {{Provide a default null value for this field.}} + @Value("${my.property}") // Noncompliant {{Provide a default null value for this field.}} [[sc=3;ec=27;secondary=-1]] private String myProperty; - @Value("${my.property}") // Noncompliant [[sc=3;ec=27;secondary=+1]] {{Provide a default null value for this field.}} + @Value("${my.property}") // Noncompliant {{Provide a default null value for this field.}} [[sc=3;ec=27;secondary=+1]] @Nullable private String myPropertyWithReversedAnnotations; @@ -29,11 +29,11 @@ public class NullableInjectedFieldsHaveDefaultValueSample { // fix@argumentfix {{Set null as default value}} // edit@argumentfix [[sc=18;ec=34]] {{"${my.property:#{null}}"}} - public void foo(@Nullable @Value("${my.property}") String argument) { // Noncompliant [[sc=29;ec=53;secondary=+0]] {{Provide a default null value for this parameter.}} + public void foo(@Nullable @Value("${my.property}") String argument) { // Noncompliant {{Provide a default null value for this parameter.}} [[sc=29;ec=53;secondary=+0]] /* Do something */ } - public void bar(@Value(value = "${my.property}") @Nullable String argument) { // Noncompliant [[sc=19;ec=51;secondary=+0]] {{Provide a default null value for this parameter.}} + public void bar(@Value(value = "${my.property}") @Nullable String argument) { // Noncompliant {{Provide a default null value for this parameter.}} [[sc=19;ec=51;secondary=+0]] /* Do something */ } diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/OptionalRestParametersShouldBeObjects.java b/java-checks-test-sources/default/src/main/java/checks/spring/OptionalRestParametersShouldBeObjects.java index 9e92b8aa737..bf8bc1568d6 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/OptionalRestParametersShouldBeObjects.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/OptionalRestParametersShouldBeObjects.java @@ -8,20 +8,25 @@ class OptionalRestParametersShouldBeObjects { @GetMapping(value = {"/article", "/article/{id}"}) - public Article getArticle(@PathVariable(required = false) int articleId, int unused) { // Noncompliant [[sc=29;ec=75]] {{Convert this optional parameter to an Object type.}} + public Article getArticle(@PathVariable(required = false) int articleId, int unused) { // Noncompliant {{Convert this optional parameter to an Object type.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ return new Article(articleId); } @GetMapping(value = {"/article", "/article/{id}"}) - public Article getArticleWithRequestParam(@RequestParam(required = false) int articleId, int unused) { // Noncompliant [[sc=45;ec=91]] {{Convert this optional parameter to an Object type.}} + public Article getArticleWithRequestParam(@RequestParam(required = false) int articleId, int unused) { // Noncompliant {{Convert this optional parameter to an Object type.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ return new Article(articleId); } @GetMapping(value = {"/article", "/article/{id}"}) public Article getArticle( - @PathVariable(required = false) float articleId, // Noncompliant [[sc=5;ec=53]] - @RequestParam(required = false) int someIssue, // Noncompliant [[sc=5;ec=51]] - @PathVariable(required = false) boolean anotherIssue // Noncompliant [[sc=5;ec=57]] + @PathVariable(required = false) float articleId, // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + @RequestParam(required = false) int someIssue, // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + @PathVariable(required = false) boolean anotherIssue // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ) { return new Article((int) (Math.floor(articleId))); } diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/PersistentEntityUsedAsRequestParameterCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/PersistentEntityUsedAsRequestParameterCheckSample.java index a156f1e60ec..c564cf02944 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/PersistentEntityUsedAsRequestParameterCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/PersistentEntityUsedAsRequestParameterCheckSample.java @@ -62,7 +62,8 @@ public void greet(@org.springframework.security.core.annotation.AuthenticationPr } @RequestMapping(path = "/foo", method = RequestMethod.POST) - public void foo1(Foo foo) { // Noncompliant [[sc=26;ec=29]] {{Replace this persistent entity with a simple POJO or DTO object.}} + public void foo1(Foo foo) { // Noncompliant {{Replace this persistent entity with a simple POJO or DTO object.}} +// ^^^ } @GetMapping diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/RequestMappingMethodPublicCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/RequestMappingMethodPublicCheckSample.java index f7c7fa34a3b..fb4b3dc8ee0 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/RequestMappingMethodPublicCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/RequestMappingMethodPublicCheckSample.java @@ -19,10 +19,11 @@ class S3751_HelloWorld { public String hello(String greetee) { return ""; } // Compliant @RequestMapping(value = "/greet", method = GET) - private String greet(String greetee) { return ""; } // Noncompliant [[sc=18;ec=23]] {{Make this method non "private".}} + private String greet(String greetee) { return ""; } // Noncompliant {{Make this method non "private".}} +// ^^^^^ @GetMapping public String a() { return ""; } - @GetMapping private String a1() { return ""; } // Noncompliant + @GetMapping private String a1() { return ""; } // Noncompliant @PostMapping public String b() { return ""; } @PostMapping private String b1() { return ""; } // Noncompliant @PutMapping public String c() { return ""; } @@ -43,10 +44,11 @@ class S3751_Foo { public String hello(String greetee) { return ""; }// Compliant @RequestMapping(value = "/greet", method = GET) - private String greet(String greetee) { return ""; } // Noncompliant [[sc=18;ec=23]] {{Make this method non "private".}} + private String greet(String greetee) { return ""; } // Noncompliant {{Make this method non "private".}} +// ^^^^^ @GetMapping public String a() { return ""; } - @GetMapping private String a1() { return ""; } // Noncompliant + @GetMapping private String a1() { return ""; } // Noncompliant @PostMapping public String b() { return ""; } @PostMapping private String b1() { return ""; } // Noncompliant @PutMapping public String c() { return ""; } diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/SpelExpressionCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/SpelExpressionCheckSample.java index 69784d16eb1..5fa93a51162 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/SpelExpressionCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/SpelExpressionCheckSample.java @@ -14,31 +14,40 @@ public class SpelExpressionCheckSample { private static final String INVALID_PROPERTY_PLACEHOLDER = "${foo.bar[}"; private static final String VALID_PROPERTY_PLACEHOLDER = "${foo.bar}"; - @Value(UNCLOSED) // Noncompliant [[sc=10;ec=18]] {{Add missing '}' for this property placeholder or SpEL expression.}} + @Value(UNCLOSED) // Noncompliant {{Add missing '}' for this property placeholder or SpEL expression.}} +// ^^^^^^^^ private String complexArgument1; - @Value(INVALID_SPEL) // Noncompliant [[sc=10;ec=22]] {{Correct this malformed SpEL expression.}} + @Value(INVALID_SPEL) // Noncompliant {{Correct this malformed SpEL expression.}} +// ^^^^^^^^^^^^ private String complexArgument2; - @Value(INVALID_PROPERTY_PLACEHOLDER) // Noncompliant [[sc=10;ec=38]] {{Correct this malformed property placeholder.}} + @Value(INVALID_PROPERTY_PLACEHOLDER) // Noncompliant {{Correct this malformed property placeholder.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ private String complexArgument3; - @Value(value = UNCLOSED) // Noncompliant [[sc=18;ec=26]] {{Add missing '}' for this property placeholder or SpEL expression.}} + @Value(value = UNCLOSED) // Noncompliant {{Add missing '}' for this property placeholder or SpEL expression.}} +// ^^^^^^^^ private String complexArgument4; - @Value(value = INVALID_SPEL) // Noncompliant [[sc=18;ec=30]] {{Correct this malformed SpEL expression.}} + @Value(value = INVALID_SPEL) // Noncompliant {{Correct this malformed SpEL expression.}} +// ^^^^^^^^^^^^ private String complexArgument5; - @Value(value = INVALID_PROPERTY_PLACEHOLDER) // Noncompliant [[sc=18;ec=46]] {{Correct this malformed property placeholder.}} + @Value(value = INVALID_PROPERTY_PLACEHOLDER) // Noncompliant {{Correct this malformed property placeholder.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ private String complexArgument6; - @Value(value = "${1 + 2 + 3") // Noncompliant [[sc=19;ec=30]] {{Add missing '}' for this property placeholder or SpEL expression.}} + @Value(value = "${1 + 2 + 3") // Noncompliant {{Add missing '}' for this property placeholder or SpEL expression.}} +// ^^^^^^^^^^^ private String complexArgument7; - @Value(value = "#{1 * * 2}") // Noncompliant [[sc=19;ec=29]] {{Correct this malformed SpEL expression.}} + @Value(value = "#{1 * * 2}") // Noncompliant {{Correct this malformed SpEL expression.}} +// ^^^^^^^^^^ private String complexArgument8; - @Value(value = "${foo.bar[}") // Noncompliant [[sc=19;ec=30]] {{Correct this malformed property placeholder.}} + @Value(value = "${foo.bar[}") // Noncompliant {{Correct this malformed property placeholder.}} +// ^^^^^^^^^^^ private String complexArgument9; @Value(value = "#{1 + 2 + 3}") // Compliant @@ -47,7 +56,8 @@ public class SpelExpressionCheckSample { @Value(value = VALID_PROPERTY_PLACEHOLDER) // Compliant private String complexArgument11; - @Value("#{systemProperties['user.region'}") // Noncompliant [[sc=11;ec=44]] {{Correct this malformed SpEL expression.}} + @Value("#{systemProperties['user.region'}") // Noncompliant {{Correct this malformed SpEL expression.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ private String region1; @Value("#{systemProperties['user.region']}") // Compliant @@ -83,7 +93,8 @@ public class SpelExpressionCheckSample { @Value("${user.region:#{ null + 3 }}") // Compliant private String default8; - @Value("${user.region:#{ null + * 3 }}") // Noncompliant [[sc=25;ec=41]] {{Correct this malformed SpEL expression.}} + @Value("${user.region:#{ null + * 3 }}") // Noncompliant {{Correct this malformed SpEL expression.}} +// ^^^^^^^^^^^^^^^^ private String default9; @Value("${user.region:#{'D'+'E'}}") // Compliant @@ -92,10 +103,12 @@ public class SpelExpressionCheckSample { @Value("${user.region:#{null}:#{null}:foo.bar}") // Noncompliant private String default11; - @Value("${user.region:#{null}:#{4**4}:foo.bar}") // Noncompliant [[sc=11;ec=49]] {{Correct this malformed property placeholder.}} + @Value("${user.region:#{null}:#{4**4}:foo.bar}") // Noncompliant {{Correct this malformed property placeholder.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ private String default12; - @Value("${user.region:#{4**4}:#{null}:foo.bar}") // Noncompliant [[sc=25;ec=32]] {{Correct this malformed SpEL expression.}} + @Value("${user.region:#{4**4}:#{null}:foo.bar}") // Noncompliant {{Correct this malformed SpEL expression.}} +// ^^^^^^^ private String default13; @Value("${user.2region:default-region}") // Compliant @@ -119,13 +132,15 @@ public class SpelExpressionCheckSample { @Value("${server.error.path:${error.path:defaultErrorValue}}") // Compliant private String nestedPropertyValue2; - @Value("#{'${listOfValues}' split(',')}") // Noncompliant [[sc=11;ec=42]] {{Correct this malformed SpEL expression.}} + @Value("#{'${listOfValues}' split(',')}") // Noncompliant {{Correct this malformed SpEL expression.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ private List valuesListNc; @Value("#{'${listOfValues}'.split(',')}") // Compliant private List valuesListC; - @Value("#{T(java.lang.Math).random() * 64h}") // Noncompliant [[sc=11;ec=46]] {{Correct this malformed SpEL expression.}} + @Value("#{T(java.lang.Math).random() * 64h}") // Noncompliant {{Correct this malformed SpEL expression.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ private Double randPercentNc; @Value("#{T(java.lang.Math).random() * 100.0}") // Compliant @@ -145,10 +160,12 @@ interface Repo { @Query("select u from User u where u.age = ?#{[0]}") // Compliant List findUsersByAge1(int age); - @Query("select u from User u where u.age = ?#{[0}") // Noncompliant [[sc=49;ec=54]] + @Query("select u from User u where u.age = ?#{[0}") // Noncompliant +// ^^^^^ List findUsersByAge2(int age); - @Query("select u from User u where u.age = ?#{[0]") // Noncompliant [[sc=49;ec=54]] {{Add missing '}' for this property placeholder or SpEL expression.}} + @Query("select u from User u where u.age = ?#{[0]") // Noncompliant {{Add missing '}' for this property placeholder or SpEL expression.}} +// ^^^^^ List findUsersByAge3(int age); @Query("select u from User u where u.age = ?#{[0*]}") // Noncompliant @@ -163,19 +180,19 @@ interface Repo { @Query("select u from User u where u.name = :#{#customer.name} and u.firstname = :#{#customer.firstname}") // Compliant List findUsersByCustomersFullName1(@Param("customer") Customer customer); - @Query("select u from User u where u.name = :#{#customer.name} and u.firstname = :#{#customer.firstname") // Noncompliant {{Add missing '}' for this property placeholder or SpEL expression.}} + @Query("select u from User u where u.name = :#{#customer.name} and u.firstname = :#{#customer.firstname") // Noncompliant {{Add missing '}' for this property placeholder or SpEL expression.}} List findUsersByCustomersFullName2(@Param("customer") Customer customer); - @Query("select u from User u where u.name = :#{#customer.name and u.firstname = :#{#customer.firstname}") // Noncompliant {{Add missing '}' for this property placeholder or SpEL expression.}} + @Query("select u from User u where u.name = :#{#customer.name and u.firstname = :#{#customer.firstname}") // Noncompliant {{Add missing '}' for this property placeholder or SpEL expression.}} List findUsersByCustomersFullName3(@Param("customer") Customer customer); - @Query("select u from User u where u.name = :#{#customer.name and u.firstname} = :#{#*customer.firstname}") // Noncompliant {{Correct this malformed SpEL expression.}} + @Query("select u from User u where u.name = :#{#customer.name and u.firstname} = :#{#*customer.firstname}") // Noncompliant {{Correct this malformed SpEL expression.}} List findUsersByCustomersFullName4(@Param("customer") Customer customer); @Query("select u from User u where u.firstname = :#{#customer.firstname} and u.role=${admin}") // Compliant List findAdminUsersByFirstname1(@Param("customer") Customer customer); - @Query("select u from User u where u.firstname = :#{#customer.firstname} and u.role=${admin") // Noncompliant + @Query("select u from User u where u.firstname = :#{#customer.firstname} and u.role=${admin") // Noncompliant List findAdminUsersByFirstname2(@Param("customer") Customer customer); } @@ -184,7 +201,8 @@ interface Repo { public static class RequestController1 { } @Controller - @RequestMapping("#{1+2+}") // Noncompliant [[sc=20;ec=27]] + @RequestMapping("#{1+2+}") // Noncompliant +// ^^^^^^^ public static class RequestController2 { } @Value("foo") // Compliant @@ -232,7 +250,8 @@ public static class RequestController2 { } @Value("$foo") // Compliant String delimiters8; - @Value("${}") // Noncompliant [[sc=11;ec=14]] + @Value("${}") // Noncompliant +// ^^^ String delimiters9; @Value("${123") // Noncompliant @@ -256,10 +275,10 @@ public static class RequestController2 { } @Value("#{{123}") // Noncompliant String delimiters16; - @Value("#{12{}3}") // Noncompliant, open + @Value("#{12{}3}") // Noncompliant String delimiters17; - @Value("#{{12}3{}") // Noncompliant, open + @Value("#{{12}3{}") // Noncompliant String delimiters18; @Value("#{{12}3{4{5}6}") // Noncompliant @@ -274,13 +293,16 @@ public static class RequestController2 { } @Value("#{ }") // Noncompliant String delimiters22; - @Value("${") // Noncompliant [[sc=11;ec=13]] + @Value("${") // Noncompliant +// ^^ String delimiters23; - @Value("${ ") // Noncompliant [[sc=11;ec=14]] + @Value("${ ") // Noncompliant +// ^^^ String delimiters24; - @Value("#{ ") // Noncompliant [[sc=11;ec=14]] + @Value("#{ ") // Noncompliant +// ^^^ String delimiters25; @Value("#{ " + "") // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/SpringAntMatcherOrderCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/SpringAntMatcherOrderCheckSample.java index 02a88af2c9d..712815ecfbc 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/SpringAntMatcherOrderCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/SpringAntMatcherOrderCheckSample.java @@ -11,12 +11,16 @@ protected void configure(HttpSecurity http, String dynamicUrl) throws Exception http .authorizeRequests() .antMatchers("/login/*me").permitAll() +// ^^^^^^^^^^^^> .antMatchers("/login/admin").hasRole("ADMIN") - .antMatchers("/login/home").permitAll() // Noncompliant [[sc=22;ec=35;secondary=-2]] {{Reorder the URL patterns from most to less specific, the pattern "/login/home" should occurs before "/login/*me".}} + .antMatchers("/login/home").permitAll() // Noncompliant {{Reorder the URL patterns from most to less specific, the pattern "/login/home" should occurs before "/login/*me".}} +// ^^^^^^^^^^^^^ .antMatchers( "/lo?in", +// ^^^^^^^^> dynamicUrl, - "/login" // Noncompliant [[sc=11;ec=19;secondary=-2]] {{Reorder the URL patterns from most to less specific, the pattern "/login" should occurs before "/lo?in".}} + "/login" // Noncompliant {{Reorder the URL patterns from most to less specific, the pattern "/login" should occurs before "/lo?in".}} +// ^^^^^^^^ ).permitAll(); http @@ -37,7 +41,7 @@ protected void configure(HttpSecurity http, String dynamicUrl) throws Exception .and() .antMatcher("/root2") .authorizeRequests() - .antMatchers("/level1").permitAll(); // Noncompliant: TODO investigate + .antMatchers("/level1").permitAll(); // Noncompliant http .antMatcher("/root1") @@ -48,7 +52,9 @@ protected void configure(HttpSecurity http, String dynamicUrl) throws Exception http .authorizeRequests() .antMatchers("/", "/index", "/secured/*/**", "/authenticate").permitAll() - .antMatchers("/secured/*/index", "/secured/socket", "/secured/success").authenticated() // Noncompliant [[sc=22;ec=40;secondary=-1]] {{Reorder the URL patterns from most to less specific, the pattern "/secured/*/index" should occurs before "/secured/*/**".}} +// ^^^^^^^^^^^^^^^> + .antMatchers("/secured/*/index", "/secured/socket", "/secured/success").authenticated() // Noncompliant {{Reorder the URL patterns from most to less specific, the pattern "/secured/*/index" should occurs before "/secured/*/**".}} +// ^^^^^^^^^^^^^^^^^^ .anyRequest().authenticated(); ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry authorizeRequests = http.authorizeRequests(); diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/SpringBeanNamingConventionCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/SpringBeanNamingConventionCheckSample.java index 9f117916af3..9413ad4a96c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/SpringBeanNamingConventionCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/SpringBeanNamingConventionCheckSample.java @@ -21,7 +21,8 @@ void NO_camel_case() {} public class SpringBeanNamingConventionCheckSample { - @Bean("my_bean") // Noncompliant [[sc=9;ec=18]] {{Rename this bean to match the regular expression '^[a-z][a-zA-Z0-9]*$'.}} + @Bean("my_bean") // Noncompliant {{Rename this bean to match the regular expression '^[a-z][a-zA-Z0-9]*$'.}} +// ^^^^^^^^^ SomeTestClass myBean1() { return null; } @@ -31,7 +32,8 @@ SomeTestClass myBean2() { return null; } - @Bean(autowire = Autowire.NO, initMethod = "toString", name = "my_bean", destroyMethod = "toString") // Noncompliant [[sc=58;ec=74]] + @Bean(autowire = Autowire.NO, initMethod = "toString", name = "my_bean", destroyMethod = "toString") // Noncompliant +// ^^^^^^^^^^^^^^^^ SomeTestClass myBean3() { return null; } diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/SpringConfigurationWithAutowiredFieldsCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/SpringConfigurationWithAutowiredFieldsCheckSample.java index 42e6275a51e..bb1371ae9d8 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/SpringConfigurationWithAutowiredFieldsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/SpringConfigurationWithAutowiredFieldsCheckSample.java @@ -15,8 +15,10 @@ class Foo { @Configuration class A { - @Autowired private Bar singleUsage; // Noncompliant [[sc=28;ec=39]] {{Inject this field value directly into "method", the only method that uses it.}} - @Inject private Bar jsr330; // Noncompliant [[sc=25;ec=31]] {{Inject this field value directly into "jsr330", the only method that uses it.}} + @Autowired private Bar singleUsage; // Noncompliant {{Inject this field value directly into "method", the only method that uses it.}} +// ^^^^^^^^^^^ + @Inject private Bar jsr330; // Noncompliant {{Inject this field value directly into "jsr330", the only method that uses it.}} +// ^^^^^^ @Autowired private Bar multipleUsage; @Autowired private Bar notUsedInBeanMethod; @Autowired private Bar notUsed; diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/SpringIncompatibleTransactionalCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/SpringIncompatibleTransactionalCheckSample.java index ae69a96342a..2a707080999 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/SpringIncompatibleTransactionalCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/SpringIncompatibleTransactionalCheckSample.java @@ -12,6 +12,7 @@ public class SpringIncompatibleTransactionalCheckSample { @Transactional public void springTransactionalDefault() { +// ^^^^^^^^^^^^^^^^^^^^^^^^^^> } @Transactional @@ -19,12 +20,13 @@ public static void unexpectedStaticMethodAnnotatedWithTransactional() { } public void nonTransactional() { - springTransactionalDefault(); // Noncompliant [[sc=5;ec=31;secondary=14]] {{"springTransactionalDefault's" @Transactional requirement is incompatible with the one for this method.}} + springTransactionalDefault(); // Noncompliant {{"springTransactionalDefault's" @Transactional requirement is incompatible with the one for this method.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^ unexpectedStaticMethodAnnotatedWithTransactional(); // ignore static methods, Spring does not support @Transactional on static methods. other.springTransactionalDefault(); getOther().springTransactionalDefault(); - this.springTransactionalDefault(); // Noncompliant + this.springTransactionalDefault(); // Noncompliant equals(other); this.equals(other); @@ -40,13 +42,13 @@ class SpringIncompatibleTransactionalCheckSampleIncompatibilityMatrix { public void nonTransactional() { nonTransactional(); - transactional(); // Noncompliant - mandatory(); // Noncompliant - nested(); // Noncompliant + transactional(); // Noncompliant + mandatory(); // Noncompliant + nested(); // Noncompliant never(); notSupported(); - required(); // Noncompliant - requiresNew(); // Noncompliant + required(); // Noncompliant + requiresNew(); // Noncompliant supports(); } @@ -55,11 +57,11 @@ public void transactional() { nonTransactional(); transactional(); mandatory(); - nested(); // Noncompliant - never(); // Noncompliant + nested(); // Noncompliant + never(); // Noncompliant notSupported(); // Noncompliant required(); - requiresNew(); // Noncompliant + requiresNew(); // Noncompliant supports(); } @@ -68,11 +70,11 @@ public void transactionalOtherProperty() { nonTransactional(); transactional(); mandatory(); - nested(); // Noncompliant - never(); // Noncompliant + nested(); // Noncompliant + never(); // Noncompliant notSupported(); // Noncompliant required(); - requiresNew(); // Noncompliant + requiresNew(); // Noncompliant supports(); } @@ -81,11 +83,11 @@ public void mandatory() { nonTransactional(); transactional(); mandatory(); - nested(); // Noncompliant - never(); // Noncompliant + nested(); // Noncompliant + never(); // Noncompliant notSupported(); // Noncompliant required(); - requiresNew(); // Noncompliant + requiresNew(); // Noncompliant supports(); } @@ -94,11 +96,11 @@ public void nested() { nonTransactional(); transactional(); mandatory(); - nested(); // Noncompliant - never(); // Noncompliant + nested(); // Noncompliant + never(); // Noncompliant notSupported(); // Noncompliant required(); - requiresNew(); // Noncompliant + requiresNew(); // Noncompliant supports(); } @@ -106,12 +108,12 @@ public void nested() { public void never() { nonTransactional(); transactional(); // Noncompliant - mandatory(); // Noncompliant - nested(); // Noncompliant + mandatory(); // Noncompliant + nested(); // Noncompliant never(); notSupported(); - required(); // Noncompliant - requiresNew(); // Noncompliant + required(); // Noncompliant + requiresNew(); // Noncompliant supports(); } @@ -119,12 +121,12 @@ public void never() { public void notSupported() { nonTransactional(); transactional(); // Noncompliant - mandatory(); // Noncompliant - nested(); // Noncompliant + mandatory(); // Noncompliant + nested(); // Noncompliant never(); notSupported(); - required(); // Noncompliant - requiresNew(); // Noncompliant + required(); // Noncompliant + requiresNew(); // Noncompliant supports(); } @@ -133,11 +135,11 @@ public void required() { nonTransactional(); transactional(); mandatory(); - nested(); // Noncompliant - never(); // Noncompliant + nested(); // Noncompliant + never(); // Noncompliant notSupported(); // Noncompliant required(); - requiresNew(); // Noncompliant + requiresNew(); // Noncompliant supports(); } @@ -146,11 +148,11 @@ public void requiresNew() { nonTransactional(); transactional(); mandatory(); - nested(); // Noncompliant - never(); // Noncompliant + nested(); // Noncompliant + never(); // Noncompliant notSupported(); // Noncompliant required(); - requiresNew(); // Noncompliant + requiresNew(); // Noncompliant supports(); } @@ -158,12 +160,12 @@ public void requiresNew() { public void supports() { nonTransactional(); transactional(); // Noncompliant - mandatory(); // Noncompliant - nested(); // Noncompliant - never(); // Noncompliant - notSupported(); // Noncompliant - required(); // Noncompliant - requiresNew(); // Noncompliant + mandatory(); // Noncompliant + nested(); // Noncompliant + never(); // Noncompliant + notSupported(); // Noncompliant + required(); // Noncompliant + requiresNew(); // Noncompliant supports(); } @@ -173,8 +175,8 @@ class SpringIncompatibleTransactionalCheckSampleSupportJavaxTransactional { public void nonTransactional() { - javaxTransactionalDefault(); // Noncompliant - javaxTransactionalRequired(); // Noncompliant + javaxTransactionalDefault(); // Noncompliant + javaxTransactionalRequired(); // Noncompliant javaxTransactionalNotSupported(); javaxTransactionalNever(); } diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/SpringRequestMappingMethodCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/SpringRequestMappingMethodCheckSample.java index 1f35057d5bd..0aee205f6d8 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/SpringRequestMappingMethodCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/SpringRequestMappingMethodCheckSample.java @@ -10,7 +10,8 @@ @RequestMapping("/home") public class SpringRequestMappingMethodCheckSample { - @RequestMapping("/") // Noncompliant [[sc=4;ec=18]] {{Make sure allowing safe and unsafe HTTP methods is safe here.}} + @RequestMapping("/") // Noncompliant {{Make sure allowing safe and unsafe HTTP methods is safe here.}} +// ^^^^^^^^^^^^^^ String home() { return "Hello from get"; } @@ -30,7 +31,8 @@ String get() { return "Hello from get"; } - @RequestMapping(path = "/delete", method = {RequestMethod.GET, RequestMethod.POST}) // Noncompliant [[sc=46;ec=85]] {{Make sure allowing safe and unsafe HTTP methods is safe here.}} + @RequestMapping(path = "/delete", method = {RequestMethod.GET, RequestMethod.POST}) // Noncompliant {{Make sure allowing safe and unsafe HTTP methods is safe here.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ String delete(@RequestParam("id") String id) { return "Hello from delete"; } diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/SpringSecurityDisableCSRFCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/SpringSecurityDisableCSRFCheckSample.java index b6860d1a514..4b411e1df3f 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/SpringSecurityDisableCSRFCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/SpringSecurityDisableCSRFCheckSample.java @@ -17,7 +17,8 @@ public class SpringSecurityDisableCSRFCheckSample extends WebSecurityConfigurerA @Override protected void configure(HttpSecurity http) throws Exception { - http.csrf().disable(); // Noncompliant [[sc=17;ec=24]] {{Make sure disabling Spring Security's CSRF protection is safe here.}} + http.csrf().disable(); // Noncompliant {{Make sure disabling Spring Security's CSRF protection is safe here.}} +// ^^^^^^^ http.csrf().getClass(); http @@ -31,9 +32,11 @@ protected void configure(HttpSecurity http) throws Exception { LogoutConfigurer logout = http.logout(); logout.disable(); - http.csrf().ignoringAntMatchers("/ignored/path"); // Noncompliant [[sc=17;ec=36]] {{Make sure disabling Spring Security's CSRF protection is safe here.}} + http.csrf().ignoringAntMatchers("/ignored/path"); // Noncompliant {{Make sure disabling Spring Security's CSRF protection is safe here.}} +// ^^^^^^^^^^^^^^^^^^^ CsrfConfigurer csrf2 = http.csrf(); - csrf2.ignoringAntMatchers("/ignored/path"); // Noncompliant [[sc=11;ec=30]] {{Make sure disabling Spring Security's CSRF protection is safe here.}} + csrf2.ignoringAntMatchers("/ignored/path"); // Noncompliant {{Make sure disabling Spring Security's CSRF protection is safe here.}} +// ^^^^^^^^^^^^^^^^^^^ } @Configuration @@ -44,9 +47,9 @@ public SecurityFilterChain filterChainCSRF(HttpSecurity http) throws Exception { RequestMatcher requestMatcherWhitelist = (HttpServletRequest request) -> request.getRequestURI().contains("whitelist"); RequestMatcher requestMatcherBlacklist = (HttpServletRequest request) -> request.getRequestURI().contains("blacklist"); - http.csrf(csrf -> csrf.requireCsrfProtectionMatcher(requestMatcherWhitelist)); // Noncompliant - http.csrf(csrf -> csrf.ignoringRequestMatchers(requestMatcherBlacklist)); // Noncompliant - http.csrf(csrf -> csrf.ignoringRequestMatchers("/S4502CSRFSpecial")); // Noncompliant + http.csrf(csrf -> csrf.requireCsrfProtectionMatcher(requestMatcherWhitelist)); // Noncompliant + http.csrf(csrf -> csrf.ignoringRequestMatchers(requestMatcherBlacklist)); // Noncompliant + http.csrf(csrf -> csrf.ignoringRequestMatchers("/S4502CSRFSpecial")); // Noncompliant http.csrf(csrf -> csrf.ignoringAntMatchers("/ignored/path")); // Noncompliant http.csrf(AbstractHttpConfigurer::disable); // Noncompliant http.csrf(csrf -> csrf.disable()); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/SpringSessionFixationCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/SpringSessionFixationCheckSample.java index abf3b5f856e..6241a6a75b4 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/SpringSessionFixationCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/SpringSessionFixationCheckSample.java @@ -16,7 +16,8 @@ protected void configure(HttpSecurity http) throws Exception { http.sessionManagement() .sessionFixation() - .none(); // Noncompliant [[sc=12;ec=16]] {{Create a new session during user authentication to prevent session fixation attacks.}} + .none(); // Noncompliant {{Create a new session during user authentication to prevent session fixation attacks.}} +// ^^^^ http.sessionManagement() .sessionFixation() @@ -25,10 +26,14 @@ protected void configure(HttpSecurity http) throws Exception { } public SecurityFilterChain filterChainSessionFixation(HttpSecurity http) throws Exception { - // Noncompliant@+1 [[sc=126;ec=130]] {{Create a new session during user authentication to prevent session fixation attacks.}} + + // Noncompliant@+1 {{Create a new session during user authentication to prevent session fixation attacks.}} http.sessionManagement(sessionConfigurer -> sessionConfigurer.sessionFixation(fixationConfigurer -> fixationConfigurer.none())); - // Noncompliant@+1 [[sc=140;ec=144]] {{Create a new session during user authentication to prevent session fixation attacks.}} +// ^^^^ + + // Noncompliant@+1 {{Create a new session during user authentication to prevent session fixation attacks.}} http.sessionManagement(sessionConfigurer -> sessionConfigurer.sessionFixation(SessionManagementConfigurer.SessionFixationConfigurer::none)); +// ^^^^ return http.build(); } diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/StatusCodesOnResponseCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/StatusCodesOnResponseCheckSample.java index 777f5effe68..e16287c6cd4 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/StatusCodesOnResponseCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/StatusCodesOnResponseCheckSample.java @@ -75,9 +75,11 @@ public ResponseEntity boo() { public ResponseEntity getUserNoncompliant() { try { - return ResponseEntity.status(INTERNAL_SERVER_ERROR).body(new User()); // Noncompliant [[sc=16;ec=60]] {{Set a HttpStatus code reflective of the operation.}} + return ResponseEntity.status(INTERNAL_SERVER_ERROR).body(new User()); // Noncompliant {{Set a HttpStatus code reflective of the operation.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } catch (NotFoundException e) { - return ResponseEntity.status(OK).build(); // Noncompliant [[sc=16;ec=41]] {{Set a HttpStatus code reflective of the operation.}} + return ResponseEntity.status(OK).build(); // Noncompliant {{Set a HttpStatus code reflective of the operation.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^ } catch (Exception e) { return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); // Compliant } @@ -85,7 +87,8 @@ public ResponseEntity getUserNoncompliant() { public ResponseEntity getUserNoncompliant2() { try { - return ResponseEntity.badRequest().build(); // Noncompliant [[sc=16;ec=43]] {{Set a HttpStatus code reflective of the operation.}} + return ResponseEntity.badRequest().build(); // Noncompliant {{Set a HttpStatus code reflective of the operation.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ } catch (NotFoundException e) { return ResponseEntity.ok().build(); // Noncompliant } catch (Exception e) { diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/SuperfluousResponseBodyAnnotationCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/SuperfluousResponseBodyAnnotationCheckSample.java index 9086616dd12..49bd173f56e 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/SuperfluousResponseBodyAnnotationCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/SuperfluousResponseBodyAnnotationCheckSample.java @@ -7,7 +7,8 @@ @RestController public class SuperfluousResponseBodyAnnotationCheckSample { - @ResponseBody // Noncompliant [[sc=3;ec=16]] {{Remove this superfluous "@ResponseBody" annotation.}} + @ResponseBody // Noncompliant {{Remove this superfluous "@ResponseBody" annotation.}} +//^^^^^^^^^^^^^ @GetMapping("foo") public String get() { return "Hello world!"; diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/TransactionalMethodVisibilityCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/TransactionalMethodVisibilityCheckSample.java index f7274074945..bf8ec724c73 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/TransactionalMethodVisibilityCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/TransactionalMethodVisibilityCheckSample.java @@ -39,8 +39,9 @@ private Future asyncMethodPrivate(){ // Noncompliant {{Make this method public void publicTransactionalMethod() {} // Compliant @org.springframework.transaction.annotation.Transactional - protected void protectedTransactionalMethod() {} // Noncompliant [[sc=18;ec=46]] {{Make this method "public" or remove the "@Transactional" annotation.}} + protected void protectedTransactionalMethod() {} // Noncompliant {{Make this method "public" or remove the "@Transactional" annotation.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @org.springframework.transaction.annotation.Transactional - void defaultVisibilityTransactionalMethod() {} // Noncompliant {{Make this method "public" or remove the "@Transactional" annotation.}} + void defaultVisibilityTransactionalMethod() {} // Noncompliant {{Make this method "public" or remove the "@Transactional" annotation.}} } diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/ValueAnnotationShouldInjectPropertyOrSpELCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/spring/ValueAnnotationShouldInjectPropertyOrSpELCheckSample.java index 87742fb15f9..92122a40c2f 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/ValueAnnotationShouldInjectPropertyOrSpELCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/ValueAnnotationShouldInjectPropertyOrSpELCheckSample.java @@ -7,32 +7,35 @@ class ValueAnnotationShouldInjectPropertyOrSpELCheckSample { private static final String COMPLIANT_CONSTANT = "${catalog.name}"; private static final String NON_COMPLIANT_CONSTANT = "catalog.name"; - @Value("catalog.name") // Noncompliant [[sc=3;ec=25]] {{Either replace the "@Value" annotation with a standard field initialization, use "${propertyName}" to inject a property or use "#{expression}" to evaluate a SpEL expression.}} + @Value("catalog.name") // Noncompliant {{Either replace the "@Value" annotation with a standard field initialization, use "${propertyName}" to inject a property or use "#{expression}" to evaluate a SpEL expression.}} +//^^^^^^^^^^^^^^^^^^^^^^ String catalogA; @Value("${catalog.name}") // Compliant String catalogB; - @Value(value = "catalog.name") // Noncompliant [[sc=3;ec=33]] {{Either replace the "@Value" annotation with a standard field initialization, use "${propertyName}" to inject a property or use "#{expression}" to evaluate a SpEL expression.}} + @Value(value = "catalog.name") // Noncompliant {{Either replace the "@Value" annotation with a standard field initialization, use "${propertyName}" to inject a property or use "#{expression}" to evaluate a SpEL expression.}} +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ String catalogWithNamedArgumentA; @Value(value = "${catalog.name}") // Compliant String catalogWithNamedArgumentB; - @Value(value = NON_COMPLIANT_CONSTANT) // Noncompliant [[sc=3;ec=41]] + @Value(value = NON_COMPLIANT_CONSTANT) // Noncompliant +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ String catalogWithNamedArgumentC; @Value(value = COMPLIANT_CONSTANT) // Compliant String catalogWithNamedArgumentD; - @Value("book.topics[0]") // Noncompliant, this will not evaluate the expression + @Value("book.topics[0]") // Noncompliant String topicA; @Value("#{book.topics[0]}") // Compliant String topicB; - @Value("Hello, world!") // Noncompliant, this use of @Value is redundant + @Value("Hello, world!") // Noncompliant String greetingA; diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/s4605/componentScan/ComponentScan.java b/java-checks-test-sources/default/src/main/java/checks/spring/s4605/componentScan/ComponentScan.java index 665c76b6858..83bd7cd1832 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/s4605/componentScan/ComponentScan.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/s4605/componentScan/ComponentScan.java @@ -37,7 +37,8 @@ class Foo7 { } @Component -class Bar1 { } // Noncompliant [[sc=7;ec=11]] {{'Bar1' is not reachable by @ComponentScan or @SpringBootApplication. Either move it to a package configured in @ComponentScan or update your @ComponentScan configuration.}} +class Bar1 { } // Noncompliant {{'Bar1' is not reachable by @ComponentScan or @SpringBootApplication. Either move it to a package configured in @ComponentScan or update your @ComponentScan configuration.}} +// ^^^^ @Service class Bar2 { } // Noncompliant @@ -46,7 +47,7 @@ class Bar2 { } // Noncompliant class Bar3 { } // Noncompliant @RestController -class Bar4 { } // Noncompliant, we ignore basePackageClasses +class Bar4 { } // Noncompliant @Configuration class Bar5 { } // ignored annotation diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/s4605/componentScan/packageC/ComponentC.java b/java-checks-test-sources/default/src/main/java/checks/spring/s4605/componentScan/packageC/ComponentC.java index cecf88cdb75..375d956fc56 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/s4605/componentScan/packageC/ComponentC.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/s4605/componentScan/packageC/ComponentC.java @@ -7,7 +7,8 @@ import org.springframework.web.bind.annotation.RestController; @Component -class ComponentC {} // Noncompliant [[sc=7;ec=17]] {{'ComponentC' is not reachable by @ComponentScan or @SpringBootApplication. Either move it to a package configured in @ComponentScan or update your @ComponentScan configuration.}} +class ComponentC {} // Noncompliant {{'ComponentC' is not reachable by @ComponentScan or @SpringBootApplication. Either move it to a package configured in @ComponentScan or update your @ComponentScan configuration.}} +// ^^^^^^^^^^ @Service class ComponentD {} // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/s4605/springBootApplication/Ko/Ko.java b/java-checks-test-sources/default/src/main/java/checks/spring/s4605/springBootApplication/Ko/Ko.java index 5c0400e5ba9..8cb6045adc4 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/s4605/springBootApplication/Ko/Ko.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/s4605/springBootApplication/Ko/Ko.java @@ -6,7 +6,8 @@ // Different from root package hierarchy @Component -class Ko1 {} // Noncompliant [[sc=7;ec=10]] {{'Ko1' is not reachable by @ComponentScan or @SpringBootApplication. Either move it to a package configured in @ComponentScan or update your @ComponentScan configuration.}} +class Ko1 {} // Noncompliant {{'Ko1' is not reachable by @ComponentScan or @SpringBootApplication. Either move it to a package configured in @ComponentScan or update your @ComponentScan configuration.}} +// ^^^ @Service class Ko2 {} // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/s4605/springBootApplication/fourthApp/controller/Controller.java b/java-checks-test-sources/default/src/main/java/checks/spring/s4605/springBootApplication/fourthApp/controller/Controller.java index 63098a26125..82c701255b9 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/s4605/springBootApplication/fourthApp/controller/Controller.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/s4605/springBootApplication/fourthApp/controller/Controller.java @@ -3,4 +3,5 @@ import org.springframework.web.bind.annotation.RestController; @RestController -public class Controller { } // Noncompliant [[sc=14;ec=24]] {{'Controller' is not reachable by @ComponentScan or @SpringBootApplication. Either move it to a package configured in @ComponentScan or update your @ComponentScan configuration.}} +public class Controller { } // Noncompliant {{'Controller' is not reachable by @ComponentScan or @SpringBootApplication. Either move it to a package configured in @ComponentScan or update your @ComponentScan configuration.}} +// ^^^^^^^^^^ diff --git a/java-checks-test-sources/default/src/main/java/checks/spring/s4605/springBootApplication/thirdApp/controller/Controller.java b/java-checks-test-sources/default/src/main/java/checks/spring/s4605/springBootApplication/thirdApp/controller/Controller.java index ceaf9104b11..d383081c159 100644 --- a/java-checks-test-sources/default/src/main/java/checks/spring/s4605/springBootApplication/thirdApp/controller/Controller.java +++ b/java-checks-test-sources/default/src/main/java/checks/spring/s4605/springBootApplication/thirdApp/controller/Controller.java @@ -3,4 +3,5 @@ import org.springframework.web.bind.annotation.RestController; @RestController -public class Controller { } // Noncompliant [[sc=14;ec=24]] {{'Controller' is not reachable by @ComponentScan or @SpringBootApplication. Either move it to a package configured in @ComponentScan or update your @ComponentScan configuration.}} +public class Controller { } // Noncompliant {{'Controller' is not reachable by @ComponentScan or @SpringBootApplication. Either move it to a package configured in @ComponentScan or update your @ComponentScan configuration.}} +// ^^^^^^^^^^ diff --git a/java-checks-test-sources/default/src/main/java/checks/sustainability/AndroidExactAlarmCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/sustainability/AndroidExactAlarmCheckSample.java index f750bc5912d..9804c97602c 100644 --- a/java-checks-test-sources/default/src/main/java/checks/sustainability/AndroidExactAlarmCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/sustainability/AndroidExactAlarmCheckSample.java @@ -8,7 +8,8 @@ public class AndroidExactAlarmCheckSample { public void setExact(AlarmManager alarmManager, PendingIntent operation) { - alarmManager.setExact(0, 1000, operation); // Noncompliant [[sc=18;ec=26]] {{Use "set" instead of "setExact".}} + alarmManager.setExact(0, 1000, operation); // Noncompliant {{Use "set" instead of "setExact".}} +// ^^^^^^^^ alarmManager.set(0, 1000, operation); // Compliant var noAlarmManager = new NoAlarmManager(); @@ -24,7 +25,8 @@ public void setExact(AlarmManager alarmManager, AlarmManager.OnAlarmListener lis } public void setExactAndAllowWhileIdle(AlarmManager alarmManager, PendingIntent operation) { - alarmManager.setExactAndAllowWhileIdle(0, 1000, operation); // Noncompliant [[sc=18;ec=43]] {{Use "setAndAllowWhileIdle" instead of "setExactAndAllowWhileIdle".}} + alarmManager.setExactAndAllowWhileIdle(0, 1000, operation); // Noncompliant {{Use "setAndAllowWhileIdle" instead of "setExactAndAllowWhileIdle".}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^ alarmManager.setAndAllowWhileIdle(0, 1000, operation); // Compliant var noAlarmManager = new NoAlarmManager(); @@ -32,7 +34,8 @@ public void setExactAndAllowWhileIdle(AlarmManager alarmManager, PendingIntent o } public void setWindow(AlarmManager alarmManager, long triggerTime, PendingIntent pendingIntent) { - alarmManager.setWindow(0, triggerTime, 300000, pendingIntent); // Noncompliant [[sc=44;ec=50]] {{Use alarm windows of 10 minutes or more instead.}} + alarmManager.setWindow(0, triggerTime, 300000, pendingIntent); // Noncompliant {{Use alarm windows of 10 minutes or more instead.}} +// ^^^^^^ alarmManager.setWindow(0, triggerTime, 600000, pendingIntent); // Compliant alarmManager.setWindow(0, triggerTime, 900000, pendingIntent); // Compliant alarmManager.setWindow(0, triggerTime, 300000L, pendingIntent); // Noncompliant diff --git a/java-checks-test-sources/default/src/main/java/checks/sustainability/AndroidFusedLocationProviderClientCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/sustainability/AndroidFusedLocationProviderClientCheckSample.java index fbde35fb533..44e9eec04d3 100644 --- a/java-checks-test-sources/default/src/main/java/checks/sustainability/AndroidFusedLocationProviderClientCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/sustainability/AndroidFusedLocationProviderClientCheckSample.java @@ -7,7 +7,8 @@ public class AndroidFusedLocationProviderClientCheckSample { public void getLocationService(Context context, NoContext noContext, Optional opt, PendingIntent operation) { - var service1 = context.getSystemService("location"); // Noncompliant [[sc=45;ec=55]] {{Use "FusedLocationProviderClient" instead of "LocationManager".}} + var service1 = context.getSystemService("location"); // Noncompliant {{Use "FusedLocationProviderClient" instead of "LocationManager".}} +// ^^^^^^^^^^ context.getSystemService("location"); // Noncompliant var service2 = context.getSystemService("locale"); // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/unused/UnusedLocalVariableCheck.java b/java-checks-test-sources/default/src/main/java/checks/unused/UnusedLocalVariableCheck.java index e35188ed80b..a312178bc72 100644 --- a/java-checks-test-sources/default/src/main/java/checks/unused/UnusedLocalVariableCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/unused/UnusedLocalVariableCheck.java @@ -27,7 +27,8 @@ private UnusedLocalVariableCheck(int unusedParameter) { // Compliant } public void f(int unusedParameter, Object o) { - int unusedLocalVariable; // Noncompliant [[sc=9;=ec=28]] {{Remove this unused "unusedLocalVariable" local variable.}} + int unusedLocalVariable; // Noncompliant {{Remove this unused "unusedLocalVariable" local variable.}} +// ^^^^^^^^^^^^^^^^^^^ int usedLocalVariable = 42; System.out.println(usedLocalVariable); @@ -80,7 +81,8 @@ public void f(int unusedParameter, Object o) { System.out.println(usedPatternVar); } - if (o instanceof String unusedPatternVar) { // Noncompliant [[sc=29;=ec=45]] + if (o instanceof String unusedPatternVar) { // Noncompliant {{Remove this unused "unusedPatternVar" local variable.}} +// ^^^^^^^^^^^^^^^^ } } @@ -99,46 +101,57 @@ public BinaryOperator> foo() { class QuickFixes { private void doSomething(Object parameter) { - int unusedAndAlone; // Noncompliant [[sc=11;ec=25;quickfixes=qfzero]] + int unusedAndAlone; // Noncompliant [[quickfixes=qfzero]] +// ^^^^^^^^^^^^^^ // fix@qfzero {{Remove unused local variable}} // edit@qfzero [[sc=7;ec=26]]{{}} - int unusedFirst = 42, used = 1; // Noncompliant [[sc=11;ec=22;quickfixes=qf0]] + int unusedFirst = 42, used = 1; // Noncompliant [[quickfixes=qf0]] +// ^^^^^^^^^^^ // fix@qf0 {{Remove unused local variable}} // edit@qf0 [[sc=11;ec=29]]{{}} - int first = 0, unusedSecond, third = 1; // Noncompliant [[sc=22;ec=34;quickfixes=qf1]] + int first = 0, unusedSecond, third = 1; // Noncompliant [[quickfixes=qf1]] +// ^^^^^^^^^^^^ // fix@qf1 {{Remove unused local variable}} // edit@qf1 [[sc=22;ec=36]]{{}} - int alpha = 0, beta = 1, unusedThird; // Noncompliant [[sc=32;ec=43;quickfixes=qf2]] + int alpha = 0, beta = 1, unusedThird; // Noncompliant [[quickfixes=qf2]] +// ^^^^^^^^^^^ // fix@qf2 {{Remove unused local variable}} // edit@qf2 [[sc=30;ec=43]]{{}} - int initializedButNotRead = used + first + third + alpha + beta; // Noncompliant [[sc=11;ec=32;quickfixes=qf3]] + int initializedButNotRead = used + first + third + alpha + beta; // Noncompliant [[quickfixes=qf3]] +// ^^^^^^^^^^^^^^^^^^^^^ // fix@qf3 {{Remove unused local variable}} // edit@qf3 [[sc=7;ec=71]]{{}} - String unitializedAndUnused; // Noncompliant [[sc=14;ec=34;quickfixes=qf4]] + // Noncompliant@+1 [[quickfixes=qf4]] + String unitializedAndUnused; +// ^^^^^^^^^^^^^^^^^^^^ // fix@qf4 {{Remove unused local variable}} - // edit@qf4 [[sc=7;ec=35]]{{}} + // edit@qf4 [[sl=+0;sc=7;ec=35]]{{}} - if (parameter instanceof String unusedMatch) { // Noncompliant [[sc=39;ec=50;quickfixes=qf5]] + if (parameter instanceof String unusedMatch) { // Noncompliant [[quickfixes=qf5]] +// ^^^^^^^^^^^ // fix@qf5 {{Remove unused local variable}} // edit@qf5 [[sc=39;ec=50]]{{}} } - for (int i, j = 0; j < 10; j++) { // Noncompliant [[sc=16;ec=17;quickfixes=qf6]] + for (int i, j = 0; j < 10; j++) { // Noncompliant [[quickfixes=qf6]] +// ^ // fix@qf6 {{Remove unused local variable}} // edit@qf6 [[sc=16;ec=18]] {{}} System.out.println(j); } - for (int i = 0, j; i < 10; i++) { // Noncompliant [[sc=23;ec=24;quickfixes=qf7]] + for (int i = 0, j; i < 10; i++) { // Noncompliant [[quickfixes=qf7]] +// ^ // fix@qf7 {{Remove unused local variable}} // edit@qf7 [[sc=21;ec=24]] {{}} System.out.println(i); } - for (int i = 0; condition();) { // Noncompliant [[sc=16;ec=17;quickfixes=qf8]] + for (int i = 0; condition();) { // Noncompliant [[quickfixes=qf8]] +// ^ // fix@qf8 {{Remove unused local variable}} // edit@qf8 [[sc=12;ec=21]] {{}} } @@ -152,39 +165,89 @@ private void doSomething(Object parameter) { // edit@qf10 [[sc=20;ec=38]] {{}} System.out.println(usedFinalLast); - final String usedFinalFirst = "Hello!", unusedFinalLast; // Noncompliant [[sc=47;ec=62;quickfixes=qf11]] + final String usedFinalFirst = "Hello!", unusedFinalLast; // Noncompliant [[quickfixes=qf11]] +// ^^^^^^^^^^^^^^^ // fix@qf11 {{Remove unused local variable}} // edit@qf11 [[sc=45;ec=62]] {{}} System.out.println(usedFinalFirst); - var unusedInferredAlone = 42; // Noncompliant [[sc=11;ec=30;quickfixes=qf12]] + var unusedInferredAlone = 42; // Noncompliant [[quickfixes=qf12]] +// ^^^^^^^^^^^^^^^^^^^ // fix@qf12 {{Remove unused local variable}} // edit@qf12 [[sc=7;ec=36]] {{}} } { - int unusedAndAlone; // Noncompliant [[sc=11;ec=25;quickfixes=qfzero]] - int unusedFirst = 42, used = 1; // Noncompliant [[sc=11;ec=22;quickfixes=qf0]] - int first = 0, unusedSecond, third = 1; // Noncompliant [[sc=22;ec=34;quickfixes=qf1]] - int alpha = 0, beta = 1, unusedThird; // Noncompliant [[sc=32;ec=43;quickfixes=qf2]] - int initializedButNotRead = used + first + third + alpha + beta; // Noncompliant [[sc=11;ec=32;quickfixes=qf3]] - String unitializedAndUnused; // Noncompliant [[sc=14;ec=34;quickfixes=qf4]] + int unusedAndAlone; // Noncompliant [[quickfixes=qfzero1]] +// ^^^^^^^^^^^^^^ + // fix@qfzero1 {{Remove unused local variable}} + // edit@qfzero1 [[sc=7;ec=26]]{{}} + int unusedFirst = 42, used = 1; // Noncompliant [[quickfixes=qf01]] +// ^^^^^^^^^^^ + // fix@qf01 {{Remove unused local variable}} + // edit@qf01 [[sc=11;ec=29]]{{}} + + int first = 0, unusedSecond, third = 1; // Noncompliant [[quickfixes=qf111]] +// ^^^^^^^^^^^^ + // fix@qf111 {{Remove unused local variable}} + // edit@qf111 [[sc=22;ec=36]]{{}} + + int alpha = 0, beta = 1, unusedThird; // Noncompliant [[quickfixes=qf21]] +// ^^^^^^^^^^^ + // fix@qf21 {{Remove unused local variable}} + // edit@qf21 [[sc=30;ec=43]]{{}} + + int initializedButNotRead = used + first + third + alpha + beta; // Noncompliant [[quickfixes=qf31]] +// ^^^^^^^^^^^^^^^^^^^^^ + // fix@qf31 {{Remove unused local variable}} + // edit@qf31 [[sc=7;ec=71]]{{}} + + // Noncompliant@+1 [[quickfixes=qf41]] + String unitializedAndUnused; +// ^^^^^^^^^^^^^^^^^^^^ + // fix@qf41 {{Remove unused local variable}} + // edit@qf41 [[sl=+0;sc=7;ec=35]]{{}} } static { - int unusedAndAlone; // Noncompliant [[sc=11;ec=25;quickfixes=qfzero]] - int unusedFirst = 42, used = 1; // Noncompliant [[sc=11;ec=22;quickfixes=qf0]] - int first = 0, unusedSecond, third = 1; // Noncompliant [[sc=22;ec=34;quickfixes=qf1]] - int alpha = 0, beta = 1, unusedThird; // Noncompliant [[sc=32;ec=43;quickfixes=qf2]] - int initializedButNotRead = used + first + third + alpha + beta; // Noncompliant [[sc=11;ec=32;quickfixes=qf3]] - String unitializedAndUnused; // Noncompliant [[sc=14;ec=34;quickfixes=qf4]] + int unusedAndAlone; // Noncompliant [[quickfixes=qfzero2]] +// ^^^^^^^^^^^^^^ + // fix@qfzero2 {{Remove unused local variable}} + // edit@qfzero2 [[sc=7;ec=26]]{{}} + int unusedFirst = 42, used = 1; // Noncompliant [[quickfixes=qf02]] +// ^^^^^^^^^^^ + // fix@qf02 {{Remove unused local variable}} + // edit@qf02 [[sc=11;ec=29]]{{}} + + int first = 0, unusedSecond, third = 1; // Noncompliant [[quickfixes=qf122]] +// ^^^^^^^^^^^^ + // fix@qf122 {{Remove unused local variable}} + // edit@qf122 [[sc=22;ec=36]]{{}} + + int alpha = 0, beta = 1, unusedThird; // Noncompliant [[quickfixes=qf22]] +// ^^^^^^^^^^^ + // fix@qf22 {{Remove unused local variable}} + // edit@qf22 [[sc=30;ec=43]]{{}} + + int initializedButNotRead = used + first + third + alpha + beta; // Noncompliant [[quickfixes=qf32]] +// ^^^^^^^^^^^^^^^^^^^^^ + // fix@qf32 {{Remove unused local variable}} + // edit@qf32 [[sc=7;ec=71]]{{}} + + // Noncompliant@+1 [[quickfixes=qf42]] + String unitializedAndUnused; +// ^^^^^^^^^^^^^^^^^^^^ + // fix@qf42 {{Remove unused local variable}} + // edit@qf42 [[sl=+0;sc=7;ec=35]]{{}} } private void doNotOfferQuickFixes() { - int unusedButIncremented = 0; // Noncompliant [[sc=11;ec=31;quickfixes=!]] + int unusedButIncremented = 0; // Noncompliant [[quickfixes=!]] +// ^^^^^^^^^^^^^^^^^^^^ unusedButIncremented++; - for (int counter = 0; condition(); counter++) { // Noncompliant [[sc=16;ec=23;quickfixes=!]] + for (int counter = 0; condition(); counter++) { // Noncompliant [[quickfixes=!]] +// ^^^^^^^ } } diff --git a/java-checks-test-sources/default/src/main/java/checks/unused/UnusedMethodParameterCheck.java b/java-checks-test-sources/default/src/main/java/checks/unused/UnusedMethodParameterCheck.java index 0babb53e10c..b4513d4c642 100644 --- a/java-checks-test-sources/default/src/main/java/checks/unused/UnusedMethodParameterCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/unused/UnusedMethodParameterCheck.java @@ -19,7 +19,8 @@ class UnusedMethodParameterCheck extends B { void doSomething() { } - void doSomething(int a, int b) { // Noncompliant [[sc=31;ec=32;quickfixes=qf_1_1]] {{Remove this unused method parameter "b".}} + void doSomething(int a, int b) { // Noncompliant {{Remove this unused method parameter "b".}} [[quickfixes=qf_1_1]] +// ^ // fix@qf_1_1 {{Remove "b"}} // edit@qf_1_1 [[sc=25;ec=32]] {{}} compute(a); @@ -56,11 +57,15 @@ void foo(int a) { } class D extends C { - void foo(int a, // Noncompliant [[sc=16;ec=17;secondary=+1,+3,+4;quickfixes=qf_2_1,qf_2_2,qf_2_3,qf_2_4]] {{Remove these unused method parameters "a", "b", "d", "e".}} + void foo(int a, // Noncompliant {{Remove these unused method parameters "a", "b", "d", "e".}} [[quickfixes=qf_2_1,qf_2_2,qf_2_3,qf_2_4]] @Nullable Object b, int c, int d, @Nullable Object e) { +// ^@-4 +// ^@-4< +// ^@-3< +// ^@-3< // fix@qf_2_1 {{Remove "a"}} // edit@qf_2_1 [[sl=+0;sc=12;el=+1;ec=12]] {{}} // fix@qf_2_2 {{Remove "b"}} @@ -73,7 +78,8 @@ class D extends C { } } class E extends C { - void bar(int a){ // Noncompliant [[sc=16;ec=17;quickfixes=qf_3_1]] {{Remove this unused method parameter "a".}} + void bar(int a){ // Noncompliant {{Remove this unused method parameter "a".}} [[quickfixes=qf_3_1]] +// ^ // fix@qf_3_1 {{Remove "a"}} // edit@qf_3_1 [[sc=12;ec=17]] {{}} System.out.println(""); @@ -129,7 +135,7 @@ private void baz(int arg) { // Noncompliant //no-op } - // Noncompliant@+1 + // Noncompliant@+1 private void qiz(int arg1, int arg2) { } @@ -156,7 +162,8 @@ public void foo(@Observes Object event, int arg2) { // Compliant System.out.println(arg2); } - public void bar(@Nonnull Object event, int arg2) { // Noncompliant {{Remove this unused method parameter "event".}} [[sc=35;ec=40]] + public void bar(@Nonnull Object event, int arg2) { // Noncompliant {{Remove this unused method parameter "event".}} +// ^^^^^ System.out.println(arg2); } @@ -175,12 +182,14 @@ void unknownWarningCombinedWithKnown(List list, int unused) { // Compliant } @SuppressWarnings({"rawtypes", "unchecked"}) - void foobar(List list, int unused) { // Noncompliant {{Remove this unused method parameter "unused".}} [[sc=30;ec=36]] + void foobar(List list, int unused) { // Noncompliant {{Remove this unused method parameter "unused".}} +// ^^^^^^ List strings = (List) list; } @SuppressWarnings("unchecked") - void uncheckedFoobar(List list, int unused) { // Noncompliant {{Remove this unused method parameter "unused".}} [[sc=42;ec=48]] + void uncheckedFoobar(List list, int unused) { // Noncompliant {{Remove this unused method parameter "unused".}} +// ^^^^^^ List strings = (List) list; } } @@ -254,21 +263,21 @@ public void foobar(String firstArg) { // Noncompliant /** * @param firstArg proper javadoc description */ - private void nonOverrideableMethod(String firstArg) { // Noncompliant {{Remove this unused method parameter "firstArg".}} + private void nonOverrideableMethod(String firstArg) { // Noncompliant {{Remove this unused method parameter "firstArg".}} System.out.println(); } /** * @param firstArg proper javadoc description */ - static void nonOverrideableMethod(int firstArg) { // Noncompliant {{Remove this unused method parameter "firstArg".}} + static void nonOverrideableMethod(int firstArg) { // Noncompliant {{Remove this unused method parameter "firstArg".}} System.out.println(); } /** * @param firstArg proper javadoc description */ - final void nonOverrideableMethod(Object firstArg) { // Noncompliant {{Remove this unused method parameter "firstArg".}} + final void nonOverrideableMethod(Object firstArg) { // Noncompliant {{Remove this unused method parameter "firstArg".}} System.out.println(); } } @@ -277,7 +286,7 @@ final class FinalDocumentedMethod { /** * @param firstArg proper javadoc description */ - void nonOverrideableMethod(int firstArg) { // Noncompliant {{Remove this unused method parameter "firstArg".}} + void nonOverrideableMethod(int firstArg) { // Noncompliant {{Remove this unused method parameter "firstArg".}} System.out.println(); } } @@ -302,7 +311,7 @@ protected void barProtected(Object o) { // Noncompliant // do something } - public void barPublic(Object o) { // Noncompliant + public void barPublic(Object o) { // Noncompliant // do something } @@ -348,18 +357,23 @@ private String bar(String a, String b) { // Compliant - used as method reference } class JakartaAnnotations { - void fooBar(int a, // Noncompliant [[sc=19;ec=20;secondary=+1,+3,+4]] {{Remove these unused method parameters "a", "b", "d", "e".}} + void fooBar(int a, // Noncompliant {{Remove these unused method parameters "a", "b", "d", "e".}} +// ^ @jakarta.annotation.Nullable Boolean b, +// ^< int c, int d, +// ^< @jakarta.annotation.Nullable Object e) { +// ^< System.out.println(c); } public void foo(@jakarta.enterprise.event.Observes Object event, int arg2) { // Compliant System.out.println(arg2); } - public void bar(@jakarta.annotation.Nonnull Object event, int arg2) { // Noncompliant {{Remove this unused method parameter "event".}} [[sc=54;ec=59]] + public void bar(@jakarta.annotation.Nonnull Object event, int arg2) { // Noncompliant {{Remove this unused method parameter "event".}} +// ^^^^^ System.out.println(arg2); } } diff --git a/java-checks-test-sources/default/src/main/java/checks/unused/UnusedPrivateFieldCheck.java b/java-checks-test-sources/default/src/main/java/checks/unused/UnusedPrivateFieldCheck.java index dc59bbc42ce..b5e44ce95b6 100644 --- a/java-checks-test-sources/default/src/main/java/checks/unused/UnusedPrivateFieldCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/unused/UnusedPrivateFieldCheck.java @@ -6,11 +6,10 @@ import java.io.IOException; import java.util.Optional; -import javax.validation.constraints.NotNull; - class UnusedPrivateFieldCheck { - private int unusedField; // Noncompliant [[sc=15;ec=26]] {{Remove this unused "unusedField" private field.}} + private int unusedField; // Noncompliant {{Remove this unused "unusedField" private field.}} +// ^^^^^^^^^^^ int usedField; // Compliant @@ -97,41 +96,63 @@ Long transform(String number) { class UnusedPrivateFieldCheckQuickfix { - private String unusedField; // Noncompliant [[sc=18;ec=29;quickfixes=qf0]] + private String unusedField; // Noncompliant [[quickfixes=qf0]] +// ^^^^^^^^^^^ // fix@qf0 {{Remove this unused private field}} // edit@qf0 [[sc=3;ec=30]]{{}} private String usedField; - private String unusedFirst, usedSecond; // Noncompliant [[sc=18;ec=29;quickfixes=qf1]] + private String unusedFirst, usedSecond; // Noncompliant [[quickfixes=qf1]] +// ^^^^^^^^^^^ // fix@qf1 {{Remove this unused private field}} // edit@qf1 [[sc=18;ec=31]]{{}} - private String usedFirst, unusedSecond; // Noncompliant [[sc=29;ec=41;quickfixes=qf2]] + void split(){ + // The CommentLinesVisitor has a bug when scanning more fields declared on the same line like the following 2 fields + // To fix it a non-comment block of code is needed between them and the comments above + } + + private String usedFirst, unusedSecond; // Noncompliant [[quickfixes=qf2]] +// ^^^^^^^^^^^^ // fix@qf2 {{Remove this unused private field}} // edit@qf2 [[sc=27;ec=41]]{{}} - private static int unusedStatic; // Noncompliant [[sc=22;ec=34;quickfixes=qf3]] + void split2(){} + + private static int unusedStatic; // Noncompliant [[quickfixes=qf3]] +// ^^^^^^^^^^^^ // fix@qf3 {{Remove this unused private field}} // edit@qf3 [[sc=3;ec=35]]{{}} - private final int unusedFinal = 0; // Noncompliant [[sc=21;ec=32;quickfixes=qf4]] + private final int unusedFinal = 0; // Noncompliant [[quickfixes=qf4]] +// ^^^^^^^^^^^ // fix@qf4 {{Remove this unused private field}} // edit@qf4 [[sc=3;ec=37]]{{}} - private static final int unusedStaticFinal = 0; // Noncompliant [[sc=28;ec=45;quickfixes=qf5]] + private static final int unusedStaticFinal = 0; // Noncompliant [[quickfixes=qf5]] +// ^^^^^^^^^^^^^^^^^ // fix@qf5 {{Remove this unused private field}} // edit@qf5 [[sc=3;ec=50]]{{}} - private static int unusedStaticFirst, usedStaticSecond; // Noncompliant [[sc=22;ec=39;quickfixes=qf6]] + void split3(){} + + private static int unusedStaticFirst, usedStaticSecond; // Noncompliant [[quickfixes=qf6]] +// ^^^^^^^^^^^^^^^^^ // fix@qf6 {{Remove this unused private field}} // edit@qf6 [[sc=22;ec=41]]{{}} - private final int unusedFinalFirst = 0, usedFinalSecond = 0; // Noncompliant [[sc=21;ec=37;quickfixes=qf7]] + void split4(){} + + private final int unusedFinalFirst = 0, usedFinalSecond = 0; // Noncompliant [[quickfixes=qf7]] +// ^^^^^^^^^^^^^^^^ // fix@qf7 {{Remove this unused private field}} // edit@qf7 [[sc=21;ec=43]]{{}} - private static final int unusedStaticFinalFirst = 0, usedStaticFinalSecond = 0; // Noncompliant [[sc=28;ec=50;quickfixes=qf8]] + void split5(){} + + private static final int unusedStaticFinalFirst = 0, usedStaticFinalSecond = 0; // Noncompliant [[quickfixes=qf8]] +// ^^^^^^^^^^^^^^^^^^^^^^ // fix@qf8 {{Remove this unused private field}} // edit@qf8 [[sc=28;ec=56]]{{}} @@ -141,7 +162,8 @@ class UnusedPrivateFieldCheckQuickfix { /** * This documentation should be removed as part of the quickfix */ - private static final int FIELD_WITH_JAVADOC = 42; // Noncompliant [[sc=28;ec=46;quickfixes=qf9]] + private static final int FIELD_WITH_JAVADOC = 42; // Noncompliant [[quickfixes=qf9]] +// ^^^^^^^^^^^^^^^^^^ // fix@qf9 {{Remove this unused private field}} // edit@qf9 [[sl=-3;sc=3;el=+0;ec=52]]{{}} diff --git a/java-checks-test-sources/default/src/main/java/checks/unused/UnusedPrivateFieldCheckWithIgnoredAnnotation.java b/java-checks-test-sources/default/src/main/java/checks/unused/UnusedPrivateFieldCheckWithIgnoredAnnotation.java index e3dbecb4cee..d8273699ed2 100644 --- a/java-checks-test-sources/default/src/main/java/checks/unused/UnusedPrivateFieldCheckWithIgnoredAnnotation.java +++ b/java-checks-test-sources/default/src/main/java/checks/unused/UnusedPrivateFieldCheckWithIgnoredAnnotation.java @@ -7,10 +7,12 @@ class UnusedPrivateFieldCheckWithIgnoredAnnotation { @Inject - private int unusedFieldAnnotationIsIgnored; // Noncompliant [[sc=15;ec=45]] {{Remove this unused "unusedFieldAnnotationIsIgnored" private field.}} + private int unusedFieldAnnotationIsIgnored; // Noncompliant {{Remove this unused "unusedFieldAnnotationIsIgnored" private field.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @Nullable - private Object unusedFieldAnnotationIsAlsoIgnored; // Noncompliant [[sc=18;ec=52]] {{Remove this unused "unusedFieldAnnotationIsAlsoIgnored" private field.}} + private Object unusedFieldAnnotationIsAlsoIgnored; // Noncompliant {{Remove this unused "unusedFieldAnnotationIsAlsoIgnored" private field.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @CheckForNull private Object unusedFieldAnnotationIsNotIgnored; // Compliant diff --git a/java-checks-test-sources/default/src/main/java/checks/unused/UnusedThrowableCheck.java b/java-checks-test-sources/default/src/main/java/checks/unused/UnusedThrowableCheck.java index d24c9146102..30082853f77 100644 --- a/java-checks-test-sources/default/src/main/java/checks/unused/UnusedThrowableCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/unused/UnusedThrowableCheck.java @@ -3,7 +3,8 @@ class UnusedThrowableCheck { void foo(int x) throws Throwable { if (x < 0) { - new IllegalArgumentException("x must be nonnegative"); // Noncompliant {{Throw this exception or remove this useless statement.}} [[sc=7;ec=60]] + new IllegalArgumentException("x must be nonnegative"); // Noncompliant {{Throw this exception or remove this useless statement.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } if (x < 0) { throw new IllegalArgumentException("x must be nonnegative"); @@ -16,7 +17,8 @@ void foo(int x) throws Throwable { } void testingQuickFixes() { - new IllegalArgumentException("x must be nonnegative"); // Noncompliant [[sc=5;ec=58;quickfixes=qf1,qf2]] + new IllegalArgumentException("x must be nonnegative"); // Noncompliant [[quickfixes=qf1,qf2]] +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // fix@qf1 {{Add "throw"}} // edit@qf1 [[sc=5;ec=5]] {{throw }} // fix@qf2 {{Remove the statement}} diff --git a/java-checks-test-sources/default/src/main/java/checks/unused/UnusedTypeParameterCheck.java b/java-checks-test-sources/default/src/main/java/checks/unused/UnusedTypeParameterCheck.java index 9590661907b..b39d8d5a3f0 100644 --- a/java-checks-test-sources/default/src/main/java/checks/unused/UnusedTypeParameterCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/unused/UnusedTypeParameterCheck.java @@ -3,7 +3,8 @@ import com.google.common.collect.MapDifference; import java.util.Map; -class UnusedTypeParameterCheck { // Noncompliant [[sc=35;ec=36]] {{S is not used in the class.}} +class UnusedTypeParameterCheck { // Noncompliant {{S is not used in the class.}} +// ^ T field; void fun(X x) {} // Noncompliant {{W is not used in the method.}} } @@ -20,6 +21,7 @@ private static void doDifference(Map left, Map< } } -record UnusedRecordTypeParameter (T t, String s) { // Noncompliant [[sc=37;ec=38]] {{U is not used in the record.}} +record UnusedRecordTypeParameter (T t, String s) { // Noncompliant {{U is not used in the record.}} +// ^ void foo() { } } diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/ConditionAlwaysTrueOrFalseCheckParentLoop.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/ConditionAlwaysTrueOrFalseCheckParentLoop.java index e3ae40599ce..7be8983debb 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/ConditionAlwaysTrueOrFalseCheckParentLoop.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/ConditionAlwaysTrueOrFalseCheckParentLoop.java @@ -6,7 +6,7 @@ public class ConditionAlwaysTrueOrFalseCheckParentLoop { public void run() { active = true; - while (active) { // Noncompliant FP + while (active) { // Noncompliant try { foo.method(); } catch (CustomException se) { diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/DenialOfServiceXMLCheckSample.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/DenialOfServiceXMLCheckSample.java index f83cc568b0d..8de71b6cac0 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/DenialOfServiceXMLCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/DenialOfServiceXMLCheckSample.java @@ -39,7 +39,8 @@ DocumentBuilderFactory secure_processing_false() throws ParserConfigurationExcep DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); // To make XxeProcessingCheck secured - factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false); // Noncompliant [[sc=5;ec=70]] {{Enable XML parsing limitations to prevent Denial of Service attacks.}} + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false); // Noncompliant {{Enable XML parsing limitations to prevent Denial of Service attacks.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ return factory; } @@ -125,7 +126,8 @@ SAXParserFactory sax_parser_unsecured() throws ParserConfigurationException, SAX SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); // To make XxeProcessingCheck secured - factory.setFeature("http://javax.xml.XMLConstants/feature/secure-processing", false); // Noncompliant [[sc=5;ec=89]] {{Enable XML parsing limitations to prevent Denial of Service attacks.}} + factory.setFeature("http://javax.xml.XMLConstants/feature/secure-processing", false); // Noncompliant {{Enable XML parsing limitations to prevent Denial of Service attacks.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ return factory; } diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/DivisionByZeroCheckPrimitives.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/DivisionByZeroCheckPrimitives.java index 294c1535012..ba5dede2400 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/DivisionByZeroCheckPrimitives.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/DivisionByZeroCheckPrimitives.java @@ -57,16 +57,16 @@ public abstract class DivisionByZeroCheckPrimitives { public double notZero(Double d) { return d / DOUBLE_WRAPPER_NOT_ZERO; } public float notZero(Float f) { return f / FLOAT_WRAPPER_NOT_ZERO; } - public int zero(byte b) { return b / BYTE_ZERO; } // Noncompliant - public int zero(short s) { return s / SHORT_ZERO; } // Noncompliant - public int zero(int i) { return i / INT_ZERO; } // Noncompliant - public long zero(long l) { return l / LONG_ZERO; } // Noncompliant + public int zero(byte b) { return b / BYTE_ZERO; } // Noncompliant + public int zero(short s) { return s / SHORT_ZERO; } // Noncompliant + public int zero(int i) { return i / INT_ZERO; } // Noncompliant + public long zero(long l) { return l / LONG_ZERO; } // Noncompliant public double zero(double d) { return d / DOUBLE_ZERO; } // Noncompliant - public float zero(float f) { return f / FLOAT_ZERO; } // Noncompliant - public int zero(char c) { return c / CHAR_ZERO; } // Noncompliant - public BigInteger zero1(BigInteger bi) { return bi.divide(BigInteger.ZERO); } // Noncompliant - public BigInteger zero2(BigInteger bi) { return bi.divide(BigInteger.valueOf(LONG_ZERO)); } // Noncompliant - public BigDecimal zero1(BigDecimal bd) { return bd.divide(BigDecimal.ZERO); } // Noncompliant + public float zero(float f) { return f / FLOAT_ZERO; } // Noncompliant + public int zero(char c) { return c / CHAR_ZERO; } // Noncompliant + public BigInteger zero1(BigInteger bi) { return bi.divide(BigInteger.ZERO); } // Noncompliant + public BigInteger zero2(BigInteger bi) { return bi.divide(BigInteger.valueOf(LONG_ZERO)); } // Noncompliant + public BigDecimal zero1(BigDecimal bd) { return bd.divide(BigDecimal.ZERO); } // Noncompliant public BigDecimal zero2(BigDecimal bd) { return bd.divide(BigDecimal.valueOf(DOUBLE_ZERO)); } // Noncompliant public int zero(Byte b) { return b / BYTE_WRAPPER_ZERO; } // FN diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/LocksNotUnlockedCheckCache.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/LocksNotUnlockedCheckCache.java index b6db660437c..c41855e1df4 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/LocksNotUnlockedCheckCache.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/LocksNotUnlockedCheckCache.java @@ -8,10 +8,10 @@ public class LocksNotUnlockedCheckCache { public void thisReportsOnlyOneIssue(boolean foo) { Lock lock = new ReentrantLock(); if(foo) { - lock.lock();// Noncompliant {{Unlock this lock along all executions paths of this method.}} + lock.lock(); // Noncompliant {{Unlock this lock along all executions paths of this method.}} ifStmt(); } else { - lock.lock();// Noncompliant {{Unlock this lock along all executions paths of this method.}} + lock.lock(); // Noncompliant {{Unlock this lock along all executions paths of this method.}} elseStmt(); } end(); @@ -21,18 +21,18 @@ public void fourIssues(boolean foo) { Lock lock = new ReentrantLock(); Lock lock2 = new ReentrantLock(); if(foo) { - lock.lock();// Noncompliant {{Unlock this lock along all executions paths of this method.}} + lock.lock(); // Noncompliant {{Unlock this lock along all executions paths of this method.}} ifStmt(); } else { - lock.lock();// Noncompliant {{Unlock this lock along all executions paths of this method.}} + lock.lock(); // Noncompliant {{Unlock this lock along all executions paths of this method.}} elseStmt(); } end(); if(foo) { - lock2.lock();// Noncompliant {{Unlock this lock along all executions paths of this method.}} + lock2.lock(); // Noncompliant {{Unlock this lock along all executions paths of this method.}} ifStmt(); } else { - lock2.lock();// Noncompliant {{Unlock this lock along all executions paths of this method.}} + lock2.lock(); // Noncompliant {{Unlock this lock along all executions paths of this method.}} elseStmt(); } end(); diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/LocksNotUnlockedCheckSample.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/LocksNotUnlockedCheckSample.java index 2505cd24785..65e6a05b7ad 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/LocksNotUnlockedCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/LocksNotUnlockedCheckSample.java @@ -15,7 +15,7 @@ abstract class LocksNotUnlockedCheckSample { public void acquireLock() { Lock local = new ReentrantLock(); - local.lock(); // Noncompliant {{Unlock this lock along all executions paths of this method.}} + local.lock(); // Noncompliant {{Unlock this lock along all executions paths of this method.}} l1.lock(); } @@ -55,16 +55,16 @@ public void doTheThing() { public void multipleLockState() { Lock lock = new ReentrantLock(); if(foo) { - lock.lock();// Noncompliant {{Unlock this lock along all executions paths of this method.}} + lock.lock(); // Noncompliant {{Unlock this lock along all executions paths of this method.}} } else { - lock.lock();// Noncompliant {{Unlock this lock along all executions paths of this method.}} + lock.lock(); // Noncompliant {{Unlock this lock along all executions paths of this method.}} } } public void doTheOtherThing() { Lock lock = new ReentrantLock(); try { - lock.tryLock(); // Noncompliant {{Unlock this lock along all executions paths of this method.}} + lock.tryLock(); // Noncompliant {{Unlock this lock along all executions paths of this method.}} doSomething(); lock.unlock(); // an exception will keep this line from being reached } catch (Exception e) { diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/MapComputeIfAbsentOrPresentCheckSample.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/MapComputeIfAbsentOrPresentCheckSample.java index cc85f7724e1..ade4ac1ea61 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/MapComputeIfAbsentOrPresentCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/MapComputeIfAbsentOrPresentCheckSample.java @@ -74,7 +74,7 @@ void gul(Map map, String key1, String key2) { } void gro(Map map, String key) { - Object value = map.get(key); // Noncompliant - reassigning everything + Object value = map.get(key); // Noncompliant Object value2 = value; if (value2 == null) { String key2 = key; @@ -288,10 +288,10 @@ void npqg(Map map, String key1) { void multipleChecks(Map map, String key1, String key2, String key3, boolean b1, boolean b2) { if (b1) { - if (!map.containsKey(key1)) // Noncompliant {{Replace this "Map.containsKey()" with a call to "Map.computeIfAbsent()".}} + if (!map.containsKey(key1)) // Noncompliant {{Replace this "Map.containsKey()" with a call to "Map.computeIfAbsent()".}} map.put(key1, new Object()); if (b2) { - if (!map.containsKey(key2)) // Noncompliant {{Replace this "Map.containsKey()" with a call to "Map.computeIfAbsent()".}} + if (!map.containsKey(key2)) // Noncompliant {{Replace this "Map.containsKey()" with a call to "Map.computeIfAbsent()".}} map.put(key2, new Object()); if (!map.containsKey(key3)) // Noncompliant {{Replace this "Map.containsKey()" with a call to "Map.computeIfAbsent()".}} diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/MethodInvocationLeadingToDivisionByZero.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/MethodInvocationLeadingToDivisionByZero.java index a72eb0700cb..13aa6198f34 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/MethodInvocationLeadingToDivisionByZero.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/MethodInvocationLeadingToDivisionByZero.java @@ -18,6 +18,7 @@ void foo3(int j) { int i = 42; // flow@foo3 [[order=1]] {{Implies 'i' is non-zero.}} if (j == 0) { // flow@foo3 [[order=2]] {{Implies 'j' is zero.}} divByZeroIfArg1Zero(i, j); // Noncompliant [[flows=foo3]] {{A division by zero will occur when invoking method "divByZeroIfArg1Zero()".}} flow@foo3 [[order=3;sc=30;ec=31]] {{'j' is passed to 'divByZeroIfArg1Zero()'.}} +// ^ } } diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/NonNullSetToNullCheck/noDefault/NonNullSetToNullCheckSample.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/NonNullSetToNullCheck/noDefault/NonNullSetToNullCheckSample.java index c66ed065929..fcabe2afa0c 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/NonNullSetToNullCheck/noDefault/NonNullSetToNullCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/NonNullSetToNullCheck/noDefault/NonNullSetToNullCheckSample.java @@ -42,7 +42,8 @@ public NonNullSetToNullCheckSample(String color) { if (color != null) { secondary = null; } - primary = color; // Noncompliant [[sc=5;ec=20]] {{"primary" is marked "@Nonnull" but is set to null.}} + primary = color; // Noncompliant {{"primary" is marked "@Nonnull" but is set to null.}} +// ^^^^^^^^^^^^^^^ testObject = new Object(); otherNonnullField = ""; } @@ -54,7 +55,8 @@ public NonNullSetToNullCheckSample(@Nonnull String color, String other) { otherNonnullField = ""; } - public NonNullSetToNullCheckSample() { // Noncompliant [[sc=10;ec=37]] {{"primary" is marked "@Nonnull" but is not initialized in this constructor.}} + public NonNullSetToNullCheckSample() { // Noncompliant {{"primary" is marked "@Nonnull" but is not initialized in this constructor.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ return; // Just for coverage } @@ -115,7 +117,7 @@ public void setColors(@Nonnull String... colors) { // ============ 2. Testing Return values ============ @Nonnull public String colorMix() { - return null; // Noncompliant {{This method's return value is marked "@Nonnull" but null is returned.}} + return null; // Noncompliant {{This method's return value is marked "@Nonnull" but null is returned.}} } @Nonnull(when = When.MAYBE) @@ -136,7 +138,7 @@ public String neverNull() { @Nonnull public String indirectMix() { String mix = null; - return mix; // Noncompliant {{This method's return value is marked "@Nonnull" but null is returned.}} + return mix; // Noncompliant {{This method's return value is marked "@Nonnull" but null is returned.}} } @Nonnull @@ -167,17 +169,18 @@ public String getSecondaryOrDefault(String color) { // ============ 3. Testing nullable value passed as argument ============ public static void initialize1() { NonNullSetToNullCheckSample instance = - new NonNullSetToNullCheckSample(null, "Blue"); // Noncompliant [[sc=7;ec=52]] {{Parameter 1 to this constructor is marked "@Nonnull" but null could be passed.}} + new NonNullSetToNullCheckSample(null, "Blue"); // Noncompliant {{Parameter 1 to this constructor is marked "@Nonnull" but null could be passed.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } public static void initialize2() { NonNullSetToNullCheckSample instance = new NonNullSetToNullCheckSample("Black", null); - instance.setColors(null, "Green"); // Noncompliant {{Parameter 1 to this call is marked "@Nonnull" but null could be passed.}} + instance.setColors(null, "Green"); // Noncompliant {{Parameter 1 to this call is marked "@Nonnull" but null could be passed.}} } public static void initialize3() { NonNullSetToNullCheckSample instance = new NonNullSetToNullCheckSample("Red", null); - instance.setSecondary(null); // Noncompliant {{Parameter 1 to this call is marked "@Nonnull" but null could be passed.}} + instance.setSecondary(null); // Noncompliant {{Parameter 1 to this call is marked "@Nonnull" but null could be passed.}} } public static void initiliaze4() { @@ -191,7 +194,7 @@ public static void initiliaze4() { public static void initialize5() { NonNullSetToNullCheckSample instance = - new NonNullSetToNullCheckSample(checkForNull(), "Blue"); // Noncompliant + new NonNullSetToNullCheckSample(checkForNull(), "Blue"); // Noncompliant } // ============ 4. Local variable assigned nullable value ============ @@ -283,11 +286,11 @@ class NonNullSetToNullCheckSampleCallingOtherConstructor { this(Integer.valueOf(s)); } - NonNullSetToNullCheckSampleCallingOtherConstructor(Object o) { // Noncompliant - calls super constructor but do not initialize value + NonNullSetToNullCheckSampleCallingOtherConstructor(Object o) { // Noncompliant super(); } - NonNullSetToNullCheckSampleCallingOtherConstructor(String s, Object o) { // Noncompliant - calls other method + NonNullSetToNullCheckSampleCallingOtherConstructor(String s, Object o) { // Noncompliant this.foo(o); } @@ -409,7 +412,7 @@ class JpaEntityInvalidDefault { private String otherField; - public JpaEntityInvalidDefault() { // Noncompliant {{"itemName" is marked "@Nonnull" but is not initialized in this constructor.}} + public JpaEntityInvalidDefault() { // Noncompliant {{"itemName" is marked "@Nonnull" but is not initialized in this constructor.}} otherField = "test"; } } @@ -483,7 +486,7 @@ public void setInitialized() { // 2. return values public String returnNull() { - return null; // Noncompliant {{This method's return value is marked "@NonNullByDefault at class level" but null is returned.}} + return null; // Noncompliant {{This method's return value is marked "@NonNullByDefault at class level" but null is returned.}} } // 3. @@ -568,7 +571,7 @@ class JakartaJpaEntityInvalidDefault { private String otherField; - public JakartaJpaEntityInvalidDefault() { // Noncompliant {{"itemName" is marked "@Nonnull" but is not initialized in this constructor.}} + public JakartaJpaEntityInvalidDefault() { // Noncompliant {{"itemName" is marked "@Nonnull" but is not initialized in this constructor.}} otherField = "test"; } public void setColors2(@jakarta.annotation.Nullable String color) { diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/ObjectOutputStreamCheckSample.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/ObjectOutputStreamCheckSample.java index eb8b6500896..d1d594fd498 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/ObjectOutputStreamCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/ObjectOutputStreamCheckSample.java @@ -15,16 +15,16 @@ class ObjectOutputStreamCheckSample { void noncompliant_1(String fileName) throws IOException { FileOutputStream fos = new FileOutputStream(fileName , true); // fos opened in append mode - ObjectOutputStream out = new ObjectOutputStream(fos); // Noncompliant {{Do not use a FileOutputStream in append mode.}} + ObjectOutputStream out = new ObjectOutputStream(fos); // Noncompliant {{Do not use a FileOutputStream in append mode.}} } void noncompliant_2(String fileName, boolean appendMode) throws IOException { if (!appendMode) return; FileOutputStream fos = new FileOutputStream(fileName, appendMode); // fos opened in append mode - ObjectOutputStream out = new ObjectOutputStream(fos); // Noncompliant + ObjectOutputStream out = new ObjectOutputStream(fos); // Noncompliant } void noncompliant_3(File file) throws IOException { FileOutputStream fos = new FileOutputStream(file , true); // fos opened in append mode - ObjectOutputStream out = new ObjectOutputStream(fos); // Noncompliant + ObjectOutputStream out = new ObjectOutputStream(fos); // Noncompliant } void noncompliant_10() throws IOException { diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/OptionalGetBeforeIsPresentCheckSample.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/OptionalGetBeforeIsPresentCheckSample.java index 00baf90ecde..8231b905a9e 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/OptionalGetBeforeIsPresentCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/OptionalGetBeforeIsPresentCheckSample.java @@ -13,7 +13,7 @@ abstract class OptionalGetBeforeIsPresentCheckSample { } OptionalGetBeforeIsPresentCheckSample(Optional s) { - s.get(); // Noncompliant {{Call "s.isPresent()" before accessing the value.}} + s.get(); // Noncompliant {{Call "s.isPresent()" before accessing the value.}} if (s.isPresent()) { s.get(); // Compliant } @@ -99,7 +99,7 @@ private void usingFilter2(Optional op) { private void usingFilter3(Optional op) { if (!op.filter(this::testSomething).isPresent()) { - op.get(); // Noncompliant - original optional may or may not be present, cannot know here by only testing the filtered optional + op.get(); // Noncompliant return; } op.get(); // Compliant - if op is not present, then filtered value will always be non present -> unreachable when op not present @@ -169,12 +169,14 @@ private void fromField7() { class Location { void test() { - Stream.of(1,2,3).findFirst().get(); // Noncompliant [[sc=5;ec=33]] + Stream.of(1,2,3).findFirst().get(); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } void test2() { Optional op = Optional.empty(); - op.get(); // Noncompliant [[sc=5;ec=7]] + op.get(); // Noncompliant +// ^^ } } diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/OptionalGetBeforeIsPresentCheck_jdk11.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/OptionalGetBeforeIsPresentCheck_jdk11.java index 954a6171209..a7a0cfc7bce 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/OptionalGetBeforeIsPresentCheck_jdk11.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/OptionalGetBeforeIsPresentCheck_jdk11.java @@ -59,12 +59,12 @@ void test_junit5_1(Optional op){ void test_junit5_2(Optional op){ Assertions.assertTrue(op.isEmpty(), "Hello"); - op.get(); // Noncompliant {{Call "op.isPresent()" or "!op.isEmpty()" before accessing the value.}} + op.get(); // Noncompliant {{Call "op.isPresent()" or "!op.isEmpty()" before accessing the value.}} } void test_junit5_3(Optional op){ Assertions.assertFalse(op.isPresent()); - op.get(); // Noncompliant {{Call "op.isPresent()" or "!op.isEmpty()" before accessing the value.}} + op.get(); // Noncompliant {{Call "op.isPresent()" or "!op.isEmpty()" before accessing the value.}} } void test_junit5_4(Optional op){ @@ -74,7 +74,7 @@ void test_junit5_4(Optional op){ void test_junit5_5(Optional op, int i){ Assertions.assertFalse(i < 0); - op.get(); // Noncompliant {{Call "op.isPresent()" or "!op.isEmpty()" before accessing the value.}} + op.get(); // Noncompliant {{Call "op.isPresent()" or "!op.isEmpty()" before accessing the value.}} } void test_junit5_6(Optional op){ @@ -89,7 +89,7 @@ void test_junit5_7(Optional op){ void test_junit5_8(Optional op, int i){ Assertions.assertFalse(i < 0, () -> "Hello"); - op.get(); // Noncompliant {{Call "op.isPresent()" or "!op.isEmpty()" before accessing the value.}} + op.get(); // Noncompliant {{Call "op.isPresent()" or "!op.isEmpty()" before accessing the value.}} } void test_junit5_9(Optional op){ @@ -124,7 +124,7 @@ void test_junit5_14(Optional op){ void test_junit5_15(Optional op){ Assertions.assertFalse(op.isPresent(), "Hello"); - op.get(); // Noncompliant + op.get(); // Noncompliant } void test_junit4_1(Optional op){ @@ -134,12 +134,12 @@ void test_junit4_1(Optional op){ void test_junit4_2(Optional op){ Assert.assertTrue("Hello", op.isEmpty()); - op.get(); // Noncompliant {{Call "op.isPresent()" or "!op.isEmpty()" before accessing the value.}} + op.get(); // Noncompliant {{Call "op.isPresent()" or "!op.isEmpty()" before accessing the value.}} } void test_junit4_3(Optional op){ Assert.assertFalse(op.isPresent()); - op.get(); // Noncompliant {{Call "op.isPresent()" or "!op.isEmpty()" before accessing the value.}} + op.get(); // Noncompliant {{Call "op.isPresent()" or "!op.isEmpty()" before accessing the value.}} } void test_junit4_4(Optional op){ @@ -149,7 +149,7 @@ void test_junit4_4(Optional op){ void test_junit4_5(Optional op, int i){ Assert.assertFalse(i < 0); - op.get(); // Noncompliant {{Call "op.isPresent()" or "!op.isEmpty()" before accessing the value.}} + op.get(); // Noncompliant {{Call "op.isPresent()" or "!op.isEmpty()" before accessing the value.}} } void test_junit4_6(Optional op){ diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/ParameterNullnessCheck/noDefault/ParameterNullnessCheckSample.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/ParameterNullnessCheck/noDefault/ParameterNullnessCheckSample.java index 55f45b68e30..99d39d28198 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/ParameterNullnessCheck/noDefault/ParameterNullnessCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/ParameterNullnessCheck/noDefault/ParameterNullnessCheckSample.java @@ -11,10 +11,12 @@ abstract class ParameterNullnessCheckSample { Object field; void foo(Object o) { // flow@foo [[order=2]] {{Method 'foo' declaration.}} - foo( // Noncompliant [[sc=5;ec=8;flows=foo]] {{Annotate the parameter with @javax.annotation.Nullable in method 'foo' declaration, or make sure that null can not be passed as argument.}} + foo( // Noncompliant [[flows=foo]] {{Annotate the parameter with @javax.annotation.Nullable in method 'foo' declaration, or make sure that null can not be passed as argument.}} +// ^^^ null); // flow@foo [[order=1]] {{Argument can be null.}} bar(o, null); // Compliant, annotated Nullable - bar(null, o); // Noncompliant [[sc=5;ec=8]] + bar(null, o); // Noncompliant +// ^^^ equals(null); B.foo(null); // Noncompliant @@ -29,12 +31,14 @@ void foo(Object o) { // flow@foo [[order=2]] {{Method 'foo' declaration.}} void testVarargs(Object o) { gul(null, o, null, o); // Compliant - ignore variadic argument - gul2(null, o, null, o); // Noncompliant [[sc=5;ec=9]] - first parameter is not variadic + gul2(null, o, null, o); // Noncompliant +// ^^^^ } void testConstructors(Object o) { C c1 = new C(null); // Noncompliant - C c2 = new C(o, // Noncompliant [[sc=16;ec=17;flows=A]] {{Annotate the parameter with @javax.annotation.Nullable in constructor declaration, or make sure that null can not be passed as argument.}} + C c2 = new C(o, // Noncompliant [[flows=A]] {{Annotate the parameter with @javax.annotation.Nullable in constructor declaration, or make sure that null can not be passed as argument.}} +// ^ null); // flow@A [[order=1]] {{Argument can be null.}} B b = new B(); diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/ParameterNullnessCheck/packageNonNull/ParameterNullnessCheckSample.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/ParameterNullnessCheck/packageNonNull/ParameterNullnessCheckSample.java index 29d82a5c51e..e8d9296ff5b 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/ParameterNullnessCheck/packageNonNull/ParameterNullnessCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/ParameterNullnessCheck/packageNonNull/ParameterNullnessCheckSample.java @@ -11,10 +11,12 @@ abstract class ParameterNullnessCheckSample { Object field; void foo(Object o) { // flow@foo [[order=2]] {{Method 'foo' declaration.}} - foo( // Noncompliant [[sc=5;ec=8;flows=foo]] {{Annotate the parameter with @javax.annotation.Nullable in method 'foo' declaration, or make sure that null can not be passed as argument.}} + foo( // Noncompliant [[flows=foo]] {{Annotate the parameter with @javax.annotation.Nullable in method 'foo' declaration, or make sure that null can not be passed as argument.}} +// ^^^ null); // flow@foo [[order=1]] {{Argument can be null.}} bar(o, null); // Compliant, annotated Nullable - bar(null, o); // Noncompliant [[sc=5;ec=8]] + bar(null, o); // Noncompliant +// ^^^ equals(null); B.foo(null); // Noncompliant @@ -32,7 +34,8 @@ void testVarargs(Object o) { void testConstructors(Object o) { C c1 = new C(null); // Noncompliant - C c2 = new C(o, // Noncompliant [[sc=16;ec=17]] {{Annotate the parameter with @javax.annotation.Nullable in constructor declaration, or make sure that null can not be passed as argument.}} + C c2 = new C(o, // Noncompliant {{Annotate the parameter with @javax.annotation.Nullable in constructor declaration, or make sure that null can not be passed as argument.}} +// ^ null); B b = new B(); } diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/PrimitiveUnboxing.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/PrimitiveUnboxing.java index 8bc3f6a1452..9db1ad746a3 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/PrimitiveUnboxing.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/PrimitiveUnboxing.java @@ -39,7 +39,8 @@ void unboxYieldToBoxedTypeIsCompliant(String key) { boolean unboxIdentifierOnReturn() { Boolean boxed = null; - return boxed; // Noncompliant [[sc=12;ec=17]] + return boxed; // Noncompliant +// ^^^^^ } class VolatileFieldsAreCompliantFalseNegatives { @@ -51,49 +52,58 @@ public long getBoxedVolatile() { } int unboxExpressionOnReturn() { - return getANullabbleInteger(); // Noncompliant [[sc=12;ec=34]] + return getANullabbleInteger(); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^ } void unboxOnExplicitYield(String key) { Integer boxed = null; int primitive = switch (key) { case "nullable": - yield getANullabbleInteger(); // Noncompliant [[sc=15;ec=37]] + yield getANullabbleInteger(); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^ case "primitive": yield 42; default: - yield boxed; // Noncompliant [[sc=15;ec=20]] + yield boxed; // Noncompliant +// ^^^^^ }; } void unboxOnImplicitYield(String key) { Integer boxed = null; int primitive = switch (key) { - case "nullable" -> getANullabbleInteger(); // Noncompliant [[sc=26;ec=48]] + case "nullable" -> getANullabbleInteger(); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^ case "primitive" -> 42; - default -> boxed; // Noncompliant [[sc=18;ec=23]] + default -> boxed; // Noncompliant +// ^^^^^ }; } boolean shortComparison() { Short boxed = null; short primitive = 1; - return primitive == boxed; // Noncompliant [[sc=25;ec=30]] + return primitive == boxed; // Noncompliant +// ^^^^^ } void initializedWithNullableReturnValue() { - int primitive = getANullabbleInteger(); // Noncompliant [[sc=21;ec=43]] + int primitive = getANullabbleInteger(); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^ } void declaredThenInitializedWithNullReturnValue() { int primitive; - primitive = getANullabbleInteger(); // Noncompliant [[sc=17;ec=39]] + primitive = getANullabbleInteger(); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^ } void declareThenInitialize() { Integer boxed = null; int primitive; - primitive = boxed; // Noncompliant [[sc=17;ec=22]] + primitive = boxed; // Noncompliant +// ^^^^^ } void declareThenOverwrite() { @@ -105,20 +115,24 @@ void declareThenOverwrite() { void declareThenPlusAssign() { Integer boxed = null; int primitive = 42; - boxed += primitive; // Noncompliant [[sc=5;ec=10]] + boxed += primitive; // Noncompliant +// ^^^^^ } void loopWithLiterals() { Integer i = null; - while (i < 42) { // Noncompliant [[sc=12;ec=13]] - i++; // Noncompliant [[sc=7;ec=8]] + while (i < 42) { // Noncompliant +// ^ + i++; // Noncompliant +// ^ } } void loopWhileLessThanReturnValue() { int primitive = 42; - while (primitive < getANullabbleInteger()) { // Noncompliant [[sc=24;ec=46]] + while (primitive < getANullabbleInteger()) { // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^ primitive--; } } @@ -134,7 +148,8 @@ void crashOnComparison() { void crashOnDecrement() { Integer i = null; do { - --i; // Noncompliant [[sc=9;ec=10]] + --i; // Noncompliant +// ^ } while (0 < i); } diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/RedundantAssignmentsCheckSample.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/RedundantAssignmentsCheckSample.java index 6eba7a6c9d4..3a472b5411c 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/RedundantAssignmentsCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/RedundantAssignmentsCheckSample.java @@ -11,7 +11,8 @@ class RedundantAssignmentsCheckSample { void foo() { a = b; // flow@foo {{Implies 'a' has the same value as 'b'.}} c = a; // flow@foo {{Implies 'c' has the same value as 'a'.}} - b = c; // Noncompliant [[sc=5;ec=10;flows=foo]] {{Remove this useless assignment; "b" already holds the assigned value along all execution paths.}} + b = c; // Noncompliant [[flows=foo]] {{Remove this useless assignment; "b" already holds the assigned value along all execution paths.}} +// ^^^^^ } void bar(boolean test) { @@ -28,22 +29,25 @@ void xmi(boolean test) { } else { d = c; // flow@xmi2 {{Implies 'd' has the same value as 'c'.}} } - b = d; // Noncompliant [[sc=5;ec=10;flows=xmi1,xmi2]] {{Remove this useless assignment; "b" already holds the assigned value along all execution paths.}} + b = d; // Noncompliant [[flows=xmi1,xmi2]] {{Remove this useless assignment; "b" already holds the assigned value along all execution paths.}} +// ^^^^^ } void gul(boolean test) { a = b; c = a; - b = test ? a : c; // Noncompliant [[sc=5;ec=21]] {{Remove this useless assignment; "b" already holds the assigned value along all execution paths.}} + b = test ? a : c; // Noncompliant {{Remove this useless assignment; "b" already holds the assigned value along all execution paths.}} +// ^^^^^^^^^^^^^^^^ } void moc(Object param) { - param = Objects.requireNonNull(param, "should not be null"); // Noncompliant [[sc=5;ec=64]] - param is reassigned with its own value + param = Objects.requireNonNull(param, "should not be null"); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } Object p; void mad() { - p = Objects.requireNonNull(p); // Noncompliant - p is reassigned with its own value + p = Objects.requireNonNull(p); // Noncompliant } Object[] arr; diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S2755_XxeProcessingCheck_DocumentBuilderFactory.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S2755_XxeProcessingCheck_DocumentBuilderFactory.java index 5d01dff01e0..fdc913e971f 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S2755_XxeProcessingCheck_DocumentBuilderFactory.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S2755_XxeProcessingCheck_DocumentBuilderFactory.java @@ -15,7 +15,8 @@ class DocumentBuilderFactoryTest { // Vulnerable when nothing is made to protect against xxe DocumentBuilderFactory no_property() { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // Noncompliant [[sc=61;ec=72]] {{Disable access to external entities in XML parsing.}} + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // Noncompliant {{Disable access to external entities in XML parsing.}} +// ^^^^^^^^^^^ return factory; } @@ -80,7 +81,8 @@ void secure_with_no_op_entity_resolver(InputStream is) throws Exception { } void insecure_with_null_entity_resolver(InputStream is) throws Exception { - DocumentBuilderFactory df = DocumentBuilderFactory.newInstance(); // Noncompliant [[sc=56;ec=67]] + DocumentBuilderFactory df = DocumentBuilderFactory.newInstance(); // Noncompliant +// ^^^^^^^^^^^ DocumentBuilder builder = df.newDocumentBuilder(); builder.setEntityResolver((publicId, systemId) -> new InputSource(new StringReader(""))); builder.setEntityResolver(null); diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S2755_XxeProcessingCheck_SaxBuilder.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S2755_XxeProcessingCheck_SaxBuilder.java index 5e6e735ef14..a92a4bac613 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S2755_XxeProcessingCheck_SaxBuilder.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S2755_XxeProcessingCheck_SaxBuilder.java @@ -15,7 +15,8 @@ class SAXBuilderTest { // Vulnerable when nothing is made to protect against xxe SAXBuilder no_property() { - SAXBuilder builder = new SAXBuilder(); // Noncompliant [[sc=30;ec=40]] + SAXBuilder builder = new SAXBuilder(); // Noncompliant +// ^^^^^^^^^^ return builder; } diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S2755_XxeProcessingCheck_SaxReader.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S2755_XxeProcessingCheck_SaxReader.java index 13afacb7991..fe9b679d598 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S2755_XxeProcessingCheck_SaxReader.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S2755_XxeProcessingCheck_SaxReader.java @@ -15,7 +15,8 @@ class SAXReaderTest { // Vulnerable when nothing is made to protect against xxe SAXReader no_property() { - SAXReader xmlReader = new SAXReader(); // Noncompliant [[sc=31;ec=40]] {{Disable access to external entities in XML parsing.}} + SAXReader xmlReader = new SAXReader(); // Noncompliant {{Disable access to external entities in XML parsing.}} +// ^^^^^^^^^ return xmlReader; } @@ -55,7 +56,7 @@ SAXReader secure_with_no_op_entity_resolver() throws SAXException { // "universal fix" not supported SAXReader univeral_fix() throws SAXException, ParserConfigurationException { - SAXReader xmlReader = new SAXReader(); // Noncompliant + SAXReader xmlReader = new SAXReader(); // Noncompliant xmlReader.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); xmlReader.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); return xmlReader; diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S2755_XxeProcessingCheck_TransformerFactory.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S2755_XxeProcessingCheck_TransformerFactory.java index b5e4c221c75..c01db79d766 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S2755_XxeProcessingCheck_TransformerFactory.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S2755_XxeProcessingCheck_TransformerFactory.java @@ -135,7 +135,7 @@ class TransformerFactoryCrossProceduralSideEffect2 { TransformerFactory cross_procedural() throws TransformerConfigurationException { // FP, SE limiation, we can not know the runtime type of enableSecureProcessing if it's not final, static, ... - TransformerFactory factory = TransformerFactory.newInstance(); // Noncompliant FP + TransformerFactory factory = TransformerFactory.newInstance(); // Noncompliant enableSecureProcessing(factory); return factory; } diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S2755_XxeProcessingCheck_XmlInputFactory.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S2755_XxeProcessingCheck_XmlInputFactory.java index 7131d9b0e8c..6a070906754 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S2755_XxeProcessingCheck_XmlInputFactory.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S2755_XxeProcessingCheck_XmlInputFactory.java @@ -9,7 +9,8 @@ class XMLInputFactoryTest { // Vulnerable when nothing is made to protect against xxe XMLInputFactory no_property_new_instance() { - XMLInputFactory factory = XMLInputFactory.newInstance(); // Noncompliant [[sc=47;ec=58]] {{Disable access to external entities in XML parsing.}} + XMLInputFactory factory = XMLInputFactory.newInstance(); // Noncompliant {{Disable access to external entities in XML parsing.}} +// ^^^^^^^^^^^ return factory; } diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S3958_StreamNotConsumedCheckSample.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S3958_StreamNotConsumedCheckSample.java index 10e0db617ca..f2653eeec94 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S3958_StreamNotConsumedCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S3958_StreamNotConsumedCheckSample.java @@ -18,7 +18,7 @@ void test2() { void test3() { Stream stream = Stream.of(1, 2, 3); - stream = stream.filter(e -> true); // Noncompliant + stream = stream.filter(e -> true); // Noncompliant stream = stream.skip(2); stream = stream.limit(1); } @@ -79,7 +79,7 @@ void exceptionalPath() { void exceptionalPath2() { try { - Stream.of(1,2,3).filter(e -> true); // Noncompliant + Stream.of(1,2,3).filter(e -> true); // Noncompliant Stream.of(1,2,3) .filter(e -> true) diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S6373_AllowXMLInclusionCheck_DocumentBuilderFactory.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S6373_AllowXMLInclusionCheck_DocumentBuilderFactory.java index 7e38c5d1a9a..94cbac5d676 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S6373_AllowXMLInclusionCheck_DocumentBuilderFactory.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S6373_AllowXMLInclusionCheck_DocumentBuilderFactory.java @@ -43,7 +43,8 @@ DocumentBuilderFactory x_include_feature_to_false() throws ParserConfigurationEx DocumentBuilderFactory x_include_setter_to_true() throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setXIncludeAware(true); // Noncompliant [[sc=5;ec=35]] {{Disable the inclusion of files in XML processing.}} + factory.setXIncludeAware(true); // Noncompliant {{Disable the inclusion of files in XML processing.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); return factory; } @@ -64,7 +65,8 @@ ValidatingDocumentBuilderFactory x_include_setter_to_true_on_subtype_of_Document Document x_include_setter_to_true_without_entity_resolver(InputStream is) throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setXIncludeAware(true); // Noncompliant [[sc=5;ec=35]] + factory.setXIncludeAware(true); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(is); diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S6373_AllowXMLInclusionCheck_SAXParserFactory.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S6373_AllowXMLInclusionCheck_SAXParserFactory.java index c55d19811a4..1f6cf9ce49f 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S6373_AllowXMLInclusionCheck_SAXParserFactory.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S6373_AllowXMLInclusionCheck_SAXParserFactory.java @@ -29,14 +29,15 @@ SAXParserFactory x_include_feature_to_false() throws SAXNotSupportedException, S SAXParserFactory x_include_setter_to_true() throws SAXNotSupportedException, SAXNotRecognizedException, ParserConfigurationException { SAXParserFactory factory = SAXParserFactory.newInstance(); - factory.setXIncludeAware(true); // Noncompliant [[sc=5;ec=35]] {{Disable the inclusion of files in XML processing.}} + factory.setXIncludeAware(true); // Noncompliant {{Disable the inclusion of files in XML processing.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); return factory; } SAXParserFactory x_include_feature_to_true() throws SAXNotSupportedException, SAXNotRecognizedException, ParserConfigurationException { SAXParserFactory factory = SAXParserFactory.newInstance(); - factory.setFeature("http://apache.org/xml/features/xinclude", true); // Noncompliant + factory.setFeature("http://apache.org/xml/features/xinclude", true); // Noncompliant factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); return factory; } diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S6373_AllowXMLInclusionCheck_XMLInputFactory.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S6373_AllowXMLInclusionCheck_XMLInputFactory.java index 2512cc62162..27332dd7f88 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S6373_AllowXMLInclusionCheck_XMLInputFactory.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S6373_AllowXMLInclusionCheck_XMLInputFactory.java @@ -22,14 +22,15 @@ XMLInputFactory x_include_feature_to_false() { XMLInputFactory x_include_feature_to_true() { XMLInputFactory factory = XMLInputFactory.newInstance(); - factory.setProperty("http://apache.org/xml/features/xinclude", true); // Noncompliant [[sc=5;ec=73]] {{Disable the inclusion of files in XML processing.}} + factory.setProperty("http://apache.org/xml/features/xinclude", true); // Noncompliant {{Disable the inclusion of files in XML processing.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ factory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE); return factory; } XMLInputFactory x_include_feature_to_true_without_entity_resolver() { XMLInputFactory factory = XMLInputFactory.newInstance(); - factory.setProperty("http://apache.org/xml/features/xinclude", true); // Noncompliant + factory.setProperty("http://apache.org/xml/features/xinclude", true); // Noncompliant factory.setXMLResolver(null); factory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE); return factory; diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S6377_XmlValidatedSignatureCheckSample.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S6377_XmlValidatedSignatureCheckSample.java index 59445c1b69c..fffcf67be4f 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S6377_XmlValidatedSignatureCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/S6377_XmlValidatedSignatureCheckSample.java @@ -61,7 +61,8 @@ private void coverage(DOMValidateContext valContext) { void noncompliant_1(Node node, KeySelector selector) throws Exception { DOMValidateContext valContext = new DOMValidateContext(selector, node); - valContext.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE); // Noncompliant [[sc=65;ec=78]] {{Change this to "true" to validate this XML signature securely.}} + valContext.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE); // Noncompliant {{Change this to "true" to validate this XML signature securely.}} +// ^^^^^^^^^^^^^ XMLSignature signature = fac.unmarshalXMLSignature(valContext); @@ -79,7 +80,8 @@ void noncompliant_2(Node node, KeySelector selector) throws Exception { void noncompliant_3(Node node, KeySelector selector) throws Exception { DOMValidateContext valContext = new DOMValidateContext(selector, node); valContext.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.TRUE); - valContext.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE); // Noncompliant [[sc=65;ec=78]] {{Change this to "true" to validate this XML signature securely.}} + valContext.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE); // Noncompliant {{Change this to "true" to validate this XML signature securely.}} +// ^^^^^^^^^^^^^ XMLSignature signature = fac.unmarshalXMLSignature(valContext); @@ -88,7 +90,8 @@ void noncompliant_3(Node node, KeySelector selector) throws Exception { DOMValidateContext noncompliant_4(Node node, KeySelector selector) throws Exception { DOMValidateContext valContext = new DOMValidateContext(selector, node); - valContext.setProperty("org.jcp.xml.dsig.secureValidation", false); // Noncompliant [[sc=65;ec=70]] {{Change this to "true" to validate this XML signature securely.}} + valContext.setProperty("org.jcp.xml.dsig.secureValidation", false); // Noncompliant {{Change this to "true" to validate this XML signature securely.}} +// ^^^^^ return valContext; } diff --git a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/XmlParserLoadsExternalSchemasCheck.java b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/XmlParserLoadsExternalSchemasCheck.java index c162aa7a105..7f286af52d1 100644 --- a/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/XmlParserLoadsExternalSchemasCheck.java +++ b/java-checks-test-sources/default/src/main/java/symbolicexecution/checks/XmlParserLoadsExternalSchemasCheck.java @@ -23,7 +23,8 @@ static DocumentBuilderFactory getDocumentBuilderFactory() throws ParserConfigura // Securing against S2755 factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); factory.setValidating(true); // We only report on the first location - factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", true); // Noncompliant [[sc=7;ec=97]] {{Disable loading of external schemas in XML parsing.}} + factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", true); // Noncompliant {{Disable loading of external schemas in XML parsing.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ return factory; } @@ -32,7 +33,8 @@ static DocumentBuilderFactory getDocumentBuilderFactorySetValidatingTrueLast() t // Securing against S2755 factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", true); - factory.setValidating(true); // Noncompliant [[sc=7;ec=34]] {{Disable loading of external schemas in XML parsing.}} + factory.setValidating(true); // Noncompliant {{Disable loading of external schemas in XML parsing.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ return factory; } @@ -73,7 +75,7 @@ static SAXReader getSAXReader() throws SAXException { // Securing against S2755 saxReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); - saxReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", true); // Noncompliant {{Disable loading of external schemas in XML parsing.}} + saxReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", true); // Noncompliant {{Disable loading of external schemas in XML parsing.}} return saxReader; } diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertJApplyConfigurationCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertJApplyConfigurationCheckSample.java index 70af952351e..9a86552a9e9 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertJApplyConfigurationCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertJApplyConfigurationCheckSample.java @@ -4,7 +4,8 @@ public class AssertJApplyConfigurationCheckSample { void notApplied() { - Configuration configuration = new Configuration(); // Noncompliant [[sc=19;ec=32]] {{Apply this configuration with apply() or applyAndDisplay().}} + Configuration configuration = new Configuration(); // Noncompliant {{Apply this configuration with apply() or applyAndDisplay().}} +// ^^^^^^^^^^^^^ configuration.setComparingPrivateFields(true); configuration.setMaxElementsForPrinting(1001); } diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertJAssertionsInConsumerCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertJAssertionsInConsumerCheckSample.java index 1d5274cddb3..db7c9f75c29 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertJAssertionsInConsumerCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertJAssertionsInConsumerCheckSample.java @@ -17,9 +17,15 @@ public abstract class AssertJAssertionsInConsumerCheckSample { public void testIsInstanceOfSatisfying(Consumer unknownRequirements) { Object myObj = getSomeObject(); Consumer myPredicateAsConsumer = s -> s.equals("b"); - assertThat(myObj).isInstanceOfSatisfying(String.class, "b"::equals); // Noncompliant [[sc=23;ec=45;secondary=20]] {{Rework this assertion to assert something inside the Consumer argument.}} - assertThat(myObj).isInstanceOfSatisfying(String.class, s -> s.equals("b")); // Noncompliant [[sc=23;ec=45;secondary=21]] - assertThat(myObj).isInstanceOfSatisfying(String.class, myPredicateAsConsumer); // Noncompliant [[sc=23;ec=45;secondary=22]] + assertThat(myObj).isInstanceOfSatisfying(String.class, "b"::equals); // Noncompliant {{Rework this assertion to assert something inside the Consumer argument.}} +// ^^^^^^^^^^^^^^^^^^^^^^ +// ^^^^^^^^^^^@-1< + assertThat(myObj).isInstanceOfSatisfying(String.class, s -> s.equals("b")); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^ +// ^^^^^^^^^^^^^^^^^^@-1< + assertThat(myObj).isInstanceOfSatisfying(String.class, myPredicateAsConsumer); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^ +// ^^^^^^^^^^^^^^^^^^^^^@-1< Consumer myRequirements = s -> assertThat(s).isEqualTo("b"); assertThat(myObj).isInstanceOfSatisfying(String.class, s -> assertThat(s).isEqualTo("b")); @@ -51,11 +57,16 @@ public void testSatisfiesAnyOf(Consumer unknownRequirements) { Consumer myPredicateAsConsumer = s -> s.equals("b"); Consumer myRequirements = s -> assertThat(s).isEqualTo("b"); - assertThat("a").satisfiesAnyOf("b"::equals, "c"::equals); // Noncompliant [[secondary=54,54]] - assertThat("a").satisfiesAnyOf("b"::equals, "c"::equals, "d"::equals); // Noncompliant [[secondary=55,55,55]] + assertThat("a").satisfiesAnyOf("b"::equals, "c"::equals); // Noncompliant +// ^^^^^^^^^^^^^^ ^^^^^^^^^^^< +// ^^^^^^^^^^^@-1< + assertThat("a").satisfiesAnyOf("b"::equals, "c"::equals, "d"::equals); // Noncompliant +// ^^^^^^^^^^^^^^ ^^^^^^^^^^^< ^^^^^^^^^^^< ^^^^^^^^^^^< + assertThat("a").satisfiesAnyOf("b"::equals, "c"::equals, "d"::equals, "e"::equals); // Noncompliant assertThat("a").satisfiesAnyOf("b"::equals, s -> s.equals("b"), myPredicateAsConsumer); // Noncompliant - assertThat("a").satisfiesAnyOf(myRequirements, myRequirements, myRequirements, "c"::equals); // Noncompliant [[secondary=58]] - only last argument is missing an assertion + assertThat("a").satisfiesAnyOf(myRequirements, myRequirements, myRequirements, "c"::equals); // Noncompliant +// ^^^^^^^^^^^^^^ ^^^^^^^^^^^< assertThat("a").satisfiesAnyOf(myRequirements, myRequirements); assertThat("a").satisfiesAnyOf(myRequirements, myRequirements, myRequirements); diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertJChainSimplificationCheckTest.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertJChainSimplificationCheckTest.java index 7a1a584f1fe..8e4482bd0fc 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertJChainSimplificationCheckTest.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertJChainSimplificationCheckTest.java @@ -108,12 +108,14 @@ void objectRelatedAssertionChains() { Comparable x = getBoolean(); Object y = getObject(); - assertThat(getObject()).isEqualTo(null); // Noncompliant [[sc=29;ec=38]] {{Use isNull() instead.}} + assertThat(getObject()).isEqualTo(null); // Noncompliant {{Use isNull() instead.}} +// ^^^^^^^^^ assertThat(getObject()).isNotEqualTo(null); // Noncompliant {{Use isNotNull() instead.}} assertThat(getObject()) .isEqualTo(null) // Noncompliant .isNotEqualTo(getObject()); - assertThat(getObject()).as("some message)").isEqualTo(getObject()).withFailMessage("another message)").isNotEqualTo(null).as("a third message"); // Noncompliant [[sc=108;ec=120]] + assertThat(getObject()).as("some message)").isEqualTo(getObject()).withFailMessage("another message)").isNotEqualTo(null).as("a third message"); // Noncompliant +// ^^^^^^^^^^^^ assertThat(new Object()).isEqualTo(null) // Noncompliant .isNotEqualTo(null); // Noncompliant @@ -123,7 +125,9 @@ void objectRelatedAssertionChains() { assertThat(getObject()).isEqualTo(false); // Compliant assertThat(getObject()).isEqualTo(""); // Compliant assertThat(getObject()).isEqualTo(0); // Compliant - assertThat(x.equals(y)).isTrue(); // Noncompliant [[sc=29;ec=35;secondary=+0]] {{Use assertThat(actual).isEqualTo(expected) instead.}} + assertThat(x.equals(y)).isTrue(); // Noncompliant {{Use assertThat(actual).isEqualTo(expected) instead.}} +// ^^^^^^ +// ^^^^^^^^^^^@-1< assertThat(x.equals(y)).isFalse(); // Noncompliant {{Use assertThat(actual).isNotEqualTo(expected) instead.}} assertThat(x == y).isTrue(); // Noncompliant {{Use assertThat(actual).isSameAs(expected) instead.}} assertThat(x == y).isFalse(); // Noncompliant {{Use assertThat(actual).isNotSameAs(expected) instead.}} @@ -142,7 +146,8 @@ void objectRelatedAssertionChains() { assertThat(x.compareTo(y)).isNotEqualTo(0); // Noncompliant {{Use isNotZero() instead.}} assertThat(getObject()).isNotEqualTo(0); // Compliant, can not use isNotZero on object assertThat(x.compareTo(y)).as("message").isNotEqualTo(0); // Noncompliant - assertThat(x.compareTo(y)).isNotEqualTo(4).isNotEqualTo(null).isNotEqualTo(-1); // Noncompliant [[sc=48;ec=60]] - but only raise issue on the 'null' check + assertThat(x.compareTo(y)).isNotEqualTo(4).isNotEqualTo(null).isNotEqualTo(-1); // Noncompliant +// ^^^^^^^^^^^^ assertThat(x.compareTo(y)).isZero(); // Noncompliant {{Use assertThat(actual).isEqualByComparingTo(expected) instead.}} assertThat(x.compareTo(y)).isNotZero(); // Noncompliant {{Use assertThat(actual).isNotEqualByComparingTo(expected) instead.}} @@ -351,45 +356,45 @@ void fileRelatedAssertionChains() { assertThat(getFile().length()).isZero(); // Noncompliant {{Use assertThat(actual).isEmpty() instead.}} assertThat(getFile().length()).isEqualTo(0); // Noncompliant {{Use isZero() instead.}} assertThat(getFile().length()).isNotZero(); // Noncompliant {{Use assertThat(actual).isNotEmpty() instead.}} - assertThat(getFile().length()).isNotEqualTo(0); // Noncompliant {{Use isNotZero() instead.}} + assertThat(getFile().length()).isNotEqualTo(0); // Noncompliant {{Use isNotZero() instead.}} assertThat(getFile().length()).isEqualTo(size); // Noncompliant {{Use assertThat(actual).hasSize(expected) instead.}} assertThat(getFile().length()).isPositive(); // Noncompliant {{Use assertThat(actual).isNotEmpty() instead.}} assertThat(getFile().canRead()).isTrue(); // Noncompliant {{Use assertThat(actual).canRead() instead.}} assertThat(getFile().canWrite()).isTrue(); // Noncompliant {{Use assertThat(actual).canWrite() instead.}} - assertThat(getFile().exists()).isTrue();// Noncompliant {{Use assertThat(actual).exists() instead.}} - assertThat(getFile().exists()).isFalse(); // Noncompliant {{Use assertThat(actual).doesNotExist() instead.}} + assertThat(getFile().exists()).isTrue(); // Noncompliant {{Use assertThat(actual).exists() instead.}} + assertThat(getFile().exists()).isFalse(); // Noncompliant {{Use assertThat(actual).doesNotExist() instead.}} assertThat(getFile().getName()).isEqualTo(name); // Noncompliant {{Use assertThat(actual).hasName(expected) instead.}} assertThat(getFile().getParent()).isEqualTo(name); // Noncompliant {{Use assertThat(actual).hasParent(expected) instead.}} assertThat(getFile().getParentFile()).isEqualTo(getFile()); // Noncompliant {{Use assertThat(actual).hasParent(expected) instead.}} - assertThat(getFile().getParent()).isNull(); // Noncompliant {{Use assertThat(actual).hasNoParent() instead.}} - assertThat(getFile().getParentFile()).isNull(); // Noncompliant {{Use assertThat(actual).hasNoParent() instead.}} - assertThat(getFile().isAbsolute()).isTrue(); // Noncompliant {{Use assertThat(actual).isAbsolute() instead.}} - assertThat(getFile().isAbsolute()).isFalse(); // Noncompliant {{Use assertThat(actual).isRelative() instead.}} - assertThat(getFile().isDirectory()).isTrue(); // Noncompliant {{Use assertThat(actual).isDirectory() instead.}} - assertThat(getFile().isFile()).isTrue(); // Noncompliant {{Use assertThat(actual).isFile() instead.}} - - assertThat(getFile().list()).isEmpty(); // Noncompliant {{Use assertThat(actual).isEmptyDirectory() instead.}} - assertThat(getFile().listFiles()).isEmpty(); // Noncompliant {{Use assertThat(actual).isEmptyDirectory() instead.}} - assertThat(getFile().list()).isNotEmpty(); // Noncompliant {{Use assertThat(actual).isNotEmptyDirectory() instead.}} - assertThat(getFile().listFiles()).isNotEmpty(); // Noncompliant {{Use assertThat(actual).isNotEmptyDirectory() instead.}} + assertThat(getFile().getParent()).isNull(); // Noncompliant {{Use assertThat(actual).hasNoParent() instead.}} + assertThat(getFile().getParentFile()).isNull(); // Noncompliant {{Use assertThat(actual).hasNoParent() instead.}} + assertThat(getFile().isAbsolute()).isTrue(); // Noncompliant {{Use assertThat(actual).isAbsolute() instead.}} + assertThat(getFile().isAbsolute()).isFalse(); // Noncompliant {{Use assertThat(actual).isRelative() instead.}} + assertThat(getFile().isDirectory()).isTrue(); // Noncompliant {{Use assertThat(actual).isDirectory() instead.}} + assertThat(getFile().isFile()).isTrue(); // Noncompliant {{Use assertThat(actual).isFile() instead.}} + + assertThat(getFile().list()).isEmpty(); // Noncompliant {{Use assertThat(actual).isEmptyDirectory() instead.}} + assertThat(getFile().listFiles()).isEmpty(); // Noncompliant {{Use assertThat(actual).isEmptyDirectory() instead.}} + assertThat(getFile().list()).isNotEmpty(); // Noncompliant {{Use assertThat(actual).isNotEmptyDirectory() instead.}} + assertThat(getFile().listFiles()).isNotEmpty(); // Noncompliant {{Use assertThat(actual).isNotEmptyDirectory() instead.}} // We report only step by step, not the final transformation possible assertThat(getFile().list().length).isEqualTo(0); // Noncompliant {{Use isZero() instead.}} assertThat(getFile().list().length).isZero(); // Noncompliant {{Use assertThat(actual).isEmpty() instead.}} - assertThat(getFile().list()).isEmpty(); // Noncompliant {{Use assertThat(actual).isEmptyDirectory() instead.}} + assertThat(getFile().list()).isEmpty(); // Noncompliant {{Use assertThat(actual).isEmptyDirectory() instead.}} assertThat(getFile()).isEmptyDirectory(); // Compliant, 3 iterations to reach a nice assertion } void pathRelatedAssertionChains() { String name = "path"; - assertThat(getPath().startsWith(name)).isTrue(); // Noncompliant {{Use assertThat(actual).startsWithRaw(expected) instead.}} - assertThat(getPath().endsWith(name)).isTrue(); // Noncompliant {{Use assertThat(actual).endsWithRaw(expected) instead.}} - assertThat(getPath().getParent()).isEqualTo(name); // Noncompliant {{Use assertThat(actual).hasParentRaw(expected) instead.}} - assertThat(getPath().getParent()).isNull(); // Noncompliant {{Use assertThat(actual).hasNoParentRaw() instead.}} - assertThat(getPath().isAbsolute()).isTrue(); // Noncompliant {{Use assertThat(actual).isAbsolute() instead.}} - assertThat(getPath().isAbsolute()).isFalse(); // Noncompliant {{Use assertThat(actual).isRelative() instead.}} + assertThat(getPath().startsWith(name)).isTrue(); // Noncompliant {{Use assertThat(actual).startsWithRaw(expected) instead.}} + assertThat(getPath().endsWith(name)).isTrue(); // Noncompliant {{Use assertThat(actual).endsWithRaw(expected) instead.}} + assertThat(getPath().getParent()).isEqualTo(name); // Noncompliant {{Use assertThat(actual).hasParentRaw(expected) instead.}} + assertThat(getPath().getParent()).isNull(); // Noncompliant {{Use assertThat(actual).hasNoParentRaw() instead.}} + assertThat(getPath().isAbsolute()).isTrue(); // Noncompliant {{Use assertThat(actual).isAbsolute() instead.}} + assertThat(getPath().isAbsolute()).isFalse(); // Noncompliant {{Use assertThat(actual).isRelative() instead.}} } void optionalRelatedAssertionChains() { @@ -419,8 +424,8 @@ void contextFreeWithLong() { assertThat(getLong()).isGreaterThanOrEqualTo(42L); // Compliant assertThat(getLong()).isLessThan(0L); // Noncompliant {{Use isNegative() instead.}} assertThat(getLong()).isLessThan(1L); // Noncompliant {{Use isNotPositive() instead.}} - assertThat(getLong()).isLessThanOrEqualTo(0L);// Noncompliant {{Use isNotPositive() instead.}} - assertThat(getLong()).isLessThanOrEqualTo(-1L);// Noncompliant {{Use isNegative() instead.}} + assertThat(getLong()).isLessThanOrEqualTo(0L); // Noncompliant {{Use isNotPositive() instead.}} + assertThat(getLong()).isLessThanOrEqualTo(-1L); // Noncompliant {{Use isNegative() instead.}} assertThat(getLong()).isLessThanOrEqualTo(-42L);// Compliant assertThat(getLong()).isNotEqualTo(0L); // Noncompliant {{Use isNotZero() instead.}} } diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertJChainSimplificationCheckTest_QuickFix.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertJChainSimplificationCheckTest_QuickFix.java index 0d6dd5fee7e..743c39068fc 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertJChainSimplificationCheckTest_QuickFix.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertJChainSimplificationCheckTest_QuickFix.java @@ -10,13 +10,16 @@ public class AssertJChainSimplificationCheckTest_QuickFix { void contextFreeQuickFixes() { - assertThat(getString()).hasSize(0); // Noncompliant [[sc=29;ec=36;quickfixes=qf_context_free1]] {{Use isEmpty() instead.}} + assertThat(getString()).hasSize(0); // Noncompliant {{Use isEmpty() instead.}} [[quickfixes=qf_context_free1]] +// ^^^^^^^ // fix@qf_context_free1 {{Use "isEmpty()"}} // edit@qf_context_free1 [[sc=29;ec=39]] {{isEmpty()}} - assertThat(getObject()).isEqualTo(null); // Noncompliant [[sc=29;ec=38;quickfixes=qf_context_free2]] {{Use isNull() instead.}} + assertThat(getObject()).isEqualTo(null); // Noncompliant {{Use isNull() instead.}} [[quickfixes=qf_context_free2]] +// ^^^^^^^^^ // fix@qf_context_free2 {{Use "isNull()"}} // edit@qf_context_free2 [[sc=29;ec=44]] {{isNull()}} - assertThat(getString().indexOf(12)).isLessThan(0); // Noncompliant [[sc=41;ec=51;quickfixes=qf_context_free3]] {{Use isNegative() instead.}} + assertThat(getString().indexOf(12)).isLessThan(0); // Noncompliant {{Use isNegative() instead.}} [[quickfixes=qf_context_free3]] +// ^^^^^^^^^^ // fix@qf_context_free3 {{Use "isNegative()"}} // edit@qf_context_free3 [[sc=41;ec=54]] {{isNegative()}} } @@ -26,74 +29,89 @@ void withContextQuickFixes() { String y = "y"; int length = 42; - assertThat(getString().length()).isZero(); // Noncompliant [[sc=38;ec=44;quickfixes=qf_context1]] {{Use assertThat(actual).isEmpty() instead.}} + assertThat(getString().length()).isZero(); // Noncompliant {{Use assertThat(actual).isEmpty() instead.}} [[quickfixes=qf_context1]] +// ^^^^^^ // fix@qf_context1 {{Use "assertThat(actual).isEmpty()"}} // edit@qf_context1 [[sc=27;ec=36]] {{}} // edit@qf_context1 [[sc=38;ec=46]] {{isEmpty()}} - assertThat(getFile().isAbsolute()).isFalse(); // Noncompliant [[sc=40;ec=47;quickfixes=qf_context2]] {{Use assertThat(actual).isRelative() instead.}} + assertThat(getFile().isAbsolute()).isFalse(); // Noncompliant {{Use assertThat(actual).isRelative() instead.}} [[quickfixes=qf_context2]] +// ^^^^^^^ // fix@qf_context2 {{Use "assertThat(actual).isRelative()"}} // edit@qf_context2 [[sc=25;ec=38]] {{}} // edit@qf_context2 [[sc=40;ec=49]] {{isRelative()}} // Expected is in the subject argument: - assertThat(getString().matches(x)).isTrue(); // Noncompliant [[sc=40;ec=46;quickfixes=qf_context3]] {{Use assertThat(actual).matches(expected) instead.}} + assertThat(getString().matches(x)).isTrue(); // Noncompliant {{Use assertThat(actual).matches(expected) instead.}} [[quickfixes=qf_context3]] +// ^^^^^^ // fix@qf_context3 {{Use "assertThat(actual).matches(expected)"}} // edit@qf_context3 [[sc=27;ec=36]] {{).matches(}} // edit@qf_context3 [[sc=38;ec=48]] {{}} - assertThat(getString().indexOf(x)).isEqualTo(-1); // Noncompliant [[sc=40;ec=49;quickfixes=qf_context4]] {{Use assertThat(actual).doesNotContain(expected) instead.}} + assertThat(getString().indexOf(x)).isEqualTo(-1); // Noncompliant {{Use assertThat(actual).doesNotContain(expected) instead.}} [[quickfixes=qf_context4]] +// ^^^^^^^^^ // fix@qf_context4 {{Use "assertThat(actual).doesNotContain(expected)"}} // edit@qf_context4 [[sc=27;ec=36]] {{).doesNotContain(}} // edit@qf_context4 [[sc=38;ec=53]] {{}} // Expected is in the predicate argument - assertThat(getString().length()).isEqualTo(12); // Noncompliant [[sc=38;ec=47;quickfixes=qf_context5]] {{Use assertThat(actual).hasSize(expected) instead.}} + assertThat(getString().length()).isEqualTo(12); // Noncompliant {{Use assertThat(actual).hasSize(expected) instead.}} [[quickfixes=qf_context5]] +// ^^^^^^^^^ // fix@qf_context5 {{Use "assertThat(actual).hasSize(expected)"}} // edit@qf_context5 [[sc=27;ec=36]] {{}} // edit@qf_context5 [[sc=38;ec=47]] {{hasSize}} - assertThat(getCollection().size()).isGreaterThan(length); // Noncompliant [[sc=40;ec=53;quickfixes=qf_context6]] {{Use assertThat(actual).hasSizeGreaterThan(expected) instead.}} + assertThat(getCollection().size()).isGreaterThan(length); // Noncompliant {{Use assertThat(actual).hasSizeGreaterThan(expected) instead.}} [[quickfixes=qf_context6]] +// ^^^^^^^^^^^^^ // fix@qf_context6 {{Use "assertThat(actual).hasSizeGreaterThan(expected)"}} // edit@qf_context6 [[sc=31;ec=38]] {{}} // edit@qf_context6 [[sc=40;ec=53]] {{hasSizeGreaterThan}} // With context because we have to check that the argument of the subject is of a given type, but the fix is the same as a context free one. - assertThat(getString().indexOf(x)).isEqualTo(0); // Noncompliant [[sc=40;ec=49;quickfixes=qf_context7]] {{Use isZero() instead.}} + assertThat(getString().indexOf(x)).isEqualTo(0); // Noncompliant {{Use isZero() instead.}} [[quickfixes=qf_context7]] +// ^^^^^^^^^ // fix@qf_context7 {{Use "isZero()"}} // edit@qf_context7 [[sc=40;ec=52]] {{isZero()}} // If "y" is not a comparable, the fix will lead to non-compilable code. The assertion does not makes sense in the first place anyway, this is acceptable. - assertThat(x.compareTo(y)).isPositive(); // Noncompliant [[sc=32;ec=42;quickfixes=qf_context8]] {{Use assertThat(actual).isGreaterThan(expected) instead.}} + assertThat(x.compareTo(y)).isPositive(); // Noncompliant {{Use assertThat(actual).isGreaterThan(expected) instead.}} [[quickfixes=qf_context8]] +// ^^^^^^^^^^ // fix@qf_context8 {{Use "assertThat(actual).isGreaterThan(expected)"}} // edit@qf_context8 [[sc=17;ec=28]] {{).isGreaterThan(}} // edit@qf_context8 [[sc=30;ec=44]] {{}} - assertThat(getArray().length).isPositive(); // Noncompliant [[sc=35;ec=45;quickfixes=qf_context9]] {{Use assertThat(actual).isNotEmpty() instead.}} + assertThat(getArray().length).isPositive(); // Noncompliant {{Use assertThat(actual).isNotEmpty() instead.}} [[quickfixes=qf_context9]] +// ^^^^^^^^^^ // fix@qf_context9 {{Use "assertThat(actual).isNotEmpty()"}} // edit@qf_context9 [[sc=26;ec=33]] {{}} // edit@qf_context9 [[sc=35;ec=47]] {{isNotEmpty()}} - assertThat(getArray().length).isEqualTo(length); // Noncompliant [[sc=35;ec=44;quickfixes=qf_context10]] {{Use assertThat(actual).hasSize(expected) instead.}} + assertThat(getArray().length).isEqualTo(length); // Noncompliant {{Use assertThat(actual).hasSize(expected) instead.}} [[quickfixes=qf_context10]] +// ^^^^^^^^^ // fix@qf_context10 {{Use "assertThat(actual).hasSize(expected)"}} // edit@qf_context10 [[sc=26;ec=33]] {{}} // edit@qf_context10 [[sc=35;ec=44]] {{hasSize}} // Parenthesis in the predicate is not a problem through - assertThat(getCollection().size()).isGreaterThan(((length))); // Noncompliant [[sc=40;ec=53;quickfixes=qf_context11]] {{Use assertThat(actual).hasSizeGreaterThan(expected) instead.}} + assertThat(getCollection().size()).isGreaterThan(((length))); // Noncompliant {{Use assertThat(actual).hasSizeGreaterThan(expected) instead.}} [[quickfixes=qf_context11]] +// ^^^^^^^^^^^^^ // fix@qf_context11 {{Use "assertThat(actual).hasSizeGreaterThan(expected)"}} // edit@qf_context11 [[sc=31;ec=38]] {{}} // edit@qf_context11 [[sc=40;ec=53]] {{hasSizeGreaterThan}} // No quick fix suggested with redundant parenthesis in the subject, it is a non-trivial fix and // the dev should anyway remove the redundant parenthesis, that will make the issue appear - assertThat(((getArray().length))).isEqualTo(length); // Noncompliant [[sc=39;ec=48;quickfixes=!]] - assertThat((((x.compareTo(y))))).isPositive(); // Noncompliant [[sc=38;ec=48;quickfixes=!]] + assertThat(((getArray().length))).isEqualTo(length); // Noncompliant [[quickfixes=!]] +// ^^^^^^^^^ + assertThat((((x.compareTo(y))))).isPositive(); // Noncompliant [[quickfixes=!]] +// ^^^^^^^^^^ // No quick fix provided (for now), should be done in case by case (non-exhaustive list) - assertThat(x.hashCode()).isEqualTo(y.hashCode()); // Noncompliant [[sc=30;ec=39;quickfixes=!]] {{Use assertThat(actual).hasSameHashCodeAs(expected) instead.}} - assertThat(getMap().get(x)).isEqualTo(y); // Noncompliant [[sc=33;ec=42;quickfixes=!]] {{Use assertThat(actual).containsEntry(key, value) instead.}} + assertThat(x.hashCode()).isEqualTo(y.hashCode()); // Noncompliant {{Use assertThat(actual).hasSameHashCodeAs(expected) instead.}} [[quickfixes=!]] +// ^^^^^^^^^ + assertThat(getMap().get(x)).isEqualTo(y); // Noncompliant {{Use assertThat(actual).containsEntry(key, value) instead.}} [[quickfixes=!]] +// ^^^^^^^^^ } private Map getMap() { diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertJConsecutiveAssertionCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertJConsecutiveAssertionCheckSample.java index f90dd300ac3..4eae4d82c29 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertJConsecutiveAssertionCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertJConsecutiveAssertionCheckSample.java @@ -18,9 +18,12 @@ public class AssertJConsecutiveAssertionCheckSample { @Test void simple_example() { - assertThat(myString).hasSize(2); // Noncompliant [[sc=5;ec=15;secondary=+1,+2]] {{Join these multiple assertions subject to one assertion chain.}} + assertThat(myString).hasSize(2); // Noncompliant {{Join these multiple assertions subject to one assertion chain.}} +// ^^^^^^^^^^ assertThat(myString).startsWith("4"); +// ^^^^^^^^^^< assertThat(myString).isEqualTo("42"); +// ^^^^^^^^^^< } @Test @@ -46,10 +49,14 @@ void two_assert_subject_argument() { @Test void two_assert_subject_argument_2() { - assertThat(myOtherString).hasSize(2); // Noncompliant [[sc=5;ec=15;secondary=+1]] + assertThat(myOtherString).hasSize(2); // Noncompliant +// ^^^^^^^^^^ assertThat(myOtherString).startsWith("2"); - assertThat(myString).startsWith("4"); // Noncompliant [[sc=5;ec=15;secondary=+1]] +// ^^^^^^^^^^< + assertThat(myString).startsWith("4"); // Noncompliant +// ^^^^^^^^^^ assertThat(myString).isEqualTo("42"); +// ^^^^^^^^^^< } @Test @@ -293,29 +300,39 @@ class CustomAssertions { @Test void nonCompliantTypeTest1() { - assertThat(myType).isNotNull(); // Noncompliant [[secondary=+1]] + assertThat(myType).isNotNull(); // Noncompliant +// ^^^^^^^^^^ assertThat(myType).isEqualTo(new MyType()); +// ^^^^^^^^^^< - CustomAssert.assertThat(myType).isFoo(); // Noncompliant [[secondary=+1]] + CustomAssert.assertThat(myType).isFoo(); // Noncompliant +// ^^^^^^^^^^ CustomAssert.assertThat(myType).isBar(); +// ^^^^^^^^^^< } @Test void nonCompliantTypeTest2() { - CustomAssert.assertThat(myType).isFoo(); // Noncompliant [[secondary=+1,+3,+4]] + CustomAssert.assertThat(myType).isFoo(); // Noncompliant +// ^^^^^^^^^^ CustomAssert.assertThat(myType).isBar(); +// ^^^^^^^^^^< assertThat(myType).isNotNull(); // will be included +// ^^^^^^^^^^< assertThat(myType).isEqualTo(new MyType()); +// ^^^^^^^^^^< } @Test void nonCompliantTypeTest3() { - CustomAssert.assertThat(myType) // Noncompliant [[secondary=+4]] + CustomAssert.assertThat(myType) // Noncompliant +// ^^^^^^^^^^ .isFoo() .isBar(); assertThat(myType) +// ^^^^^^^^^^< .isNotNull() .isEqualTo(new MyType()); } @@ -323,9 +340,12 @@ void nonCompliantTypeTest3() { @Test void nonCompliantTypeTest4() { assertThat(myType).isNotNull(); // Compliant - mixed, can not be chained - CustomAssert.assertThat(myType).isBar(); // Noncompliant [[secondary=+1,+2]] + CustomAssert.assertThat(myType).isBar(); // Noncompliant +// ^^^^^^^^^^ assertThat(myType).isEqualTo(new MyType()); +// ^^^^^^^^^^< CustomAssert.assertThat(myType).isBar(); +// ^^^^^^^^^^< } @Test diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertJContextBeforeAssertionCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertJContextBeforeAssertionCheckSample.java index 471b1789e3e..b6e949003f5 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertJContextBeforeAssertionCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertJContextBeforeAssertionCheckSample.java @@ -15,14 +15,17 @@ public class AssertJContextBeforeAssertionCheckSample { void foo() { assertThat("").isEqualTo("").as("Description1").isEqualTo(""); // Compliant - assertThat("").isEqualTo("").as("Description"); // Noncompliant [[sc=34;ec=36]] {{Add an assertion predicate after calling this method.}} + assertThat("").isEqualTo("").as("Description"); // Noncompliant {{Add an assertion predicate after calling this method.}} +// ^^ assertThat("").isEqualTo("").as(new TextDescription("Description")); // Noncompliant assertThat("").isEqualTo("").as("Description", new Object()); // Noncompliant - assertThat("").as("Description1").isEqualTo("").as("Description2"); // Noncompliant [[sc=53;ec=55]] + assertThat("").as("Description1").isEqualTo("").as("Description2"); // Noncompliant +// ^^ assertThat("").as("Description").isEqualTo(""); // Compliant assertThat("").isEqualTo("").as("Description1").isEqualTo(""); // Compliant - assertThat("").isEqualTo("").describedAs("Description"); // Noncompliant [[sc=34;ec=45]] + assertThat("").isEqualTo("").describedAs("Description"); // Noncompliant +// ^^^^^^^^^^^ assertThat("").isEqualTo("").describedAs(new TextDescription("Description")); // Noncompliant assertThat("").isEqualTo("").describedAs("Description", new Object()); // Noncompliant assertThat("").describedAs("Description").isEqualTo(""); // Compliant @@ -75,7 +78,8 @@ public int compare(Integer o1, Integer o2) { assertThat(getList()).isEqualTo(new ArrayList<>()).filteredOnAssertions(o -> {}); // Noncompliant // Only one issue when multiple missplaced calls. - assertThat("").isEqualTo("").as("message").withFailMessage("fail message"); // Noncompliant [[sc=48;ec=63]] + assertThat("").isEqualTo("").as("message").withFailMessage("fail message"); // Noncompliant +// ^^^^^^^^^^^^^^^ // assertThatObject assertThatObject("").isEqualTo("").as("Description1"); // Noncompliant diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertJTestForEmptinessCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertJTestForEmptinessCheckSample.java index 50b4ad38e08..a0fe9b3d6ec 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertJTestForEmptinessCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertJTestForEmptinessCheckSample.java @@ -15,7 +15,9 @@ public class AssertJTestForEmptinessCheckSample { @Test void simple_all_match() { List logs = getLogs(); - assertThat(logs).allMatch(e -> e.contains("error")); // Noncompliant [[sc=22;ec=30;secondary=18]] {{Test the emptiness of the list before calling this assertion predicate.}} + assertThat(logs).allMatch(e -> e.contains("error")); // Noncompliant {{Test the emptiness of the list before calling this assertion predicate.}} +// ^^^^^^^^ +// ^^^^@-1< } @Test diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertThatThrownByAloneCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertThatThrownByAloneCheckSample.java index 4318eaa0052..f09d27dcae3 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertThatThrownByAloneCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertThatThrownByAloneCheckSample.java @@ -10,8 +10,10 @@ public class AssertThatThrownByAloneCheckSample { @Test void noncompliant() { - assertThatThrownBy(() -> shouldThrow()); // Noncompliant [[sc=5;ec=23]] {{Test further the exception raised by this assertThatThrownBy call.}} - assertThatThrownBy(() -> shouldThrow(), "Don't do that"); // Noncompliant [[sc=5;ec=23]] {{Test further the exception raised by this assertThatThrownBy call.}} + assertThatThrownBy(() -> shouldThrow()); // Noncompliant {{Test further the exception raised by this assertThatThrownBy call.}} +// ^^^^^^^^^^^^^^^^^^ + assertThatThrownBy(() -> shouldThrow(), "Don't do that"); // Noncompliant {{Test further the exception raised by this assertThatThrownBy call.}} +// ^^^^^^^^^^^^^^^^^^ } @Test diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertTrueInsteadOfDedicatedAssertCheckTest.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertTrueInsteadOfDedicatedAssertCheckTest.java index 9f3171bd375..ddb35e8236a 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertTrueInsteadOfDedicatedAssertCheckTest.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertTrueInsteadOfDedicatedAssertCheckTest.java @@ -41,7 +41,9 @@ boolean predicate() { } void assertTrue_JUnit4_orgJunitAssert() { - Assert.assertTrue(null == foo); // Noncompliant [[sc=12;ec=22;secondary=44]] {{Use assertNull instead.}} + Assert.assertTrue(null == foo); // Noncompliant {{Use assertNull instead.}} +// ^^^^^^^^^^ +// ^^^^^^^^^^^@-1< assertTrue(foo == null); // Noncompliant Assert.assertTrue(foo != null); // Noncompliant {{Use assertNotNull instead.}} diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionArgumentOrderCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionArgumentOrderCheckSample.java index 7efa1916084..18c459f8ba5 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionArgumentOrderCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionArgumentOrderCheckSample.java @@ -1,15 +1,18 @@ package checks.tests; -import static org.assertj.core.api.Assertions.assertThatObject; -import static org.junit.Assert.*; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatObject; import static org.assertj.core.api.AssertionsForClassTypes.withinPercentage; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; class AssertionArgumentOrderCheckSample { static final String CONSTANT = ""; void junit() { assertEquals(0, new AssertionArgumentOrderCheckSample().actual()); - assertEquals(new AssertionArgumentOrderCheckSample().actual(), 0); // Noncompliant [[sc=68;ec=69;secondary=12]] + assertEquals(new AssertionArgumentOrderCheckSample().actual(), 0); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^> ^ assertEquals("message", new AssertionArgumentOrderCheckSample().actual(), 0); // Noncompliant assertEquals("message", 0, new AssertionArgumentOrderCheckSample().actual()); assertEquals("message", "constantString", actualObject()); @@ -49,7 +52,8 @@ void junit() { void assertJ() { // Simple cases, we can find the expected value - assertThat(0).isEqualTo(new AssertionArgumentOrderCheckSample().actual()); // Noncompliant [[sc=16;ec=17;secondary=52]] {{Swap these 2 arguments so they are in the correct order: actual value, expected value.}} + assertThat(0).isEqualTo(new AssertionArgumentOrderCheckSample().actual()); // Noncompliant {{Swap these 2 arguments so they are in the correct order: actual value, expected value.}} +// ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< assertThat(new AssertionArgumentOrderCheckSample().actual()).isEqualTo(0); assertThat("a").isEqualTo("b"); // Noncompliant {{Change this assertion to not compare two literals.}} assertThat(actualObject()).isEqualTo("constantString"); diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionArgumentOrderCheck_JUnit5.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionArgumentOrderCheck_JUnit5.java index 4a882d38bf5..ffa78b01226 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionArgumentOrderCheck_JUnit5.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionArgumentOrderCheck_JUnit5.java @@ -9,7 +9,13 @@ import static java.util.Collections.emptySet; import static java.util.Collections.singleton; import static java.util.Collections.singletonList; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertIterableEquals; +import static org.junit.jupiter.api.Assertions.assertLinesMatch; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; class AssertionArgumentOrderCheck_JUnit5 { static final String CONSTANT = ""; @@ -22,7 +28,8 @@ class AssertionArgumentOrderCheck_JUnit5 { void fun() { assertEquals(0, new AssertionArgumentOrderCheck_JUnit5().actual()); - assertEquals(new AssertionArgumentOrderCheck_JUnit5().actual(), 0); // Noncompliant [[sc=69;ec=70;secondary=25]] {{Swap these 2 arguments so they are in the correct order: expected value, actual value.}} + assertEquals(new AssertionArgumentOrderCheck_JUnit5().actual(), 0); // Noncompliant {{Swap these 2 arguments so they are in the correct order: expected value, actual value.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^> ^ 1 assertEquals(new AssertionArgumentOrderCheck_JUnit5().actual(), 0, "message"); // Noncompliant {{Swap these 2 arguments so they are in the correct order: expected value, actual value.}} assertEquals(new AssertionArgumentOrderCheck_JUnit5().actual(), 0, () -> "messageSupplier"); // Noncompliant assertEquals("constantString", actualObject(), "message"); diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionArgumentOrderCheck_QuickFixes.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionArgumentOrderCheck_QuickFixes.java index 0b092d4f359..a88d2f0acc4 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionArgumentOrderCheck_QuickFixes.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionArgumentOrderCheck_QuickFixes.java @@ -6,38 +6,45 @@ abstract class AssertionArgumentOrderCheck_QuickFixes { void foo() { - // Noncompliant@+1 [[sc=16;ec=32;quickfixes=!]] {{Replace this literal with the actual expression you want to assert.}} - assertThat("constantString"); - // Noncompliant@+1 [[sc=21;ec=22;quickfixes=!]] {{Change this assertion to not compare two literals.}} - assertEquals(1, 2); + assertThat("constantString"); // Noncompliant {{Replace this literal with the actual expression you want to assert.}} [[quickfixes=!]] +// ^^^^^^^^^^^^^^^^ - // Noncompliant@+1 [[sc=34;ec=38;quickfixes=qf1]] {{Swap these 2 arguments so they are in the correct order: expected value, actual value.}} - assertEquals(actualDouble(), 0.0d, 1d); + + assertEquals(1, 2); // Noncompliant {{Change this assertion to not compare two literals.}} [[quickfixes=!]] +// ^ + + + assertEquals(actualDouble(), 0.0d, 1d); // Noncompliant {{Swap these 2 arguments so they are in the correct order: expected value, actual value.}} [[quickfixes=qf1]] +// ^^^^ // fix@qf1 {{Swap arguments}} // edit@qf1 [[sc=18;ec=32]] {{0.0d}} // edit@qf1 [[sc=34;ec=38]] {{actualDouble()}} - // Noncompliant@+1 [[sc=16;ec=19;quickfixes=qf2]] {{Swap these 2 arguments so they are in the correct order: actual value, expected value.}} - assertThat(123).isEqualTo(ConstantUtils.MY_CONSTANT); + + assertThat(123).isEqualTo(ConstantUtils.MY_CONSTANT); // Noncompliant {{Swap these 2 arguments so they are in the correct order: actual value, expected value.}} [[quickfixes=qf2]] +// ^^^ // fix@qf2 {{Swap arguments}} // edit@qf2 [[sc=31;ec=56]] {{123}} // edit@qf2 [[sc=16;ec=19]] {{ConstantUtils.MY_CONSTANT}} - // Noncompliant@+1 [[sc=16;ec=32;quickfixes=qf3]] {{Swap these 2 arguments so they are in the correct order: actual value, expected value.}} - assertThat("constantString") + + assertThat("constantString") // Noncompliant {{Swap these 2 arguments so they are in the correct order: actual value, expected value.}} [[quickfixes=qf3]] +// ^^^^^^^^^^^^^^^^ .isEqualTo(actualObject()); // fix@qf3 {{Swap arguments}} - // edit@qf3 [[sl=+1;sc=18;el=+1;ec=32]] {{"constantString"}} + // edit@qf3 [[sl=+2;sc=18;el=+2;ec=32]] {{"constantString"}} // edit@qf3 [[sc=16;ec=32]] {{actualObject()}} - // Noncompliant@+1 [[sc=16;ec=27;quickfixes=qf4]] {{Swap these 2 arguments so they are in the correct order: actual value, expected value.}} - assertThat(this.MY_CST).isEqualTo(actualObject()); + + assertThat(this.MY_CST).isEqualTo(actualObject()); // Noncompliant {{Swap these 2 arguments so they are in the correct order: actual value, expected value.}} [[quickfixes=qf4]] +// ^^^^^^^^^^^ // fix@qf4 {{Swap arguments}} // edit@qf4 [[sc=39;ec=53]] {{this.MY_CST}} // edit@qf4 [[sc=16;ec=27]] {{actualObject()}} - // Noncompliant@+4 [[sc=7;ec=13;quickfixes=qf5]] {{Swap these 2 arguments so they are in the correct order: expected value, actual value.}} + + // Noncompliant@+4 {{Swap these 2 arguments so they are in the correct order: expected value, actual value.}} [[el=+3;sc=7;ec=12;quickfixes=qf5]] assertEquals( "not expected", actualObject(), diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionArgumentOrderCheck_TestNG.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionArgumentOrderCheck_TestNG.java index ec12f4761c6..0636767bcc4 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionArgumentOrderCheck_TestNG.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionArgumentOrderCheck_TestNG.java @@ -16,8 +16,10 @@ void test() { assertSame(actualString(), "abc"); // Compliant assertSame(actualString(), "abc", "message"); // Compliant assertSame( - "abc", // Noncompliant [[sc=7;ec=12;secondary=20]] {{Swap these 2 arguments so they are in the correct order: actual value, expected value.}} + "abc", // Noncompliant {{Swap these 2 arguments so they are in the correct order: actual value, expected value.}} +// ^^^^^ actualString()); +// ^^^^^^^^^^^^^^< assertSame("abc", actualString(), "message"); // Noncompliant assertNotSame(actualString(), "abc"); // Compliant diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionCompareToSelfCheck_Assertj.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionCompareToSelfCheck_Assertj.java index 1efc8328fd4..9a061189925 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionCompareToSelfCheck_Assertj.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionCompareToSelfCheck_Assertj.java @@ -20,11 +20,13 @@ void test_object() { assertThat(actual).isEqualTo(expected); // Compliant assertThat( actual - ).isEqualTo(actual); // Noncompliant [[sc=19;ec=25;secondary=22]] {{Replace this assertion to not have the same actual and expected expression.}} - assertThatObject(actual).as("message").isEqualTo(actual); // Noncompliant - assertThat(actual).describedAs("message").isEqualTo(actual); // Noncompliant - assertThat(actual).withFailMessage("message", 1, 2).isEqualTo(actual); // Noncompliant - assertThat(actual).overridingErrorMessage("message", 1, 2).isEqualTo(actual); // Noncompliant +// ^^^^^^> + ).isEqualTo(actual); // Noncompliant {{Replace this assertion to not have the same actual and expected expression.}} +// ^^^^^^ + assertThatObject(actual).as("message").isEqualTo(actual); // Noncompliant + assertThat(actual).describedAs("message").isEqualTo(actual); // Noncompliant + assertThat(actual).withFailMessage("message", 1, 2).isEqualTo(actual); // Noncompliant + assertThat(actual).overridingErrorMessage("message", 1, 2).isEqualTo(actual); // Noncompliant assertThat(getRandomObjects()).isEqualTo(getRandomObjects()); // Compliant, actual and expected could be different assertThat(getRandomObjects().length).isEqualTo(getRandomObjects().length); // Compliant assertThat(new Random()).isEqualTo(new Random()); // Compliant @@ -59,8 +61,8 @@ void test_string() { String actual = "foo"; String expected = "foo"; assertThat(actual).contains(expected); // Compliant - assertThat(actual).contains(actual); // Noncompliant - assertThat(actual).containsIgnoringCase(actual); // Noncompliant + assertThat(actual).contains(actual); // Noncompliant + assertThat(actual).containsIgnoringCase(actual); // Noncompliant assertThat(actual).doesNotContain(actual); // Noncompliant assertThat(actual).containsSequence(actual); // Noncompliant assertThat(actual).containsSubsequence(actual); // Noncompliant @@ -79,16 +81,16 @@ void test_list() { List actual = new ArrayList<>(); Object expected = new Object(); assertThat(actual).contains(expected); // Compliant - assertThat(actual).contains(actual); // Noncompliant - assertThat(actual).containsAll(actual); // Noncompliant - assertThat(actual).containsAnyOf(actual); // Noncompliant - assertThat(actual).containsOnly(actual); // Noncompliant - assertThat(actual).containsOnlyElementsOf(actual); // Noncompliant - assertThat(actual).hasSameElementsAs(actual); // Noncompliant - assertThat(actual).hasSameHashCodeAs(actual); // Noncompliant - assertThat(actual).hasSameSizeAs(actual); // Noncompliant - assertThat(actual).isEqualTo(actual); // Noncompliant - assertThat(actual).isSameAs(actual); // Noncompliant + assertThat(actual).contains(actual); // Noncompliant + assertThat(actual).containsAll(actual); // Noncompliant + assertThat(actual).containsAnyOf(actual); // Noncompliant + assertThat(actual).containsOnly(actual); // Noncompliant + assertThat(actual).containsOnlyElementsOf(actual); // Noncompliant + assertThat(actual).hasSameElementsAs(actual); // Noncompliant + assertThat(actual).hasSameHashCodeAs(actual); // Noncompliant + assertThat(actual).hasSameSizeAs(actual); // Noncompliant + assertThat(actual).isEqualTo(actual); // Noncompliant + assertThat(actual).isSameAs(actual); // Noncompliant assertThat(actual).contains(); // Compliant assertThat(actual).containsAnyOf(); // Compliant @@ -100,7 +102,7 @@ void test_map() { Map actual = new HashMap<>(); Map expected = new HashMap<>(); assertThat(actual).containsAllEntriesOf(expected); // Compliant - assertThat(actual).containsAllEntriesOf(actual); // Noncompliant + assertThat(actual).containsAllEntriesOf(actual); // Noncompliant assertThat(actual).containsExactlyInAnyOrderEntriesOf(actual); // Noncompliant } diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionCompareToSelfCheck_FestAssert.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionCompareToSelfCheck_FestAssert.java index f3f827fe15c..fda6d7d6701 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionCompareToSelfCheck_FestAssert.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionCompareToSelfCheck_FestAssert.java @@ -13,10 +13,11 @@ void test_object() { Object actual = new Object(); Object expected = new Object(); assertThat(actual).isEqualTo(expected); // Compliant - assertThat(actual).isEqualTo(actual); // Noncompliant [[sc=34;ec=40]] {{Replace this assertion to not have the same actual and expected expression.}} - assertThat(actual).as("message").isEqualTo(actual); // Noncompliant - assertThat(actual).describedAs("message").isEqualTo(actual); // Noncompliant - assertThat(actual).overridingErrorMessage("message").isEqualTo(actual); // Noncompliant + assertThat(actual).isEqualTo(actual); // Noncompliant {{Replace this assertion to not have the same actual and expected expression.}} +// ^^^^^^ + assertThat(actual).as("message").isEqualTo(actual); // Noncompliant + assertThat(actual).describedAs("message").isEqualTo(actual); // Noncompliant + assertThat(actual).overridingErrorMessage("message").isEqualTo(actual); // Noncompliant assertThat(getRandomObjects()).isEqualTo(getRandomObjects()); // Compliant, actual and expected could be different assertThat(getRandomObjects().length).isEqualTo(getRandomObjects().length); // Compliant, actual and expected could be different } @@ -26,8 +27,8 @@ void test_string() { String actual = "foo"; String expected = "foo"; assertThat(actual).contains(expected); // Compliant - assertThat(actual).contains(actual); // Noncompliant - assertThat(actual).containsIgnoringCase(actual); // Noncompliant + assertThat(actual).contains(actual); // Noncompliant + assertThat(actual).containsIgnoringCase(actual); // Noncompliant assertThat(actual).doesNotContain(actual); // Noncompliant assertThat(actual).endsWith(actual); // Noncompliant assertThat(actual).isEqualTo(actual); // Noncompliant @@ -41,11 +42,11 @@ void test_list() { List actual = new ArrayList<>(); Object expected = new Object(); assertThat(actual).contains(expected); // Compliant - assertThat(actual).contains(actual); // Noncompliant - assertThat(actual).containsExactly(actual); // Noncompliant - assertThat(actual).containsOnly(actual); // Noncompliant - assertThat(actual).isEqualTo(actual); // Noncompliant - assertThat(actual).isSameAs(actual); // Noncompliant + assertThat(actual).contains(actual); // Noncompliant + assertThat(actual).containsExactly(actual); // Noncompliant + assertThat(actual).containsOnly(actual); // Noncompliant + assertThat(actual).isEqualTo(actual); // Noncompliant + assertThat(actual).isSameAs(actual); // Noncompliant assertThat(actual).contains(); // Compliant assertThat(actual).containsExactly(); // Compliant diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionCompareToSelfCheck_JUnit4.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionCompareToSelfCheck_JUnit4.java index e907c14b254..834074b8caf 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionCompareToSelfCheck_JUnit4.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionCompareToSelfCheck_JUnit4.java @@ -13,7 +13,8 @@ void test_object() { Object expected = new Object(); assertEquals(expected, actual); // Compliant assertEquals("message", expected, actual); // Compliant - assertEquals(actual, actual); // Noncompliant [[sc=18;ec=24]] {{Replace this assertion to not have the same actual and expected expression.}} + assertEquals(actual, actual); // Noncompliant {{Replace this assertion to not have the same actual and expected expression.}} +// ^^^^^^ assertEquals("message", actual, actual); // Noncompliant } diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionCompareToSelfCheck_JUnit5.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionCompareToSelfCheck_JUnit5.java index 512125d9a5e..107ef7076a7 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionCompareToSelfCheck_JUnit5.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionCompareToSelfCheck_JUnit5.java @@ -17,7 +17,8 @@ void test_object() { Object expected = new Object(); assertEquals(expected, actual); // Compliant assertEquals(expected, actual, "message"); // Compliant - assertEquals(actual, actual); // Noncompliant [[sc=18;ec=24]] {{Replace this assertion to not have the same actual and expected expression.}} + assertEquals(actual, actual); // Noncompliant {{Replace this assertion to not have the same actual and expected expression.}} +// ^^^^^^ assertEquals(actual, actual, "message"); // Noncompliant assertEquals(actual, actual, () -> "message"); // Noncompliant } diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionInThreadRunCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionInThreadRunCheckSample.java index 855dce60a2d..79f71cd78d6 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionInThreadRunCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionInThreadRunCheckSample.java @@ -7,14 +7,16 @@ class AssertionInThreadRunCheckSample extends Thread { @Override public void run() { - org.junit.Assert.assertTrue(true); // Noncompliant [[sc=22;ec=32]] {{Remove this assertion.}} - org.junit.jupiter.api.Assertions.assertTrue(true); // Noncompliant [[sc=38;ec=48]] {{Remove this assertion.}} + org.junit.Assert.assertTrue(true); // Noncompliant {{Remove this assertion.}} +// ^^^^^^^^^^ + org.junit.jupiter.api.Assertions.assertTrue(true); // Noncompliant {{Remove this assertion.}} +// ^^^^^^^^^^ org.junit.Assert.assertEquals(true, false); // Noncompliant {{Remove this assertion.}} org.junit.jupiter.api.Assertions.assertEquals("a", "b"); // Noncompliant {{Remove this assertion.}} junit.framework.Assert.assertEquals(true, true); // Noncompliant {{Remove this assertion.}} junit.framework.Assert.fail("message"); // Noncompliant {{Remove this assertion.}} - org.fest.assertions.Assertions.assertThat(true).isTrue();// Noncompliant {{Remove this assertion.}} - org.assertj.core.api.Assertions.assertThat(true).isTrue();// Noncompliant {{Remove this assertion.}} + org.fest.assertions.Assertions.assertThat(true).isTrue(); // Noncompliant {{Remove this assertion.}} + org.assertj.core.api.Assertions.assertThat(true).isTrue(); // Noncompliant {{Remove this assertion.}} } public void foo() {} public void run(int i){} diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionInTryCatchCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionInTryCatchCheckSample.java index eadfb03c362..6786b4a2304 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionInTryCatchCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionInTryCatchCheckSample.java @@ -18,18 +18,22 @@ public void test_non_compliant1() { // Test secondary issue location try { throwAssertionError(); // This test will pass even if we comment this line! - org.junit.Assert.fail("Expected an AssertionError!"); // Noncompliant [[sc=24;ec=28;secondary=22]] {{Don't use fail() inside a try-catch catching an AssertionError.}} + org.junit.Assert.fail("Expected an AssertionError!"); // Noncompliant {{Don't use fail() inside a try-catch catching an AssertionError.}} +// ^^^^ } catch (AssertionError e) {} +// ^^^^^^^^^^^^^^< } @Test public void test_non_compliant2() { try { throwAssertionError(); // This test will pass even if we comment this line! - fail("Expected an AssertionError!"); // Noncompliant [[sc=7;ec=11;secondary=32]] + fail("Expected an AssertionError!"); // Noncompliant +// ^^^^ } catch (IllegalStateException e) { } catch (AssertionError e) {} +// ^^^^^^^^^^^^^^< } @Test diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionTypesCheck_AssertJ.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionTypesCheck_AssertJ.java index 65241d4721a..60b97bfde75 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionTypesCheck_AssertJ.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionTypesCheck_AssertJ.java @@ -20,34 +20,37 @@ public class AssertionTypesCheck_AssertJ { @Test void test_assertj() { assertThat(bytePrimitive()) - .isNotNull(); // Noncompliant [[sc=8;ec=17]] {{Change the assertion arguments to not compare a primitive value with null.}} + .isNotNull(); // Noncompliant {{Change the assertion arguments to not compare a primitive value with null.}} +// ^^^^^^^^^ assertThat(shortPrimitive()) .as("msg") .isNotNull() // Noncompliant - .isNull(); // Noncompliant + .isNull(); // Noncompliant assertThatObject(intPrimitive()).isNull(); // Noncompliant - assertThat(charPrimitive()).isNotNull(); // Noncompliant + assertThat(charPrimitive()).isNotNull(); // Noncompliant assertThat(getString()).isNotNull(); // Compliant - assertThat(longPrimitive()).isNotNull(); // Noncompliant - assertThat(floatPrimitive()).isNotNull(); // Noncompliant - assertThat(doublePrimitive()).isNotNull(); // Noncompliant + assertThat(longPrimitive()).isNotNull(); // Noncompliant + assertThat(floatPrimitive()).isNotNull(); // Noncompliant + assertThat(doublePrimitive()).isNotNull(); // Noncompliant assertThat(doublePrimitive()) +// ^^^^^^^^^^^^^^^^^> .withFailMessage("msg", 42) - .isNotEqualTo(null); // Noncompliant [[sc=21;ec=25;secondary=35]] {{Change the assertion arguments to not compare dissimilar types.}} + .isNotEqualTo(null); // Noncompliant {{Change the assertion arguments to not compare dissimilar types.}} +// ^^^^ assertThat(booleanPrimitive()) .describedAs("msg") .isNotEqualTo("foo") // Noncompliant - .isNotSameAs(null) // Noncompliant - .isSameAs("bar"); // Noncompliant + .isNotSameAs(null) // Noncompliant + .isSameAs("bar"); // Noncompliant assertThat(doublePrimitive()) .overridingErrorMessage("msg", 42) .isNotEqualTo(null); // Noncompliant assertThat(booleanPrimitive()).isNotEqualTo(null); // Noncompliant - assertThat(intArray()).isNotEqualTo(42); // Noncompliant + assertThat(intArray()).isNotEqualTo(42); // Noncompliant assertThat(intArray()).isNotEqualTo(new int[] {42}); // Compliant assertThat(intArray()).isNotEqualTo(null); // Compliant @@ -65,9 +68,9 @@ void test_assertj() { assertThat(o).isNotEqualTo(new int[] {42}); // Compliant assertThat(a).isNotEqualTo(new int[] {42}); // Noncompliant - assertThat(a).isNotEqualTo(new A[] {a}); // Noncompliant + assertThat(a).isNotEqualTo(new A[] {a}); // Noncompliant assertThat(new int[] {42}).isNotEqualTo(a); // Noncompliant - assertThat(new A[] {a}).isNotEqualTo(a); // Noncompliant + assertThat(new A[] {a}).isNotEqualTo(a); // Noncompliant assertThat(new A[] {}).isNotEqualTo(new A[] {}); // Compliant assertThat(new B[] {}).isNotEqualTo(new A[] {}); // Compliant @@ -83,7 +86,7 @@ void test_assertj() { assertThat(new int[] {}).isNotEqualTo(new int[] {}); // Compliant assertThat(new int[] {}).isNotEqualTo(new A[] {}); // Noncompliant - assertThat(new int[] {}).isNotEqualTo(new long[] {});// Noncompliant + assertThat(new int[] {}).isNotEqualTo(new long[] {}); // Noncompliant assertThat(a2).isNotEqualTo(a); // Compliant assertThat(new B() {}).isNotEqualTo(b); // Compliant @@ -96,9 +99,9 @@ void test_assertj() { assertThat(o).isNotEqualTo(b); // Compliant org.assertj.core.api.AssertionsForInterfaceTypes. - assertThat(x).isNotEqualTo(a); // Noncompliant + assertThat(x).isNotEqualTo(a); // Noncompliant org.assertj.core.api.AssertionsForClassTypes. - assertThat(x).isEqualTo(a); // Noncompliant + assertThat(x).isEqualTo(a); // Noncompliant // Here we are not sure, but it seems valuable to raise an issue that // could be a false-positive because the negative assertion is useless by @@ -113,17 +116,17 @@ void test_assertj() { // we can raise issues without having false-positives assertThat(i1).isEqualTo(y); // Noncompliant - assertThat(i2).isNotEqualTo(a); // Noncompliant + assertThat(i2).isNotEqualTo(a); // Noncompliant assertThat(i2).isEqualTo(a); // Compliant - assertThat(x).isEqualTo(a); // Noncompliant + assertThat(x).isEqualTo(a); // Noncompliant assertThat(i1).isNotEqualTo(i1); // Compliant assertThat(i1).isEqualTo(i1); // Compliant - assertThat(i2).isNotEqualTo(i1); // Noncompliant + assertThat(i2).isNotEqualTo(i1); // Noncompliant assertThat(i2).isEqualTo(i1); // Compliant - assertThat(i1).isNotEqualTo(y); // Noncompliant + assertThat(i1).isNotEqualTo(y); // Noncompliant assertThat(a) .extracting("hashCode") @@ -147,18 +150,18 @@ void test_assertj_primitives() { assertThat(booleanPrimitive()).isEqualTo(Boolean.TRUE); // Compliant assertThat(booleanPrimitive()).isNotEqualTo(Boolean.FALSE); // Compliant assertThat(booleanPrimitive()).isNotEqualTo(false); // Compliant - assertThat(booleanPrimitive()).isNotEqualTo(5); // Noncompliant - assertThat(intPrimitive()).isNotEqualTo(5.0); // Noncompliant + assertThat(booleanPrimitive()).isNotEqualTo(5); // Noncompliant + assertThat(intPrimitive()).isNotEqualTo(5.0); // Noncompliant assertThat(floatPrimitive()).isEqualTo(5); // Compliant - assertThat(intPrimitive()).isNotEqualTo(5L); // Noncompliant + assertThat(intPrimitive()).isNotEqualTo(5L); // Noncompliant assertThat(longPrimitive()).isEqualTo(5); // Compliant - assertThat(floatPrimitive()).isNotEqualTo(5.0d); // Noncompliant + assertThat(floatPrimitive()).isNotEqualTo(5.0d); // Noncompliant assertThat(doublePrimitive()).isEqualTo(5.0f); // Compliant assertThat(charPrimitive()).isEqualTo('a'); // Compliant - assertThat(charPrimitive()).isNotEqualTo(97); // Noncompliant + assertThat(charPrimitive()).isNotEqualTo(97); // Noncompliant assertThat(intPrimitive()).isEqualTo('a'); // Compliant - assertThat(charPrimitive()).isNotEqualTo("a"); // Noncompliant - assertThat(getString()).isNotEqualTo('a'); // Noncompliant + assertThat(charPrimitive()).isNotEqualTo("a"); // Noncompliant + assertThat(getString()).isNotEqualTo('a'); // Noncompliant assertThat(Long.valueOf(5)).isEqualTo(Long.valueOf(5)); // Compliant assertThat(Long.valueOf(5)).isNotEqualTo(Integer.valueOf(5)); // Noncompliant diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionTypesCheck_JUnit4.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionTypesCheck_JUnit4.java index df1f0f669ad..76538936af0 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionTypesCheck_JUnit4.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionTypesCheck_JUnit4.java @@ -11,10 +11,11 @@ public class AssertionTypesCheck_JUnit4 { @Test void test_junit() { - assertNotNull("message", bytePrimitive()); // Noncompliant [[sc=30;ec=45]] {{Change the assertion arguments to not compare a primitive value with null.}} - assertNotNull(shortPrimitive()); // Noncompliant - assertNotNull(intPrimitive()); // Noncompliant - assertNotNull(charPrimitive()); // Noncompliant + assertNotNull("message", bytePrimitive()); // Noncompliant {{Change the assertion arguments to not compare a primitive value with null.}} +// ^^^^^^^^^^^^^^^ + assertNotNull(shortPrimitive()); // Noncompliant + assertNotNull(intPrimitive()); // Noncompliant + assertNotNull(charPrimitive()); // Noncompliant assertNotNull(getString()); // Compliant assertNotNull("msg", getString()); // Compliant @@ -25,8 +26,10 @@ void test_junit() { assertNull("msg", doublePrimitive()); // Noncompliant assertEquals( - null, // Noncompliant [[sc=7;ec=11;secondary=29]] {{Change the assertion arguments to not compare dissimilar types.}} + null, // Noncompliant {{Change the assertion arguments to not compare dissimilar types.}} +// ^^^^ doublePrimitive()); +// ^^^^^^^^^^^^^^^^^< assertEquals( doublePrimitive(), // Noncompliant null); @@ -55,32 +58,32 @@ void test_junit() { assertNotEquals(new A[] {}, new A[] {}); // Compliant assertNotEquals(new A[] {}, new B[] {}); // Compliant - assertNotEquals(new A[] {}, new X[] {}); // Noncompliant - assertNotEquals(new A[][] {}, new A[] {}); // Noncompliant + assertNotEquals(new A[] {}, new X[] {}); // Noncompliant + assertNotEquals(new A[][] {}, new A[] {}); // Noncompliant assertNotEquals(new A[][] {}, new B[][] {}); // Compliant assertNotEquals(new A[][] {}, new X[][] {}); // Noncompliant assertNotEquals(new int[] {}, new int[] {}); // Compliant - assertNotEquals(new A[] {}, new int[] {}); // Noncompliant - assertNotEquals(new long[] {}, new int[] {});// Noncompliant + assertNotEquals(new A[] {}, new int[] {}); // Noncompliant + assertNotEquals(new long[] {}, new int[] {}); // Noncompliant assertNotEquals(a, a2); // Compliant assertNotEquals(b, new B(){}); // Compliant assertNotEquals(b, i1); // Compliant assertNotEquals(i1, b); // Compliant assertNotEquals(b, new I1(){}); // Noncompliant - assertNotEquals(b, i2); // Noncompliant + assertNotEquals(b, i2); // Noncompliant assertNotEquals(a, b); // Compliant assertNotEquals(b, a); // Compliant assertNotEquals(b, o); // Compliant - assertNotEquals(a, x); // Noncompliant - assertEquals(a, x); // Noncompliant + assertNotEquals(a, x); // Noncompliant + assertEquals(a, x); // Noncompliant // Here we are not sure, but it seems valuable to raise an issue that // could be a false-positive because the negative assertion is useless by // always passing if types are dissimilar - assertNotEquals(a, i1); // Noncompliant + assertNotEquals(a, i1); // Noncompliant // Here we are not sure, but it seems NOT valuable to raise an issue that // could be a false-positive because the positive assertion is helpful and @@ -88,36 +91,36 @@ void test_junit() { assertEquals(a, i1); // Compliant // And in case of final classes, the inheritance is known and final, // we can raise issues without having false-positives - assertEquals(y, i1); // Noncompliant + assertEquals(y, i1); // Noncompliant - assertNotEquals(a, i2); // Noncompliant + assertNotEquals(a, i2); // Noncompliant assertEquals(a, i2); // Compliant - assertEquals(a, x); // Noncompliant + assertEquals(a, x); // Noncompliant assertNotEquals(i1, i1); // Compliant assertEquals(i1, i1); // Compliant - assertNotEquals(i1, i2); // Noncompliant + assertNotEquals(i1, i2); // Noncompliant assertEquals(i1, i2); // Compliant - assertNotEquals(y, i1); // Noncompliant + assertNotEquals(y, i1); // Noncompliant assertEquals(true, booleanPrimitive()); // Compliant assertEquals(Boolean.TRUE, booleanPrimitive()); // Compliant assertNotEquals(Boolean.FALSE, booleanPrimitive()); // Compliant assertNotEquals(false, booleanPrimitive()); // Compliant - assertNotEquals(5, booleanPrimitive()); // Noncompliant - assertNotEquals(5.0, intPrimitive()); // Noncompliant + assertNotEquals(5, booleanPrimitive()); // Noncompliant + assertNotEquals(5.0, intPrimitive()); // Noncompliant assertEquals(5, floatPrimitive()); // Compliant assertNotEquals(5L, intPrimitive()); // Compliant assertEquals(5, longPrimitive()); // Compliant - assertNotEquals(5.0d, floatPrimitive()); // Noncompliant + assertNotEquals(5.0d, floatPrimitive()); // Noncompliant assertEquals(5.0f, doublePrimitive(), 0.01); // Compliant assertEquals('a', charPrimitive()); // Compliant assertNotEquals(97, charPrimitive()); // Compliant assertEquals('a', intPrimitive()); // Compliant - assertNotEquals("a", charPrimitive()); // Noncompliant - assertNotEquals('a', getString()); // Noncompliant + assertNotEquals("a", charPrimitive()); // Noncompliant + assertNotEquals('a', getString()); // Noncompliant assertEquals(Long.valueOf(5), Long.valueOf(5)); // Compliant assertNotEquals(Integer.valueOf(5), Long.valueOf(5)); // Noncompliant diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionTypesCheck_JUnit5.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionTypesCheck_JUnit5.java index c27299184da..01692bbc829 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionTypesCheck_JUnit5.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionTypesCheck_JUnit5.java @@ -21,7 +21,8 @@ public class AssertionTypesCheck_JUnit5 { @Test void test_junit() { - assertNotNull(bytePrimitive()); // Noncompliant [[sc=19;ec=34]] {{Change the assertion arguments to not compare a primitive value with null.}} + assertNotNull(bytePrimitive()); // Noncompliant {{Change the assertion arguments to not compare a primitive value with null.}} +// ^^^^^^^^^^^^^^^ assertNotNull(shortPrimitive(), "msg"); // Noncompliant assertNotNull(intPrimitive(), () -> "msg"); // Noncompliant assertNotNull(charPrimitive()); // Noncompliant @@ -34,8 +35,10 @@ void test_junit() { assertNull(doublePrimitive(), () -> "msg"); // Noncompliant assertEquals( - null, // Noncompliant [[sc=7;ec=11;secondary=38]] {{Change the assertion arguments to not compare dissimilar types.}} + null, // Noncompliant {{Change the assertion arguments to not compare dissimilar types.}} +// ^^^^ doublePrimitive()); +// ^^^^^^^^^^^^^^^^^< assertEquals(null, booleanPrimitive(), "msg"); // Noncompliant assertNotEquals(null, doublePrimitive()); // Noncompliant @@ -60,32 +63,32 @@ void test_junit() { assertNotEquals(new A[] {}, new A[] {}); // Compliant assertNotEquals(new A[] {}, new B[] {}); // Compliant - assertNotEquals(new A[] {}, new X[] {}); // Noncompliant - assertNotEquals(new A[][] {}, new A[] {}); // Noncompliant + assertNotEquals(new A[] {}, new X[] {}); // Noncompliant + assertNotEquals(new A[][] {}, new A[] {}); // Noncompliant assertNotEquals(new A[][] {}, new B[][] {}); // Compliant assertNotEquals(new A[][] {}, new X[][] {}); // Noncompliant assertNotEquals(new int[] {}, new int[] {}); // Compliant - assertNotEquals(new A[] {}, new int[] {}); // Noncompliant - assertNotEquals(new long[] {}, new int[] {});// Noncompliant + assertNotEquals(new A[] {}, new int[] {}); // Noncompliant + assertNotEquals(new long[] {}, new int[] {}); // Noncompliant assertNotEquals(a, a2); // Compliant assertNotEquals(b, new B(){}); // Compliant assertNotEquals(b, i1); // Compliant assertNotEquals(i1, b); // Compliant assertNotEquals(b, new I1(){}); // Noncompliant - assertNotEquals(b, i2); // Noncompliant + assertNotEquals(b, i2); // Noncompliant assertNotEquals(a, b); // Compliant assertNotEquals(b, a); // Compliant assertNotEquals(b, o); // Compliant - assertNotEquals(a, x); // Noncompliant - assertEquals(a, x); // Noncompliant + assertNotEquals(a, x); // Noncompliant + assertEquals(a, x); // Noncompliant // Here we are not sure, but it seems valuable to raise an issue that // could be a false-positive because the negative assertion is useless by // always passing if types are dissimilar - assertNotEquals(a, i1); // Noncompliant + assertNotEquals(a, i1); // Noncompliant // example of false-positive: assertNotEquals((A) b, (I1) new B()); // Noncompliant @@ -97,19 +100,19 @@ void test_junit() { assertEquals((A) b, (I1) b); // Compliant // And in case of final classes, the inheritance is known and final, // we can raise issues without having false-positives - assertEquals(y, i1); // Noncompliant + assertEquals(y, i1); // Noncompliant - assertNotEquals(a, i2); // Noncompliant + assertNotEquals(a, i2); // Noncompliant assertEquals(a, i2); // Compliant - assertEquals(a, x); // Noncompliant + assertEquals(a, x); // Noncompliant assertNotEquals(i1, i1); // Compliant assertEquals(i1, i1); // Compliant - assertNotEquals(i1, i2); // Noncompliant + assertNotEquals(i1, i2); // Noncompliant assertEquals(i1, i2); // Compliant - assertNotEquals(y, i1); // Noncompliant + assertNotEquals(y, i1); // Noncompliant assertNotEquals(42, Integer.valueOf(42)); // Compliant assertNotEquals(42L, Long.valueOf(42L)); // Compliant @@ -118,7 +121,7 @@ void test_junit() { assertEquals(Boolean.TRUE, booleanPrimitive()); // Compliant assertNotEquals(Boolean.FALSE, booleanPrimitive()); // Compliant assertNotEquals(false, booleanPrimitive()); // Compliant - assertNotEquals(5, booleanPrimitive()); // Noncompliant + assertNotEquals(5, booleanPrimitive()); // Noncompliant assertNotEquals(5.0, intPrimitive()); // Compliant assertEquals(5, floatPrimitive()); // Compliant assertNotEquals(5L, intPrimitive()); // Compliant @@ -128,8 +131,8 @@ void test_junit() { assertEquals('a', charPrimitive()); // Compliant assertNotEquals(97, charPrimitive()); // Compliant assertEquals('a', intPrimitive()); // Compliant - assertNotEquals("a", charPrimitive()); // Noncompliant - assertNotEquals('a', getString()); // Noncompliant + assertNotEquals("a", charPrimitive()); // Noncompliant + assertNotEquals('a', getString()); // Noncompliant assertEquals(Long.valueOf(5), Long.valueOf(5)); // Compliant assertNotEquals(Integer.valueOf(5), Long.valueOf(5)); // Noncompliant diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsCompletenessCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsCompletenessCheckSample.java index 94f22455d0c..86f4c2ddfbe 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsCompletenessCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsCompletenessCheckSample.java @@ -26,8 +26,8 @@ public class AssertionsCompletenessCheckSample { public void fest_assertions() { org.fest.assertions.Assertions.assertThat(true); // Noncompliant {{Complete the assertion.}} org.fest.assertions.Assertions.assertThat(true).as("foo"); // Noncompliant - org.fest.assertions.Assertions.assertThat(true).describedAs("foo"); // Noncompliant - org.fest.assertions.Assertions.assertThat(true).overridingErrorMessage("foo"); // Noncompliant + org.fest.assertions.Assertions.assertThat(true).describedAs("foo"); // Noncompliant + org.fest.assertions.Assertions.assertThat(true).overridingErrorMessage("foo"); // Noncompliant org.fest.assertions.Assertions.assertThat(true).isTrue(); // Compliant org.fest.assertions.Assertions.assertThat(AssertionsCompletenessCheckSample.class.toString()).hasSize(0); // Compliant @@ -258,7 +258,8 @@ public void assertj_junit_soft_assertions_cross_methods_5() throws Exception { @Test public void assertj_junit_soft_assertions_cross_methods_6() throws Exception { - doIncompleteSoftAssertions2(); // Noncompliant [[sc=5;ec=34;secondary=284,289]] {{Add one or more 'assertThat' before 'assertAll'.}} + doIncompleteSoftAssertions2(); // Noncompliant {{Add one or more 'assertThat' before 'assertAll'.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } private void doSomething(org.assertj.core.api.SoftAssertions softly) { @@ -282,11 +283,13 @@ private void doIncompleteSoftAssertions1(String expected) { private void doIncompleteSoftAssertions2() { doIncompleteSoftAssertions3(); +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^< } private void doIncompleteSoftAssertions3() { org.assertj.core.api.SoftAssertions softly = new org.assertj.core.api.SoftAssertions(); softly.assertAll(); +// ^^^^^^^^^^^^^^^^< } private void doBoth(org.assertj.core.api.SoftAssertions softly, boolean doItAgain) { diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsInTestsCheck/AssertJ.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsInTestsCheck/AssertJ.java index 914f5a44f88..93d782da016 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsInTestsCheck/AssertJ.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsInTestsCheck/AssertJ.java @@ -214,7 +214,7 @@ public void bdd_assertions_split_with_intermediate_assertion() { // Compliant } @Test - public void bdd_assertions_example_without_assertion() { // Noncompliant - nothing is asserted here + public void bdd_assertions_example_without_assertion() { // Noncompliant BDDAssertions.then(listStringMethod()); } diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsInTestsCheck/Junit4.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsInTestsCheck/Junit4.java index 3aca9487b18..6d3e3f830f3 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsInTestsCheck/Junit4.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsInTestsCheck/Junit4.java @@ -24,7 +24,8 @@ private static int static_and_not_a_unit_test() { } @Test - public void contains_no_assertions() { // Noncompliant [[sc=15;ec=37]] {{Add at least one assertion to this test case.}} + public void contains_no_assertions() { // Noncompliant {{Add at least one assertion to this test case.}} +// ^^^^^^^^^^^^^^^^^^^^^^ } @Nullable diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsInTestsCheck/Selenide.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsInTestsCheck/Selenide.java index aea5be84e7b..0d28d35b997 100755 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsInTestsCheck/Selenide.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsInTestsCheck/Selenide.java @@ -24,7 +24,8 @@ public void selenide_verify_ElementsCollection() { // Compliant } @Test - public void contains_no_assertions() { // Noncompliant [[sc=15;ec=37]] {{Add at least one assertion to this test case.}} + public void contains_no_assertions() { // Noncompliant {{Add at least one assertion to this test case.}} +// ^^^^^^^^^^^^^^^^^^^^^^ Selenide.open("https://www.google.com/"); Selenide.$(By.name("q")).val("selenide").pressEnter(); } diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsInTestsCheck/SpringBootSanityJ4Test.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsInTestsCheck/SpringBootSanityJ4Test.java index f7811256cb5..0f802885984 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsInTestsCheck/SpringBootSanityJ4Test.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsInTestsCheck/SpringBootSanityJ4Test.java @@ -14,7 +14,7 @@ public void contextLoads() { // Compliant, no assertions needed for this spring } @Test - public void anotherTest(){ // Noncompliant, no assertions + public void anotherTest(){ // Noncompliant } diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsInTestsCheck/SpringBootSanityTestSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsInTestsCheck/SpringBootSanityTestSample.java index 62e3cb9a863..68a38e26dcb 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsInTestsCheck/SpringBootSanityTestSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsInTestsCheck/SpringBootSanityTestSample.java @@ -11,7 +11,7 @@ void contextLoads() { // Compliant, no assertions needed for this spring sanity } @Test - void anotherTest(){ // Noncompliant, no assertions + void anotherTest(){ // Noncompliant } diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsWithoutMessageCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsWithoutMessageCheckSample.java index d464da595f6..aba4554a446 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsWithoutMessageCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsWithoutMessageCheckSample.java @@ -15,7 +15,8 @@ class AssertionsWithoutMessageCheckSample { void foo() { org.assertj.core.api.Assertions.assertThat("").usingComparator(null).as("a").isEqualTo(222); // Compliant - org.junit.Assert.assertTrue(true); // Noncompliant [[sc=22;ec=32]] {{Add a message to this assertion.}} + org.junit.Assert.assertTrue(true); // Noncompliant {{Add a message to this assertion.}} +// ^^^^^^^^^^ org.junit.Assert.assertTrue("message", true); org.junit.Assert.assertTrue(1 > 2); // Noncompliant {{Add a message to this assertion.}} org.junit.Assert.assertFalse(false); // Noncompliant @@ -31,7 +32,7 @@ void foo() { junit.framework.Assert.assertNotNull("foo"); // Noncompliant - org.fest.assertions.Assertions.assertThat(true).isTrue();// Noncompliant {{Add a message to this assertion chain before the predicate method.}} + org.fest.assertions.Assertions.assertThat(true).isTrue(); // Noncompliant {{Add a message to this assertion chain before the predicate method.}} org.fest.assertions.Assertions.assertThat(true).as("verifying the truth").isTrue(); org.fest.assertions.Assertions.assertThat(true).as(new BasicDescription("description")).isTrue(); org.fest.assertions.Assertions.assertThat(true).describedAs("verifying the truth").isTrue(); // compliant - describedAs is an alias for as @@ -53,13 +54,16 @@ void foo() { org.assertj.core.api.Assertions.assertThat(true).overridingErrorMessage("fail message").isTrue(); org.assertj.core.api.Assertions.assertThat(true).overridingErrorMessage("fail message", new Object()).isTrue(); org.assertj.core.api.Assertions.assertThat("").as("Message").isEqualTo(""); - org.assertj.core.api.Assertions.assertThat("").isEqualTo("").as("Message"); // Noncompliant [[sc=52;ec=61]] {{Add a message to this assertion chain before the predicate method.}} - org.assertj.core.api.Assertions.assertThat("").matches("x").matches("y"); // Noncompliant [[sc=52;ec=59]] + org.assertj.core.api.Assertions.assertThat("").isEqualTo("").as("Message"); // Noncompliant {{Add a message to this assertion chain before the predicate method.}} +// ^^^^^^^^^ + org.assertj.core.api.Assertions.assertThat("").matches("x").matches("y"); // Noncompliant +// ^^^^^^^ org.assertj.core.api.AssertionsForClassTypes.assertThat("").isEqualTo(""); // Noncompliant org.assertj.core.api.Assertions.assertThat("").usingComparator(null).as("a").isEqualTo(222); // Compliant org.assertj.core.api.Assertions.assertThat("").as("message").usingComparator(null).isEqualTo(222); // Compliant - org.assertj.core.api.Assertions.assertThat("").isEqualTo("1").usingComparator(null).isEqualTo("2"); // Noncompliant [[sc=52;ec=61]] + org.assertj.core.api.Assertions.assertThat("").isEqualTo("1").usingComparator(null).isEqualTo("2"); // Noncompliant +// ^^^^^^^^^ org.assertj.core.api.Assertions.assertThat("").usingComparator(null).isEqualTo(222); // Noncompliant org.assertj.core.api.Assertions.assertThat(new Object()).as("message").extracting("field").isEqualTo(222); // Compliant org.assertj.core.api.Assertions.assertThat(new Object()).extracting("field").isEqualTo(222); // Noncompliant @@ -102,7 +106,8 @@ void junit5() { org.junit.jupiter.api.Assertions.fail(() -> "message"); org.junit.jupiter.api.Assertions.fail("message", new java.lang.RuntimeException()); - org.junit.jupiter.api.Assertions.assertFalse(false); // Noncompliant [[sc=38;ec=49]] {{Add a message to this assertion.}} + org.junit.jupiter.api.Assertions.assertFalse(false); // Noncompliant {{Add a message to this assertion.}} +// ^^^^^^^^^^^ org.junit.jupiter.api.Assertions.assertFalse(false, "message"); org.junit.jupiter.api.Assertions.assertTrue(false); // Noncompliant org.junit.jupiter.api.Assertions.assertTrue(false, () -> "message"); @@ -150,7 +155,7 @@ void junit5() { org.junit.jupiter.api.Assertions.assertEquals(1.0, 2.0, 1.0, () -> "messageSupplier"); org.junit.jupiter.api.Assertions.assertDoesNotThrow(() -> new AssertionsWithoutMessageCheckSample()); // Noncompliant - org.junit.jupiter.api.Assertions.assertDoesNotThrow(AssertionsWithoutMessageCheckSample::new); // Noncompliant + org.junit.jupiter.api.Assertions.assertDoesNotThrow(AssertionsWithoutMessageCheckSample::new); // Noncompliant org.junit.jupiter.api.Assertions.assertDoesNotThrow(() -> new AssertionsWithoutMessageCheckSample(), "message"); org.junit.jupiter.api.Assertions.assertDoesNotThrow(AssertionsWithoutMessageCheckSample::new, "message"); org.junit.jupiter.api.Assertions.assertDoesNotThrow(AssertionsWithoutMessageCheckSample::new, () -> "message"); diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/BooleanOrNullLiteralInAssertionsCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/BooleanOrNullLiteralInAssertionsCheckSample.java index b6fb198b218..ae969b382c0 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/BooleanOrNullLiteralInAssertionsCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/BooleanOrNullLiteralInAssertionsCheckSample.java @@ -4,23 +4,31 @@ class BooleanOrNullLiteralInAssertionsCheckSample { void booleans() { - org.junit.Assert.assertTrue( // Noncompliant [[sc=22;ec=32;secondary=8]] {{Remove or correct this assertion.}} + org.junit.Assert.assertTrue( // Noncompliant {{Remove or correct this assertion.}} +// ^^^^^^^^^^ true +// ^^^^< ); - org.junit.Assert.assertEquals( // Noncompliant [[sc=22;ec=34;secondary=11,12]] {{Remove or correct this assertion.}} + org.junit.Assert.assertEquals( // Noncompliant {{Remove or correct this assertion.}} +// ^^^^^^^^^^^^ true, +// ^^^^< true +// ^^^^< ); org.junit.Assert.assertTrue("message", true); // Noncompliant {{Remove or correct this assertion.}} org.junit.Assert.assertTrue(1 > 2); org.junit.Assert.assertFalse(false); // Noncompliant org.junit.Assert.assertFalse("message", false); // Noncompliant - org.junit.jupiter.api.Assertions.assertTrue(true); // Noncompliant [[sc=38;ec=48]] {{Remove or correct this assertion.}} + org.junit.jupiter.api.Assertions.assertTrue(true); // Noncompliant {{Remove or correct this assertion.}} +// ^^^^^^^^^^ org.junit.jupiter.api.Assertions.assertFalse(true); // Noncompliant org.junit.jupiter.api.Assertions.assertTrue(getBool()); org.junit.jupiter.api.Assertions.assertFalse(getBool()); - org.junit.jupiter.api.Assertions.assertEquals(true, getBool()); // Noncompliant [[sc=38;ec=50]] {{Use assertTrue instead.}} - org.junit.jupiter.api.Assertions.assertSame(getBool(), false); // Noncompliant [[sc=38;ec=48]] {{Use assertFalse instead.}} + org.junit.jupiter.api.Assertions.assertEquals(true, getBool()); // Noncompliant {{Use assertTrue instead.}} +// ^^^^^^^^^^^^ + org.junit.jupiter.api.Assertions.assertSame(getBool(), false); // Noncompliant {{Use assertFalse instead.}} +// ^^^^^^^^^^ org.junit.jupiter.api.Assertions.assertNotEquals(true, getBool()); // Noncompliant {{Use assertFalse instead.}} org.junit.jupiter.api.Assertions.assertNotEquals(false, getBool()); // Noncompliant {{Use assertTrue instead.}} diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/CallSuperInTestCaseCheck.java b/java-checks-test-sources/default/src/test/java/checks/tests/CallSuperInTestCaseCheck.java index 69b8cdb4c38..fe94eadd0d5 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/CallSuperInTestCaseCheck.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/CallSuperInTestCaseCheck.java @@ -19,7 +19,8 @@ public void tearDown() { } class CallSuperInTestCaseCheckE extends CallSuperInTestCaseCheckB { - public void setUp() { // Noncompliant [[sc=15;ec=20]] {{Add a "super.setUp()" call to this method.}} + public void setUp() { // Noncompliant {{Add a "super.setUp()" call to this method.}} +// ^^^^^ } public void tearDown() { // Noncompliant {{Add a "super.tearDown()" call to this method.}} } diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/ExpectedExceptionCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/ExpectedExceptionCheckSample.java index d1f6e6fa819..4a04c009eea 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/ExpectedExceptionCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/ExpectedExceptionCheckSample.java @@ -14,10 +14,13 @@ public class ExpectedExceptionCheckSample { @Test public void assertions_before_and_after_expect() throws IOException { Assert.assertEquals(1, 1); - expectedException.expect(IOException.class); // Noncompliant [[sc=23;ec=29;secondary=19,20]] {{Consider using org.junit.Assert.assertThrows before other assertions.}} + expectedException.expect(IOException.class); // Noncompliant {{Consider using org.junit.Assert.assertThrows before other assertions.}} +// ^^^^^^ functionThrowingIOException(); Assert.assertEquals(1, 1); +// ^^^^^^^^^^^^< Assert.assertNotEquals(2, 3); +// ^^^^^^^^^^^^^^^< } @Test diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/IgnoredTestsCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/IgnoredTestsCheckSample.java index 6e0c684911a..c441a509c78 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/IgnoredTestsCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/IgnoredTestsCheckSample.java @@ -6,13 +6,15 @@ abstract class IgnoredTestsCheckSample { @org.junit.Ignore - void foo() {} // Noncompliant [[sc=8;ec=11]] {{Either add an explanation about why this test is skipped or remove the "@Ignore" annotation.}} + void foo() {} // Noncompliant {{Either add an explanation about why this test is skipped or remove the "@Ignore" annotation.}} +// ^^^ @Ignore void bar() {} // Noncompliant @Disabled - void disabledJunit5() {} // Noncompliant [[sc=8;ec=22]] {{Either add an explanation about why this test is skipped or remove the "@Disabled" annotation.}} + void disabledJunit5() {} // Noncompliant {{Either add an explanation about why this test is skipped or remove the "@Disabled" annotation.}} +// ^^^^^^^^^^^^^^ void qix() {} @@ -26,7 +28,9 @@ void foo2WithoutFQN() {} void disabledJunit5WithComment() {} void assume1() { - Assume.assumeTrue(false); // Noncompliant [[sc=12;ec=22;secondary=+0]] {{This assumption is called with a boolean constant; remove it or, to skip this test use an @Ignore/@Disabled annotation in combination with an explanation about why it is skipped.}} + Assume.assumeTrue(false); // Noncompliant {{This assumption is called with a boolean constant; remove it or, to skip this test use an @Ignore/@Disabled annotation in combination with an explanation about why it is skipped.}} +// ^^^^^^^^^^ +// ^^^^^^^@-1< Assume.assumeTrue(true); } void assume2() { diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/JUnit45MethodAnnotationCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/JUnit45MethodAnnotationCheckSample.java index 5c29a120be6..8aae7b03015 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/JUnit45MethodAnnotationCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/JUnit45MethodAnnotationCheckSample.java @@ -3,8 +3,9 @@ class JUnit45MethodAnnotationCheckSample_JUnit4 { @org.junit.Test void test() { } - public void setUp() { } // Noncompliant [[sc=15;ec=20]] {{Annotate this method with JUnit4 '@org.junit.Before' or rename it to avoid confusion.}} - public void tearDown() { } // Noncompliant {{Annotate this method with JUnit4 '@org.junit.After' or rename it to avoid confusion.}} + public void setUp() { } // Noncompliant {{Annotate this method with JUnit4 '@org.junit.Before' or rename it to avoid confusion.}} +// ^^^^^ + public void tearDown() { } // Noncompliant {{Annotate this method with JUnit4 '@org.junit.After' or rename it to avoid confusion.}} } class JUnit45MethodAnnotationCheckSample_JUnit4_compliant { @@ -44,7 +45,7 @@ class JUnit45MethodAnnotationCheckSample_JUnit5 { @org.junit.jupiter.api.Test void test() { } public void setUp() { } // Noncompliant {{Annotate this method with JUnit5 '@org.junit.jupiter.api.BeforeEach' or rename it to avoid confusion.}} - public void tearDown() { } // Noncompliant {{Annotate this method with JUnit5 '@org.junit.jupiter.api.AfterEach' or rename it to avoid confusion.}} + public void tearDown() { } // Noncompliant {{Annotate this method with JUnit5 '@org.junit.jupiter.api.AfterEach' or rename it to avoid confusion.}} } class JUnit45MethodAnnotationCheckSample_JUnit5_compliant { diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/JUnit4AnnotationsCheckTest.java b/java-checks-test-sources/default/src/test/java/checks/tests/JUnit4AnnotationsCheckTest.java index 55a9c6d584d..ba69bf382a2 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/JUnit4AnnotationsCheckTest.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/JUnit4AnnotationsCheckTest.java @@ -34,7 +34,8 @@ public class JUnit4AnnotationsCheckTest { - @Test // Noncompliant [[sc=3;ec=8]] {{Change this JUnit4 org.junit.Test to the equivalent JUnit5 org.junit.jupiter.api.Test annotation.}} + @Test // Noncompliant {{Change this JUnit4 org.junit.Test to the equivalent JUnit5 org.junit.jupiter.api.Test annotation.}} +//^^^^^ private void someTestMethod() {} @org.junit.Test // Noncompliant diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/JUnit5DefaultPackageClassAndMethodCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/JUnit5DefaultPackageClassAndMethodCheckSample.java index 4a50c9b4f56..208b9bf2ff5 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/JUnit5DefaultPackageClassAndMethodCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/JUnit5DefaultPackageClassAndMethodCheckSample.java @@ -9,17 +9,20 @@ class JUnit5DefaultPackageClassAndMethodCheckSample { @Test - public void testPublic() {} // Noncompliant [[sc=3;ec=9;quickfixes=qf1]] {{Remove this 'public' modifier.}} + public void testPublic() {} // Noncompliant {{Remove this 'public' modifier.}} [[quickfixes=qf1]] +//^^^^^^ // fix@qf1 {{Remove "public" modifier}} // edit@qf1 [[sc=3;ec=10]] {{}} @Test - public static void testPublicStatic() {} // Noncompliant [[sc=3;ec=9;quickfixes=qf2]] {{Remove this 'public' modifier.}} + public static void testPublicStatic() {} // Noncompliant {{Remove this 'public' modifier.}} [[quickfixes=qf2]] +//^^^^^^ // fix@qf2 {{Remove "public" modifier}} // edit@qf2 [[sc=3;ec=10]] {{}} @Test - protected void testProtected() {} // Noncompliant [[sc=3;ec=12;quickfixes=qf3]] + protected void testProtected() {} // Noncompliant [[quickfixes=qf3]] +//^^^^^^^^^ // fix@qf3 {{Remove "protected" modifier}} // edit@qf3 [[sc=3;ec=13]] {{}} @@ -49,7 +52,8 @@ public static class WithoutTest { // Compliant } - protected static class PublicWithOneTest { // Noncompliant [[sc=3;ec=12;quickfixes=qf4]] {{Remove this 'protected' modifier.}} + protected static class PublicWithOneTest { // Noncompliant {{Remove this 'protected' modifier.}} [[quickfixes=qf4]] +//^^^^^^^^^ // fix@qf4 {{Remove "protected" modifier}} // edit@qf4 [[sc=3;ec=13]] {{}} @Test diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/JUnit5SilentlyIgnoreClassAndMethodCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/JUnit5SilentlyIgnoreClassAndMethodCheckSample.java index b6620daff7c..6c0cbb69979 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/JUnit5SilentlyIgnoreClassAndMethodCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/JUnit5SilentlyIgnoreClassAndMethodCheckSample.java @@ -11,7 +11,8 @@ class JUnit5SilentlyIgnoreClassAndMethodCheckSample { @Test - private void testPrivate() {} // Noncompliant [[sc=3;ec=10]] {{Remove this 'private' modifier.}} + private void testPrivate() {} // Noncompliant {{Remove this 'private' modifier.}} +//^^^^^^^ @Test void testDefault() {} // Compliant @@ -36,7 +37,8 @@ private class PrivateWithoutTest { // Compliant } @Nested - private class PrivateWithOneTest { // Noncompliant [[sc=3;ec=10]] {{Remove this 'private' modifier.}} + private class PrivateWithOneTest { // Noncompliant {{Remove this 'private' modifier.}} +//^^^^^^^ @Test void test() {} } @@ -54,10 +56,12 @@ void test() {} } @Test - static void staticTest() {} // Noncompliant [[sc=3;ec=9]] {{Remove this 'static' modifier.}} + static void staticTest() {} // Noncompliant {{Remove this 'static' modifier.}} +//^^^^^^ @Test - int testReturningValue() { return 0; } // Noncompliant [[sc=3;ec=6]] {{Replace the return type by void.}} + int testReturningValue() { return 0; } // Noncompliant {{Replace the return type by void.}} +//^^^ @TestFactory Collection testFactory() { // Compliant, TestFactory returning a value @@ -74,17 +78,20 @@ void test() { @Nested class Quickfixes { @Test - private void testPrivate() {} // Noncompliant [[sc=5;ec=12;quickfixes=qf4]] + private void testPrivate() {} // Noncompliant [[quickfixes=qf4]] +// ^^^^^^^ // fix@qf4 {{Remove modifier}} // edit@qf4 [[sc=5;ec=12]] {{}} @Test - static void staticTest() {} // Noncompliant [[sc=5;ec=11;quickfixes=qf5]] + static void staticTest() {} // Noncompliant [[quickfixes=qf5]] +// ^^^^^^ // fix@qf5 {{Remove modifier}} // edit@qf5 [[sc=5;ec=11]] {{}} @Nested - private class PrivateWithOneTest { // Noncompliant [[sc=5;ec=12;quickfixes=qf3]] + private class PrivateWithOneTest { // Noncompliant [[quickfixes=qf3]] +// ^^^^^^^ // fix@qf3 {{Remove modifier}} // edit@qf3 [[sc=5;ec=12]] {{}} @Test @@ -92,17 +99,19 @@ void test() {} } @Test - List quickFixes() { return Collections.emptyList(); } // Noncompliant [[sc=5;ec=17;quickfixes=qf1]] + List quickFixes() { return Collections.emptyList(); } // Noncompliant [[quickfixes=qf1]] +// ^^^^^^^^^^^^ // fix@qf1 {{Replace with void}} // edit@qf1 [[sc=5;ec=17]] {{void}} // edit@qf1 [[sc=40;ec=63]] {{}} @Test - Object bar(boolean b, Object o) { // Noncompliant [[sc=5;ec=11;quickfixes=qf2]] + Object bar(boolean b, Object o) { // Noncompliant [[quickfixes=qf2]] +// ^^^^^^ // fix@qf2 {{Replace with void}} // edit@qf2 [[sc=5;ec=11]] {{void}} - // edit@qf2 [[sl=+6;sc=16;el=+6;ec=39]] {{}} - // edit@qf2 [[sl=+8;sc=14;el=+8;ec=15]] {{}} + // edit@qf2 [[sl=+7;sc=16;el=+7;ec=39]] {{}} + // edit@qf2 [[sl=+9;sc=14;el=+9;ec=15]] {{}} if (b) { return Collections.emptyList(); } diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/JUnitCompatibleAnnotationsCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/JUnitCompatibleAnnotationsCheckSample.java index 9c904061116..f2ee4ba0f63 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/JUnitCompatibleAnnotationsCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/JUnitCompatibleAnnotationsCheckSample.java @@ -8,8 +8,11 @@ public class JUnitCompatibleAnnotationsCheckSample { @Test +//^^^^^> @RepeatedTest(2) - void test() { // Noncompliant [[sc=8;ec=12;secondary=10,11]]{{Remove one of these conflicting annotations.}} +//^^^^^^^^^^^^^^^^> + void test() { // Noncompliant {{Remove one of these conflicting annotations.}} +// ^^^^ } @RepeatedTest(4) @@ -19,7 +22,7 @@ void test2() { // Compliant @ParameterizedTest @Test @MethodSource("methodSource") - void test3(int argument) { // Noncompliant + void test3(int argument) { // Noncompliant } } diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/JunitNestedAnnotationCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/JunitNestedAnnotationCheckSample.java index 1f5cf2c5d86..0f8841f9d6b 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/JunitNestedAnnotationCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/JunitNestedAnnotationCheckSample.java @@ -17,7 +17,8 @@ void not_a_test() { } } - class NotAnnotatedInnerClassWithOneTest { // Noncompliant [[sc=9;ec=42]] {{Add @Nested to this inner test class}} + class NotAnnotatedInnerClassWithOneTest { // Noncompliant {{Add @Nested to this inner test class}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @ParameterizedTest @ValueSource(strings = { "a", "b", "c" }) void test(String value) { diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/MockingAllMethodsCheck.java b/java-checks-test-sources/default/src/test/java/checks/tests/MockingAllMethodsCheck.java index a1b3fe993a1..edb84ba7fbc 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/MockingAllMethodsCheck.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/MockingAllMethodsCheck.java @@ -8,10 +8,14 @@ public class MockingAllMethodsCheck { @Test void test_mocking_MyClass() { - MyClass myClassMock = mock(MyClass.class); // Noncompliant [[sc=5;ec=47;secondary=12,13,14]] {{Refactor this test instead of mocking every non-private member of this class.}} + MyClass myClassMock = mock(MyClass.class); // Noncompliant {{Refactor this test instead of mocking every non-private member of this class.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ when(myClassMock.f()).thenReturn(1); +// ^^^^^^^^^^^^^^^^^^^^^< when(myClassMock.g()).thenReturn(2); +// ^^^^^^^^^^^^^^^^^^^^^< when(myClassMock.h()).thenReturn(3); +// ^^^^^^^^^^^^^^^^^^^^^< //... } @@ -43,9 +47,12 @@ abstract class MyClass { @Test void test_mocking_MyConcreteClass() { - MyConcreteClass myClassMock = mock(MyConcreteClass.class); // Noncompliant [[secondary=47,48]] + MyConcreteClass myClassMock = mock(MyConcreteClass.class); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ when(myClassMock.f()).thenReturn(1); +// ^^^^^^^^^^^^^^^^^^^^^< when(myClassMock.g()).thenReturn(2); +// ^^^^^^^^^^^^^^^^^^^^^< //... } @@ -92,9 +99,12 @@ private int g() { @Test void test_mocking_MyClass4() { - MyClass4 myClassMock = mock(MyClass4.class); // Noncompliant [[secondary=96,97]] + MyClass4 myClassMock = mock(MyClass4.class); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ when(myClassMock.f()).thenReturn(1); +// ^^^^^^^^^^^^^^^^^^^^^< when(myClassMock.g()).thenReturn(2); +// ^^^^^^^^^^^^^^^^^^^^^< //... } @@ -127,11 +137,14 @@ void test_mocking_MyClass4_weirdly2() { void test_mocking_MyClass4_extremely_weirdly() { // FP because we falsely make the analysis think that realInstance's methods are being mocked - MyConcreteClass realInstance = new MyConcreteClass(); // Noncompliant [[secondary=132,134]] + MyConcreteClass realInstance = new MyConcreteClass(); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mock(MyClass4.class).f(); when(realInstance.f()).thenReturn(1); +// ^^^^^^^^^^^^^^^^^^^^^^< mock(MyClass4.class).f(); when(realInstance.g()).thenReturn(2); +// ^^^^^^^^^^^^^^^^^^^^^^< //... } @@ -184,10 +197,13 @@ void test_mocking_MyClass4_through_separate_methods() { @Test void test_mocking_MyClass4_through_a_mutable_variable() { // FP because we don't recognize that `myClassMock` is reassigned - MyClass4 myClassMock = mock(MyClass4.class); // Noncompliant [[secondary=188,190]] + MyClass4 myClassMock = mock(MyClass4.class); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ when(myClassMock.f()).thenReturn(1); +// ^^^^^^^^^^^^^^^^^^^^^< myClassMock = mock(MyClass4.class); when(myClassMock.g()).thenReturn(2); +// ^^^^^^^^^^^^^^^^^^^^^< } @Test @@ -201,18 +217,26 @@ void test_mocking_MyClass4_through_static_member() { void test_mocking_Child() { // Just mocking the methods from child is enough to trigger the rule because we don't look at the parent class - Child childMock = mock(Child.class); // Noncompliant [[secondary=205,206]] + Child childMock = mock(Child.class); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ when(childMock.h()).thenReturn(1); +// ^^^^^^^^^^^^^^^^^^^< when(childMock.i()).thenReturn(2); +// ^^^^^^^^^^^^^^^^^^^< } void test_mocking_Child_and_Parent_methods() { // Mocking methods other than the ones we're looking at won't make the issue disappear - Child childMock = mock(Child.class); // Noncompliant [[secondary=212,213,214,215]] + Child childMock = mock(Child.class); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ when(childMock.f()).thenReturn(1); +// ^^^^^^^^^^^^^^^^^^^< when(childMock.g()).thenReturn(2); +// ^^^^^^^^^^^^^^^^^^^< when(childMock.h()).thenReturn(3); +// ^^^^^^^^^^^^^^^^^^^< when(childMock.i()).thenReturn(4); +// ^^^^^^^^^^^^^^^^^^^< } diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/MockitoAnnotatedObjectsShouldBeInitialized.java b/java-checks-test-sources/default/src/test/java/checks/tests/MockitoAnnotatedObjectsShouldBeInitialized.java index c4d551ffa5f..e2975786d54 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/MockitoAnnotatedObjectsShouldBeInitialized.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/MockitoAnnotatedObjectsShouldBeInitialized.java @@ -160,7 +160,7 @@ public class MockitoRuleWrongStaticMethod { @Rule public MockitoRule rule = foo(); - @Mock // Noncompliant {{Initialize mocks before using them.}} + @Mock // Noncompliant {{Initialize mocks before using them.}} private Bar bar; private MockitoRule foo() { return null; } diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/MockitoArgumentMatchersUsedOnAllParameters.java b/java-checks-test-sources/default/src/test/java/checks/tests/MockitoArgumentMatchersUsedOnAllParameters.java index 64d75d18896..bcceeffc25f 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/MockitoArgumentMatchersUsedOnAllParameters.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/MockitoArgumentMatchersUsedOnAllParameters.java @@ -34,27 +34,36 @@ public void nonCompliant() { Integer i1 = null, i2 = null, val1 = null, val2 = null; given(foo.bar( anyInt(), - i1, // Noncompliant [[sc=7;ec=9;secondary=+1]] {{Add an "eq()" argument matcher on these parameters.}} + i1, // Noncompliant {{Add an "eq()" argument matcher on these parameters.}} +// ^^ i2)) +// ^^< .willReturn(null); - when(foo.baz(eq(val1), val2)).thenReturn("hi");// Noncompliant [[sc=28;ec=32]] {{Add an "eq()" argument matcher on this parameter.}} - doThrow(new RuntimeException()).when(foo).quux(intThat(x -> x >= 42), -1); // Noncompliant [[sc=75;ec=77]] {{Add an "eq()" argument matcher on this parameter.}} + when(foo.baz(eq(val1), val2)).thenReturn("hi"); // Noncompliant {{Add an "eq()" argument matcher on this parameter.}} +// ^^^^ + doThrow(new RuntimeException()).when(foo).quux(intThat(x -> x >= 42), -1); // Noncompliant {{Add an "eq()" argument matcher on this parameter.}} +// ^^ verify(foo).bar( - i1, // Noncompliant [[sc=7;ec=9;secondary=+2]] {{Add an "eq()" argument matcher on these parameters.}} + i1, // Noncompliant {{Add an "eq()" argument matcher on these parameters.}} +// ^^ anyInt(), i2); +// ^^< ArgumentCaptor captor = ArgumentCaptor.forClass(Integer.class); verify(foo).bar(captor.capture(), - i1, // Noncompliant [[sc=7;ec=9]] {{Add an "eq()" argument matcher on this parameter.}} + i1, // Noncompliant {{Add an "eq()" argument matcher on this parameter.}} +// ^^ any()); verify(foo).bar(anyInt(), - i1.toString(), // Noncompliant [[sc=7;ec=20]] {{Add an "eq()" argument matcher on this parameter.}} + i1.toString(), // Noncompliant {{Add an "eq()" argument matcher on this parameter.}} +// ^^^^^^^^^^^^^ any()); verify(foo).bar( - returnRawValue(), // Noncompliant [[sc=7;ec=23]] {{Add an "eq()" argument matcher on this parameter.}} + returnRawValue(), // Noncompliant {{Add an "eq()" argument matcher on this parameter.}} +// ^^^^^^^^^^^^^^^^ any(), any() ); diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/MockitoEqSimplificationCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/MockitoEqSimplificationCheckSample.java index a324f146e39..667347c21de 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/MockitoEqSimplificationCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/MockitoEqSimplificationCheckSample.java @@ -31,16 +31,24 @@ public void myTest() { Object v4 = new Object(); Object v5 = new Object(); - given(foo.bar(eq(v1), // Noncompliant [[sc=19;ec=21;secondary=+1,+2]] {{Remove this and every subsequent useless "eq(...)" invocation; pass the values directly.}} + given(foo.bar(eq(v1), // Noncompliant {{Remove this and every subsequent useless "eq(...)" invocation; pass the values directly.}} +// ^^ eq(v2), +// ^^< eq(v3))).willReturn(null); - when(foo.baz(eq(v4), // Noncompliant [[sc=18;ec=20;secondary=+1]] {{Remove this and every subsequent useless "eq(...)" invocation; pass the values directly.}} +// ^^< + when(foo.baz(eq(v4), // Noncompliant {{Remove this and every subsequent useless "eq(...)" invocation; pass the values directly.}} +// ^^ eq(v5))).thenReturn("foo"); - when(foo.baz(eq(v4), // Noncompliant [[sc=18;ec=20;secondary=+1]] +// ^^< + when(foo.baz(eq(v4), // Noncompliant +// ^^ eq(v5))).thenReturn("foo"); - doThrow(new RuntimeException()).when(foo).quux(eq(42)); // Noncompliant [[sc=52;ec=54]] {{Remove this useless "eq(...)" invocation; pass the values directly.}} +// ^^< + doThrow(new RuntimeException()).when(foo).quux(eq(42)); // Noncompliant {{Remove this useless "eq(...)" invocation; pass the values directly.}} +// ^^ doCallRealMethod().when(foo).baz(eq(v4), eq(v5)); // Noncompliant - verify(foo).bar(eq(v1), eq(v2), eq(v3)); // Noncompliant + verify(foo).bar(eq(v1), eq(v2), eq(v3)); // Noncompliant verify(foo, never()).bar(eq(v1), eq(v2), eq(v3)); // Noncompliant InOrder inOrder = Mockito.inOrder(foo); diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/NoTestInTestClassCheckArchUnitTest.java b/java-checks-test-sources/default/src/test/java/checks/tests/NoTestInTestClassCheckArchUnitTest.java index 7523db2e486..5a82b76e718 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/NoTestInTestClassCheckArchUnitTest.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/NoTestInTestClassCheckArchUnitTest.java @@ -12,7 +12,8 @@ import static com.tngtech.archunit.library.dependencies.SlicesRuleDefinition.slices; // missing @RunWith or @AnalyzeClasses -public class NoTestInTestClassCheckArchUnitTest { // Noncompliant [[sc=14;ec=48]] {{Add some tests to this class.}} +public class NoTestInTestClassCheckArchUnitTest { // Noncompliant {{Add some tests to this class.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @ArchTest public static final ArchRule noJodatime = GeneralCodingRules.NO_CLASSES_SHOULD_USE_JODATIME; @@ -31,7 +32,8 @@ class NoTestInTestClassCheckArchUnit1Test { @RunWith(ArchUnitRunner.class) @AnalyzeClasses(packages = "checks") -class NoTestInTestClassCheckArchUnit2Test { // Noncompliant [[sc=7;ec=42]] {{Add some tests to this class.}} +class NoTestInTestClassCheckArchUnit2Test { // Noncompliant {{Add some tests to this class.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // missing @ArchTest public static final ArchRule noJavaUtilLogging = GeneralCodingRules.NO_CLASSES_SHOULD_USE_JAVA_UTIL_LOGGING; @@ -58,7 +60,7 @@ private void no_access_to_standard_streams_as_method(JavaClasses classes) { } @AnalyzeClasses(packages = "checks") -class NoTestInTestClassCheckArchUnit5Test { // Noncompliant [[sc=7;ec=42] {{Add some tests to this class.}} +class NoTestInTestClassCheckArchUnit5Test { // Noncompliant {{Add some tests to this class.}} // missing @ArchTest public static final ArchRule noCycles = slices().matching("checks.(**)").should().beFreeOfCycles(); @@ -66,7 +68,8 @@ class NoTestInTestClassCheckArchUnit5Test { // Noncompliant [[sc=7;ec=42] {{Add } @AnalyzeClasses(packages = "checks") -class NoTestInTestClassCheckArchUnit6Test { // Noncompliant [[sc=7;ec=42]] {{Add some tests to this class.}} +class NoTestInTestClassCheckArchUnit6Test { // Noncompliant {{Add some tests to this class.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // missing @ArchTest private void no_access_to_standard_streams_as_method(JavaClasses classes) { @@ -90,7 +93,8 @@ interface NoTestInTestClassCheckInterfaceTest { } @AnalyzeClasses(packages = "checks") -class NoTestInTestClassCheckArchUnit9Test implements NoTestInTestClassCheckInterfaceTest { // Noncompliant [[sc=7;ec=42]] {{Add some tests to this class.}} +class NoTestInTestClassCheckArchUnit9Test implements NoTestInTestClassCheckInterfaceTest { // Noncompliant {{Add some tests to this class.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // does not inherit tests from interface fields diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/NoTestInTestClassCheckEnclosed.java b/java-checks-test-sources/default/src/test/java/checks/tests/NoTestInTestClassCheckEnclosed.java index 6e81567bab6..2cdee246fce 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/NoTestInTestClassCheckEnclosed.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/NoTestInTestClassCheckEnclosed.java @@ -5,15 +5,18 @@ import org.junit.runner.RunWith; @RunWith(Enclosed.class) -class MyNewTest { // Noncompliant [[sc=7;ec=16]] {{Add some tests to this class.}} +class MyNewTest { // Noncompliant {{Add some tests to this class.}} +// ^^^^^^^^^ } @RunWith(Enclosed.class) -class MyNew2Test { // Noncompliant [[sc=7;ec=17]] {{Add some tests to this class.}} +class MyNew2Test { // Noncompliant {{Add some tests to this class.}} +// ^^^^^^^^^^ } @RunWith(Enclosed.class) -class EnclosedNoInnerClassesTest { // Noncompliant [[sc=7;ec=33]] {{Add some tests to this class.}} +class EnclosedNoInnerClassesTest { // Noncompliant {{Add some tests to this class.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^ @Test public void something() { } @@ -23,7 +26,8 @@ public void testSomething() { } @RunWith(Enclosed.class) -class EnclosedIgnoreAbstractInnerClassTest { // Noncompliant [[sc=7;ec=43]] {{Add some tests to this class.}} +class EnclosedIgnoreAbstractInnerClassTest { // Noncompliant {{Add some tests to this class.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ abstract public static class IgnoredTest { @Test public void ignored() { @@ -41,7 +45,8 @@ public void publicStaticInner() { } @RunWith(Enclosed.class) -class EnclosedWithPublicInnerClassTest { // Noncompliant [[sc=7;ec=39]] {{Add some tests to this class.}} +class EnclosedWithPublicInnerClassTest { // Noncompliant {{Add some tests to this class.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ public class PublicInner { @Test public void publicInner() { @@ -51,7 +56,8 @@ public void publicInner() { @RunWith(Enclosed.class) -class EnclosedWithStaticInnerClassTest { // Noncompliant [[sc=7;ec=39]] {{Add some tests to this class.}} +class EnclosedWithStaticInnerClassTest { // Noncompliant {{Add some tests to this class.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ static class StaticInner { @Test public void staticInner() { @@ -60,7 +66,8 @@ public void staticInner() { } @RunWith(Enclosed.class) -class EnclosedExtendsTestClassTest extends SimpleTest { // Noncompliant [[sc=7;ec=35]] +class EnclosedExtendsTestClassTest extends SimpleTest { // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } @RunWith(Enclosed.class) @@ -70,7 +77,8 @@ public static class InnerClass extends SimpleTest { } @RunWith(Enclosed.class) -class EnclosedWithInnerClassExtendsTest { // Noncompliant [[sc=7;ec=40]] +class EnclosedWithInnerClassExtendsTest { // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ class InnerClass extends SimpleTest { } } @@ -80,7 +88,8 @@ class EnclosedExtendsWithInnerPublicClassTest extends TestsWithInnerPublicTest { } @RunWith(Enclosed.class) -class EnclosedExtendsWithInnerClassTest extends TestsWithInnerTest { // Noncompliant [[sc=7;ec=40]] +class EnclosedExtendsWithInnerClassTest extends TestsWithInnerTest { // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } @@ -98,7 +107,8 @@ public void test() { } } -class TestsWithInnerTest { // Noncompliant [[sc=7;ec=25]] +class TestsWithInnerTest { // Noncompliant +// ^^^^^^^^^^^^^^^^^^ static class InnerClass { @Test public void test() { diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/NoTestInTestClassCheckNoClasspath.java b/java-checks-test-sources/default/src/test/java/checks/tests/NoTestInTestClassCheckNoClasspath.java index e8cf0f38df6..8aaaf405595 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/NoTestInTestClassCheckNoClasspath.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/NoTestInTestClassCheckNoClasspath.java @@ -10,7 +10,8 @@ void foo() { } } -class ATest { // Noncompliant [[sc=7;ec=12]] {{Add some tests to this class.}} +class ATest { // Noncompliant {{Add some tests to this class.}} +// ^^^^^ ATest() {} void foo() { new AnonymousClass() { diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/NoTestInTestClassCustomPattern.java b/java-checks-test-sources/default/src/test/java/checks/tests/NoTestInTestClassCustomPattern.java index 63e0243fff2..68bc2e88ad3 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/NoTestInTestClassCustomPattern.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/NoTestInTestClassCustomPattern.java @@ -3,22 +3,26 @@ public class NoTestInTestClassCustomPattern { } -class TestJUnit4WithJUnit3 { // Noncompliant [[sc=7;ec=27]] +class TestJUnit4WithJUnit3 { // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^ public void test() { } } -class JUnit4WithJUnit3Test { // Noncompliant [[sc=7;ec=27]] +class JUnit4WithJUnit3Test { // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^ public void test() { } } -class JUnit4WithJUnit3Tests { // Noncompliant [[sc=7;ec=28]] +class JUnit4WithJUnit3Tests { // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^ public void test() { } } -class JUnit4WithJUnit3TestCase { // Noncompliant [[sc=7;ec=31]] +class JUnit4WithJUnit3TestCase { // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^ public void test() { } } diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/NoTestsInTestClassCheckPactTest.java b/java-checks-test-sources/default/src/test/java/checks/tests/NoTestsInTestClassCheckPactTest.java index 8e27fd7a592..c51b68dad1e 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/NoTestsInTestClassCheckPactTest.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/NoTestsInTestClassCheckPactTest.java @@ -54,7 +54,8 @@ public void testB() { @Consumer("glory") @PactBroker @RunWith(RestPactRunner.class) -class NoTestsInTestClassCheckPactNonCompliantTest{ // Noncompliant [[sc=7;ec=50]] +class NoTestsInTestClassCheckPactNonCompliantTest{ // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ public void testA() { // Prepare service before interaction that require "default" state diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/OneExpectedCheckedExceptionCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/OneExpectedCheckedExceptionCheckSample.java index 7c07f67d157..efea47eaab8 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/OneExpectedCheckedExceptionCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/OneExpectedCheckedExceptionCheckSample.java @@ -22,13 +22,16 @@ public void testG() { assertThrows(IOException.class, () -> throwIOException2(throwIOException(1)) ); // Noncompliant assertThrows(IOException.class, () -> throwIOException2(throwIOException(1)), "Message"); // Noncompliant assertThrows(IOException.class, () -> throwIOException2(throwIOException(1)), () -> "message"); // Noncompliant - assertThrows(IOException.class, () -> { // Noncompliant [[sc=5;ec=17;secondary=25,26] {{Refactor the code of the lambda to not have multiple invocations throwing the same checked exception.}} + assertThrows(IOException.class, () -> { // Noncompliant {{Refactor the code of the lambda to not have multiple invocations throwing the same checked exception.}} if (throwIOException2(1) == throwIOException(1)) {} } ); - assertThrows(IOException.class, () -> // Noncompliant [[sc=5;ec=17;secondary=30,31]] + assertThrows(IOException.class, () -> // Noncompliant +// ^^^^^^^^^^^^ new ThrowingIOException( +// ^^^^^^^^^^^^^^^^^^^< throwIOException(1) +// ^^^^^^^^^^^^^^^^< ) ); org.junit.Assert.assertThrows(IOException.class, () -> throwIOException2(throwIOException(1)) ); // Noncompliant org.junit.Assert.assertThrows("Message", IOException.class, () -> throwIOException2(throwIOException(1)) ); // Noncompliant @@ -51,9 +54,12 @@ public void testG() { @Test public void testGTryCatchIdiom() { - try { // Noncompliant [[sc=5;ec=8;secondary=55,56]] {{Refactor the body of this try/catch to not have multiple invocations throwing the same checked exception.}} + try { // Noncompliant {{Refactor the body of this try/catch to not have multiple invocations throwing the same checked exception.}} +// ^^^ throwIOException2( +// ^^^^^^^^^^^^^^^^^< throwIOException(1) +// ^^^^^^^^^^^^^^^^< ); Assert.fail("Expected an IOException to be thrown"); } catch (IOException e) { @@ -157,9 +163,12 @@ void f() throws IOException { public void test_AssertJ() { Throwable thrown = org.assertj.core.api.Assertions - .catchThrowableOfType( // Noncompliant [[sc=8;ec=28;secondary=161,162]] {{Refactor the code of the lambda to not have multiple invocations throwing the same checked exception.}} + .catchThrowableOfType( // Noncompliant {{Refactor the code of the lambda to not have multiple invocations throwing the same checked exception.}} +// ^^^^^^^^^^^^^^^^^^^^ () -> throwIOException2( +// ^^^^^^^^^^^^^^^^^< throwIOException(1)), +// ^^^^^^^^^^^^^^^^< IOException.class); org.assertj.core.api.Assertions.assertThat(thrown).hasMessage("error"); diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/OneExpectedRuntimeExceptionCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/OneExpectedRuntimeExceptionCheckSample.java index 41c188fc7e9..625d1277df8 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/OneExpectedRuntimeExceptionCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/OneExpectedRuntimeExceptionCheckSample.java @@ -22,13 +22,16 @@ public void testG() { assertThrows(IllegalStateException.class, () -> foo(foo(1)) ); // Noncompliant assertThrows(IllegalStateException.class, () -> foo(foo(1)), "Message"); // Noncompliant assertThrows(IllegalStateException.class, () -> foo(foo(1)), () -> "message"); // Noncompliant - assertThrows(IllegalStateException.class, () -> { // Noncompliant [[sc=5;ec=17;secondary=26,27] {{Refactor the code of the lambda to have only one invocation possibly throwing a runtime exception.}} + assertThrows(IllegalStateException.class, () -> { // Noncompliant {{Refactor the code of the lambda to have only one invocation possibly throwing a runtime exception.}} if (foo(1) == foo(1)) {} } ); - assertThrows(IllegalStateException.class, () -> // Noncompliant [[sc=5;ec=17;secondary=30,31]] + assertThrows(IllegalStateException.class, () -> // Noncompliant +// ^^^^^^^^^^^^ new NestedClass( +// ^^^^^^^^^^^< foo(1) +// ^^^< ) ); org.junit.Assert.assertThrows(IllegalStateException.class, () -> foo(foo(1)) ); // Noncompliant org.junit.Assert.assertThrows("Message", IllegalStateException.class, () -> foo(foo(1)) ); // Noncompliant @@ -59,9 +62,12 @@ public void mockito() { @Test public void testGTryCatchIdiom() { - try { // Noncompliant [[sc=5;ec=8;secondary=63,64]] {{Refactor the body of this try/catch to have only one invocation possibly throwing a runtime exception.}} + try { // Noncompliant {{Refactor the body of this try/catch to have only one invocation possibly throwing a runtime exception.}} +// ^^^ foo( +// ^^^< foo(1) +// ^^^< ); Assert.fail("Expected an IllegalStateException to be thrown"); } catch (IllegalStateException e) { @@ -152,9 +158,12 @@ void f() throws IOException { public void test_AssertJ() { Throwable thrown = org.assertj.core.api.Assertions - .catchThrowableOfType( // Noncompliant [[sc=8;ec=28;secondary=156,157]] {{Refactor the code of the lambda to have only one invocation possibly throwing a runtime exception.}} + .catchThrowableOfType( // Noncompliant {{Refactor the code of the lambda to have only one invocation possibly throwing a runtime exception.}} +// ^^^^^^^^^^^^^^^^^^^^ () -> foo( +// ^^^< foo(1)), +// ^^^< IllegalStateException.class); org.assertj.core.api.Assertions.assertThat(thrown).hasMessage("error"); diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/ParameterizedTestCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/ParameterizedTestCheckSample.java index b75371e2d34..1895d154791 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/ParameterizedTestCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/ParameterizedTestCheckSample.java @@ -14,15 +14,18 @@ public class ParameterizedTestCheckSample { String setup = "a"; @Test - void testSum11() { // Noncompliant [[sc=8;ec=17;secondary=21,21,21,25,33]] {{Replace these 3 tests with a single Parameterized one.}} + void testSum11() { // Noncompliant {{Replace these 3 tests with a single Parameterized one.}} +// ^^^^^^^^^ setup(setup); setup(setup); setup(setup); assertEquals(Integer.sum(1, 1), 2); +// ^< ^< ^< } @Test void testSum12() { // Similar test +// ^^^^^^^^^< setup(setup); setup(setup); setup(setup); @@ -31,6 +34,7 @@ void testSum12() { // Similar test @Test void testSum22() { // Similar test +// ^^^^^^^^^< setup(setup); setup(setup); setup(setup); @@ -57,38 +61,46 @@ void testSum(int a, int b, int result) { // Only consider ints,shorts,bytes,longs,floats,doubles,chars,strings,boolean. Types does not need to be the same // ints @Test - void testInt1() { // Noncompliant [[secondary=63,63,66,72]] {{Replace these 3 tests with a single Parameterized one.}} + void testInt1() { // Noncompliant {{Replace these 3 tests with a single Parameterized one.}} +// ^^^^^^^^ setup(); setup(); assertEquals(getObject(1), 1); +// ^< ^< } @Test void testInt2() { +// ^^^^^^^^< setup(); setup(); assertEquals(getObject(2), 2); } @Test void testInt3() { +// ^^^^^^^^< setup(); setup(); assertEquals(getObject(3), 3); } // shorts @Test - void testShort1() { // Noncompliant [[secondary=82,82,85,91]] + void testShort1() { // Noncompliant +// ^^^^^^^^^^ setup(); setup(); assertEquals(getObject((short) 1), 1); +// ^< ^< } @Test void testShort2() { +// ^^^^^^^^^^< setup(); setup(); assertEquals(getObject((short) 2), 2); } @Test void testShort3() { +// ^^^^^^^^^^< setup(); setup(); assertEquals(getObject((short) 3), 3); @@ -123,19 +135,23 @@ void testDouble1() { } // strings @Test - void testString1() { // Noncompliant [[secondary=129,129,132,138,152]] + void testString1() { // Noncompliant +// ^^^^^^^^^^^ setup(); setup(); assertEquals(getObject("1"), "1"); +// ^^^< ^^^< } @Test void testString2() { +// ^^^^^^^^^^^< setup(); setup(); assertEquals(getObject("2"), "2"); } @Test void testString3() { +// ^^^^^^^^^^^< setup(); setup(); assertEquals(getObject("3"), "3"); @@ -150,25 +166,30 @@ void testChar1() { // Not a secondary of testString1 // null @Test void testNull() { // null and string are compatible, the method can be parameterized together with testString1 +// ^^^^^^^^< setup(); setup(); assertEquals(getObject(null), null); } // booleans @Test - void testBoolean1() { // Noncompliant [[secondary=162,162,165,171]] + void testBoolean1() { // Noncompliant +// ^^^^^^^^^^^^ setup(); setup(); assertEquals(getObject(true), true); +// ^^^^< ^^^^< } @Test void testBoolean2() { +// ^^^^^^^^^^^^< setup(); setup(); assertEquals(getObject(true), false); } @Test void testBoolean3() { +// ^^^^^^^^^^^^< setup(); setup(); assertEquals(getObject(false), false); @@ -181,7 +202,7 @@ void testCast() { // Not a secondary for any issue } @Test - void testComplex1() { // Noncompliant [secondary=186,188,189,193,202]] + void testComplex1() { // Noncompliant setup("Always the same, no need to parameterize"); Object o = getObject(1); assertNotNull(o); diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/RandomizedTestDataCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/RandomizedTestDataCheckSample.java index c85f150e66d..af6da260ab7 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/RandomizedTestDataCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/RandomizedTestDataCheckSample.java @@ -8,30 +8,40 @@ public class RandomizedTestDataCheckSample { @Test public void randomizedTest() { - int userAge = new Random().nextInt(42); // Noncompliant[[sc=19;ec=31;secondary=25,27,29,31,33,42]]{{Replace randomly generated values with fixed ones.}} - UUID userID = UUID.randomUUID(); // Noncompliant[[sc=19;ec=36;secondary=26,28,30,32,34]]{{Replace randomly generated values with fixed ones.}} - MyRandom myRandom = new MyRandom(); // Compliant - } + UUID userID = UUID.randomUUID(); // Noncompliant {{Replace randomly generated values with fixed ones.}} +// ^^^^^^^^^^^^^^^^^ + UUID u1 = UUID.randomUUID(); +// ^^^^^^^^^^^^^^^^^< + UUID u2 = UUID.randomUUID(); +// ^^^^^^^^^^^^^^^^^< + UUID u3 = UUID.randomUUID(); +// ^^^^^^^^^^^^^^^^^< + UUID u4 = UUID.randomUUID(); +// ^^^^^^^^^^^^^^^^^< + UUID u5 = UUID.randomUUID(); +// ^^^^^^^^^^^^^^^^^< - @Test - public void notRandomizedTest() { - int userAge = 31; // Compliant - UUID userID = UUID.fromString("00000000-000-0000-0000-000000000001"); //Compliant - } + int userAge = new Random().nextInt(42); // Noncompliant {{Replace randomly generated values with fixed ones.}} +// ^^^^^^^^^^^^ - @Test - public void secondaryLocations() { int age1 = new Random().nextInt(42); - UUID u1 = UUID.randomUUID(); +// ^^^^^^^^^^^^< int age2 = new Random().nextInt(42); - UUID u2 = UUID.randomUUID(); +// ^^^^^^^^^^^^< int age3 = new Random().nextInt(42); - UUID u3 = UUID.randomUUID(); +// ^^^^^^^^^^^^< int age4 = new Random().nextInt(42); - UUID u4 = UUID.randomUUID(); +// ^^^^^^^^^^^^< int age5 = new Random().nextInt(42); - UUID u5 = UUID.randomUUID(); +// ^^^^^^^^^^^^< + MyRandom myRandom = new MyRandom(); // Compliant + } + + @Test + public void notRandomizedTest() { + int userAge = 31; // Compliant + UUID userID = UUID.fromString("00000000-000-0000-0000-000000000001"); //Compliant } class MyRandom { @@ -40,6 +50,7 @@ class MyRandom { @Test public void randomizedTestWithSeed() { int userAge = new Random(111111111111L).nextInt(42); +// ^^^^^^^^^^^^^^^^^^^^^^^^^< } } diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/SpringAssertionsSimplificationCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/SpringAssertionsSimplificationCheckSample.java index 5b06d25f2e0..d41274a9c46 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/SpringAssertionsSimplificationCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/SpringAssertionsSimplificationCheckSample.java @@ -21,8 +21,10 @@ public class SpringAssertionsSimplificationCheckSample { void couldBeSimplified() { ModelAndView mav = getMyModelAndView(); - assertEquals("register", mav.getViewName()); // Noncompliant [[sc=5;ec=17]] {{Replace this assertion by "ModelAndViewAssert.assertViewName".}} - assertTrue((Boolean) mav.getModelMap().get("myAttribute")); // Noncompliant [[sc=5;ec=15]] {{Replace this assertion by "ModelAndViewAssert.assertModelAttributeValue".}} + assertEquals("register", mav.getViewName()); // Noncompliant {{Replace this assertion by "ModelAndViewAssert.assertViewName".}} +// ^^^^^^^^^^^^ + assertTrue((Boolean) mav.getModelMap().get("myAttribute")); // Noncompliant {{Replace this assertion by "ModelAndViewAssert.assertModelAttributeValue".}} +// ^^^^^^^^^^ assertFalse((Boolean) mav.getModelMap().get("myAttribute")); // Noncompliant {{Replace this assertion by "ModelAndViewAssert.assertModelAttributeValue".}} assertEquals(myObject, mav.getModelMap().get("myAttribute")); // Noncompliant {{Replace this assertion by "ModelAndViewAssert.assertModelAttributeValue".}} @@ -39,7 +41,8 @@ void couldBeSimplified() { Object o = modelMap.get("myAttribute"); // AssertJ - assertThat(mav.getViewName()).isEqualTo("register"); // Noncompliant [[sc=5;ec=15]] {{Replace this assertion by "ModelAndViewAssert.assertViewName".}} + assertThat(mav.getViewName()).isEqualTo("register"); // Noncompliant {{Replace this assertion by "ModelAndViewAssert.assertViewName".}} +// ^^^^^^^^^^ assertThat((Boolean) mav.getModelMap().get("myAttribute")).isTrue(); // Noncompliant {{Replace this assertion by "ModelAndViewAssert.assertModelAttributeValue".}} assertThat((Boolean) mav.getModelMap().get("myAttribute")).isFalse(); // Noncompliant {{Replace this assertion by "ModelAndViewAssert.assertModelAttributeValue".}} assertThat(mav.getModelMap().get("myAttribute")).isEqualTo(myObject); // Noncompliant {{Replace this assertion by "ModelAndViewAssert.assertModelAttributeValue".}} diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/TestAnnotationWithExpectedExceptionCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/TestAnnotationWithExpectedExceptionCheckSample.java index 16ec3dbed77..15ae793f0cb 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/TestAnnotationWithExpectedExceptionCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/TestAnnotationWithExpectedExceptionCheckSample.java @@ -6,11 +6,14 @@ public void testException() { throwingMethod(); } - @org.junit.Test(expected = ArrayIndexOutOfBoundsException.class) // Noncompliant [[sc=19;ec=66;secondary=12,13]] {{Move assertions into separate method or use assertThrows or try-catch instead.}} + @org.junit.Test(expected = ArrayIndexOutOfBoundsException.class) // Noncompliant {{Move assertions into separate method or use assertThrows or try-catch instead.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ public void testException2() { throwingMethod(); org.junit.Assert.assertTrue(true); +// ^^^^^^^^^^< org.junit.Assert.assertTrue(true); +// ^^^^^^^^^^< } @org.junit.Test(expected = ArrayIndexOutOfBoundsException.class, timeout = 0) // Noncompliant diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/TestStabilityCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/TestStabilityCheckSample.java index 219cfb1a6cc..6d67ce78478 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/TestStabilityCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/TestStabilityCheckSample.java @@ -4,7 +4,8 @@ public class TestStabilityCheckSample { - @Test(successPercentage = 80, invocationCount = 10) // Noncompliant[[sc=9;ec=31]]{{Make this test stable and remove this "successPercentage" argument.}} + @Test(successPercentage = 80, invocationCount = 10) // Noncompliant {{Make this test stable and remove this "successPercentage" argument.}} +// ^^^^^^^^^^^^^^^^^^^^^^ public void flakyTest() { } diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/ThreadSleepInTestsCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/ThreadSleepInTestsCheckSample.java index 63fa39d4964..3bd957d3ba7 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/ThreadSleepInTestsCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/ThreadSleepInTestsCheckSample.java @@ -11,14 +11,16 @@ public class ThreadSleepInTestsCheckSample { @Test public void test() throws InterruptedException { foo(); - Thread.sleep(1000); // Noncompliant [[sc=12;ec=17]] {{Remove this use of "Thread.sleep()".}} + Thread.sleep(1000); // Noncompliant {{Remove this use of "Thread.sleep()".}} +// ^^^^^ bar(); } @Test public void test2() throws InterruptedException { foo(); - sleep(1000); // Noncompliant [[sc=5;ec=10]] {{Remove this use of "Thread.sleep()".}} + sleep(1000); // Noncompliant {{Remove this use of "Thread.sleep()".}} +// ^^^^^ bar(); } @@ -32,14 +34,16 @@ public void test3() throws InterruptedException { @Test public void test4() throws InterruptedException { foo(); - java.util.concurrent.TimeUnit.SECONDS.sleep(1); // Noncompliant [[sc=43;ec=48]] {{Remove this use of "TimeUnit.sleep()".}} + java.util.concurrent.TimeUnit.SECONDS.sleep(1); // Noncompliant {{Remove this use of "TimeUnit.sleep()".}} +// ^^^^^ bar(); } @Test public void test5() throws InterruptedException { foo(); - TimeUnit.HOURS.sleep(1); // Noncompliant [[sc=20;ec=25]] {{Remove this use of "TimeUnit.sleep()".}} + TimeUnit.HOURS.sleep(1); // Noncompliant {{Remove this use of "TimeUnit.sleep()".}} +// ^^^^^ bar(); } diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/TooManyAssertionsCheckCustom2.java b/java-checks-test-sources/default/src/test/java/checks/tests/TooManyAssertionsCheckCustom2.java index 2f94cf568e8..aebd7b5ff52 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/TooManyAssertionsCheckCustom2.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/TooManyAssertionsCheckCustom2.java @@ -8,10 +8,14 @@ public class TooManyAssertionsCheckCustom2 { @Test - void test1() { // Noncompliant [[sc=8;ec=13;secondary=12,13,14]]{{Refactor this method to reduce the number of assertions from 3 to less than 2.}} + void test1() { // Noncompliant {{Refactor this method to reduce the number of assertions from 3 to less than 2.}} +// ^^^^^ assertEquals(1, f(1)); +// ^^^^^^^^^^^^^^^^^^^^^< assertEquals(2, f(2)); +// ^^^^^^^^^^^^^^^^^^^^^< assertEquals(3, f(3)); +// ^^^^^^^^^^^^^^^^^^^^^< Observable objectObservable = Observable.create(null, null); objectObservable.test(); } @@ -23,10 +27,14 @@ void test2() { // Compliant } @Test - void test3() { // Noncompliant [[sc=8;ec=13;secondary=27,28,29]]{{Refactor this method to reduce the number of assertions from 3 to less than 2.}} + void test3() { // Noncompliant {{Refactor this method to reduce the number of assertions from 3 to less than 2.}} +// ^^^^^ assertEquals(2, f(2)); +// ^^^^^^^^^^^^^^^^^^^^^< assertEquals(3, f(1)); +// ^^^^^^^^^^^^^^^^^^^^^< customAssert(); +// ^^^^^^^^^^^^^^< } void customAssert() { diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/TooManyAssertionsCheckCustom25.java b/java-checks-test-sources/default/src/test/java/checks/tests/TooManyAssertionsCheckCustom25.java index 407fd1d420e..dc41fac7f85 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/TooManyAssertionsCheckCustom25.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/TooManyAssertionsCheckCustom25.java @@ -45,7 +45,8 @@ void test1() { // Compliant } @Test - void test2() { // Noncompliant [[sc=8;ec=13]]{{Refactor this method to reduce the number of assertions from 26 to less than 25.}} + void test2() { // Noncompliant {{Refactor this method to reduce the number of assertions from 26 to less than 25.}} +// ^^^^^ assertEquals(101, g(1)); assertEquals(102, g(2)); assertEquals(103, g(3)); diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/UnusedTestRuleCheck.java b/java-checks-test-sources/default/src/test/java/checks/tests/UnusedTestRuleCheck.java index c44d708aadc..60eb0cb6395 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/UnusedTestRuleCheck.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/UnusedTestRuleCheck.java @@ -10,7 +10,8 @@ class UnusedTestRuleCheck { @Rule - public TestName testNameUnused = new TestName(); // Noncompliant [[sc=19;ec=33]] {{Remove this unused "TestName".}} + public TestName testNameUnused = new TestName(); // Noncompliant {{Remove this unused "TestName".}} +// ^^^^^^^^^^^^^^ public TestName testNameObj = new TestName(); @@ -21,7 +22,7 @@ class UnusedTestRuleCheck { public TestName testNameUsed = new TestName(); @Rule - public TemporaryFolder tempFolderUnused = new TemporaryFolder(); // Noncompliant {{Remove this unused "TemporaryFolder".}} + public TemporaryFolder tempFolderUnused = new TemporaryFolder(); // Noncompliant {{Remove this unused "TemporaryFolder".}} @Rule public TemporaryFolder tempFolderUsed = new TemporaryFolder(); diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/UnusedTestRuleCheck_JUnit5.java b/java-checks-test-sources/default/src/test/java/checks/tests/UnusedTestRuleCheck_JUnit5.java index 01021ad4254..9801dd5c448 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/UnusedTestRuleCheck_JUnit5.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/UnusedTestRuleCheck_JUnit5.java @@ -19,11 +19,13 @@ class UnusedTestRuleCheck_Junit5 { @TempDir static Path sharedTempDir; @TempDir - static Path unusedSharedTempDir; // Noncompliant [[sc=15;ec=34]] {{Remove this unused "TempDir".}} + static Path unusedSharedTempDir; // Noncompliant {{Remove this unused "TempDir".}} +// ^^^^^^^^^^^^^^^^^^^ @TempDir File tempDir; @TempDir - File unusedTempDir; // Noncompliant [[sc=8;ec=21]] {{Remove this unused "TempDir".}} + File unusedTempDir; // Noncompliant {{Remove this unused "TempDir".}} +// ^^^^^^^^^^^^^ UnusedTestRuleCheck_Junit5(TestInfo testInfo) { assertEquals("TestInfo Demo", testInfo.getDisplayName()); @@ -61,7 +63,8 @@ void testUsingTempDirParam(@TempDir Path tempDirParam) throws IOException { } @Test - void testNotUsingTempDirParam(@TempDir Path unusedTempDirParam) throws IOException { // Noncompliant [[sc=47;ec=65]] {{Remove this unused "TempDir".}} + void testNotUsingTempDirParam(@TempDir Path unusedTempDirParam) throws IOException { // Noncompliant {{Remove this unused "TempDir".}} +// ^^^^^^^^^^^^^^^^^^ assertTrue(true); } @@ -75,11 +78,13 @@ class Test2 { interface ForCoverage { } - Test2(TestInfo testInfo) { // Noncompliant [[sc=18;ec=26]] {{Remove this unused "TestInfo".}} + Test2(TestInfo testInfo) { // Noncompliant {{Remove this unused "TestInfo".}} +// ^^^^^^^^ } @BeforeEach - void init(TestInfo testInfo) { // Noncompliant [[sc=22;ec=30]] {{Remove this unused "TestInfo".}} + void init(TestInfo testInfo) { // Noncompliant {{Remove this unused "TestInfo".}} +// ^^^^^^^^ String displayName = "abc"; assertTrue(displayName.equals("TEST 1") || displayName.equals("test2()")); } diff --git a/java-checks-test-sources/spring-3.2/src/main/java/checks/WeakSSLContextCheckSample.java b/java-checks-test-sources/spring-3.2/src/main/java/checks/WeakSSLContextCheckSample.java index e940aff37be..43ef17c9893 100644 --- a/java-checks-test-sources/spring-3.2/src/main/java/checks/WeakSSLContextCheckSample.java +++ b/java-checks-test-sources/spring-3.2/src/main/java/checks/WeakSSLContextCheckSample.java @@ -15,12 +15,17 @@ public class WeakSSLContextCheckSample { @Autowired public WeakSSLContextCheckSample(SslProperties props, DefaultSslBundleRegistry registry, Set propsSet) { - props.getBundle().getJks().get("").getOptions().setEnabledProtocols(Set.of("TLSv1.1", // Noncompliant [[sc=53;ec=72;secondary=18,20]] {{Change this code to use a stronger protocol.}} + props.getBundle().getJks().get("").getOptions().setEnabledProtocols(Set.of("TLSv1.1", // Noncompliant {{Change this code to use a stronger protocol.}} +// ^^^^^^^^^^^^^^^^^^^ +// ^^^^^^^^^@-1< "test", "TLSv1.0")); +// ^^^^^^^^^< props.getBundle().getJks().get("").getOptions().setEnabledProtocols(Set.of("TLSv1.0")); // Noncompliant - props.getBundle().getJks().get("").getOptions().setEnabledProtocols(Set.of(TLSV_1_0)); // Noncompliant [[sc=53;ec=72;secondary=23]] {{Change this code to use a stronger protocol.}} + props.getBundle().getJks().get("").getOptions().setEnabledProtocols(Set.of(TLSV_1_0)); // Noncompliant {{Change this code to use a stronger protocol.}} +// ^^^^^^^^^^^^^^^^^^^ +// ^^^^^^^^@-1< props.getBundle().getJks().get("").getOptions().setEnabledProtocols(Set.of(null)); // coverage props.getBundle().getJks().get("").getOptions().setEnabledProtocols(Set.of("TLSv1")); // Compliant diff --git a/java-checks-testkit/pom.xml b/java-checks-testkit/pom.xml index 4db390d03ac..9e06d8cfd0f 100644 --- a/java-checks-testkit/pom.xml +++ b/java-checks-testkit/pom.xml @@ -54,6 +54,11 @@ junit-jupiter-migrationsupport test + + org.sonarsource.analyzer-commons + sonar-analyzer-test-commons + compile + diff --git a/java-checks-testkit/src/main/java/org/sonar/java/checks/verifier/CheckVerifier.java b/java-checks-testkit/src/main/java/org/sonar/java/checks/verifier/CheckVerifier.java index 848a59327da..e22d8135e03 100644 --- a/java-checks-testkit/src/main/java/org/sonar/java/checks/verifier/CheckVerifier.java +++ b/java-checks-testkit/src/main/java/org/sonar/java/checks/verifier/CheckVerifier.java @@ -26,13 +26,14 @@ import org.sonar.api.batch.sensor.cache.ReadCache; import org.sonar.api.batch.sensor.cache.WriteCache; import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.internal.JavaCheckVerifier; import org.sonar.plugins.java.api.JavaFileScanner; /** - * This interface defines how to use checks (rules) verifiers. It's goal is to provide all the required information - * to the analyzer to verify checks' expected behavior. + * This interface defines how to use checks (rules) verifiers. Its goal is to provide all the required information + * to the analyzer to verify the checks' expected behavior. *

- * The starting point to define a verifier is {@link #newVerifier()}. Then, configuration can be specified. + * The starting point to define a verifier is {@link #newVerifier()}. Then, a configuration can be specified. *

* It is required to provide to the verifier at least the following: *

    @@ -40,36 +41,17 @@ *
  • A test file, by calling {@link #onFile(String)}, {@link #onFiles(String...)}, or {@link #onFiles(Collection)}
  • *
* Methods starting with "verify..." (e.g {@link #verifyIssues()} ) are the methods which effectively validate the rule. - * It is required to call any of them at the end of the verifier's configuration in order to trigger the verification. + * Any of them must be called at the end of the verifier's configuration to trigger the verification. * Nothing will happen if one of these method is not called. - *

- * In the test file(s), lines on which it is expected to have issues being raised have to be flagged with a comment - * prefixed by the "Noncompliant" string, followed by some optional details/specificity of the expected issue. - *

- * It is possible to specify the absolute line number on which the issue should appear by appending {@literal "@"} to "Noncompliant". - * But it is usually better to use line number relative to the current, this is possible to do by prefixing the number with either '+' or '-'. - *

- * For example, the following comment says that an issue is going to be raised on the next line (@+1), with the given message: - *

- *   // Noncompliant@+1 {{do not import "java.util.List"}}
- *   import java.util.List;
- * 
- * Full syntax: - *
- *   // Noncompliant@+1 [[startColumn=1;endLine=+1;endColumn=2;effortToFix=4;secondary=3,4]] {{issue message}}
- * 
- * Some attributes can also be written using a simplified form, for instance: - *
- *   // Noncompliant [[sc=14;ec=42]] {{issue message}}
- * 
- * Finally, note that attributes between {@literal [[...]]} are all optional: - *
    - *
  • startColumn (sc): column where the highlight starts
  • - *
  • endLine (el): relative endLine where the highlight ends (i.e. +1), same line if omitted
  • - *
  • endColumn (ec): column where the highlight ends
  • - *
  • effortToFix: the cost to fix as integer
  • - *
  • secondary: a comma separated list of integers identifying the lines of secondary locations if any
  • - *
+ * It uses + * + * MultiFileVerifier + * + * from + * sonar-analyzer-commons - test-commons + * + * library + * to verify issues on file. */ public interface CheckVerifier { @@ -79,6 +61,43 @@ public interface CheckVerifier { * @return the newly instantiated verifier */ static CheckVerifier newVerifier() { + return JavaCheckVerifier.newInstance(); + } + + /** + *

+ * In the test file(s), lines on which it is expected to have issues being raised have to be flagged with a comment + * prefixed by the "Noncompliant" string, followed by some optional details/specificity of the expected issue. + *

+ * It is possible to specify the absolute line number on which the issue should appear by appending {@literal "@"} to "Noncompliant". + * But it is usually better to use the line number relative to the current; this is possible by prefixing the number with either '+' or '-'. + *

+ * For example, the following comment says that an issue is going to be raised on the following line (@+1) with the given message: + *

+   *   // Noncompliant@+1 {{do not import "java.util.List"}}
+   *   import java.util.List;
+   * 
+ * Full syntax: + *
+   *   // Noncompliant@+1 [[startColumn=1;endLine=+1;endColumn=2;effortToFix=4;secondary=3,4]] {{issue message}}
+   * 
+ * Some attributes can also be written using a simplified form, for instance: + *
+   *   // Noncompliant [[sc=14;ec=42]] {{issue message}}
+   * 
+ * Finally, note that attributes between {@literal [[...]]} are all optional: + *
    + *
  • startColumn (sc): column where the highlight starts
  • + *
  • endLine (el): relative endLine where the highlight ends (i.e. +1), same line if omitted
  • + *
  • endColumn (ec): column where the highlight ends
  • + *
  • effortToFix: the cost to fix as integer
  • + *
  • secondary: a comma-separated list of integers identifying the lines of secondary locations if any
  • + *
+ * + * @deprecated in favor of {@link #newVerifier()}, which uses the analyzer-commons-test-commons library to verify issues on checks. + */ + @Deprecated(since = "7.35", forRemoval = true) + static CheckVerifier newInternalVerifier() { return InternalCheckVerifier.newInstance(); } @@ -87,7 +106,7 @@ static CheckVerifier newVerifier() { * * @param check the rule to be verified * - * @return the verifier configured to use the check provided as argument + * @return the verifier configured to use the check provided as an argument */ CheckVerifier withCheck(JavaFileScanner check); @@ -102,10 +121,10 @@ static CheckVerifier newVerifier() { /** * Defines the classpath to be used for the verification. Usually used when the code of the - * test files requires the knowledge of a particular set of libraries or java compiled classes. + * test files require the knowledge of a particular set of libraries or java compiled classes. * - * @param classpath a collection of file which defines the classes/jars/zips which contains - * the bytecode to be used as classpath when executing the rule + * @param classpath a collection of files which defines the classes/jars/zips which contains + * the bytecode to be used as a classpath when executing the rule * * @return the verifier configured to use the files provided as argument as classpath */ @@ -113,8 +132,8 @@ static CheckVerifier newVerifier() { /** * Defines the java version syntax to be used for the verification. Usually used when the code of the - * test files target explicitly a given version (eg. java 7), where a particular syntax/API has been introduced. - * Preview features for the specified java version will be disabled by default, use {@link CheckVerifier#withJavaVersion(int, boolean)} + * test files explicitly target a given version (e.g. java 7) where a particular syntax/API has been introduced. + * Preview features for the specified java version will be disabled by default; use {@link CheckVerifier#withJavaVersion(int, boolean)} * to enable or disable preview features associated with the specified java version. * * @param javaVersionAsInt defines the java language syntax version to be considered during verification, provided as an integer. @@ -123,14 +142,14 @@ static CheckVerifier newVerifier() { * @return the verifier configured to consider the provided test file(s) as following the syntax of the given java version */ CheckVerifier withJavaVersion(int javaVersionAsInt); - + /** * Defines the java version syntax to be used for the verification. Usually used when the code of the - * test files target explicitly a given version (eg. java 7), where a particular syntax/API has been introduced. + * test files explicitly target a given version (e.g. java 7) where a particular syntax/API has been introduced. * * @param javaVersionAsInt defines the java language syntax version to be considered during verification, provided as an integer. * For instance, for Java 1.7, use '7'. For Java 12, simply '12'. - * + * * @param enablePreviewFeatures defines if preview features from the specified java version should be enabled or not * * @return the verifier configured to consider the provided test file(s) as following the syntax of the given java version @@ -140,7 +159,7 @@ static CheckVerifier newVerifier() { CheckVerifier withJavaVersion(int javaVersionAsInt, boolean enablePreviewFeatures); /** - * Defines the whether the current file is analyzer in an android context. + * Defines whether the current file is an analyzer in an Android context. * * @return the verifier currently configured */ @@ -152,7 +171,7 @@ static CheckVerifier newVerifier() { * * @param filename the file to be analyzed * - * @return the verifier configured to consider the provided test file as source for the rule(s) + * @return the verifier configured to consider the provided test file as the source for the rule(s) */ CheckVerifier onFile(String filename); @@ -178,21 +197,21 @@ static CheckVerifier newVerifier() { /** * Adds a collection of files with an expected status to be verified by the given rule(s). - * If a file by the same filename is already listed to be analyzed, an exception is thrown. + * An exception is thrown if a file by the same filename is already listed to be analyzed. * @param status The status of the files to be analyzed * @param filenames a collection of files to be analyzed * @return the verifier configured - * @throws IllegalArgumentException if a file by the same filename had already been added + * @throws IllegalArgumentException if a file by the same filename has already been added */ CheckVerifier addFiles(InputFile.Status status, String... filenames); /** * Adds a collection of files with an expected status. - * If a file by the same filename is already listed to be analyzed, an exception is thrown. + * An exception is thrown if a file with the same filename is already listed to be analyzed. * @param status The status of the files to be analyzed * @param filenames a collection of files to be analyzed * @return the verifier configured - * @throws IllegalArgumentException if a file by the same filename had already been added + * @throws IllegalArgumentException if a file by the same filename has already been added */ CheckVerifier addFiles(InputFile.Status status, Collection filenames); @@ -220,7 +239,7 @@ static CheckVerifier newVerifier() { void verifyIssues(); /** - * Verifies that an issue (only one) is raised directly on the file, and not + * Verifies that an issue (only one) is raised directly on the file and not * within the content of the file. * * @param expectedIssueMessage the message to be expected with the issue. @@ -228,7 +247,7 @@ static CheckVerifier newVerifier() { void verifyIssueOnFile(String expectedIssueMessage); /** - * Verifies that an issue (only one) is raised directly on the project which would include this file, + * Verifies that an issue (only one) is raised directly on the project, which would include this file, * and not within the content of the file. * * @param expectedIssueMessage diff --git a/java-checks-testkit/src/main/java/org/sonar/java/checks/verifier/internal/CheckVerifierUtils.java b/java-checks-testkit/src/main/java/org/sonar/java/checks/verifier/internal/CheckVerifierUtils.java new file mode 100644 index 00000000000..1b45c8b007b --- /dev/null +++ b/java-checks-testkit/src/main/java/org/sonar/java/checks/verifier/internal/CheckVerifierUtils.java @@ -0,0 +1,90 @@ +/* + * SonarQube Java + * Copyright (C) 2012-2024 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.java.checks.verifier.internal; + +import com.sonar.sslr.api.RecognitionException; +import java.util.Collection; +import javax.annotation.Nullable; +import org.sonar.api.batch.fs.FileSystem; +import org.sonar.api.batch.fs.InputFile; +import org.sonar.api.batch.sensor.SensorContext; +import org.sonar.api.batch.sensor.cache.ReadCache; +import org.sonar.api.batch.sensor.cache.WriteCache; +import org.sonar.api.config.Configuration; +import org.sonar.java.SonarComponents; +import org.sonar.java.classpath.ClasspathForMain; +import org.sonar.java.classpath.ClasspathForTest; + +public class CheckVerifierUtils { + + private CheckVerifierUtils() { + // utility class + } + + protected static final String CHECK_OR_CHECKS = "check(s)"; + protected static final String FILE_OR_FILES = "file(s)"; + + protected static SonarComponents sonarComponents(boolean isCacheEnabled, ReadCache readCache, WriteCache writeCache) { + SensorContext sensorContext; + if (isCacheEnabled) { + sensorContext = new CacheEnabledSensorContext(readCache, writeCache); + } else { + sensorContext = new InternalSensorContext(); + } + FileSystem fileSystem = sensorContext.fileSystem(); + Configuration config = sensorContext.config(); + + ClasspathForMain classpathForMain = new ClasspathForMain(config, fileSystem); + ClasspathForTest classpathForTest = new ClasspathForTest(config, fileSystem); + + SonarComponents sonarComponents = new SonarComponents(null, fileSystem, classpathForMain, classpathForTest, null, null) { + @Override + public boolean reportAnalysisError(RecognitionException re, InputFile inputFile) { + throw new AssertionError(String.format("Should not fail analysis (%s)", re.getMessage())); + } + + @Override + public boolean canSkipUnchangedFiles() { + return isCacheEnabled; + } + }; + sonarComponents.setSensorContext(sensorContext); + return sonarComponents; + } + + protected static void requiresNull(@Nullable Object obj, String fieldName) { + if (obj != null) { + throw new AssertionError(String.format("Do not set %s multiple times!", fieldName)); + } + } + + protected static void requiresNonNull(@Nullable Object obj, String fieldName) { + if (obj == null) { + throw new AssertionError(String.format("Set %s before calling any verification method!", fieldName)); + } + } + + protected static void requiresNonEmpty(Collection objects, String fieldName) { + if (objects.isEmpty()) { + throw new AssertionError(String.format("Provide at least one %s!", fieldName)); + } + } + +} diff --git a/java-checks-testkit/src/main/java/org/sonar/java/checks/verifier/internal/InternalCheckVerifier.java b/java-checks-testkit/src/main/java/org/sonar/java/checks/verifier/internal/InternalCheckVerifier.java index 999ae5dadac..349f1f6b482 100644 --- a/java-checks-testkit/src/main/java/org/sonar/java/checks/verifier/internal/InternalCheckVerifier.java +++ b/java-checks-testkit/src/main/java/org/sonar/java/checks/verifier/internal/InternalCheckVerifier.java @@ -19,7 +19,6 @@ */ package org.sonar.java.checks.verifier.internal; -import com.sonar.sslr.api.RecognitionException; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; @@ -43,12 +42,9 @@ import java.util.function.Function; import java.util.stream.Collectors; import javax.annotation.Nullable; -import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.batch.sensor.cache.ReadCache; import org.sonar.api.batch.sensor.cache.WriteCache; -import org.sonar.api.config.Configuration; import org.sonar.java.SonarComponents; import org.sonar.java.annotations.Beta; import org.sonar.java.annotations.VisibleForTesting; @@ -58,8 +54,6 @@ import org.sonar.java.caching.JavaWriteCacheImpl; import org.sonar.java.checks.verifier.CheckVerifier; import org.sonar.java.checks.verifier.FilesUtils; -import org.sonar.java.classpath.ClasspathForMain; -import org.sonar.java.classpath.ClasspathForTest; import org.sonar.java.model.JavaVersionImpl; import org.sonar.java.reporting.AnalyzerMessage; import org.sonar.java.reporting.AnalyzerMessage.TextSpan; @@ -72,6 +66,11 @@ import org.sonar.plugins.java.api.JavaVersion; import org.sonar.plugins.java.api.caching.CacheContext; +import static org.sonar.java.checks.verifier.internal.CheckVerifierUtils.CHECK_OR_CHECKS; +import static org.sonar.java.checks.verifier.internal.CheckVerifierUtils.FILE_OR_FILES; +import static org.sonar.java.checks.verifier.internal.CheckVerifierUtils.requiresNonEmpty; +import static org.sonar.java.checks.verifier.internal.CheckVerifierUtils.requiresNonNull; +import static org.sonar.java.checks.verifier.internal.CheckVerifierUtils.requiresNull; import static org.sonar.java.checks.verifier.internal.Expectations.IssueAttribute.EFFORT_TO_FIX; import static org.sonar.java.checks.verifier.internal.Expectations.IssueAttribute.END_COLUMN; import static org.sonar.java.checks.verifier.internal.Expectations.IssueAttribute.END_LINE; @@ -82,9 +81,6 @@ public class InternalCheckVerifier implements CheckVerifier { - private static final String CHECK_OR_CHECKS = "check(s)"; - private static final String FILE_OR_FILES = "file(s)"; - private static final JavaVersion DEFAULT_JAVA_VERSION = new JavaVersionImpl(); private static final List DEFAULT_CLASSPATH; @@ -300,7 +296,7 @@ private void verifyAll() { } else { visitors.add(expectations.parser()); } - SonarComponents sonarComponents = sonarComponents(); + SonarComponents sonarComponents = CheckVerifierUtils.sonarComponents(isCacheEnabled, readCache, writeCache); VisitorsBridgeForTests visitorsBridge; JavaVersion actualVersion = javaVersion == null ? DEFAULT_JAVA_VERSION : javaVersion; if (withoutSemantic) { @@ -636,52 +632,6 @@ private static String flowToString(List flow) { return flow.stream().map(m -> String.valueOf(m.getLine())).collect(Collectors.joining(",", "[", "]")); } - private static void requiresNull(@Nullable Object obj, String fieldName) { - if (obj != null) { - throw new AssertionError(String.format("Do not set %s multiple times!", fieldName)); - } - } - - private static void requiresNonNull(@Nullable Object obj, String fieldName) { - if (obj == null) { - throw new AssertionError(String.format("Set %s before calling any verification method!", fieldName)); - } - } - - private static void requiresNonEmpty(Collection objects, String fieldName) { - if (objects.isEmpty()) { - throw new AssertionError(String.format("Provide at least one %s!", fieldName)); - } - } - - private SonarComponents sonarComponents() { - SensorContext sensorContext; - if (isCacheEnabled) { - sensorContext = new CacheEnabledSensorContext(readCache, writeCache); - } else { - sensorContext = new InternalSensorContext(); - } - FileSystem fileSystem = sensorContext.fileSystem(); - Configuration config = sensorContext.config(); - - ClasspathForMain classpathForMain = new ClasspathForMain(config, fileSystem); - ClasspathForTest classpathForTest = new ClasspathForTest(config, fileSystem); - - SonarComponents sonarComponents = new SonarComponents(null, fileSystem, classpathForMain, classpathForTest, null, null) { - @Override - public boolean reportAnalysisError(RecognitionException re, InputFile inputFile) { - throw new AssertionError(String.format("Should not fail analysis (%s)", re.getMessage())); - } - - @Override - public boolean canSkipUnchangedFiles() { - return isCacheEnabled; - } - }; - sonarComponents.setSensorContext(sensorContext); - return sonarComponents; - } - private static class QuickFixesVerifier implements Consumer> { private final Map> expectedQuickFixes; diff --git a/java-checks-testkit/src/main/java/org/sonar/java/checks/verifier/internal/JavaCheckVerifier.java b/java-checks-testkit/src/main/java/org/sonar/java/checks/verifier/internal/JavaCheckVerifier.java new file mode 100644 index 00000000000..47690767fc2 --- /dev/null +++ b/java-checks-testkit/src/main/java/org/sonar/java/checks/verifier/internal/JavaCheckVerifier.java @@ -0,0 +1,360 @@ +/* + * SonarQube Java + * Copyright (C) 2012-2024 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.java.checks.verifier.internal; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import javax.annotation.Nullable; +import org.sonar.api.batch.fs.InputFile; +import org.sonar.api.batch.sensor.cache.ReadCache; +import org.sonar.api.batch.sensor.cache.WriteCache; +import org.sonar.java.SonarComponents; +import org.sonar.java.annotations.VisibleForTesting; +import org.sonar.java.ast.JavaAstScanner; +import org.sonar.java.ast.visitors.CommentLinesVisitor; +import org.sonar.java.caching.DummyCache; +import org.sonar.java.caching.JavaReadCacheImpl; +import org.sonar.java.caching.JavaWriteCacheImpl; +import org.sonar.java.checks.verifier.CheckVerifier; +import org.sonar.java.checks.verifier.FilesUtils; +import org.sonar.java.model.JavaVersionImpl; +import org.sonar.java.reporting.AnalyzerMessage; +import org.sonar.java.reporting.JavaQuickFix; +import org.sonar.java.test.classpath.TestClasspathUtils; +import org.sonar.java.testing.JavaFileScannerContextForTests; +import org.sonar.java.testing.VisitorsBridgeForTests; +import org.sonar.plugins.java.api.JavaFileScanner; +import org.sonar.plugins.java.api.JavaVersion; +import org.sonar.plugins.java.api.caching.CacheContext; +import org.sonarsource.analyzer.commons.checks.verifier.MultiFileVerifier; +import org.sonarsource.analyzer.commons.checks.verifier.quickfix.QuickFix; +import org.sonarsource.analyzer.commons.checks.verifier.quickfix.TextEdit; +import org.sonarsource.analyzer.commons.checks.verifier.quickfix.TextSpan; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.sonar.java.checks.verifier.internal.CheckVerifierUtils.CHECK_OR_CHECKS; +import static org.sonar.java.checks.verifier.internal.CheckVerifierUtils.FILE_OR_FILES; +import static org.sonar.java.checks.verifier.internal.CheckVerifierUtils.requiresNonEmpty; +import static org.sonar.java.checks.verifier.internal.CheckVerifierUtils.requiresNonNull; +import static org.sonar.java.checks.verifier.internal.CheckVerifierUtils.requiresNull; + +public class JavaCheckVerifier implements CheckVerifier { + + private static final JavaVersion DEFAULT_JAVA_VERSION = new JavaVersionImpl(); + private static final List DEFAULT_CLASSPATH; + private static final int COMMENT_PREFIX_LENGTH = 2; + private static final int COMMENT_SUFFIX_LENGTH = 0; + + private JavaCheckVerifier() { + } + + public static JavaCheckVerifier newInstance() { + return new JavaCheckVerifier(); + } + + static { + Path path = Paths.get(FilesUtils.DEFAULT_TEST_CLASSPATH_FILE.replace('/', File.separatorChar)); + // Because of 'java-custom-rules-example' module, we silently use an empty classpath if the file does not exist + DEFAULT_CLASSPATH = Files.exists(path) ? TestClasspathUtils.loadFromFile(path.toString()) : new ArrayList<>(); + Optional.of(new File(FilesUtils.DEFAULT_TEST_CLASSES_DIRECTORY)).filter(File::exists).ifPresent(DEFAULT_CLASSPATH::add); + } + + private List checks = null; + private List classpath = null; + private JavaVersion javaVersion = null; + private boolean inAndroidContext = false; + private List files = null; + private boolean withoutSemantic = false; + private boolean isCacheEnabled = false; + + @VisibleForTesting + CacheContext cacheContext = null; + private ReadCache readCache; + private WriteCache writeCache; + + private MultiFileVerifier createVerifier() { + MultiFileVerifier verifier = MultiFileVerifier.create(Paths.get(files.get(0).uri()), UTF_8); + + JavaVersion actualVersion = javaVersion == null ? DEFAULT_JAVA_VERSION : javaVersion; + List actualClasspath = classpath == null ? DEFAULT_CLASSPATH : classpath; + + List visitors = new ArrayList<>(checks); + CommentLinesVisitor commentLinesVisitor = new CommentLinesVisitor(); + visitors.add(commentLinesVisitor); + SonarComponents sonarComponents = CheckVerifierUtils.sonarComponents(isCacheEnabled, readCache, writeCache); + VisitorsBridgeForTests visitorsBridge; + if (withoutSemantic) { + visitorsBridge = new VisitorsBridgeForTests(visitors, sonarComponents, actualVersion); + } else { + visitorsBridge = new VisitorsBridgeForTests(visitors, actualClasspath, sonarComponents, actualVersion); + } + + JavaAstScanner astScanner = new JavaAstScanner(sonarComponents); + visitorsBridge.setInAndroidContext(inAndroidContext); + + astScanner.setVisitorBridge(visitorsBridge); + + List filesToParse = files; + if (isCacheEnabled) { + visitorsBridge.setCacheContext(cacheContext); + filesToParse = astScanner.scanWithoutParsing(files).get(false); + } + astScanner.scan(filesToParse); + + addComments(verifier, commentLinesVisitor); + + JavaFileScannerContextForTests testJavaFileScannerContext = visitorsBridge.lastCreatedTestContext(); + JavaFileScannerContextForTests testModuleScannerContext = visitorsBridge.lastCreatedModuleContext(); + if (testJavaFileScannerContext != null) { + addIssues(testJavaFileScannerContext, verifier); + addIssues(testModuleScannerContext, verifier); + } + + return verifier; + } + + private static void addIssues(JavaFileScannerContextForTests scannerContext, MultiFileVerifier verifier) { + scannerContext.getIssues().forEach(issue -> { + if (!issue.getInputComponent().isFile()) { + return; + } + Path path = ((InternalInputFile) issue.getInputComponent()).path(); + String issueMessage = issue.getMessage(); + AnalyzerMessage.TextSpan textSpan = issue.primaryLocation(); + MultiFileVerifier.Issue verifierIssue; + if (textSpan != null) { + verifierIssue = getIssueForTextSpan(verifier, textSpan, path, issueMessage); + } else if (issue.getLine() != null) { + verifierIssue = verifier.reportIssue(path, issueMessage).onLine(issue.getLine()); + } else { + verifierIssue = verifier.reportIssue(path, issueMessage).onFile(); + } + + var quickfixes = scannerContext.getQuickFixes().get(textSpan); + if (quickfixes != null) { + for (var qf : quickfixes) { + verifierIssue = verifierIssue.addQuickFix(convertQuickFix(qf)); + } + } + + List secondaries = issue.flows.stream().map(l -> l.isEmpty() ? null : l.get(0)).filter(Objects::nonNull).toList(); + MultiFileVerifier.Issue finalVerifierIssue = verifierIssue; + secondaries.forEach(secondary -> addSecondary(path, finalVerifierIssue, secondary)); + }); + } + + private static MultiFileVerifier.Issue getIssueForTextSpan(MultiFileVerifier verifier, AnalyzerMessage.TextSpan textSpan, Path path, String issueMessage) { + MultiFileVerifier.Issue verifierIssue; + if (textSpan.endCharacter < 0) { + // Sometimes we create a textspan with endCharacter < 0 to raise an issue on the line. + verifierIssue = verifier.reportIssue(path, issueMessage).onLine(textSpan.startLine); + } else { + verifierIssue = verifier.reportIssue(path, issueMessage) + .onRange(textSpan.startLine, textSpan.startCharacter + 1, textSpan.endLine, textSpan.endCharacter); + } + return verifierIssue; + } + + private static QuickFix convertQuickFix(JavaQuickFix javaQuickFix) { + return QuickFix.newQuickFix(javaQuickFix.getDescription()) + .addTextEdits(javaQuickFix.getTextEdits().stream() + .map(te -> TextEdit.replaceTextSpan(convertTextSpan(te.getTextSpan()), convertReplacement(te.getReplacement()))).toList()) + .build(); + } + + private static TextSpan convertTextSpan(AnalyzerMessage.TextSpan textSpan) { + return new TextSpan(textSpan.startLine, textSpan.startCharacter + 1, textSpan.endLine, textSpan.endCharacter + 1); + } + + private static String convertReplacement(String replacement) { + return replacement.replace("\n", "\\n"); + } + + private static void addSecondary(Path path, MultiFileVerifier.Issue issue, AnalyzerMessage secondary) { + AnalyzerMessage.TextSpan textSpan = secondary.primaryLocation(); + issue.addSecondary(path, textSpan.startLine, textSpan.startCharacter + 1, textSpan.endLine, textSpan.endCharacter, secondary.getMessage()); + } + + private static void addComments(MultiFileVerifier singleFileVerifier, CommentLinesVisitor commentLinesVisitor) { + commentLinesVisitor.getSyntaxTrivia().keySet() + .forEach(path -> commentLinesVisitor.getSyntaxTrivia().get(path).stream() + .sorted(Comparator.comparingInt(t -> t.range().start().line())) + .forEach(trivia -> singleFileVerifier.addComment( + path, + trivia.range().start().line(), + trivia.range().start().column(), + trivia.comment(), + COMMENT_PREFIX_LENGTH, + COMMENT_SUFFIX_LENGTH))); + } + + @Override + public CheckVerifier withCheck(JavaFileScanner check) { + requiresNull(checks, CHECK_OR_CHECKS); + this.checks = Collections.singletonList(check); + return this; + } + + @Override + public CheckVerifier withChecks(JavaFileScanner... checks) { + requiresNull(this.checks, CHECK_OR_CHECKS); + requiresNonEmpty(Arrays.asList(checks), "check"); + this.checks = Arrays.asList(checks); + return this; + } + + @Override + public CheckVerifier withClassPath(Collection classpath) { + requiresNull(this.classpath, "classpath"); + this.classpath = new ArrayList<>(classpath); + return this; + } + + @Override + public CheckVerifier withJavaVersion(int javaVersionAsInt) { + requiresNull(javaVersion, "java version"); + return withJavaVersion(javaVersionAsInt, false); + } + + @Override + public CheckVerifier withJavaVersion(int javaVersionAsInt, boolean enablePreviewFeatures) { + requiresNull(javaVersion, "java version"); + if (enablePreviewFeatures && javaVersionAsInt != JavaVersionImpl.MAX_SUPPORTED) { + var message = String.format( + "Preview features can only be enabled when the version == latest supported Java version (%d != %d)", + javaVersionAsInt, + JavaVersionImpl.MAX_SUPPORTED); + throw new IllegalArgumentException(message); + } + this.javaVersion = new JavaVersionImpl(javaVersionAsInt, enablePreviewFeatures); + return this; + } + + @Override + public CheckVerifier withinAndroidContext(boolean inAndroidContext) { + this.inAndroidContext = inAndroidContext; + return this; + } + + @Override + public CheckVerifier onFile(String filename) { + requiresNull(files, FILE_OR_FILES); + return onFiles(Collections.singletonList(filename)); + } + + @Override + public CheckVerifier onFiles(String... filenames) { + List asList = Arrays.asList(filenames); + requiresNonEmpty(asList, "file"); + return onFiles(asList); + } + + @Override + public CheckVerifier onFiles(Collection filenames) { + requiresNull(files, FILE_OR_FILES); + requiresNonEmpty(filenames, "file"); + this.files = new ArrayList<>(); + return addFiles(InputFile.Status.SAME, filenames); + } + + @Override + public CheckVerifier addFiles(InputFile.Status status, String... filenames) { + return addFiles(status, Arrays.asList(filenames)); + } + + @Override + public CheckVerifier addFiles(InputFile.Status status, Collection filenames) { + requiresNonEmpty(filenames, "file"); + if (this.files == null) { + this.files = new ArrayList<>(filenames.size()); + } + + var filesToAdd = filenames.stream() + .map(name -> InternalInputFile.inputFile("", new File(name), status)) + .toList(); + + var filesToAddStrings = filesToAdd.stream().map(Object::toString).toList(); + + this.files.forEach(inputFile -> { + if (filesToAddStrings.contains(inputFile.toString())) { + throw new IllegalArgumentException(String.format("File %s was already added.", inputFile)); + } + }); + + this.files.addAll(filesToAdd); + + return this; + } + + @Override + public CheckVerifier withoutSemantic() { + this.withoutSemantic = true; + return this; + } + + @Override + public CheckVerifier withCache(@Nullable ReadCache readCache, @Nullable WriteCache writeCache) { + this.isCacheEnabled = true; + this.readCache = readCache; + this.writeCache = writeCache; + this.cacheContext = new InternalCacheContext( + true, + readCache == null ? new DummyCache() : new JavaReadCacheImpl(readCache), + writeCache == null ? new DummyCache() : new JavaWriteCacheImpl(writeCache)); + return this; + } + + @Override + public void verifyIssues() { + requiresNonNull(checks, CHECK_OR_CHECKS); + requiresNonNull(files, FILE_OR_FILES); + createVerifier().assertOneOrMoreIssues(); + } + + @Override + public void verifyIssueOnFile(String expectedIssueMessage) { + requiresNonNull(checks, CHECK_OR_CHECKS); + requiresNonNull(files, FILE_OR_FILES); + createVerifier().assertOneOrMoreIssues(); + } + + @Override + public void verifyIssueOnProject(String expectedIssueMessage) { + throw new UnsupportedOperationException("Not implemented!"); + } + + @Override + public void verifyNoIssues() { + requiresNonNull(checks, CHECK_OR_CHECKS); + requiresNonNull(files, FILE_OR_FILES); + createVerifier().assertNoIssuesRaised(); + } + +} diff --git a/java-checks-testkit/src/test/files/java-check-verifier/CommonsJavaCheckVerifier.java b/java-checks-testkit/src/test/files/java-check-verifier/CommonsJavaCheckVerifier.java new file mode 100644 index 00000000000..95132cdc0c5 --- /dev/null +++ b/java-checks-testkit/src/test/files/java-check-verifier/CommonsJavaCheckVerifier.java @@ -0,0 +1,22 @@ +class A { // Noncompliant {{message}} + + int i; // Noncompliant {{message1}} + + void foo() { // test method + // Noncompliant@+1 {{message2}} + int j; + int k; + // Noncompliant@-1 {{message3}} {{message3}} + + int l; // Noncompliant {{message4}} + // ^ + + int m; // Noncompliant + int n; // Noncompliant + + String string = ""; + // ^^> + System.out.println(string); // Noncompliant {{message12}} + // ^^^^^^ + } +} diff --git a/java-checks-testkit/src/test/files/java-check-verifier/CommonsJavaCheckVerifierOnFile.java b/java-checks-testkit/src/test/files/java-check-verifier/CommonsJavaCheckVerifierOnFile.java new file mode 100644 index 00000000000..84b6165f1fb --- /dev/null +++ b/java-checks-testkit/src/test/files/java-check-verifier/CommonsJavaCheckVerifierOnFile.java @@ -0,0 +1,7 @@ +class A { + int i; + + void foo() {} +} + +// Noncompliant@0 diff --git a/java-checks-testkit/src/test/java/org/sonar/java/checks/verifier/CheckVerifierTest.java b/java-checks-testkit/src/test/java/org/sonar/java/checks/verifier/CheckVerifierTest.java index ce684a19820..8dba81939e6 100644 --- a/java-checks-testkit/src/test/java/org/sonar/java/checks/verifier/CheckVerifierTest.java +++ b/java-checks-testkit/src/test/java/org/sonar/java/checks/verifier/CheckVerifierTest.java @@ -19,7 +19,6 @@ */ package org.sonar.java.checks.verifier; -import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; @@ -46,6 +45,7 @@ class CheckVerifierTest { private static final String FILENAME_ISSUES = "src/test/files/JavaCheckVerifier.java"; + private static final String FILENAME_ISSUES_JAVA_CHECK_VERIFIER = "src/test/files/java-check-verifier/CommonsJavaCheckVerifier.java"; private static final String FILENAME_NO_ISSUE = "src/test/files/JavaCheckVerifierNoIssue.java"; private static final IssuableSubscriptionVisitor NO_EFFECT_VISITOR = new IssuableSubscriptionVisitor() { @Override @@ -57,8 +57,17 @@ public List nodesToVisit() { @Test void verify_line_issues() { IssuableSubscriptionVisitor visitor = new FakeVisitor().withDefaultIssues(); + CheckVerifier.newInternalVerifier() + .onFile(FILENAME_ISSUES) + .withCheck(visitor) + .verifyIssues(); + } + + @Test + void verify_line_issues_java_verifier() { + IssuableSubscriptionVisitor visitor = new FakeVisitor().withDefaultIssuesForJavaCheckVerifier(); CheckVerifier.newVerifier() - .onFile("src/test/files/JavaCheckVerifier.java") + .onFile(FILENAME_ISSUES_JAVA_CHECK_VERIFIER) .withCheck(visitor) .verifyIssues(); } @@ -66,7 +75,7 @@ void verify_line_issues() { @Test void verify_unexpected_issue() { IssuableSubscriptionVisitor visitor = new FakeVisitor().withDefaultIssues().withIssue(4, "extra message"); - CheckVerifier verifier = CheckVerifier.newVerifier().onFile(FILENAME_ISSUES).withCheck(visitor); + CheckVerifier verifier = CheckVerifier.newInternalVerifier().onFile(FILENAME_ISSUES).withCheck(visitor); try { verifier.verifyIssues(); @@ -76,10 +85,22 @@ void verify_unexpected_issue() { } } + @Test + void verify_unexpected_issue_java_verifier() { + IssuableSubscriptionVisitor visitor = new FakeVisitor().withDefaultIssuesForJavaCheckVerifier().withIssue(4, "extra message"); + CheckVerifier verifier = CheckVerifier.newVerifier().onFile(FILENAME_ISSUES_JAVA_CHECK_VERIFIER).withCheck(visitor); + try { + verifier.verifyIssues(); + Fail.fail("Should have failed"); + } catch (AssertionError e) { + assertThat(e).hasMessageContaining("ERROR: Expect 9 issues instead of 10. In file (CommonsJavaCheckVerifier.java:7)"); + } + } + @Test void verify_combined_missing_expected_and_unexpected_issues() { IssuableSubscriptionVisitor visitor = new FakeVisitor().withDefaultIssues().withIssue(4, "extra message").withoutIssue(1); - CheckVerifier verifier = CheckVerifier.newVerifier().onFile(FILENAME_ISSUES).withCheck(visitor); + CheckVerifier verifier = CheckVerifier.newInternalVerifier().onFile(FILENAME_ISSUES).withCheck(visitor); try { verifier.verifyIssues(); @@ -92,7 +113,7 @@ void verify_combined_missing_expected_and_unexpected_issues() { @Test void verify_missing_expected_issue() { IssuableSubscriptionVisitor visitor = new FakeVisitor().withDefaultIssues().withoutIssue(1); - CheckVerifier verifier = CheckVerifier.newVerifier().onFile(FILENAME_ISSUES).withCheck(visitor); + CheckVerifier verifier = CheckVerifier.newInternalVerifier().onFile(FILENAME_ISSUES).withCheck(visitor); try { verifier.verifyIssues(); @@ -106,20 +127,38 @@ void verify_missing_expected_issue() { void verify_issue_on_file() { String expectedMessage = "messageOnFile"; IssuableSubscriptionVisitor visitor = new FakeVisitor().withIssueOnFile(expectedMessage); - CheckVerifier.newVerifier() + CheckVerifier.newInternalVerifier() .onFile(FILENAME_ISSUES) .withCheck(visitor) .verifyIssueOnFile(expectedMessage); } + @Test + void verify_issue_on_file_java_verifier() { + String expectedMessage = "messageOnFile"; + IssuableSubscriptionVisitor visitor = new FakeVisitor().withIssueOnFile(expectedMessage); + CheckVerifier.newVerifier() + .onFile("src/test/files/java-check-verifier/CommonsJavaCheckVerifierOnFile.java") + .withCheck(visitor) + .verifyIssueOnFile(expectedMessage); + } + @Test void verify_issue_on_file_incorrect() { - CheckVerifier verifier = CheckVerifier.newVerifier().onFile(FILENAME_ISSUES).withCheck(new FakeVisitor().withDefaultIssues()); + CheckVerifier verifier = CheckVerifier.newInternalVerifier().onFile(FILENAME_ISSUES).withCheck(new FakeVisitor().withDefaultIssues()); assertThrows(AssertionError.class, () -> verifier.onFile("messageOnFile")); } @Test void verify_no_issue() { + CheckVerifier.newInternalVerifier() + .onFile(FILENAME_NO_ISSUE) + .withCheck(NO_EFFECT_VISITOR) + .verifyNoIssues(); + } + + @Test + void verify_no_issue_java_verifier() { CheckVerifier.newVerifier() .onFile(FILENAME_NO_ISSUE) .withCheck(NO_EFFECT_VISITOR) @@ -130,7 +169,7 @@ void verify_no_issue() { void verify_with_provided_classes() { IssuableSubscriptionVisitor visitor = new FakeVisitor().withDefaultIssues(); - CheckVerifier.newVerifier() + CheckVerifier.newInternalVerifier() .onFile(FILENAME_ISSUES) .withCheck(visitor) .withClassPath(Collections.emptyList()) @@ -138,18 +177,29 @@ void verify_with_provided_classes() { } @Test - void verify_with_default_test_jar() throws IOException { + void verify_with_provided_classes_java_verifier() { + IssuableSubscriptionVisitor visitor = new FakeVisitor().withDefaultIssuesForJavaCheckVerifier(); + + CheckVerifier.newVerifier() + .onFile(FILENAME_ISSUES_JAVA_CHECK_VERIFIER) + .withCheck(visitor) + .withClassPath(Collections.emptyList()) + .verifyIssues(); + } + + @Test + void verify_with_default_test_jar() { // This path is the actual test-jars path for this project, as the currently supplied jar doesn't cause any issues in the test file // retain the actual folder with contents. This will prevent other tests to fail which rely on the supplied bytecode. - CheckVerifier.newVerifier() + CheckVerifier.newInternalVerifier() .onFile(FILENAME_NO_ISSUE) .withCheck(NO_EFFECT_VISITOR) .verifyNoIssues(); } @Test - void verify_should_fail_when_using_incorrect_shift() throws IOException { - CheckVerifier verifier = CheckVerifier.newVerifier() + void verify_should_fail_when_using_incorrect_shift() { + CheckVerifier verifier = CheckVerifier.newInternalVerifier() .onFile("src/test/files/JavaCheckVerifierIncorrectShift.java") .withCheck(NO_EFFECT_VISITOR); @@ -162,8 +212,8 @@ void verify_should_fail_when_using_incorrect_shift() throws IOException { } @Test - void verify_should_fail_when_using_incorrect_attribute() throws IOException { - CheckVerifier verifier = CheckVerifier.newVerifier() + void verify_should_fail_when_using_incorrect_attribute() { + CheckVerifier verifier = CheckVerifier.newInternalVerifier() .onFile("src/test/files/JavaCheckVerifierIncorrectAttribute.java") .withCheck(NO_EFFECT_VISITOR); @@ -176,8 +226,8 @@ void verify_should_fail_when_using_incorrect_attribute() throws IOException { } @Test - void verify_should_fail_when_using_incorrect_attribute2() throws IOException { - CheckVerifier verifier = CheckVerifier.newVerifier() + void verify_should_fail_when_using_incorrect_attribute2() { + CheckVerifier verifier = CheckVerifier.newInternalVerifier() .onFile("src/test/files/JavaCheckVerifierIncorrectAttribute2.java") .withCheck(NO_EFFECT_VISITOR); @@ -190,8 +240,8 @@ void verify_should_fail_when_using_incorrect_attribute2() throws IOException { } @Test - void verify_should_fail_when_using_incorrect_endLine() throws IOException { - CheckVerifier verifier = CheckVerifier.newVerifier() + void verify_should_fail_when_using_incorrect_endLine() { + CheckVerifier verifier = CheckVerifier.newInternalVerifier() .onFile("src/test/files/JavaCheckVerifierIncorrectEndLine.java") .withCheck(NO_EFFECT_VISITOR); @@ -204,9 +254,9 @@ void verify_should_fail_when_using_incorrect_endLine() throws IOException { } @Test - void verify_should_fail_when_using_incorrect_secondaryLocation() throws IOException { + void verify_should_fail_when_using_incorrect_secondaryLocation() { IssuableSubscriptionVisitor visitor = new FakeVisitor().withDefaultIssues(); - CheckVerifier verifier = CheckVerifier.newVerifier() + CheckVerifier verifier = CheckVerifier.newInternalVerifier() .onFile("src/test/files/JavaCheckVerifierIncorrectSecondaryLocation.java") .withCheck(visitor); @@ -219,9 +269,9 @@ void verify_should_fail_when_using_incorrect_secondaryLocation() throws IOExcept } @Test - void verify_should_fail_when_using_incorrect_secondaryLocation2() throws IOException { + void verify_should_fail_when_using_incorrect_secondaryLocation2() { IssuableSubscriptionVisitor visitor = new FakeVisitor().withDefaultIssues(); - CheckVerifier verifier = CheckVerifier.newVerifier() + CheckVerifier verifier = CheckVerifier.newInternalVerifier() .onFile("src/test/files/JavaCheckVerifierIncorrectSecondaryLocation2.java") .withCheck(visitor); @@ -257,7 +307,7 @@ void verify_flows() { .flow(41, "When", 42, "Given") .add(); - CheckVerifier.newVerifier() + CheckVerifier.newInternalVerifier() .onFile("src/test/files/JavaCheckVerifierFlows.java") .withCheck(fakeVisitor) .verifyIssues(); @@ -276,7 +326,7 @@ void verify_unexpected_flows() { .issueWithFlow(20) .flow(17, "msg", 19, null) .add(); - CheckVerifier verifier = CheckVerifier.newVerifier() + CheckVerifier verifier = CheckVerifier.newInternalVerifier() .onFile("src/test/files/JavaCheckVerifierFlows.java") .withCheck(fakeVisitor); @@ -298,7 +348,7 @@ void verify_missing_flows() { .issueWithFlow(20) .flow(17, "msg", 19, null) .add(); - CheckVerifier verifier = CheckVerifier.newVerifier() + CheckVerifier verifier = CheckVerifier.newInternalVerifier() .onFile("src/test/files/JavaCheckVerifierFlows.java") .withCheck(fakeVisitor); @@ -323,7 +373,7 @@ void verify_flow_messages() { .issueWithFlow(20) .flow(17, "msg", 19, null) .add(); - Throwable throwable = catchThrowable(() -> CheckVerifier.newVerifier().onFile("src/test/files/JavaCheckVerifierFlows.java").withCheck(fakeVisitor).verifyIssues()); + Throwable throwable = catchThrowable(() -> CheckVerifier.newInternalVerifier().onFile("src/test/files/JavaCheckVerifierFlows.java").withCheck(fakeVisitor).verifyIssues()); assertThat(throwable) .isInstanceOf(AssertionError.class) .hasMessage("Wrong messages in flow npe1 [9,3]. Expected: [\"a is assigned to b here\", \"a is assigned to null here\"] but was: [\"invalid 2\", \"invalid 1\"]"); @@ -342,7 +392,7 @@ void verify_flow_locations() { .issueWithFlow(20) .flow(17, "msg", 19, null) .add(); - Throwable throwable = catchThrowable(() -> CheckVerifier.newVerifier().onFile("src/test/files/JavaCheckVerifierFlows.java").withCheck(fakeVisitor).verifyIssues()); + Throwable throwable = catchThrowable(() -> CheckVerifier.newInternalVerifier().onFile("src/test/files/JavaCheckVerifierFlows.java").withCheck(fakeVisitor).verifyIssues()); assertThat(throwable) .isInstanceOf(AssertionError.class) .hasMessage("line 3 attribute mismatch for 'START_COLUMN'. Expected: '12', but was: '6'"); @@ -356,7 +406,7 @@ void verify_superfluous_flows() { .flowItem(3, "a is assigned to null here", 12, 20) .flowItem(9, "a is assigned to b here", 7, 12) .add(); - CheckVerifier verifier = CheckVerifier.newVerifier() + CheckVerifier verifier = CheckVerifier.newInternalVerifier() .onFile("src/test/files/JavaCheckVerifierFlowsSuperfluous.java") .withCheck(fakeVisitor); @@ -377,7 +427,7 @@ void verify_flow_messages_explicit_order() { .flowItem(6, "msg2") .flowItem(4, "msg3") .add(); - CheckVerifier.newVerifier() + CheckVerifier.newInternalVerifier() .onFile("src/test/files/JavaCheckVerifierFlowsExplicitOrder.java") .withCheck(fakeVisitor) .verifyIssues(); @@ -394,7 +444,7 @@ void verify_flow_messages_implicit_order() { .flowItem(6, "msg4") .flowItem(6, "msg5") .add(); - CheckVerifier.newVerifier() + CheckVerifier.newInternalVerifier() .onFile("src/test/files/JavaCheckVerifierFlowsImplicitOrder.java") .withCheck(fakeVisitor) .verifyIssues(); @@ -402,7 +452,8 @@ void verify_flow_messages_implicit_order() { @Test void verify_fail_when_same_explicit_order_is_provided() { - Throwable throwable = catchThrowable(() -> CheckVerifier.newVerifier().onFile("src/test/files/JavaCheckVerifierFlowsDuplicateExplicitOrder.java").withCheck(new FakeVisitor()).verifyIssues()); + Throwable throwable = catchThrowable( + () -> CheckVerifier.newInternalVerifier().onFile("src/test/files/JavaCheckVerifierFlowsDuplicateExplicitOrder.java").withCheck(new FakeVisitor()).verifyIssues()); assertThat(throwable) .isInstanceOf(AssertionError.class) .hasMessageContaining("Same explicit ORDER=1 provided for two comments.") @@ -412,7 +463,8 @@ void verify_fail_when_same_explicit_order_is_provided() { @Test void verify_fail_when_mixing_explicit_and_implicit_order() { - Throwable throwable = catchThrowable(() -> CheckVerifier.newVerifier().onFile("src/test/files/JavaCheckVerifierFlowsMixedExplicitOrder.java").withCheck(new FakeVisitor()).verifyIssues()); + Throwable throwable = catchThrowable( + () -> CheckVerifier.newInternalVerifier().onFile("src/test/files/JavaCheckVerifierFlowsMixedExplicitOrder.java").withCheck(new FakeVisitor()).verifyIssues()); assertThat(throwable) .isInstanceOf(AssertionError.class) .hasMessageContaining("Mixed explicit and implicit order in same flow.") @@ -443,7 +495,7 @@ void verify_two_flows_with_same_lines() { .flowItem(11, "msg2") .flowItem(12, "msg3") .add(); - CheckVerifier.newVerifier() + CheckVerifier.newInternalVerifier() .onFile("src/test/files/JavaCheckVerifierFlowsWithSameLines.java") .withCheck(fakeVisitor) .verifyIssues(); @@ -462,13 +514,14 @@ void verify_two_flows_with_same_lines_wrong_msg() { .flowItem(5, "f2") .flowItem(6, "line6") .add(); - Throwable throwable = catchThrowable(() -> CheckVerifier.newVerifier().onFile("src/test/files/JavaCheckVerifierFlowsWithSameLines2.java").withCheck(fakeVisitor).verifyIssues()); + Throwable throwable = catchThrowable( + () -> CheckVerifier.newInternalVerifier().onFile("src/test/files/JavaCheckVerifierFlowsWithSameLines2.java").withCheck(fakeVisitor).verifyIssues()); assertThat(throwable) .hasMessage("Unexpected flows: [6,5,4]\n" + "[6,5,4]. Missing flows: wrong_msg1 [6,5,4],wrong_msg2 [6,5,4]."); } @Rule(key = "JavaCheckVerifier-Tester") - private static class FakeVisitor extends IssuableSubscriptionVisitor implements IssueWithFlowBuilder { + private static class FakeVisitor extends IssuableSubscriptionVisitor { Map> issues = new LinkedHashMap<>(); Map> preciseIssues = new LinkedHashMap<>(); @@ -477,6 +530,20 @@ private static class FakeVisitor extends IssuableSubscriptionVisitor implements private static final InputFile OTHER_FAKE_INPUT_FILE = TestUtils.emptyInputFile("f"); private AnalyzerMessage issueWithFlow; + private FakeVisitor withDefaultIssuesForJavaCheckVerifier() { + AnalyzerMessage withMultipleLocation = new AnalyzerMessage(this, FAKE_INPUT_FILE, new AnalyzerMessage.TextSpan(19, 24, 19, 30), "message12", 0); + withMultipleLocation.flows.add(Collections.singletonList(new AnalyzerMessage(this, FAKE_INPUT_FILE, new AnalyzerMessage.TextSpan(17, 21, 17, 23), "no message", 0))); + return this.withIssue(1, "message") + .withIssue(3, "message1") + .withIssue(7, "message2") + .withIssue(8, "message3") + .withIssue(8, "message3") + .withPreciseIssue(withMultipleLocation) + .withPreciseIssue(new AnalyzerMessage(this, FAKE_INPUT_FILE, 14, "no message", 0)) + .withPreciseIssue(new AnalyzerMessage(this, FAKE_INPUT_FILE, 15, "message12", 0)) + .withPreciseIssue(new AnalyzerMessage(this, FAKE_INPUT_FILE, new AnalyzerMessage.TextSpan(11, 9, 11, 10), "message4", 0)); + } + private FakeVisitor withDefaultIssues() { AnalyzerMessage withMultipleLocation = new AnalyzerMessage(this, FAKE_INPUT_FILE, new AnalyzerMessage.TextSpan(10, 9, 10, 10), "message4", 3); withMultipleLocation.flows.add(Collections.singletonList(new AnalyzerMessage(this, FAKE_INPUT_FILE, 3, "no message", 0))); @@ -620,8 +687,4 @@ private static void checkState(boolean condition, String errorMessage) { } } - private interface IssueWithFlowBuilder { - - } - } diff --git a/java-checks-testkit/src/test/java/org/sonar/java/checks/verifier/internal/CheckVerifierTestUtils.java b/java-checks-testkit/src/test/java/org/sonar/java/checks/verifier/internal/CheckVerifierTestUtils.java new file mode 100644 index 00000000000..06a2d07dc6f --- /dev/null +++ b/java-checks-testkit/src/test/java/org/sonar/java/checks/verifier/internal/CheckVerifierTestUtils.java @@ -0,0 +1,201 @@ +/* + * SonarQube Java + * Copyright (C) 2012-2024 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.java.checks.verifier.internal; + +import java.util.Collections; +import java.util.List; +import java.util.function.Supplier; +import java.util.stream.Stream; +import org.sonar.check.Rule; +import org.sonar.java.reporting.InternalJavaIssueBuilder; +import org.sonar.java.reporting.JavaQuickFix; +import org.sonar.java.testing.JavaFileScannerContextForTests; +import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; +import org.sonar.plugins.java.api.JavaFileScanner; +import org.sonar.plugins.java.api.JavaFileScannerContext; +import org.sonar.plugins.java.api.ModuleScannerContext; +import org.sonar.plugins.java.api.caching.CacheContext; +import org.sonar.plugins.java.api.internal.EndOfAnalysis; +import org.sonar.plugins.java.api.tree.ClassTree; +import org.sonar.plugins.java.api.tree.Tree; + +public class CheckVerifierTestUtils { + + private CheckVerifierTestUtils() { + // utility class + } + + protected static final String TEST_FILE = "src/test/files/testing/Compliant.java"; + protected static final String TEST_FILE_PARSE_ERROR = "src/test/files/testing/ParsingError.java"; + protected static final String TEST_FILE_NONCOMPLIANT = "src/test/files/testing/Noncompliant.java"; + protected static final String TEST_FILE_NONCOMPLIANT_ISSUE_ON_FILE = "src/test/files/java-check-verifier/CommonsJavaCheckVerifierOnFile.java"; + protected static final String TEST_FILE_WITH_QUICK_FIX = "src/test/files/testing/IssueWithQuickFix.java"; + protected static final String TEST_FILE_WITH_NO_EXPECTED = "src/test/files/testing/IssueWithNoQuickFixExpected.java"; + protected static final String TEST_FILE_WITH_QUICK_FIX_ON_MULTIPLE_LINE = "src/test/files/testing/IssueWithQuickFixMultipleLine.java"; + protected static final String TEST_FILE_WITH_TWO_QUICK_FIX = "src/test/files/testing/IssueWithTwoQuickFixes.java"; + protected static final String TEST_FILE_WITH_PREVIEW_FEATURES = "src/test/files/testing/NeedJava21PreviewFeaturesEnabled.java"; + + protected static final JavaFileScanner FAILING_CHECK = new FailingCheck(); + protected static final JavaFileScanner NO_EFFECT_CHECK = new NoEffectCheck(); + protected static final JavaFileScanner FILE_LINE_ISSUE_CHECK = new FileLineIssueCheck(); + protected static final JavaFileScanner PROJECT_ISSUE_CHECK = new ProjectIssueCheck(); + protected static final JavaFileScanner FILE_ISSUE_CHECK = new FileIssueCheck(); + protected static final JavaFileScanner FILE_ISSUE_CHECK_IN_ANDROID = new FileIssueCheckInAndroidContext(); + + @Rule(key = "FailingCheck") + protected static final class FailingCheck implements JavaFileScanner { + @Override + public void scanFile(JavaFileScannerContext context) { + throw new RuntimeException("This checks fails systematically with a RuntimeException"); + } + } + + @Rule(key = "NoEffectCheck") + protected final static class NoEffectCheck implements JavaFileScanner { + + @Override + public void scanFile(JavaFileScannerContext context) { + // do nothing + } + } + + @Rule(key = "NoEffectEndOfAnalysisCheck") + protected static class NoEffectEndOfAnalysisCheck implements JavaFileScanner, EndOfAnalysis { + @Override + public void endOfAnalysis(ModuleScannerContext context) { + // do nothing + } + + @Override + public void scanFile(JavaFileScannerContext context) { + // do nothing + } + } + + @Rule(key = "FileIssueCheck") + protected static final class FileIssueCheck implements JavaFileScanner { + + @Override + public void scanFile(JavaFileScannerContext context) { + context.addIssueOnFile(this, "issueOnFile"); + } + } + + @Rule(key = "FileLineIssueCheck") + protected static final class FileLineIssueCheck implements JavaFileScanner { + + @Override + public void scanFile(JavaFileScannerContext context) { + context.addIssue(1, this, "issueOnLine"); + } + } + + @Rule(key = "ProjectIssueCheck") + protected static final class ProjectIssueCheck implements JavaFileScanner { + + @Override + public void scanFile(JavaFileScannerContext context) { + context.addIssueOnProject(this, "issueOnProject"); + } + } + + @Rule(key = "MultipleIssuePerLineCheck") + protected static final class MultipleIssuePerLineCheck implements JavaFileScanner { + + private final String msg1; + private final String msg2; + private boolean flipOrder; + + MultipleIssuePerLineCheck() { + this("msg 1", "msg 2"); + } + + MultipleIssuePerLineCheck(String msg1, String msg2) { + this.msg1 = msg1; + this.msg2 = msg2; + this.flipOrder = false; + } + + @Override + public void scanFile(JavaFileScannerContext context) { + String[] msgs = {msg1, msg2}; + report(context, 4, msgs); + + if (flipOrder) { + msgs = new String[] {msg2, msg1}; + } + report(context, 7, msgs); + } + + private void report(JavaFileScannerContext context, int line, String... messages) { + Stream.of(messages).forEach(msg -> context.addIssue(line, this, msg)); + } + + public void setFlipOrder(boolean flipOrder) { + this.flipOrder = flipOrder; + } + } + + @Rule(key = "IssueWithQuickFix") + protected static final class IssueWithQuickFix extends IssuableSubscriptionVisitor { + Supplier> quickFixes; + + IssueWithQuickFix(Supplier> quickFixes) { + this.quickFixes = quickFixes; + } + + static IssueWithQuickFix of(Supplier quickFixes) { + return new IssueWithQuickFix(() -> Collections.singletonList(quickFixes.get())); + } + + @Override + public List nodesToVisit() { + return Collections.singletonList(Tree.Kind.CLASS); + } + + @Override + public void visitNode(Tree tree) { + ClassTree classTree = (ClassTree) tree; + ((InternalJavaIssueBuilder) ((JavaFileScannerContextForTests) context).newIssue()) + .forRule(this) + .onTree(classTree.declarationKeyword()) + .withMessage("message") + .withQuickFixes(quickFixes) + .report(); + } + } + + @Rule(key = "FileIssueAndroidCheck") + protected static final class FileIssueCheckInAndroidContext implements JavaFileScanner { + @Override + public void scanFile(JavaFileScannerContext context) { + if (context.inAndroidContext()) { + context.addIssueOnFile(this, "issueOnFile"); + } + } + } + + protected static boolean equivalent(CacheContext a, CacheContext b) { + return a.isCacheEnabled() == b.isCacheEnabled() && + a.getReadCache().equals(b.getReadCache()) && + a.getWriteCache().equals(b.getWriteCache()); + } + +} diff --git a/java-checks-testkit/src/test/java/org/sonar/java/checks/verifier/internal/InternalCheckVerifierTest.java b/java-checks-testkit/src/test/java/org/sonar/java/checks/verifier/internal/InternalCheckVerifierTest.java index 31ae1d5e851..a9ecd35d962 100644 --- a/java-checks-testkit/src/test/java/org/sonar/java/checks/verifier/internal/InternalCheckVerifierTest.java +++ b/java-checks-testkit/src/test/java/org/sonar/java/checks/verifier/internal/InternalCheckVerifierTest.java @@ -27,7 +27,6 @@ import java.util.Collections; import java.util.List; import java.util.function.Supplier; -import java.util.stream.Stream; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.sonar.api.batch.fs.InputFile; @@ -42,20 +41,13 @@ import org.sonar.java.checks.verifier.CheckVerifier; import org.sonar.java.model.JavaVersionImpl; import org.sonar.java.reporting.AnalyzerMessage; -import org.sonar.java.reporting.InternalJavaIssueBuilder; import org.sonar.java.reporting.JavaQuickFix; import org.sonar.java.reporting.JavaTextEdit; -import org.sonar.java.testing.JavaFileScannerContextForTests; -import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; import org.sonar.plugins.java.api.JavaFileScanner; import org.sonar.plugins.java.api.JavaFileScannerContext; -import org.sonar.plugins.java.api.ModuleScannerContext; import org.sonar.plugins.java.api.caching.CacheContext; import org.sonar.plugins.java.api.caching.JavaReadCache; import org.sonar.plugins.java.api.caching.JavaWriteCache; -import org.sonar.plugins.java.api.internal.EndOfAnalysis; -import org.sonar.plugins.java.api.tree.ClassTree; -import org.sonar.plugins.java.api.tree.Tree; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -64,24 +56,25 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.FAILING_CHECK; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.FILE_ISSUE_CHECK; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.FILE_ISSUE_CHECK_IN_ANDROID; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.FILE_LINE_ISSUE_CHECK; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.IssueWithQuickFix; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.MultipleIssuePerLineCheck; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.NO_EFFECT_CHECK; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.NoEffectEndOfAnalysisCheck; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.PROJECT_ISSUE_CHECK; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.TEST_FILE; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.TEST_FILE_NONCOMPLIANT; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.TEST_FILE_PARSE_ERROR; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.TEST_FILE_WITH_NO_EXPECTED; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.TEST_FILE_WITH_QUICK_FIX; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.TEST_FILE_WITH_QUICK_FIX_ON_MULTIPLE_LINE; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.TEST_FILE_WITH_TWO_QUICK_FIX; class InternalCheckVerifierTest { - private static final String TEST_FILE = "src/test/files/testing/Compliant.java"; - private static final String TEST_FILE_PARSE_ERROR = "src/test/files/testing/ParsingError.java"; - private static final String TEST_FILE_NONCOMPLIANT = "src/test/files/testing/Noncompliant.java"; - private static final String TEST_FILE_WITH_QUICK_FIX = "src/test/files/testing/IssueWithQuickFix.java"; - private static final String TEST_FILE_WITH_QUICK_FIX_ON_MULTIPLE_LINE = "src/test/files/testing/IssueWithQuickFixMultipleLine.java"; - private static final String TEST_FILE_WITH_TWO_QUICK_FIX = "src/test/files/testing/IssueWithTwoQuickFixes.java"; - private static final String TEST_FILE_WITH_NO_EXPECTED = "src/test/files/testing/IssueWithNoQuickFixExpected.java"; - private static final String TEST_FILE_WITH_PREVIEW_FEATURES = "src/test/files/testing/NeedJava21PreviewFeaturesEnabled.java"; - private static final JavaFileScanner FAILING_CHECK = new FailingCheck(); - private static final JavaFileScanner NO_EFFECT_CHECK = new NoEffectCheck(); - private static final JavaFileScanner FILE_LINE_ISSUE_CHECK = new FileLineIssueCheck(); - private static final JavaFileScanner PROJECT_ISSUE_CHECK = new ProjectIssueCheck(); - private static final JavaFileScanner FILE_ISSUE_CHECK = new FileIssueCheck(); - private static final JavaFileScanner FILE_ISSUE_CHECK_IN_ANDROID = new FileIssueCheckInAndroidContext(); - @Nested class TestingCheckVerifierInitialConfiguration { @@ -680,7 +673,7 @@ void order_of_expected_issue_on_same_line_is_relevant() { @Test void wrong_order_of_expected_issue_on_same_line_should_fail() { MultipleIssuePerLineCheck check = new MultipleIssuePerLineCheck(); - check.flipOrder = true; + check.setFlipOrder(true); Throwable e = catchThrowable(() -> InternalCheckVerifier.newInstance() .onFile("src/test/files/testing/MultipleIssuesSameLine.java") @@ -1019,8 +1012,8 @@ void withCache_effectively_sets_the_caches_for_scanWithoutParsing() throws IOExc .withCheck(check) .verifyNoIssues(); - verify(check, times(1)).scanWithoutParsing(argThat(context -> equivalent(cacheContext, context.getCacheContext()))); - verify(check, times(1)).endOfAnalysis(argThat(context -> equivalent(cacheContext, context.getCacheContext()))); + verify(check, times(1)).scanWithoutParsing(argThat(context -> CheckVerifierTestUtils.equivalent(cacheContext, context.getCacheContext()))); + verify(check, times(1)).endOfAnalysis(argThat(context -> CheckVerifierTestUtils.equivalent(cacheContext, context.getCacheContext()))); } @Test @@ -1046,138 +1039,4 @@ void withCache_can_handle_a_mix_of_caches_combination() { assertThat(dummyReadInternalWrite.cacheContext.getWriteCache()).isInstanceOf(JavaWriteCache.class); } - boolean equivalent(CacheContext a, CacheContext b) { - return a.isCacheEnabled() == b.isCacheEnabled() && - a.getReadCache().equals(b.getReadCache()) && - a.getWriteCache().equals(b.getWriteCache()); - } - - @Rule(key = "FailingCheck") - private static final class FailingCheck implements JavaFileScanner { - @Override - public void scanFile(JavaFileScannerContext context) { - throw new RuntimeException("This checks fails systemmatically with a RuntimeException"); - } - } - - @Rule(key = "NoEffectCheck") - private final static class NoEffectCheck implements JavaFileScanner { - - @Override - public void scanFile(JavaFileScannerContext context) { - // do nothing - } - } - - @Rule(key="NoEffectEndOfAnalysisCheck") - private static class NoEffectEndOfAnalysisCheck implements JavaFileScanner, EndOfAnalysis { - @Override - public void endOfAnalysis(ModuleScannerContext context) { - // do nothing - } - - @Override - public void scanFile(JavaFileScannerContext context) { - // do nothing - } - } - - @Rule(key = "FileIssueCheck") - private static final class FileIssueCheck implements JavaFileScanner { - - @Override - public void scanFile(JavaFileScannerContext context) { - context.addIssueOnFile(this, "issueOnFile"); - } - } - - @Rule(key = "FileLineIssueCheck") - private static final class FileLineIssueCheck implements JavaFileScanner { - - @Override - public void scanFile(JavaFileScannerContext context) { - context.addIssue(1, this, "issueOnLine"); - } - } - - @Rule(key = "ProjectIssueCheck") - private static final class ProjectIssueCheck implements JavaFileScanner { - - @Override - public void scanFile(JavaFileScannerContext context) { - context.addIssueOnProject(this, "issueOnProject"); - } - } - - @Rule(key = "MultipleIssuePerLineCheck") - private static final class MultipleIssuePerLineCheck implements JavaFileScanner { - - private final String msg1; - private final String msg2; - private boolean flipOrder = false; - - MultipleIssuePerLineCheck() { - this("msg 1", "msg 2"); - } - - MultipleIssuePerLineCheck(String msg1, String msg2) { - this.msg1 = msg1; - this.msg2 = msg2; - } - - @Override - public void scanFile(JavaFileScannerContext context) { - String[] msgs = {msg1, msg2}; - report(context, 4, msgs); - - if (flipOrder) { - msgs = new String[]{msg2, msg1}; - } - report(context, 7, msgs); - } - - private void report(JavaFileScannerContext context, int line, String... messages) { - Stream.of(messages).forEach(msg -> context.addIssue(line, this, msg)); - } - } - - @Rule(key = "IssueWithQuickFix") - private static final class IssueWithQuickFix extends IssuableSubscriptionVisitor { - Supplier> quickFixes; - - IssueWithQuickFix(Supplier> quickFixes) { - this.quickFixes = quickFixes; - } - - static IssueWithQuickFix of(Supplier quickFixes) { - return new IssueWithQuickFix(() -> Collections.singletonList(quickFixes.get())); - } - - @Override - public List nodesToVisit() { - return Collections.singletonList(Tree.Kind.CLASS); - } - - @Override - public void visitNode(Tree tree) { - ClassTree classTree = (ClassTree) tree; - ((InternalJavaIssueBuilder) ((JavaFileScannerContextForTests) context).newIssue()) - .forRule(this) - .onTree(classTree.declarationKeyword()) - .withMessage("message") - .withQuickFixes(quickFixes) - .report(); - } - } - - @Rule(key = "FileIssueAndroidCheck") - private static final class FileIssueCheckInAndroidContext implements JavaFileScanner { - @Override - public void scanFile(JavaFileScannerContext context) { - if (context.inAndroidContext()) { - context.addIssueOnFile(this, "issueOnFile"); - } - } - } - } diff --git a/java-checks-testkit/src/test/java/org/sonar/java/checks/verifier/internal/JavaCheckVerifierTest.java b/java-checks-testkit/src/test/java/org/sonar/java/checks/verifier/internal/JavaCheckVerifierTest.java new file mode 100644 index 00000000000..b5182a9ec3d --- /dev/null +++ b/java-checks-testkit/src/test/java/org/sonar/java/checks/verifier/internal/JavaCheckVerifierTest.java @@ -0,0 +1,292 @@ +/* + * SonarQube Java + * Copyright (C) 2012-2024 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.java.checks.verifier.internal; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.security.NoSuchAlgorithmException; +import java.util.function.Supplier; +import org.junit.jupiter.api.Test; +import org.sonar.api.batch.fs.InputFile; +import org.sonar.api.batch.sensor.cache.ReadCache; +import org.sonar.api.batch.sensor.cache.WriteCache; +import org.sonar.java.AnalysisException; +import org.sonar.java.caching.DummyCache; +import org.sonar.java.caching.FileHashingUtils; +import org.sonar.java.caching.JavaReadCacheImpl; +import org.sonar.java.caching.JavaWriteCacheImpl; +import org.sonar.java.checks.verifier.CheckVerifier; +import org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.IssueWithQuickFix; +import org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.NoEffectEndOfAnalysisCheck; +import org.sonar.java.model.JavaVersionImpl; +import org.sonar.java.reporting.AnalyzerMessage; +import org.sonar.java.reporting.JavaQuickFix; +import org.sonar.java.reporting.JavaTextEdit; +import org.sonar.plugins.java.api.caching.CacheContext; +import org.sonar.plugins.java.api.caching.JavaReadCache; +import org.sonar.plugins.java.api.caching.JavaWriteCache; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.FAILING_CHECK; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.FILE_ISSUE_CHECK; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.FILE_ISSUE_CHECK_IN_ANDROID; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.FILE_LINE_ISSUE_CHECK; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.NO_EFFECT_CHECK; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.PROJECT_ISSUE_CHECK; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.TEST_FILE; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.TEST_FILE_NONCOMPLIANT; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.TEST_FILE_NONCOMPLIANT_ISSUE_ON_FILE; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.TEST_FILE_PARSE_ERROR; +import static org.sonar.java.checks.verifier.internal.CheckVerifierTestUtils.TEST_FILE_WITH_QUICK_FIX; + +class JavaCheckVerifierTest { + + @Test + void failing_check_should_make_verifier_fail() { + Throwable e = catchThrowable(() -> JavaCheckVerifier.newInstance() + .withCheck(FAILING_CHECK) + .onFile(CheckVerifierTestUtils.TEST_FILE) + .verifyNoIssues()); + + assertThat(e) + .isInstanceOf(AnalysisException.class) + .hasMessage("Failing check"); + } + + @Test + void invalid_file_should_make_verifier_fail() { + Throwable e = catchThrowable(() -> JavaCheckVerifier.newInstance() + .withCheck(NO_EFFECT_CHECK) + .onFile(TEST_FILE_PARSE_ERROR) + .verifyNoIssues()); + + assertThat(e) + .isInstanceOf(AssertionError.class) + .hasMessage("Should not fail analysis (Parse error at line 1 column 8: Syntax error, insert \"}\" to complete ClassBody)"); + } + + @Test + void setting_check_is_required() { + Throwable e = catchThrowable(() -> JavaCheckVerifier.newInstance() + .withJavaVersion(21) + .onFile(TEST_FILE) + .verifyNoIssues()); + + assertThat(e) + .isInstanceOf(AssertionError.class) + .hasMessage("Set check(s) before calling any verification method!"); + } + + @Test + void setting_checks_is_required() { + Throwable e = catchThrowable(() -> JavaCheckVerifier.newInstance() + .withJavaVersion(21) + .withChecks() + .onFile(TEST_FILE) + .verifyNoIssues()); + + assertThat(e) + .isInstanceOf(AssertionError.class) + .hasMessage("Provide at least one check!"); + } + + @Test + void setting_no_issues_without_semantic_should_fail_if_issue_is_raised() { + Throwable e = catchThrowable(() -> JavaCheckVerifier.newInstance() + .withJavaVersion(11) + .onFile(TEST_FILE) + .withCheck(FILE_LINE_ISSUE_CHECK) + .withoutSemantic() + .verifyNoIssues()); + + assertThat(e) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("ERROR: No issues were expected, but some were found. expected:<0> but was:<1>"); + } + + @Test + void preview_features_can_only_be_enabled_for_the_latest_java_version() { + int desiredJavaVersion = JavaVersionImpl.MAX_SUPPORTED - 1; + final CheckVerifier verifier = JavaCheckVerifier.newInstance(); + assertThatThrownBy(() -> verifier.withJavaVersion(desiredJavaVersion, true)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage( + String.format("Preview features can only be enabled when the version == latest supported Java version (%d != %d)", desiredJavaVersion, JavaVersionImpl.MAX_SUPPORTED)); + } + + @Test + void verify_on_project_is_not_implemented() { + Throwable e = catchThrowable(() -> JavaCheckVerifier.newInstance() + .onFile(TEST_FILE) + .withCheck(PROJECT_ISSUE_CHECK) + .verifyIssueOnProject("issueOnProject")); + + assertThat(e) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessage("Not implemented!"); + } + + @Test + void no_issue_if_not_in_android_context() { + JavaCheckVerifier.newInstance() + .onFile(TEST_FILE) + .withChecks(FILE_ISSUE_CHECK_IN_ANDROID) + .withinAndroidContext(false) + .verifyNoIssues(); + } + + @Test + void issue_if_in_android_context() { + Throwable e = catchThrowable(() -> JavaCheckVerifier.newInstance() + .onFile(TEST_FILE) + .withChecks(FILE_ISSUE_CHECK_IN_ANDROID) + .withinAndroidContext(true) + .verifyNoIssues()); + + assertThat(e) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("ERROR: No issues were expected, but some were found. expected:<0> but was:<1>"); + } + + @Test + void raising_issues_while_expecting_none_should_fail() { + Throwable e = catchThrowable(() -> JavaCheckVerifier.newInstance() + .onFile(TEST_FILE) + .withChecks( + FILE_ISSUE_CHECK, + PROJECT_ISSUE_CHECK, + FILE_LINE_ISSUE_CHECK, + FILE_LINE_ISSUE_CHECK) + .verifyNoIssues()); + + assertThat(e) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("ERROR: No issues were expected, but some were found. expected:<0> but was:<3>"); + } + + @Test + void verify_on_file_should_work() { + JavaCheckVerifier.newInstance() + .onFile(TEST_FILE_NONCOMPLIANT_ISSUE_ON_FILE) + .withCheck(FILE_ISSUE_CHECK) + .verifyIssueOnFile("issueOnFile"); + } + + @Test + void raising_no_issue_while_expecting_some_should_fail() { + Throwable e = catchThrowable(() -> JavaCheckVerifier.newInstance() + .onFile(TEST_FILE) + .withChecks(NO_EFFECT_CHECK) + .verifyIssues()); + + assertThat(e) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("ERROR: 'assertOneOrMoreIssues()' is called but there's no 'Noncompliant' comments."); + } + + @Test + void test_one_quick_fix() { + Supplier quickFix = () -> JavaQuickFix.newQuickFix("Description") + .addTextEdit(JavaTextEdit.replaceTextSpan( + new AnalyzerMessage.TextSpan(1, 6, 1, 7), "Replacement")) + .build(); + JavaCheckVerifier.newInstance() + .onFile(TEST_FILE_WITH_QUICK_FIX) + .withCheck(IssueWithQuickFix.of(quickFix)) + .verifyIssues(); + } + + @Test + void addFiles_registers_file_to_be_analyzed() { + JavaCheckVerifier.newInstance() + .addFiles(InputFile.Status.ADDED, TEST_FILE) + .withCheck(NO_EFFECT_CHECK) + .verifyNoIssues(); + + JavaCheckVerifier.newInstance() + .addFiles(InputFile.Status.ADDED, TEST_FILE) + .addFiles(InputFile.Status.ADDED, TEST_FILE_NONCOMPLIANT) + .withCheck(NO_EFFECT_CHECK) + .verifyNoIssues(); + } + + @Test + void addFiles_throws_an_IllegalArgumentException_if_file_added_before() { + JavaCheckVerifier checkVerifier = JavaCheckVerifier.newInstance(); + checkVerifier.onFiles(TEST_FILE); + assertThatThrownBy(() -> { + checkVerifier.addFiles(InputFile.Status.ADDED, TEST_FILE); + }).isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(String.format("File %s was already added.", Path.of(TEST_FILE))); + } + + @Test + void withCache_effectively_sets_the_caches_for_scanWithoutParsing() throws IOException, NoSuchAlgorithmException { + InputFile inputFile = InternalInputFile.inputFile("", new File(TEST_FILE), InputFile.Status.SAME); + ReadCache readCache = new InternalReadCache().put("java:contentHash:MD5::" + TEST_FILE, FileHashingUtils.inputFileContentHash(inputFile)); + WriteCache writeCache = new InternalWriteCache().bind(readCache); + CacheContext cacheContext = new InternalCacheContext( + true, + new JavaReadCacheImpl(readCache), + new JavaWriteCacheImpl(writeCache)); + + var check = spy(new NoEffectEndOfAnalysisCheck()); + + JavaCheckVerifier.newInstance() + .withCache(readCache, writeCache) + .onFile(TEST_FILE) + .withCheck(check) + .verifyNoIssues(); + + verify(check, times(1)).scanWithoutParsing(argThat(context -> CheckVerifierTestUtils.equivalent(cacheContext, context.getCacheContext()))); + verify(check, times(1)).endOfAnalysis(argThat(context -> CheckVerifierTestUtils.equivalent(cacheContext, context.getCacheContext()))); + } + + @Test + void withCache_can_handle_a_mix_of_caches_combination() { + JavaCheckVerifier dummyReadDummyWrite = JavaCheckVerifier.newInstance(); + dummyReadDummyWrite.withCache(null, null); + assertThat(dummyReadDummyWrite.cacheContext.getReadCache()).isInstanceOf(DummyCache.class); + assertThat(dummyReadDummyWrite.cacheContext.getWriteCache()).isInstanceOf(DummyCache.class); + + JavaCheckVerifier internalReadDummyWrite = JavaCheckVerifier.newInstance(); + internalReadDummyWrite.withCache(new InternalReadCache(), null); + assertThat(internalReadDummyWrite.cacheContext.getReadCache()).isInstanceOf(JavaReadCache.class); + assertThat(internalReadDummyWrite.cacheContext.getWriteCache()).isInstanceOf(DummyCache.class); + + JavaCheckVerifier internalReadInternalWrite = JavaCheckVerifier.newInstance(); + internalReadInternalWrite.withCache(new InternalReadCache(), new InternalWriteCache()); + assertThat(internalReadInternalWrite.cacheContext.getReadCache()).isInstanceOf(JavaReadCache.class); + assertThat(internalReadInternalWrite.cacheContext.getWriteCache()).isInstanceOf(JavaWriteCache.class); + + JavaCheckVerifier dummyReadInternalWrite = JavaCheckVerifier.newInstance(); + dummyReadInternalWrite.withCache(null, new InternalWriteCache()); + assertThat(dummyReadInternalWrite.cacheContext.getReadCache()).isInstanceOf(JavaReadCache.class); + assertThat(dummyReadInternalWrite.cacheContext.getWriteCache()).isInstanceOf(JavaWriteCache.class); + } + +} diff --git a/java-checks/src/test/files/checks/AbsOnNegative.java b/java-checks/src/test/files/checks/AbsOnNegative.java index aae555645dc..cd605f029bb 100644 --- a/java-checks/src/test/files/checks/AbsOnNegative.java +++ b/java-checks/src/test/files/checks/AbsOnNegative.java @@ -7,7 +7,8 @@ public void method() { intmethod(0); // Compliant Math.abs(0); // Compliant Math.abs(intmethod(0)); // Compliant - Math.abs(hashCode()); // Noncompliant [[sc=14;ec=24]] {{Use the original value instead.}} + Math.abs(hashCode()); // Noncompliant {{Use the original value instead.}} +// ^^^^^^^^^^ Math.abs(((int) super.hashCode())); // Noncompliant {{Use the original value instead.}} Math.abs(this.hashCode()); // Noncompliant {{Use the original value instead.}} Math.abs(new java.util.Random().nextInt()); // Noncompliant {{Use the original value instead.}} @@ -23,7 +24,8 @@ public void method() { x = -((int) 0); // Compliant x = -intmethod(0); // Compliant x = -this.compareTo(this); // Noncompliant {{Use the original value instead.}} - x = -Integer.MIN_VALUE; // Noncompliant [[sc=10;ec=27]] {{Use the original value instead.}} + x = -Integer.MIN_VALUE; // Noncompliant {{Use the original value instead.}} +// ^^^^^^^^^^^^^^^^^ x = -Long.MIN_VALUE; // Noncompliant {{Use the original value instead.}} x = -TestClass.MIN_VALUE; // Compliant x = -TestClass.SOME_VALUE; // Compliant diff --git a/java-checks/src/test/files/checks/AbstractClassWithoutAbstractMethodCheck.java b/java-checks/src/test/files/checks/AbstractClassWithoutAbstractMethodCheck.java index 3aab6609eb4..6a2c8c10407 100644 --- a/java-checks/src/test/files/checks/AbstractClassWithoutAbstractMethodCheck.java +++ b/java-checks/src/test/files/checks/AbstractClassWithoutAbstractMethodCheck.java @@ -5,7 +5,8 @@ public abstract class Animal { // Noncompliant {{Convert this "Animal" class to } -public abstract class AbstractColor { // Noncompliant {{Convert this "AbstractColor" class to a concrete class with a private constructor}} [[sc=23;ec=36]] +public abstract class AbstractColor { // Noncompliant {{Convert this "AbstractColor" class to a concrete class with a private constructor}} +// ^^^^^^^^^^^^^ private int red = 0; private int green = 0; private int blue = 0; @@ -53,7 +54,8 @@ public void flipSwitch() } } -public abstract class Empty { // Noncompliant {{Convert this "Empty" class to an interface}} [[sc=23;ec=28]] +public abstract class Empty { // Noncompliant {{Convert this "Empty" class to an interface}} +// ^^^^^ } abstract class A { // Noncompliant {{Convert this "A" class to an interface}} diff --git a/java-checks/src/test/files/checks/Architecture.java b/java-checks/src/test/files/checks/Architecture.java index 9025dc4e848..11a714775dd 100644 --- a/java-checks/src/test/files/checks/Architecture.java +++ b/java-checks/src/test/files/checks/Architecture.java @@ -5,7 +5,8 @@ public class ArchitectureConstraint { int a = 1; - Pattern pattern = Pattern.compile("*.java"); // Noncompliant [[sc=3;ec=10]] {{org.sonar.java.checks.targets.ArchitectureConstraint must not use java.util.regex.Pattern}} + Pattern pattern = Pattern.compile("*.java"); // Noncompliant {{org.sonar.java.checks.targets.ArchitectureConstraint must not use java.util.regex.Pattern}} +//^^^^^^^ public ArchitectureConstraint() { Pattern.compile("*.java"); Pattern.compile("*"); diff --git a/java-checks/src/test/files/checks/ArchitectureSelf.java b/java-checks/src/test/files/checks/ArchitectureSelf.java index d84d1a137a2..e56db8582c4 100644 --- a/java-checks/src/test/files/checks/ArchitectureSelf.java +++ b/java-checks/src/test/files/checks/ArchitectureSelf.java @@ -11,4 +11,4 @@ public ArchitectureSelf() { } public static void method() {} -} \ No newline at end of file +} diff --git a/java-checks/src/test/files/checks/AssertionFailInCatchBlockCheck.java b/java-checks/src/test/files/checks/AssertionFailInCatchBlockCheck.java index 8ec968d2928..e39d020cb1d 100644 --- a/java-checks/src/test/files/checks/AssertionFailInCatchBlockCheck.java +++ b/java-checks/src/test/files/checks/AssertionFailInCatchBlockCheck.java @@ -8,7 +8,8 @@ public class MyTest { try { File.createTempFile(null, null); } catch (IOException e) { - Assert.fail(e.getMessage()); // Noncompliant [[sc=7;ec=34]] {{Remove this failure assertion and simply add the exception type to the method signature.}} + Assert.fail(e.getMessage()); // Noncompliant {{Remove this failure assertion and simply add the exception type to the method signature.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ } Assert.fail(); // Compliant, not in catch } @@ -20,32 +21,37 @@ public void testMethodKoWithMessage() { // Some code } catch (Exception e) { if (true) { - Assert.fail(e.getMessage()); // Noncompliant [[sc=9;ec=36]] {{Remove this failure assertion and simply add the exception type to the method signature.}} + Assert.fail(e.getMessage()); // Noncompliant {{Remove this failure assertion and simply add the exception type to the method signature.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ } } try { // Some code } catch (Exception e) { - org.junit.Assert.fail(e.getMessage()); // Noncompliant [[sc=7;ec=44]] {{Remove this failure assertion and simply add the exception type to the method signature.}} + org.junit.Assert.fail(e.getMessage()); // Noncompliant {{Remove this failure assertion and simply add the exception type to the method signature.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } try { // Some code } catch (Exception e) { - org.junit.jupiter.api.Assertions.fail(e.getMessage()); // Noncompliant [[sc=7;ec=60]] {{Remove this failure assertion and simply add the exception type to the method signature.}} + org.junit.jupiter.api.Assertions.fail(e.getMessage()); // Noncompliant {{Remove this failure assertion and simply add the exception type to the method signature.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } try { // Some code } catch (Exception e) { - junit.framework.Assert.fail(e.getMessage()); // Noncompliant [[sc=7;ec=50]] {{Remove this failure assertion and simply add the exception type to the method signature.}} + junit.framework.Assert.fail(e.getMessage()); // Noncompliant {{Remove this failure assertion and simply add the exception type to the method signature.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } try { // Some code } catch (Exception e) { - org.fest.assertions.Fail.fail(); // Noncompliant [[sc=7;ec=38]] {{Remove this failure assertion and simply add the exception type to the method signature.}} + org.fest.assertions.Fail.fail(); // Noncompliant {{Remove this failure assertion and simply add the exception type to the method signature.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } try { @@ -67,19 +73,22 @@ public void testMethodKoWithNoMessage() { try { // Some code } catch (Exception e) { - Assert.fail(); // Noncompliant [[sc=7;ec=20]] {{Remove this failure assertion and simply add the exception type to the method signature.}} + Assert.fail(); // Noncompliant {{Remove this failure assertion and simply add the exception type to the method signature.}} +// ^^^^^^^^^^^^^ } try { // Some code } catch (Exception e) { - org.junit.Assert.fail(); // Noncompliant [[sc=7;ec=30]] {{Remove this failure assertion and simply add the exception type to the method signature.}} + org.junit.Assert.fail(); // Noncompliant {{Remove this failure assertion and simply add the exception type to the method signature.}} +// ^^^^^^^^^^^^^^^^^^^^^^^ } try { // Some code } catch (Exception e) { - junit.framework.Assert.fail(); // Noncompliant [[sc=7;ec=36]] {{Remove this failure assertion and simply add the exception type to the method signature.}} + junit.framework.Assert.fail(); // Noncompliant {{Remove this failure assertion and simply add the exception type to the method signature.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } } diff --git a/java-checks/src/test/files/checks/BooleanInversionCheck.java b/java-checks/src/test/files/checks/BooleanInversionCheck.java index eab66a25f8d..173b115ffc1 100644 --- a/java-checks/src/test/files/checks/BooleanInversionCheck.java +++ b/java-checks/src/test/files/checks/BooleanInversionCheck.java @@ -4,12 +4,14 @@ class A { int i = 0; private void noncompliant() { - if ( !(a == 2)) { } // Noncompliant {{Use the opposite operator ("!=") instead.}} [[sc=10;ec=19]] - boolean b = !(i < 10); // Noncompliant {{Use the opposite operator (">=") instead.}} - b = !(i > 10); // Noncompliant {{Use the opposite operator ("<=") instead.}} - b = !(i != 10); // Noncompliant {{Use the opposite operator ("==") instead.}} [[sc=9;ec=19]] - b = !(i <= 10); // Noncompliant {{Use the opposite operator (">") instead.}} - b = !(i >= 10); // Noncompliant {{Use the opposite operator ("<") instead.}} + if ( !(a == 2)) { } // Noncompliant {{Use the opposite operator ("!=") instead.}} +// ^^^^^^^^^ + boolean b = !(i < 10); // Noncompliant {{Use the opposite operator (">=") instead.}} + b = !(i > 10); // Noncompliant {{Use the opposite operator ("<=") instead.}} + b = !(i != 10); // Noncompliant {{Use the opposite operator ("==") instead.}} +// ^^^^^^^^^^ + b = !(i <= 10); // Noncompliant {{Use the opposite operator (">") instead.}} + b = !(i >= 10); // Noncompliant {{Use the opposite operator ("<") instead.}} } private void compliant() { diff --git a/java-checks/src/test/files/checks/CatchExceptionCheck.java b/java-checks/src/test/files/checks/CatchExceptionCheck.java index e3bc6ce137a..17016634b15 100644 --- a/java-checks/src/test/files/checks/CatchExceptionCheck.java +++ b/java-checks/src/test/files/checks/CatchExceptionCheck.java @@ -9,7 +9,8 @@ void m1() { m3(); } catch (MyException e) { } catch (MyException1 | MyException2 e) { - } catch (Exception e) { // Noncompliant [[sc=14;ec=23]] {{Catch a list of specific exception subtypes instead.}} + } catch (Exception e) { // Noncompliant {{Catch a list of specific exception subtypes instead.}} +// ^^^^^^^^^ } try { } catch (MyException1 | Exception e) { // Noncompliant diff --git a/java-checks/src/test/files/checks/CatchNPECheck.java b/java-checks/src/test/files/checks/CatchNPECheck.java index 1263da05847..d951abe867f 100644 --- a/java-checks/src/test/files/checks/CatchNPECheck.java +++ b/java-checks/src/test/files/checks/CatchNPECheck.java @@ -3,12 +3,14 @@ class A { private void method(){ try { a.equals(null); - } catch(NullPointerException npe) { // Noncompliant [[sc=13;ec=33]] {{Avoid catching NullPointerException.}} + } catch(NullPointerException npe) { // Noncompliant {{Avoid catching NullPointerException.}} +// ^^^^^^^^^^^^^^^^^^^^ log.info("argument was null"); } try { a.equals(null); - } catch(java.lang.NullPointerException npe) { // Noncompliant [[sc=23;ec=43]] {{Avoid catching NullPointerException.}} + } catch(java.lang.NullPointerException npe) { // Noncompliant {{Avoid catching NullPointerException.}} +// ^^^^^^^^^^^^^^^^^^^^ log.info("argument was null"); } try { diff --git a/java-checks/src/test/files/checks/CatchRethrowingCheck.java b/java-checks/src/test/files/checks/CatchRethrowingCheck.java index e8127d1d544..c63625dbbf2 100644 --- a/java-checks/src/test/files/checks/CatchRethrowingCheck.java +++ b/java-checks/src/test/files/checks/CatchRethrowingCheck.java @@ -2,7 +2,8 @@ class A { void foo() { try { } catch (IOException ioe) { - throw ioe; // Noncompliant [[sc=7;ec=17]] {{Add logic to this catch clause or eliminate it and rethrow the exception automatically.}} + throw ioe; // Noncompliant {{Add logic to this catch clause or eliminate it and rethrow the exception automatically.}} +// ^^^^^^^^^^ } try { @@ -19,4 +20,4 @@ void foo() { } -} \ No newline at end of file +} diff --git a/java-checks/src/test/files/checks/ChildClassShadowField.java b/java-checks/src/test/files/checks/ChildClassShadowField.java index 3bbb976814a..8c21fe0f611 100644 --- a/java-checks/src/test/files/checks/ChildClassShadowField.java +++ b/java-checks/src/test/files/checks/ChildClassShadowField.java @@ -15,7 +15,8 @@ String baseMethod() { } class Derived11 extends Base { - boolean baseField; // Noncompliant [[sc=11;ec=20]] {{"baseField" is the name of a field in "Base".}} + boolean baseField; // Noncompliant {{"baseField" is the name of a field in "Base".}} +// ^^^^^^^^^ String myStaticField; // Compliant - ignore static fields in parent class diff --git a/java-checks/src/test/files/checks/ClassCouplingCheck.java b/java-checks/src/test/files/checks/ClassCouplingCheck.java index 6a53084f187..59ec03b81db 100644 --- a/java-checks/src/test/files/checks/ClassCouplingCheck.java +++ b/java-checks/src/test/files/checks/ClassCouplingCheck.java @@ -1,4 +1,5 @@ -class Foo { // Noncompliant [[sc=7;ec=10]] {{Split this class into smaller and more specialized ones to reduce its dependencies on other classes from 21 to the maximum authorized 20 or less.}} +class Foo { // Noncompliant {{Split this class into smaller and more specialized ones to reduce its dependencies on other classes from 21 to the maximum authorized 20 or less.}} +// ^^^ T1 a1; // Foo is coupled to T1 T2 a2; // Foo is coupled to T2 T3 a3; // Foo is coupled to T3 @@ -30,7 +31,7 @@ class Bar { // Compliant T2 a2; } -class Baz { // Noncompliant +class Baz { // Noncompliant T1 a1; T2 a2; T3 a3; diff --git a/java-checks/src/test/files/checks/ClassFieldCountCheck/CountOnlyPublicFields.java b/java-checks/src/test/files/checks/ClassFieldCountCheck/CountOnlyPublicFields.java index 8589374e4d4..23561de6785 100644 --- a/java-checks/src/test/files/checks/ClassFieldCountCheck/CountOnlyPublicFields.java +++ b/java-checks/src/test/files/checks/ClassFieldCountCheck/CountOnlyPublicFields.java @@ -1,4 +1,5 @@ -class TooManyFields { // Noncompliant [[sc=7;ec=20]] {{Refactor this class so it has no more than 20 public fields, rather than the 26 it currently has.}} +class TooManyFields { // Noncompliant {{Refactor this class so it has no more than 20 public fields, rather than the 26 it currently has.}} +// ^^^^^^^^^^^^^ int nonPublicField1; int nonPublicField2; int nonPublicField3; diff --git a/java-checks/src/test/files/checks/ClassFieldCountCheck/UnusualTrees.java b/java-checks/src/test/files/checks/ClassFieldCountCheck/UnusualTrees.java index 7b70b7a664e..cbfe6c0732e 100644 --- a/java-checks/src/test/files/checks/ClassFieldCountCheck/UnusualTrees.java +++ b/java-checks/src/test/files/checks/ClassFieldCountCheck/UnusualTrees.java @@ -1,5 +1,7 @@ -enum TooManyFieldsEnum { // Noncompliant [[sc=6;ec=23]] {{Refactor this class so it has no more than 2 fields, rather than the 3 it currently has.}} - ENUM_CONSTANT_TREE { // Noncompliant [[sc=3;ec=21]] {{Refactor this class so it has no more than 2 fields, rather than the 3 it currently has.}} +enum TooManyFieldsEnum { // Noncompliant {{Refactor this class so it has no more than 2 fields, rather than the 3 it currently has.}} +// ^^^^^^^^^^^^^^^^^ + ENUM_CONSTANT_TREE { // Noncompliant {{Refactor this class so it has no more than 2 fields, rather than the 3 it currently has.}} +//^^^^^^^^^^^^^^^^^^ int field1; int field2; int field3; @@ -17,7 +19,8 @@ interface TooManyFieldsInterface { // Compliant - interface fields are effective class TooManyFieldsAnonymous { { - new java.util.ArrayList() { // Noncompliant [[sc=9;ec=37]] {{Refactor this class so it has no more than 2 fields, rather than the 3 it currently has.}} + new java.util.ArrayList() { // Noncompliant {{Refactor this class so it has no more than 2 fields, rather than the 3 it currently has.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ int field1; int field2; int field3; diff --git a/java-checks/src/test/files/checks/ClassVariableVisibilityCheck.java b/java-checks/src/test/files/checks/ClassVariableVisibilityCheck.java index 2ba12f3add6..a4b4f94532e 100644 --- a/java-checks/src/test/files/checks/ClassVariableVisibilityCheck.java +++ b/java-checks/src/test/files/checks/ClassVariableVisibilityCheck.java @@ -4,7 +4,8 @@ class Foo { private int foo1; int foo2; protected int foo3; - public int foo4; // Noncompliant [[sc=14;ec=18]] {{Make foo4 a static final constant or non-public and provide accessors if needed.}} + public int foo4; // Noncompliant {{Make foo4 a static final constant or non-public and provide accessors if needed.}} +// ^^^^ public static int foo5; // Noncompliant {{Make foo5 a static final constant or non-public and provide accessors if needed.}} public final int foo6; // Compliant diff --git a/java-checks/src/test/files/checks/ClassWithOnlyStaticMethodsInstantiationCheck.java b/java-checks/src/test/files/checks/ClassWithOnlyStaticMethodsInstantiationCheck.java index d75d4045224..f5fc5e46a45 100644 --- a/java-checks/src/test/files/checks/ClassWithOnlyStaticMethodsInstantiationCheck.java +++ b/java-checks/src/test/files/checks/ClassWithOnlyStaticMethodsInstantiationCheck.java @@ -2,12 +2,14 @@ class Tester { void bar() { - A a = new A(); // Noncompliant [[sc=15;ec=16]] {{Remove this instantiation of "A".}} + A a = new A(); // Noncompliant {{Remove this instantiation of "A".}} +// ^ D d = new D(); // Noncompliant {{Remove this instantiation of "D".}} E e = new E(); // Noncompliant {{Remove this instantiation of "E".}} F f = new F(); // Noncompliant {{Remove this instantiation of "F".}} InnerClass i1 = new InnerClass(); // Noncompliant {{Remove this instantiation of "InnerClass".}} - Tester.InnerClass i2 = new Tester.InnerClass(); // Noncompliant [[sc=32;ec=49]] {{Remove this instantiation of "InnerClass".}} + Tester.InnerClass i2 = new Tester.InnerClass(); // Noncompliant {{Remove this instantiation of "InnerClass".}} +// ^^^^^^^^^^^^^^^^^ J j = new J(); // Noncompliant {{Remove this instantiation of "J".}} B b = new B(); // Compliant C c = new C(); // Compliant diff --git a/java-checks/src/test/files/checks/CloneMethodCallsSuperCloneCheck.java b/java-checks/src/test/files/checks/CloneMethodCallsSuperCloneCheck.java index 5935d24a220..1fb70366364 100644 --- a/java-checks/src/test/files/checks/CloneMethodCallsSuperCloneCheck.java +++ b/java-checks/src/test/files/checks/CloneMethodCallsSuperCloneCheck.java @@ -1,6 +1,7 @@ class A { @Override - protected A clone() throws CloneNotSupportedException { // Noncompliant [[sc=15;ec=20]] {{Use super.clone() to create and seed the cloned instance to be returned.}} + protected A clone() throws CloneNotSupportedException { // Noncompliant {{Use super.clone() to create and seed the cloned instance to be returned.}} +// ^^^^^ return new A(); } diff --git a/java-checks/src/test/files/checks/CloneOverrideCheck.java b/java-checks/src/test/files/checks/CloneOverrideCheck.java index b77ff938c8a..298be9b99ee 100644 --- a/java-checks/src/test/files/checks/CloneOverrideCheck.java +++ b/java-checks/src/test/files/checks/CloneOverrideCheck.java @@ -1,5 +1,6 @@ class A { - public Object clone(){ // Noncompliant [[sc=17;ec=22]] {{Remove this "clone" implementation; use a copy constructor or copy factory instead.}} + public Object clone(){ // Noncompliant {{Remove this "clone" implementation; use a copy constructor or copy factory instead.}} +// ^^^^^ return super.clone(); } public Object clonerMethod() { // Compliant @@ -15,17 +16,17 @@ protected Object clone() throws CloneNotSupportedException { // Compliant, commo } class C { @Override - protected Object clone() throws CloneNotSupportedException { // Noncompliant, not a one statement method + protected Object clone() throws CloneNotSupportedException { // Noncompliant System.out.println(""); throw new CloneNotSupportedException("Clone not supported for a Singleton"); } } class D { - protected abstract Object clone() throws CloneNotSupportedException; // Noncompliant (theoritical case, cannot happen in real life). + protected abstract Object clone() throws CloneNotSupportedException; // Noncompliant } class E { @Override - protected Object clone() throws CloneNotSupportedException { // Noncompliant, incorrect type of exception + protected Object clone() throws CloneNotSupportedException { // Noncompliant throw new UnsupportedOperationException("Clone not supported for a Singleton"); } } diff --git a/java-checks/src/test/files/checks/CognitiveComplexityMethodCheckMax0.java b/java-checks/src/test/files/checks/CognitiveComplexityMethodCheckMax0.java index fba3215e9da..3843040f385 100644 --- a/java-checks/src/test/files/checks/CognitiveComplexityMethodCheckMax0.java +++ b/java-checks/src/test/files/checks/CognitiveComplexityMethodCheckMax0.java @@ -1,11 +1,14 @@ class CognitiveComplexityCheck { - public int ternaryOp(int a, int b) { // Noncompliant [[sc=14;ec=23;secondary=6,8]] {{Refactor this method to reduce its Cognitive Complexity from 2 to the 0 allowed.}} + public int ternaryOp(int a, int b) { // Noncompliant {{Refactor this method to reduce its Cognitive Complexity from 2 to the 0 allowed.}} +// ^^^^^^^^^ int c = a>b?b:a; +// ^< return c>20?4:7; +// ^< } @@ -24,16 +27,16 @@ public void extraConditions4() { // Noncompliant {{Refactor this method to reduc public void extraConditions5() { // Noncompliant {{Refactor this method to reduce its Cognitive Complexity from 5 to the 0 allowed.}} if (a || b && c || d && e) {} } - public void extraConditions6() {// Noncompliant {{Refactor this method to reduce its Cognitive Complexity from 3 to the 0 allowed.}} + public void extraConditions6() { // Noncompliant {{Refactor this method to reduce its Cognitive Complexity from 3 to the 0 allowed.}} if (a && b && c || d || e) {} } - public void extraConditions7() {// Noncompliant {{Refactor this method to reduce its Cognitive Complexity from 1 to the 0 allowed.}} + public void extraConditions7() { // Noncompliant {{Refactor this method to reduce its Cognitive Complexity from 1 to the 0 allowed.}} if (a) {} } - public void extraConditions8() {// Noncompliant {{Refactor this method to reduce its Cognitive Complexity from 2 to the 0 allowed.}} + public void extraConditions8() { // Noncompliant {{Refactor this method to reduce its Cognitive Complexity from 2 to the 0 allowed.}} if (a && b && c && d && e) {} } - public void extraConditions9() {// Noncompliant {{Refactor this method to reduce its Cognitive Complexity from 2 to the 0 allowed.}} + public void extraConditions9() { // Noncompliant {{Refactor this method to reduce its Cognitive Complexity from 2 to the 0 allowed.}} if (a || b || c || d || e) {} } public void extraCondition10() { // Noncompliant {{Refactor this method to reduce its Cognitive Complexity from 4 to the 0 allowed.}} @@ -41,20 +44,26 @@ public void extraCondition10() { // Noncompliant {{Refactor this method to reduc } - public void switch2(){ // Noncompliant [[sc=15;ec=22;secondary=46,50,51,51,51,55,57]] {{Refactor this method to reduce its Cognitive Complexity from 12 to the 0 allowed.}} + public void switch2(){ // Noncompliant {{Refactor this method to reduce its Cognitive Complexity from 12 to the 0 allowed.}} +// ^^^^^^^ switch(foo){ //+1 +// ^^^^^^< case 1: break; case ASSIGNMENT: if (lhs.is(Tree.Kind.IDENTIFIER)) { //+2 (nesting=1) +// ^^< if (a && b && c || d) { //+5 (nesting=2) +// ^^< ^^< ^^< } if(element.is(Tree.Kind.ASSIGNMENT)) { //+3 (nesting=2) +// ^^< out.remove(symbol); } else { //+1 +// ^^^^< out.add(symbol); } } @@ -66,19 +75,27 @@ public void extraCondition11() { // Noncompliant {{Refactor this method to reduc if (a || (b || c)) {} } - public void extraConditions12() { // Noncompliant [[secondary=70,72,74,76,78,80,81]] {{Refactor this method to reduce its Cognitive Complexity from 7 to the 0 allowed.}} + public void extraConditions12() { // Noncompliant {{Refactor this method to reduce its Cognitive Complexity from 7 to the 0 allowed.}} + //^^^^^^^^^^^^^^^^^ if ( // +1 +// ^^< a && b // +1 - secondary on each first operator of a new sequence +// ^^< && c || d // +1 +// ^^< || e && f // +1 +// ^^< && g || (h // +1 +// ^^< || (i && j // +1 +// ^^< || k)) // +1 - parentheses completely ignored +// ^^< || l || m ){} @@ -184,7 +201,7 @@ private static String getValueToEval( Measure.Level alertLevel, Color foo ) { // } } - boolean isPalindrome(char [] s, int len) { // Noncompliant Refactor this method to reduce its Cognitive Complexity from 3 to the 0 allowed. + boolean isPalindrome(char [] s, int len) { // Noncompliant if(len < 2) return true; diff --git a/java-checks/src/test/files/checks/CollectionCallingItselfCheck.java b/java-checks/src/test/files/checks/CollectionCallingItselfCheck.java index 386d565f673..5a905c0f918 100644 --- a/java-checks/src/test/files/checks/CollectionCallingItselfCheck.java +++ b/java-checks/src/test/files/checks/CollectionCallingItselfCheck.java @@ -8,7 +8,8 @@ void fun() { strings.addAll(strings); // Noncompliant {{Remove or correct this "addAll" call.}} strings.containsAll(strings); // Noncompliant {{Remove or correct this "containsAll" call.}} strings.removeAll(strings); // Noncompliant {{Remove or correct this "removeAll" call.}} - strings.retainAll(strings); // Noncompliant [[sc=5;ec=31]] {{Remove or correct this "retainAll" call.}} + strings.retainAll(strings); // Noncompliant {{Remove or correct this "retainAll" call.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^ strings.wait(); strings.foo(); } diff --git a/java-checks/src/test/files/checks/CollectionInappropriateCallsCheckUnknownTypes.java b/java-checks/src/test/files/checks/CollectionInappropriateCallsCheckUnknownTypes.java index 5ab1cf48b34..d62787cbcb5 100644 --- a/java-checks/src/test/files/checks/CollectionInappropriateCallsCheckUnknownTypes.java +++ b/java-checks/src/test/files/checks/CollectionInappropriateCallsCheckUnknownTypes.java @@ -54,6 +54,6 @@ public String testSplitArray() { class LombokVal { boolean foo(List words) { lombok.val y = "Hello World"; - return words.contains(y); // Noncompliant - FP - handled by lombok filter + return words.contains(y); // Noncompliant } } diff --git a/java-checks/src/test/files/checks/CollectionMethodsWithLinearComplexity.java b/java-checks/src/test/files/checks/CollectionMethodsWithLinearComplexity.java index a04ac5a1537..5a73a10f79d 100644 --- a/java-checks/src/test/files/checks/CollectionMethodsWithLinearComplexity.java +++ b/java-checks/src/test/files/checks/CollectionMethodsWithLinearComplexity.java @@ -6,7 +6,8 @@ class A { final ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue(); void foo() { - log.info("Queue contains " + queue.size() + " elements"); // Noncompliant [[sc=40;ec=44]] {{This call to "size()" may be a performance hot spot if the collection is large.}} + log.info("Queue contains " + queue.size() + " elements"); // Noncompliant {{This call to "size()" may be a performance hot spot if the collection is large.}} +// ^^^^ } } diff --git a/java-checks/src/test/files/checks/CollectionsEmptyConstants.java b/java-checks/src/test/files/checks/CollectionsEmptyConstants.java index 1208a332748..7821aeaa0a7 100644 --- a/java-checks/src/test/files/checks/CollectionsEmptyConstants.java +++ b/java-checks/src/test/files/checks/CollectionsEmptyConstants.java @@ -3,7 +3,8 @@ class A{ - List collection1 = Collections.EMPTY_LIST; // Noncompliant {{Replace "Collections.EMPTY_LIST" by "Collections.emptyList()".}} [[sc=30;ec=52]] + List collection1 = Collections.EMPTY_LIST; // Noncompliant {{Replace "Collections.EMPTY_LIST" by "Collections.emptyList()".}} +// ^^^^^^^^^^^^^^^^^^^^^^ Map collection2 = Collections.EMPTY_MAP; // Noncompliant {{Replace "Collections.EMPTY_MAP" by "Collections.emptyMap()".}} Set collection3 = Collections.EMPTY_SET; // Noncompliant {{Replace "Collections.EMPTY_SET" by "Collections.emptySet()".}} diff --git a/java-checks/src/test/files/checks/CommentRegularExpressionCheck.java b/java-checks/src/test/files/checks/CommentRegularExpressionCheck.java index 1678736f885..b41c23fd812 100644 --- a/java-checks/src/test/files/checks/CommentRegularExpressionCheck.java +++ b/java-checks/src/test/files/checks/CommentRegularExpressionCheck.java @@ -1,14 +1,14 @@ public class A { void foo() { - // Noncompliant@+1 -// Noncompliant@+1 {{Avoid TODO}} + // Noncompliant@+1 + // Noncompliant@+1 {{Avoid TODO}} // todo // hehe -// Noncompliant@+1 + // Noncompliant@+1 // ToDo -// Noncompliant@+1 + // Noncompliant@+1 /* okiey ToDo diff --git a/java-checks/src/test/files/checks/ConstructorCallingOverridableCheck.java b/java-checks/src/test/files/checks/ConstructorCallingOverridableCheck.java index d86cf895c2e..4bebb6b2775 100644 --- a/java-checks/src/test/files/checks/ConstructorCallingOverridableCheck.java +++ b/java-checks/src/test/files/checks/ConstructorCallingOverridableCheck.java @@ -82,7 +82,7 @@ public class C extends D { public class Parent { public Parent () { - doSomething(); // Noncompliant + doSomething(); // Noncompliant } public void doSomething () { // not final; can be overridden diff --git a/java-checks/src/test/files/checks/CustomCryptographicAlgorithmCheck.java b/java-checks/src/test/files/checks/CustomCryptographicAlgorithmCheck.java index f9844008548..aa55729c1ec 100644 --- a/java-checks/src/test/files/checks/CustomCryptographicAlgorithmCheck.java +++ b/java-checks/src/test/files/checks/CustomCryptographicAlgorithmCheck.java @@ -3,13 +3,15 @@ class A { // Compliant void foo() { - MessageDigest md = new MessageDigest() { // Noncompliant [[sc=28;ec=41]] {{Make sure using a non-standard cryptographic algorithm is safe here.}} + MessageDigest md = new MessageDigest() { // Noncompliant {{Make sure using a non-standard cryptographic algorithm is safe here.}} +// ^^^^^^^^^^^^^ }; } } -abstract class B extends MessageDigest { // Noncompliant [[sc=16;ec=17]] {{Make sure using a non-standard cryptographic algorithm is safe here.}} +abstract class B extends MessageDigest { // Noncompliant {{Make sure using a non-standard cryptographic algorithm is safe here.}} +// ^ protected B(String algorithm) { super(algorithm); } @@ -28,4 +30,4 @@ protected D(String algorithm) { } class E extends Observable { // Compliant -} \ No newline at end of file +} diff --git a/java-checks/src/test/files/checks/CustomSerializationMethodCheck.java b/java-checks/src/test/files/checks/CustomSerializationMethodCheck.java index 9d9964e6097..f1322eace9a 100644 --- a/java-checks/src/test/files/checks/CustomSerializationMethodCheck.java +++ b/java-checks/src/test/files/checks/CustomSerializationMethodCheck.java @@ -14,13 +14,15 @@ Object readResolve() throws ObjectStreamException {} } class B implements Serializable { // non private methods - void writeObject(ObjectOutputStream out) throws IOException {} // Noncompliant [[sc=8;ec=19]] {{Make "writeObject" "private".}} + void writeObject(ObjectOutputStream out) throws IOException {} // Noncompliant {{Make "writeObject" "private".}} +// ^^^^^^^^^^^ void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {} // Noncompliant void readObjectNoData() throws ObjectStreamException {} // Noncompliant } class C implements Serializable { // static methods - private static void writeObject(ObjectOutputStream out) throws IOException {} // Noncompliant [[sc=23;ec=34]] {{The "static" modifier should not be applied to "writeObject".}} + private static void writeObject(ObjectOutputStream out) throws IOException {} // Noncompliant {{The "static" modifier should not be applied to "writeObject".}} +// ^^^^^^^^^^^ private static void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {} // Noncompliant private static void readObjectNoData() throws ObjectStreamException {} // Noncompliant static Object writeReplace() throws ObjectStreamException {} // Noncompliant @@ -36,7 +38,8 @@ Object readResolve() {} } class E implements Serializable { // invalid return type - Unknown writeReplace() throws ObjectStreamException {} // Noncompliant [[sc=11;ec=23]] {{"writeReplace" should return "java.lang.Object".}} + Unknown writeReplace() throws ObjectStreamException {} // Noncompliant {{"writeReplace" should return "java.lang.Object".}} +// ^^^^^^^^^^^^ String readResolve() throws ObjectStreamException {} // Noncompliant } diff --git a/java-checks/src/test/files/checks/DateAndTimesCheck.java b/java-checks/src/test/files/checks/DateAndTimesCheck.java index 8a31d01e858..a9198692e08 100644 --- a/java-checks/src/test/files/checks/DateAndTimesCheck.java +++ b/java-checks/src/test/files/checks/DateAndTimesCheck.java @@ -7,7 +7,7 @@ void foo() { Date now = new Date(); // Noncompliant {{Use the Java 8 Date and Time API instead.}} now = new Date(1499159427440L); // Noncompliant DateFormat df = new SimpleDateFormat("dd.MM.yyyy"); - Calendar christmas = Calendar.getInstance(); // Noncompliant + Calendar christmas = Calendar.getInstance(); // Noncompliant christmas = Calendar.getInstance(Locale.CANADA); // Noncompliant christmas.setTime(df.parse("25.12.2020")); } diff --git a/java-checks/src/test/files/checks/DeprecatedTagPresenceCheck.java b/java-checks/src/test/files/checks/DeprecatedTagPresenceCheck.java index 7b7a4bb122d..4662d8a5cbd 100644 --- a/java-checks/src/test/files/checks/DeprecatedTagPresenceCheck.java +++ b/java-checks/src/test/files/checks/DeprecatedTagPresenceCheck.java @@ -1,7 +1,8 @@ class Foo { @Deprecated - public int foo; // Noncompliant [[sc=14;ec=17]] {{Do not forget to remove this deprecated code someday.}} + public int foo; // Noncompliant {{Do not forget to remove this deprecated code someday.}} +// ^^^ public void foo1() { // Compliant } @@ -22,7 +23,8 @@ public void foo3() { // Noncompliant */ @Ignore @Deprecated - public void foo4() { // Noncompliant [[sc=15;ec=19]] + public void foo4() { // Noncompliant +// ^^^^ } @Deprecated diff --git a/java-checks/src/test/files/checks/DisallowedClassCheck.java b/java-checks/src/test/files/checks/DisallowedClassCheck.java index 58093582021..1d817f59036 100644 --- a/java-checks/src/test/files/checks/DisallowedClassCheck.java +++ b/java-checks/src/test/files/checks/DisallowedClassCheck.java @@ -6,34 +6,46 @@ import static java.lang.String.CASE_INSENSITIVE_ORDER; // Noncompliant class A { - private String disallowed; // Noncompliant [[sc=11;ec=17]] + private String disallowed; // Noncompliant +// ^^^^^^ private Integer allowed; private java.util.Date date; - String method1() { // Noncompliant [[sc=3;ec=9]] + String method1() { // Noncompliant +//^^^^^^ } - Unknown method(String param) { // Noncompliant [[sc=18;ec=24]] + Unknown method(String param) { // Noncompliant +// ^^^^^^ B var = new B(); // Compliant, no subtypes checked - String str = new String(); // Noncompliant [[sc=5;ec=11]] - Object obj1 = String.valueOf(3); // Noncompliant [[sc=19;ec=33]] + String str = new String(); // Noncompliant +// ^^^^^^ + Object obj1 = String.valueOf(3); // Noncompliant +// ^^^^^^^^^^^^^^ Object obj2 = valueOf(3); // Compliant, already reported in the static import Object obj3 = unknown(3); - Object obj4 = java.lang.String.CASE_INSENSITIVE_ORDER; // Noncompliant [[sc=19;ec=58]] - Object obj5 = String.CASE_INSENSITIVE_ORDER; // Noncompliant [[sc=19;ec=48]] + Object obj4 = java.lang.String.CASE_INSENSITIVE_ORDER; // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + Object obj5 = String.CASE_INSENSITIVE_ORDER; // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Object obj6 = CASE_INSENSITIVE_ORDER; // Compliant, already reported in the static import - var.doSomethingElse(String.CASE_INSENSITIVE_ORDER); // Noncompliant [[sc=25;ec=54]] - var.doSomethingElse(new String().CASE_INSENSITIVE_ORDER); // Noncompliant [[sc=25;ec=37]] - var.doSomethingElse(String.valueOf(2)); // Noncompliant [[sc=25;ec=39]] + var.doSomethingElse(String.CASE_INSENSITIVE_ORDER); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + var.doSomethingElse(new String().CASE_INSENSITIVE_ORDER); // Noncompliant +// ^^^^^^^^^^^^ + var.doSomethingElse(String.valueOf(2)); // Noncompliant +// ^^^^^^^^^^^^^^ System.out.println(var); var.doSomething(new Integer(1)); return new Unknown(); } void usedWithReflection() throws ClassNotFoundException { - Class c = Class.forName("java.lang.String"); // Noncompliant [[sc=15;ec=48]] + Class c = Class.forName("java.lang.String"); // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } } -class B extends String { // Noncompliant [[sc=17;ec=23]] +class B extends String { // Noncompliant +// ^^^^^^ public B(Integer a) { } public void doSomething(Integer a) { diff --git a/java-checks/src/test/files/checks/DisallowedClassCheckAnnotation.java b/java-checks/src/test/files/checks/DisallowedClassCheckAnnotation.java index 7180c85573c..9fc00d792fa 100644 --- a/java-checks/src/test/files/checks/DisallowedClassCheckAnnotation.java +++ b/java-checks/src/test/files/checks/DisallowedClassCheckAnnotation.java @@ -1,9 +1,11 @@ package org.foo; -@MyAnnotation // Noncompliant [[sc=2;ec=14]] +@MyAnnotation // Noncompliant +//^[sc=2;ec=13] public class A { - @org.foo.MyAnnotation( // Noncompliant [[sc=4;ec=24]] {{Remove the use of this forbidden class.}} + @org.foo.MyAnnotation( // Noncompliant {{Remove the use of this forbidden class.}} +// ^^^^^^^^^^^^^^^^^^^^ field = "53" ) void foo() { diff --git a/java-checks/src/test/files/checks/DisallowedClassCheckRegex.java b/java-checks/src/test/files/checks/DisallowedClassCheckRegex.java index 774b1285f84..7cec9809c36 100644 --- a/java-checks/src/test/files/checks/DisallowedClassCheckRegex.java +++ b/java-checks/src/test/files/checks/DisallowedClassCheckRegex.java @@ -2,25 +2,36 @@ import static java.lang.String.valueOf; // Noncompliant class A { - private String disallowed; // Noncompliant [[sc=11;ec=17]] - private Integer disallowed2; // Noncompliant [[sc=11;ec=18]] + private String disallowed; // Noncompliant +// ^^^^^^ + private Integer disallowed2; // Noncompliant +// ^^^^^^^ private java.util.Date date; - String method1() { // Noncompliant [[sc=3;ec=9]] + String method1() { // Noncompliant +//^^^^^^ } -void method(String param) { // Noncompliant [[sc=13;ec=19]] +void method(String param) { // Noncompliant +// ^^^^^^ B var = new B(); // Compliant, no subtypes checked - String str = new String(); // Noncompliant [[sc=3;ec=9]] - Object obj = // Noncompliant [[sc=3;ec=9]] - String.valueOf(3); // Noncompliant [[sc=5;ec=19]] + String str = new String(); // Noncompliant +//^^^^^^ + Object obj = // Noncompliant +//^^^^^^ + String.valueOf(3); // Noncompliant +// ^^^^^^^^^^^^^^ obj = valueOf(3); // Compliant, already reported in static import //System is part of java.lang - System.out.println(var); // Noncompliant [[sc=3;ec=13]] - var.doSomething(new Integer(1)); // Noncompliant [[sc=19;ec=33]] + System.out.println(var); // Noncompliant +//^^^^^^^^^^ + var.doSomething(new Integer(1)); // Noncompliant +// ^^^^^^^^^^^^^^ } } class B extends String { // Noncompliant - public B(Integer a) { // Noncompliant [[sc=12;ec=19]] + public B(Integer a) { // Noncompliant +// ^^^^^^^ } - public void doSomething(Integer a) { // Noncompliant [[sc=27;ec=34]] + public void doSomething(Integer a) { // Noncompliant +// ^^^^^^^ } } diff --git a/java-checks/src/test/files/checks/DisallowedConstructorCheck/detected.java b/java-checks/src/test/files/checks/DisallowedConstructorCheck/detected.java index 5a5f3768c7d..c0c5381e87e 100644 --- a/java-checks/src/test/files/checks/DisallowedConstructorCheck/detected.java +++ b/java-checks/src/test/files/checks/DisallowedConstructorCheck/detected.java @@ -10,7 +10,8 @@ class B { } } void plop() { - new A(1,2,new String[]{"1"}); // Noncompliant [[sc=8;ec=9]] {{Remove this forbidden initialization}} + new A(1,2,new String[]{"1"}); // Noncompliant {{Remove this forbidden initialization}} +// ^ new A(); new B(1,2,new String[]{"1"}); new B(); diff --git a/java-checks/src/test/files/checks/DisallowedMethodCheck/detected.java b/java-checks/src/test/files/checks/DisallowedMethodCheck/detected.java index f472146d88b..91e0255b30e 100644 --- a/java-checks/src/test/files/checks/DisallowedMethodCheck/detected.java +++ b/java-checks/src/test/files/checks/DisallowedMethodCheck/detected.java @@ -4,7 +4,8 @@ void foo(int i, long l, String[] s) { void bar(){} void plop() { - foo(1,2,new String[]{"1"}); // Noncompliant [[sc=4;ec=7]] {{Remove this forbidden call}} + foo(1,2,new String[]{"1"}); // Noncompliant {{Remove this forbidden call}} +// ^^^ bar(); } } diff --git a/java-checks/src/test/files/checks/DoubleBraceInitializationCheck.java b/java-checks/src/test/files/checks/DoubleBraceInitializationCheck.java index c6aac7c9593..583f9e04e35 100644 --- a/java-checks/src/test/files/checks/DoubleBraceInitializationCheck.java +++ b/java-checks/src/test/files/checks/DoubleBraceInitializationCheck.java @@ -2,13 +2,15 @@ import java.util.Map; class A { - Map source = new HashMap() {{ // Noncompliant [[sc=46;el=+3;ec=5]] {{Use another way to initialize this instance.}} + Map source = new HashMap() {{ // Noncompliant {{Use another way to initialize this instance.}} +//^[sc=46;ec=5;sl=5;el=8] put("firstName", "John"); put("lastName", "Smith"); }}; B b0 = new B(); - B b1 = new B() {{ bar("hello"); }}; // Noncompliant [[sc=18;ec=37]] {{Use another way to initialize this instance.}} + B b1 = new B() {{ bar("hello"); }}; // Noncompliant {{Use another way to initialize this instance.}} +// ^^^^^^^^^^^^^^^^^^^ B b2 = new B() {{ field = -1; } diff --git a/java-checks/src/test/files/checks/DoublePrefixOperatorCheck/DoublePrefixOperatorCheck.java b/java-checks/src/test/files/checks/DoublePrefixOperatorCheck/DoublePrefixOperatorCheck.java index 16c695b1f52..6433f574e9b 100644 --- a/java-checks/src/test/files/checks/DoublePrefixOperatorCheck/DoublePrefixOperatorCheck.java +++ b/java-checks/src/test/files/checks/DoublePrefixOperatorCheck/DoublePrefixOperatorCheck.java @@ -4,26 +4,35 @@ class test1 { int hash = 1; int hashCode = 2; - boolean flag2 = !!flag; // Noncompliant - int a1 = ~~~a; // Noncompliant [[sc=12;ec=14]]{{Remove multiple operator prefixes.}} + boolean flag2 = !!flag; // Noncompliant + int a1 = ~~~a; // Noncompliant {{Remove multiple operator prefixes.}} +// ^^ boolean flag3 = !!!flag; // Noncompliant - boolean flag4 = !!!foo(); // Noncompliant [[sc=19;ec=21]] + boolean flag4 = !!!foo(); // Noncompliant +// ^^ - boolean flag5 = !(!flag4); // Noncompliant [[sc=19;ec=22]] {{Remove multiple operator prefixes.}} + boolean flag5 = !(!flag4); // Noncompliant {{Remove multiple operator prefixes.}} +// ^^^ - int c = ~(~(~a3)); // Noncompliant [[sc=11;ec=14]] {{Remove multiple operator prefixes.}} + int c = ~(~(~a3)); // Noncompliant {{Remove multiple operator prefixes.}} +// ^^^ - boolean flag6 = !(!(!flag4)); // Noncompliant [[sc=19;ec=22]] {{Remove multiple operator prefixes.}} + boolean flag6 = !(!(!flag4)); // Noncompliant {{Remove multiple operator prefixes.}} +// ^^^ - int a3 = - - -a2; // Noncompliant [[sc=13;ec=16]] + int a3 = - - -a2; // Noncompliant +// ^^^ - int a4 = - -a2; // Noncompliant [[sc=13;ec=16]] + int a4 = - -a2; // Noncompliant +// ^^^ - int a5 = + + +a2; // Noncompliant [[sc=13;ec=16]] + int a5 = + + +a2; // Noncompliant +// ^^^ - int a6 = + +a2; // Noncompliant [[sc=13;ec=16]] + int a6 = + +a2; // Noncompliant +// ^^^ int a2 = ~~a; // Compliant @@ -38,4 +47,4 @@ class test1 { boolean flag7 = !foo(); // Compliant int h1 = ~~hash; // Compliant int h2 = ~~hashCodep; // Compliant -} \ No newline at end of file +} diff --git a/java-checks/src/test/files/checks/EmptyBlock.java b/java-checks/src/test/files/checks/EmptyBlock.java index 17037cad8f4..ed60e50c9f8 100644 --- a/java-checks/src/test/files/checks/EmptyBlock.java +++ b/java-checks/src/test/files/checks/EmptyBlock.java @@ -1,6 +1,8 @@ class EmptyBlock { - // Noncompliant@+1 [[sc=10;ec=11]] {{Either remove or fill this block of code.}} + +// Noncompliant@+1 static { + } static { @@ -11,7 +13,7 @@ class EmptyBlock { // comment } - // Noncompliant@+1 + // Noncompliant@+1 { } @@ -25,7 +27,7 @@ class EmptyBlock { void method() { for (int i = 0; i < 10; i++) - // Noncompliant@+1 + // Noncompliant@+1 { } for (int i = 0; i < 10; i++); @@ -39,17 +41,18 @@ void method() { break; } - // Noncompliant@+1 [[sc=16;ec=17]] {{Either remove or fill this block of code.}} - switch (1) { + + switch (1) { // Noncompliant {{Either remove or fill this block of code.}} +// ^ } - // Noncompliant@+1 + // Noncompliant@+1 try { } catch (Exception e) - // Noncompliant@+1 + // Noncompliant@+1 { } finally - // Noncompliant@+1 + // Noncompliant@+1 { } @@ -70,7 +73,7 @@ void method() { } synchronized (this) - // Noncompliant@+1 + // Noncompliant@+1 { } @@ -78,7 +81,7 @@ void method() { doSomething(); } - // Noncompliant@+1 + // Noncompliant@+1 synchronized (this) { // comment } @@ -93,7 +96,7 @@ void anotherMethod() { public void write(int b) {} }); } - // Noncompliant@+1 + // Noncompliant@+1 catch (IOException cannotHappen) { } } diff --git a/java-checks/src/test/files/checks/EnumEqualCheck.java b/java-checks/src/test/files/checks/EnumEqualCheck.java index 16eeda7e462..cb98f2a2a17 100644 --- a/java-checks/src/test/files/checks/EnumEqualCheck.java +++ b/java-checks/src/test/files/checks/EnumEqualCheck.java @@ -12,8 +12,10 @@ boolean foo(Object o) { } public boolean isFruitGrape(Fruit candidateFruit) { - if("".equals(Fruit.GRAPE)) { } // Noncompliant [[sc=11;ec=17]] - if(Fruit.GRAPE.equals("")) { } // Noncompliant [[sc=20;ec=26]] + if("".equals(Fruit.GRAPE)) { } // Noncompliant +// ^^^^^^ + if(Fruit.GRAPE.equals("")) { } // Noncompliant +// ^^^^^^ if(equals(new A())) { } return candidateFruit.equals(Fruit.GRAPE); // Noncompliant {{Use "==" to perform this enum comparison instead of using "equals"}} } diff --git a/java-checks/src/test/files/checks/EqualsNotOverridenWithCompareToCheck.java b/java-checks/src/test/files/checks/EqualsNotOverridenWithCompareToCheck.java index 1f3b80dac1e..7fd924e05e2 100644 --- a/java-checks/src/test/files/checks/EqualsNotOverridenWithCompareToCheck.java +++ b/java-checks/src/test/files/checks/EqualsNotOverridenWithCompareToCheck.java @@ -15,7 +15,8 @@ public boolean equals(Object obj) { class Foo2 implements Comparable { @Override - public int compareTo(Foo2 o) { // Noncompliant [[sc=14;ec=23]] {{Override "equals(Object obj)" to comply with the contract of the "compareTo(T o)" method.}} + public int compareTo(Foo2 o) { // Noncompliant {{Override "equals(Object obj)" to comply with the contract of the "compareTo(T o)" method.}} +// ^^^^^^^^^ return 0; } @@ -42,7 +43,7 @@ public int compareTo() { class Foo5 implements Comparable { @Override - public int compareTo(Foo5 o) { // Noncompliant + public int compareTo(Foo5 o) { // Noncompliant return 0; } @@ -56,7 +57,7 @@ public int equals() { class Foo6 implements Comparable { @Override - public int compareTo(Foo6 o) { // Noncompliant + public int compareTo(Foo6 o) { // Noncompliant return 0; } @@ -87,7 +88,7 @@ enum Foo8 implements Comparable { ; @Override - public int compareTo(Foo8 o) { // Noncompliant + public int compareTo(Foo8 o) { // Noncompliant return 0; } diff --git a/java-checks/src/test/files/checks/EqualsOverridenWithHashCodeCheck.java b/java-checks/src/test/files/checks/EqualsOverridenWithHashCodeCheck.java index ef78987196a..a1a37ebe777 100644 --- a/java-checks/src/test/files/checks/EqualsOverridenWithHashCodeCheck.java +++ b/java-checks/src/test/files/checks/EqualsOverridenWithHashCodeCheck.java @@ -2,12 +2,14 @@ class A { } class B { - public boolean equals(Object o) { // Noncompliant [[sc=18;ec=24]] {{This class overrides "equals()" and should therefore also override "hashCode()".}} + public boolean equals(Object o) { // Noncompliant {{This class overrides "equals()" and should therefore also override "hashCode()".}} +// ^^^^^^ } } class C { - public int hashCode() { // Noncompliant [[sc=14;ec=22]] {{This class overrides "hashCode()" and should therefore also override "equals()".}} + public int hashCode() { // Noncompliant {{This class overrides "hashCode()" and should therefore also override "equals()".}} +// ^^^^^^^^ } } diff --git a/java-checks/src/test/files/checks/ExceptionsShouldBeImmutableCheck.java b/java-checks/src/test/files/checks/ExceptionsShouldBeImmutableCheck.java index 7bb44eca958..ca479b8008f 100644 --- a/java-checks/src/test/files/checks/ExceptionsShouldBeImmutableCheck.java +++ b/java-checks/src/test/files/checks/ExceptionsShouldBeImmutableCheck.java @@ -1,5 +1,6 @@ class FooException extends RuntimeException { - int foo; // Noncompliant [[sc=7;ec=10]] {{Make this "foo" field final.}} + int foo; // Noncompliant {{Make this "foo" field final.}} +// ^^^ public final int bar; int a = 42, // Noncompliant @@ -7,7 +8,8 @@ class FooException extends RuntimeException { } class Foo extends RuntimeException { - int foo; // Noncompliant [[sc=7;ec=10]] {{Make this "foo" field final.}} + int foo; // Noncompliant {{Make this "foo" field final.}} +// ^^^ } class BarException { diff --git a/java-checks/src/test/files/checks/FieldModifier.java b/java-checks/src/test/files/checks/FieldModifier.java index e72b23e76eb..5cfa970f63f 100644 --- a/java-checks/src/test/files/checks/FieldModifier.java +++ b/java-checks/src/test/files/checks/FieldModifier.java @@ -18,7 +18,8 @@ class A { // modifierIsIntentionallyOmmited int ab; // Compliant - int member; // Noncompliant [[sc=7;ec=13]] {{Explicitly declare the visibility for "member".}} + int member; // Noncompliant {{Explicitly declare the visibility for "member".}} +// ^^^^^^ public int member2; private int member3; } diff --git a/java-checks/src/test/files/checks/FilesExistsJDK8Check.java b/java-checks/src/test/files/checks/FilesExistsJDK8Check.java index 4f6f9efdedd..73e264a2020 100644 --- a/java-checks/src/test/files/checks/FilesExistsJDK8Check.java +++ b/java-checks/src/test/files/checks/FilesExistsJDK8Check.java @@ -13,5 +13,6 @@ void foo() { } } java.util.function.Predicate p1 = f -> Files.isRegularFile(f); // Noncompliant - java.util.function.Predicate p2 = Files::isRegularFile; // Noncompliant [[sc=64;ec=77]] + java.util.function.Predicate p2 = Files::isRegularFile; // Noncompliant +// ^^^^^^^^^^^^^ } diff --git a/java-checks/src/test/files/checks/FinalClassCheck.java b/java-checks/src/test/files/checks/FinalClassCheck.java index ca892bfee0c..46f85b5c1a8 100644 --- a/java-checks/src/test/files/checks/FinalClassCheck.java +++ b/java-checks/src/test/files/checks/FinalClassCheck.java @@ -12,7 +12,7 @@ public static int magic(){ } -public class PrivateConstructorNotFinalClass { // Noncompliant {{Make this class "final" or add a public constructor.}} +public class PrivateConstructorNotFinalClass { // Noncompliant {{Make this class "final" or add a public constructor.}} private PrivateConstructorNotFinalClass() { // ... diff --git a/java-checks/src/test/files/checks/ForLoopCounterChangedCheck.java b/java-checks/src/test/files/checks/ForLoopCounterChangedCheck.java index cbd5e6de512..13208250e62 100644 --- a/java-checks/src/test/files/checks/ForLoopCounterChangedCheck.java +++ b/java-checks/src/test/files/checks/ForLoopCounterChangedCheck.java @@ -7,7 +7,8 @@ void foo() { } for (int b = 0; b < 42; b++) { - b = 0; // Noncompliant [[sc=7;ec=8]] {{Refactor the code in order to not assign to this loop counter from within the loop body.}} + b = 0; // Noncompliant {{Refactor the code in order to not assign to this loop counter from within the loop body.}} +// ^ } for (String c: "aaaa".split("a")) { @@ -15,27 +16,27 @@ void foo() { } for (int d = 0, e = 0; d < 42; d++) { - d = 0; // Noncompliant - e = 0; // Noncompliant + d = 0; // Noncompliant + e = 0; // Noncompliant } int g; for (int f = 0; f < 42; f++) { - f = 0; // Noncompliant + f = 0; // Noncompliant g = 0; // Compliant for (int g = 0; g < 42; g++) { - g = 0; // Noncompliant - f = 0; // Noncompliant + g = 0; // Noncompliant + f = 0; // Noncompliant } - f = 0; // Noncompliant + f = 0; // Noncompliant g = 0; // Compliant } g = 0; // Compliant for (int h = 0; h < 42; h++) { - h = // Noncompliant - h = // Noncompliant + h = // Noncompliant + h = // Noncompliant 0; } @@ -43,14 +44,14 @@ void foo() { ++g; // Compliant for (int i = 0; 0 < 42; i++) { - i++; // Noncompliant - ++i; // Noncompliant - --i; // Noncompliant - i--; // Noncompliant + i++; // Noncompliant + ++i; // Noncompliant + --i; // Noncompliant + i--; // Noncompliant } for (int j = 0; j < 42; j++) { // Compliant - for (int k = 0; j++ < 42; k++) { // Noncompliant + for (int k = 0; j++ < 42; k++) { // Noncompliant } } @@ -59,7 +60,7 @@ void foo() { } for (int i = 0; i < 10; i++) { - for (int k = 0; k < 20; i++) { // Noncompliant + for (int k = 0; k < 20; i++) { // Noncompliant System.out.println("Hello"); } } diff --git a/java-checks/src/test/files/checks/ForLoopIncrementSignCheck.java b/java-checks/src/test/files/checks/ForLoopIncrementSignCheck.java index 8fed3efea5e..a56032d1b52 100644 --- a/java-checks/src/test/files/checks/ForLoopIncrementSignCheck.java +++ b/java-checks/src/test/files/checks/ForLoopIncrementSignCheck.java @@ -2,10 +2,12 @@ class A { void myMethod(int x, int y, int z) { int j = 0, k = 0; for (int i = x; i < y; i++) {} - for (int i = x; i > y; i++) {} // Noncompliant [[sc=21;ec=26]] {{"i" is incremented and will never reach "stop condition".}} + for (int i = x; i > y; i++) {} // Noncompliant {{"i" is incremented and will never reach "stop condition".}} +// ^^^^^ for (int i = x; i >=y; i++) {} // Noncompliant for (int i = x; i > y; i--) {} - for (int z = x; z < y; z--) {} // Noncompliant [[sc=21;ec=26]] {{"z" is decremented and will never reach "stop condition".}} + for (int z = x; z < y; z--) {} // Noncompliant {{"z" is decremented and will never reach "stop condition".}} +// ^^^^^ for (int i = x; i <=y; i--) {} // Noncompliant for (int i = x; y > i; i++) {} for (int i = x; y < i; i++) {} // Noncompliant diff --git a/java-checks/src/test/files/checks/ForLoopTerminationConditionCheck.java b/java-checks/src/test/files/checks/ForLoopTerminationConditionCheck.java index 7ffbbada5e7..52acf19838c 100644 --- a/java-checks/src/test/files/checks/ForLoopTerminationConditionCheck.java +++ b/java-checks/src/test/files/checks/ForLoopTerminationConditionCheck.java @@ -14,7 +14,7 @@ void myMethod() { for (int i = 1; i != 4; j+=1) {} // Noncompliant for (int i = 1; i != 4; j=j+1) {} // Noncompliant for (k=0,j = 1; j != 4; j += 2) {} // Noncompliant - for (int i = 1; i != 4; aMethod()) {} // Noncompliant + for (int i = 1; i != 4; aMethod()) {} // Noncompliant for (int i = 1; i != 4; i++) { i = 5; } // Noncompliant for (int i = 1; i != 4; i++) { j = i+=1; } // Noncompliant for (int i = 1; i != 4; i++) { k = -(i++); } // Noncompliant @@ -46,4 +46,4 @@ void myMethod() { for (String s = "abc"; s.length() > 0; s = s.substring(1)) {} for (Integer i = 1; i != null; i += 2) {} } -} \ No newline at end of file +} diff --git a/java-checks/src/test/files/checks/ForLoopUsedAsWhileLoopCheck.java b/java-checks/src/test/files/checks/ForLoopUsedAsWhileLoopCheck.java index 61617801f74..8b8ce1f283d 100644 --- a/java-checks/src/test/files/checks/ForLoopUsedAsWhileLoopCheck.java +++ b/java-checks/src/test/files/checks/ForLoopUsedAsWhileLoopCheck.java @@ -3,7 +3,8 @@ class A { private void noncompliant() { int i = 0; - for (; i < 5;) { // Noncompliant [[sc=5;ec=8]] + for (; i < 5;) { // Noncompliant +// ^^^ i++; } } diff --git a/java-checks/src/test/files/checks/GettersSettersOnRightField.java b/java-checks/src/test/files/checks/GettersSettersOnRightField.java index d592bf31c3a..899ef8ad71b 100644 --- a/java-checks/src/test/files/checks/GettersSettersOnRightField.java +++ b/java-checks/src/test/files/checks/GettersSettersOnRightField.java @@ -9,11 +9,11 @@ public void setX(int val) { // Noncompliant {{Refactor this setter so that it ac this.y = val; } - public int getY() { // Noncompliant {{Refactor this getter so that it actually refers to the field "y".}} + public int getY() { // Noncompliant {{Refactor this getter so that it actually refers to the field "y".}} return this.x; } - public String getLastName() { // Noncompliant {{Refactor this getter so that it actually refers to the field "lastName".}} + public String getLastName() { // Noncompliant {{Refactor this getter so that it actually refers to the field "lastName".}} return name; } diff --git a/java-checks/src/test/files/checks/IfElseIfStatementEndsWithElseCheck.java b/java-checks/src/test/files/checks/IfElseIfStatementEndsWithElseCheck.java index 8bd5adbecec..c11b120ec32 100644 --- a/java-checks/src/test/files/checks/IfElseIfStatementEndsWithElseCheck.java +++ b/java-checks/src/test/files/checks/IfElseIfStatementEndsWithElseCheck.java @@ -15,7 +15,8 @@ else if(x == 3) { // Noncompliant } else { } if(x == 0) { - }else if( x == 1) { // Noncompliant [[sc=6;ec=13]] {{"if ... else if" constructs should end with "else" clauses.}} + }else if( x == 1) { // Noncompliant {{"if ... else if" constructs should end with "else" clauses.}} +// ^^^^^^^ } if(x==0) { // Compliant @@ -24,7 +25,8 @@ else if(x == 3) { // Noncompliant if(x == 10) { // Compliant } if(x == 11) { - }else if(x == 12){// Noncompliant [[sc=8;ec=15]] {{"if ... else if" constructs should end with "else" clauses.}} + }else if(x == 12){ // Noncompliant {{"if ... else if" constructs should end with "else" clauses.}} +// ^^^^^^^ } } if(x == 0) {} // Compliant @@ -32,12 +34,13 @@ else if(x == 3) { // Noncompliant if(x == 13) { //Compliant } else { if(x == 14) { - }else if(x == 15) {// Noncompliant [[sc=8;ec=15]] {{"if ... else if" constructs should end with "else" clauses.}} + }else if(x == 15) { // Noncompliant {{"if ... else if" constructs should end with "else" clauses.}} +// ^^^^^^^ } } if(x ==16) { }else if(x == 17) { - }else if(x == 18) { // Noncompliant + }else if(x == 18) { // Noncompliant } if(x ==16) { }else if(x == 17) { @@ -46,7 +49,7 @@ else if(x == 3) { // Noncompliant if(x ==16) { }else if(x == 17) { }else if(x == 18) { - }else if(x == 19){} // Noncompliant + }else if(x == 19){} // Noncompliant } void foo2(int op) { diff --git a/java-checks/src/test/files/checks/IgnoredOperationStatusCheck.java b/java-checks/src/test/files/checks/IgnoredOperationStatusCheck.java index 43660fcfa79..6d22713363f 100644 --- a/java-checks/src/test/files/checks/IgnoredOperationStatusCheck.java +++ b/java-checks/src/test/files/checks/IgnoredOperationStatusCheck.java @@ -16,8 +16,10 @@ class A { boolean fileOp(File f) { - f.delete(); // Noncompliant [[sc=5;ec=16]] {{Do something with the "boolean" value returned by "delete".}} - boolean b1 = f.delete(); // Noncompliant [[sc=5;ec=29]] {{Do something with the "boolean" value returned by "delete".}} + f.delete(); // Noncompliant {{Do something with the "boolean" value returned by "delete".}} +// ^^^^^^^^^^^ + boolean b1 = f.delete(); // Noncompliant {{Do something with the "boolean" value returned by "delete".}} +// ^^^^^^^^^^^^^^^^^^^^^^^^ boolean b2 = f.delete(); // Compliant if (b2 || f.delete()) {} // Compliant @@ -34,7 +36,8 @@ boolean fileOp(File f) { } boolean lockOp(Lock l) { - l.tryLock(); // Noncompliant [[sc=5;ec=17]] {{Do something with the "boolean" value returned by "tryLock".}} + l.tryLock(); // Noncompliant {{Do something with the "boolean" value returned by "tryLock".}} +// ^^^^^^^^^^^^ l.tryLock(0L, TimeUnit.DAYS); // Compliant return l.tryLock(); // Compliant } diff --git a/java-checks/src/test/files/checks/IncrementDecrementInSubExpressionCheck.java b/java-checks/src/test/files/checks/IncrementDecrementInSubExpressionCheck.java index 0c039b1fda2..d68e49d9515 100644 --- a/java-checks/src/test/files/checks/IncrementDecrementInSubExpressionCheck.java +++ b/java-checks/src/test/files/checks/IncrementDecrementInSubExpressionCheck.java @@ -8,7 +8,8 @@ public void f() { foo[i]++; - foo[i++] = 0; // Noncompliant {{Extract this increment or decrement operator into a dedicated statement.}} [[sc=9;ec=12]] + foo[i++] = 0; // Noncompliant {{Extract this increment or decrement operator into a dedicated statement.}} +// ^^^ foo[i--] = 0; // Noncompliant foo[++i] = 0; // Noncompliant foo[--i] = 0; // Noncompliant diff --git a/java-checks/src/test/files/checks/InnerStaticClassesCheckSample.java b/java-checks/src/test/files/checks/InnerStaticClassesCheckSample.java index 3b84fce14ab..43f02eda89e 100644 --- a/java-checks/src/test/files/checks/InnerStaticClassesCheckSample.java +++ b/java-checks/src/test/files/checks/InnerStaticClassesCheckSample.java @@ -3,7 +3,8 @@ class Fruit { private int value; - public class Seed { // Noncompliant [[sc=16;ec=20]]{{Make this a "static" inner class.}} + public class Seed { // Noncompliant {{Make this a "static" inner class.}} +// ^^^^ int germinationDays = 0; public Seed(int germinationDays) { this.germinationDays = germinationDays; diff --git a/java-checks/src/test/files/checks/InputStreamOverrideReadCheck.java b/java-checks/src/test/files/checks/InputStreamOverrideReadCheck.java index 2a6414f5c6b..10f95417508 100644 --- a/java-checks/src/test/files/checks/InputStreamOverrideReadCheck.java +++ b/java-checks/src/test/files/checks/InputStreamOverrideReadCheck.java @@ -1,6 +1,7 @@ import java.io.*; -public class MyStream extends InputStream { // Noncompliant [[sc=14;ec=22]]{{Provide an override of "read(byte[],int,int)" for this class.}} +public class MyStream extends InputStream { // Noncompliant {{Provide an override of "read(byte[],int,int)" for this class.}} +// ^^^^^^^^ private FileInputStream fin; public MyStream(File file) throws IOException { diff --git a/java-checks/src/test/files/checks/LambdaOptionalParenthesisCheck.java b/java-checks/src/test/files/checks/LambdaOptionalParenthesisCheck.java index f447477457b..8af3b3aa36a 100644 --- a/java-checks/src/test/files/checks/LambdaOptionalParenthesisCheck.java +++ b/java-checks/src/test/files/checks/LambdaOptionalParenthesisCheck.java @@ -1,7 +1,8 @@ class A{ void method(){ IntStream.range(1,5).map(a->a+1) - .map((a)->a+1) // Noncompliant [[sc=30;ec=31]] {{Remove the parentheses around the "a" parameter}} + .map((a)->a+1) // Noncompliant {{Remove the parentheses around the "a" parameter}} +// ^ .map((int x)->x+1) ; Collectors.groupingBy((Map page) -> Site.category(page), TreeMap::new, toList()); diff --git a/java-checks/src/test/files/checks/LambdaSingleExpressionCheck_no_version.java b/java-checks/src/test/files/checks/LambdaSingleExpressionCheck_no_version.java index dd61645db25..fee4fe24aa4 100644 --- a/java-checks/src/test/files/checks/LambdaSingleExpressionCheck_no_version.java +++ b/java-checks/src/test/files/checks/LambdaSingleExpressionCheck_no_version.java @@ -1,7 +1,8 @@ class A { public void method() { IntStream.range(1, 5).map(x -> x * x - 1).forEach(x -> System.out.println(x)); - IntStream.range(1, 5).map(x -> {return x * x - 1;}) // Noncompliant [[sc=36;ec=37]] {{Remove useless curly braces around statement and then remove useless return keyword (sonar.java.source not set. Assuming 8 or greater.)}} + IntStream.range(1, 5).map(x -> {return x * x - 1;}) // Noncompliant {{Remove useless curly braces around statement and then remove useless return keyword (sonar.java.source not set. Assuming 8 or greater.)}} +// ^ .forEach(x -> { // Noncompliant {{Remove useless curly braces around statement (sonar.java.source not set. Assuming 8 or greater.)}} System.out.println(x + 11); }); diff --git a/java-checks/src/test/files/checks/LambdaTypeParameterCheck.java b/java-checks/src/test/files/checks/LambdaTypeParameterCheck.java index 6ec6465731e..f828e3951c9 100644 --- a/java-checks/src/test/files/checks/LambdaTypeParameterCheck.java +++ b/java-checks/src/test/files/checks/LambdaTypeParameterCheck.java @@ -7,10 +7,14 @@ public void foo() { foo(s -> s.length()); // compliant : no block and one param foo((String a, Object b) -> a.length()); // Compliant foo((a, b) -> a.length()); // compliant two params and no block - foo((a, b) -> {return a.length();}); // Noncompliant [[sc=10;ec=14]] {{Specify a type for: 'a', 'b'}} - foo(s -> {return s.length();}); // Noncompliant [[sc=9;ec=10]] {{Specify a type for: 's'}} - foo((a, b, c) -> a.length()); // Noncompliant [[sc=10;ec=17]] {{Specify a type for: 'a', 'b', 'c'}} - foo((a, b, c) -> {return a.length();}); // Noncompliant [[sc=10;ec=17]] {{Specify a type for: 'a', 'b', 'c'}} + foo((a, b) -> {return a.length();}); // Noncompliant {{Specify a type for: 'a', 'b'}} +// ^^^^ + foo(s -> {return s.length();}); // Noncompliant {{Specify a type for: 's'}} +// ^ + foo((a, b, c) -> a.length()); // Noncompliant {{Specify a type for: 'a', 'b', 'c'}} +// ^^^^^^^ + foo((a, b, c) -> {return a.length();}); // Noncompliant {{Specify a type for: 'a', 'b', 'c'}} +// ^^^^^^^ } abstract void foo(Consumer s); diff --git a/java-checks/src/test/files/checks/LoggersDeclarationCheck.java b/java-checks/src/test/files/checks/LoggersDeclarationCheck.java index 97a9f0bd9dd..7002f0feaa9 100644 --- a/java-checks/src/test/files/checks/LoggersDeclarationCheck.java +++ b/java-checks/src/test/files/checks/LoggersDeclarationCheck.java @@ -12,7 +12,8 @@ class A { private static final Log LOGGER; // Compliant - private static final Log foo; // Noncompliant [[sc=28;ec=31]] {{Rename the "foo" logger to comply with the format "LOG(?:GER)?".}} + private static final Log foo; // Noncompliant {{Rename the "foo" logger to comply with the format "LOG(?:GER)?".}} +// ^^^ private static final Foo foo2; // Compliant diff --git a/java-checks/src/test/files/checks/LoopExecutingAtMostOnceCheck.java b/java-checks/src/test/files/checks/LoopExecutingAtMostOnceCheck.java index 829a46180a1..05baed39c45 100644 --- a/java-checks/src/test/files/checks/LoopExecutingAtMostOnceCheck.java +++ b/java-checks/src/test/files/checks/LoopExecutingAtMostOnceCheck.java @@ -2,7 +2,7 @@ class A { void m1() { for (int i = 0; i < 10; i++) { foo(); - break; // Noncompliant {{Remove this "break" statement or make it conditional.}} + break; // Noncompliant {{Remove this "break" statement or make it conditional.}} } } @@ -10,7 +10,7 @@ void m3() throws Exception { int i = 0; while (i++ < 10) { foo(); - throw new Exception("BOUM!"); // Noncompliant {{Remove this "throw" statement or make it conditional.}} + throw new Exception("BOUM!"); // Noncompliant {{Remove this "throw" statement or make it conditional.}} } } @@ -18,7 +18,7 @@ void m4() { int i = 0; do { foo(); - break; // Noncompliant {{Remove this "break" statement or make it conditional.}} + break; // Noncompliant {{Remove this "break" statement or make it conditional.}} } while (i++ < 10); } @@ -32,7 +32,7 @@ void m5(java.util.List myList) { void m6() { for (int i = 0; i < 10; ++i) { foo(); - return; // Noncompliant {{Remove this "return" statement or make it conditional.}} + return; // Noncompliant {{Remove this "return" statement or make it conditional.}} } } @@ -59,7 +59,7 @@ void m9(boolean b) { if (b) while (i++ < 10) { foo(); - return; // Noncompliant {{Remove this "return" statement or make it conditional.}} + return; // Noncompliant {{Remove this "return" statement or make it conditional.}} } } @@ -67,7 +67,7 @@ void m10(boolean b) throws Exception { int i = 0; while (i++ < 10) { foo(i); - throw new Exception("BOUM!"); // Noncompliant {{Remove this "throw" statement or make it conditional.}} + throw new Exception("BOUM!"); // Noncompliant {{Remove this "throw" statement or make it conditional.}} } } diff --git a/java-checks/src/test/files/checks/LoopsOnSameSetCheck.java b/java-checks/src/test/files/checks/LoopsOnSameSetCheck.java index 5d625bb9df2..429c9918f28 100644 --- a/java-checks/src/test/files/checks/LoopsOnSameSetCheck.java +++ b/java-checks/src/test/files/checks/LoopsOnSameSetCheck.java @@ -12,17 +12,18 @@ private List getList() { public void doSomethingToAList(List strings, List strings2) { for (String str : strings); foo(); - for (String str : strings); // Noncompliant [[sc=23;ec=30]] {{Combine this loop with the one that starts on line 13.}} + for (String str : strings); // Noncompliant {{Combine this loop with the one that starts on line 13.}} +// ^^^^^^^ strings = null; for (String str : strings); // strings get reassigned for (String str : getList()); - for (String str : getList()); // Noncompliant {{Combine this loop with the one that starts on line 18.}} + for (String str : getList()); // Noncompliant {{Combine this loop with the one that starts on line 19.}} foo(); for (String str : getList()); // no issue if something in between for loops for (String str : foo()); List list = null; for (String str : list); - for (String str : list); // Noncompliant {{Combine this loop with the one that starts on line 24.}} + for (String str : list); // Noncompliant {{Combine this loop with the one that starts on line 25.}} if (list.size() > 10) { list.remove(0); } diff --git a/java-checks/src/test/files/checks/MagicNumberCheck.java b/java-checks/src/test/files/checks/MagicNumberCheck.java index e2fa24cbd8f..350d4ea0f5e 100644 --- a/java-checks/src/test/files/checks/MagicNumberCheck.java +++ b/java-checks/src/test/files/checks/MagicNumberCheck.java @@ -12,12 +12,17 @@ final class A { int b = 1; int c = -1; - int d = 2; // Noncompliant [[sc=11;ec=12]] {{Assign this magic number 2 to a well-named constant, and use the constant instead.}} - int e = 42; // Noncompliant [[sc=11;ec=13]] {{Assign this magic number 42 to a well-named constant, and use the constant instead.}} + int d = 2; // Noncompliant {{Assign this magic number 2 to a well-named constant, and use the constant instead.}} +// ^ + int e = 42; // Noncompliant {{Assign this magic number 42 to a well-named constant, and use the constant instead.}} +// ^^ - long aLong = 12L; // Noncompliant [[sc=16;ec=19]] {{Assign this magic number 12L to a well-named constant, and use the constant instead.}} - double aDouble = 12.3d; // Noncompliant [[sc=20;ec=25]] {{Assign this magic number 12.3d to a well-named constant, and use the constant instead.}} - float aFloat = 12.3F; // Noncompliant [[sc=18;ec=23]] {{Assign this magic number 12.3F to a well-named constant, and use the constant instead.}} + long aLong = 12L; // Noncompliant {{Assign this magic number 12L to a well-named constant, and use the constant instead.}} +// ^^^ + double aDouble = 12.3d; // Noncompliant {{Assign this magic number 12.3d to a well-named constant, and use the constant instead.}} +// ^^^^^ + float aFloat = 12.3F; // Noncompliant {{Assign this magic number 12.3F to a well-named constant, and use the constant instead.}} +// ^^^^^ String string = "string"; String strDouble = "123.3d"; boolean bool = true; diff --git a/java-checks/src/test/files/checks/MagicNumberCheckCustom.java b/java-checks/src/test/files/checks/MagicNumberCheckCustom.java index 724869d46dd..8874eee8058 100644 --- a/java-checks/src/test/files/checks/MagicNumberCheckCustom.java +++ b/java-checks/src/test/files/checks/MagicNumberCheckCustom.java @@ -13,7 +13,8 @@ final class A { int c = -1; int d = 2; - int e = 42; // Noncompliant [[sc=11;ec=13]] {{Assign this magic number 42 to a well-named constant, and use the constant instead.}} + int e = 42; // Noncompliant {{Assign this magic number 42 to a well-named constant, and use the constant instead.}} +// ^^ long aLong = 12L; // Noncompliant {{Assign this magic number 12L to a well-named constant, and use the constant instead.}} double aDouble = 12.3d; // Noncompliant {{Assign this magic number 12.3d to a well-named constant, and use the constant instead.}} diff --git a/java-checks/src/test/files/checks/MainMethodThrowsExceptionCheck.java b/java-checks/src/test/files/checks/MainMethodThrowsExceptionCheck.java index 6672f2f726e..5f2d1e8d7e2 100644 --- a/java-checks/src/test/files/checks/MainMethodThrowsExceptionCheck.java +++ b/java-checks/src/test/files/checks/MainMethodThrowsExceptionCheck.java @@ -1,7 +1,8 @@ import java.io.IOException; class A{ - public static void main(String[] args) throws IOException { // Noncompliant [[sc=42;ec=48]] {{Remove this throws clause.}} + public static void main(String[] args) throws IOException { // Noncompliant {{Remove this throws clause.}} +// ^^^^^^ } public void main(String[] args) throws IOException { diff --git a/java-checks/src/test/files/checks/MethodComplexityJavaLangPackage.java b/java-checks/src/test/files/checks/MethodComplexityJavaLangPackage.java index 0de9162e4ac..736ae1ec8ba 100644 --- a/java-checks/src/test/files/checks/MethodComplexityJavaLangPackage.java +++ b/java-checks/src/test/files/checks/MethodComplexityJavaLangPackage.java @@ -1,18 +1,26 @@ public class HelloWorld { - public void sayHello() { // Noncompliant [[effortToFix=1;sc=15;ec=23;secondary=4,5]] {{The Cyclomatic Complexity of this method "sayHello" is 2 which is greater than 1 authorized.}} + public void sayHello() { // Noncompliant {{The Cyclomatic Complexity of this method "sayHello" is 2 which is greater than 1 authorized.}} +// ^^^^^^^^ +// ^^^^^^^^@-1< while (false) { +// ^^^^^< } } - public void sayHello2() { // Noncompliant [[effortToFix=3;sc=15;ec=24;secondary=9,10,14,15]] {{The Cyclomatic Complexity of this method "sayHello2" is 4 which is greater than 1 authorized.}} + public void sayHello2() { // Noncompliant {{The Cyclomatic Complexity of this method "sayHello2" is 4 which is greater than 1 authorized.}} +// ^^^^^^^^^ +// ^^^^^^^^^@-1< while (false) { +// ^^^^^< } return a || b +// ^^< && c; +// ^^< } public boolean equals(Object o) { diff --git a/java-checks/src/test/files/checks/MethodComplexityNoncompliant.java b/java-checks/src/test/files/checks/MethodComplexityNoncompliant.java index 7d677c2070d..0b747c71739 100644 --- a/java-checks/src/test/files/checks/MethodComplexityNoncompliant.java +++ b/java-checks/src/test/files/checks/MethodComplexityNoncompliant.java @@ -1,17 +1,25 @@ public class HelloWorld { - public void sayHello() { // Noncompliant [[effortToFix=1;sc=15;ec=23;secondary=3,4]] {{The Cyclomatic Complexity of this method "sayHello" is 2 which is greater than 1 authorized.}} + public void sayHello() { // Noncompliant {{The Cyclomatic Complexity of this method "sayHello" is 2 which is greater than 1 authorized.}} +// ^^^^^^^^ +// ^^^^^^^^@-1< while (false) { +// ^^^^^< } } - public void sayHello2() { // Noncompliant [[effortToFix=3;sc=15;ec=24;secondary=8,9,13,14]] {{The Cyclomatic Complexity of this method "sayHello2" is 4 which is greater than 1 authorized.}} + public void sayHello2() { // Noncompliant {{The Cyclomatic Complexity of this method "sayHello2" is 4 which is greater than 1 authorized.}} +// ^^^^^^^^^ +// ^^^^^^^^^@-1< while (false) { +// ^^^^^< } return a || b +// ^^< && c; +// ^^< } public boolean equals(Object o) { diff --git a/java-checks/src/test/files/checks/MethodIdenticalImplementationsCheck.java b/java-checks/src/test/files/checks/MethodIdenticalImplementationsCheck.java index cb1f2f8b5b3..edb1d4f0675 100644 --- a/java-checks/src/test/files/checks/MethodIdenticalImplementationsCheck.java +++ b/java-checks/src/test/files/checks/MethodIdenticalImplementationsCheck.java @@ -3,13 +3,17 @@ abstract class A { private String code; public String getCode() { return code; } - public String getName() { return code; } // Noncompliant [[sc=17;ec=24;secondary=5]] {{Update this method so that its implementation is not identical to "getCode" on line 5.}} - public String getWord() { return code; } // Noncompliant [[sc=17;ec=24;secondary=5]] {{Update this method so that its implementation is not identical to "getCode" on line 5.}} +// ^^^^^^^> + public String getName() { return code; } // Noncompliant {{Update this method so that its implementation is not identical to "getCode" on line 5.}} +// ^^^^^^^ + public String getWord() { return code; } // Noncompliant {{Update this method so that its implementation is not identical to "getCode" on line 5.}} +// ^^^^^^^ String getOtherCode() { return CODE; } String getOtherName() { return CODE; } // Compliant - not getters (not public) void greek1() { +// ^^^^^^> Object x = null; try { x = new Object(); @@ -22,7 +26,8 @@ void greek1() { } } - void greek2() { // Noncompliant [[sc=8;ec=14;secondary=12]] {{Update this method so that its implementation is not identical to "greek1" on line 12.}} + void greek2() { // Noncompliant {{Update this method so that its implementation is not identical to "greek1" on line 15.}} +// ^^^^^^ Object x = null; try { x = new Object(); @@ -115,7 +120,7 @@ void bam1(LocalA o1, LocalB o2) { } LocalB o2; - void bam2(LocalA o1) { // Noncompliant - parameters are not considered + void bam2(LocalA o1) { // Noncompliant doSomething(o1); doSomethingElse(o2); } diff --git a/java-checks/src/test/files/checks/MethodParametersOrderCheck.java b/java-checks/src/test/files/checks/MethodParametersOrderCheck.java index f83eb9e70df..782f93470fb 100644 --- a/java-checks/src/test/files/checks/MethodParametersOrderCheck.java +++ b/java-checks/src/test/files/checks/MethodParametersOrderCheck.java @@ -2,6 +2,7 @@ class A { int a; public double divide(int divisor, int dividend) { +// ^^^^^^^^^^^^>^^^^^^^^^^^^> return divisor / dividend; } @@ -16,9 +17,11 @@ public void doTheThing() { alpha(A); int divisor = 15; int dividend = 5; - double result = divide(dividend, divisor); // Noncompliant [[sc=27;ec=46;secondary=4,4]] {{Parameters to divide have the same names but not the same order as the method arguments.}} + double result = divide(dividend, divisor); // Noncompliant {{Parameters to divide have the same names but not the same order as the method arguments.}} +// ^^^^^^^^^^^^^^^^^^^ double result1 = divide(new B().alpha, divisor); // Compliant - double result2 = divide(new B().dividend, divisor); // Noncompliant [[sc=28;ec=55;secondary=4,4]] {{Parameters to divide have the same names but not the same order as the method arguments.}} + double result2 = divide(new B().dividend, divisor); // Noncompliant {{Parameters to divide have the same names but not the same order as the method arguments.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unknown e; String b =""; beta(e, b); // Compliant @@ -79,7 +82,7 @@ public void test1() { new B().test2(a, b); // Compliant new B().test2(b, a); // Noncompliant new B().test2(a, b, entry); // Compliant - new B().test2(c, b, a); // Noncompliant [[secondary=101,103]] + new B().test2(c, b, a); // Noncompliant } public void foo2() { diff --git a/java-checks/src/test/files/checks/MissingBeanValidationCheck.java b/java-checks/src/test/files/checks/MissingBeanValidationCheck.java index 56f951f4d2c..d33fb1ed752 100644 --- a/java-checks/src/test/files/checks/MissingBeanValidationCheck.java +++ b/java-checks/src/test/files/checks/MissingBeanValidationCheck.java @@ -33,9 +33,11 @@ class NonCompliantGroup { private User owner; // Noncompliant - private List members; // Noncompliant [[sc=11;ec=21]] {{Add missing "@Valid" on "members" to validate it with "Bean Validation".}} + private List members; // Noncompliant {{Add missing "@Valid" on "members" to validate it with "Bean Validation".}} +// ^^^^^^^^^^ - private Building.Size office; // Noncompliant [[sc=11;ec=30]] + private Building.Size office; // Noncompliant +// ^^^^^^^^^^^^^^^^^^^ private Building.Size company; // Compliant - Parametrized type, non-specified } @@ -58,7 +60,8 @@ class NonCompliantService { public void login(User user) { // Noncompliant {{Add missing "@Valid" on "user" to validate it with "Bean Validation".}} } - public List list(Department department) { // Noncompliant [[sc=26;ec=36]] {{Add missing "@Valid" on "department" to validate it with "Bean Validation".}} + public List list(Department department) { // Noncompliant {{Add missing "@Valid" on "department" to validate it with "Bean Validation".}} +// ^^^^^^^^^^ } } diff --git a/java-checks/src/test/files/checks/MultilineBlocksCurlyBracesCheck.java b/java-checks/src/test/files/checks/MultilineBlocksCurlyBracesCheck.java index dc87577e947..d042454d70b 100644 --- a/java-checks/src/test/files/checks/MultilineBlocksCurlyBracesCheck.java +++ b/java-checks/src/test/files/checks/MultilineBlocksCurlyBracesCheck.java @@ -3,7 +3,7 @@ public class A { void nonCompliant() { if (condition) firstActionInBlock(); - secondAction(); // Noncompliant {{This line will not be executed conditionally; only the first line of this 2-line block will be. The rest will execute unconditionally.}} + secondAction(); // Noncompliant {{This line will not be executed conditionally; only the first line of this 2-line block will be. The rest will execute unconditionally.}} thirdAction(); if (condition) { @@ -17,16 +17,16 @@ void nonCompliant() { action(); else firstActionInBlock(); - secondAction(); // Noncompliant {{This line will not be executed conditionally; only the first line of this 2-line block will be. The rest will execute unconditionally.}} + secondAction(); // Noncompliant {{This line will not be executed conditionally; only the first line of this 2-line block will be. The rest will execute unconditionally.}} String str = null; for (int i = 0; i < array.length; i++) str = array[i]; - doTheThing(str); // Noncompliant {{This line will not be executed in a loop; only the first line of this 2-line block will be. The rest will execute only once.}} + doTheThing(str); // Noncompliant {{This line will not be executed in a loop; only the first line of this 2-line block will be. The rest will execute only once.}} while (true) firstActionInBlock(); - secondAction(); // Noncompliant {{This line will not be executed in a loop; only the first line of this 2-line block will be. The rest will execute only once.}} + secondAction(); // Noncompliant {{This line will not be executed in a loop; only the first line of this 2-line block will be. The rest will execute only once.}} int[] test = new int[]{1, 2}; for (int intValue : test) @@ -59,10 +59,10 @@ void compliant() { void expansion() { if (condition); secondAction(); // Noncompliant - if (condition) firstActionInBlock(); secondAction(); // Noncompliant; secondAction executed unconditionally + if (condition) firstActionInBlock(); secondAction(); // Noncompliant if (condition) firstActionInBlock(); - secondAction(); // Noncompliant {{This line will not be executed conditionally; only the first line of this 2-line block will be. The rest will execute unconditionally.}} + secondAction(); // Noncompliant {{This line will not be executed conditionally; only the first line of this 2-line block will be. The rest will execute unconditionally.}} if (condition) firstActionInBlock(); secondAction(); @@ -72,10 +72,10 @@ void expansion() { secondAction(); for (int i = 0;i<10;i++); secondAction(); // Noncompliant - for (int i = 0;i<10;i++) firstActionInBlock(); secondAction(); // Noncompliant; secondAction executed unconditionally + for (int i = 0;i<10;i++) firstActionInBlock(); secondAction(); // Noncompliant for (int i = 0;i<10;i++) firstActionInBlock(); - secondAction(); // Noncompliant + secondAction(); // Noncompliant for (int i = 0;i<10;i++) firstActionInBlock(); secondAction(); // compliant : indentation is not confusing diff --git a/java-checks/src/test/files/checks/NioFileDeleteCheck.java b/java-checks/src/test/files/checks/NioFileDeleteCheck.java index de38dcfaa97..071d117445e 100644 --- a/java-checks/src/test/files/checks/NioFileDeleteCheck.java +++ b/java-checks/src/test/files/checks/NioFileDeleteCheck.java @@ -3,7 +3,7 @@ class A { public void cleanUp(Path path) { File file = new File(path); - if (!file.delete()) { // Noncompliant {{Use "java.nio.file.Files#delete" here for better messages on error conditions.}} + if (!file.delete()) { // Noncompliant {{Use "java.nio.file.Files#delete" here for better messages on error conditions.}} } java.nio.file.Files.delete(path); // compliant } diff --git a/java-checks/src/test/files/checks/NoSonar.java b/java-checks/src/test/files/checks/NoSonar.java index f61d143ef87..b77905893f3 100644 --- a/java-checks/src/test/files/checks/NoSonar.java +++ b/java-checks/src/test/files/checks/NoSonar.java @@ -1,4 +1,5 @@ public class HelloWorld { +// Noncompliant@+1 // Noncompliant {{Is //NOSONAR used to exclude false-positive or to hide real quality flaw ?}} // OK } diff --git a/java-checks/src/test/files/checks/NonShortCircuitLogicCheck.java b/java-checks/src/test/files/checks/NonShortCircuitLogicCheck.java index 1b9733a0eb6..a7064fa7896 100644 --- a/java-checks/src/test/files/checks/NonShortCircuitLogicCheck.java +++ b/java-checks/src/test/files/checks/NonShortCircuitLogicCheck.java @@ -4,7 +4,8 @@ void method1() { boolean[] tests = { getTrue() || getFalse(), getTrue() && getFalse(), - getTrue() | getFalse(), // Noncompliant [[sc=15;ec=16]] {{Correct this "|" to "||" and extract the right operand to a variable if it should always be evaluated.}} + getTrue() | getFalse(), // Noncompliant {{Correct this "|" to "||" and extract the right operand to a variable if it should always be evaluated.}} +// ^ getTrue() & getFalse(), // Noncompliant {{Correct this "&" to "&&" and extract the right operand to a variable if it should always be evaluated.}} Boolean.TRUE | Boolean.FALSE, // Noncompliant {{Correct this "|" to "||".}} Boolean.TRUE & Boolean.FALSE, // Noncompliant {{Correct this "&" to "&&".}} diff --git a/java-checks/src/test/files/checks/ObjectFinalizeOverloadedCheck.java b/java-checks/src/test/files/checks/ObjectFinalizeOverloadedCheck.java index bb32ddeb090..6d003468c7e 100644 --- a/java-checks/src/test/files/checks/ObjectFinalizeOverloadedCheck.java +++ b/java-checks/src/test/files/checks/ObjectFinalizeOverloadedCheck.java @@ -6,7 +6,8 @@ public void finalize() { // Compliant public void finalize() { // Compliant } - public void finalize(int a) { // Noncompliant [[sc=15;ec=23]] {{Rename this method to avoid any possible confusion with Object.finalize().}} + public void finalize(int a) { // Noncompliant {{Rename this method to avoid any possible confusion with Object.finalize().}} +// ^^^^^^^^ } private void finalize(int a, int b) { // Noncompliant {{Rename this method to avoid any possible confusion with Object.finalize().}} diff --git a/java-checks/src/test/files/checks/OctalValuesCheck.java b/java-checks/src/test/files/checks/OctalValuesCheck.java index 1a58076893a..f96c08f5bdb 100644 --- a/java-checks/src/test/files/checks/OctalValuesCheck.java +++ b/java-checks/src/test/files/checks/OctalValuesCheck.java @@ -2,7 +2,8 @@ class A { int a = 0; int b = 1; int c = 42; - int d = 010; // Noncompliant [[sc=11;ec=14]] {{Use decimal values instead of octal ones.}} + int d = 010; // Noncompliant {{Use decimal values instead of octal ones.}} +// ^^^ int e = 00; // Noncompliant int f = 0.; int g = 0x00; diff --git a/java-checks/src/test/files/checks/OperatorPrecedence.java b/java-checks/src/test/files/checks/OperatorPrecedence.java index 67dd3e3420b..7d3b68c61c9 100644 --- a/java-checks/src/test/files/checks/OperatorPrecedence.java +++ b/java-checks/src/test/files/checks/OperatorPrecedence.java @@ -7,9 +7,11 @@ abstract class Class { boolean t; @Annotation1(1 + 2 + 3) // Compliant - @Annotation2(1 & 2 | 3) // Noncompliant [[sc=16;ec=21]] {{Add parentheses to make the operator precedence explicit.}} + @Annotation2(1 & 2 | 3) // Noncompliant {{Add parentheses to make the operator precedence explicit.}} +// ^^^^^ @Annotation3(key = 1 + 2 + 3) // Compliant - @Annotation4(key = 1 & 2 | 3) // Noncompliant [[sc=22;ec=27]] {{Add parentheses to make the operator precedence explicit.}} + @Annotation4(key = 1 & 2 | 3) // Noncompliant {{Add parentheses to make the operator precedence explicit.}} +// ^^^^^ public int method(int[] array, int value) { ; // should raise an issue in initializer @@ -114,7 +116,8 @@ public int method() { Predicate p2 = (value > 0) ? x -> false : y -> true; // Compliant IntFunction p3 = (value > 0) ? x -> x++ : y -> 42; // Compliant - Predicate p4 = (value > 0) ? null : x -> { return true; }; // Noncompliant [[sc=49;ec=70]] {{Add parentheses to make the operator precedence explicit.}} + Predicate p4 = (value > 0) ? null : x -> { return true; }; // Noncompliant {{Add parentheses to make the operator precedence explicit.}} +// ^^^^^^^^^^^^^^^^^^^^^ Predicate p5 = (value > 0) ? null : (x -> { return true; }); // Compliant; Predicate p6 = (value > 0) ? null : x -> x == null ? true : false; // Noncompliant {{Add parentheses to make the operator precedence explicit.}} diff --git a/java-checks/src/test/files/checks/OverwrittenKeyCheck.java b/java-checks/src/test/files/checks/OverwrittenKeyCheck.java index 8b3db8b573a..3a3679203de 100644 --- a/java-checks/src/test/files/checks/OverwrittenKeyCheck.java +++ b/java-checks/src/test/files/checks/OverwrittenKeyCheck.java @@ -6,7 +6,9 @@ class A { void map() { map.put("a", "Apple"); - map.put("a", "Banana"); // Noncompliant [[secondary=8]]{{Verify this is the key that was intended; it was already set before.}} +// ^^^> + map.put("a", "Banana"); // Noncompliant {{Verify this is the key that was intended; it was already set before.}} + // ^^^ } void map2() { @@ -16,14 +18,20 @@ void map2() { if (blah) { map.put(3, "test"); map.put(4, "another"); - map.put(4, "another"); // Noncompliant [[secondary=18,20,21]] +// ^> + map.put(4, "another"); // Noncompliant + // ^ map.put(4, "another"); +// ^< map.put(4, "another"); +// ^< } for (int i = 0; i < 10; i++) { map.put(i, "test"); - map.put(i, "test"); // Noncompliant [[secondary=25]] +// ^> + map.put(i, "test"); // Noncompliant + // ^ } for (int i = 0; i < 10; i++) { @@ -34,11 +42,13 @@ void map2() { void mix(Map other, Object[] arr) { arr[1] = null; +// ^> map.put("a", 1); other.put("a", 2); - map.put("a", 1); // Noncompliant [[secondary=37]] - other.put("a", 2); // Noncompliant [[secondary=38]] - arr[1] = null; // Noncompliant [[secondary=36]] + arr[1] = null; // Noncompliant + // ^ + map.put("a", 1); // Noncompliant + other.put("a", 2); // Noncompliant } int[] ints; @@ -46,7 +56,9 @@ void mix(Map other, Object[] arr) { void arrays() { int i; ints[i] = 1; - ints[i] = 2; // Noncompliant [[secondary=48]] {{Verify this is the index that was intended; it was already set before.}} +// ^> + ints[i] = 2; // Noncompliant {{Verify this is the index that was intended; it was already set before.}} + // ^ } void marrays(int[][] arr) { @@ -58,14 +70,14 @@ void marrays(int[][] arr) { void hashMap() { HashMap hashMap = new HashMap<>(); hashMap.put("a", "Apple"); - hashMap.put("a", "Apple"); // Noncompliant [[secondary=60,62]] + hashMap.put("a", "Apple"); // Noncompliant hashMap.put("a", "Banana"); } void rhs(int[] arr, Map map, int i) { arr[i] = arr[i] + 1; arr[i] = arr[i] + 1; // compliant arr[i] is used on RHS - arr[i] = 3; // Noncompliant [[secondary=67,69,70]] + arr[i] = 3; // Noncompliant arr[i] = 3; arr[i] = i; arr[i++] = i; // index is not a symbol diff --git a/java-checks/src/test/files/checks/PACKAGE/BadPackageNameNoncompliant.java b/java-checks/src/test/files/checks/PACKAGE/BadPackageNameNoncompliant.java index 071eff60c96..b605f69b576 100644 --- a/java-checks/src/test/files/checks/PACKAGE/BadPackageNameNoncompliant.java +++ b/java-checks/src/test/files/checks/PACKAGE/BadPackageNameNoncompliant.java @@ -1,4 +1,5 @@ -package PACKAGE; // Noncompliant [[sc=9;ec=16]] {{Rename this package name to match the regular expression '^[a-z_]+(\.[a-z_][a-z0-9_]*)*$'.}} +package PACKAGE; // Noncompliant {{Rename this package name to match the regular expression '^[a-z_]+(\.[a-z_][a-z0-9_]*)*$'.}} +// ^^^^^^^ class BadPackageName { } diff --git a/java-checks/src/test/files/checks/PrimitiveTypeBoxingWithToStringCheck.java b/java-checks/src/test/files/checks/PrimitiveTypeBoxingWithToStringCheck.java index 17e512aa452..882ebc2b477 100644 --- a/java-checks/src/test/files/checks/PrimitiveTypeBoxingWithToStringCheck.java +++ b/java-checks/src/test/files/checks/PrimitiveTypeBoxingWithToStringCheck.java @@ -9,11 +9,13 @@ void foo() { int myInt = 4; boolean myBoolean = true; - new Integer(myInt).toString(); // Noncompliant [[sc=5;ec=34]] {{Use "Integer.toString" instead.}} + new Integer(myInt).toString(); // Noncompliant {{Use "Integer.toString" instead.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Integer.toString(myInt); // Compliant A.returnInteger(myInt).toString(); // Compliant Integer.valueOf(myInt).toString(); // Noncompliant {{Use "Integer.toString" instead.}} - bar(new Integer(myInt).toString()); // Noncompliant [[sc=9;ec=38]] {{Use "Integer.toString" instead.}} + bar(new Integer(myInt).toString()); // Noncompliant {{Use "Integer.toString" instead.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ new Boolean(myBoolean).toString(); // Noncompliant {{Use "Boolean.toString" instead.}} Boolean.toString(myBoolean); // Compliant diff --git a/java-checks/src/test/files/checks/ProtectedMemberInFinalClassCheck.java b/java-checks/src/test/files/checks/ProtectedMemberInFinalClassCheck.java index 8ed4e09c403..bb8d9caf1a0 100644 --- a/java-checks/src/test/files/checks/ProtectedMemberInFinalClassCheck.java +++ b/java-checks/src/test/files/checks/ProtectedMemberInFinalClassCheck.java @@ -10,7 +10,8 @@ final class A { void method1() {} private void method2() {} - protected void // Noncompliant [[sc=3;ec=12]] {{Remove this "protected" modifier.}} + protected void // Noncompliant {{Remove this "protected" modifier.}} +//^^^^^^^^^ method3() {} public void method4() {} } diff --git a/java-checks/src/test/files/checks/PublicStaticFieldShouldBeFinalCheck.java b/java-checks/src/test/files/checks/PublicStaticFieldShouldBeFinalCheck.java index d21fd4606fe..eba969135fb 100644 --- a/java-checks/src/test/files/checks/PublicStaticFieldShouldBeFinalCheck.java +++ b/java-checks/src/test/files/checks/PublicStaticFieldShouldBeFinalCheck.java @@ -1,6 +1,7 @@ public class Greeter { - public static Foo foo = new Foo(); // Noncompliant {{Make this "public static foo" field final}} [[sc=21;ec=24]] + public static Foo foo = new Foo(); // Noncompliant {{Make this "public static foo" field final}} +// ^^^ public static final Bar bar = new Bar(); // Compliant public final Bar bar2 = new Bar(); // Compliant diff --git a/java-checks/src/test/files/checks/RedundantStreamCollectCheck.java b/java-checks/src/test/files/checks/RedundantStreamCollectCheck.java index e2bea23e045..8a7367e340c 100644 --- a/java-checks/src/test/files/checks/RedundantStreamCollectCheck.java +++ b/java-checks/src/test/files/checks/RedundantStreamCollectCheck.java @@ -21,8 +21,8 @@ void test(Stream stream, BinaryOperator binaryOperator, Comparat stream.collect(maxBy(comparator)); // Noncompliant {{Use "max()" instead.}} stream.collect(minBy(comparator)); // Noncompliant {{Use "min()" instead.}} stream.collect(mapping(Object::toString, Collectors.toList())); // Noncompliant {{Use "map(...).collect()" instead.}} - stream.collect(reducing(binaryOperator)); // Noncompliant {{Use "reduce(...).collect()" instead.}} - stream.collect(summingInt(Object::hashCode)); // Noncompliant {{Use "mapToInt(...).sum()" instead.}} + stream.collect(reducing(binaryOperator)); // Noncompliant {{Use "reduce(...).collect()" instead.}} + stream.collect(summingInt(Object::hashCode)); // Noncompliant {{Use "mapToInt(...).sum()" instead.}} stream.collect(summingLong(Object::hashCode)); // Noncompliant {{Use "mapToLong(...).sum()" instead.}} stream.collect(summingDouble(Object::hashCode)); // Noncompliant {{Use "mapToDouble(...).sum()" instead.}} } diff --git a/java-checks/src/test/files/checks/RepeatAnnotationCheck.java b/java-checks/src/test/files/checks/RepeatAnnotationCheck.java index b2a867ba3d3..d726fd673e1 100644 --- a/java-checks/src/test/files/checks/RepeatAnnotationCheck.java +++ b/java-checks/src/test/files/checks/RepeatAnnotationCheck.java @@ -1,5 +1,6 @@ class A{ - @SomeAnnotations({ // Noncompliant [[sc=4;ec=19]] {{Remove the 'SomeAnnotations' wrapper from this annotation group}} + @SomeAnnotations({ // Noncompliant {{Remove the 'SomeAnnotations' wrapper from this annotation group}} +// ^^^^^^^^^^^^^^^ @SomeAnnotation("a"), @SomeAnnotation("b"), @SomeAnnotation("c"), diff --git a/java-checks/src/test/files/checks/RepeatAnnotationCheck_no_version.java b/java-checks/src/test/files/checks/RepeatAnnotationCheck_no_version.java index 20ca1fb0687..94c6cc394d9 100644 --- a/java-checks/src/test/files/checks/RepeatAnnotationCheck_no_version.java +++ b/java-checks/src/test/files/checks/RepeatAnnotationCheck_no_version.java @@ -31,4 +31,4 @@ void methodThree(){} @interface SomeAnnotation { } -} \ No newline at end of file +} diff --git a/java-checks/src/test/files/checks/ReplaceGuavaWithJava8Check_no_version.java b/java-checks/src/test/files/checks/ReplaceGuavaWithJava8Check_no_version.java index ce7d03ed937..800826c4816 100644 --- a/java-checks/src/test/files/checks/ReplaceGuavaWithJava8Check_no_version.java +++ b/java-checks/src/test/files/checks/ReplaceGuavaWithJava8Check_no_version.java @@ -1,3 +1,4 @@ class A { - A(com.google.common.base.Predicate p) {} // Noncompliant [[sc=5;ec=37]] {{Use "java.util.function.Predicate" instead. (sonar.java.source not set. Assuming 8 or greater.)}} + A(com.google.common.base.Predicate p) {} // Noncompliant {{Use "java.util.function.Predicate" instead. (sonar.java.source not set. Assuming 8 or greater.)}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } diff --git a/java-checks/src/test/files/checks/ReturnInFinallyCheck.java b/java-checks/src/test/files/checks/ReturnInFinallyCheck.java index 97375107b16..299bf76bca7 100644 --- a/java-checks/src/test/files/checks/ReturnInFinallyCheck.java +++ b/java-checks/src/test/files/checks/ReturnInFinallyCheck.java @@ -5,7 +5,8 @@ private void f() { } catch (Exception e) { return; // Compliant } finally { - return; // Noncompliant [[sc=7;ec=13]] {{Remove this return statement from this finally block.}} + return; // Noncompliant {{Remove this return statement from this finally block.}} +// ^^^^^^ } try { @@ -36,14 +37,16 @@ public void foo() { } catch (Exception e) { return; // Compliant } finally { - continue; // Noncompliant [[sc=9;ec=17]] {{Remove this continue statement from this finally block.}} + continue; // Noncompliant {{Remove this continue statement from this finally block.}} +// ^^^^^^^^ } try { return; // Compliant } catch (Exception e) { return; // Compliant } finally { - break; // Noncompliant [[sc=9;ec=14]] {{Remove this break statement from this finally block.}} + break; // Noncompliant {{Remove this break statement from this finally block.}} +// ^^^^^ } } @@ -52,7 +55,8 @@ public void foo() { } catch (Exception e) { return; // Compliant } finally { - throw new Exception(); // Noncompliant [[sc=7;ec=12]] {{Remove this throw statement from this finally block.}} + throw new Exception(); // Noncompliant {{Remove this throw statement from this finally block.}} +// ^^^^^ } } } diff --git a/java-checks/src/test/files/checks/ReturnOfBooleanExpressionsCheck.java b/java-checks/src/test/files/checks/ReturnOfBooleanExpressionsCheck.java index c38130ce28d..aab092722ad 100644 --- a/java-checks/src/test/files/checks/ReturnOfBooleanExpressionsCheck.java +++ b/java-checks/src/test/files/checks/ReturnOfBooleanExpressionsCheck.java @@ -1,6 +1,7 @@ class A { void foo() { - if (something) { // Noncompliant [[sc=5;ec=7]] {{Replace this if-then-else statement by a single return statement.}} + if (something) { // Noncompliant {{Replace this if-then-else statement by a single return statement.}} +// ^^ return true; } else { return false; diff --git a/java-checks/src/test/files/checks/RightCurlyBraceDifferentLineAsNextBlockCheck.java b/java-checks/src/test/files/checks/RightCurlyBraceDifferentLineAsNextBlockCheck.java index 4019faabc7d..05a6803e847 100644 --- a/java-checks/src/test/files/checks/RightCurlyBraceDifferentLineAsNextBlockCheck.java +++ b/java-checks/src/test/files/checks/RightCurlyBraceDifferentLineAsNextBlockCheck.java @@ -2,7 +2,8 @@ class Foo { public void myMethod() { if(something) { executeTask(); - } else if (somethingElse) { // Noncompliant [[sc=7;ec=11]] {{Move this "else" keyword to a new dedicated line.}} + } else if (somethingElse) { // Noncompliant {{Move this "else" keyword to a new dedicated line.}} +// ^^^^ doSomethingElse(); } else { // Compliant @@ -17,7 +18,7 @@ public void myMethod() { try { generateOrder(); - } catch (Exception e) { // Noncompliant {{Move this "catch" keyword to a new dedicated line.}} + } catch (Exception e) { // Noncompliant {{Move this "catch" keyword to a new dedicated line.}} log(e); } finally { // Compliant diff --git a/java-checks/src/test/files/checks/RightCurlyBraceStartLineCheck.java b/java-checks/src/test/files/checks/RightCurlyBraceStartLineCheck.java index f01c2f32d49..976fbaef2e8 100644 --- a/java-checks/src/test/files/checks/RightCurlyBraceStartLineCheck.java +++ b/java-checks/src/test/files/checks/RightCurlyBraceStartLineCheck.java @@ -9,13 +9,14 @@ class Foo { public void myMethod() throws IOException { if(something) { - executeTask();} // Noncompliant [[sc=21;ec=22]] {{Move this closing curly brace to the next line.}} + executeTask();} // Noncompliant {{Move this closing curly brace to the next line.}} +// ^ else if (somethingElse) { doSomethingElse(); } if (0) { - ; } else if (0) { // Noncompliant {{Move this closing curly brace to the next line.}} + ; } else if (0) { // Noncompliant {{Move this closing curly brace to the next line.}} } else { } @@ -35,34 +36,34 @@ public void foo2() { } public void foo3(boolean test) { if (test) { - }} // Noncompliant {{Move this closing curly brace to the next line.}} + }} // Noncompliant {{Move this closing curly brace to the next line.}} public void foo4(boolean test) { if (test) { } else { - return; } // Noncompliant {{Move this closing curly brace to the next line.}} + return; } // Noncompliant {{Move this closing curly brace to the next line.}} } public void foo5() { - assert true;} // Noncompliant {{Move this closing curly brace to the next line.}} + assert true;} // Noncompliant {{Move this closing curly brace to the next line.}} public void foo6() { try (InputStream is = new FileInputStream("")){ - }} // Noncompliant {{Move this closing curly brace to the next line.}} + }} // Noncompliant {{Move this closing curly brace to the next line.}} public void foo7() { try (InputStream is = new FileInputStream("")){ } finally { - }} // Noncompliant {{Move this closing curly brace to the next line.}} + }} // Noncompliant {{Move this closing curly brace to the next line.}} public void foo8(int test) { switch(test) { - } } // Noncompliant {{Move this closing curly brace to the next line.}} + } } // Noncompliant {{Move this closing curly brace to the next line.}} public void foo9(boolean test) { if(test) { do { - } while(true); } // Noncompliant {{Move this closing curly brace to the next line.}} + } while(true); } // Noncompliant {{Move this closing curly brace to the next line.}} if(test) { while(true) { break; } } @@ -71,36 +72,36 @@ public void foo9(boolean test) { public void foo10(boolean test, List list) { if (test) { for (int i = 0; i < array.length; i++) { - }} // Noncompliant {{Move this closing curly brace to the next line.}} + }} // Noncompliant {{Move this closing curly brace to the next line.}} if (test) { for (Object object : list) { - }} // Noncompliant {{Move this closing curly brace to the next line.}} + }} // Noncompliant {{Move this closing curly brace to the next line.}} } public void foo11() throws IOException { - throw new IOException(); } // Noncompliant {{Move this closing curly brace to the next line.}} + throw new IOException(); } // Noncompliant {{Move this closing curly brace to the next line.}} public void foo12() { synchronized (new Object()) { - }} // Noncompliant {{Move this closing curly brace to the next line.}} + }} // Noncompliant {{Move this closing curly brace to the next line.}} public void foo13() { class InnerClass { - }} // Noncompliant {{Move this closing curly brace to the next line.}} + }} // Noncompliant {{Move this closing curly brace to the next line.}} public void foo14() { - int i; } // Noncompliant {{Move this closing curly brace to the next line.}} + int i; } // Noncompliant {{Move this closing curly brace to the next line.}} public int foo15() { - return 0; } // Noncompliant {{Move this closing curly brace to the next line.}} + return 0; } // Noncompliant {{Move this closing curly brace to the next line.}} public void foo16() { while (true) { - break; } // Noncompliant {{Move this closing curly brace to the next line.}} + break; } // Noncompliant {{Move this closing curly brace to the next line.}} } public void fooLast() { - }} // Noncompliant {{Move this closing curly brace to the next line.}} + }} // Noncompliant {{Move this closing curly brace to the next line.}} @Properties({}) class Exceptions { @@ -118,7 +119,7 @@ class Bar { class EmptyClass {} abstract class AbstractClass { - abstract void foo();} // Noncompliant {{Move this closing curly brace to the next line.}} + abstract void foo();} // Noncompliant {{Move this closing curly brace to the next line.}} @interface XmlIDREF {} @@ -128,4 +129,4 @@ enum XmlNsForm {UNQUALIFIED, QUALIFIED, UNSET } enum MyEnum {A, B, C { - }} // Noncompliant {{Move this closing curly brace to the next line.}} + }} // Noncompliant {{Move this closing curly brace to the next line.}} diff --git a/java-checks/src/test/files/checks/SelectorMethodArgumentCheck.java b/java-checks/src/test/files/checks/SelectorMethodArgumentCheck.java index 97ba857046f..13263532230 100644 --- a/java-checks/src/test/files/checks/SelectorMethodArgumentCheck.java +++ b/java-checks/src/test/files/checks/SelectorMethodArgumentCheck.java @@ -1,5 +1,6 @@ class A { - public void tempt(String name, boolean ofAge) { // Noncompliant [[sc=15;ec=20]] {{Provide multiple methods instead of using "ofAge" to determine which action to take.}} + public void tempt(String name, boolean ofAge) { // Noncompliant {{Provide multiple methods instead of using "ofAge" to determine which action to take.}} +// ^^^^^ if (ofAge) { offerLiquor(name); } else { @@ -34,7 +35,7 @@ public void attempt(String name, int size, boolean isNice) { // Compliant } abstract class B { - // Noncompliant@+1 + // Noncompliant@+1 public int foo(int a, boolean b, boolean c) { // Noncompliant if (b) { } else { diff --git a/java-checks/src/test/files/checks/SeveralBreakOrContinuePerLoopCheck.java b/java-checks/src/test/files/checks/SeveralBreakOrContinuePerLoopCheck.java index 17d6e6e2031..6bf4a494811 100644 --- a/java-checks/src/test/files/checks/SeveralBreakOrContinuePerLoopCheck.java +++ b/java-checks/src/test/files/checks/SeveralBreakOrContinuePerLoopCheck.java @@ -7,9 +7,12 @@ private void f() { break; } - for (int i = 0; i < 42; i++) { // Noncompliant {{Reduce the total number of break and continue statements in this loop to use at most one.}} [[sc=5;ec=8;secondary=11,12]] + for (int i = 0; i < 42; i++) { // Noncompliant {{Reduce the total number of break and continue statements in this loop to use at most one.}} +// ^^^ break; +// ^^^^^^< break; +// ^^^^^^< } for (int i = 0; i < 42; i++) { // Noncompliant @@ -17,9 +20,12 @@ private void f() { continue; } - while (true) { // Noncompliant [[sc=5;ec=10;secondary=21,22]] + while (true) { // Noncompliant +// ^^^^^ continue; +// ^^^^^^^^^< continue; +// ^^^^^^^^^< } for (Integer a: a) { // Compliant @@ -33,12 +39,16 @@ private void f() { break; } - do { // Noncompliant [[sc=5;ec=7;secondary=37,40,41]] + do { // Noncompliant +// ^^ break; +// ^^^^^^< switch (foo) { case 0: continue; +// ^^^^^^^^^< continue; +// ^^^^^^^^^< case 0: break; break; diff --git a/java-checks/src/test/files/checks/SpringConstructorInjectionCheck.java b/java-checks/src/test/files/checks/SpringConstructorInjectionCheck.java index d4228131315..4e8afe65d23 100644 --- a/java-checks/src/test/files/checks/SpringConstructorInjectionCheck.java +++ b/java-checks/src/test/files/checks/SpringConstructorInjectionCheck.java @@ -4,13 +4,16 @@ @Repository public class HelloWorld { - @Autowired// Noncompliant [[secondary=10,13]] {{Remove this annotation and use constructor injection instead.}} + @Autowired // Noncompliant {{Remove this annotation and use constructor injection instead.}} +//^^^^^^^^^^ private String name = null; @Autowired +//^^^^^^^^^^< private String surname = null; HelloWorld() { +//^^^^^^^^^^< } } @@ -28,9 +31,11 @@ public class HelloWorld2 { @Service public class HelloWorld3 { - @Autowired// Noncompliant [[secondary=34]] {{Remove this annotation and use constructor injection instead.}} + @Autowired // Noncompliant {{Remove this annotation and use constructor injection instead.}} +//^^^^^^^^^^ private String name = null; @Autowired +//^^^^^^^^^^< private String surname = null; } diff --git a/java-checks/src/test/files/checks/StaticFieldInitializationCheck.java b/java-checks/src/test/files/checks/StaticFieldInitializationCheck.java index af69789e603..68a0e3ab16d 100644 --- a/java-checks/src/test/files/checks/StaticFieldInitializationCheck.java +++ b/java-checks/src/test/files/checks/StaticFieldInitializationCheck.java @@ -6,7 +6,8 @@ public static Object getInstance() { return instance; } - instance = new Object(); // Noncompliant [[sc=5;ec=13]] {{Synchronize this lazy initialization of 'instance'}} + instance = new Object(); // Noncompliant {{Synchronize this lazy initialization of 'instance'}} +// ^^^^^^^^ return instance; } @@ -115,7 +116,7 @@ class C { public static void resetConfiguration2() { try { - CONFIG = null; // Noncompliant : before the lock + CONFIG = null; // Noncompliant LOCK.tryLock(); } finally { LOCK.unlock(); diff --git a/java-checks/src/test/files/checks/StaticImportCountCheck/MixedStandardAndStaticImports.java b/java-checks/src/test/files/checks/StaticImportCountCheck/MixedStandardAndStaticImports.java index 57f38915aa2..fefce056d19 100644 --- a/java-checks/src/test/files/checks/StaticImportCountCheck/MixedStandardAndStaticImports.java +++ b/java-checks/src/test/files/checks/StaticImportCountCheck/MixedStandardAndStaticImports.java @@ -2,10 +2,18 @@ import java.util.Collections; import java.util.List; -import static java.lang.Math.*; // Noncompliant [[sc=1;ec=32;secondary=5,6,7,8,9,10,11]] {{Reduce the number of "static" imports in this class from 7 to the maximum allowed 4.}} +import static java.lang.Math.*; // Noncompliant {{Reduce the number of "static" imports in this class from 7 to the maximum allowed 4.}} +//^[sc=1;ec=31] +//^[sc=1;ec=31]@-1< import static java.util.Collections.*; +//^[sc=1;ec=38]< import static com.myco.corporate.Constants.*; +//^[sc=1;ec=45]< import static com.myco.division.Constants.*; +//^[sc=1;ec=44]< import static com.myco.department.Constants.*; +//^[sc=1;ec=46]< import static com.myco.department.Constants.*; +//^[sc=1;ec=46]< import static com.myco.department.Constants.*; +//^[sc=1;ec=46]< diff --git a/java-checks/src/test/files/checks/StaticImportCountCheck/MixedStandardAndStaticImportsCustomThreshold.java b/java-checks/src/test/files/checks/StaticImportCountCheck/MixedStandardAndStaticImportsCustomThreshold.java index 1b556862da5..b7228b7ce98 100644 --- a/java-checks/src/test/files/checks/StaticImportCountCheck/MixedStandardAndStaticImportsCustomThreshold.java +++ b/java-checks/src/test/files/checks/StaticImportCountCheck/MixedStandardAndStaticImportsCustomThreshold.java @@ -2,8 +2,14 @@ import java.util.Collections; import java.util.List; -import static java.lang.Math.*; // Noncompliant [[sc=1;ec=32;secondary=5,6,7,8,9]] {{Reduce the number of "static" imports in this class from 5 to the maximum allowed 3.}} -import static java.util.Collections.*; -import static com.myco.corporate.Constants.*; -import static com.myco.division.Constants.*; -import static com.myco.department.Constants.*; + import static java.lang.Math.*; // Noncompliant {{Reduce the number of "static" imports in this class from 5 to the maximum allowed 3.}} +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^@-1< + import static java.util.Collections.*; +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< + import static com.myco.corporate.Constants.*; +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< + import static com.myco.division.Constants.*; +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< + import static com.myco.department.Constants.*; +//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^< diff --git a/java-checks/src/test/files/checks/StaticImportCountCheck/StaticImportCountCheck.java b/java-checks/src/test/files/checks/StaticImportCountCheck/StaticImportCountCheck.java index 4f869fd007c..7c9b04e5aab 100644 --- a/java-checks/src/test/files/checks/StaticImportCountCheck/StaticImportCountCheck.java +++ b/java-checks/src/test/files/checks/StaticImportCountCheck/StaticImportCountCheck.java @@ -1,7 +1,15 @@ -import static java.lang.Math.*; // Noncompliant [[sc=1;ec=32;secondary=1,2,3,4,5,6,7]] {{Reduce the number of "static" imports in this class from 7 to the maximum allowed 4.}} +import static java.lang.Math.*; // Noncompliant {{Reduce the number of "static" imports in this class from 7 to the maximum allowed 4.}} +//^[sc=1;ec=31] +//^[sc=1;ec=31]@-1< import static java.util.Collections.*; +//^[sc=1;ec=38]< import static com.myco.corporate.Constants.*; +//^[sc=1;ec=45]< import static com.myco.division.Constants.*; +//^[sc=1;ec=44]< import static com.myco.department.Constants.*; +//^[sc=1;ec=46]< import static com.myco.department.Constants.*; +//^[sc=1;ec=46]< import static com.myco.department.Constants.*; +//^[sc=1;ec=46]< diff --git a/java-checks/src/test/files/checks/StaticMembersAccessCheck.java b/java-checks/src/test/files/checks/StaticMembersAccessCheck.java index 1666387de68..25b3a5f7bca 100644 --- a/java-checks/src/test/files/checks/StaticMembersAccessCheck.java +++ b/java-checks/src/test/files/checks/StaticMembersAccessCheck.java @@ -32,7 +32,8 @@ public A.D d() { } public void noncompliant() { - first.counter ++; // Noncompliant [[sc=5;ec=18]] {{Change this instance-reference to a static reference.}} + first.counter ++; // Noncompliant {{Change this instance-reference to a static reference.}} +// ^^^^^^^^^^^^^ second.counter ++; // Noncompliant second.method(); // Noncompliant third.counter ++; // Noncompliant @@ -40,7 +41,8 @@ public void noncompliant() { first.c.d.counter++; // Noncompliant first.d().counter++; // Noncompliant d().counter++; // Noncompliant - ((A.D) d()).counter++; // Noncompliant [[sc=5;ec=24]] + ((A.D) d()).counter++; // Noncompliant +// ^^^^^^^^^^^^^^^^^^^ (d()).counter++; // Noncompliant A.D[] darray = new A.D[1]; darray[0].counter++; // Noncompliant diff --git a/java-checks/src/test/files/checks/StringCallsBeyondBoundsCheck.java b/java-checks/src/test/files/checks/StringCallsBeyondBoundsCheck.java index c9f3f8502fb..bf9f2d91dbc 100644 --- a/java-checks/src/test/files/checks/StringCallsBeyondBoundsCheck.java +++ b/java-checks/src/test/files/checks/StringCallsBeyondBoundsCheck.java @@ -6,90 +6,90 @@ void f(String aString) { "".charAt("".length()); "".charAt("".length() - 1); - "".charAt(0); // Noncompliant - "".charAt(-1); // Noncompliant + "".charAt(0); // Noncompliant + "".charAt(-1); // Noncompliant "".charAt(minusOne); str.charAt(str.hashCode()); - str.charAt(str.length()); // Noncompliant + str.charAt(str.length()); // Noncompliant str.charAt(str.length() - 1); str.charAt(0); - str.charAt(-1); // Noncompliant + str.charAt(-1); // Noncompliant str.charAt(minusOne); aString.charAt(aString.length()); // Noncompliant - str.codePointAt(str.length()); // Noncompliant + str.codePointAt(str.length()); // Noncompliant str.codePointAt(str.length() - 1); str.codePointAt(0); "str".codePointAt(0); - str.codePointAt(-1); // Noncompliant + str.codePointAt(-1); // Noncompliant str.codePointAt(minusOne); aString.codePointAt(aString.length()); // Noncompliant str.codePointCount(0, str.length()); str.codePointCount(0, str.length() - 1); - str.codePointCount(-1, str.length()); // Noncompliant + str.codePointCount(-1, str.length()); // Noncompliant str.codePointCount(minusOne, str.length()); - str.codePointCount(5, 0); // Noncompliant + str.codePointCount(5, 0); // Noncompliant str.codePointCount(0, 25); - "str".codePointCount(0, 25); // Noncompliant + "str".codePointCount(0, 25); // Noncompliant str.codePointBefore(str.length()); str.codePointBefore(25); - "str".codePointBefore(25); // Noncompliant + "str".codePointBefore(25); // Noncompliant str.codePointBefore(1); "str".codePointBefore(1); - str.codePointBefore(0); // Noncompliant + str.codePointBefore(0); // Noncompliant str.codePointBefore(zero); - str.getChars(str.length(), 0, array, 0); // Noncompliant + str.getChars(str.length(), 0, array, 0); // Noncompliant str.getChars(0, str.length(), array, 0); - str.getChars(-1, str.length(), array, 0); // Noncompliant + str.getChars(-1, str.length(), array, 0); // Noncompliant str.getChars(minusOne, str.length(), array, 0); - str.getChars(5, 0, array, 0); // Noncompliant + str.getChars(5, 0, array, 0); // Noncompliant str.getChars(0, 25, array, 0); - "str".getChars(0, 25, array, 0); // Noncompliant + "str".getChars(0, 25, array, 0); // Noncompliant "str".getChars(0, 2, array, 0); - str.getChars(0, str.length(), array, -1); // Noncompliant + str.getChars(0, str.length(), array, -1); // Noncompliant str.getChars(0, str.length(), array, minusOne); - str.offsetByCodePoints(str.length(), any); // Noncompliant + str.offsetByCodePoints(str.length(), any); // Noncompliant str.offsetByCodePoints(25, any); str.offsetByCodePoints(0, any); "str".offsetByCodePoints(any, any + 5); "str".offsetByCodePoints(0, any); - "str".offsetByCodePoints(25, any); // Noncompliant - str.offsetByCodePoints(-1, any); // Noncompliant + "str".offsetByCodePoints(25, any); // Noncompliant + str.offsetByCodePoints(-1, any); // Noncompliant str.offsetByCodePoints(minusOne, any); str.subSequence(0, str.length()); - str.subSequence(-1, str.length()); // Noncompliant - str.subSequence(str.length(), 0); // Noncompliant + str.subSequence(-1, str.length()); // Noncompliant + str.subSequence(str.length(), 0); // Noncompliant str.subSequence(minusOne, str.length()); - str.subSequence(0, -1); // Noncompliant - str.subSequence(5, 0); // Noncompliant + str.subSequence(0, -1); // Noncompliant + str.subSequence(5, 0); // Noncompliant str.subSequence(0, 25); - "str".subSequence(0, 25); // Noncompliant + "str".subSequence(0, 25); // Noncompliant "str".subSequence(0, 2); "str".subSequence(minusOne, str.length()); str.substring(str.length()); // Noncompliant str.substring(25); - "str".substring(25); // Noncompliant + "str".substring(25); // Noncompliant "str".substring(1); str.substring(0); - str.substring(-1); // Noncompliant + str.substring(-1); // Noncompliant str.substring(minusOne); str.substring(0, str.length()); - str.substring(str.length(), 0); // Noncompliant - str.substring(-1, str.length()); // Noncompliant + str.substring(str.length(), 0); // Noncompliant + str.substring(-1, str.length()); // Noncompliant str.substring(minusOne, str.length()); - str.substring(0, -1); // Noncompliant - str.substring(5, 0); // Noncompliant + str.substring(0, -1); // Noncompliant + str.substring(5, 0); // Noncompliant str.substring(0, 25); - "str".substring(0, 25); // Noncompliant + "str".substring(0, 25); // Noncompliant } } diff --git a/java-checks/src/test/files/checks/SuppressWarningsCheck/test1.java b/java-checks/src/test/files/checks/SuppressWarningsCheck/test1.java index a0cbf530cfe..9aa330711b9 100644 --- a/java-checks/src/test/files/checks/SuppressWarningsCheck/test1.java +++ b/java-checks/src/test/files/checks/SuppressWarningsCheck/test1.java @@ -1,31 +1,33 @@ -@SuppressWarnings("unused") // Noncompliant [[sc=2;ec=18]] {{Suppressing warnings is not allowed}} + + @SuppressWarnings("unused") // Noncompliant {{Suppressing warnings is not allowed}} +// ^^^^^^^^^^^^^^^^ class A { - + private final String BOXING = "boxing"; - + @SuppressWarnings("all") // Noncompliant private void f() { } - + @SuppressWarnings({"unchecked", "cast"}) // Noncompliant private void g() { } - + @SuppressWarnings(BOXING) // Noncompliant private void h() { } - + @SuppressWarnings({BOXING, "all"}) // Noncompliant private void i() { } - + @SuppressWarnings("boxing") // Noncompliant private void j() { } - + @Override private String toString() { return ""; } - + } diff --git a/java-checks/src/test/files/checks/SwitchAtLeastThreeCasesCheck.java b/java-checks/src/test/files/checks/SwitchAtLeastThreeCasesCheck.java index eb307feb914..9912576657a 100644 --- a/java-checks/src/test/files/checks/SwitchAtLeastThreeCasesCheck.java +++ b/java-checks/src/test/files/checks/SwitchAtLeastThreeCasesCheck.java @@ -35,7 +35,8 @@ void goo(Shape shape) { } public void f() { - switch (variable) { // Noncompliant [[sc=5;ec=11]] {{Replace this "switch" statement by "if" statements to increase readability.}} + switch (variable) { // Noncompliant {{Replace this "switch" statement by "if" statements to increase readability.}} +// ^^^^^^ case 0: doSomething(); break; diff --git a/java-checks/src/test/files/checks/SwitchCaseWithoutBreakCheck.java b/java-checks/src/test/files/checks/SwitchCaseWithoutBreakCheck.java index d2b82368df5..a919c1eccb0 100644 --- a/java-checks/src/test/files/checks/SwitchCaseWithoutBreakCheck.java +++ b/java-checks/src/test/files/checks/SwitchCaseWithoutBreakCheck.java @@ -9,11 +9,13 @@ private void f(byte b, char c) { int myVariable = 0; switch (myVariable) { case 0: - case 1: // Noncompliant {{End this switch case with an unconditional break, return or throw statement.}} [[sc=7;ec=14]] + case 1: // Noncompliant {{End this switch case with an unconditional break, return or throw statement.}} +// ^^^^^^^ System.out.println("Test"); case 2: // Compliant break; - case (8 | 2): // Noncompliant {{End this switch case with an unconditional break, return or throw statement.}} [[sc=7;ec=20]] + case (8 | 2): // Noncompliant {{End this switch case with an unconditional break, return or throw statement.}} +// ^^^^^^^^^^^^^ System.out.println("Test"); case 3: // Compliant return; @@ -104,11 +106,13 @@ private void f(byte b, char c) { switch (b) { case (byte) 0: // Compliant break; - case (byte) 1: // Noncompliant {{End this switch case with an unconditional break, return or throw statement.}} [[sc=7;ec=21]] + case (byte) 1: // Noncompliant {{End this switch case with an unconditional break, return or throw statement.}} +// ^^^^^^^^^^^^^^ System.out.println("Test"); case 2: // Compliant break; - case 3: // Noncompliant {{End this switch case with an unconditional break, return or throw statement.}} [[sc=7;ec=14]] + case 3: // Noncompliant {{End this switch case with an unconditional break, return or throw statement.}} +// ^^^^^^^ System.out.println("Test 2"); case 4: break; @@ -117,11 +121,13 @@ private void f(byte b, char c) { switch (c) { case 'c': // Compliant break; - case 'a': // Noncompliant {{End this switch case with an unconditional break, return or throw statement.}} [[sc=7;ec=16]] + case 'a': // Noncompliant {{End this switch case with an unconditional break, return or throw statement.}} +// ^^^^^^^^^ System.out.println("Test"); case 'd': // Compliant break; - case 'e': // Noncompliant {{End this switch case with an unconditional break, return or throw statement.}} [[sc=7;ec=16]] + case 'e': // Noncompliant {{End this switch case with an unconditional break, return or throw statement.}} +// ^^^^^^^^^ System.out.println("Test 2"); case 'x': break; diff --git a/java-checks/src/test/files/checks/SymmetricEqualsCheck.java b/java-checks/src/test/files/checks/SymmetricEqualsCheck.java index d7ea6d113e1..c9a108b153d 100644 --- a/java-checks/src/test/files/checks/SymmetricEqualsCheck.java +++ b/java-checks/src/test/files/checks/SymmetricEqualsCheck.java @@ -5,15 +5,18 @@ public boolean equals(Object obj) { if (obj == this) { return true; } - if (Fruit.class == obj.getClass()) { // Noncompliant [[sc=9;ec=20]] {{Compare to "this.getClass()" instead.}} + if (Fruit.class == obj.getClass()) { // Noncompliant {{Compare to "this.getClass()" instead.}} +// ^^^^^^^^^^^ return ripe.equals(((Fruit) obj).getRipe()); } - if (obj instanceof Fruit) { // Noncompliant [[sc=9;ec=29]] {{Compare to "this.getClass()" instead.}} + if (obj instanceof Fruit) { // Noncompliant {{Compare to "this.getClass()" instead.}} +// ^^^^^^^^^^^^^^^^^^^^ return ripe.equals(((Fruit) obj).getRipe()); - } else if (obj instanceof Season) { // Noncompliant [[sc=16;ec=37]] {{Remove this comparison to an unrelated class.}} + } else if (obj instanceof Season) { // Noncompliant {{Remove this comparison to an unrelated class.}} +// ^^^^^^^^^^^^^^^^^^^^^ // ... } - if (Fruit.class != obj.getClass()) { // Noncompliant broken for child classes + if (Fruit.class != obj.getClass()) { // Noncompliant } } } @@ -45,7 +48,8 @@ public boolean equals(Object j) { if (Foo.class==obj.getClass()){ // Noncompliant } - if (obj instanceof Season) { // Noncompliant [[sc=13;ec=34]] symmetry broken for Season class + if (obj instanceof Season) { // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^ // ... } return false; @@ -109,7 +113,8 @@ public boolean equals(Object obj) { return f.equals(((MyObject) obj).f); } - if (obj.getClass() == String.class) { // Noncompliant [[sc=27;ec=39]] {{Remove this comparison to an unrelated class.}} + if (obj.getClass() == String.class) { // Noncompliant {{Remove this comparison to an unrelated class.}} +// ^^^^^^^^^^^^ return f.equals(obj.toString()); } if (obj.getClass() == Parent.class) { // Noncompliant diff --git a/java-checks/src/test/files/checks/SynchronizationOnGetClassCheck.java b/java-checks/src/test/files/checks/SynchronizationOnGetClassCheck.java index 7fb65b2213f..1a03e8ad7a5 100644 --- a/java-checks/src/test/files/checks/SynchronizationOnGetClassCheck.java +++ b/java-checks/src/test/files/checks/SynchronizationOnGetClassCheck.java @@ -1,22 +1,26 @@ class MyClass { MyClass() { - synchronized (getClass()) { // Noncompliant [[sc=19;ec=29]] {{Synchronize on the static class name instead.}} + synchronized (getClass()) { // Noncompliant {{Synchronize on the static class name instead.}} +// ^^^^^^^^^^ } } public void methodInvocationSynchronizedExpr() { - synchronized (getClass()) { // Noncompliant [[sc=19;ec=29]] {{Synchronize on the static class name instead.}} + synchronized (getClass()) { // Noncompliant {{Synchronize on the static class name instead.}} +// ^^^^^^^^^^ } } public void memberSelectSynchronizedExpr() { - synchronized (this.getClass()) { // Noncompliant [[sc=19;ec=34]] {{Synchronize on the static class name instead.}} + synchronized (this.getClass()) { // Noncompliant {{Synchronize on the static class name instead.}} +// ^^^^^^^^^^^^^^^ } } } class MyClassWithInitializer { { - synchronized (getClass()) { // Noncompliant [[sc=19;ec=29]] {{Synchronize on the static class name instead.}} + synchronized (getClass()) { // Noncompliant {{Synchronize on the static class name instead.}} +// ^^^^^^^^^^ } } } @@ -34,14 +38,16 @@ enum MyEnumWithInitializer { class MyClassWithStaticInitializer { static { - synchronized (getClass()) { // Noncompliant [[sc=19;ec=29]] {{Synchronize on the static class name instead.}} + synchronized (getClass()) { // Noncompliant {{Synchronize on the static class name instead.}} +// ^^^^^^^^^^ } } } class MyClassWithLambda { java.util.function.Consumer c = s -> { - synchronized (getClass()) { // Noncompliant [[sc=19;ec=29]] {{Synchronize on the static class name instead.}} + synchronized (getClass()) { // Noncompliant {{Synchronize on the static class name instead.}} +// ^^^^^^^^^^ } }; } diff --git a/java-checks/src/test/files/checks/SynchronizedFieldAssignmentCheck.java b/java-checks/src/test/files/checks/SynchronizedFieldAssignmentCheck.java index 4926cdb5ab6..f9a38d236d0 100644 --- a/java-checks/src/test/files/checks/SynchronizedFieldAssignmentCheck.java +++ b/java-checks/src/test/files/checks/SynchronizedFieldAssignmentCheck.java @@ -6,7 +6,8 @@ class A { private void doSomething() { - synchronized (color) { // Noncompliant [[sc=19;ec=24]] {{"color" is not "private final", and should not be used for synchronization. }} + synchronized (color) { // Noncompliant {{"color" is not "private final", and should not be used for synchronization. }} +// ^^^^^ color = "green"; } diff --git a/java-checks/src/test/files/checks/SystemExitCalledCheck.java b/java-checks/src/test/files/checks/SystemExitCalledCheck.java index 06ff2e3a0ca..d23f4599b89 100644 --- a/java-checks/src/test/files/checks/SystemExitCalledCheck.java +++ b/java-checks/src/test/files/checks/SystemExitCalledCheck.java @@ -4,11 +4,13 @@ class A { } void f() { - System.exit(0); // Noncompliant {{Remove this call to "exit" or ensure it is really required.}} - int a = System.exit(0); // Noncompliant [[sc=13;ec=24]] {{Remove this call to "exit" or ensure it is really required.}} + System.exit(0); // Noncompliant {{Remove this call to "exit" or ensure it is really required.}} + int a = System.exit(0); // Noncompliant {{Remove this call to "exit" or ensure it is really required.}} +// ^^^^^^^^^^^ System.gc(); // Compliant exit(); // Compliant - Runtime.getRuntime().exit(); // Noncompliant [[sc=5;ec=30]] {{Remove this call to "exit" or ensure it is really required.}} + Runtime.getRuntime().exit(); // Noncompliant {{Remove this call to "exit" or ensure it is really required.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^ Object o = Runtime.getRuntime().foo; // Compliant Runtime.getRuntime().foo(); // Compliant Runtime.getRuntime().halt(12); // Noncompliant {{Remove this call to "halt" or ensure it is really required.}} diff --git a/java-checks/src/test/files/checks/TernaryOperator.java b/java-checks/src/test/files/checks/TernaryOperator.java index c2a8b8092c0..526277a959f 100644 --- a/java-checks/src/test/files/checks/TernaryOperator.java +++ b/java-checks/src/test/files/checks/TernaryOperator.java @@ -1,3 +1,4 @@ class A { - String s = condition ? "" : null; // Noncompliant [[sc=24;ec=25]] {{Convert this usage of the ternary operator to an "if"/"else" structure.}} + String s = condition ? "" : null; // Noncompliant {{Convert this usage of the ternary operator to an "if"/"else" structure.}} +// ^ } diff --git a/java-checks/src/test/files/checks/ThisExposedFromConstructorCheck.java b/java-checks/src/test/files/checks/ThisExposedFromConstructorCheck.java index 015cd098d7c..40494c26888 100644 --- a/java-checks/src/test/files/checks/ThisExposedFromConstructorCheck.java +++ b/java-checks/src/test/files/checks/ThisExposedFromConstructorCheck.java @@ -16,7 +16,7 @@ class A extends B { A[] as = new A[1]; public A() { - list.add(this); // Noncompliant [sc=16;ec=20] {{Make sure the use of "this" doesn't expose partially-constructed instances of this class in multi-threaded environments.}} + list.add(this); // Noncompliant {{Make sure the use of "this" doesn't expose partially-constructed instances of this class in multi-threaded environments.}} tempVal = this; // Compliant this.tempVal = this; // Compliant diff --git a/java-checks/src/test/files/checks/ThreadLocalWithInitialCheck.java b/java-checks/src/test/files/checks/ThreadLocalWithInitialCheck.java index 2dd2d36190c..9ccd33a8274 100644 --- a/java-checks/src/test/files/checks/ThreadLocalWithInitialCheck.java +++ b/java-checks/src/test/files/checks/ThreadLocalWithInitialCheck.java @@ -3,7 +3,8 @@ class A { ThreadLocal> myThreadLocal = - new ThreadLocal>() { // Noncompliant [[sc=9;ec=34]] {{Replace this anonymous class with a call to "ThreadLocal.withInitial". (sonar.java.source not set. Assuming 8 or greater.)}} + new ThreadLocal>() { // Noncompliant {{Replace this anonymous class with a call to "ThreadLocal.withInitial". (sonar.java.source not set. Assuming 8 or greater.)}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^ @Override protected List initialValue() { return new ArrayList(); diff --git a/java-checks/src/test/files/checks/ThrowCheckedExceptionCheck.java b/java-checks/src/test/files/checks/ThrowCheckedExceptionCheck.java index 54657a18732..5e818778200 100644 --- a/java-checks/src/test/files/checks/ThrowCheckedExceptionCheck.java +++ b/java-checks/src/test/files/checks/ThrowCheckedExceptionCheck.java @@ -4,7 +4,8 @@ class A { void method() { throw new MyRuntimeException(); //Compliant runtime exception throw new IllegalStateException(); //Compliant runtime exception - throw new MyCheckedException(); // Noncompliant [[sc=11;ec=35]] {{Remove the usage of the checked exception 'MyCheckedException'.}} + throw new MyCheckedException(); // Noncompliant {{Remove the usage of the checked exception 'MyCheckedException'.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^ throw new IOException(); // Noncompliant {{Remove the usage of the checked exception 'IOException'.}} throw new MyError(); // Compliant not an exception } diff --git a/java-checks/src/test/files/checks/ThrowsSeveralCheckedException.java b/java-checks/src/test/files/checks/ThrowsSeveralCheckedException.java index c4215fb12b9..3f6be86e7c9 100644 --- a/java-checks/src/test/files/checks/ThrowsSeveralCheckedException.java +++ b/java-checks/src/test/files/checks/ThrowsSeveralCheckedException.java @@ -27,7 +27,8 @@ public void foo7() throws MyRuntimeException { public void foo8() throws IllegalArgumentException, MyException, NullPointerException { } - public void foo9() throws IOException, MyException { // Noncompliant [[sc=15;ec=19]] {{Refactor this method to throw at most one checked exception instead of: java.io.IOException, ThrowsSeveralCheckedException$MyException}} + public void foo9() throws IOException, MyException { // Noncompliant {{Refactor this method to throw at most one checked exception instead of: java.io.IOException, ThrowsSeveralCheckedException$MyException}} +// ^^^^ } public void foo10() throws IOException, IOException, SQLException { // Noncompliant {{Refactor this method to throw at most one checked exception instead of: java.io.IOException, java.io.IOException, java.sql.SQLException}} diff --git a/java-checks/src/test/files/checks/UndocumentedApiCheck/UndocumentedApi.java b/java-checks/src/test/files/checks/UndocumentedApiCheck/UndocumentedApi.java index 66721ffde6a..18efdfb1f5a 100644 --- a/java-checks/src/test/files/checks/UndocumentedApiCheck/UndocumentedApi.java +++ b/java-checks/src/test/files/checks/UndocumentedApiCheck/UndocumentedApi.java @@ -3,7 +3,8 @@ * some documentation */ public class UndocumentedApi { // Compliant - documented - public String p; // Noncompliant [[sc=17;ec=18]] + public String p; // Noncompliant +// ^ private String key; // Compliant - private public UndocumentedApi() { // Compliant - empty constructor @@ -66,7 +67,7 @@ public A() { // Noncompliant {{Document this public constructor by adding an exp /** * This is a Javadoc comment */ -public class MyClass implements Runnable { // Noncompliant {{Document the parameter(s): }} +public class MyClass implements Runnable { // Noncompliant {{Document the parameter(s): }} private int status; // Compliant - not public @@ -75,7 +76,7 @@ public class MyClass implements Runnable { // Noncompliant {{Document the */ public String message; // Compliant - well documented - public MyClass() { // Noncompliant + public MyClass() { // Noncompliant this.status = 0; } @@ -101,13 +102,13 @@ public void doSomething1(int value) { // Compliant * Valid descriptions. * @return foo Valid descriptions. */ - public int doSomething2(int value) { // Noncompliant {{Document the parameter(s): value}} + public int doSomething2(int value) { // Noncompliant {{Document the parameter(s): value}} return value; } /** Valid descriptions. * */ - public int doSomething3() { // Noncompliant {{Document this method return value.}} + public int doSomething3() { // Noncompliant {{Document this method return value.}} return value; } } @@ -162,7 +163,7 @@ class FooPackage { // Compliant - non public /** Valid descriptions.. */ public class Foo { // Compliant - // Noncompliant@+3 + // Noncompliant@+3 /** Valid descriptions. */ public int foo1(int a, int b, int c) { // Noncompliant @@ -286,7 +287,8 @@ public interface Foo { @Target({METHOD}) @Retention(RUNTIME) - public @interface Transient { // Noncompliant [[sc=21;ec=30]] + public @interface Transient { // Noncompliant +// ^^^^^^^^^ boolean value() default true; // Noncompliant } } diff --git a/java-checks/src/test/files/checks/UndocumentedApiCheck/UndocumentedApiIncomplete.java b/java-checks/src/test/files/checks/UndocumentedApiCheck/UndocumentedApiIncomplete.java index 2eb462c2c74..78bbb7b096d 100644 --- a/java-checks/src/test/files/checks/UndocumentedApiCheck/UndocumentedApiIncomplete.java +++ b/java-checks/src/test/files/checks/UndocumentedApiCheck/UndocumentedApiIncomplete.java @@ -3,27 +3,27 @@ /** * FIXME */ -public class A { } // Noncompliant {{Document this public class by adding an explicit description.}} - placeholder +public class A { } // Noncompliant {{Document this public class by adding an explicit description.}} /** * . */ -public class B { } // Noncompliant {{Document this public class by adding an explicit description.}} - placeholder +public class B { } // Noncompliant {{Document this public class by adding an explicit description.}} /** * ... */ -public class C { } // Noncompliant {{Document this public class by adding an explicit description.}} - placeholder +public class C { } // Noncompliant {{Document this public class by adding an explicit description.}} /** * TODO */ -public class D { } // Noncompliant {{Document this public class by adding an explicit description.}} - placeholder +public class D { } // Noncompliant {{Document this public class by adding an explicit description.}} /** * */ -public class E { } // Noncompliant {{Document this public class by adding an explicit description.}} - empty javadoc +public class E { } // Noncompliant {{Document this public class by adding an explicit description.}} /** * OneWordIsEnough @@ -35,7 +35,7 @@ public class F { } // Compliant */ public class G extends F { } // Compliant -public class H { } // Noncompliant {{Document this public class by adding an explicit description.}} - no javadoc +public class H { } // Noncompliant {{Document this public class by adding an explicit description.}} /** * This is documented @@ -50,20 +50,20 @@ public void foo() { } * This is documented * @param sab */ - public void foo(String s, Object o) { } // Noncompliant {{Document the parameter(s): s, o}} - wrong name + public void foo(String s, Object o) { } // Noncompliant {{Document the parameter(s): s, o}} /** * This is documented * @param o * @param o FIXME */ - public void foo(Object o) { } // Noncompliant {{Document the parameter(s): o}} - undocumented + public void foo(Object o) { } // Noncompliant {{Document the parameter(s): o}} /** * This is documented * @param l . */ - public void foo(long l) { } // Noncompliant {{Document the parameter(s): l}} - placeholder + public void foo(long l) { } // Noncompliant {{Document the parameter(s): l}} /** * This is documented @@ -74,7 +74,7 @@ public void foo(int i) { } // Compliant - documented parameter /** * @param d the ratio of fools */ - public void foo(double d) { } // Noncompliant {{Document this public method by adding an explicit description.}} - param documented but not the method + public void foo(double d) { } // Noncompliant {{Document this public method by adding an explicit description.}} /** * This is documented @@ -91,7 +91,7 @@ public class ReturnValue { /** * @return */ - public String bar1() { } // Noncompliant {{Document this public method by adding an explicit description.}} - undocumented + public String bar1() { } // Noncompliant {{Document this public method by adding an explicit description.}} /** * @return this is documented @@ -112,7 +112,7 @@ public void bar4() { } // Noncompliant {{Document this public method by adding a * This is documented * @return FIXME */ - public String bro() { } // Noncompliant {{Document this method return value.}} - placeholder + public String bro() { } // Noncompliant {{Document this method return value.}} /** * This is documented diff --git a/java-checks/src/test/files/checks/UnnecessarySemicolonCheck.java b/java-checks/src/test/files/checks/UnnecessarySemicolonCheck.java index 08f79db8ed2..4d06f52fe59 100644 --- a/java-checks/src/test/files/checks/UnnecessarySemicolonCheck.java +++ b/java-checks/src/test/files/checks/UnnecessarySemicolonCheck.java @@ -11,10 +11,12 @@ private static InputStream input(String path) throws IOException { public static void main(String[] args) throws IOException { - try(InputStream i1 = input("i1");) { // Noncompliant [[sc=37;ec=38]] {{Remove this extraneous semicolon.}} + try(InputStream i1 = input("i1");) { // Noncompliant {{Remove this extraneous semicolon.}} +// ^ } - try(InputStream i1 = input("i1");InputStream i2 = input("i2");) { // Noncompliant [[sc=66;ec=67]] + try(InputStream i1 = input("i1");InputStream i2 = input("i2");) { // Noncompliant +// ^ } try(InputStream i1 = input("i1")) { // Compliant diff --git a/java-checks/src/test/files/checks/UppercaseSuffixesCheck.java b/java-checks/src/test/files/checks/UppercaseSuffixesCheck.java index 1e29403de34..a8a5f16fc0c 100644 --- a/java-checks/src/test/files/checks/UppercaseSuffixesCheck.java +++ b/java-checks/src/test/files/checks/UppercaseSuffixesCheck.java @@ -1,6 +1,7 @@ class A { double f = 1.; - long long1 = 1l; // Noncompliant [[sc=16;ec=18]] {{Upper-case this literal "l" suffix.}} + long long1 = 1l; // Noncompliant {{Upper-case this literal "l" suffix.}} +// ^^ float float1 = 1.0f; // Noncompliant {{Upper-case this literal "f" suffix.}} double double1 = 1.0d; // Noncompliant {{Upper-case this literal "d" suffix.}} diff --git a/java-checks/src/test/files/checks/UppercaseSuffixesCheckOnlyLong.java b/java-checks/src/test/files/checks/UppercaseSuffixesCheckOnlyLong.java index a7028e873b8..163ec77354f 100644 --- a/java-checks/src/test/files/checks/UppercaseSuffixesCheckOnlyLong.java +++ b/java-checks/src/test/files/checks/UppercaseSuffixesCheckOnlyLong.java @@ -1,6 +1,7 @@ class A { double f = 1.; - long long1 = 1l; // Noncompliant [[sc=16;ec=18]] {{Upper-case this literal "l" suffix.}} + long long1 = 1l; // Noncompliant {{Upper-case this literal "l" suffix.}} +// ^^ float float1 = 1.0f; // Compliant double double1 = 1.0d; // Compliant diff --git a/java-checks/src/test/files/checks/UseSwitchExpressionCheck.java b/java-checks/src/test/files/checks/UseSwitchExpressionCheck.java index 2f2d12e77bb..2e71a2e7985 100644 --- a/java-checks/src/test/files/checks/UseSwitchExpressionCheck.java +++ b/java-checks/src/test/files/checks/UseSwitchExpressionCheck.java @@ -9,7 +9,7 @@ enum DoW { void foo(DoW day) { int numLetters; - switch (day) { // Noncompliant {{Use "switch" expression to set value of "numLetters".}} + switch (day) { // Noncompliant {{Use "switch" expression to set value of "numLetters".}} case MONDAY: case FRIDAY: case SUNDAY: @@ -32,7 +32,7 @@ void foo(DoW day) { void two_throwing_branches(DoW day) { boolean isWeekday = false; - switch (day) { // Noncompliant {{Use "switch" expression to set value of "isWeekday".}} + switch (day) { // Noncompliant {{Use "switch" expression to set value of "isWeekday".}} case MONDAY: case TUESDAY: case WEDNESDAY: @@ -104,7 +104,7 @@ int return_switch_block(int x) { void expression_switch_non_compliant() { int numLetters; - switch (day) { // Noncompliant {{Use "switch" expression to set value of "numLetters".}} + switch (day) { // Noncompliant {{Use "switch" expression to set value of "numLetters".}} case MONDAY, FRIDAY, SUNDAY -> { numLetters = 6; } diff --git a/java-checks/src/test/files/checks/UselessParenthesesCheck.java b/java-checks/src/test/files/checks/UselessParenthesesCheck.java index cf760555a97..3c7061a859e 100644 --- a/java-checks/src/test/files/checks/UselessParenthesesCheck.java +++ b/java-checks/src/test/files/checks/UselessParenthesesCheck.java @@ -2,11 +2,14 @@ class Foo { void foo() { return 3; // Compliant return (x); // Compliant - return ((x)); // Noncompliant [[sc=13;ec=14;secondary=5]] {{Remove these useless parentheses.}} + return ((x)); // Noncompliant {{Remove these useless parentheses.}} +// ^ ^< return (x + 1); // Compliant - return ((x + 1)); // Noncompliant [[sc=13;ec=14;secondary=7]] {{Remove these useless parentheses.}} + return ((x + 1)); // Noncompliant {{Remove these useless parentheses.}} +// ^ ^< int x = (y / 2 + 1); // Compliant - int x2 = ((y / 2 + 1)); // Noncompliant [[sc=15;ec=16;secondary=9]] {{Remove these useless parentheses.}} + int x2 = ((y / 2 + 1)); // Noncompliant {{Remove these useless parentheses.}} +// ^ ^< int y = (4+X) * y; // Compliant int y2 = 4+(X * y); // Compliant diff --git a/java-checks/src/test/files/checks/ValueBasedObjectsShouldNotBeSerializedCheck.java b/java-checks/src/test/files/checks/ValueBasedObjectsShouldNotBeSerializedCheck.java index 0d6a15d348e..71315b209e6 100644 --- a/java-checks/src/test/files/checks/ValueBasedObjectsShouldNotBeSerializedCheck.java +++ b/java-checks/src/test/files/checks/ValueBasedObjectsShouldNotBeSerializedCheck.java @@ -26,11 +26,13 @@ public class SerializableClass extends SerializableBaseClass { OptionalLong attr2b; // Compliant, as Optional is not serializable (another rule accounts for non serializable fields) - HijrahDate attr3; // Noncompliant [[sc=14;ec=19]] {{Make this value-based field transient so it is not included in the serialization of this class.}} + HijrahDate attr3; // Noncompliant {{Make this value-based field transient so it is not included in the serialization of this class.}} +// ^^^^^ Clock attr4; // Compliant, as Clock is not a value-based class - LocalDateTime attr5; // Noncompliant [[sc=17;ec=22]] {{Make this value-based field transient so it is not included in the serialization of this class.}} + LocalDateTime attr5; // Noncompliant {{Make this value-based field transient so it is not included in the serialization of this class.}} +// ^^^^^ transient Optional attr6; @@ -38,13 +40,17 @@ public class SerializableClass extends SerializableBaseClass { transient HijrahDate attr8; - HijrahDate[][] attr9; // Noncompliant [[sc=18;ec=23]] {{Make this value-based field transient so it is not included in the serialization of this class.}} + HijrahDate[][] attr9; // Noncompliant {{Make this value-based field transient so it is not included in the serialization of this class.}} +// ^^^^^ - List attr10; // Noncompliant [[sc=23;ec=29]] {{Make this value-based field transient so it is not included in the serialization of this class.}} + List attr10; // Noncompliant {{Make this value-based field transient so it is not included in the serialization of this class.}} +// ^^^^^^ - List attr11; // Noncompliant [[sc=25;ec=31]] {{Make this value-based field transient so it is not included in the serialization of this class.}} + List attr11; // Noncompliant {{Make this value-based field transient so it is not included in the serialization of this class.}} +// ^^^^^^ - Map attr12; // Noncompliant [[sc=30;ec=36]] {{Make this value-based field transient so it is not included in the serialization of this class.}} + Map attr12; // Noncompliant {{Make this value-based field transient so it is not included in the serialization of this class.}} +// ^^^^^^ List attr13; @@ -65,7 +71,8 @@ public void doSomething() { Optional attr3; // Compliant, as Optional is not serializable - LocalDateTime attr4; // Noncompliant [[sc=21;ec=26]] {{Make this value-based field transient so it is not included in the serialization of this class.}} + LocalDateTime attr4; // Noncompliant {{Make this value-based field transient so it is not included in the serialization of this class.}} +// ^^^^^ }; } @@ -99,7 +106,8 @@ enum MyEnum implements Serializable { String attr1; - HijrahDate attr2; // Noncompliant [[sc=14;ec=19]] {{Make this value-based field transient so it is not included in the serialization of this class.}} + HijrahDate attr2; // Noncompliant {{Make this value-based field transient so it is not included in the serialization of this class.}} +// ^^^^^ } @@ -109,6 +117,7 @@ enum MyEnum implements Serializable { String elem1(); - HijrahDate elem2(); // Noncompliant [[sc=14;ec=19]] {{Make this value-based field transient so it is not included in the serialization of this class.}} + HijrahDate elem2(); // Noncompliant {{Make this value-based field transient so it is not included in the serialization of this class.}} +// ^^^^^ } diff --git a/java-checks/src/test/files/checks/VariableDeclarationScopeCheck.java b/java-checks/src/test/files/checks/VariableDeclarationScopeCheck.java index e02b706a0f7..37f2441198a 100644 --- a/java-checks/src/test/files/checks/VariableDeclarationScopeCheck.java +++ b/java-checks/src/test/files/checks/VariableDeclarationScopeCheck.java @@ -3,7 +3,8 @@ abstract class A { void m1(); void m2(int par) { - int a; // Noncompliant [[sc=9;ec=10]] {{Move the declaration of "a" closer to the code that uses it.}} + int a; // Noncompliant {{Move the declaration of "a" closer to the code that uses it.}} +// ^ if (true) { } diff --git a/java-checks/src/test/files/checks/WaitInSynchronizeCheck.java b/java-checks/src/test/files/checks/WaitInSynchronizeCheck.java index 75febee21d9..88e959ca49a 100644 --- a/java-checks/src/test/files/checks/WaitInSynchronizeCheck.java +++ b/java-checks/src/test/files/checks/WaitInSynchronizeCheck.java @@ -17,10 +17,11 @@ synchronized void foo() { notifyAll(); } void bar() { - obj.wait(); // Noncompliant [[sc=9;ec=13]] {{Move this call to "wait()" into a synchronized block to be sure the monitor on "String" is held.}} + obj.wait(); // Noncompliant {{Move this call to "wait()" into a synchronized block to be sure the monitor on "String" is held.}} +// ^^^^ wait(1, 2); // Noncompliant {{Move this call to "wait()" into a synchronized block to be sure the monitor on "this" is held.}} - wait(1); // Noncompliant - notify(); // Noncompliant + wait(1); // Noncompliant + notify(); // Noncompliant notifyAll(); // Noncompliant } diff --git a/java-checks/src/test/files/checks/WaitInWhileLoopCheck.java b/java-checks/src/test/files/checks/WaitInWhileLoopCheck.java index b40ab5fde09..51bd857c510 100644 --- a/java-checks/src/test/files/checks/WaitInWhileLoopCheck.java +++ b/java-checks/src/test/files/checks/WaitInWhileLoopCheck.java @@ -7,7 +7,8 @@ void foo() { Condition condition; synchronized (obj) { if (!suitableCondition()){ - obj.wait(12); // Noncompliant [[sc=13;ec=17]] {{Remove this call to "wait" or move it into a "while" loop.}} + obj.wait(12); // Noncompliant {{Remove this call to "wait" or move it into a "while" loop.}} +// ^^^^ condition.await(); // Noncompliant } for(;;){ diff --git a/java-checks/src/test/files/checks/mismatchPackage/DefaultPackage.java b/java-checks/src/test/files/checks/mismatchPackage/DefaultPackage.java index a4fff4dc1c2..35247d24616 100644 --- a/java-checks/src/test/files/checks/mismatchPackage/DefaultPackage.java +++ b/java-checks/src/test/files/checks/mismatchPackage/DefaultPackage.java @@ -1 +1 @@ -class DefaultPackage{} \ No newline at end of file +class DefaultPackage{} diff --git a/java-checks/src/test/files/checks/mismatchPackage/Matching.java b/java-checks/src/test/files/checks/mismatchPackage/Matching.java index c3331e2135e..abfb831dd64 100644 --- a/java-checks/src/test/files/checks/mismatchPackage/Matching.java +++ b/java-checks/src/test/files/checks/mismatchPackage/Matching.java @@ -1,3 +1,3 @@ package mismatchPackage; -class Matching {} \ No newline at end of file +class Matching {} diff --git a/java-checks/src/test/files/checks/mismatchPackage/Mismatch.java b/java-checks/src/test/files/checks/mismatchPackage/Mismatch.java index 0c297a631de..bf009e118ab 100644 --- a/java-checks/src/test/files/checks/mismatchPackage/Mismatch.java +++ b/java-checks/src/test/files/checks/mismatchPackage/Mismatch.java @@ -1,3 +1,4 @@ -package org.foo.mismatchPackage; // Noncompliant [[sc=9;ec=32]] +package org.foo.mismatchPackage; // Noncompliant +// ^^^^^^^^^^^^^^^^^^^^^^^ class Mismatch {} diff --git a/java-checks/src/test/files/checks/naming/BadConstantNameNoncompliant.java b/java-checks/src/test/files/checks/naming/BadConstantNameNoncompliant.java index 58b8fd143cc..f0ad5e845a8 100644 --- a/java-checks/src/test/files/checks/naming/BadConstantNameNoncompliant.java +++ b/java-checks/src/test/files/checks/naming/BadConstantNameNoncompliant.java @@ -3,7 +3,8 @@ class BadConstantName { static final long serialVersionUID = 42L; public static final int GOOD_CONSTANT = 0; - public static final int bad_constant = 0; // Noncompliant [[sc=27;ec=39]] {{Rename this constant name to match the regular expression '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.}} + public static final int bad_constant = 0; // Noncompliant {{Rename this constant name to match the regular expression '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.}} +// ^^^^^^^^^^^^ public static int static_field; public final int final_field = 0; public static final Object object = 0; diff --git a/java-checks/src/test/files/checks/naming/BadFieldNameStaticNonFinal.java b/java-checks/src/test/files/checks/naming/BadFieldNameStaticNonFinal.java index 38fc4bc6a6e..14f0c217ca9 100644 --- a/java-checks/src/test/files/checks/naming/BadFieldNameStaticNonFinal.java +++ b/java-checks/src/test/files/checks/naming/BadFieldNameStaticNonFinal.java @@ -1,7 +1,8 @@ class BadFieldName { public int BAD_FIELD_NAME; public int goodFieldName; - public static int BAD_FIELD_NAME_STATIC_NON_FINAL; // Noncompliant [[sc=21;ec=52]] {{Rename this field "BAD_FIELD_NAME_STATIC_NON_FINAL" to match the regular expression '^[a-z][a-zA-Z0-9]*$'.}} + public static int BAD_FIELD_NAME_STATIC_NON_FINAL; // Noncompliant {{Rename this field "BAD_FIELD_NAME_STATIC_NON_FINAL" to match the regular expression '^[a-z][a-zA-Z0-9]*$'.}} +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ public static int goodFieldNameStaticNonFinal; public final static int STATIC; // Compliant, final modifier diff --git a/java-checks/src/test/files/checks/naming/BadGenericNameNoncompliant.java b/java-checks/src/test/files/checks/naming/BadGenericNameNoncompliant.java index 9a554552d7f..3fec5a16dff 100644 --- a/java-checks/src/test/files/checks/naming/BadGenericNameNoncompliant.java +++ b/java-checks/src/test/files/checks/naming/BadGenericNameNoncompliant.java @@ -1,4 +1,5 @@ -class MyClass { // Noncompliant [[sc=15;ec=19]] {{Rename this generic name to match the regular expression '^[A-Z][0-9]?$'.}} +class MyClass { // Noncompliant {{Rename this generic name to match the regular expression '^[A-Z][0-9]?$'.}} +// ^^^^ void addAll(Collection c) { // Noncompliant } } diff --git a/java-checks/src/test/files/checks/naming/BadLocalVariableNameNoncompliant.java b/java-checks/src/test/files/checks/naming/BadLocalVariableNameNoncompliant.java index 40f5c433ecf..4c341c7ea49 100644 --- a/java-checks/src/test/files/checks/naming/BadLocalVariableNameNoncompliant.java +++ b/java-checks/src/test/files/checks/naming/BadLocalVariableNameNoncompliant.java @@ -1,6 +1,7 @@ class BadLocalVariableName { void method( - int BAD_FORMAL_PARAMETER // Noncompliant [[sc=9;ec=29]] {{Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.}} + int BAD_FORMAL_PARAMETER // Noncompliant {{Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.}} +// ^^^^^^^^^^^^^^^^^^^^ ) { int BAD; // Noncompliant int good; diff --git a/java-checks/src/test/files/checks/naming/KeywordAsIdentifierCheck.java b/java-checks/src/test/files/checks/naming/KeywordAsIdentifierCheck.java index 8e90918622a..63676b31060 100644 --- a/java-checks/src/test/files/checks/naming/KeywordAsIdentifierCheck.java +++ b/java-checks/src/test/files/checks/naming/KeywordAsIdentifierCheck.java @@ -1,7 +1,9 @@ class A { int foo = 0; - int _ = 0; // Noncompliant [[sc=7;ec=8]] {{Use a different name than "_".}} - int enum = 0; // Noncompliant [[sc=7;ec=11]] {{Use a different name than "enum".}} + int _ = 0; // Noncompliant {{Use a different name than "_".}} +// ^ + int enum = 0; // Noncompliant {{Use a different name than "enum".}} +// ^^^^ public void f( int a, @@ -11,7 +13,7 @@ public void f( public void g(){ int a; - int _; // Noncompliant + int _; // Noncompliant int enum; // Noncompliant _ = enum; // should be reported only for declarations } diff --git a/java-checks/src/test/files/checks/naming/KeywordAsIdentifierCheck_java1.java b/java-checks/src/test/files/checks/naming/KeywordAsIdentifierCheck_java1.java index 37a1a61b4a7..1b81e59988e 100644 --- a/java-checks/src/test/files/checks/naming/KeywordAsIdentifierCheck_java1.java +++ b/java-checks/src/test/files/checks/naming/KeywordAsIdentifierCheck_java1.java @@ -1,6 +1,7 @@ class A { int a = 0; - int assert = 0; // Noncompliant [[sc=7;ec=13]] {{Use a different name than "assert".}} + int assert = 0; // Noncompliant {{Use a different name than "assert".}} +// ^^^^^^ public void f( int a, @@ -9,7 +10,7 @@ public void f( public void g(){ int a; - int assert; // Noncompliant + int assert; // Noncompliant a = assert; // should be reported only for declarations } } diff --git a/java-checks/src/test/files/checks/naming/MethodNameSameAsClassCheck.java b/java-checks/src/test/files/checks/naming/MethodNameSameAsClassCheck.java index 293fe7f6484..c7cc3a534de 100644 --- a/java-checks/src/test/files/checks/naming/MethodNameSameAsClassCheck.java +++ b/java-checks/src/test/files/checks/naming/MethodNameSameAsClassCheck.java @@ -4,7 +4,8 @@ class My { My() { } - int My() { // Noncompliant [[sc=7;ec=9]] {{Rename this method to prevent any misunderstanding or make it a constructor.}} + int My() { // Noncompliant {{Rename this method to prevent any misunderstanding or make it a constructor.}} +// ^^ } void foo() { diff --git a/java-checks/src/test/files/checks/naming/MethodNamedEqualsCheck.java b/java-checks/src/test/files/checks/naming/MethodNamedEqualsCheck.java index 152d5703712..fe12ca5e804 100644 --- a/java-checks/src/test/files/checks/naming/MethodNamedEqualsCheck.java +++ b/java-checks/src/test/files/checks/naming/MethodNamedEqualsCheck.java @@ -1,5 +1,6 @@ class C { - public boolean equals(Boolean b) { // Noncompliant [[sc=18;ec=24]] {{Either override Object.equals(Object), or rename the method to prevent any confusion.}} + public boolean equals(Boolean b) { // Noncompliant {{Either override Object.equals(Object), or rename the method to prevent any confusion.}} +// ^^^^^^ return b; } } diff --git a/java-checks/src/test/files/checks/parsing/ParsingError.java b/java-checks/src/test/files/checks/parsing/ParsingError.java index 1e88aff85f6..b544cd3a5a3 100644 --- a/java-checks/src/test/files/checks/parsing/ParsingError.java +++ b/java-checks/src/test/files/checks/parsing/ParsingError.java @@ -1 +1 @@ -class \ No newline at end of file +class diff --git a/java-checks/src/test/files/checks/serialization/BlindSerialVersionUidCheck.java b/java-checks/src/test/files/checks/serialization/BlindSerialVersionUidCheck.java index d7ac860dfbe..6f82d152752 100644 --- a/java-checks/src/test/files/checks/serialization/BlindSerialVersionUidCheck.java +++ b/java-checks/src/test/files/checks/serialization/BlindSerialVersionUidCheck.java @@ -2,7 +2,8 @@ class A implements Cloneable {} class B implements Serializable { - private static final long serialVersionUID = 1L; // Noncompliant [[sc=29;ec=45]] {{Remove this "serialVersionUID".}} + private static final long serialVersionUID = 1L; // Noncompliant {{Remove this "serialVersionUID".}} +// ^^^^^^^^^^^^^^^^ } class C implements Serializable {} class D1 extends C {} diff --git a/java-checks/src/test/files/checks/serialization/PrivateReadResolveCheck.java b/java-checks/src/test/files/checks/serialization/PrivateReadResolveCheck.java index 971b65b079c..b054b2dfb31 100644 --- a/java-checks/src/test/files/checks/serialization/PrivateReadResolveCheck.java +++ b/java-checks/src/test/files/checks/serialization/PrivateReadResolveCheck.java @@ -2,7 +2,7 @@ public class Fruit implements Serializable { private static final long serialVersionUID = 1; - private Object readResolve() throws ObjectStreamException // Noncompliant + private Object readResolve() throws ObjectStreamException // Noncompliant {} } @@ -41,4 +41,4 @@ public class Fruit6 implements Serializable { private Object readResolve(int a) throws ObjectStreamException // compliant, not read resolve method {} void foo() {} -} \ No newline at end of file +} diff --git a/java-checks/src/test/files/checks/serialization/SerializableComparatorCheck.java b/java-checks/src/test/files/checks/serialization/SerializableComparatorCheck.java index f160c746be1..376007a743f 100644 --- a/java-checks/src/test/files/checks/serialization/SerializableComparatorCheck.java +++ b/java-checks/src/test/files/checks/serialization/SerializableComparatorCheck.java @@ -1,7 +1,8 @@ import java.io.Serializable; import java.util.Comparator; -class A implements Comparator {} // Noncompliant [[sc=7;ec=8]] {{Make this class "Serializable".}} +class A implements Comparator {} // Noncompliant {{Make this class "Serializable".}} +// ^ class B implements Comparator, Serializable {} abstract class C implements Comparator {} class D extends C {} // Noncompliant diff --git a/java-checks/src/test/files/checks/spring/SpringComponentWithWrongScopeCheck.java b/java-checks/src/test/files/checks/spring/SpringComponentWithWrongScopeCheck.java index 9b9eef6de29..a3eee5c58c3 100644 --- a/java-checks/src/test/files/checks/spring/SpringComponentWithWrongScopeCheck.java +++ b/java-checks/src/test/files/checks/spring/SpringComponentWithWrongScopeCheck.java @@ -6,19 +6,22 @@ import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; -@Scope("prototype") // Noncompliant [[sc=1;ec=20]] {{Remove this "@Scope" annotation.}} + @Scope("prototype") // Noncompliant {{Remove this "@Scope" annotation.}} +//^^^^^^^^^^^^^^^^^^^ @Controller public class ControllerHelloWorld { public static final String PROTOTYPE = "prototype"; } -@Scope("prototype") // Noncompliant [[sc=1;ec=20]] {{Remove this "@Scope" annotation.}} + @Scope("prototype") // Noncompliant {{Remove this "@Scope" annotation.}} +//^^^^^^^^^^^^^^^^^^^ @Service class ServiceHelloWorld { } -@Scope("prototype") // Noncompliant [[sc=1;ec=20]] {{Remove this "@Scope" annotation.}} + @Scope("prototype") // Noncompliant {{Remove this "@Scope" annotation.}} +//^^^^^^^^^^^^^^^^^^^ @Repository class RepositoryHelloWorld { diff --git a/java-checks/src/test/files/checks/spring/SpringComposedRequestMappingCheck.java b/java-checks/src/test/files/checks/spring/SpringComposedRequestMappingCheck.java index 7ad13026aa3..5286b6115cb 100644 --- a/java-checks/src/test/files/checks/spring/SpringComposedRequestMappingCheck.java +++ b/java-checks/src/test/files/checks/spring/SpringComposedRequestMappingCheck.java @@ -19,7 +19,8 @@ public class Controller { @RequestMapping("/1") String m1() { return ""; } - @RequestMapping(path = "/2", method = RequestMethod.GET) // Noncompliant [[sc=4;ec=18]] {{Replace "@RequestMapping(method = RequestMethod.GET)" with "@GetMapping"}} + @RequestMapping(path = "/2", method = RequestMethod.GET) // Noncompliant {{Replace "@RequestMapping(method = RequestMethod.GET)" with "@GetMapping"}} +// ^^^^^^^^^^^^^^ String m2() { return ""; } @RequestMapping(path = "/3", method = {POST}) // Noncompliant {{Replace "@RequestMapping(method = RequestMethod.POST)" with "@PostMapping"}} diff --git a/java-checks/src/test/files/checks/unused/UnusedLabelCheck.java b/java-checks/src/test/files/checks/unused/UnusedLabelCheck.java index 998553af6cd..52b4322243f 100644 --- a/java-checks/src/test/files/checks/unused/UnusedLabelCheck.java +++ b/java-checks/src/test/files/checks/unused/UnusedLabelCheck.java @@ -7,7 +7,8 @@ void foo() { for (int i = 0; i < 10; i++) { break outer; } - label2: // Noncompliant [[sc=5;ec=11]] {{Remove this unused label.}} + label2: // Noncompliant {{Remove this unused label.}} +// ^^^^^^ for (int i = 0; i < 10; i++) { break; } diff --git a/java-checks/src/test/files/checks/unused/UnusedReturnedData.java b/java-checks/src/test/files/checks/unused/UnusedReturnedData.java index 252f474bfae..471811f1dad 100644 --- a/java-checks/src/test/files/checks/unused/UnusedReturnedData.java +++ b/java-checks/src/test/files/checks/unused/UnusedReturnedData.java @@ -7,8 +7,10 @@ public boolean method() { final java.io.Reader rd; java.io.BufferedReader brd; - rd.read(); // Noncompliant [[sc=8;ec=12]] {{Use or store the value returned from "read" instead of throwing it away.}} - brd.readLine(); // Noncompliant [[sc=9;ec=17]] {{Use or store the value returned from "readLine" instead of throwing it away.}} + rd.read(); // Noncompliant {{Use or store the value returned from "read" instead of throwing it away.}} +// ^^^^ + brd.readLine(); // Noncompliant {{Use or store the value returned from "readLine" instead of throwing it away.}} +// ^^^^^^^^ String line = brd.readLine(); // Compliant line = brd.readLine(); // Compliant diff --git a/java-checks/src/test/java/org/sonar/java/checks/ArrayDesignatorAfterTypeCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/ArrayDesignatorAfterTypeCheckTest.java index ca120ba860a..ded0fb05e89 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/ArrayDesignatorAfterTypeCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/ArrayDesignatorAfterTypeCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -28,10 +28,9 @@ class ArrayDesignatorAfterTypeCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/ArrayDesignatorAfterTypeCheckSample.java")) .withCheck(new ArrayDesignatorAfterTypeCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/ArrayDesignatorOnVariableCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/ArrayDesignatorOnVariableCheckTest.java index 22c18fff2a2..24b4d4b4c61 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/ArrayDesignatorOnVariableCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/ArrayDesignatorOnVariableCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -28,10 +28,9 @@ class ArrayDesignatorOnVariableCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/ArrayDesignatorOnVariableCheckSample.java")) .withCheck(new ArrayDesignatorOnVariableCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/ArrayHashCodeAndToStringCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/ArrayHashCodeAndToStringCheckTest.java index 23a4e6dafa6..53246fc8679 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/ArrayHashCodeAndToStringCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/ArrayHashCodeAndToStringCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -28,10 +28,9 @@ class ArrayHashCodeAndToStringCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/ArrayHashCodeAndToStringCheckSample.java")) .withCheck(new ArrayHashCodeAndToStringCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/BigDecimalDoubleConstructorCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/BigDecimalDoubleConstructorCheckTest.java index a8b88685655..150570f1832 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/BigDecimalDoubleConstructorCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/BigDecimalDoubleConstructorCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -28,10 +28,9 @@ class BigDecimalDoubleConstructorCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/BigDecimalDoubleConstructorCheckSample.java")) .withCheck(new BigDecimalDoubleConstructorCheck()) - .withQuickFixes() .verifyIssues(); } } diff --git a/java-checks/src/test/java/org/sonar/java/checks/BooleanLiteralCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/BooleanLiteralCheckTest.java index 94ec6e1a1d9..03779aa48c1 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/BooleanLiteralCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/BooleanLiteralCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -28,10 +28,9 @@ class BooleanLiteralCheckTest { @Test void detected() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/BooleanLiteralCheckSample.java")) .withCheck(new BooleanLiteralCheck()) - .withQuickFixes() .verifyIssues(); } } diff --git a/java-checks/src/test/java/org/sonar/java/checks/BoxedBooleanExpressionsCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/BoxedBooleanExpressionsCheckTest.java index 14603ac2512..e17881fa0b3 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/BoxedBooleanExpressionsCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/BoxedBooleanExpressionsCheckTest.java @@ -21,7 +21,6 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -43,10 +42,9 @@ void test() { @Test void test_quick_fixes() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/BoxedBooleanExpressionsCheckWithQuickFixes.java")) .withCheck(new BoxedBooleanExpressionsCheck()) - .withQuickFixes() .verifyIssues(); } } diff --git a/java-checks/src/test/java/org/sonar/java/checks/CollapsibleIfCandidateCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/CollapsibleIfCandidateCheckTest.java index 6bdf01eaea6..8aaddaec90a 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/CollapsibleIfCandidateCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/CollapsibleIfCandidateCheckTest.java @@ -21,7 +21,6 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; @@ -38,10 +37,9 @@ void detected() { @Test void test_quick_fixes() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/CollapsibleIfCandidateCheck.java")) .withCheck(new CollapsibleIfCandidateCheck()) - .withQuickFixes() .verifyIssues(); } } diff --git a/java-checks/src/test/java/org/sonar/java/checks/CollectionImplementationReferencedCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/CollectionImplementationReferencedCheckTest.java index 64665717fcf..eef3f84c9b0 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/CollectionImplementationReferencedCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/CollectionImplementationReferencedCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -28,10 +28,9 @@ class CollectionImplementationReferencedCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/CollectionImplementationReferencedCheck.java")) .withCheck(new CollectionImplementationReferencedCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/CollectionIsEmptyCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/CollectionIsEmptyCheckTest.java index 36ce18d56f0..ed2cc1137cc 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/CollectionIsEmptyCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/CollectionIsEmptyCheckTest.java @@ -21,7 +21,6 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -29,10 +28,9 @@ class CollectionIsEmptyCheckTest { @Test void test() { - ((InternalCheckVerifier) CheckVerifier.newVerifier()) + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/CollectionIsEmptyCheck.java")) .withCheck(new CollectionIsEmptyCheck()) - .withQuickFixes() .verifyIssues(); } } diff --git a/java-checks/src/test/java/org/sonar/java/checks/CombineCatchCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/CombineCatchCheckTest.java index fc95ab2eb02..9abcdf06ca7 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/CombineCatchCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/CombineCatchCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; @@ -29,25 +29,23 @@ class CombineCatchCheckTest { @Test void java_version_unset() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/CombineCatchCheck_no_version.java")) .withCheck(new CombineCatchCheck()) - .withQuickFixes() .verifyIssues(); } @Test void java_version_unset_not_compiling() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(nonCompilingTestSourcesPath("checks/CombineCatchCheck_no_version.java")) .withCheck(new CombineCatchCheck()) - .withQuickFixes() .verifyIssues(); } @Test void java_version_set() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/CombineCatchCheck.java")) .withCheck(new CombineCatchCheck()) .withJavaVersion(7) diff --git a/java-checks/src/test/java/org/sonar/java/checks/CompareStringsBoxedTypesWithEqualsCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/CompareStringsBoxedTypesWithEqualsCheckTest.java index dfb96e6ca91..f664c3e1a79 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/CompareStringsBoxedTypesWithEqualsCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/CompareStringsBoxedTypesWithEqualsCheckTest.java @@ -21,19 +21,17 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; -import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; +import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; class CompareStringsBoxedTypesWithEqualsCheckTest { @Test void detected() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/CompareStringsBoxedTypesWithEqualsCheck.java")) .withCheck(new CompareStringsBoxedTypesWithEqualsCheck()) - .withQuickFixes() .verifyIssues(); CheckVerifier.newVerifier() .onFile(nonCompilingTestSourcesPath("checks/CompareStringsBoxedTypesWithEqualsCheck.java")) diff --git a/java-checks/src/test/java/org/sonar/java/checks/CompareToResultTestCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/CompareToResultTestCheckTest.java index a2a60654720..3db9e769d63 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/CompareToResultTestCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/CompareToResultTestCheckTest.java @@ -22,16 +22,14 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; import org.sonar.java.checks.verifier.TestUtils; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; class CompareToResultTestCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(TestUtils.mainCodeSourcesPath("checks/CompareToResultTestCheck.java")) .withCheck(new CompareToResultTestCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/ConcatenationWithStringValueOfCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/ConcatenationWithStringValueOfCheckTest.java index 2def50df6eb..5de9d30b1e2 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/ConcatenationWithStringValueOfCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/ConcatenationWithStringValueOfCheckTest.java @@ -21,7 +21,6 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -29,10 +28,9 @@ class ConcatenationWithStringValueOfCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/ConcatenationWithStringValueOfCheck.java")) .withCheck(new ConcatenationWithStringValueOfCheck()) - .withQuickFixes() .verifyIssues(); } } diff --git a/java-checks/src/test/java/org/sonar/java/checks/DateFormatWeekYearCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/DateFormatWeekYearCheckTest.java index 19abcffb70f..0fe78fb7dab 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/DateFormatWeekYearCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/DateFormatWeekYearCheckTest.java @@ -21,7 +21,6 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -29,10 +28,9 @@ class DateFormatWeekYearCheckTest { @Test void test() { - ((InternalCheckVerifier) CheckVerifier.newVerifier()) + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("/checks/DateFormatWeekYearCheckSample.java")) .withCheck(new DateFormatWeekYearCheck()) - .withQuickFixes() .verifyIssues(); } } diff --git a/java-checks/src/test/java/org/sonar/java/checks/DefaultPackageCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/DefaultPackageCheckTest.java index 377e399cc63..f917498e231 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/DefaultPackageCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/DefaultPackageCheckTest.java @@ -31,7 +31,7 @@ void without_package() { CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/EmptyFile.java")) .withCheck(new DefaultPackageCheck()) - .verifyIssueOnFile("Move this file to a named package."); + .verifyIssues(); } @Test diff --git a/java-checks/src/test/java/org/sonar/java/checks/DiamondOperatorCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/DiamondOperatorCheckTest.java index 6e965dd2ce8..0f0da3a555f 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/DiamondOperatorCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/DiamondOperatorCheckTest.java @@ -21,7 +21,6 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -29,10 +28,9 @@ class DiamondOperatorCheckTest { @Test void test_no_version() { - ((InternalCheckVerifier) CheckVerifier.newVerifier()) + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/DiamondOperatorCheck_no_version.java")) .withCheck(new DiamondOperatorCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/EmptyFileCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/EmptyFileCheckTest.java index a370fcec2f0..f417084ac65 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/EmptyFileCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/EmptyFileCheckTest.java @@ -29,9 +29,9 @@ class EmptyFileCheckTest { @Test void test_empty_file() { CheckVerifier.newVerifier() - .onFile(mainCodeSourcesPath("checks/EmptyFile.java")) + .onFile(mainCodeSourcesPath("checks/EmptyFileCheckSample.java")) .withCheck(new EmptyFileCheck()) - .verifyIssueOnFile("This file has 0 lines of code."); + .verifyIssues(); } @Test diff --git a/java-checks/src/test/java/org/sonar/java/checks/EmptyMethodsCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/EmptyMethodsCheckTest.java index a39dbf119e8..352b3801da2 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/EmptyMethodsCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/EmptyMethodsCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -28,19 +28,17 @@ class EmptyMethodsCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/EmptyMethodsCheckSample.java")) .withCheck(new EmptyMethodsCheck()) - .withQuickFixes() .verifyIssues(); } @Test void test_no_semantics() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/EmptyMethodsCheckNoSemantics.java")) .withCheck(new EmptyMethodsCheck()) - .withQuickFixes() .withoutSemantic() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/EmptyStatementUsageCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/EmptyStatementUsageCheckTest.java index 9309395349b..1c5528bb4b3 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/EmptyStatementUsageCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/EmptyStatementUsageCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -28,19 +28,17 @@ class EmptyStatementUsageCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/EmptyStatementUsageCheckSample.java")) .withCheck(new EmptyStatementUsageCheck()) - .withQuickFixes() .verifyIssues(); } @Test void test_only_one_empty_statement() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/EmptyStatementUsageCheckOnyStatement.java")) .withCheck(new EmptyStatementUsageCheck()) - .withQuickFixes() .verifyIssues(); } } diff --git a/java-checks/src/test/java/org/sonar/java/checks/EqualsParametersMarkedNonNullCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/EqualsParametersMarkedNonNullCheckTest.java index ec910a3e02d..bef56ef712d 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/EqualsParametersMarkedNonNullCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/EqualsParametersMarkedNonNullCheckTest.java @@ -21,7 +21,6 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -29,10 +28,9 @@ class EqualsParametersMarkedNonNullCheckTest { @Test void detected() { - ((InternalCheckVerifier) CheckVerifier.newVerifier()) + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/EqualsParametersMarkedNonNullCheckSample.java")) .withCheck(new EqualsParametersMarkedNonNullCheck()) - .withQuickFixes() .verifyIssues(); } } diff --git a/java-checks/src/test/java/org/sonar/java/checks/FileHeaderCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/FileHeaderCheckTest.java index cc7ea11d317..8d8a7a9893b 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/FileHeaderCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/FileHeaderCheckTest.java @@ -44,14 +44,14 @@ void test() { CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/FileHeaderCheck/Class1.java")) .withCheck(check) - .verifyIssueOnFile("Add or update the header of this file."); + .verifyIssues(); check = new FileHeaderCheck(); check.headerFormat = "// copyright 2005"; CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/FileHeaderCheck/Class2.java")) .withCheck(check) - .verifyIssueOnFile("Add or update the header of this file."); + .verifyIssues(); check = new FileHeaderCheck(); check.headerFormat = "// copyright 2012"; @@ -111,12 +111,12 @@ void regex() { CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/FileHeaderCheck/Regex1.java")) .withCheck(check) - .verifyIssueOnFile("Add or update the header of this file."); + .verifyIssues(); // Check that the regular expression is compiled once CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/FileHeaderCheck/Regex1.java")) .withCheck(check) - .verifyIssueOnFile("Add or update the header of this file."); + .verifyIssues(); check = new FileHeaderCheck(); check.headerFormat = "// copyright \\d{4}\\n// mycompany"; @@ -125,7 +125,7 @@ void regex() { CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/FileHeaderCheck/Regex2.java")) .withCheck(check) - .verifyIssueOnFile("Add or update the header of this file."); + .verifyIssues(); check = new FileHeaderCheck(); check.headerFormat = "// copyright \\d{4}\\r?\\n// mycompany"; @@ -141,7 +141,7 @@ void regex() { CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/FileHeaderCheck/Regex4.java")) .withCheck(check) - .verifyIssueOnFile("Add or update the header of this file."); + .verifyIssues(); } @Test diff --git a/java-checks/src/test/java/org/sonar/java/checks/ImmediateReverseBoxingCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/ImmediateReverseBoxingCheckTest.java index d9d4f7e9589..fd463305982 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/ImmediateReverseBoxingCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/ImmediateReverseBoxingCheckTest.java @@ -21,19 +21,17 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; -import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; +import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; class ImmediateReverseBoxingCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/ImmediateReverseBoxingCheckSample.java")) .withCheck(new ImmediateReverseBoxingCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/ImmediatelyReturnedVariableCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/ImmediatelyReturnedVariableCheckTest.java index fb79151789a..e4c4e97a1ca 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/ImmediatelyReturnedVariableCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/ImmediatelyReturnedVariableCheckTest.java @@ -22,16 +22,14 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; import org.sonar.java.checks.verifier.TestUtils; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; class ImmediatelyReturnedVariableCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(TestUtils.mainCodeSourcesPath("checks/ImmediatelyReturnedVariableCheckSample.java")) .withCheck(new ImmediatelyReturnedVariableCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/MathClampRangeCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/MathClampRangeCheckTest.java index 11a14c3fcf3..33cbd59a7db 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/MathClampRangeCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/MathClampRangeCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.java.checks.MathClampRangeCheck.isLessThan; @@ -30,22 +30,18 @@ class MathClampRangeCheckTest { @Test void test_java_21() { - InternalCheckVerifier - .newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/MathClampRangeCheckSample.java")) .withCheck(new MathClampRangeCheck()) - .withQuickFixes() .withJavaVersion(21) .verifyIssues(); } @Test void test_before_java_21() { - InternalCheckVerifier - .newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/MathClampRangeCheckSample.java")) .withCheck(new MathClampRangeCheck()) - .withQuickFixes() .withJavaVersion(20) .verifyNoIssues(); } @@ -53,15 +49,15 @@ void test_before_java_21() { @Test void test_less_than() { // conversion to integer - assertThat(isLessThan(Integer.MIN_VALUE,Integer.MAX_VALUE)).isTrue(); - assertThat(isLessThan(Integer.MAX_VALUE,Integer.MIN_VALUE)).isFalse(); - assertThat(isLessThan(20,(byte)'A')).isTrue(); + assertThat(isLessThan(Integer.MIN_VALUE, Integer.MAX_VALUE)).isTrue(); + assertThat(isLessThan(Integer.MAX_VALUE, Integer.MIN_VALUE)).isFalse(); + assertThat(isLessThan(20, (byte) 'A')).isTrue(); // conversion to long - assertThat(isLessThan(Long.MIN_VALUE,Long.MAX_VALUE)).isTrue(); - assertThat(isLessThan(Long.MAX_VALUE,Long.MIN_VALUE)).isFalse(); - assertThat(isLessThan(Integer.MIN_VALUE,Long.MIN_VALUE)).isFalse(); - assertThat(isLessThan(Long.MAX_VALUE,Integer.MAX_VALUE)).isFalse(); + assertThat(isLessThan(Long.MIN_VALUE, Long.MAX_VALUE)).isTrue(); + assertThat(isLessThan(Long.MAX_VALUE, Long.MIN_VALUE)).isFalse(); + assertThat(isLessThan(Integer.MIN_VALUE, Long.MIN_VALUE)).isFalse(); + assertThat(isLessThan(Long.MAX_VALUE, Integer.MAX_VALUE)).isFalse(); // conversion to float assertThat(isLessThan(1.0f, 2.0f)).isTrue(); @@ -69,9 +65,9 @@ void test_less_than() { assertThat(isLessThan(9_223_372_036_854_775_806L, 9_223_372_036_854_775_805f)).isFalse(); assertThat(isLessThan(9_223_372_036_854_775_805f, 9_223_372_036_854_775_806L)).isFalse(); // a == b because of float low precision - assertThat(isLessThan(Float.NEGATIVE_INFINITY,Float.POSITIVE_INFINITY)).isTrue(); - assertThat(isLessThan(Float.NaN,Float.POSITIVE_INFINITY)).isFalse(); - assertThat(isLessThan(Float.NaN,Float.NaN)).isFalse(); + assertThat(isLessThan(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY)).isTrue(); + assertThat(isLessThan(Float.NaN, Float.POSITIVE_INFINITY)).isFalse(); + assertThat(isLessThan(Float.NaN, Float.NaN)).isFalse(); // conversion to double assertThat(isLessThan(1.0d, 2.0d)).isTrue(); diff --git a/java-checks/src/test/java/org/sonar/java/checks/MissingNewLineAtEndOfFileCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/MissingNewLineAtEndOfFileCheckTest.java index b6504cd8ce1..ebd0708f227 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/MissingNewLineAtEndOfFileCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/MissingNewLineAtEndOfFileCheckTest.java @@ -21,6 +21,8 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; class MissingNewLineAtEndOfFileCheckTest { @@ -30,20 +32,24 @@ void test() { CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/MissingNewLineAtEndOfFile.java")) .withCheck(new MissingNewLineAtEndOfFileCheck()) - .verifyIssueOnFile("Add a new line at the end of this file."); + .verifyIssues(); } @Test void empty_file() { CheckVerifier.newVerifier() - .onFile(mainCodeSourcesPath("checks/EmptyFile.java")) + .onFile(mainCodeSourcesPath("checks/EmptyFileMissingNewLine.java")) .withCheck(new MissingNewLineAtEndOfFileCheck()) - .verifyIssueOnFile("Add a new line at the end of this file."); + .verifyIssues(); + } - CheckVerifier.newVerifier() + @Test + void completely_empty_file() { + var verifier = CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/CompletelyEmptyFile.java")) - .withCheck(new MissingNewLineAtEndOfFileCheck()) - .verifyIssueOnFile("Add a new line at the end of this file."); + .withCheck(new MissingNewLineAtEndOfFileCheck()); + assertThatThrownBy(() -> verifier.verifyNoIssues()) + .hasMessageContaining("No issues were expected, but some were found."); } @Test diff --git a/java-checks/src/test/java/org/sonar/java/checks/MissingPackageInfoCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/MissingPackageInfoCheckTest.java index 77458a0c10e..245a53667ff 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/MissingPackageInfoCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/MissingPackageInfoCheckTest.java @@ -65,7 +65,7 @@ class MissingPackageInfoCheckTest { void initVerifier() { this.readCache = new InternalReadCache(); this.writeCache = new InternalWriteCache().bind(readCache); - this.verifier = CheckVerifier.newVerifier() + this.verifier = CheckVerifier.newInternalVerifier() .withCache(readCache, writeCache); } @@ -73,7 +73,7 @@ void initVerifier() { void no_package_info() { MissingPackageInfoCheck check = new MissingPackageInfoCheck(); - CheckVerifier.newVerifier() + CheckVerifier.newInternalVerifier() .onFiles( mainCodeSourcesPath("DefaultPackage.java"), mainCodeSourcesPath("checks/packageInfo/HelloWorld.java"), @@ -106,7 +106,7 @@ void caching() { var populatedReadCache = new InternalReadCache().putAll(writeCache); var writeCache2 = new InternalWriteCache().bind(populatedReadCache); - CheckVerifier.newVerifier() + CheckVerifier.newInternalVerifier() .withCache(populatedReadCache, writeCache2) .addFiles(InputFile.Status.SAME, mainCodeSourcesPath("checks/packageInfo/HelloWorld.java"), diff --git a/java-checks/src/test/java/org/sonar/java/checks/ModifiersOrderCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/ModifiersOrderCheckTest.java index 1562d2ba1f8..1213f407ef0 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/ModifiersOrderCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/ModifiersOrderCheckTest.java @@ -21,7 +21,6 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -37,10 +36,9 @@ void test() { @Test void quickFixes() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/ModifiersOrderCheckWithQuickFixes.java")) .withCheck(new ModifiersOrderCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/NotifyCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/NotifyCheckTest.java index 6d95878e1c5..aa1593203a7 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/NotifyCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/NotifyCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -28,10 +28,9 @@ class NotifyCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/NotifyCheckSample.java")) .withCheck(new NotifyCheck()) - .withQuickFixes() .verifyIssues(); } } diff --git a/java-checks/src/test/java/org/sonar/java/checks/OmitPermittedTypesCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/OmitPermittedTypesCheckTest.java index 5fce72eca3d..be2011f1ca0 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/OmitPermittedTypesCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/OmitPermittedTypesCheckTest.java @@ -22,7 +22,6 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -30,10 +29,9 @@ class OmitPermittedTypesCheckTest { @Test void test() { - ((InternalCheckVerifier) CheckVerifier.newVerifier()) + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/OmitPermittedTypesCheck/OmitPermittedTypesCheckSample.java")) .withCheck(new OmitPermittedTypesCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/OneClassInterfacePerFileCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/OneClassInterfacePerFileCheckTest.java index 044fe12feac..3244963409d 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/OneClassInterfacePerFileCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/OneClassInterfacePerFileCheckTest.java @@ -39,7 +39,7 @@ void noncompliant() { CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/OneClassInterfacePerFileCheckNoncompliant.java")) .withCheck(new OneClassInterfacePerFileCheck()) - .verifyIssueOnFile("There are 4 top-level types in this file; move all but one of them to other files."); + .verifyIssues(); } } diff --git a/java-checks/src/test/java/org/sonar/java/checks/OneDeclarationPerLineCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/OneDeclarationPerLineCheckTest.java index 7774d552bda..c690aff7ea3 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/OneDeclarationPerLineCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/OneDeclarationPerLineCheckTest.java @@ -20,17 +20,16 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; class OneDeclarationPerLineCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/OneDeclarationPerLineCheckSample.java")) .withCheck(new OneDeclarationPerLineCheck()) - .withQuickFixes() .verifyIssues(); } } diff --git a/java-checks/src/test/java/org/sonar/java/checks/OverrideAnnotationCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/OverrideAnnotationCheckTest.java index a2e2adefa28..95bf4ee8659 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/OverrideAnnotationCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/OverrideAnnotationCheckTest.java @@ -21,10 +21,9 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; -import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; +import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; class OverrideAnnotationCheckTest { @@ -38,10 +37,9 @@ void test_java() { @Test void quickfixes() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/OverrideAnnotationCheck_QuickFixes.java")) .withCheck(new OverrideAnnotationCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/PatternMatchUsingIfCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/PatternMatchUsingIfCheckTest.java index b998d467f75..8cd4e36b14f 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/PatternMatchUsingIfCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/PatternMatchUsingIfCheckTest.java @@ -20,21 +20,20 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; +import org.sonar.java.checks.verifier.CheckVerifier; import org.sonar.java.checks.verifier.TestUtils; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; class PatternMatchUsingIfCheckTest { @Test void test_java_21() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(TestUtils.mainCodeSourcesPath("checks/PatternMatchUsingIfCheckSample.java")) .withCheck(new PatternMatchUsingIfCheck()) .withJavaVersion(21) - .withQuickFixes() .verifyIssues(); } // No test with Java version < 21 because the sample crashes the parser - + } diff --git a/java-checks/src/test/java/org/sonar/java/checks/PrimitivesMarkedNullableCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/PrimitivesMarkedNullableCheckTest.java index d7c2e23e7ec..43b138b9793 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/PrimitivesMarkedNullableCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/PrimitivesMarkedNullableCheckTest.java @@ -21,7 +21,6 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -29,10 +28,9 @@ class PrimitivesMarkedNullableCheckTest { @Test void test() { - ((InternalCheckVerifier) CheckVerifier.newVerifier()) + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/PrimitivesMarkedNullableCheckSample.java")) .withCheck(new PrimitivesMarkedNullableCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/PrivateFieldUsedLocallyCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/PrivateFieldUsedLocallyCheckTest.java index 94fea630514..45670a92e6e 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/PrivateFieldUsedLocallyCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/PrivateFieldUsedLocallyCheckTest.java @@ -21,7 +21,6 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; @@ -38,10 +37,9 @@ void test() { @Test void test_quick_fixes() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/PrivateFieldUsedLocallyCheckSample.java")) .withCheck(new PrivateFieldUsedLocallyCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/RedundantThrowsDeclarationCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/RedundantThrowsDeclarationCheckTest.java index 5eb30f0c047..b4782e66d85 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/RedundantThrowsDeclarationCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/RedundantThrowsDeclarationCheckTest.java @@ -21,7 +21,6 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; @@ -30,19 +29,17 @@ class RedundantThrowsDeclarationCheckTest { @Test void test() { - ((InternalCheckVerifier) CheckVerifier.newVerifier()) + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/RedundantThrowsDeclarationCheckSample.java")) .withCheck(new RedundantThrowsDeclarationCheck()) - .withQuickFixes() .verifyIssues(); } @Test void test_non_compiling_code() { - ((InternalCheckVerifier) CheckVerifier.newVerifier()) + CheckVerifier.newVerifier() .onFile(nonCompilingTestSourcesPath("checks/RedundantThrowsDeclarationCheckSample.java")) .withCheck(new RedundantThrowsDeclarationCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/RedundantTypeCastCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/RedundantTypeCastCheckTest.java index ee296f9ccec..71c155be3d3 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/RedundantTypeCastCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/RedundantTypeCastCheckTest.java @@ -21,18 +21,16 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; -import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; +import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; class RedundantTypeCastCheckTest { @Test void test() { - ((InternalCheckVerifier) CheckVerifier.newVerifier()) + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/RedundantTypeCastCheckSample.java")) .withCheck(new RedundantTypeCastCheck()) - .withQuickFixes() .verifyIssues(); } @@ -46,11 +44,10 @@ void test_non_compiling() { @Test void testWithoutSemantic() { - ((InternalCheckVerifier) CheckVerifier.newVerifier()) + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/RedundantTypeCastCheckSample.java")) .withCheck(new RedundantTypeCastCheck()) .withoutSemantic() - .withQuickFixes() .verifyIssues(); CheckVerifier.newVerifier() diff --git a/java-checks/src/test/java/org/sonar/java/checks/ReplaceLambdaByMethodRefCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/ReplaceLambdaByMethodRefCheckTest.java index 11e4eaa3499..9400623e841 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/ReplaceLambdaByMethodRefCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/ReplaceLambdaByMethodRefCheckTest.java @@ -21,10 +21,9 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; -import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; +import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; class ReplaceLambdaByMethodRefCheckTest { @@ -33,18 +32,16 @@ class ReplaceLambdaByMethodRefCheckTest { @Test void java8() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath(FILENAME)) .withCheck(new ReplaceLambdaByMethodRefCheck()) .withJavaVersion(8) - .withQuickFixes() .verifyIssues(); - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath(FILENAME)) .withCheck(new ReplaceLambdaByMethodRefCheck()) .withJavaVersion(8) .withoutSemantic() - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/ReturnEmptyArrayNotNullCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/ReturnEmptyArrayNotNullCheckTest.java index 8af788b9c9a..bef057167cb 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/ReturnEmptyArrayNotNullCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/ReturnEmptyArrayNotNullCheckTest.java @@ -22,7 +22,6 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; import org.sonar.java.checks.verifier.TestUtils; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; class ReturnEmptyArrayNotNullCheckTest { @@ -36,16 +35,14 @@ void test() { @Test void quick_fixes() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(TestUtils.mainCodeSourcesPath("checks/ReturnEmptyArrayNotNullCheckWithQuickFixes.java")) .withCheck(new ReturnEmptyArrayNotNullCheck()) - .withQuickFixes() .verifyIssues(); - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(TestUtils.mainCodeSourcesPath("checks/ReturnEmptyArrayNotNullCheckWithQuickFixesAndImports.java")) .withCheck(new ReturnEmptyArrayNotNullCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/RightCurlyBraceSameLineAsNextBlockCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/RightCurlyBraceSameLineAsNextBlockCheckTest.java index 23e995dfcfe..05f4198236a 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/RightCurlyBraceSameLineAsNextBlockCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/RightCurlyBraceSameLineAsNextBlockCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -28,10 +28,9 @@ class RightCurlyBraceSameLineAsNextBlockCheckTest { @Test void detected() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/RightCurlyBraceSameLineAsNextBlockCheckSample.java")) .withCheck(new RightCurlyBraceSameLineAsNextBlockCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/SelfAssignementCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/SelfAssignementCheckTest.java index fdbb2cdc561..57590056ca1 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/SelfAssignementCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/SelfAssignementCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -28,10 +28,9 @@ class SelfAssignementCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/SelfAssignementCheckSample.java")) .withCheck(new SelfAssignementCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/SingleIfInsteadOfPatternMatchGuardCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/SingleIfInsteadOfPatternMatchGuardCheckTest.java index 3cb526c9bc2..6b76e6e8811 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/SingleIfInsteadOfPatternMatchGuardCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/SingleIfInsteadOfPatternMatchGuardCheckTest.java @@ -20,18 +20,17 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; +import org.sonar.java.checks.verifier.CheckVerifier; import org.sonar.java.checks.verifier.TestUtils; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; class SingleIfInsteadOfPatternMatchGuardCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(TestUtils.mainCodeSourcesPath("checks/SingleIfInsteadOfPatternMatchGuardCheckSample.java")) .withCheck(new SingleIfInsteadOfPatternMatchGuardCheck()) .withJavaVersion(21) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/StandardCharsetsConstantsCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/StandardCharsetsConstantsCheckTest.java index fac3fa189a7..4c608fba0d0 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/StandardCharsetsConstantsCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/StandardCharsetsConstantsCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; @@ -29,32 +29,29 @@ class StandardCharsetsConstantsCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/StandardCharsetsConstantsCheckSample.java")) .withCheck(new StandardCharsetsConstantsCheck()) - .withQuickFixes() .verifyIssues(); - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/StandardCharsetsConstantsCheckSample.java")) .withCheck(new StandardCharsetsConstantsCheck()) .withJavaVersion(7) - .withQuickFixes() .verifyIssues(); - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/StandardCharsetsConstantsCheck_java8.java")) .withCheck(new StandardCharsetsConstantsCheck()) .withJavaVersion(8) .verifyIssues(); - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(nonCompilingTestSourcesPath("checks/StandardCharsetsConstantsCheck_java10.java")) .withCheck(new StandardCharsetsConstantsCheck()) .withJavaVersion(10) .verifyIssues(); - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/StandardCharsetsConstantsCheckSample.java")) .withCheck(new StandardCharsetsConstantsCheck()) .withJavaVersion(6) - .withQuickFixes() .verifyNoIssues(); } } diff --git a/java-checks/src/test/java/org/sonar/java/checks/StaticMemberAccessCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/StaticMemberAccessCheckTest.java index b27f3a1930f..25f02162100 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/StaticMemberAccessCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/StaticMemberAccessCheckTest.java @@ -21,10 +21,9 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; -import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; +import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; class StaticMemberAccessCheckTest { @@ -40,10 +39,9 @@ void test() { @Test void quick_fixes() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/StaticMemberAccessQuickFixes.java")) .withCheck(new StaticMemberAccessCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/StaticMembersAccessCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/StaticMembersAccessCheckTest.java index 6bcf011ba25..12d985c5b38 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/StaticMembersAccessCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/StaticMembersAccessCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -28,10 +28,9 @@ class StaticMembersAccessCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/StaticMembersAccessCheckSample.java")) .withCheck(new StaticMembersAccessCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/StaticMethodCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/StaticMethodCheckTest.java index 74908fe9b48..dfdef7622b9 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/StaticMethodCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/StaticMethodCheckTest.java @@ -21,19 +21,17 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; -import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; +import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; class StaticMethodCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/StaticMethodCheckSample.java")) .withCheck(new StaticMethodCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/StringLiteralInsideEqualsCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/StringLiteralInsideEqualsCheckTest.java index 8ea734963f1..6071999e45e 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/StringLiteralInsideEqualsCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/StringLiteralInsideEqualsCheckTest.java @@ -20,7 +20,8 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; + import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; @@ -28,19 +29,17 @@ class StringLiteralInsideEqualsCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/StringLiteralInsideEqualsCheckSample.java")) .withCheck(new StringLiteralInsideEqualsCheck()) - .withQuickFixes() .verifyIssues(); } - + @Test void testNonCompiling() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(nonCompilingTestSourcesPath("checks/StringLiteralInsideEqualsCheckSample.java")) .withCheck(new StringLiteralInsideEqualsCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/StringPrimitiveConstructorCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/StringPrimitiveConstructorCheckTest.java index d408365c77c..397b4574ad4 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/StringPrimitiveConstructorCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/StringPrimitiveConstructorCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -28,10 +28,9 @@ class StringPrimitiveConstructorCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/StringPrimitiveConstructorCheckSample.java")) .withCheck(new StringPrimitiveConstructorCheck()) - .withQuickFixes() .verifyIssues(); } } diff --git a/java-checks/src/test/java/org/sonar/java/checks/StringToStringCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/StringToStringCheckTest.java index 7fe4ed0a4b3..be48a1bf384 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/StringToStringCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/StringToStringCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -28,19 +28,17 @@ class StringToStringCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/StringToString.java")) .withCheck(new StringToStringCheck()) - .withQuickFixes() .verifyIssues(); } @Test void testTextBlocks() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/TextBlockToString.java")) .withCheck(new StringToStringCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/SynchronizedClassUsageCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/SynchronizedClassUsageCheckTest.java index 9feb5a6eb41..60fd9f52707 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/SynchronizedClassUsageCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/SynchronizedClassUsageCheckTest.java @@ -22,12 +22,11 @@ import java.util.Collections; import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; class SynchronizedClassUsageCheckTest { - + @Test void detected() { CheckVerifier.newVerifier() diff --git a/java-checks/src/test/java/org/sonar/java/checks/TabCharacterCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/TabCharacterCheckTest.java index 6ac150f726e..53ce3a7e08d 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/TabCharacterCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/TabCharacterCheckTest.java @@ -31,7 +31,7 @@ void test() { CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/TabCharacter.java")) .withCheck(new TabCharacterCheck()) - .verifyIssueOnFile("Replace all tab characters in this file by sequences of white-spaces."); + .verifyIssues(); } @Test diff --git a/java-checks/src/test/java/org/sonar/java/checks/ThreadLocalCleanupCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/ThreadLocalCleanupCheckTest.java index 3321138699f..6db45c9c7fe 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/ThreadLocalCleanupCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/ThreadLocalCleanupCheckTest.java @@ -21,19 +21,17 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; -import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; +import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; class ThreadLocalCleanupCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/ThreadLocalCleanup.java")) .withCheck(new ThreadLocalCleanupCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/ThreadRunCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/ThreadRunCheckTest.java index 1824b5ffb74..8322e45b458 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/ThreadRunCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/ThreadRunCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -28,10 +28,9 @@ class ThreadRunCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/ThreadRunCheckSample.java")) .withCheck(new ThreadRunCheck()) - .withQuickFixes() .verifyIssues(); } } diff --git a/java-checks/src/test/java/org/sonar/java/checks/ToArrayCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/ToArrayCheckTest.java index 55b101a4977..dfdf320bd40 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/ToArrayCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/ToArrayCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -28,10 +28,9 @@ class ToArrayCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/ToArrayCheckSample.java")) .withCheck(new ToArrayCheck()) - .withQuickFixes() .verifyIssues(); } } diff --git a/java-checks/src/test/java/org/sonar/java/checks/ToStringReturningNullCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/ToStringReturningNullCheckTest.java index d6b16fab5c0..97b8447baf4 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/ToStringReturningNullCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/ToStringReturningNullCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -28,10 +28,9 @@ class ToStringReturningNullCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/ToStringReturningNullCheckSample.java")) .withCheck(new ToStringReturningNullCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/ToStringUsingBoxingCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/ToStringUsingBoxingCheckTest.java index aee292bff2c..bbb1ed33e57 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/ToStringUsingBoxingCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/ToStringUsingBoxingCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -28,10 +28,9 @@ class ToStringUsingBoxingCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/ToStringUsingBoxingCheckSample.java")) .withCheck(new ToStringUsingBoxingCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/UselessImportCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/UselessImportCheckTest.java index 7e674038d48..de6629f26d2 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/UselessImportCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/UselessImportCheckTest.java @@ -21,10 +21,9 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; -import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; +import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; class UselessImportCheckTest { @@ -38,16 +37,14 @@ void detected_with_package() { @Test void quickFixes() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/UselessImportCheck/WithQuickFixes.java")) .withCheck(new UselessImportCheck()) - .withQuickFixes() .verifyIssues(); - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/UselessImportCheck/WithQuickFixesSingleImport.java")) .withCheck(new UselessImportCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/UselessPackageInfoCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/UselessPackageInfoCheckTest.java index 093de4fc50a..f6fdda82584 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/UselessPackageInfoCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/UselessPackageInfoCheckTest.java @@ -70,7 +70,7 @@ void withNoOtherFile() { verifier .onFile(mainCodeSourcesPath("checks/UselessPackageInfoCheck/packageWithNoOtherFiles/package-info.java")) .withCheck(new UselessPackageInfoCheck()) - .verifyIssueOnFile("Remove this package."); + .verifyIssues(); } @Test @@ -153,11 +153,11 @@ void cache_deserialization_throws_IOException() throws IOException, NoSuchAlgori var inputStream = mock(InputStream.class); doThrow(new IOException()).when(inputStream).readAllBytes(); var localReadCache = mock(ReadCache.class); - + String filePath = mainCodeSourcesPath("checks/UselessPackageInfoCheck/packageWithNoOtherFilesButNotPackageInfo/HelloWorld1.java"); InputFile cachedFile = HashCacheTestHelper.inputFileFromPath(filePath); byte[] cachedHash = FileHashingUtils.inputFileContentHash(cachedFile); - + doReturn(inputStream).when(localReadCache).read("java:S1228;S4032:package:"+cachedFile.key()); doReturn(true).when(localReadCache).contains(any()); doReturn(new ByteArrayInputStream(cachedHash)) diff --git a/java-checks/src/test/java/org/sonar/java/checks/VirtualThreadNotSynchronizedCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/VirtualThreadNotSynchronizedCheckTest.java index 660f0e10bc1..d244a931383 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/VirtualThreadNotSynchronizedCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/VirtualThreadNotSynchronizedCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -28,8 +28,7 @@ class VirtualThreadNotSynchronizedCheckTest { @Test void test() { - InternalCheckVerifier - .newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/VirtualThreadNotSynchronizedCheckSample.java")) .withCheck(new VirtualThreadNotSynchronizedCheck()) .withJavaVersion(21) @@ -38,12 +37,10 @@ void test() { @Test void test_prior_java21() { - InternalCheckVerifier - .newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/VirtualThreadNotSynchronizedCheckSample.java")) .withCheck(new VirtualThreadNotSynchronizedCheck()) .withJavaVersion(20) .verifyNoIssues(); } } - diff --git a/java-checks/src/test/java/org/sonar/java/checks/VirtualThreadUnsupportedMethodsCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/VirtualThreadUnsupportedMethodsCheckTest.java index 8042baaf6f6..10f75138285 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/VirtualThreadUnsupportedMethodsCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/VirtualThreadUnsupportedMethodsCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -28,8 +28,7 @@ class VirtualThreadUnsupportedMethodsCheckTest { @Test void test() { - InternalCheckVerifier - .newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/VirtualThreadUnsupportedMethodsSample.java")) .withCheck(new VirtualThreadUnsupportedMethodsCheck()) .withJavaVersion(21) @@ -38,8 +37,7 @@ void test() { @Test void test_prior_java21() { - InternalCheckVerifier - .newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/VirtualThreadUnsupportedMethodsSample.java")) .withCheck(new VirtualThreadUnsupportedMethodsCheck()) .withJavaVersion(20) diff --git a/java-checks/src/test/java/org/sonar/java/checks/design/BrainMethodCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/design/BrainMethodCheckTest.java index 5f87b48fe45..e5efa525cc5 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/design/BrainMethodCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/design/BrainMethodCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks.design; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -32,7 +32,7 @@ class BrainMethodCheckTest { @Test void testHighComplexityFileWithDefaultThresholds() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(highComplexityFilePath) .withChecks(new BrainMethodCheck()) .verifyIssues(); @@ -47,7 +47,7 @@ void testHighComplexityFileWithHigherThresholds() { check.nestingThreshold = 8; check.cyclomaticThreshold = 45; - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(highComplexityFilePath) .withChecks(check) .verifyNoIssues(); @@ -55,7 +55,7 @@ void testHighComplexityFileWithHigherThresholds() { @Test void testLowComplexityFileWithDefaultThresholds() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(lowComplexityFilePath) .withChecks(new BrainMethodCheck()) .verifyNoIssues(); @@ -69,12 +69,12 @@ void testLowComplexityFileWithLowerThresholds() { check.noavThreshold = 4; check.cyclomaticThreshold = 5; - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(lowComplexityFilePath) .withChecks(check) .verifyIssues(); } - + @Test void testSubsetOfIssuesWithLowerThresholds() { var check = new BrainMethodCheck(); @@ -85,8 +85,8 @@ void testSubsetOfIssuesWithLowerThresholds() { check.nestingThreshold = 1; check.numberOfIssuesToReport = 1; - - InternalCheckVerifier.newInstance() + + CheckVerifier.newVerifier() .onFile(subsetFilePath) .withChecks(check) .verifyIssues(); diff --git a/java-checks/src/test/java/org/sonar/java/checks/spring/AsyncMethodsOnConfigurationClassCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/spring/AsyncMethodsOnConfigurationClassCheckTest.java index d237c9bbef1..2cff7d88cac 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/spring/AsyncMethodsOnConfigurationClassCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/spring/AsyncMethodsOnConfigurationClassCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks.spring; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -28,10 +28,9 @@ class AsyncMethodsOnConfigurationClassCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/spring/AsyncMethodsOnConfigurationClassCheckSample.java")) .withCheck(new AsyncMethodsOnConfigurationClassCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/spring/AvoidQualifierOnBeanMethodsCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/spring/AvoidQualifierOnBeanMethodsCheckTest.java index b51037ed775..982b5c560be 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/spring/AvoidQualifierOnBeanMethodsCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/spring/AvoidQualifierOnBeanMethodsCheckTest.java @@ -21,7 +21,6 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -29,10 +28,9 @@ class AvoidQualifierOnBeanMethodsCheckTest { @Test void test() { - ((InternalCheckVerifier) CheckVerifier.newVerifier()) + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/spring/AvoidQualifierOnBeanMethodsCheckSample.java")) .withCheck(new AvoidQualifierOnBeanMethodsCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/spring/ControllerWithRestControllerReplacementCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/spring/ControllerWithRestControllerReplacementCheckTest.java index ef03fb11596..07e5f0e3095 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/spring/ControllerWithRestControllerReplacementCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/spring/ControllerWithRestControllerReplacementCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks.spring; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; @@ -28,10 +28,9 @@ class ControllerWithRestControllerReplacementCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/spring/ControllerWithRestControllerReplacementCheck.java")) .withCheck(new ControllerWithRestControllerReplacementCheck()) - .withQuickFixes() .verifyIssues(); } } diff --git a/java-checks/src/test/java/org/sonar/java/checks/spring/NullableInjectedFieldsHaveDefaultValueCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/spring/NullableInjectedFieldsHaveDefaultValueCheckTest.java index 7fae9cf9ae8..97306caf277 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/spring/NullableInjectedFieldsHaveDefaultValueCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/spring/NullableInjectedFieldsHaveDefaultValueCheckTest.java @@ -20,16 +20,15 @@ package org.sonar.java.checks.spring; import org.junit.jupiter.api.Test; +import org.sonar.java.checks.verifier.CheckVerifier; import org.sonar.java.checks.verifier.TestUtils; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; class NullableInjectedFieldsHaveDefaultValueCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(TestUtils.mainCodeSourcesPath("checks/spring/NullableInjectedFieldsHaveDefaultValueSample.java")) .withCheck(new NullableInjectedFieldsHaveDefaultValueCheck()) - .withQuickFixes() .verifyIssues(); } } diff --git a/java-checks/src/test/java/org/sonar/java/checks/tests/AssertJChainSimplificationCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/tests/AssertJChainSimplificationCheckTest.java index 1fe3f5fb586..eeae119356c 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/tests/AssertJChainSimplificationCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/tests/AssertJChainSimplificationCheckTest.java @@ -21,7 +21,6 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; import static org.sonar.java.checks.verifier.TestUtils.testCodeSourcesPath; @@ -45,10 +44,9 @@ void testJava11Cases() { @Test void test_quick_fixes() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(testCodeSourcesPath("checks/tests/AssertJChainSimplificationCheckTest_QuickFix.java")) .withCheck(new AssertJChainSimplificationCheck()) - .withQuickFixes() .verifyIssues(); } } diff --git a/java-checks/src/test/java/org/sonar/java/checks/tests/AssertionArgumentOrderCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/tests/AssertionArgumentOrderCheckTest.java index 49109a84801..d67cc53879c 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/tests/AssertionArgumentOrderCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/tests/AssertionArgumentOrderCheckTest.java @@ -21,7 +21,6 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.testCodeSourcesPath; @@ -53,11 +52,9 @@ void test_TestNG() { @Test void quickfixes() { - InternalCheckVerifier - .newInstance() + CheckVerifier.newVerifier() .onFile(testCodeSourcesPath("checks/tests/AssertionArgumentOrderCheck_QuickFixes.java")) .withCheck(new AssertionArgumentOrderCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/tests/JUnit5DefaultPackageClassAndMethodCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/tests/JUnit5DefaultPackageClassAndMethodCheckTest.java index 84be163433a..ef40a0f198c 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/tests/JUnit5DefaultPackageClassAndMethodCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/tests/JUnit5DefaultPackageClassAndMethodCheckTest.java @@ -21,7 +21,6 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.testCodeSourcesPath; @@ -31,10 +30,9 @@ class JUnit5DefaultPackageClassAndMethodCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(testSourcePath) .withCheck(new JUnit5DefaultPackageClassAndMethodCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/tests/JUnit5SilentlyIgnoreClassAndMethodCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/tests/JUnit5SilentlyIgnoreClassAndMethodCheckTest.java index 0a403afa988..b4bd916365c 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/tests/JUnit5SilentlyIgnoreClassAndMethodCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/tests/JUnit5SilentlyIgnoreClassAndMethodCheckTest.java @@ -20,7 +20,7 @@ package org.sonar.java.checks.tests; import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; +import org.sonar.java.checks.verifier.CheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; import static org.sonar.java.checks.verifier.TestUtils.testCodeSourcesPath; @@ -31,16 +31,15 @@ class JUnit5SilentlyIgnoreClassAndMethodCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(testCodeSourcesPath(SOURCE_PATH)) .withCheck(new JUnit5SilentlyIgnoreClassAndMethodCheck()) - .withQuickFixes() .verifyIssues(); } @Test void test_without_semantic() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(testCodeSourcesPath(SOURCE_PATH)) .withCheck(new JUnit5SilentlyIgnoreClassAndMethodCheck()) .withoutSemantic() @@ -49,7 +48,7 @@ void test_without_semantic() { @Test void test_unknown_symbols() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(nonCompilingTestSourcesPath(SOURCE_PATH)) .withCheck(new JUnit5SilentlyIgnoreClassAndMethodCheck()) .verifyIssues(); diff --git a/java-checks/src/test/java/org/sonar/java/checks/unused/UnusedLocalVariableCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/unused/UnusedLocalVariableCheckTest.java index 05644760081..c8a640b7ba0 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/unused/UnusedLocalVariableCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/unused/UnusedLocalVariableCheckTest.java @@ -22,16 +22,14 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; import org.sonar.java.checks.verifier.TestUtils; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; class UnusedLocalVariableCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(TestUtils.mainCodeSourcesPath("checks/unused/UnusedLocalVariableCheck.java")) .withCheck(new UnusedLocalVariableCheck()) - .withQuickFixes() .verifyIssues(); } diff --git a/java-checks/src/test/java/org/sonar/java/checks/unused/UnusedMethodParameterCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/unused/UnusedMethodParameterCheckTest.java index 45ea68f0944..9f9bf766283 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/unused/UnusedMethodParameterCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/unused/UnusedMethodParameterCheckTest.java @@ -21,28 +21,25 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; -import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; +import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; class UnusedMethodParameterCheckTest { @Test void test() { - ((InternalCheckVerifier) CheckVerifier.newVerifier()) + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/unused/UnusedMethodParameterCheck.java")) .withCheck(new UnusedMethodParameterCheck()) - .withQuickFixes() .verifyIssues(); } @Test void test_non_compiling() { - ((InternalCheckVerifier) CheckVerifier.newVerifier()) + CheckVerifier.newVerifier() .onFile(nonCompilingTestSourcesPath("checks/unused/UnusedMethodParameterCheck.java")) .withCheck(new UnusedMethodParameterCheck()) - .withQuickFixes() .verifyIssues(); } } diff --git a/java-checks/src/test/java/org/sonar/java/checks/unused/UnusedPrivateFieldCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/unused/UnusedPrivateFieldCheckTest.java index 7c5c87568b5..f2005ac616b 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/unused/UnusedPrivateFieldCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/unused/UnusedPrivateFieldCheckTest.java @@ -21,7 +21,6 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; @@ -30,10 +29,9 @@ class UnusedPrivateFieldCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/unused/UnusedPrivateFieldCheck.java")) .withCheck(new UnusedPrivateFieldCheck()) - .withQuickFixes() .verifyIssues(); } @@ -55,10 +53,9 @@ void test_native() { @Test void test_quick_fixes() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/unused/UnusedPrivateFieldCheckWithQuickfixes.java")) .withCheck(new UnusedPrivateFieldCheck()) - .withQuickFixes() .verifyIssues(); } @@ -74,7 +71,7 @@ void test_ignored_annotation() { @Test void test_lombok_annotations() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(mainCodeSourcesPath("checks/unused/UnusedPrivateFieldLombok.java")) .withCheck(new UnusedPrivateFieldCheck()) .verifyIssues(); diff --git a/java-checks/src/test/java/org/sonar/java/checks/unused/UnusedPrivateMethodCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/unused/UnusedPrivateMethodCheckTest.java index b1b3d7554b6..cf18380b0b9 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/unused/UnusedPrivateMethodCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/unused/UnusedPrivateMethodCheckTest.java @@ -22,16 +22,14 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; import org.sonar.java.checks.verifier.TestUtils; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; class UnusedPrivateMethodCheckTest { @Test void test() { - InternalCheckVerifier.newInstance() + CheckVerifier.newVerifier() .onFile(TestUtils.mainCodeSourcesPath("checks/UnusedPrivateMethod.java")) .withCheck(new UnusedPrivateMethodCheck()) - .withQuickFixes() .verifyIssues(); } @@ -42,7 +40,7 @@ void test_non_compiling() { .withCheck(new UnusedPrivateMethodCheck()) .verifyIssues(); } - + @Test void test_non_compiling_unknown() { CheckVerifier.newVerifier() diff --git a/java-checks/src/test/java/org/sonar/java/checks/unused/UnusedThrowableCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/unused/UnusedThrowableCheckTest.java index 8eae0aa11e8..9768aaad8db 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/unused/UnusedThrowableCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/unused/UnusedThrowableCheckTest.java @@ -22,16 +22,14 @@ import org.junit.jupiter.api.Test; import org.sonar.java.checks.verifier.CheckVerifier; import org.sonar.java.checks.verifier.TestUtils; -import org.sonar.java.checks.verifier.internal.InternalCheckVerifier; class UnusedThrowableCheckTest { @Test void test() { - ((InternalCheckVerifier) CheckVerifier.newVerifier()) + CheckVerifier.newVerifier() .onFile(TestUtils.mainCodeSourcesPath("checks/unused/UnusedThrowableCheck.java")) .withCheck(new UnusedThrowableCheck()) - .withQuickFixes() .verifyIssues(); } } diff --git a/java-frontend/src/main/java/org/sonar/java/ast/visitors/CommentLinesVisitor.java b/java-frontend/src/main/java/org/sonar/java/ast/visitors/CommentLinesVisitor.java index b7dc02c3a8d..99a37406f5f 100644 --- a/java-frontend/src/main/java/org/sonar/java/ast/visitors/CommentLinesVisitor.java +++ b/java-frontend/src/main/java/org/sonar/java/ast/visitors/CommentLinesVisitor.java @@ -19,9 +19,13 @@ */ package org.sonar.java.ast.visitors; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.Collections; +import java.util.HashMap; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Set; import org.sonar.java.model.LineUtils; import org.sonar.plugins.java.api.tree.CompilationUnitTree; @@ -33,6 +37,7 @@ public class CommentLinesVisitor extends SubscriptionVisitor { private Set comments = new HashSet<>(); private Set noSonarLines = new HashSet<>(); + private Map> syntaxTrivia = new HashMap<>(); private boolean seenFirstToken; @Override @@ -43,6 +48,7 @@ public List nodesToVisit() { public void analyzeCommentLines(CompilationUnitTree tree) { comments.clear(); noSonarLines.clear(); + syntaxTrivia.clear(); seenFirstToken = false; scanTree(tree); } @@ -63,15 +69,24 @@ private void handleCommentsForTrivia(SyntaxTrivia trivia) { String[] commentLines = getContents(trivia.comment()).split("(\r)?\n|\r", -1); int line = LineUtils.startLine(trivia); for (String commentLine : commentLines) { - if(commentLine.contains("NOSONAR")) { + if (commentLine.contains("NOSONAR")) { noSonarLines.add(line); } else if (!isBlank(commentLine)) { + Path path = Path.of(""); + if (context != null) { + path = Paths.get(context.getInputFile().uri()); + } + syntaxTrivia.computeIfAbsent(path, k -> new HashSet<>()).add(trivia); comments.add(line); } line++; } } + public Map> getSyntaxTrivia() { + return syntaxTrivia; + } + public Set noSonarLines() { return noSonarLines; } @@ -91,7 +106,6 @@ private static boolean isBlank(String line) { return true; } - private static String getContents(String comment) { return comment.startsWith("//") ? comment.substring(2) : comment.substring(2, comment.length() - 2); } diff --git a/java-symbolic-execution/src/test/java/org/sonar/java/se/SECheckVerifier.java b/java-symbolic-execution/src/test/java/org/sonar/java/se/SECheckVerifier.java index 3f90c8f52ac..4c65cca225a 100644 --- a/java-symbolic-execution/src/test/java/org/sonar/java/se/SECheckVerifier.java +++ b/java-symbolic-execution/src/test/java/org/sonar/java/se/SECheckVerifier.java @@ -45,7 +45,7 @@ public static SECheckVerifier newVerifier() { } private SECheckVerifier() { - checkVerifier = (InternalCheckVerifier) CheckVerifier.newVerifier(); + checkVerifier = (InternalCheckVerifier) CheckVerifier.newInternalVerifier(); } @Override diff --git a/pom.xml b/pom.xml index eac4d2dbd1e..40a4875555e 100644 --- a/pom.xml +++ b/pom.xml @@ -87,13 +87,13 @@ true 10.4.1.88267 - 10.2.0.1908 9.8.0.76914 - 2.8.0.2699 + 2.11.0.2861 3.40.0.183 1.24.0.633 -Xmx512m