repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/EmptyCatchPositiveCases.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; /** * @author yuan@ece.toronto.edu (Ding Yuan) */ public class EmptyCatchPositiveCases { public void error() throws IllegalArgumentException { throw new IllegalArgumentException("Fake exception."); } public void catchIsCompleteEmpty() { try { error(); } // BUG: Diagnostic contains: catch (Throwable t) { } } }
1,002
26.861111
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ArrayEqualsNegativeCases.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import com.google.common.base.Objects; /** * @author eaftan@google.com (Eddie Aftandilian) */ public class ArrayEqualsNegativeCases { public void neitherArray() { Object a = new Object(); Object b = new Object(); if (a.equals(b)) { System.out.println("Objects are equal!"); } else { System.out.println("Objects are not equal!"); } if (Objects.equal(a, b)) { System.out.println("Objects are equal!"); } else { System.out.println("Objects are not equal!"); } } public void firstArray() { Object[] a = new Object[3]; Object b = new Object(); if (a.equals(b)) { System.out.println("arrays are equal!"); } else { System.out.println("arrays are not equal!"); } if (Objects.equal(a, b)) { System.out.println("Objects are equal!"); } else { System.out.println("Objects are not equal!"); } } public void secondArray() { Object a = new Object(); Object[] b = new Object[3]; if (a.equals(b)) { System.out.println("arrays are equal!"); } else { System.out.println("arrays are not equal!"); } if (Objects.equal(a, b)) { System.out.println("Objects are equal!"); } else { System.out.println("Objects are not equal!"); } } }
1,963
24.842105
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/OverridesNegativeCase3.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author cushon@google.com (Liam Miller-Cushon) */ public class OverridesNegativeCase3 { abstract class Base { abstract void arrayMethod(Object[] xs); } abstract class SubOne extends Base { @Override abstract void arrayMethod(Object[] xs); } abstract class SubTwo extends SubOne { @Override abstract void arrayMethod(Object[] xs); } abstract class SubThree extends SubTwo { @Override abstract void arrayMethod(Object[] xs); } }
1,134
27.375
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/BanSerializableReadPositiveCases.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import com.google.errorprone.bugpatterns.BanSerializableReadTest; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.Serializable; /** * {@link BanSerializableReadTest} * * @author tshadwell@google.com (Thomas Shadwell) */ class BanSerializableReadPositiveCases implements Serializable { public final String hi = "hi"; /** * Says 'hi' by piping the string value unsafely through Object I/O stream * * @throws IOException * @throws ClassNotFoundException */ public static final void sayHi() throws IOException, ClassNotFoundException { PipedInputStream in = new PipedInputStream(); PipedOutputStream out = new PipedOutputStream(in); ObjectOutputStream serializer = new ObjectOutputStream(out); ObjectInputStream deserializer = new ObjectInputStream(in); serializer.writeObject(new BanSerializableReadPositiveCases()); serializer.close(); BanSerializableReadPositiveCases crime = // BUG: Diagnostic contains: BanSerializableRead (BanSerializableReadPositiveCases) deserializer.readObject(); System.out.println(crime.hi); } /** * The checker has a special allowlist that allows classes to define methods called readObject -- * Java accepts these as an override to the default serialization behaviour. While we want to * allow such methods to be defined, we don't want to allow these methods to be called. * * @throws IOException * @throws ClassNotFoundException */ public static final void directCall() throws IOException, ClassNotFoundException { PipedInputStream in = new PipedInputStream(); PipedOutputStream out = new PipedOutputStream(in); ObjectOutputStream serializer = new ObjectOutputStream(out); ObjectInputStream deserializer = new ObjectInputStream(in); BanSerializableReadPositiveCases self = new BanSerializableReadPositiveCases(); // BUG: Diagnostic contains: BanSerializableRead self.readObject(deserializer); } /** * The checker has a special allowlist that allows classes to define methods called readExternal. * Java accepts these as an override to the default serialization behaviour. While we want to * allow such methods to be defined, we don't want to allow these methods to be called. */ public static final void directCall2() throws IOException { PipedInputStream in = new PipedInputStream(); ObjectInputStream deserializer = new ObjectInputStream(in); BanSerializableReadNegativeCases neg = new BanSerializableReadNegativeCases(); // BUG: Diagnostic contains: BanSerializableRead neg.readExternal(deserializer); } public void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); } }
3,534
36.210526
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/InstanceOfAndCastMatchWrongTypePositiveCases.java
/* Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * Created by sulku and mariasam on 6/6/17. * * @author mariasam (Maria Sam) * @author sulku (Marsela Sulku) */ public class InstanceOfAndCastMatchWrongTypePositiveCases { private static void basicIllegalCast(Object foo2) { if (foo2 instanceof SuperClass) { // BUG: Diagnostic contains: Casting inside String str = ((String) foo2).toString(); } } private static void basicIllegalCastJavaClass(Object foo2) { if (foo2 instanceof String) { // BUG: Diagnostic contains: Casting inside double val = ((Integer) foo2).doubleValue(); } } private static void andsInIf(Object foo2) { if (foo2 instanceof String && 7 == 7) { // BUG: Diagnostic contains: Casting inside double val = ((Integer) foo2).doubleValue(); } } private static void andsInIfInstanceOfLast(Object foo2) { if (7 == 7 && foo2 instanceof String) { // BUG: Diagnostic contains: Casting inside double val = ((Integer) foo2).doubleValue(); } } private static void andsInIfInstanceOfMiddle(Object foo2) { if (7 == 7 && foo2 instanceof String && 8 == 8) { // BUG: Diagnostic contains: Casting inside double val = ((Integer) foo2).doubleValue(); } } private static void castingInIfWithElse(Object foo2) { if (foo2 instanceof String) { // BUG: Diagnostic contains: Casting inside String str = ((Integer) foo2).toString(); } else { String str = ""; } } private static void castMultipleInIfAndElse(Object foo2, Object foo3) { if (foo2 instanceof String) { String str = ((Integer) foo3).toString(); // BUG: Diagnostic contains: Casting inside String str2 = ((Integer) foo2).toString(); } else { String str = ((Integer) foo3).toString(); String str2 = ""; } } private static void multipleAndsInIf(Object foo2) { // BUG: Diagnostic contains: Casting inside if (7 == 7 && (foo2 instanceof SuperClass) && (((String) foo2).equals(""))) { String str = ""; } } private static void castOneObjectWithMultipleObjectsInIf(Object foo2, Object foo3) { if (7 == 7 && foo3 instanceof String && foo2 instanceof String) { // BUG: Diagnostic contains: Casting inside String str = ((Integer) foo2).toString(); } } private static void aboveTestButDifferentOrder(Object foo2, Object foo3) { if (7 == 7 && foo2 instanceof String && foo3 instanceof String) { // BUG: Diagnostic contains: Casting inside String str = ((Integer) foo2).toString(); } } private static void nestedIf(Object foo2) { if (foo2 instanceof String) { if (7 == 7) { // BUG: Diagnostic contains: Casting inside String str = ((Integer) foo2).toString(); } } } private static void nestedIfWithElse(Object foo2) { if (foo2 instanceof String) { if (7 == 7) { String str = ""; } else { // BUG: Diagnostic contains: Casting inside String str = ((Integer) foo2).toString(); } } } private static void assignmentInBlockDiffVariable(Object foo2) { String foo1; if (foo2 instanceof SuperClass) { foo1 = ""; // BUG: Diagnostic contains: Casting inside String str = ((Integer) foo2).toString(); } } private static void assignmentInBlock(Object foo2) { if (foo2 instanceof SuperClass) { // BUG: Diagnostic contains: Casting inside String str = ((Integer) foo2).toString(); foo2 = ""; } } private static void assignmentInBlockTwice(Object foo2) { Object foo1 = null; if (foo2 instanceof SuperClass) { foo1 = ""; // BUG: Diagnostic contains: Casting inside String str = ((Integer) foo2).toString(); foo2 = ""; } } private static void testSameClass(Object foo) { if (foo instanceof String) { InstanceOfAndCastMatchWrongTypePositiveCases other = // BUG: Diagnostic contains: Casting inside (InstanceOfAndCastMatchWrongTypePositiveCases) foo; } } private static void testElseIf(Object foo) { if (foo instanceof String) { String str = (String) foo; } else if (foo instanceof String) { // BUG: Diagnostic contains: Casting inside Integer i = (Integer) foo; } else { foo = (SuperClass) foo; } } public static String testCall() { return ""; } } class SuperClass {}
5,080
28.369942
86
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ShouldHaveEvenArgsNegativeCases.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import static com.google.common.truth.Truth.assertThat; import java.util.HashMap; import java.util.Map; /** * Negative test cases for {@link ShouldHaveEvenArgs} check. * * @author bhagwani@google.com (Sumit Bhagwani) */ public class ShouldHaveEvenArgsNegativeCases { private static final Map<String, String> map = new HashMap<String, String>(); public void testWithNoArgs() { assertThat(map).containsExactly(); } public void testWithMinimalArgs() { assertThat(map).containsExactly("hello", "there"); } public void testWithEvenArgs() { assertThat(map).containsExactly("hello", "there", "hello", "there"); } public void testWithVarargs(Object... args) { assertThat(map).containsExactly("hello", args); assertThat(map).containsExactly("hello", "world", args); } public void testWithArray() { String[] arg = {"hello", "there"}; assertThat(map).containsExactly("yolo", arg); String key = "hello"; Object[] value = new Object[] {}; Object[][] args = new Object[][] {}; assertThat(map).containsExactly(key, value); assertThat(map).containsExactly(key, value, (Object[]) args); assertThat(map).containsExactly(key, value, key, value, key, value); } }
1,893
29.063492
79
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ErroneousThreadPoolConstructorCheckerPositiveCases.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import static java.util.Comparator.comparingInt; import static java.util.concurrent.TimeUnit.SECONDS; import java.util.Collection; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedTransferQueue; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; /** * Positive test cases for {@link * com.google.errorprone.bugpatterns.ErroneousThreadPoolConstructorChecker} bug pattern. */ final class ErroneousThreadPoolConstructorCheckerPositiveCases { private static final int CORE_POOL_SIZE = 10; private static final int MAXIMUM_POOL_SIZE = 20; private static final long KEEP_ALIVE_TIME = 60; private void createThreadPoolWithUnboundedLinkedBlockingQueue(Collection<Runnable> initialTasks) { // BUG: Diagnostic contains: ErroneousThreadPoolConstructorChecker new ThreadPoolExecutor( CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, SECONDS, new LinkedBlockingQueue<>()); // BUG: Diagnostic contains: ErroneousThreadPoolConstructorChecker new ThreadPoolExecutor( CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, SECONDS, new LinkedBlockingQueue<>(initialTasks)); } private void createThreadPoolWithUnboundedLinkedBlockingDeque(Collection<Runnable> initialTasks) { // BUG: Diagnostic contains: ErroneousThreadPoolConstructorChecker new ThreadPoolExecutor( CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, SECONDS, new LinkedBlockingDeque<>()); // BUG: Diagnostic contains: ErroneousThreadPoolConstructorChecker new ThreadPoolExecutor( CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, SECONDS, new LinkedBlockingDeque<>(initialTasks)); } private void createThreadPoolWithUnboundedLinkedTransferQueue(Collection<Runnable> initialTasks) { // BUG: Diagnostic contains: ErroneousThreadPoolConstructorChecker new ThreadPoolExecutor( CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, SECONDS, new LinkedTransferQueue<>()); // BUG: Diagnostic contains: ErroneousThreadPoolConstructorChecker new ThreadPoolExecutor( CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, SECONDS, new LinkedTransferQueue<>(initialTasks)); } private void createThreadPoolWithUnboundedPriorityBlockingQueue( int initialCapacity, Collection<Runnable> initialTasks) { // BUG: Diagnostic contains: ErroneousThreadPoolConstructorChecker new ThreadPoolExecutor( CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, SECONDS, new PriorityBlockingQueue<>()); // BUG: Diagnostic contains: ErroneousThreadPoolConstructorChecker new ThreadPoolExecutor( CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, SECONDS, new PriorityBlockingQueue<>(initialTasks)); // BUG: Diagnostic contains: ErroneousThreadPoolConstructorChecker new ThreadPoolExecutor( CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, SECONDS, new PriorityBlockingQueue<>(initialCapacity)); // BUG: Diagnostic contains: ErroneousThreadPoolConstructorChecker new ThreadPoolExecutor( CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, SECONDS, new PriorityBlockingQueue<>(initialCapacity, comparingInt(Object::hashCode))); } }
4,133
38
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/UnnecessaryBoxedAssignmentCases.java
/* * Copyright 2019 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author awturner@google.com (Andy Turner) */ class UnnecessaryBoxedAssignmentCases { void negative_void() { return; } boolean positive_booleanPrimitive(boolean aBoolean) { return Boolean.valueOf(aBoolean); } Boolean positive_booleanWrapped(boolean aBoolean) { Boolean b = Boolean.valueOf(aBoolean); return Boolean.valueOf(aBoolean); } Boolean negative_booleanString(String aString) { Boolean b = Boolean.valueOf(aString); return Boolean.valueOf(aString); } byte positive_bytePrimitive(byte aByte) { return Byte.valueOf(aByte); } Byte positive_byteWrapped(byte aByte) { Byte b = Byte.valueOf(aByte); return Byte.valueOf(aByte); } Byte negative_byteString(String aString) { Byte b = Byte.valueOf(aString); return Byte.valueOf(aString); } int positive_integerPrimitive(int aInteger) { return Integer.valueOf(aInteger); } Integer positive_integerWrapped(int aInteger) { Integer i = Integer.valueOf(aInteger); return Integer.valueOf(aInteger); } Integer negative_integerString(String aString) { Integer i = Integer.valueOf(aString); return Integer.valueOf(aString); } Long negative_integerWrapped(int aInteger) { Long aLong = Long.valueOf(aInteger); return Long.valueOf(aInteger); } Integer positive_wrappedAgain(int aInteger) { Integer a = Integer.valueOf(aInteger); a = Integer.valueOf(aInteger); return Integer.valueOf(a); } }
2,138
25.7375
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/DeadExceptionNegativeCases.java
/* * Copyright 2011 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; public class DeadExceptionNegativeCases { public void noError() { Exception e = new RuntimeException("stored"); e = new UnsupportedOperationException("also stored"); throw new IllegalArgumentException("thrown"); } public Exception returnsException() { return new RuntimeException("returned"); } }
984
31.833333
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ShouldHaveEvenArgsPositiveCases.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import static com.google.common.truth.Truth.assertThat; import com.google.common.truth.Correspondence; import java.util.HashMap; import java.util.Map; /** * Positive test cases for {@link ShouldHaveEvenArgs} check. * * @author bhagwani@google.com (Sumit Bhagwani) */ public class ShouldHaveEvenArgsPositiveCases { private static final Map map = new HashMap<String, String>(); public void testWithOddArgs() { // BUG: Diagnostic contains: even number of arguments assertThat(map).containsExactly("hello", "there", "rest"); // BUG: Diagnostic contains: even number of arguments assertThat(map).containsExactly("hello", "there", "hello", "there", "rest"); // BUG: Diagnostic contains: even number of arguments assertThat(map).containsExactly(null, null, null, null, new Object[] {}); } public void testWithArrayArgs() { String key = "hello"; Object[] value = new Object[] {}; Object[][] args = new Object[][] {}; // BUG: Diagnostic contains: even number of arguments assertThat(map).containsExactly(key, value, (Object) args); } public void testWithOddArgsWithCorrespondence() { assertThat(map) .comparingValuesUsing(Correspondence.from((a, b) -> true, "dummy")) // BUG: Diagnostic contains: even number of arguments .containsExactly("hello", "there", "rest"); assertThat(map) .comparingValuesUsing(Correspondence.from((a, b) -> true, "dummy")) // BUG: Diagnostic contains: even number of arguments .containsExactly("hello", "there", "hello", "there", "rest"); } }
2,251
33.121212
80
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/RethrowReflectiveOperationExceptionAsLinkageErrorNegativeCases.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.io.IOException; public class RethrowReflectiveOperationExceptionAsLinkageErrorNegativeCases { void assertionErrorNonStringConstructor() { try { throw new ReflectiveOperationException(); } catch (ReflectiveOperationException e) { throw new AssertionError(1); } } void assertionErrorNoArgConstructor() { try { throw new ReflectiveOperationException(); } catch (ReflectiveOperationException e) { throw new AssertionError(); } } void noThrowAssertionError() { try { throw new ReflectiveOperationException(); } catch (ReflectiveOperationException e) { throw new IllegalStateException(e); } } void noCatchReflectiveOperationException() { try { throw new ReflectiveOperationException(); } catch (Exception e) { throw new AssertionError(e); } } void multiCatchExceptions() { try { int a = 100; if (a < 100) { throw new IOException("Test"); } throw new ReflectiveOperationException(); } catch (IOException | ReflectiveOperationException e) { throw new AssertionError(e); } } void throwNewReflectiveOperationException() { throw new AssertionError(new ReflectiveOperationException("Test")); } }
1,938
26.7
77
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/StaticQualifiedUsingExpressionPositiveCase1.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.math.BigDecimal; /** * @author eaftan@google.com (Eddie Aftandilian) */ class MyClass { static int STATIC_FIELD = 42; static int staticMethod() { return 42; } int FIELD = 42; int method() { return 42; } static class StaticInnerClass { static final MyClass myClass = new MyClass(); } } class MyStaticClass { static MyClass myClass = new MyClass(); } public class StaticQualifiedUsingExpressionPositiveCase1 { public static int staticVar1 = 1; private StaticQualifiedUsingExpressionPositiveCase1 next; public static int staticTestMethod() { return 1; } public static Object staticTestMethod2() { return new Object(); } public static Object staticTestMethod3(Object x) { return null; } public void test1() { StaticQualifiedUsingExpressionPositiveCase1 testObj = new StaticQualifiedUsingExpressionPositiveCase1(); int i; // BUG: Diagnostic contains: variable staticVar1 // i = staticVar1 i = this.staticVar1; // BUG: Diagnostic contains: variable staticVar1 // i = staticVar1 i = testObj.staticVar1; // BUG: Diagnostic contains: variable staticVar1 // i = staticVar1 i = testObj.next.next.next.staticVar1; } public void test2() { int i; Integer integer = Integer.valueOf(1); // BUG: Diagnostic contains: variable MAX_VALUE // i = Integer.MAX_VALUE i = integer.MAX_VALUE; } public void test3() { String s1 = new String(); // BUG: Diagnostic contains: method valueOf // String s2 = String.valueOf(10) String s2 = s1.valueOf(10); // BUG: Diagnostic contains: method valueOf // s2 = String.valueOf(10) s2 = new String().valueOf(10); // BUG: Diagnostic contains: method staticTestMethod // int i = staticTestMethod() int i = this.staticTestMethod(); // BUG: Diagnostic contains: method staticTestMethod2 // String s3 = staticTestMethod2().toString String s3 = this.staticTestMethod2().toString(); // BUG: Diagnostic contains: method staticTestMethod // i = staticTestMethod() i = this.next.next.next.staticTestMethod(); } public void test4() { BigDecimal decimal = new BigDecimal(1); // BUG: Diagnostic contains: method valueOf // BigDecimal decimal2 = BigDecimal.valueOf(1) BigDecimal decimal2 = decimal.valueOf(1); } public static MyClass hiding; public void test5(MyClass hiding) { // BUG: Diagnostic contains: method staticTestMethod3 // Object o = staticTestMethod3(this.toString()) Object o = this.staticTestMethod3(this.toString()); // BUG: Diagnostic contains: variable myClass // x = MyClass.StaticInnerClass.myClass.FIELD; int x = new MyClass.StaticInnerClass().myClass.FIELD; // BUG: Diagnostic contains: variable STATIC_FIELD // x = MyClass.STATIC_FIELD; x = new MyClass.StaticInnerClass().myClass.STATIC_FIELD; // BUG: Diagnostic contains: variable hiding // StaticQualifiedUsingExpressionPositiveCase1.hiding = hiding; this.hiding = hiding; // BUG: Diagnostic contains: variable STATIC_FIELD // x = MyClass.STATIC_FIELD; x = MyStaticClass.myClass.STATIC_FIELD; // BUG: Diagnostic contains: method staticMethod // x = MyClass.staticMethod(); x = MyStaticClass.myClass.staticMethod(); x = MyStaticClass.myClass.FIELD; x = MyStaticClass.myClass.method(); } static class Bar { static int baz = 0; static int baz() { return 42; } } static class Foo { static Bar bar; } static void test6() { Foo foo = new Foo(); // BUG: Diagnostic contains: method baz // x = Bar.baz(); int x = Foo.bar.baz(); Bar bar = Foo.bar; // BUG: Diagnostic contains: variable bar // bar = Foo.bar; bar = foo.bar; // BUG: Diagnostic contains: variable baz // x = Bar.baz; x = Foo.bar.baz; } static class C<T extends String> { static int foo() { return 42; } } public void test7() { // BUG: Diagnostic contains: method foo // x = C.foo(); int x = new C<String>().foo(); } }
4,772
25.814607
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ClassCanBeStaticNegativeCases.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author alexloh@google.com (Alex Loh) */ public class ClassCanBeStaticNegativeCases { int outerVar; public int outerMethod() { return 0; } public static class Inner1 { // inner class already static int innerVar; } public class Inner2 { // inner class references an outer variable int innerVar = outerVar; } public class Inner3 { // inner class references an outer variable in a method int localMethod() { return outerVar; } } public class Inner4 { // inner class references an outer method in a method int localMethod() { return outerMethod(); } } // outer class is a nested but non-static, and thus cannot have a static class class NonStaticOuter { int nonStaticVar = outerVar; class Inner5 {} } // inner class is local and thus cannot be static void foo() { class Inner6 {} } // inner class is anonymous and thus cannot be static Object bar() { return new Object() {}; } // enums are already static enum Inner7 { RED, BLUE, VIOLET, } // outer class is a nested but non-static, and thus cannot have a static class void baz() { class NonStaticOuter2 { int nonStaticVar = outerVar; class Inner8 {} } } // inner class references a method from inheritance public interface OuterInter { int outerInterMethod(); } abstract static class AbstractOuter implements OuterInter { class Inner8 { int localMethod() { return outerInterMethod(); } } } }
2,205
22.221053
80
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/OverrideThrowableToStringNegativeCases.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author mariasam@google.com (Maria Sam) */ public class OverrideThrowableToStringNegativeCases { class BasicTest extends Throwable {} class OtherToString { public String toString() { return ""; } } class NoToString extends Throwable { public void test() { System.out.println("test"); } } class GetMessage extends Throwable { public String getMessage() { return ""; } } class OverridesBoth extends Throwable { public String toString() { return ""; } public String getMessage() { return ""; } } }
1,258
22.754717
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/IncrementInForLoopAndHeaderNegativeCases.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.util.List; /** Created by mariasam on 7/20/17. */ public class IncrementInForLoopAndHeaderNegativeCases { public void arrayInc() { for (int[] level = {}; level[0] > 10; level[0]--) { System.out.println("test"); } } public void emptyForLoop() { for (int i = 0; i < 2; i++) {} } public void inIf() { for (int i = 0; i < 20; i++) { if (i == 7) { i++; } } } public void inWhile() { for (int i = 0; i < 20; i++) { while (i == 7) { i++; } } } public void inDoWhile() { for (int i = 0; i < 20; i++) { do { i++; } while (i == 7); } } public void inFor() { for (int i = 0; i < 20; i++) { for (int a = 0; a < i; a++) { i++; } } } public void inForEach(List<String> list) { for (int i = 0; i < 10; i++) { for (String s : list) { i++; } } } public void otherVarInc() { for (int i = 0; i < 2; i++) { int a = 0; a++; } } }
1,701
20.275
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/UnsafeReflectiveConstructionCastNegativeCases.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * Negative cases for {@link UnsafeReflectiveConstructionCast}. * * @author bhagwani@google.com (Sumit Bhagwani) */ public class UnsafeReflectiveConstructionCastNegativeCases { public String newInstanceDirectCall() throws Exception { return (String) Class.forName("java.lang.String").newInstance(); } public String newInstanceDirectlyOnClassAndGetDeclaredConstructor() throws Exception { return (String) String.class.getDeclaredConstructor().newInstance(); } public String newInstanceDirectlyOnClassAndNewInstance() throws Exception { return (String) String.class.newInstance(); } public String invocationWithAsSubclass() throws Exception { return Class.forName("java.lang.String").asSubclass(String.class).newInstance(); } public class Supplier<T> { public T get(String className) { try { return (T) Class.forName(className).getDeclaredConstructor().newInstance(); } catch (ReflectiveOperationException e) { throw new IllegalStateException(e); } } } }
1,705
31.807692
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/GetClassOnClassPositiveCases.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author chy@google.com (Christine Yang) * @author kmuhlrad@google.com (Katy Muhlrad) */ public class GetClassOnClassPositiveCases { public void getClassOnClass(Class clazz) { // BUG: Diagnostic contains: clazz.getName() System.out.println(clazz.getClass().getName()); } public void getClassOnClass2() { String s = "hi"; // BUG: Diagnostic contains: s.getClass().getName() s.getClass().getClass().getName(); } public void getClassOnClass3() { // BUG: Diagnostic contains: String.class.getName() System.out.println(String.class.getClass().getName()); } }
1,267
29.926829
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/SelfEqualsPositiveCase.java
/* * Copyright 2011 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import static com.google.common.truth.Truth.assertThat; import org.junit.Assert; /** * Positive test cases for {@link SelfEquals} check. * * @author eaftan@google.com (Eddie Aftandilian) * @author bhagwani@google.com (Sumit Bhagwani) */ public class SelfEqualsPositiveCase { protected String simpleField; public boolean test1(Object obj) { if (obj == null || getClass() != obj.getClass()) { return false; } SelfEqualsPositiveCase other = (SelfEqualsPositiveCase) obj; // BUG: Diagnostic contains: simpleField.equals(other.simpleField); return simpleField.equals(simpleField); } public boolean test2(SelfEqualsPositiveCase obj) { if (obj == null || getClass() != obj.getClass()) { return false; } SelfEqualsPositiveCase other = (SelfEqualsPositiveCase) obj; // BUG: Diagnostic contains: simpleField.equals(other.simpleField); return simpleField.equals(this.simpleField); } public boolean test3(SelfEqualsPositiveCase obj) { if (obj == null || getClass() != obj.getClass()) { return false; } SelfEqualsPositiveCase other = (SelfEqualsPositiveCase) obj; // BUG: Diagnostic contains: this.simpleField.equals(other.simpleField); return this.simpleField.equals(simpleField); } public boolean test4(SelfEqualsPositiveCase obj) { if (obj == null || getClass() != obj.getClass()) { return false; } SelfEqualsPositiveCase other = (SelfEqualsPositiveCase) obj; // BUG: Diagnostic contains: this.simpleField.equals(other.simpleField); return this.simpleField.equals(this.simpleField); } public boolean test5(SelfEqualsPositiveCase obj) { if (obj == null || getClass() != obj.getClass()) { return false; } SelfEqualsPositiveCase other = (SelfEqualsPositiveCase) obj; // BUG: Diagnostic contains: return equals(this); } public void testAssertTrue(SelfEqualsPositiveCase obj) { Assert.assertTrue(obj.equals(obj)); } public void testAssertThat(SelfEqualsPositiveCase obj) { assertThat(obj.equals(obj)).isTrue(); } @Override public boolean equals(Object obj) { if (obj == null || getClass() != obj.getClass()) { return false; } SelfEqualsPositiveCase other = (SelfEqualsPositiveCase) obj; return simpleField.equals(((SelfEqualsPositiveCase) other).simpleField); } private static class SubClass extends SelfEqualsPositiveCase { @Override public boolean equals(Object obj) { if (obj == null || getClass() != obj.getClass()) { return false; } SubClass other = (SubClass) obj; return simpleField.equals(((SubClass) other).simpleField); } } public void testSub() { SubClass sc = new SubClass(); // BUG: Diagnostic contains: sc.equals(sc); } }
3,460
30.18018
76
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/BanJNDIPositiveCases_expected.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import com.google.security.annotations.SuppressBanJNDICompletedSecurityReview; import java.io.IOException; import java.util.Hashtable; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import javax.management.remote.rmi.RMIConnector; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.Name; import javax.naming.NamingException; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.sql.rowset.spi.SyncFactory; import javax.sql.rowset.spi.SyncFactoryException; /** * {@link BanJNDITest} * * @author tshadwell@google.com (Thomas Shadwell) */ class BanJNDIPositiveCases { private static DirContext FakeDirContext = ((DirContext) new Object()); @SuppressBanJNDICompletedSecurityReview private void callsModifyAttributes() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeDirContext.modifyAttributes(((Name) new Object()), 0, ((Attributes) new Object())); } @SuppressBanJNDICompletedSecurityReview private void callsGetAttributes() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeDirContext.getAttributes(((Name) new Object())); } @SuppressBanJNDICompletedSecurityReview private void callsSearch() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeDirContext.search(((Name) new Object()), ((Attributes) new Object())); } @SuppressBanJNDICompletedSecurityReview private void callsGetSchema() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeDirContext.getSchema(((Name) new Object())); } @SuppressBanJNDICompletedSecurityReview private void callsGetSchemaClassDefinition() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeDirContext.getSchemaClassDefinition(((Name) new Object())); } private static Context FakeContext = ((Context) new Object()); @SuppressBanJNDICompletedSecurityReview private void callsLookup() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeContext.lookup("hello"); } @SuppressBanJNDICompletedSecurityReview private void callsSubclassLookup() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeDirContext.lookup("hello"); } @SuppressBanJNDICompletedSecurityReview private void callsBind() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeContext.bind(((Name) new Object()), new Object()); } @SuppressBanJNDICompletedSecurityReview private void subclassCallsBind() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeDirContext.bind(((Name) new Object()), new Object()); } @SuppressBanJNDICompletedSecurityReview private void callsRebind() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeContext.rebind(((Name) new Object()), new Object()); } @SuppressBanJNDICompletedSecurityReview private void subclassCallsRebind() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeDirContext.rebind(((Name) new Object()), new Object()); } @SuppressBanJNDICompletedSecurityReview private void callsCreateSubcontext() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeContext.createSubcontext((Name) new Object()); } @SuppressBanJNDICompletedSecurityReview private void subclassCallsCreateSubcontext() throws NamingException { // BUG: Diagnostic contains: BanJNDI FakeDirContext.createSubcontext((Name) new Object()); } RMIConnector fakeRMIConnector = ((RMIConnector) new Object()); @SuppressBanJNDICompletedSecurityReview private void callsRMIConnect() throws IOException { // BUG: Diagnostic contains: BanJNDI fakeRMIConnector.connect(); } @SuppressBanJNDICompletedSecurityReview private void callsEnumerateBindings() throws SyncFactoryException { // BUG: Diagnostic contains: BanJNDI SyncFactory.getInstance("fear is the little-death"); } // unable to load javax.jdo for testing (must be some super optional pkg?) @SuppressBanJNDICompletedSecurityReview private void callsJMXConnectorFactoryConnect() throws IOException { // BUG: Diagnostic contains: BanJNDI JMXConnectorFactory.connect(((JMXServiceURL) new Object())); } @SuppressBanJNDICompletedSecurityReview private void callsDoLookup() throws NamingException { // BUG: Diagnostic contains: BanJNDI InitialContext.doLookup(((Name) new Object())); } @SuppressBanJNDICompletedSecurityReview private static boolean callToJMXConnectorFactoryConnect() throws java.net.MalformedURLException, java.io.IOException { JMXConnector connector = // BUG: Diagnostic contains: BanJNDI JMXConnectorFactory.connect( new JMXServiceURL("service:jmx:rmi:///jndi/rmi:// fake data 123 ")); connector.connect(); return false; } @SuppressBanJNDICompletedSecurityReview private Object subclassesJavaNamingcontext() throws NamingException { InitialContext c = new InitialContext(new Hashtable(0)); // BUG: Diagnostic contains: BanJNDI return c.lookup("hello"); } }
5,870
33.535294
91
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnitAssertSameCheckNegativeCases.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * Negative test cases for {@link JUnitAssertSameCheck} check. * * @author bhagwani@google.com (Sumit Bhagwani) */ public class JUnitAssertSameCheckNegativeCases { public void test(Object obj1, Object obj2) { org.junit.Assert.assertSame(obj1, obj2); org.junit.Assert.assertSame("message", obj1, obj2); junit.framework.Assert.assertSame(obj1, obj2); junit.framework.Assert.assertSame("message", obj1, obj2); } }
1,101
32.393939
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/UnnecessaryBoxedAssignmentCases_expected.java
/* * Copyright 2019 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author awturner@google.com (Andy Turner) */ class UnnecessaryBoxedAssignmentCases { void negative_void() { return; } boolean positive_booleanPrimitive(boolean aBoolean) { return aBoolean; } Boolean positive_booleanWrapped(boolean aBoolean) { Boolean b = aBoolean; return aBoolean; } Boolean negative_booleanString(String aString) { Boolean b = Boolean.valueOf(aString); return Boolean.valueOf(aString); } byte positive_bytePrimitive(byte aByte) { return aByte; } Byte positive_byteWrapped(byte aByte) { Byte b = aByte; return aByte; } Byte negative_byteString(String aString) { Byte b = Byte.valueOf(aString); return Byte.valueOf(aString); } int positive_integerPrimitive(int aInteger) { return aInteger; } Integer positive_integerWrapped(int aInteger) { Integer i = aInteger; return aInteger; } Integer negative_integerString(String aString) { Integer i = Integer.valueOf(aString); return Integer.valueOf(aString); } Long negative_integerWrapped(int aInteger) { Long aLong = Long.valueOf(aInteger); return Long.valueOf(aInteger); } Integer positive_wrappedAgain(int aInteger) { Integer a = aInteger; a = aInteger; return a; } }
1,943
23.3
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ThreadJoinLoopNegativeCases.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.util.List; /** * @author mariasam@google.com (Maria Sam) on 7/10/17. */ public class ThreadJoinLoopNegativeCases { public void basicCase(Thread thread) throws InterruptedException { thread.join(); } public void inIf(Thread thread) { try { if (7 == 7) { thread.join(); } } catch (InterruptedException e) { e.printStackTrace(); } } public void basicCaseTry(Thread thread) { try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } public void basicCaseWhile(Thread thread, List<String> list) { while (list.size() == 7) { try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } public void basicCaseFor(Thread thread, List<String> list) { for (int i = 0; i < list.size(); i++) { try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } public void basicCaseForEach(Thread thread, List<String> list) { for (String str : list) { try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } public void multipleCatches(Thread thread, int[] arr) { try { thread.join(); int test = arr[10]; } catch (ArrayIndexOutOfBoundsException e) { // ignore } catch (InterruptedException e) { System.out.println("test"); } } public void fullInterruptedFullException(Thread thread) { try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void justException(Thread thread) { try { thread.join(); } catch (Exception e) { e.printStackTrace(); } } public void multipleMethodInvocations(Thread thread, Thread thread2) { try { thread.join(); thread2.join(); } catch (Exception e) { e.printStackTrace(); } } public void tryFinally(Thread thread) { try { thread.join(); } catch (InterruptedException e) { // ignore } finally { System.out.println("test finally"); } } public void tryAssigningThread(Thread thread) { while (true) { try { thread.join(); thread = null; } catch (InterruptedException e) { // ignore } } } }
3,107
21.852941
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ModifySourceCollectionInStreamNegativeCases.java
/* * Copyright 2019 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.bugpatterns.testdata; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Test cases for {@link com.google.errorprone.bugpatterns.ModifySourceCollectionInStream}. * * @author deltazulu@google.com (Donald Duo Zhao) */ public class ModifySourceCollectionInStreamNegativeCases { private final List<Integer> mutableValues = Arrays.asList(1, 2, 3); private void mutateStreamSourceMethodReference() { List<Integer> mutableValues = new ArrayList<>(); mutableValues.stream().map(x -> x + 1).filter(x -> x < 5).forEach(this.mutableValues::add); mutableValues.forEach(this.mutableValues::add); ModifySourceCollectionInStreamNegativeCases[] cases = { new ModifySourceCollectionInStreamNegativeCases(), new ModifySourceCollectionInStreamNegativeCases() }; cases[0].mutableValues.stream() .map(x -> x + 1) .filter(x -> x < 5) .forEach(cases[1].mutableValues::add); } private List<Integer> mutateStreamSourceLambdaExpression() { List<Integer> localCopy = new ArrayList<>(); Stream<Integer> values1 = mutableValues.stream() .map( x -> { localCopy.add(x); return x + 1; }); Stream<Integer> values2 = mutableValues.stream() .filter( x -> { localCopy.remove(x); return mutableValues.size() > 5; }); return Stream.concat(values1, values2).collect(Collectors.toList()); } private void mutateStreamSourceInNonStreamApi() { mutableValues.stream() .map(x -> x + 1) .filter(x -> x < 5) .findAny() .ifPresent(mutableValues::add); mutableValues.stream() .map(x -> x + 1) .filter(x -> x < 5) .findFirst() .ifPresent(value -> mutableValues.remove(value)); } private void mutateDifferentStreamSource() { // Mutate a different stream source. mutableValues.stream().filter(x -> x < 5).collect(Collectors.toList()).stream() .forEach(mutableValues::remove); // Mutate source collection whose stream has been closed. mutableValues.stream() .filter(x -> x < 5) .collect(Collectors.toList()) .forEach(mutableValue -> mutableValues.remove(mutableValue)); } private void mutateNonCollectionStreamSource(CustomContainer<Double> vals) { vals.stream().map(x -> 2.0 * x).forEach(vals::add); } private void lambdaExpressionAsInitializer(List<Double> vals) { Consumer<Double> consumer = x -> vals.remove(x); } private interface CustomContainer<T> { Stream<T> stream(); boolean add(T t); } }
3,453
29.298246
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnit4SetUpNotRunPositiveCaseCustomBefore2.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Test case with a custom Before annotation. */ @RunWith(JUnit4.class) public class JUnit4SetUpNotRunPositiveCaseCustomBefore2 { // This will compile-fail and suggest the import of org.junit.Before // BUG: Diagnostic contains: @Before @Before public void initMocks() {} // BUG: Diagnostic contains: @Before @Before protected void badVisibility() {} } @interface Before {}
1,119
30.111111
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/NonRuntimeAnnotationPositiveCases.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * @author scottjohnson@google.com (Scott Johnsson) */ @NonRuntimeAnnotationPositiveCases.NotSpecified @NonRuntimeAnnotationPositiveCases.NonRuntime public class NonRuntimeAnnotationPositiveCases { public NonRuntime testAnnotation() { // BUG: Diagnostic contains: runtime; NonRuntime NonRuntimeAnnotationPositiveCases.class.getAnnotation( NonRuntimeAnnotationPositiveCases.NonRuntime.class); // BUG: Diagnostic contains: NonRuntimeAnnotationPositiveCases.class.getAnnotation( NonRuntimeAnnotationPositiveCases.NotSpecified.class); // BUG: Diagnostic contains: return this.getClass().getAnnotation(NonRuntimeAnnotationPositiveCases.NonRuntime.class); } /** Annotation that is explicitly NOT retained at runtime */ @Retention(RetentionPolicy.SOURCE) public @interface NonRuntime {} /** Annotation that is implicitly NOT retained at runtime */ public @interface NotSpecified {} }
1,686
34.893617
93
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/FuturesGetCheckedIllegalExceptionTypeNegativeCases.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.bugpatterns.testdata; import static com.google.common.util.concurrent.Futures.getChecked; import static java.util.concurrent.TimeUnit.SECONDS; import java.io.IOException; import java.util.concurrent.Future; /** Negative cases for {@link FuturesGetCheckedIllegalExceptionType}. */ public class FuturesGetCheckedIllegalExceptionTypeNegativeCases { <T extends Exception> void runtime(Future<?> future, Class<? extends Exception> c1, Class<T> c2) throws Exception { getChecked(future, Exception.class); getChecked(future, Exception.class, 0, SECONDS); getChecked(future, IOException.class); // These might or might not be RuntimeExceptions. We can't prove it one way or the other. getChecked(future, c1); getChecked(future, c2); getChecked(future, null); } <T extends ProtectedConstructorException> void constructor( Future<?> future, Class<? extends ProtectedConstructorException> c1, Class<T> c2) throws Exception { getChecked(future, StaticNestedWithExplicitConstructorException.class); getChecked(future, StaticNestedWithImplicitConstructorException.class); /* * These might be ProtectedConstructorException, but they might be a subtype with a public * constructor. */ getChecked(future, c1); getChecked(future, c2); } public static class StaticNestedWithExplicitConstructorException extends Exception { public StaticNestedWithExplicitConstructorException() {} } public static class StaticNestedWithImplicitConstructorException extends Exception {} public static class ProtectedConstructorException extends Exception { protected ProtectedConstructorException() {} } }
2,315
38.254237
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/MisusedWeekYearPositiveCases.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.Locale; public class MisusedWeekYearPositiveCases { void testConstructorWithLiteralPattern() { // BUG: Diagnostic contains: new SimpleDateFormat("yyyy-MM-dd") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd"); // BUG: Diagnostic contains: new SimpleDateFormat("yy-MM-dd") simpleDateFormat = new SimpleDateFormat("YY-MM-dd"); // BUG: Diagnostic contains: new SimpleDateFormat("y-MM-dd") simpleDateFormat = new SimpleDateFormat("Y-MM-dd"); // BUG: Diagnostic contains: new SimpleDateFormat("yyyyMMdd_HHmm") simpleDateFormat = new SimpleDateFormat("YYYYMMdd_HHmm"); // BUG: Diagnostic contains: new SimpleDateFormat("yyyy-MM-dd", DateFormatSymbols.getInstance()) simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd", DateFormatSymbols.getInstance()); // BUG: Diagnostic contains: new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()) simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd", Locale.getDefault()); } void testConstructorWithLiteralPatternWithFolding() { // TODO(eaftan): javac has a bug in that when it folds string literals, the start position of // the folded string literal node is set as the start position of the + operator. We have // fixed this in our internal javac, but haven't pushed the change to our external javac mirror. // We should push that fix to the javac mirror repo, and then we can test that the suggested // fix offered here is correct ("yyyy-MM-dd"). // BUG: Diagnostic contains: SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY" + "-MM-dd"); } private static final String WEEK_YEAR_PATTERN = "YYYY"; private static final String WEEK_YEAR_PATTERN_2 = "YY"; private static final String WEEK_YEAR_PATTERN_3 = "Y"; void testConstructorWithConstantPattern() { // BUG: Diagnostic contains: SimpleDateFormat simpleDateFormat = new SimpleDateFormat(WEEK_YEAR_PATTERN); } void testConstructorWithConstantPattern2() { // BUG: Diagnostic contains: SimpleDateFormat simpleDateFormat = new SimpleDateFormat(WEEK_YEAR_PATTERN_2); } void testConstructorWithConstantPattern3() { // BUG: Diagnostic contains: SimpleDateFormat simpleDateFormat = new SimpleDateFormat(WEEK_YEAR_PATTERN_3); } void testConstructorWithConstantPatternWithFolding() { // BUG: Diagnostic contains: SimpleDateFormat simpleDateFormat = new SimpleDateFormat(WEEK_YEAR_PATTERN + "-MM-dd"); } void testConstructorWithConstantPatternWithFolding2() { // BUG: Diagnostic contains: SimpleDateFormat simpleDateFormat = new SimpleDateFormat(WEEK_YEAR_PATTERN_2 + "-MM-dd"); } void testConstructorWithConstantPatternWithFolding3() { // BUG: Diagnostic contains: SimpleDateFormat simpleDateFormat = new SimpleDateFormat(WEEK_YEAR_PATTERN_3 + "-MM-dd"); } void testApplyPatternAndApplyLocalizedPatternWithLiteralPattern() { SimpleDateFormat sdf = new SimpleDateFormat(); // BUG: Diagnostic contains: sdf.applyPattern("yyyy-MM-dd") sdf.applyPattern("YYYY-MM-dd"); // BUG: Diagnostic contains: sdf.applyLocalizedPattern("yyyy-MM-dd") sdf.applyLocalizedPattern("YYYY-MM-dd"); } void testApplyPatternAndApplyLocalizedPatternWithConstantPattern() { SimpleDateFormat sdf = new SimpleDateFormat(); // BUG: Diagnostic contains: sdf.applyPattern(WEEK_YEAR_PATTERN); // BUG: Diagnostic contains: sdf.applyLocalizedPattern(WEEK_YEAR_PATTERN); } void testDateTimeFormatter() { // BUG: Diagnostic contains: java.time.format.DateTimeFormatter.ofPattern(WEEK_YEAR_PATTERN); } }
4,371
38.387387
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/MisusedWeekYearPositiveCases2.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import com.ibm.icu.text.DateFormatSymbols; import com.ibm.icu.text.SimpleDateFormat; import com.ibm.icu.util.ULocale; import java.util.Locale; /** Tests for {@link com.ibm.icu.text.SimpleDateFormat}. */ public class MisusedWeekYearPositiveCases2 { void testConstructors() { // BUG: Diagnostic contains: new SimpleDateFormat("yyyy-MM-dd") SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd"); // BUG: Diagnostic contains: sdf = new SimpleDateFormat("YYYY-MM-dd", DateFormatSymbols.getInstance()); // BUG: Diagnostic contains: sdf = new SimpleDateFormat("YYYY-MM-dd", DateFormatSymbols.getInstance(), ULocale.CANADA); // BUG: Diagnostic contains: sdf = new SimpleDateFormat("YYYY-MM-dd", Locale.getDefault()); // BUG: Diagnostic contains: sdf = new SimpleDateFormat("YYYY-MM-dd", "", ULocale.CANADA); // BUG: Diagnostic contains: sdf = new SimpleDateFormat("YYYY-MM-dd", ULocale.CANADA); } void testApplyPatternAndApplyLocalizedPattern() { SimpleDateFormat sdf = new SimpleDateFormat(); // BUG: Diagnostic contains: sdf.applyPattern("yyyy-MM-dd") sdf.applyPattern("YYYY-MM-dd"); // BUG: Diagnostic contains: sdf.applyLocalizedPattern("YYYY-MM-dd"); } }
1,902
33.6
94
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnit3TestNotRunNegativeCase4.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import junit.framework.TestCase; import org.junit.Test; /** * Abstract class - let's ignore those for now, it's hard to say what are they run with. * * @author rburny@google.com (Radoslaw Burny) */ public abstract class JUnit3TestNotRunNegativeCase4 extends TestCase { @Test public void name() {} public void tesMisspelled() {} @Test public void tesBothIssuesAtOnce() {} }
1,053
27.486486
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ProtocolBufferOrdinalPositiveCases.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import com.google.errorprone.bugpatterns.proto.ProtoTest.TestEnum; /** Positive test cases for {@link ProtocolBufferOrdinal} check. */ public class ProtocolBufferOrdinalPositiveCases { public static void checkCallOnOrdinal() { // BUG: Diagnostic contains: ProtocolBufferOrdinal TestEnum.TEST_ENUM_VAL.ordinal(); // BUG: Diagnostic contains: ProtocolBufferOrdinal ProtoLiteEnum.FOO.ordinal(); } enum ProtoLiteEnum implements com.google.protobuf.Internal.EnumLite { FOO(1), BAR(2); private final int number; private ProtoLiteEnum(int number) { this.number = number; } @Override public int getNumber() { return number; } } }
1,358
27.914894
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/CollectorShouldNotUseStatePositiveCases.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; import java.util.function.BiConsumer; import java.util.stream.Collector; /** * @author sulku@google.com (Marsela Sulku) */ public class CollectorShouldNotUseStatePositiveCases { public void test() { // BUG: Diagnostic contains: Collector.of() should not use state Collector.of( ImmutableList::builder, new BiConsumer<ImmutableList.Builder<Object>, Object>() { boolean isFirst = true; private static final String bob = "bob"; @Override public void accept(Builder<Object> objectBuilder, Object o) { if (isFirst) { System.out.println("it's first"); } else { objectBuilder.add(o); } } }, (left, right) -> left.addAll(right.build()), ImmutableList.Builder::build); // BUG: Diagnostic contains: Collector.of() should not use state Collector.of( ImmutableList::builder, new BiConsumer<ImmutableList.Builder<Object>, Object>() { boolean isFirst = true; private final String bob = "bob"; private final String joe = "joe"; @Override public void accept(Builder<Object> objectBuilder, Object o) { if (isFirst) { System.out.println("it's first"); } else { objectBuilder.add(o); } } }, (left, right) -> left.addAll(right.build()), ImmutableList.Builder::build); } }
2,263
31.342857
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/EqualsNaNPositiveCases.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author lowasser@google.com (Louis Wasserman) */ public class EqualsNaNPositiveCases { // BUG: Diagnostic contains: Double.isNaN(0.0) static final boolean ZERO_DOUBLE_NAN = 0.0 == Double.NaN; // BUG: Diagnostic contains: !Double.isNaN(1.0) static final boolean ONE_NOT_DOUBLE_NAN = Double.NaN != 1.0; // BUG: Diagnostic contains: Float.isNaN(2.f) static final boolean TWO_FLOAT_NAN = 2.f == Float.NaN; // BUG: Diagnostic contains: !Float.isNaN(3.0f) static final boolean THREE_NOT_FLOAT_NAN = 3.0f != Float.NaN; // BUG: Diagnostic contains: Double.isNaN(Double.NaN) static final boolean NAN_IS_NAN = Double.NaN == Double.NaN; // BUG: Diagnostic contains: Double.isNaN(123456) static final boolean INT_IS_NAN = 123456 == Double.NaN; }
1,434
33.166667
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/FutureReturnValueIgnoredNegativeCases.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import static com.google.common.util.concurrent.Futures.immediateFuture; import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import static org.junit.Assert.assertThrows; import static org.mockito.Mockito.doAnswer; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Supplier; import com.google.common.base.Ticker; import com.google.common.reflect.AbstractInvocationHandler; import com.google.common.util.concurrent.AbstractFuture; import com.google.common.util.concurrent.AsyncFunction; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.errorprone.annotations.CanIgnoreReturnValue; import io.netty.channel.ChannelFuture; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ForkJoinTask; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.RecursiveAction; import java.util.concurrent.ScheduledExecutorService; import org.junit.function.ThrowingRunnable; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; /** */ public class FutureReturnValueIgnoredNegativeCases { public FutureReturnValueIgnoredNegativeCases() {} static ListenableFuture<Object> getFuture() { return immediateFuture(null); } interface CanIgnoreMethod { @CanIgnoreReturnValue Future<Object> getFuture(); } public static class CanIgnoreImpl implements CanIgnoreMethod { @Override public Future<Object> getFuture() { return null; } } static void callIgnoredInterfaceMethod() { new CanIgnoreImpl().getFuture(); } @CanIgnoreReturnValue static ListenableFuture<Object> getFutureIgnore() { return immediateFuture(null); } static void putInMap() { Map<Object, Future<?>> map = new HashMap<>(); map.put(new Object(), immediateFuture(null)); Map map2 = new HashMap(); map2.put(new Object(), immediateFuture(null)); } static void preconditions() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Preconditions.checkNotNull(getFuture()); Preconditions.checkNotNull(new Object()); FutureReturnValueIgnoredNegativeCases.class.getDeclaredMethod("preconditions").invoke(null); } static void checkIgnore() { getFutureIgnore(); } void ignoreForkJoinTaskFork(ForkJoinTask<?> t) { t.fork(); } void ignoreForkJoinTaskFork_subclass(RecursiveAction t) { t.fork(); } void ignoreExecutorCompletionServiceSubmit(ExecutorCompletionService s) { s.submit(() -> null); } void ignoreChannelFutureAddListener(ChannelFuture cf) { cf.addListener((ChannelFuture f) -> {}); } void ignoreChannelFutureAddListeners(ChannelFuture cf) { cf.addListeners((ChannelFuture f) -> {}, (ChannelFuture f) -> {}); } <V> ListenableFuture<V> ignoreVarArgs( Callable<V> combiner, Executor executor, ListenableFuture<?>... futures) { return combine(combiner, executor, Arrays.asList(futures)); } public static <V> ListenableFuture<V> combine( final Callable<V> combiner, Executor executor, Iterable<? extends ListenableFuture<?>> futures) { return null; } private static final class TypedClass<T> { ListenableFuture<Void> ignoreReturnTypeSetByInputFuture(T input) { return returnsInputType(logAsyncInternal(input), 0); } protected ListenableFuture<Void> logAsyncInternal(T record) { return null; } <V> ListenableFuture<V> returnsInputType(ListenableFuture<V> future, final int n) { return null; } } public static class RetryingFuture<T> extends AbstractFuture<T> { /** * Enables the user to receive notifications about state changes of a retrying future, and use * them e.g. for logging. */ public interface Interceptor<T> {} /** Creates a builder for {@link RetryingFuture} instances. */ public static Builder<Object> builder() { return new Builder<>(); } /** A builder for {@link RetryingFuture} instances. */ public static final class Builder<T> { private Builder() {} /** Sets the {@link Executor} in which all tries and retries are performed. */ @CanIgnoreReturnValue public Builder<T> setExecutor(Executor executor) { return this; } /** * Sets the {@link ScheduledExecutorService} used for scheduling retries after delay. It will * also be used for tries and retries if {@link #setExecutor(Executor)} is not called. */ @CanIgnoreReturnValue public Builder<T> setScheduledExecutorService( ScheduledExecutorService scheduledExecutorService) { return this; } public <U extends T> Builder<U> setInterceptor(Interceptor<U> interceptor) { // Safely limiting the kinds of RetryingFutures this builder can produce, // based on the type of the interceptor. @SuppressWarnings("unchecked") Builder<U> me = (Builder<U>) this; return me; } public Builder<T> setTicker(Ticker ticker) { return this; } public <U extends T> RetryingFuture<U> build( Supplier<? extends ListenableFuture<U>> futureSupplier, Predicate<? super Exception> shouldContinue) { return new RetryingFuture<U>( futureSupplier, null, shouldContinue, null, // We need to maintain Java 7 compatibility null, null, null); } public <U extends T> RetryingFuture<U> build( Supplier<? extends ListenableFuture<U>> futureSupplier, Object strategy, Predicate<? super Exception> shouldContinue) { return new RetryingFuture<U>( futureSupplier, strategy, shouldContinue, null, // We need to maintain Java 7 compatibility null, null, null); } } RetryingFuture( Supplier<? extends ListenableFuture<T>> futureSupplier, Object strategy, Predicate<? super Exception> shouldContinue, Executor executor, ScheduledExecutorService scheduledExecutorService, Ticker ticker, final Interceptor<? super T> interceptor) {} public static <T> RetryingFuture<T> retryingFuture( Supplier<? extends ListenableFuture<T>> futureSupplier, Object strategy, Predicate<? super Exception> shouldContinue, Executor executor, Interceptor<? super T> interceptor) { return builder() .setInterceptor(interceptor) .setExecutor(executor) .build(futureSupplier, strategy, shouldContinue); } } private static class TypedObject<T> { public <O extends Object> ListenableFuture<O> transformAndClose( Function<? super T, O> function, Executor executor) { return null; } public ListenableFuture<T> close() { return transformAndClose(Functions.identity(), directExecutor()); } } private static void mocking() { doAnswer(invocation -> immediateFuture(null)).when(null); doAnswer( invocation -> { return immediateFuture(null); }) .when(null); doAnswer( new Answer() { @Override public Object answer(InvocationOnMock mock) { return immediateFuture(null); } }) .when(null); } private static void throwing() { assertThrows(RuntimeException.class, () -> immediateFuture(null)); assertThrows( RuntimeException.class, () -> { immediateFuture(null); }); assertThrows( RuntimeException.class, new ThrowingRunnable() { @Override public void run() throws Throwable { immediateFuture(null); } }); } private static AsyncFunction<String, String> provideAsyncFunction() { return Futures::immediateFuture; } private static Runnable provideNonFutureInterface() { return new FutureTask(null); } private static void invocation() { new AbstractInvocationHandler() { @Override protected Object handleInvocation(Object o, Method method, Object[] params) { return immediateFuture(null); } }; } }
9,481
29.785714
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/FloatingPointAssertionWithinEpsilonPositiveCases.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertEquals; /** * Positive test cases for FloatingPointAssertionWithinEpsilon check. * * @author ghm@google.com (Graeme Morgan) */ final class FloatingPointAssertionWithinEpsilonPositiveCases { private static final float TOLERANCE = 1e-10f; private static final double TOLERANCE2 = 1e-20f; private static final float VALUE = 1; public void testFloat() { // BUG: Diagnostic contains: 6.0e-08 assertThat(1.0f).isWithin(1e-20f).of(1.0f); // BUG: Diagnostic contains: 6.0e-08 assertThat(1f).isWithin(TOLERANCE).of(VALUE); // BUG: Diagnostic contains: 1.0e+03 assertThat(1e10f).isWithin(1).of(1e10f); // BUG: Diagnostic contains: 1.2e-07 assertThat(1f).isNotWithin(1e-10f).of(2); // BUG: Diagnostic contains: 6.0e-08 assertEquals(1f, 1f, TOLERANCE); // BUG: Diagnostic contains: 6.0e-08 assertEquals("equal!", 1f, 1f, TOLERANCE); } public void testDouble() { // BUG: Diagnostic contains: 1.1e-16 assertThat(1.0).isWithin(1e-20).of(1.0); // BUG: Diagnostic contains: 1.1e-16 assertThat(1.0).isWithin(TOLERANCE2).of(1.0f); // BUG: Diagnostic contains: 1.1e-16 assertThat(1.0).isWithin(TOLERANCE2).of(1); // BUG: Diagnostic contains: 1.6e+04 assertThat(1e20).isWithin(1).of(1e20); // BUG: Diagnostic contains: 1.4e-17 assertThat(0.1).isNotWithin(TOLERANCE2).of(0.1f); // BUG: Diagnostic contains: 1.1e-16 assertEquals(1.0, 1.0, TOLERANCE2); // BUG: Diagnostic contains: 1.1e-16 assertEquals("equal!", 1.0, 1.0, TOLERANCE2); } }
2,301
32.362319
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/UngroupedOverloadsPositiveCasesMultiple.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author hanuszczak@google.com (Łukasz Hanuszczak) */ public class UngroupedOverloadsPositiveCasesMultiple { private int foo; // BUG: Diagnostic contains: ungrouped overloads of 'bar' public void bar(int x, String z, int y) { System.out.println(String.format("z: %s, x: %d, y: %d", z, x, y)); } private UngroupedOverloadsPositiveCasesMultiple(int foo) { this.foo = foo; } // BUG: Diagnostic contains: ungrouped overloads of 'bar' public void bar(int x) { bar(foo, x); } public void baz(String x) { bar(42, x, 42); } // BUG: Diagnostic contains: ungrouped overloads of 'bar' public void bar(int x, int y) { bar(y, FOO, x); } public static final String FOO = "foo"; // BUG: Diagnostic contains: ungrouped overloads of 'bar' public void bar(int x, int y, int z) { bar(x, String.valueOf(y), z); } // BUG: Diagnostic contains: ungrouped overloads of 'quux' public int quux() { return quux(quux); } public int quux = 42; // BUG: Diagnostic contains: ungrouped overloads of 'quux' public int quux(int x) { return x + quux; } private static class Quux {} // BUG: Diagnostic contains: ungrouped overloads of 'quux' public int quux(int x, int y) { return quux(x + y); } // BUG: Diagnostic contains: ungrouped overloads of 'norf' public int norf(int x) { return quux(x, x); } // BUG: Diagnostic contains: ungrouped overloads of 'norf' public int norf(int x, int y) { return norf(x + y); } public void foo() { System.out.println("foo"); } // BUG: Diagnostic contains: ungrouped overloads of 'norf' public void norf(int x, int y, int w) { norf(x + w, y + w); } }
2,368
24.202128
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ComparisonContractViolatedPositiveCases.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.util.Comparator; public class ComparisonContractViolatedPositiveCases { static final int POSITIVE_CONSTANT = 50; static class Struct { int intField; long longField; @Override public boolean equals(Object o) { return o instanceof Struct && intField == ((Struct) o).intField && longField == ((Struct) o).longField; } @Override public int hashCode() { return intField + (int) longField; } } static final Comparator<Struct> intComparisonNoZero1 = new Comparator<Struct>() { @Override public int compare(Struct left, Struct right) { // BUG: Diagnostic contains: Integer.compare(left.intField, right.intField) return (left.intField < right.intField) ? -1 : 1; } }; static final Comparator<Struct> intComparisonNoZero2 = new Comparator<Struct>() { @Override public int compare(Struct left, Struct right) { // BUG: Diagnostic contains: Integer.compare(left.intField, right.intField) return (right.intField < left.intField) ? 1 : -1; } }; static final Comparator<Struct> intComparisonNoZero3 = new Comparator<Struct>() { @Override public int compare(Struct left, Struct right) { // BUG: Diagnostic contains: Integer.compare(left.intField, right.intField) return (left.intField > right.intField) ? 1 : -1; } }; static final Comparator<Struct> intComparisonNoZero4 = new Comparator<Struct>() { @Override public int compare(Struct left, Struct right) { // BUG: Diagnostic contains: Integer.compare(left.intField, right.intField) return (left.intField <= right.intField) ? -1 : 1; } }; static final Comparator<Struct> longComparisonNoZero1 = new Comparator<Struct>() { @Override public int compare(Struct left, Struct right) { // BUG: Diagnostic contains: Long.compare(left.longField, right.longField) return (left.longField < right.longField) ? -1 : 1; } }; static final Comparator<Struct> longComparisonNoZero2 = new Comparator<Struct>() { @Override public int compare(Struct left, Struct right) { // BUG: Diagnostic contains: Long.compare(left.longField, right.longField) return (left.longField < right.longField) ? -1 : POSITIVE_CONSTANT; } }; static final Comparator<Struct> zeroOrOneComparator = new Comparator<Struct>() { @Override // BUG: Diagnostic contains: violates the contract public int compare(Struct o1, Struct o2) { return o1.equals(o2) ? 0 : 1; } }; static final Comparator<Struct> zeroOrNegativeOneComparator = new Comparator<Struct>() { @Override // BUG: Diagnostic contains: violates the contract public int compare(Struct o1, Struct o2) { return o1.equals(o2) ? 0 : -1; } }; static final Comparator<Struct> zeroOrPositiveConstantComparator = new Comparator<Struct>() { @Override // BUG: Diagnostic contains: violates the contract public int compare(Struct o1, Struct o2) { return o1.equals(o2) ? 0 : POSITIVE_CONSTANT; } }; }
4,012
30.849206
85
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/UnnecessaryBoxedVariableCases.java
/* * Copyright 2019 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import static com.google.common.base.Preconditions.checkNotNull; import java.util.List; import java.util.stream.Stream; import javax.annotation.Nullable; /** * @author awturner@google.com (Andy Turner) */ class UnnecessaryBoxedVariableCases { void positive_local() { Integer i = 0; } int positive_local_return() { Integer i = 0; return i; } Integer positive_local_addition() { Integer i = 0; return i + 1; } void positive_local_compoundAddition(Integer addend) { Integer i = 0; i += addend; int j = 0; j += i; } void positive_methodInvocation() { Integer i = 0; methodPrimitiveArg(i); } void negative_methodInvocation() { Integer i = 0; methodBoxedArg(i); } void positive_assignedValueOf() { Integer i = Integer.valueOf(0); } int positive_assignedValueOf_return() { Integer i = Integer.valueOf(0); return i; } int positive_noInitializer() { Integer i; i = 0; return i; } void negative_enhancedForLoopOverCollection(List<Integer> list) { for (Integer i : list) {} } void negative_enhancedForLoopOverWrappedArray(Integer[] array) { for (Integer i : array) {} } void positive_enhancedForLoopOverPrimitiveArray(int[] array) { for (Integer i : array) {} } final void negative_invokeMethod(Integer i) throws InterruptedException { i.wait(0); } final Object[] negative_objectArray(Long l) { return new Object[] {"", l}; } void negative_null() { Integer i = null; } void negative_null_noInitializer() { Integer i; i = null; i = 0; } void negative_null_reassignNull() { Integer i = 0; i = null; } void negative_enhancedForLoopOverPrimitiveArray_assignInLoop(int[] array) { for (Integer i : array) { i = null; } } void negative_boxedVoid() { Void v; } int negative_assignmentInReturn() { Integer myVariable; return myVariable = methodBoxedArg(42); } int positive_assignmentInReturn() { Integer myVariable; return myVariable = Integer.valueOf(42); } int positive_assignmentInReturn2() { Integer myVariable; return myVariable = Integer.valueOf(42); } int positive_hashCode() { Integer myVariable = 0; return myVariable.hashCode(); } short positive_castMethod() { Integer myVariable = 0; return myVariable.shortValue(); } int positive_castMethod_sameType() { Integer myVariable = 0; return myVariable.intValue(); } void positive_castMethod_statementExpression() { Integer myVariable = 0; myVariable.longValue(); } void negative_methodReference() { Integer myVariable = 0; Stream<Integer> stream = Stream.of(1).filter(myVariable::equals); } static void positive_parameter_staticMethod(Boolean b) { boolean a = b; } static void negative_parameter_staticMethod(Boolean b) { System.out.println("a " + b); } static boolean positive_parameter_returnType(Boolean b) { return b; } void negative_parameter_instanceMethod_nonFinal(Boolean b) { boolean a = b; } final void negative_parameter_instanceMethod_final(Boolean b) { boolean a = b; } static void negative_parameter_unused(Integer i) {} static void positive_removeNullable_parameter(@Nullable Integer i) { int j = i; } static void positive_removeNullable_localVariable() { @Nullable Integer i = 0; @javax.annotation.Nullable Integer j = 0; int k = i + j; } static int positive_nullChecked_expression(Integer i) { return checkNotNull(i); } static int positive_nullChecked_expression_message(Integer i) { return checkNotNull(i, "Null: [%s]", i); } static int positive_nullChecked_statement(Integer i) { checkNotNull(i); return i; } static int positive_nullChecked_statement_message(Integer i) { checkNotNull(i, "Null: [%s]", i); return i; } private void methodPrimitiveArg(int i) {} private Integer methodBoxedArg(Integer i) { return i; } }
4,706
20.691244
77
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ClassCanBeStaticPositiveCase1.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author alexloh@google.com (Alex Loh) */ public class ClassCanBeStaticPositiveCase1 { int outerVar; // Non-static inner class that does not use outer scope // BUG: Diagnostic contains: static class Inner1 class Inner1 { int innerVar; } }
924
27.90625
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/TryFailThrowableNegativeCases.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import junit.framework.TestCase; import org.junit.Assert; /** * @author adamwos@google.com (Adam Wos) */ public class TryFailThrowableNegativeCases { public static void withoutFail() { try { dummyMethod(); } catch (Throwable t) { dummyRecover(); } } public static void failOutsideTry() { try { dummyMethod(); } catch (Throwable t) { dummyRecover(); } Assert.fail(); } public static void withoutCatch() { try { dummyMethod(); Assert.fail(""); } finally { dummyRecover(); } } /** For now, this isn't supported. */ public static void multipleCatches() { try { dummyMethod(); Assert.fail("1234"); } catch (Error e) { dummyRecover(); } catch (Throwable t) { dummyRecover(); } } public static void failNotLast() { try { dummyMethod(); Assert.fail("Not last :("); dummyMethod(); } catch (Throwable t) { dummyRecover(); } } public static void catchException() { try { dummyMethod(); Assert.fail(); } catch (Exception t) { dummyRecover(); } } public static void catchException_failWithMessage() { try { dummyMethod(); Assert.fail("message"); } catch (Exception t) { dummyRecover(); } } public static void codeCatch_failNoMessage() { try { dummyMethod(); Assert.fail(); } catch (Throwable t) { dummyRecover(); } } public static void codeCatch_failWithMessage() { try { dummyMethod(); Assert.fail("Faaail!"); } catch (Throwable t444) { dummyRecover(); } } public static void codeCatch_staticImportedFail() { try { dummyMethod(); fail(); } catch (Throwable t444) { dummyRecover(); } } @SuppressWarnings("deprecation") // deprecated in JUnit 4.11 public static void codeCatch_oldAssertFail() { try { dummyMethod(); junit.framework.Assert.fail(); } catch (Throwable codeCatch_oldAssertFail) { dummyRecover(); } } @SuppressWarnings("deprecation") // deprecated in JUnit 4.11 public static void codeCatch_oldAssertFailWithMessage() { try { dummyMethod(); junit.framework.Assert.fail("message"); } catch (Throwable codeCatch_oldAssertFailWithMessage) { dummyRecover(); } } public static void codeCatch_FQFail() { try { dummyMethod(); org.junit.Assert.fail("Faaail!"); } catch (Throwable t444) { dummyRecover(); } } public static void codeCatch_assert() { try { dummyMethod(); assertEquals(1, 2); } catch (Throwable t) { dummyMethod(); } } public static void commentCatch_assertNotLast() { try { dummyMethod(); assertTrue("foobar!", true); dummyRecover(); } catch (Throwable t) { dummyMethod(); } } static final class SomeTest extends TestCase { public void testInTestCase() { try { dummyMethod(); fail("message"); } catch (Throwable codeCatch_oldAssertFailWithMessage) { dummyRecover(); } } } private static void dummyRecover() {} private static void dummyMethod() {} }
4,049
20.774194
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/OverridesNegativeCase1.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author cushon@google.com (Liam Miller-Cushon) */ public class OverridesNegativeCase1 { abstract class Base { abstract void varargsMethod(Object... xs); abstract void arrayMethod(Object[] xs); } abstract class Child1 extends Base { @Override abstract void varargsMethod(final Object... newNames); } abstract class Child2 extends Base { @Override abstract void arrayMethod(Object[] xs); } static class StaticClass { static void staticVarargsMethod(Object... xs) {} static void staticArrayMethod(Object[] xs) {} } interface Interface { void varargsMethod(Object... xs); void arrayMethod(Object[] xs); } abstract class ImplementsInterface implements Interface { public abstract void varargsMethod(Object... xs); public abstract void arrayMethod(Object[] xs); } } // Varargs methods might end up overriding synthetic (e.g. bridge) methods, which will have already // been lowered into a non-varargs form. Test that we don't report errors when a varargs method // overrides a synthetic non-varargs method: abstract class One { static class Builder { Builder varargsMethod(String... args) { return this; } } } class Two extends One { static class Builder extends One.Builder { @Override public Builder varargsMethod(String... args) { super.varargsMethod(args); return this; } } } class Three extends Two { static class Builder extends Two.Builder { @Override public Builder varargsMethod(String... args) { super.varargsMethod(args); return this; } } }
2,265
25.045977
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/TruthSelfEqualsPositiveCases.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; /** * Positive test cases for TruthSelfEquals check. * * @author bhagwani@google.com (Sumit Bhagwani) */ public class TruthSelfEqualsPositiveCases { public void testAssertThatEq() { String test = Boolean.TRUE.toString(); // BUG: Diagnostic contains: new EqualsTester().addEqualityGroup(test).testEquals() assertThat(test).isEqualTo(test); } public void testAssertWithMessageEq() { String test = Boolean.TRUE.toString(); // BUG: Diagnostic contains: new EqualsTester().addEqualityGroup(test).testEquals() assertWithMessage("msg").that(test).isEqualTo(test); } public void testAssertThatSame() { String test = Boolean.TRUE.toString(); // BUG: Diagnostic contains: new EqualsTester().addEqualityGroup(test).testEquals() assertThat(test).isSameInstanceAs(test); } public void testAssertWithMessageSame() { String test = Boolean.TRUE.toString(); // BUG: Diagnostic contains: new EqualsTester().addEqualityGroup(test).testEquals() assertWithMessage("msg").that(test).isSameInstanceAs(test); } public void testAssertThatNeq() { String test = Boolean.TRUE.toString(); // BUG: Diagnostic contains: isNotEqualTo method are the same object assertThat(test).isNotEqualTo(test); } public void testAssertThatNotSame() { String test = Boolean.TRUE.toString(); // BUG: Diagnostic contains: isNotSameInstanceAs method are the same object assertThat(test).isNotSameInstanceAs(test); } public void testAssertWithMessageNeq() { String test = Boolean.TRUE.toString(); // BUG: Diagnostic contains: isNotEqualTo method are the same object assertWithMessage("msg").that(test).isNotEqualTo(test); } public void testAssertWithMessageNotSame() { String test = Boolean.TRUE.toString(); // BUG: Diagnostic contains: isNotSameInstanceAs method are the same object assertWithMessage("msg").that(test).isNotSameInstanceAs(test); } }
2,723
34.376623
87
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/TruthAssertExpectedPositiveCases.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import com.google.common.collect.ImmutableList; /** * Positive test cases for TruthAssertExpected check. * * @author ghm@google.com (Graeme Morgan) */ final class TruthAssertExpectedPositiveCases { private static final ImmutableList<Object> EXPECTED_LIST = ImmutableList.of(); private static final float EXPECTED_FLOAT = 1f; private float actualFloat() { return 3.14f; } private void simple() { Object expected = new Object(); Object actual = new Object(); Object foo = new Object(); // BUG: Diagnostic contains: assertThat(foo).isEqualTo(expected) assertThat(expected).isEqualTo(foo); // BUG: Diagnostic contains: assertThat(foo).isNotEqualTo(expected) assertThat(expected).isNotEqualTo(foo); // BUG: Diagnostic contains: assertWithMessage("reversed!").that(actual).isEqualTo(expected) assertWithMessage("reversed!").that(expected).isEqualTo(actual); // BUG: Diagnostic contains: assertThat(actual.hashCode()).isEqualTo(expected.hashCode()) assertThat(expected.hashCode()).isEqualTo(actual.hashCode()); } private void tolerantFloats() { // BUG: Diagnostic contains: assertThat(actualFloat()).isWithin(1f).of(EXPECTED_FLOAT) assertThat(EXPECTED_FLOAT).isWithin(1f).of(actualFloat()); } private void lists() { // BUG: Diagnostic contains: // assertThat(ImmutableList.of(this)).containsExactlyElementsIn(EXPECTED_LIST); assertThat(EXPECTED_LIST).containsExactlyElementsIn(ImmutableList.of(this)); // BUG: Diagnostic contains: // assertThat(ImmutableList.of(this)).containsExactlyElementsIn(EXPECTED_LIST).inOrder(); assertThat(EXPECTED_LIST).containsExactlyElementsIn(ImmutableList.of(this)).inOrder(); } }
2,498
36.298507
96
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/AssertFalsePositiveCases.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author sebastian.h.monte@gmail.com (Sebastian Monte) */ public class AssertFalsePositiveCases { public void assertFalse() { // BUG: Diagnostic contains: throw new AssertionError() assert false; } }
881
30.5
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/TryFailThrowablePositiveCases.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Arrays; import junit.framework.TestCase; import org.junit.Assert; /** * @author adamwos@google.com (Adam Wos) */ public class TryFailThrowablePositiveCases { public static void emptyCatch_failNoMessage() { try { dummyMethod(); Assert.fail(); // BUG: Diagnostic contains: catch (Exception t) } catch (Throwable t) { } } public static void commentCatch_failNoMessage() { try { dummyMethod(); Assert.fail(); // BUG: Diagnostic contains: catch (Exception t123) } catch (Throwable t123) { // expected! ; /* that's an empty comment */ } } public static void commentCatch_failWithMessage() { try { dummyMethod(); Assert.fail("Faaail!"); // BUG: Diagnostic contains: catch (Exception t) } catch (Throwable t) { // expected! } } public static void commentCatch_failNotLast() { try { dummyMethod(); fail("Faaail!"); dummyMethod(); // BUG: Diagnostic contains: catch (Exception t) } catch (Throwable t) { // expected! } } public static void commentCatch_assert() { try { dummyMethod(); assertEquals(1, 2); // BUG: Diagnostic contains: catch (Exception t) } catch (Throwable t) { // expected! } } public static void commentCatch_assertNotLast() { try { dummyMethod(); assertTrue("foobar!", true); dummyRecover(); // BUG: Diagnostic contains: catch (Exception t) } catch (Throwable t) { // expected! } } public static void customMoreAsserts() { try { dummyMethod(); CustomMoreAsserts.assertFoobar(); dummyMethod(); // BUG: Diagnostic contains: catch (Exception t) } catch (Throwable t) { // expected! } } public static void customMoreAsserts_fail() { try { dummyMethod(); CustomMoreAsserts.fail("param", 0x42); dummyMethod(); // BUG: Diagnostic contains: catch (Exception t) } catch (Throwable t) { // expected! } } static final class SomeTest extends TestCase { public void testInTestCase() { try { dummyMethod(); fail("message"); // BUG: Diagnostic contains: catch (Exception codeCatch_oldAssertFailWithMessage) } catch (Throwable codeCatch_oldAssertFailWithMessage) { // comment /* another */ } } } static final class CustomMoreAsserts { static void assertFoobar() {} static void fail(String param1, int param2) {} } private static void dummyRecover() {} private static void dummyMethod() {} public static void catchesAssertionError() { try { dummyMethod(); Assert.fail(); // BUG: Diagnostic contains: remove this line } catch (AssertionError e) { } } public static void hasMessage() { try { dummyMethod(); Assert.fail("foo"); // BUG: Diagnostic contains: remove this line } catch (AssertionError e) { } } public static void catchesError_lastStatement() { try { dummyMethod(); Assert.fail(); // BUG: Diagnostic contains: remove this line } catch (Error e) { } } public static void catchesError_notLastStatement() { try { dummyMethod(); Assert.fail(); // BUG: Diagnostic contains: boolean threw = false; } catch (Error e) { } assertTrue(true); } public static void catchesError_nested() { for (Object o : Arrays.asList()) { try { dummyMethod(); Assert.fail(); // BUG: Diagnostic contains: boolean threw = false; } catch (Error e) { } } } public static void catchesError_nestedNoBlock() { for (Object o : Arrays.asList()) try { dummyMethod(); Assert.fail(); // BUG: Diagnostic contains: boolean threw = false; } catch (Error e) { } } }
4,732
22.78392
89
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ReturnValueIgnoredPositiveCases.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Locale; /** * @author alexeagle@google.com (Alex Eagle) */ public class ReturnValueIgnoredPositiveCases { String a = "thing"; // BUG: Diagnostic contains: Return value of 'valueOf' must be used private Runnable r = () -> String.valueOf(""); { // String methods // BUG: Diagnostic contains: remove this line String.format("%d", 10); // BUG: Diagnostic contains: remove this line String.format("%d", 10).trim(); // BUG: Diagnostic contains: remove this line java.lang.String.format("%d", 10).trim(); // BUG: Diagnostic contains: a = a.intern() a.intern(); // BUG: Diagnostic contains: a = a.trim() a.trim(); // BUG: Diagnostic contains: a = a.trim().concat("b") a.trim().concat("b"); // BUG: Diagnostic contains: a = a.concat("append this") a.concat("append this"); // BUG: Diagnostic contains: a = a.replace('t', 'b') a.replace('t', 'b'); // BUG: Diagnostic contains: a = a.replace("thi", "fli") a.replace("thi", "fli"); // BUG: Diagnostic contains: a = a.replaceAll("i", "b") a.replaceAll("i", "b"); // BUG: Diagnostic contains: a = a.replaceFirst("a", "b") a.replaceFirst("a", "b"); // BUG: Diagnostic contains: a = a.toLowerCase() a.toLowerCase(); // BUG: Diagnostic contains: a = a.toLowerCase(Locale.ENGLISH) a.toLowerCase(Locale.ENGLISH); // BUG: Diagnostic contains: a = a.toUpperCase() a.toUpperCase(); // BUG: Diagnostic contains: a = a.toUpperCase(Locale.ENGLISH) a.toUpperCase(Locale.ENGLISH); // BUG: Diagnostic contains: a = a.substring(0) a.substring(0); // BUG: Diagnostic contains: a = a.substring(0, 1) a.substring(0, 1); } StringBuffer sb = new StringBuffer("hello"); { // BUG: Diagnostic contains: sb.toString().trim(); } BigInteger b = new BigInteger("123456789"); { // BigInteger methods // BUG: Diagnostic contains: b = b.add(new BigInteger("3")) b.add(new BigInteger("3")); // BUG: Diagnostic contains: b = b.abs() b.abs(); // BUG: Diagnostic contains: b = b.shiftLeft(3) b.shiftLeft(3); // BUG: Diagnostic contains: b = b.subtract(BigInteger.TEN) b.subtract(BigInteger.TEN); } BigDecimal c = new BigDecimal("1234.5678"); { // BigDecimal methods // BUG: Diagnostic contains: c = c.add(new BigDecimal("1.3")) c.add(new BigDecimal("1.3")); // BUG: Diagnostic contains: c = c.abs() c.abs(); // BUG: Diagnostic contains: c = c.divide(new BigDecimal("4.5")) c.divide(new BigDecimal("4.5")); // BUG: Diagnostic contains: new BigDecimal("10").add(c); } Path p = Paths.get("foo/bar/baz"); { // Path methods // BUG: Diagnostic contains: p = p.getFileName(); p.getFileName(); // BUG: Diagnostic contains: p = p.getName(0); p.getName(0); // BUG: Diagnostic contains: p = p.getParent(); p.getParent(); // BUG: Diagnostic contains: p = p.getRoot(); p.getRoot(); // BUG: Diagnostic contains: p = p.normalize(); p.normalize(); // BUG: Diagnostic contains: p = p.relativize(p); p.relativize(p); // BUG: Diagnostic contains: p = p.resolve(p); p.resolve(p); // BUG: Diagnostic contains: p = p.resolve("string"); p.resolve("string"); // BUG: Diagnostic contains: p = p.resolveSibling(p); p.resolveSibling(p); // BUG: Diagnostic contains: p = p.resolveSibling("string"); p.resolveSibling("string"); // BUG: Diagnostic contains: p = p.subpath(0, 1); p.subpath(0, 1); // BUG: Diagnostic contains: p = p.toAbsolutePath(); p.toAbsolutePath(); try { // BUG: Diagnostic contains: p = p.toRealPath(); p.toRealPath(); } catch (IOException e) { } } int[] numbers = {5, 4, 3, 2, 1}; Object[] objects = {new Object(), new Object()}; { // Arrays methods // BUG: Diagnostic contains: Return value of 'asList' must be used Arrays.asList(5, 4, 3, 2, 1); // BUG: Diagnostic contains: Return value of 'binarySearch' must be used Arrays.binarySearch(numbers, 3); // BUG: Diagnostic contains: Return value of 'copyOf' must be used Arrays.copyOf(numbers, 3); // BUG: Diagnostic contains: Return value of 'copyOfRange' must be used Arrays.copyOfRange(numbers, 1, 3); // BUG: Diagnostic contains: Return value of 'deepEquals' must be used Arrays.deepEquals(objects, objects); // BUG: Diagnostic contains: Return value of 'deepHashCode' must be used Arrays.deepHashCode(objects); // BUG: Diagnostic contains: Return value of 'deepToString' must be used Arrays.deepToString(objects); // BUG: Diagnostic contains: Return value of 'equals' must be used Arrays.equals(objects, objects); // BUG: Diagnostic contains: Return value of 'hashCode' must be used Arrays.hashCode(objects); // BUG: Diagnostic contains: Return value of 'toString' must be used Arrays.toString(objects); } }
5,766
33.740964
76
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/CheckReturnValuePositiveCases.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import com.google.errorprone.annotations.CheckReturnValue; import org.junit.rules.ExpectedException; /** * @author eaftan@google.com (Eddie Aftandilian) */ public class CheckReturnValuePositiveCases { IntValue intValue = new IntValue(0); @CheckReturnValue private int increment(int bar) { return bar + 1; } public void foo() { int i = 1; // BUG: Diagnostic contains: The result of `increment(...)` must be used // // If you really don't want to use the result, then assign it to a variable: `var unused = ...`. // // If callers of `increment(...)` shouldn't be required to use its result, then annotate it with // `@CanIgnoreReturnValue`. increment(i); System.out.println(i); } public void bar() { // BUG: Diagnostic contains: this.intValue = this.intValue.increment() this.intValue.increment(); } public void testIntValue() { IntValue value = new IntValue(10); // BUG: Diagnostic contains: value = value.increment() value.increment(); } private void callRunnable(Runnable runnable) { runnable.run(); } public void testResolvedToVoidLambda() { // BUG: Diagnostic contains: callRunnable(() -> this.intValue.increment()); } public void testResolvedToVoidMethodReference(boolean predicate) { // BUG: Diagnostic contains: The result of `increment()` must be used // // `this.intValue::increment` acts as an implementation of `Runnable.run` // -- which is a `void` method, so it doesn't use the result of `increment()`. // // To use the result, you may need to restructure your code. // // If you really don't want to use the result, then switch to a lambda that assigns it to a // variable: `() -> { var unused = ...; }`. // // If callers of `increment()` shouldn't be required to use its result, then annotate it with // `@CanIgnoreReturnValue`. callRunnable(this.intValue::increment); // BUG: Diagnostic contains: The result of `increment()` must be used callRunnable(predicate ? this.intValue::increment : this.intValue::increment2); } public void testConstructorResolvedToVoidMethodReference() { // BUG: Diagnostic contains: The result of `new MyObject()` must be used // // `MyObject::new` acts as an implementation of `Runnable.run` // -- which is a `void` method, so it doesn't use the result of `new MyObject()`. // // To use the result, you may need to restructure your code. // // If you really don't want to use the result, then switch to a lambda that assigns it to a // variable: `() -> { var unused = ...; }`. // // If callers of `MyObject()` shouldn't be required to use its result, then annotate it with // `@CanIgnoreReturnValue`. callRunnable(MyObject::new); } public void testRegularLambda() { callRunnable( () -> { // BUG: Diagnostic contains: this.intValue.increment(); }); } public void testBeforeAndAfterRule() { // BUG: Diagnostic contains: new IntValue(1).increment(); ExpectedException.none().expect(IllegalStateException.class); new IntValue(1).increment(); // No error here, last statement in block } public void constructor() { // BUG: Diagnostic contains: The result of `new MyObject()` must be used new MyObject() {}; class MySubObject1 extends MyObject {} class MySubObject2 extends MyObject { MySubObject2() {} } class MySubObject3 extends MyObject { MySubObject3() { super(); } } // BUG: Diagnostic contains: The result of `new MyObject()` must be used // // If you really don't want to use the result, then assign it to a variable: `var unused = ...`. // // If callers of `MyObject()` shouldn't be required to use its result, then annotate it with // `@CanIgnoreReturnValue`. new MyObject(); } private class IntValue { final int i; public IntValue(int i) { this.i = i; } @javax.annotation.CheckReturnValue public IntValue increment() { return new IntValue(i + 1); } public void increment2() { // BUG: Diagnostic contains: this.increment(); } public void increment3() { // BUG: Diagnostic contains: increment(); } } private static class MyObject { @CheckReturnValue MyObject() {} } private abstract static class LB1<A> {} private static class LB2<A> extends LB1<A> { @CheckReturnValue public static <T> LB2<T> lb1() { return new LB2<T>(); } public static <T> LB2<T> lb2() { // BUG: Diagnostic contains: lb1(); return lb1(); } } private static class JavaxAnnotation { @javax.annotation.CheckReturnValue public static int check() { return 1; } public static void ignoresCheck() { // BUG: Diagnostic contains: check(); } } }
5,599
27.571429
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/BanClassLoaderPositiveCases.java
/* * Copyright 2023 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import static java.rmi.server.RMIClassLoader.loadClass; import java.lang.invoke.MethodHandles; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; class BanClassLoaderPositiveCases { /** Override loadClass with an insecure implementation. */ // BUG: Diagnostic contains: BanClassLoader class InsecureClassLoader extends URLClassLoader { public InsecureClassLoader() { super(new URL[0]); } @Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { try { addURL(new URL("jar:https://evil.com/bad.jar")); } catch (MalformedURLException e) { } return findClass(name); } } /** Calling static methods in java.rmi.server.RMIClassLoader. */ public static final Class<?> loadRMI() throws ClassNotFoundException, MalformedURLException { // BUG: Diagnostic contains: BanClassLoader return loadClass("evil.com", "BadClass"); } /** Calling constructor of java.net.URLClassLoader. */ public ClassLoader loadFromURL() throws MalformedURLException { // BUG: Diagnostic contains: BanClassLoader URLClassLoader loader = new URLClassLoader(new URL[] {new URL("jar:https://evil.com/bad.jar")}); return loader; } /** Calling methods of nested class. */ public static final Class<?> methodHandlesDefineClass(byte[] bytes) throws IllegalAccessException { // BUG: Diagnostic contains: BanClassLoader return MethodHandles.lookup().defineClass(bytes); } }
2,199
33.375
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/MustBeClosedCheckerNegativeCases.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import static org.junit.Assert.fail; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; import com.google.common.collect.ImmutableList; import com.google.errorprone.annotations.MustBeClosed; @SuppressWarnings({"UnnecessaryCast", "LambdaToMemberReference"}) public class MustBeClosedCheckerNegativeCases { class Closeable implements AutoCloseable { @Override public void close() {} } class Foo { void bar() {} @MustBeClosed Closeable mustBeClosedAnnotatedMethod() { return new Closeable(); } } class MustBeClosedAnnotatedConstructor extends Closeable { @MustBeClosed MustBeClosedAnnotatedConstructor() {} } @SuppressWarnings("MustBeClosedChecker") void respectsSuppressWarnings_onMethod() { new Foo().mustBeClosedAnnotatedMethod(); } void respectsSuppressWarnings_onLocal() { @SuppressWarnings("MustBeClosedChecker") var unused = new Foo().mustBeClosedAnnotatedMethod(); } void negativeCase3() { try (Closeable closeable = new Foo().mustBeClosedAnnotatedMethod()) {} } void negativeCase4() { Foo foo = new Foo(); try (Closeable closeable = foo.mustBeClosedAnnotatedMethod()) {} } void negativeCase5() { new Foo().bar(); } void negativeCase6() { try (MustBeClosedAnnotatedConstructor foo = new MustBeClosedAnnotatedConstructor()) {} } void negativeCase7() { try (MustBeClosedAnnotatedConstructor foo = new MustBeClosedAnnotatedConstructor(); Closeable closeable = new Foo().mustBeClosedAnnotatedMethod()) {} } @MustBeClosed Closeable positiveCase8() { // This is fine since the caller method is annotated. return new MustBeClosedAnnotatedConstructor(); } @MustBeClosed Closeable positiveCase7() { // This is fine since the caller method is annotated. return new Foo().mustBeClosedAnnotatedMethod(); } @MustBeClosed Closeable ternary(boolean condition) { return condition ? new Foo().mustBeClosedAnnotatedMethod() : null; } @MustBeClosed Closeable cast() { // TODO(b/241012760): remove the following line after the bug is fixed. // BUG: Diagnostic contains: return (Closeable) new Foo().mustBeClosedAnnotatedMethod(); } void tryWithResources() { Foo foo = new Foo(); Closeable closeable = foo.mustBeClosedAnnotatedMethod(); try { } finally { closeable.close(); } } void mockitoWhen(Foo mockFoo) { when(mockFoo.mustBeClosedAnnotatedMethod()).thenReturn(null); doReturn(null).when(mockFoo).mustBeClosedAnnotatedMethod(); } void testException() { try { ((Foo) null).mustBeClosedAnnotatedMethod(); fail(); } catch (NullPointerException e) { } } abstract class ParentWithNoArgument implements AutoCloseable { @MustBeClosed ParentWithNoArgument() {} } abstract class ParentWithArgument implements AutoCloseable { @MustBeClosed ParentWithArgument(int i) {} } abstract class ChildOfParentWithArgument extends ParentWithArgument { @MustBeClosed ChildOfParentWithArgument() { super(0); } } interface ResourceFactory { @MustBeClosed MustBeClosedAnnotatedConstructor getResource(); } void consumeCloseable(ResourceFactory factory) { try (Closeable c = factory.getResource()) {} } void expressionLambdaReturningCloseable() { consumeCloseable(() -> new MustBeClosedAnnotatedConstructor()); } void statementLambdaReturningCloseable() { consumeCloseable( () -> { return new MustBeClosedAnnotatedConstructor(); }); } void methodReferenceReturningCloseable() { consumeCloseable(MustBeClosedAnnotatedConstructor::new); } void ternaryFunctionalExpressionReturningCloseable(boolean condition) { consumeCloseable( condition ? () -> new MustBeClosedAnnotatedConstructor() : MustBeClosedAnnotatedConstructor::new); } void inferredFunctionalExpressionReturningCloseable(ResourceFactory factory) { ImmutableList.of( factory, () -> new MustBeClosedAnnotatedConstructor(), MustBeClosedAnnotatedConstructor::new) .forEach(this::consumeCloseable); } }
4,905
25.518919
90
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ModifyCollectionInEnhancedForLoopNegativeCases.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.bugpatterns; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CopyOnWriteArrayList; /** * @author anishvisaria98@gmail.com (Anish Visaria) */ public class ModifyCollectionInEnhancedForLoopNegativeCases { public static void testBasic(ArrayList<Integer> arr, HashSet<Integer> set) { for (Integer a : arr) { set.add(a); set.addAll(arr); set.clear(); set.removeAll(arr); set.retainAll(arr); } for (Integer i : set) { arr.add(i); arr.addAll(set); arr.clear(); arr.removeAll(set); arr.retainAll(set); } } public static void testNested(ArrayList<Integer> arr, LinkedList<Integer> list) { for (Integer x : arr) { for (Integer y : list) {} list.add(x); list.addAll(arr); list.clear(); list.removeAll(arr); list.retainAll(arr); } } public static void testBreakOutOfLoop(ArrayList<Integer> xs) { for (Integer x : xs) { xs.remove(x); return; } for (Integer x : xs) { xs.remove(x); System.err.println(); break; } } public static void testMapKeySet(HashMap<Integer, Integer> map1, HashMap<Integer, Integer> map2) { for (Integer a : map1.keySet()) { map2.putIfAbsent(Integer.parseInt("42"), Integer.parseInt("43")); map2.clear(); map2.remove(a); } } public static void testMapValues(HashMap<Integer, Integer> map1, HashMap<Integer, Integer> map2) { for (Integer a : map1.values()) { map2.putIfAbsent(Integer.parseInt("42"), a); map2.clear(); map2.remove(Integer.parseInt("42")); } } public static void testMapEntrySet( HashMap<Integer, Integer> map1, HashMap<Integer, Integer> map2) { for (Map.Entry<Integer, Integer> a : map1.entrySet()) { map2.putIfAbsent(Integer.parseInt("42"), Integer.parseInt("43")); map2.clear(); map2.remove(a.getKey()); } } private static void concurrent() { CopyOnWriteArrayList<Integer> cowal = new CopyOnWriteArrayList<>(); for (int i : cowal) { cowal.remove(i); } } interface MyBlockingQueue<T> extends BlockingQueue<T> {} private static void customConcurrent(MyBlockingQueue<Integer> mbq) { for (Integer i : mbq) { mbq.add(i); } } }
3,062
26.348214
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/EmptyIfStatementPositiveCases.java
/* * Copyright 2011 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * Positive test cases for the empty if statement check. * * @author eaftan@google.com (Eddie Aftandilian) */ public class EmptyIfStatementPositiveCases { public static void positiveCase1() { int i = 10; // BUG: Diagnostic contains: if (i == 10) { if (i == 10); { i++; } } public static void positiveCase2() { int i = 10; // BUG: Diagnostic contains: if (i == 10) if (i == 10); i++; System.out.println("foo"); } public static void positiveCase3() { int i = 10; if (i == 10) // BUG: Diagnostic contains: remove this line ; i++; System.out.println("foo"); } public static void positiveCase4() { int i = 10; // BUG: Diagnostic contains: remove this line if (i == 10) ; } public static void positiveCase5() { int i = 10; if (i == 10) // BUG: Diagnostic contains: remove this line ; { System.out.println("foo"); } } }
1,635
23.787879
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/OverrideThrowableToStringPositiveCases.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author mariasam@google.com (Maria Sam) */ class OverrideThrowableToStringPositiveCases { class BasicTest extends Throwable { @Override // BUG: Diagnostic contains: override public String toString() { return ""; } } class MultipleMethods extends Throwable { public MultipleMethods() { ; } @Override // BUG: Diagnostic contains: override public String toString() { return ""; } } class NoOverride extends Throwable { // BUG: Diagnostic contains: override public String toString() { return ""; } } }
1,262
22.830189
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnit3TestNotRunNegativeCase1.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import junit.framework.TestCase; import org.junit.Ignore; import org.junit.Test; /** * @author rburny@google.com (Radoslaw Burny) */ public class JUnit3TestNotRunNegativeCase1 extends TestCase { // correctly spelled public void test() {} public void testCorrectlySpelled() {} // real words public void bestNameEver() {} public void destroy() {} public void restore() {} public void establish() {} public void estimate() {} // different signature public boolean teslaInventedLightbulb() { return true; } public void tesselate(float f) {} // surrounding class is not a JUnit3 TestCase private static class TestCase { private void tesHelper() {} private void destroy() {} } // correct test, despite redundant annotation @Test public void testILikeAnnotations() {} // both @Test & @Ignore @Test @Ignore public void ignoredTest2() {} @Ignore @Test public void ignoredTest() {} }
1,617
21.788732
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ClassCanBeStaticPositiveCase2.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author alexloh@google.com (Alex Loh) */ public class ClassCanBeStaticPositiveCase2 { int outerVar1; int outerVar2; // Outer variable overridden // BUG: Diagnostic contains: private /* COMMENT */ static final class Inner2 private /* COMMENT */ final class Inner2 { int outerVar1; int innerVar = outerVar1; int localMethod(int outerVar2) { return outerVar2; } } }
1,070
27.184211
78
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/EqualsReferencePositiveCases.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** Created by mariasam on 6/22/17. */ public class EqualsReferencePositiveCases { @Override // BUG: Diagnostic contains: == public boolean equals(Object o) { System.out.println(this.equals(o)); return true; } class EqualsInElse { @Override // BUG: Diagnostic contains: == public boolean equals(Object o) { System.out.println(o == this); return this.equals(o); } } class FinalObject { @Override // BUG: Diagnostic contains: == public boolean equals(final Object object) { return this.equals(object); } } class NoThis { @Override // BUG: Diagnostic contains: == public boolean equals(Object o) { return equals(o); } } }
1,384
25.132075
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/OrderingFromPositiveCases.java
/* * Copyright 2011 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import com.google.common.collect.Ordering; import java.util.Comparator; /** * Positive test cases for theOrdering.from(new Comparator<T>() { ... }) check * * @author sjnickerson@google.com (Simon Nickerson) */ public class OrderingFromPositiveCases { public static void positiveCase1() { // BUG: Diagnostic contains: new Ordering<String>( Ordering<String> ord = Ordering.from( new Comparator<String>() { @Override public int compare(String first, String second) { int compare = first.length() - second.length(); return (compare != 0) ? compare : first.compareTo(second); } }); } }
1,367
31.571429
78
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnit3TestNotRunNegativeCase3.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import junit.framework.TestCase; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runner.Runner; /** * Tricky case - mixed JUnit3 and JUnit4. * * @author rburny@google.com (Radoslaw Burny) */ @RunWith(Runner.class) public class JUnit3TestNotRunNegativeCase3 extends TestCase { @Test public void name() {} public void tesMisspelled() {} @Test public void tesBothIssuesAtOnce() {} }
1,085
26.15
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ComparableTypePositiveCases.java
/* Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.io.Serializable; import java.util.Comparator; public class ComparableTypePositiveCases { // BUG: Diagnostic contains: [ComparableType] public static class CompareClass implements Comparable<Integer> { @Override public int compareTo(Integer o) { return 0; } } // BUG: Diagnostic contains: [ComparableType] public static class SerializableComparable implements Serializable, Comparable<Long> { @Override public int compareTo(Long o) { return 0; } } // BUG: Diagnostic contains: [ComparableType] public static class ComparableSerializable implements Comparable<Long>, Serializable { @Override public int compareTo(Long o) { return 0; } } // BUG: Diagnostic contains: [ComparableType] public static class BadClass implements Comparable<Double>, Comparator<Double> { @Override public int compareTo(Double o) { return 0; } @Override public int compare(Double o1, Double o2) { return 0; } } // BUG: Diagnostic contains: [ComparableType] public static class AnotherBadClass implements Comparator<Double>, Comparable<Double> { @Override public int compareTo(Double o) { return 0; } @Override public int compare(Double o1, Double o2) { return 0; } } public static class A {} public static class B extends A {} // BUG: Diagnostic contains: [ComparableType] public static class C extends A implements Comparable<B> { @Override public int compareTo(B o) { return 0; } } interface Foo {} // BUG: Diagnostic contains: [ComparableType] static final class Open implements Comparable<Foo> { @Override public int compareTo(Foo o) { return 0; } } // BUG: Diagnostic contains: [ComparableType] public abstract static class AClass implements Comparable<Integer> {} public static class BClass extends AClass { @Override public int compareTo(Integer o) { return 0; } } // found via flume public static class SpendXGetYValues { public Comparable<SpendXGetYValues> yToXRatio() { // BUG: Diagnostic contains: [ComparableType] return new Comparable<SpendXGetYValues>() { @Override public int compareTo(SpendXGetYValues other) { return 0; } }; } } // BUG: Diagnostic contains: [ComparableType] public abstract static class One<T> implements Comparable<T> {} public static class Two extends One<Integer> { @Override public int compareTo(Integer o) { return 0; } } }
3,260
23.335821
89
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/InsecureCipherModePositiveCases.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.security.KeyFactory; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import javax.crypto.Cipher; import javax.crypto.KeyAgreement; import javax.crypto.NoSuchPaddingException; /** * @author avenet@google.com (Arnaud J. Venet) */ public class InsecureCipherModePositiveCases { static Cipher defaultAesCipher; static { try { // BUG: Diagnostic contains: the mode and padding must be explicitly specified defaultAesCipher = Cipher.getInstance("AES"); } catch (NoSuchAlgorithmException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchPaddingException e) { // We don't handle any exception as this code is not meant to be executed. } } static Cipher defaultRsaCipher; static { try { // BUG: Diagnostic contains: the mode and padding must be explicitly specified defaultRsaCipher = Cipher.getInstance("RSA"); } catch (NoSuchAlgorithmException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchPaddingException e) { // We don't handle any exception as this code is not meant to be executed. } } static final String AES_STRING = "AES"; static Cipher defaultAesCipherWithConstantString; static { try { // BUG: Diagnostic contains: the mode and padding must be explicitly specified defaultAesCipherWithConstantString = Cipher.getInstance(AES_STRING); } catch (NoSuchAlgorithmException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchPaddingException e) { // We don't handle any exception as this code is not meant to be executed. } } static Cipher explicitAesCipher; static { try { // BUG: Diagnostic contains: ECB mode must not be used explicitAesCipher = Cipher.getInstance("AES/ECB/NoPadding"); } catch (NoSuchAlgorithmException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchPaddingException e) { // We don't handle any exception as this code is not meant to be executed. } } static Cipher explicitDesCipher; static { try { // BUG: Diagnostic contains: ECB mode must not be used explicitDesCipher = Cipher.getInstance("DES/ECB/NoPadding"); } catch (NoSuchAlgorithmException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchPaddingException e) { // We don't handle any exception as this code is not meant to be executed. } } static Cipher explicitDesCipherWithProvider; static { try { // BUG: Diagnostic contains: ECB mode must not be used explicitDesCipherWithProvider = Cipher.getInstance("DES/ECB/NoPadding", "My Provider"); } catch (NoSuchAlgorithmException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchPaddingException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchProviderException e) { // We don't handle any exception as this code is not meant to be executed. } } static String transformation; static { try { transformation = "DES/CBC/NoPadding"; // BUG: Diagnostic contains: the transformation is not a compile-time constant Cipher cipher = Cipher.getInstance(transformation); } catch (NoSuchAlgorithmException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchPaddingException e) { // We don't handle any exception as this code is not meant to be executed. } } static void transformationAsParameter(String transformation) { try { // BUG: Diagnostic contains: the transformation is not a compile-time constant Cipher cipher = Cipher.getInstance(transformation); } catch (NoSuchAlgorithmException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchPaddingException e) { // We don't handle any exception as this code is not meant to be executed. } } class CipherWrapper { Cipher cipher; // Make sure that the checker is enabled inside constructors. public CipherWrapper() { try { // BUG: Diagnostic contains: the mode and padding must be explicitly specified cipher = Cipher.getInstance("AES"); } catch (NoSuchAlgorithmException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchPaddingException e) { // We don't handle any exception as this code is not meant to be executed. } } } static Cipher complexCipher1; static { try { String algorithm = "AES"; // BUG: Diagnostic contains: the transformation is not a compile-time constant complexCipher1 = Cipher.getInstance(algorithm); } catch (NoSuchAlgorithmException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchPaddingException e) { // We don't handle any exception as this code is not meant to be executed. } } static Cipher complexCipher2; static { try { String transformation = "AES"; transformation += "/ECB"; transformation += "/NoPadding"; // BUG: Diagnostic contains: the transformation is not a compile-time constant complexCipher2 = Cipher.getInstance(transformation); } catch (NoSuchAlgorithmException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchPaddingException e) { // We don't handle any exception as this code is not meant to be executed. } } static Cipher IesCipher; static { try { // BUG: Diagnostic contains: the mode and padding must be explicitly specified IesCipher = Cipher.getInstance("ECIES"); // BUG: Diagnostic contains: IES IesCipher = Cipher.getInstance("ECIES/DHAES/NoPadding"); // BUG: Diagnostic contains: IES IesCipher = Cipher.getInstance("ECIESWITHAES/NONE/PKCS5Padding"); // BUG: Diagnostic contains: IES IesCipher = Cipher.getInstance("DHIESWITHAES/DHAES/PKCS7Padding"); // BUG: Diagnostic contains: IES IesCipher = Cipher.getInstance("ECIESWITHDESEDE/NONE/NOPADDING"); // BUG: Diagnostic contains: IES IesCipher = Cipher.getInstance("DHIESWITHDESEDE/DHAES/PKCS5PADDING"); // BUG: Diagnostic contains: IES IesCipher = Cipher.getInstance("ECIESWITHAES/CBC/PKCS7PADDING"); // BUG: Diagnostic contains: IES IesCipher = Cipher.getInstance("ECIESWITHAES-CBC/NONE/PKCS5PADDING"); // BUG: Diagnostic contains: IES IesCipher = Cipher.getInstance("ECIESwithDESEDE-CBC/DHAES/NOPADDING"); } catch (NoSuchAlgorithmException e) { // We don't handle any exception as this code is not meant to be executed. } catch (NoSuchPaddingException e) { // We don't handle any exception as this code is not meant to be executed. } } interface StringProvider { String get(); } public void keyOperations(StringProvider provider) { KeyFactory keyFactory; KeyAgreement keyAgreement; KeyPairGenerator keyPairGenerator; final String dh = "DH"; try { // BUG: Diagnostic contains: compile-time constant keyFactory = KeyFactory.getInstance(provider.get()); // BUG: Diagnostic contains: Diffie-Hellman on prime fields keyFactory = KeyFactory.getInstance(dh); // BUG: Diagnostic contains: DSA keyAgreement = KeyAgreement.getInstance("DSA"); // BUG: Diagnostic contains: compile-time constant keyAgreement = KeyAgreement.getInstance(provider.get()); // BUG: Diagnostic contains: Diffie-Hellman on prime fields keyPairGenerator = KeyPairGenerator.getInstance(dh); // BUG: Diagnostic contains: compile-time constant keyPairGenerator = KeyPairGenerator.getInstance(provider.get()); } catch (NoSuchAlgorithmException e) { // We don't handle any exception as this code is not meant to be executed. } } }
8,933
36.225
93
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/CannotMockFinalClassNegativeCases2.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.mockito.Mock; import org.mockito.Mockito; /** Test for CannotMockFinalClass in the absence of @RunWith(JUnit4.class). */ public class CannotMockFinalClassNegativeCases2 { static final class FinalClass {} @Mock FinalClass impossible; public void method() { FinalClass local = Mockito.mock(FinalClass.class); } }
946
30.566667
78
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/SwigMemoryLeakNegativeCases.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author irogers@google.com (Ian Rogers) */ public class SwigMemoryLeakNegativeCases { private long swigCPtr; protected boolean swigCMemOwn; public SwigMemoryLeakNegativeCases(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = cPtr; } @SuppressWarnings("removal") // deprecated for removal starting in JDK 18 protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; nativeDelete(swigCPtr); } swigCPtr = 0; } } private static native void nativeDelete(long cptr); }
1,310
26.3125
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/FunctionalInterfaceMethodChangedPositiveCases.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; public class FunctionalInterfaceMethodChangedPositiveCases { @FunctionalInterface interface SuperFI { void superSam(); } @FunctionalInterface interface OtherSuperFI { void otherSuperSam(); } @FunctionalInterface interface SubFI extends SuperFI { void subSam(); @Override // BUG: Diagnostic contains: default void superSam() { subSam(); System.out.println("do something else"); } } @FunctionalInterface interface MultipleInheritanceSubFIOneBad extends SuperFI, OtherSuperFI { void subSam(); @Override default void superSam() { subSam(); } @Override // BUG: Diagnostic contains: default void otherSuperSam() { subSam(); System.out.println("do something else"); } } @FunctionalInterface interface MultipleInheritanceSubFIBothBad extends SuperFI, OtherSuperFI { void subSam(); @Override // BUG: Diagnostic contains: default void superSam() { superSam(); System.out.println("do something else"); } @Override // BUG: Diagnostic contains: default void otherSuperSam() { subSam(); System.out.println("do something else"); } } @FunctionalInterface interface ValueReturningSuperFI { String superSam(); } @FunctionalInterface interface ValueReturningSubFI extends ValueReturningSuperFI { String subSam(); @Override // BUG: Diagnostic contains: default String superSam() { System.out.println("do something else"); return subSam(); } } @FunctionalInterface public interface ValueReturningSubFI2 extends ValueReturningSuperFI { String subSam(); @Override // BUG: Diagnostic contains: default String superSam() { subSam(); return null; } } }
2,470
21.87963
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ModifyCollectionInEnhancedForLoopPositiveCases.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.bugpatterns; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; /** * @author anishvisaria98@gmail.com (Anish Visaria) */ public class ModifyCollectionInEnhancedForLoopPositiveCases { public static void testBasic(ArrayList<Integer> arr, HashSet<Integer> set) { for (Integer a : arr) { // BUG: Diagnostic contains: arr.add(new Integer("42")); // BUG: Diagnostic contains: arr.addAll(set); // BUG: Diagnostic contains: arr.clear(); // BUG: Diagnostic contains: arr.remove(a); // BUG: Diagnostic contains: arr.removeAll(set); // BUG: Diagnostic contains: arr.retainAll(set); } } public static void testNested(ArrayList<Integer> arr, LinkedList<Integer> list) { for (Integer x : arr) { for (Integer y : list) { // BUG: Diagnostic contains: arr.add(y); // BUG: Diagnostic contains: arr.addAll(list); // BUG: Diagnostic contains: arr.clear(); // BUG: Diagnostic contains: arr.remove(x); // BUG: Diagnostic contains: arr.removeAll(list); // BUG: Diagnostic contains: arr.retainAll(list); // BUG: Diagnostic contains: list.add(x); // BUG: Diagnostic contains: list.addAll(arr); // BUG: Diagnostic contains: list.clear(); // BUG: Diagnostic contains: list.remove(y); // BUG: Diagnostic contains: list.removeAll(arr); // BUG: Diagnostic contains: list.retainAll(arr); } } } public static void testMapKeySet(HashMap<Integer, Integer> map) { for (Integer a : map.keySet()) { // BUG: Diagnostic contains: map.putIfAbsent(new Integer("42"), new Integer("43")); // BUG: Diagnostic contains: map.clear(); // BUG: Diagnostic contains: map.remove(a); } } public static void testMapValues(HashMap<Integer, Integer> map) { for (Integer a : map.values()) { // BUG: Diagnostic contains: map.putIfAbsent(new Integer("42"), new Integer("43")); // BUG: Diagnostic contains: map.putIfAbsent(new Integer("42"), a); // BUG: Diagnostic contains: map.clear(); } } public static void testMapEntrySet(HashMap<Integer, Integer> map) { for (Map.Entry<Integer, Integer> a : map.entrySet()) { // BUG: Diagnostic contains: map.putIfAbsent(new Integer("42"), new Integer("43")); // BUG: Diagnostic contains: map.clear(); // BUG: Diagnostic contains: map.remove(a.getKey()); } } }
3,304
29.321101
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/FuturesGetCheckedIllegalExceptionTypePositiveCases.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.bugpatterns.testdata; import static com.google.common.util.concurrent.Futures.getChecked; import static java.util.concurrent.TimeUnit.SECONDS; import java.util.concurrent.Future; /** Positive cases for {@link FuturesGetCheckedIllegalExceptionType}. */ public class FuturesGetCheckedIllegalExceptionTypePositiveCases { <T extends RuntimeException> void runtime( Future<?> future, Class<? extends RuntimeException> c1, Class<T> c2) throws Exception { // BUG: Diagnostic contains: getUnchecked(future) getChecked(future, RuntimeException.class); // BUG: Diagnostic contains: getUnchecked(future) getChecked(future, IllegalArgumentException.class); // BUG: Diagnostic contains: getUnchecked(future) getChecked(future, RuntimeException.class, 0, SECONDS); // BUG: Diagnostic contains: getUnchecked(future) getChecked(future, c1); // BUG: Diagnostic contains: getUnchecked(future) getChecked(future, c2); } void visibility(Future<?> future) throws Exception { // BUG: Diagnostic contains: parameters getChecked(future, PrivateConstructorException.class); // BUG: Diagnostic contains: parameters getChecked(future, PackagePrivateConstructorException.class); // BUG: Diagnostic contains: parameters getChecked(future, ProtectedConstructorException.class); } void parameters(Future<?> future) throws Exception { // BUG: Diagnostic contains: parameters getChecked(future, OtherParameterTypeException.class); // TODO(cpovirk): Consider a specialized error message if inner classes prove to be common. // BUG: Diagnostic contains: parameters getChecked(future, InnerClassWithExplicitConstructorException.class); // BUG: Diagnostic contains: parameters getChecked(future, InnerClassWithImplicitConstructorException.class); } public static class PrivateConstructorException extends Exception { private PrivateConstructorException() {} } public static class PackagePrivateConstructorException extends Exception { PackagePrivateConstructorException() {} } public static class ProtectedConstructorException extends Exception { protected ProtectedConstructorException() {} } public class OtherParameterTypeException extends Exception { public OtherParameterTypeException(int it) {} } public class InnerClassWithExplicitConstructorException extends Exception { public InnerClassWithExplicitConstructorException() {} } public class InnerClassWithImplicitConstructorException extends Exception {} }
3,174
39.189873
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/IterableAndIteratorNegativeCases.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.util.Iterator; /** * @author jsjeon@google.com (Jinseong Jeon) */ public class IterableAndIteratorNegativeCases { /** Test Node */ public static class MyNode { String tag; MyNode next; } /** Test List that implements only Iterator */ public static class MyList1 implements Iterator<MyNode> { private MyNode head; public MyList1() { head = null; } @Override public boolean hasNext() { return head != null; } @Override public MyNode next() { if (hasNext()) { MyNode ret = head; head = head.next; return ret; } return null; } @Override public void remove() { throw new UnsupportedOperationException("remove is not supported"); } public void add(MyNode node) { if (!hasNext()) { head.next = node; } head = node; } } /** Test List that implements only Iterable */ public static class MyList2 implements Iterable<MyNode> { @Override public Iterator<MyNode> iterator() { MyList1 l = new MyList1(); // code to populate the list goes here return l; } } }
1,830
22.177215
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/FinallyPositiveCase2.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.io.IOException; /** * @author cushon@google.com (Liam Miller-Cushon) */ public class FinallyPositiveCase2 { public void completeWithReturn(boolean flag) { try { } finally { // BUG: Diagnostic contains: return; } } public void completeWithThrow(boolean flag) throws Exception { try { } finally { // BUG: Diagnostic contains: throw new Exception(); } } public void unreachableThrow(boolean flag) throws Exception { try { } finally { if (flag) { // BUG: Diagnostic contains: throw new Exception(); } } } public void nestedBlocks(int i, boolean flag) throws Exception { try { } finally { switch (i) { default: { while (flag) { do { if (flag) { } else { // BUG: Diagnostic contains: throw new Exception(); } } while (flag); } } } } } public void nestedFinally() throws Exception { try { } finally { try { } finally { // BUG: Diagnostic contains: throw new IOException(); } } } public void returnFromTryNestedInFinally() { try { } finally { try { // BUG: Diagnostic contains: return; } finally { } } } public void returnFromCatchNestedInFinally() { try { } finally { try { } catch (Exception e) { // BUG: Diagnostic contains: return; } finally { } } } public void throwUncaughtFromNestedTryInFinally() throws Exception { try { } finally { try { // BUG: Diagnostic contains: throw new Exception(); } finally { } } } public void throwFromNestedCatchInFinally() throws Exception { try { } finally { try { } catch (Exception e) { // BUG: Diagnostic contains: throw new Exception(); } finally { } } } }
2,736
19.578947
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/Allowlist.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.lang.annotation.ElementType; import java.lang.annotation.Target; @Target({ElementType.METHOD, ElementType.CONSTRUCTOR}) public @interface Allowlist {}
825
34.913043
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ObjectToStringPositiveCases.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author bhagwani@google.com (Sumit Bhagwani) */ public class ObjectToStringPositiveCases { public static final class FinalObjectClassWithoutToString {} public static final class FinalGenericClassWithoutToString<T> {} void directToStringCalls() { FinalObjectClassWithoutToString finalObjectClassWithoutToString = new FinalObjectClassWithoutToString(); // BUG: Diagnostic contains: ObjectToString System.out.println(finalObjectClassWithoutToString.toString()); } void genericClassShowsErasure() { FinalGenericClassWithoutToString<Object> finalGenericClassWithoutToString = new FinalGenericClassWithoutToString<>(); // BUG: Diagnostic contains: `FinalGenericClassWithoutToString@ System.out.println(finalGenericClassWithoutToString.toString()); } }
1,472
34.071429
79
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/StaticQualifiedUsingExpressionPositiveCase2.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author eaftan@google.com (Eddie Aftandilian) */ public class StaticQualifiedUsingExpressionPositiveCase2 { private static class TestClass { public static int staticTestMethod() { return 1; } } public int test1() { // BUG: Diagnostic contains: method staticTestMethod // return TestClass.staticTestMethod() return new TestClass().staticTestMethod(); } }
1,060
28.472222
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ModifyingCollectionWithItselfPositiveCases.java
/* * Copyright 2011 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.util.ArrayList; import java.util.List; /** * @author scottjohnson@google.com (Scott Johnson) */ public class ModifyingCollectionWithItselfPositiveCases { List<Integer> a = new ArrayList<Integer>(); List<Integer> c = new ArrayList<Integer>(); public void addAll(List<Integer> b) { // BUG: Diagnostic contains: a.addAll(b) this.a.addAll(a); // BUG: Diagnostic contains: a.addAll(1, b) a.addAll(1, a); } public void containsAll(List<Integer> b) { // BUG: Diagnostic contains: this.a.containsAll(b) this.a.containsAll(this.a); // BUG: Diagnostic contains: a.containsAll(b) a.containsAll(this.a); } public void retainAll(List<Integer> a) { // BUG: Diagnostic contains: this.a.retainAll(a) a.retainAll(a); } public void removeAll() { // BUG: Diagnostic contains: a.clear() this.a.removeAll(a); // BUG: Diagnostic contains: a.clear() a.removeAll(a); } static class HasOneField { List<Integer> a; void removeAll() { // BUG: Diagnostic contains: a.clear(); a.removeAll(a); } void testParameterFirst(List<Integer> b) { // BUG: Diagnostic contains: this.a.removeAll(b); b.removeAll(b); } void expressionStatementChecks() { // BUG: Diagnostic contains: ModifyingCollectionWithItself boolean b = 2 == 2 && a.containsAll(a); // BUG: Diagnostic contains: ModifyingCollectionWithItself b = a.retainAll(a); // BUG: Diagnostic contains: ModifyingCollectionWithItself b = a.removeAll(a); } } }
2,234
25.607143
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/StringSplitterPositiveCases.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * Positive test cases for StringSplitter check. * * @author dturner@twosigma.com (David Turner) */ public class StringSplitterPositiveCases { public void StringSplitOneArg() { String foo = "a:b"; // BUG: Diagnostic contains: String[] xs = foo.split(":"); } }
946
28.59375
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ArrayToStringConcatenationNegativeCases.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author adgar@google.com (Mike Edgar) */ public class ArrayToStringConcatenationNegativeCases { public void notArray() { Object a = new Object(); String b = a + " a string"; } public void notArray_refactored() { Object a = new Object(); String b = " a string"; String c = a + b; } }
982
27.911765
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/CannotMockFinalClassPositiveCases.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.Mockito; /** Test for CannotMockFinalClass. */ @RunWith(JUnit4.class) public class CannotMockFinalClassPositiveCases { static final class FinalClass {} // BUG: Diagnostic contains: Mockito cannot mock @Mock FinalClass impossible; public void method() { // BUG: Diagnostic contains: Mockito cannot mock FinalClass local = Mockito.mock(FinalClass.class); } }
1,097
30.371429
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/PrivateSecurityContractProtoAccessPositiveCases.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import com.google.common.html.types.SafeHtmlProto; import com.google.protobuf.ByteString; public class PrivateSecurityContractProtoAccessPositiveCases { static SafeHtmlProto safeHtmlProto; static { safeHtmlProto = SafeHtmlProto.newBuilder() // BUG: Diagnostic contains: Forbidden access to a private proto field .clearPrivateDoNotAccessOrElseSafeHtmlWrappedValue() // BUG: Diagnostic contains: Forbidden access to a private proto field .setPrivateDoNotAccessOrElseSafeHtmlWrappedValue("foo") .build(); } static SafeHtmlProto safeHtmlProtoFromBytes; static { safeHtmlProtoFromBytes = SafeHtmlProto.newBuilder() // BUG: Diagnostic contains: Forbidden access to a private proto field .setPrivateDoNotAccessOrElseSafeHtmlWrappedValueBytes(ByteString.copyFromUtf8("foo")) .build(); } static String readSafeHtmlProto(SafeHtmlProto safeHtmlProto) { // BUG: Diagnostic contains: Forbidden access to a private proto field if (safeHtmlProto.hasPrivateDoNotAccessOrElseSafeHtmlWrappedValue()) { // BUG: Diagnostic contains: Forbidden access to a private proto field return safeHtmlProto.getPrivateDoNotAccessOrElseSafeHtmlWrappedValue(); } return ""; } static ByteString readSafeHtmlProtoBytes(SafeHtmlProto safeHtmlProto) { // BUG: Diagnostic contains: Forbidden access to a private proto field return safeHtmlProto.getPrivateDoNotAccessOrElseSafeHtmlWrappedValueBytes(); } static String readSafeHtmlProtoBuilder(SafeHtmlProto.Builder safeHtmlProto) { // BUG: Diagnostic contains: Forbidden access to a private proto field if (safeHtmlProto.hasPrivateDoNotAccessOrElseSafeHtmlWrappedValue()) { // BUG: Diagnostic contains: Forbidden access to a private proto field return safeHtmlProto.getPrivateDoNotAccessOrElseSafeHtmlWrappedValue(); } return ""; } static ByteString readSafeHtmlProtoBuilderBytes(SafeHtmlProto.Builder safeHtmlProto) { // BUG: Diagnostic contains: Forbidden access to a private proto field return safeHtmlProto.getPrivateDoNotAccessOrElseSafeHtmlWrappedValueBytes(); } }
2,871
38.342466
97
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/BadComparablePositiveCases.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.io.File; import java.util.Comparator; /** * @author irogers@google.com (Ian Rogers) */ public class BadComparablePositiveCases { static class ComparableTest implements Comparable<ComparableTest> { private final long value = 0; public int compareTo(ComparableTest other) { // BUG: Diagnostic contains: return Long.compare(value, other.value); return (int) (value - other.value); } } static class BoxedComparableTest implements Comparable<BoxedComparableTest> { private final Long value = Long.valueOf(0); public int compareTo(BoxedComparableTest other) { // BUG: Diagnostic contains: return value.compareTo(other.value); return (int) (value - other.value); } } static final Comparator<Number> COMPARATOR_UNBOXED_INT_CAST = new Comparator<Number>() { public int compare(Number n1, Number n2) { // BUG: Diagnostic contains: return Long.compare(n1.longValue(), n2.longValue()) return (int) (n1.longValue() - n2.longValue()); } }; static final Comparator<Long> COMPARATOR_BOXED_INT_CAST = new Comparator<Long>() { public int compare(Long n1, Long n2) { // BUG: Diagnostic contains: return n1.compareTo(n2) return (int) (n1 - n2); } }; static final Comparator<File> COMPARATOR_FILE_INT_CAST = new Comparator<File>() { public int compare(File lhs, File rhs) { // BUG: Diagnostic contains: return Long.compare(rhs.lastModified(), lhs.lastModified()) return (int) (rhs.lastModified() - lhs.lastModified()); } }; }
2,294
32.75
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/LockOnNonEnclosingClassLiteralPositiveCases.java
/* * Copyright 2023 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; public class LockOnNonEnclosingClassLiteralPositiveCases { static { // BUG: Diagnostic contains: Lock on the class other than the enclosing class of the code block // can unintentionally prevent the locked class being used properly. synchronized (String.class) { } } private void methodContainsSynchronizedBlock() { // BUG: Diagnostic contains: Lock on the class other than the enclosing class of the code block // can unintentionally prevent the locked class being used properly. synchronized (String.class) { } } class SubClass { public void methodContainsSynchronizedBlock() { // BUG: Diagnostic contains: Lock on the class other than the enclosing class of the code // block can unintentionally prevent the locked class being used properly. synchronized (LockOnNonEnclosingClassLiteralPositiveCases.class) { } } } }
1,562
33.733333
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/LambdaFunctionalInterfacePositiveCases.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.util.ArrayList; import java.util.List; import java.util.function.Function; public class LambdaFunctionalInterfacePositiveCases { // BUG: Diagnostic contains: [LambdaFunctionalInterface] private double fooIntToDoubleFunctionPr(int x, Function<Integer, Double> fn) { return fn.apply(x); } // BUG: Diagnostic contains: [LambdaFunctionalInterface] private long fooIntToLongFunction(int x, Function<Integer, Long> fn) { return fn.apply(x); } // BUG: Diagnostic contains: [LambdaFunctionalInterface] private long fooIntToIntFunction(int x, Function<Integer, Long> fn) { return fn.apply(x); } // BUG: Diagnostic contains: [LambdaFunctionalInterface] private double fooDoubleToDoubleFunction(double x, Function<Double, Double> fn) { return fn.apply(x); } // BUG: Diagnostic contains: [LambdaFunctionalInterface] private int fooDoubleToIntFunction(double x, Function<Double, Integer> fn) { return fn.apply(x); } // BUG: Diagnostic contains: [LambdaFunctionalInterface] private void fooInterface(String str, Function<Integer, Double> func) {} // BUG: Diagnostic contains: [LambdaFunctionalInterface] private double fooDouble(double x, Function<Double, Integer> fn) { return fn.apply(x); } public static class WithCallSiteExplicitFunction { private static double generateDataSeries(Function<Double, Double> curveFunction) { final double scale = 100; final double modX = 2.0; return modX / curveFunction.apply(scale); } // call site private static double generateSpendCurveForMetric(double curved) { // explicit Function variable creation Function<Double, Double> curveFunction = x -> Math.pow(x, 1 / curved) * 100; return generateDataSeries(curveFunction); } // call site: lambda Function public Double getMu() { return generateDataSeries(mu -> 2.3); } } public static class WithCallSiteAnonymousFunction { private static double findOptimalMu(Function<Double, Long> costFunc, double mid) { return costFunc.apply(mid); } // call site: anonymous Function public Double getMu() { return findOptimalMu( new Function<Double, Long>() { @Override public Long apply(Double mu) { return 0L; } }, 3.0); } } public static class WithCallSiteLambdaFunction { // BUG: Diagnostic contains: [LambdaFunctionalInterface] private static double findOptimalMuLambda(Function<Double, Long> costFunc, double mid) { return costFunc.apply(mid); } // call site: lambda public Double getMu() { return findOptimalMuLambda(mu -> 0L, 3.0); } // call site: lambda public Double getTu() { return findOptimalMuLambda(mu -> 2L, 4.0); } } public static class TwoLambdaFunctions { // BUG: Diagnostic contains: [LambdaFunctionalInterface] private static double find( Function<Double, Long> firstFunc, Function<Integer, Long> secondFun, double mid) { firstFunc.apply(mid + 2); return firstFunc.apply(mid); } // call site: lambda public Double getMu() { return find(mu -> 0L, nu -> 1L, 3.0); } // call site: lambda public Double getTu() { return find(mu -> 2L, nu -> 3L, 4.0); } } public static class NumbertoT { // BUG: Diagnostic contains: [LambdaFunctionalInterface] private static <T extends Number> List<T> numToTFunction(Function<Double, T> converter) { List<T> namedNumberIntervals = new ArrayList<>(); T min = converter.apply(2.9); T max = converter.apply(5.6); namedNumberIntervals.add(min); namedNumberIntervals.add(max); return namedNumberIntervals; } // call site: lambda public List<Integer> getIntList() { List<Integer> result = numToTFunction(num -> 2 + 3); return result; } // call site: lambda public List<Double> getDoubleList() { List<Double> result = numToTFunction(num -> 2.3); return result; } } public static class TtoNumber { // BUG: Diagnostic contains: [LambdaFunctionalInterface] private <T> int sumAll(Function<T, Integer> sizeConv) { return sizeConv.apply((T) Integer.valueOf(3)); } public int getSumAll() { return sumAll(o -> 2); } } }
5,047
27.681818
93
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ArrayHashCodeNegativeCases2.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.util.Objects; /** * Java 7 specific tests * * @author eaftan@google.com (Eddie Aftandilian) */ public class ArrayHashCodeNegativeCases2 { private Object[] objArray = {1, 2, 3}; private String[] stringArray = {"1", "2", "3"}; private int[] intArray = {1, 2, 3}; private byte[] byteArray = {1, 2, 3}; private Object obj = new Object(); private String str = "foo"; public void nonVaragsHashCodeOnNonArrayType() { int hashCode; hashCode = Objects.hashCode(obj); hashCode = Objects.hashCode(str); } public void varagsHashCodeOnNonArrayType() { int hashCode; hashCode = Objects.hash(obj); hashCode = Objects.hash(str); } public void varagsHashCodeOnObjectOrStringArray() { int hashCode; hashCode = Objects.hash(objArray); hashCode = Objects.hash((Object[]) stringArray); } }
1,512
27.54717
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/BanJNDINegativeCases.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import javax.naming.Name; import javax.naming.NamingException; import javax.naming.directory.DirContext; /** * {@link BanJNDITest} * * @author tshadwell@google.com (Thomas Shadwell) */ class BanJNDIPositiveCases { private static DirContext FakeDirContext = ((DirContext) new Object()); // Check we didn't ban all of Context by accident. private void callsList() throws NamingException { FakeDirContext.list(((Name) new Object())); } }
1,115
30
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/NoAllocationCheckerPositiveCases.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import com.google.errorprone.annotations.NoAllocation; /** * @author agoode@google.com (Adam Goode) */ public class NoAllocationCheckerPositiveCases { // Trigger on new array. @NoAllocation public int[] newArray(int size) { // BUG: Diagnostic contains: @NoAllocation // Allocating a new array return new int[size]; } @NoAllocation public int[] arrayInitializer(int a, int b) { // BUG: Diagnostic contains: @NoAllocation // Allocating a new array int[] array = {a, b}; return array; } @NoAllocation public int[] returnArrayInitializer(int a, int b) { // BUG: Diagnostic contains: @NoAllocation // Allocating a new array return new int[] {a, b}; } // Trigger on new. @NoAllocation public String newString(String s) { // BUG: Diagnostic contains: @NoAllocation // Constructing return new String(s); } // Trigger calling a method that does allocation. public String allocateString() { return new String(); } @NoAllocation public String getString() { // BUG: Diagnostic contains: @NoAllocation // Calling a method return allocateString(); } // Trigger on string conversion. @NoAllocation public int getInt() { return 1; } @NoAllocation public String stringConvReturn(int i) { // BUG: Diagnostic contains: @NoAllocation // String concatenation return "" + i; } @NoAllocation public String stringConvAssign(int i) { // BUG: Diagnostic contains: @NoAllocation // String concatenation String s = "" + i; return s; } @NoAllocation public String stringConvAssign2(int i) { String s = ""; // BUG: Diagnostic contains: @NoAllocation // String concatenation s = s + i; return s; } @NoAllocation public String stringConvAssign3(int i) { String s = ""; // BUG: Diagnostic contains: @NoAllocation // String concatenation s = i + s; return s; } @NoAllocation public String stringConvReturnMethod() { // BUG: Diagnostic contains: @NoAllocation // String concatenation String s = "" + getInt(); return s; } @NoAllocation public String stringConvCompoundAssign(int i) { String s = ""; // BUG: Diagnostic contains: @NoAllocation // Compound assignment s += i; return s; } @NoAllocation public String stringConvCompoundReturnMethod() { String s = ""; // BUG: Diagnostic contains: @NoAllocation // Compound assignment s += getInt(); return s; } // Trigger on string concatenation. @NoAllocation public String doubleString(String s) { // BUG: Diagnostic contains: @NoAllocation // String concatenation return s + s; } @NoAllocation public String doubleStringCompound(String s) { // BUG: Diagnostic contains: @NoAllocation // Compound assignment s += s; return s; } // Trigger on foreach with non-array. @NoAllocation public int iteration(Iterable<Object> a) { int result = 0; // BUG: Diagnostic contains: @NoAllocation // Iterating for (Object o : a) { result++; } return result; } // Trigger on autoboxing. @NoAllocation public Integer assignBox(int i) { Integer in; // BUG: Diagnostic contains: @NoAllocation // Assigning a primitive value in = i; return in; } @NoAllocation public Integer initializeBox(int i) { // BUG: Diagnostic contains: @NoAllocation // Initializing a non-primitive Integer in = i; return in; } @NoAllocation public Integer initializeBoxLiteral() { // BUG: Diagnostic contains: @NoAllocation // Initializing a non-primitive Integer in = 0; return in; } @NoAllocation public int castBox(int i) { // BUG: Diagnostic contains: @NoAllocation // Casting a primitive int in = (Integer) i; return in; } @NoAllocation public Integer returnBox(int i) { // BUG: Diagnostic contains: @NoAllocation // Returning a primitive return i; } @NoAllocation public int unBox(Integer i) { return i; } @NoAllocation public void callBox(int i) { // BUG: Diagnostic contains: @NoAllocation // Calling a method unBox(i); } @NoAllocation public int unBox2(int i1, Integer i2) { return i2; } @NoAllocation public void callBox2(int i1, int i2) { // BUG: Diagnostic contains: @NoAllocation // Calling a method unBox2(i1, i2); } @NoAllocation public int unBox3(Integer i1, int i2) { return i1; } @NoAllocation public void callBox3(int i1, int i2) { // BUG: Diagnostic contains: @NoAllocation // Calling a method unBox3(i1, i2); } @NoAllocation public int varArgsMethod(int a, int... b) { return a + b[0]; } @NoAllocation public void callVarArgs0() { // BUG: Diagnostic contains: @NoAllocation // Calling a method varArgsMethod(0); } @NoAllocation public void callVarArgs() { // BUG: Diagnostic contains: @NoAllocation // Calling a method varArgsMethod(1, 2); } @NoAllocation public void callVarArgs2() { // BUG: Diagnostic contains: @NoAllocation // Calling a method varArgsMethod(1, 2, 3); } @NoAllocation public Object varArgsMethodObject(Object a, Object... b) { return b[0]; } @NoAllocation public void callVarArgsObject(Object a, Object[] b) { // BUG: Diagnostic contains: @NoAllocation // Calling a method varArgsMethodObject(a, b[0]); } @NoAllocation public void callVarArgsObjectWithPrimitiveArray(Object a, int[] b) { // BUG: Diagnostic contains: @NoAllocation // Calling a method varArgsMethodObject(a, b); } @NoAllocation public int forBox(int[] a) { int count = 0; // BUG: Diagnostic contains: @NoAllocation // Pre- and post- increment/decrement for (Integer i = 0; i < a.length; i++) { count++; } return count; } @NoAllocation public void arrayBox(Integer[] a, int i) { // BUG: Diagnostic contains: @NoAllocation // Assigning a primitive value a[0] = i; } @NoAllocation public int preIncrementBox(Integer i) { // BUG: Diagnostic contains: @NoAllocation // Pre- and post- increment/decrement ++i; return i; } @NoAllocation public int postIncrementBox(Integer i) { // BUG: Diagnostic contains: @NoAllocation // Pre- and post- increment/decrement i++; return i; } @NoAllocation public int preDecrementBox(Integer i) { // BUG: Diagnostic contains: @NoAllocation // Pre- and post- increment/decrement --i; return i; } @NoAllocation public int postDecrementBox(Integer i) { // BUG: Diagnostic contains: @NoAllocation // Pre- and post- increment/decrement i--; return i; } @NoAllocation public int forEachBox(int[] a) { int last = -1; // BUG: Diagnostic contains: @NoAllocation // Iterating for (Integer i : a) { last = i; } return last; } @NoAllocation public void arrayPreIncrementBox(Integer[] a) { // BUG: Diagnostic contains: @NoAllocation // Pre- and post- increment/decrement ++a[0]; } @NoAllocation public void arrayPostIncrementBox(Integer[] a) { // BUG: Diagnostic contains: @NoAllocation // Pre- and post- increment/decrement a[0]++; } @NoAllocation public void arrayPreDecrementBox(Integer[] a) { // BUG: Diagnostic contains: @NoAllocation // Pre- and post- increment/decrement --a[0]; } @NoAllocation public void arrayPostDecrementBox(Integer[] a) { // BUG: Diagnostic contains: @NoAllocation // Pre- and post- increment/decrement a[0]--; } @NoAllocation public int compoundBox(Integer a, int b) { // BUG: Diagnostic contains: @NoAllocation // Compound assignment a += b; return a; } @NoAllocation public void arrayCompoundBox(Integer[] a, int b) { // BUG: Diagnostic contains: @NoAllocation // Compound assignment a[0] += b; } @NoAllocation public void andAssignmentBox(Integer i1, Integer i2) { // BUG: Diagnostic contains: @NoAllocation // Compound assignment i1 &= i2; } @NoAllocation public void divideAssignmentBox(Integer i1, Integer i2) { // BUG: Diagnostic contains: @NoAllocation // Compound assignment i1 /= i2; } @NoAllocation public void leftShiftAssignmentBox(Integer i1, Integer i2) { // BUG: Diagnostic contains: @NoAllocation // Compound assignment i1 <<= i2; } @NoAllocation public void minusAssignmentBox(Integer i1, Integer i2) { // BUG: Diagnostic contains: @NoAllocation // Compound assignment i1 -= i2; } @NoAllocation public void multiplyAssignmentBox(Integer i1, Integer i2) { // BUG: Diagnostic contains: @NoAllocation // Compound assignment i1 *= i2; } @NoAllocation public void orAssignmentBox(Integer i1, Integer i2) { // BUG: Diagnostic contains: @NoAllocation // Compound assignment i1 |= i2; } @NoAllocation public void plusAssignmentBox(Integer i1, Integer i2) { // BUG: Diagnostic contains: @NoAllocation // Compound assignment i1 += i2; } @NoAllocation public void remainderAssignmentBox(Integer i1, Integer i2) { // BUG: Diagnostic contains: @NoAllocation // Compound assignment i1 %= i2; } @NoAllocation public void rightShiftAssignmentBox(Integer i1, Integer i2) { // BUG: Diagnostic contains: @NoAllocation // Compound assignment i1 >>= i2; } @NoAllocation public void unsignedRightShiftAssignmentBox(Integer i1, Integer i2) { // BUG: Diagnostic contains: @NoAllocation // Compound assignment i1 >>>= i2; } @NoAllocation public void xorAssignmentBox(Integer i1, Integer i2) { // BUG: Diagnostic contains: @NoAllocation // Compound assignment i1 ^= i2; } // Cloning is right out. @NoAllocation public Object doClone() throws CloneNotSupportedException { // BUG: Diagnostic contains: @NoAllocation // Calling a method return clone(); } // Throwing doesn't exempt through method declarations. @NoAllocation public String throwForeach(final Iterable<Object> a) { throw new RuntimeException() { @NoAllocation private void f() { // BUG: Diagnostic contains: @NoAllocation // Iterating for (Object o : a) { // BUG: Diagnostic contains: @NoAllocation // Calling a method a.toString(); } } }; } public interface NoAllocationInterface { @NoAllocation void method(); } public static class NoAllocationImplementingClass implements NoAllocationInterface { @Override // BUG: Diagnostic contains: @NoAllocation public void method() {} } public abstract static class NoAllocationAbstractClass { @NoAllocation abstract void method(); } public static class NoAllocationConcreteClass extends NoAllocationAbstractClass { @Override // BUG: Diagnostic contains: @NoAllocation void method() {} } public static class NoAllocationParentClass implements NoAllocationInterface { @Override @NoAllocation public void method() {} } public static class NoAllocationSubclass extends NoAllocationParentClass { @Override // BUG: Diagnostic contains: @NoAllocation public void method() {} } }
12,080
22.099426
86
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/FinallyNegativeCase2.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.io.IOException; /** * @author cushon@google.com (Liam Miller-Cushon) */ public class FinallyNegativeCase2 { public void test1(boolean flag) { try { return; } finally { } } public void test2() throws Exception { try { } catch (Exception e) { throw new Exception(); } finally { } } public void returnInAnonymousClass(boolean flag) { try { } finally { new Object() { void foo() { return; } }; } } public void throwFromNestedTryInFinally() throws Exception { try { } finally { try { throw new Exception(); } catch (Exception e) { } finally { } } } public void nestedTryInFinally2() throws Exception { try { } finally { try { // This exception will propagate out through the enclosing finally, // but we don't do exception analysis and have no way of knowing that. // Xlint:finally doesn't handle this either, since it only reports // situations where the end of a finally block is unreachable as // definied by JLS 14.21. throw new IOException(); } catch (Exception e) { } } } }
1,888
23.532468
78
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/UngroupedOverloadsPositiveCasesCovering.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author hanuszczak@google.com (Łukasz Hanuszczak) */ public class UngroupedOverloadsPositiveCasesCovering { // BUG: Diagnostic contains: ungrouped overloads of 'foo' public void foo(int x) { System.out.println(x); } // BUG: Diagnostic contains: ungrouped overloads of 'bar' public void bar() { foo(); } public void baz() { bar(); } // BUG: Diagnostic contains: ungrouped overloads of 'bar' public void bar(int x) { foo(x); } // BUG: Diagnostic contains: ungrouped overloads of 'quux' private void quux() { norf(); } private void norf() { quux(); } // BUG: Diagnostic contains: ungrouped overloads of 'quux' public void quux(int x) { bar(x); } // BUG: Diagnostic contains: ungrouped overloads of 'foo' public void foo() { foo(42); } }
1,488
23.016129
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/StringSplitterNegativeCases.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * Negative test cases for StringSplitter check. * * @author dturner@twosigma.com (David Turner) */ public class StringSplitterNegativeCases { public void StringSplitTwoArgs() { String foo = "a:b"; foo.split(":", 1); } public void StringSplitTwoArgsOneNegative() { String foo = "a:b"; foo.split(":", -1); } }
1,003
27.685714
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/FuzzyEqualsShouldNotBeUsedInEqualsMethodPositiveCases.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import com.google.common.math.DoubleMath; /** * @author sulku@google.com (Marsela Sulku) */ public class FuzzyEqualsShouldNotBeUsedInEqualsMethodPositiveCases { public boolean equals(Object o) { // BUG: Diagnostic contains: DoubleMath.fuzzyEquals should never DoubleMath.fuzzyEquals(0.2, 9.3, 2.0); return true; } private class TestClass { public boolean equals(Object other) { double x = 0, y = 0, z = 0; // BUG: Diagnostic contains: DoubleMath.fuzzyEquals should never return DoubleMath.fuzzyEquals(x, y, z); } } }
1,230
29.775
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/OverridesPositiveCase2.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.bugpatterns.testdata; /** * This tests the case where there is a chain of method overrides where the varargs constraint is * not met, and the root is a varargs parameter. TODO(cushon): The original implementation tried to * be clever and make this consistent, but didn't handle multiple interface inheritance. * * @author cushon@google.com (Liam Miller-Cushon) */ public class OverridesPositiveCase2 { abstract class Base { abstract void varargsMethod(Object... xs); } abstract class SubOne extends Base { @Override // BUG: Diagnostic contains: abstract void varargsMethod(Object[] newNames); } abstract class SubTwo extends SubOne { @Override // BUG: Diagnostic contains: abstract void varargsMethod(Object... xs); } abstract class SubThree extends SubTwo { @Override // BUG: Diagnostic contains: abstract void varargsMethod(Object[] newNames); } }
1,545
31.893617
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/CannotMockFinalClassNegativeCases.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.Mockito; /** Test for CannotMockFinalClass. */ @RunWith(JUnit4.class) public class CannotMockFinalClassNegativeCases { static class NonFinalClass {} @Mock NonFinalClass okToMock; public void method() { NonFinalClass local = Mockito.mock(NonFinalClass.class); } }
997
29.242424
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/LongLiteralLowerCaseSuffixNegativeCases.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * Negative cases for {@link LongLiteralLowerCaseSuffix} * * @author Simon Nickerson (sjnickerson@google.com) */ public class LongLiteralLowerCaseSuffixNegativeCases { public void positiveUpperCase() { long value = 123432L; } public void zeroUpperCase() { long value = 0L; } public void negativeUpperCase() { long value = -3L; } public void notLong() { String value = "0l"; } public void variableEndingInEllIsNotALongLiteral() { long ell = 0L; long value = ell; } public void positiveNoSuffix() { long value = 3; } public void negativeNoSuffix() { long value = -3; } public void positiveHexUpperCase() { long value = 0x80L; } public void zeroHexUpperCase() { long value = 0x0L; } public void negativeHexUpperCase() { long value = -0x80L; } }
1,504
21.80303
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ComparableAndComparatorPositiveCases.java
/* Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.util.Comparator; /** * @author sulku@google.com (Marsela Sulku) * @author mariasam@google.com (Maria Sam) */ public class ComparableAndComparatorPositiveCases { /** implements both interfaces */ // BUG: Diagnostic contains: Class should not implement both public static class BadClass implements Comparable<BadClass>, Comparator<BadClass> { @Override public int compareTo(BadClass comparableNode) { return 0; } @Override public int compare(BadClass a, BadClass b) { return 0; } } /** Superclass test class */ public static class SuperClass implements Comparator<SuperClass> { @Override public int compare(SuperClass o1, SuperClass o2) { return 0; } } /** SubClass test class */ // BUG: Diagnostic contains: Class should not implement both public static class SubClass extends SuperClass implements Comparable<SubClass> { @Override public int compareTo(SubClass o) { return 0; } } }
1,655
28.052632
86
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/PrimitiveArrayPassedToVarargsMethodPositiveCases.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.util.Arrays; /** * @author eaftan@google.com (Eddie Aftandilian) */ public class PrimitiveArrayPassedToVarargsMethodPositiveCases { public void objectVarargsMethod(Object... objs) {} public <T> void genericVarargsMethod(T... genericArrays) {} public void objectVarargsMethodWithMultipleParams(Object obj1, Object... objs) {} public void doIt() { int[] intArray = {1, 2, 3}; // BUG: Diagnostic contains: objectVarargsMethod(intArray); // BUG: Diagnostic contains: genericVarargsMethod(intArray); // BUG: Diagnostic contains: objectVarargsMethodWithMultipleParams(new Object(), intArray); // BUG: Diagnostic contains: Arrays.asList(intArray); } }
1,376
27.6875
83
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/FinallyNegativeCase1.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author eaftan@google.com (Eddie Aftandilian) */ public class FinallyNegativeCase1 { public static void test1() { while (true) { try { break; } finally { } } } public static void test2() { while (true) { try { continue; } finally { } } } public static void test3() { try { return; } finally { } } public static void test4() throws Exception { try { throw new Exception(); } catch (Exception e) { } finally { } } /** break inner loop. */ public void test5() { label: while (true) { try { } finally { while (true) { break; } } } } /** continue statement jumps out of inner for. */ public void test6() { label: for (; ; ) { try { } finally { for (; ; ) { continue; } } } } /** break statement jumps out of switch. */ public void test7() { int i = 10; while (true) { try { } finally { switch (i) { case 10: break; } } } } }
1,819
17.762887
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/SelfEqualsNegativeCases.java
/* * Copyright 2011 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import static com.google.common.truth.Truth.assertThat; /** * Negative test cases for {@link SelfEquals} check. * * @author alexeagle@google.com (Alex Eagle) * @author bhagwani@google.com (Sumit Bhagwani) */ public class SelfEqualsNegativeCases { private String field; @Override public int hashCode() { return field != null ? field.hashCode() : 0; } @Override public boolean equals(Object o) { if (!(o instanceof SelfEqualsNegativeCases)) { return false; } SelfEqualsNegativeCases other = (SelfEqualsNegativeCases) o; return field.equals(other.field); } public boolean test() { return Boolean.TRUE.toString().equals(Boolean.FALSE.toString()); } public void testAssertThatEq(SelfEqualsNegativeCases obj) { assertThat(obj).isEqualTo(obj); } public void testAssertThatNeq(SelfEqualsNegativeCases obj) { assertThat(obj).isNotEqualTo(obj); } }
1,577
26.684211
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/OverridesNegativeCase2.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @author cushon@google.com (Liam Miller-Cushon) */ public class OverridesNegativeCase2 { abstract class Base { abstract void varargsMethod(Object... xs); } abstract class SubOne extends Base { @Override abstract void varargsMethod(Object... newNames); } abstract class SubTwo extends SubOne { @Override abstract void varargsMethod(Object... xs); } abstract class SubThree extends SubTwo { @Override abstract void varargsMethod(Object... newNames); } }
1,158
27.975
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/OverridesPositiveCase1.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.bugpatterns.testdata; /** * This tests that the a bug is reported when a method override changes the type of a parameter from * varargs to array, or array to varargs. It also ensures that the implementation can handles cases * with multiple parameters, and whitespaces between the square brackets for array types. * * @author cushon@google.com (Liam Miller-Cushon) */ public class OverridesPositiveCase1 { abstract class Base { abstract void varargsMethod(Object... xs); abstract void arrayMethod(int x, Object[] xs); } abstract class Child1 extends Base { @Override // BUG: Diagnostic contains: abstract void arrayMethod(int x, Object[] newNames); abstract void arrayMethod(int x, Object... newNames); } abstract class Child2 extends Base { @Override // BUG: Diagnostic contains: abstract void varargsMethod(Object... xs); abstract void varargsMethod(Object[] xs); } abstract class Child3 extends Base { @Override // BUG: Diagnostic contains: abstract void varargsMethod(Object... xs); abstract void varargsMethod(Object[] xs); } abstract class Child4 extends Base { @Override // BUG: Diagnostic contains: abstract void varargsMethod(Object... xs); abstract void varargsMethod(Object[] xs); } abstract class Child5 extends Base { @Override // BUG: Diagnostic contains: Varargs abstract void varargsMethod(Object[ /**/] xs); } interface Interface { void varargsMethod(Object... xs); void arrayMethod(Object[] xs); } abstract class ImplementsInterface implements Interface { @Override // BUG: Diagnostic contains: public abstract void varargsMethod(Object[] xs); @Override // BUG: Diagnostic contains: public abstract void arrayMethod(Object... xs); } abstract class MyBase { abstract void f(Object... xs); abstract void g(Object[] xs); } interface MyInterface { void f(Object[] xs); void g(Object... xs); } abstract class ImplementsAndExtends extends MyBase implements MyInterface { // BUG: Diagnostic contains: public abstract void f(Object... xs); // BUG: Diagnostic contains: public abstract void g(Object[] xs); } abstract class ImplementsAndExtends2 extends MyBase implements MyInterface { // BUG: Diagnostic contains: public abstract void f(Object[] xs); // BUG: Diagnostic contains: public abstract void g(Object... xs); } }
3,080
28.912621
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/InstanceOfAndCastMatchWrongTypeNegativeCases.java
/* Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.io.FilterWriter; import java.io.StringWriter; import java.io.Writer; /** * Created by sulku and mariasam on 6/6/17. * * @author mariasam (Maria Sam) * @author sulku (Marsela Sulku) */ public class InstanceOfAndCastMatchWrongTypeNegativeCases { public static void notCustomClass(Object objSubClass) { if (!(objSubClass instanceof SuperNegativeClass)) { DisjointClass str = (DisjointClass) objSubClass; } } public static void hi(String foo) { if (foo instanceof String) { ((String) foo).charAt(0); } } public static void castToSameClass(String foo) { if (foo instanceof String) { ((String) foo).charAt(0); } } public static void castToSameClassWithExtraLines(String foo) { if (foo instanceof String) { String somethingBefore = "hello"; ((String) foo).charAt(0); String somethingAfter = "goodbye"; } } public static void castAMethod() { if (testCall() instanceof String) { String bar = (String) testCall(); } } public static void castToSuperType(String foo) { if (foo instanceof String) { Object bar = ((Object) foo).toString(); } } public static void castMethodToSuperType(String foo) { if (testCall() instanceof String) { Object bar = (Object) testCall(); } } public static void castToCustomSuperType() { SuperNegativeClass superClass = new SuperNegativeClass(); SubNegativeClass subClass = new SubNegativeClass(); if (subClass instanceof SubNegativeClass) { String str = ((SuperNegativeClass) subClass).toString(); } } public static void castToSubtype(String foo) { if (foo instanceof Object) { String somethingBefore = "hello"; String bar = ((String) foo).toString(); String somethingAfter = "goodbye"; } } public static void nestedIfStatements(String foo) { if (7 == 7) { if (foo instanceof Object) { String bar = ((String) foo).toString(); } } } public static void castMethodToSubType() { if (testCall() instanceof Object) { String bar = ((String) testCall()).toString(); } } public static void castAMethodInElse() { if (testCall() instanceof Object) { String str = ""; } else { String bar = ((String) testCall()).toString(); } } public static void nestedIfOutside() { SubNegativeClass subClass = new SubNegativeClass(); if (subClass instanceof SuperNegativeClass) { if (7 == 7) { String bar = ((SuperNegativeClass) subClass).toString(); } } } public static void nestedIfElseInIf() { SubNegativeClass subClass = new SubNegativeClass(); if (subClass instanceof SuperNegativeClass) { if (7 == 7) { String bar = ((SuperNegativeClass) subClass).toString(); } else { String str = ""; } } } public static void elseIfMethod() { if (testCall() instanceof Object) { String str = ""; } else if (7 == 7) { String bar = ((String) testCall()).toString(); } else { String str = ""; } } public static void nestedSubClasses(Object objSubClass) { if (objSubClass instanceof SuperNegativeClass) { if (objSubClass instanceof DisjointClass) { DisjointClass disClass = (DisjointClass) objSubClass; } } } public static void switchCaseStatement(Object objSubClass) { Integer datatype = 0; if (objSubClass instanceof SuperNegativeClass) { String str = ""; } else { switch (datatype) { case 0: DisjointClass str = (DisjointClass) objSubClass; break; default: break; } } } public static void nestedAnd(String foo, Object foo3) { if (foo instanceof String) { if (foo3 instanceof SuperNegativeClass && ((SuperNegativeClass) foo3).toString().equals("")) { String str = foo3.toString(); } } } private static void multipleElseIf(Object foo3) { if (foo3 instanceof String) { String str = ""; } else if (7 == 7 && foo3 instanceof SuperNegativeClass) { ((SuperNegativeClass) foo3).toString(); } else if (8 == 8) { DisjointClass dis = (DisjointClass) foo3; } } private static void orInCondition(Object foo3) { if (foo3 instanceof String || 7 == 7) { String str = ((DisjointClass) foo3).toString(); } } private static void castInElse(Object foo3) { if (foo3 instanceof String) { String str = ""; } else { String str = ((DisjointClass) foo3).toString(); } } private static void multipleObjectCasts(Object foo2, Object foo3) { if (foo3 instanceof String) { String str = ((DisjointClass) foo2).toString(); } else { String str = ((DisjointClass) foo3).toString(); } } private static void orsAndAnds(Object foo2) { if (7 == 7 && (foo2 instanceof DisjointClass) && (!((DisjointClass) foo2).equals(""))) { String str = ""; } } private static void assignmentInBlock(Object foo2) { if (foo2 instanceof SuperNegativeClass) { foo2 = ""; String str = ((Integer) foo2).toString(); } } private static void assignmentInBlockElse(Object foo2) { String foo1; if (foo2 instanceof SuperNegativeClass) { String str = ""; } else { foo1 = ""; String str = ((Integer) foo2).toString(); } } private static void assignmentInBlockElseIf(Object foo2) { Object foo1 = null; if (foo2 instanceof SuperNegativeClass) { String str = ""; } else if (foo2 == foo1) { foo1 = ""; String str = ((Integer) foo2).toString(); } } private static void innerClassDecl(Object[] list) { for (Object c : list) { if (c instanceof String) { try { Writer fw = new FilterWriter(new StringWriter()) { public void write(int c) { char a = (char) c; } }; } catch (Exception e) { String str = ""; } } } } private static void randomCode(Object foo) { if (7 == 7) { System.out.println("test"); foo = (Integer) foo; } } private static void twoAssignments(Object foo, Object foo2) { if (foo instanceof String) { foo2 = ""; String str = (String) foo; foo = ""; } } public static String testCall() { return ""; } public static Object testCallReturnsObject() { return new Object(); } static class SuperNegativeClass {} static class SubNegativeClass extends SuperNegativeClass {} static class DisjointClass {} }
7,322
24.785211
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ArrayHashCodeNegativeCases.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import com.google.common.base.Objects; /** * @author eaftan@google.com (Eddie Aftandilian) */ public class ArrayHashCodeNegativeCases { private Object[] objArray = {1, 2, 3}; private String[] stringArray = {"1", "2", "3"}; private int[] intArray = {1, 2, 3}; private byte[] byteArray = {1, 2, 3}; private Object obj = new Object(); private String str = "foo"; public void objectHashCodeOnNonArrayType() { int hashCode; hashCode = obj.hashCode(); hashCode = str.hashCode(); } public void varagsHashCodeOnNonArrayType() { int hashCode; hashCode = Objects.hashCode(obj); hashCode = Objects.hashCode(str); } public void varagsHashCodeOnObjectOrStringArray() { int hashCode; hashCode = Objects.hashCode(objArray); hashCode = Objects.hashCode((Object[]) stringArray); } }
1,495
28.333333
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/SelfComparisonPositiveCase.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * Positive test case for {@link SelfComparison} check. * * @author bhagwani@google.com (Sumit Bhagwani) */ public class SelfComparisonPositiveCase implements Comparable<Object> { public int test1() { SelfComparisonPositiveCase obj = new SelfComparisonPositiveCase(); // BUG: Diagnostic contains: An object is compared to itself return obj.compareTo(obj); } private SelfComparisonPositiveCase obj = new SelfComparisonPositiveCase(); public int test2() { // BUG: Diagnostic contains: An object is compared to itself return obj.compareTo(this.obj); } public int test3() { // BUG: Diagnostic contains: An object is compared to itself return this.obj.compareTo(obj); } public int test4() { // BUG: Diagnostic contains: An object is compared to itself return this.obj.compareTo(this.obj); } public int test5() { // BUG: Diagnostic contains: An object is compared to itself return compareTo(this); } @Override public int compareTo(Object o) { return 0; } public static class ComparisonTest implements Comparable<ComparisonTest> { private String testField; @Override public int compareTo(ComparisonTest s) { return testField.compareTo(s.testField); } public int test1() { ComparisonTest obj = new ComparisonTest(); // BUG: Diagnostic contains: An object is compared to itself return obj.compareTo(obj); } private ComparisonTest obj = new ComparisonTest(); public int test2() { // BUG: Diagnostic contains: An object is compared to itself return obj.compareTo(this.obj); } public int test3() { // BUG: Diagnostic contains: An object is compared to itself return this.obj.compareTo(obj); } public int test4() { // BUG: Diagnostic contains: An object is compared to itself return this.obj.compareTo(this.obj); } public int test5() { // BUG: Diagnostic contains: An object is compared to itself return compareTo(this); } } }
2,710
27.239583
76
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/DepAnnNegativeCase1.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; /** * @deprecated */ @Deprecated public class DepAnnNegativeCase1 { /** * @deprecated */ @Deprecated public DepAnnNegativeCase1() {} /** * @deprecated */ @Deprecated int myField; /** * @deprecated */ @Deprecated enum Enum { VALUE, } /** * @deprecated */ @Deprecated interface Interface {} /** * @deprecated */ @Deprecated public void deprecatedMethood() {} @Deprecated public void deprecatedMethoodWithoutComment() {} /** deprecated */ public void deprecatedMethodWithMalformedComment() {} /** * @deprecated */ @SuppressWarnings("dep-ann") public void suppressed() {} public void newMethod() {} }
1,356
18.385714
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/JUnit4TestNotRunNegativeCase3.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import org.junit.*; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author eaftan@google.com (Eddie Aftandilian) */ @RunWith(JUnit4.class) public class JUnit4TestNotRunNegativeCase3 { // Doesn't begin with "test", and doesn't contain any assertion-like method invocations. public void thisIsATest() {} // Isn't public. void testTest1() {} // Have checked annotation. @Test public void testTest2() {} @Before public void testBefore() {} @After public void testAfter() {} @BeforeClass public void testBeforeClass() {} @AfterClass public void testAfterClass() {} // Has parameters. public void testTest3(int foo) {} // Doesn't return void public int testSomething() { return 42; } }
1,422
23.534483
90
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/ArrayEqualsNegativeCases2.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import java.util.Objects; /** * Tests that only run with Java 7 and above. * * @author eaftan@google.com (Eddie Aftandilian) */ public class ArrayEqualsNegativeCases2 { public void neitherArray() { Object a = new Object(); Object b = new Object(); if (Objects.equals(a, b)) { System.out.println("Objects are equal!"); } else { System.out.println("Objects are not equal!"); } } public void firstArray() { Object[] a = new Object[3]; Object b = new Object(); if (Objects.equals(a, b)) { System.out.println("arrays are equal!"); } else { System.out.println("arrays are not equal!"); } } public void secondArray() { Object a = new Object(); Object[] b = new Object[3]; if (Objects.equals(a, b)) { System.out.println("arrays are equal!"); } else { System.out.println("arrays are not equal!"); } } }
1,574
25.25
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/BanSerializableReadPositiveCases_expected.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import com.google.errorprone.bugpatterns.BanSerializableReadTest; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.Serializable; /** * {@link BanSerializableReadTest} * * @author tshadwell@google.com (Thomas Shadwell) */ class BanSerializableReadPositiveCases implements Serializable { public final String hi = "hi"; /** * Says 'hi' by piping the string value unsafely through Object I/O stream * * @throws IOException * @throws ClassNotFoundException */ @SuppressWarnings("BanSerializableRead") public static final void sayHi() throws IOException, ClassNotFoundException { PipedInputStream in = new PipedInputStream(); PipedOutputStream out = new PipedOutputStream(in); ObjectOutputStream serializer = new ObjectOutputStream(out); ObjectInputStream deserializer = new ObjectInputStream(in); serializer.writeObject(new BanSerializableReadPositiveCases()); serializer.close(); BanSerializableReadPositiveCases crime = // BUG: Diagnostic contains: BanSerializableRead (BanSerializableReadPositiveCases) deserializer.readObject(); System.out.println(crime.hi); } /** * The checker has a special allowlist that allows classes to define methods called readObject -- * Java accepts these as an override to the default serialization behaviour. While we want to * allow such methods to be defined, we don't want to allow these methods to be called. * * @throws IOException * @throws ClassNotFoundException */ @SuppressWarnings("BanSerializableRead") public static final void directCall() throws IOException, ClassNotFoundException { PipedInputStream in = new PipedInputStream(); PipedOutputStream out = new PipedOutputStream(in); ObjectOutputStream serializer = new ObjectOutputStream(out); ObjectInputStream deserializer = new ObjectInputStream(in); BanSerializableReadPositiveCases self = new BanSerializableReadPositiveCases(); // BUG: Diagnostic contains: BanSerializableRead self.readObject(deserializer); } /** * The checker has a special allowlist that allows classes to define methods called readExternal. * Java accepts these as an override to the default serialization behaviour. While we want to * allow such methods to be defined, we don't want to allow these methods to be called. */ @SuppressWarnings("BanSerializableRead") public static final void directCall2() throws IOException { PipedInputStream in = new PipedInputStream(); ObjectInputStream deserializer = new ObjectInputStream(in); BanSerializableReadNegativeCases neg = new BanSerializableReadNegativeCases(); // BUG: Diagnostic contains: BanSerializableRead neg.readExternal(deserializer); } public void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); } }
3,663
36.387755
99
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/bugpatterns/testdata/SuppressWarningsDeprecatedPositiveCases.java
package com.google.errorprone.bugpatterns.testdata; /* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Positive cases for {@link SuppressWarningsDeprecated}. * * @author sjnickerson@google.com (Simon Nickerson) */ public class SuppressWarningsDeprecatedPositiveCases { // BUG: Diagnostic contains: @SuppressWarnings("deprecation") @SuppressWarnings("deprecated") public static void positiveCase1() {} // BUG: Diagnostic contains: @SuppressWarnings("deprecation") @SuppressWarnings({"deprecated"}) public static void positiveCase2() {} // BUG: Diagnostic contains: @SuppressWarnings({"deprecation", "foobarbaz"}) @SuppressWarnings({"deprecated", "foobarbaz"}) public static void positiveCase3() {} public static void positiveCase4() { // BUG: Diagnostic contains: @SuppressWarnings({"deprecation", "foobarbaz"}) @SuppressWarnings({"deprecated", "foobarbaz"}) int a = 3; } public static void positiveCase5() { // BUG: Diagnostic contains: @SuppressWarnings("deprecation") @SuppressWarnings("deprecated") int a = 3; } public static void positiveCase6() { // BUG: Diagnostic contains: @SuppressWarnings("deprecation") @SuppressWarnings("deprecated") class Foo {} ; } public static void positiveCase7() { // BUG: Diagnostic contains: @SuppressWarnings({"deprecation", "foobarbaz"}) @SuppressWarnings({"deprecated", "foobarbaz"}) class Foo {} ; } // BUG: Diagnostic contains: @SuppressWarnings(value = "deprecation") @SuppressWarnings(value = {"deprecated"}) public static void positiveCase8() {} // BUG: Diagnostic contains: @SuppressWarnings(value = "deprecation") @SuppressWarnings(value = "deprecated") public static void positiveCase9() {} }
2,320
31.690141
80
java