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 |
|---|---|---|---|---|---|---|
codeql | codeql-master/java/ql/test/library-tests/successors/TestTryCatch/PopulateRuntimeException.java | // make sure java.lang.RuntimeException is extracted
class MyRuntimeException extends RuntimeException {} | 105 | 52 | 52 | java |
codeql | codeql-master/java/ql/test/library-tests/successors/CloseReaderTest/CloseReaderTest.java | package successors;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
public class CloseReaderTest {
public static String readPassword(File keyFile)
{
// TODO: use Console.readPassword() when it's available.
System.out.print("Enter password for " + keyFile
+ " (password will not be hidden): ");
System.out.flush();
BufferedReader stdin = new BufferedReader(new InputStreamReader(
System.in));
try
{
return stdin.readLine();
} catch (IOException ex)
{
return null;
}
}
}
| 572 | 21.038462 | 66 | java |
codeql | codeql-master/java/ql/test/library-tests/successors/CloseReaderTest/PopulateRuntimeException.java | // make sure java.lang.RuntimeException is extracted
class MyRuntimeException extends RuntimeException {} | 105 | 52 | 52 | java |
codeql | codeql-master/java/ql/test/library-tests/successors/TestContinue/TestContinue.java | package successors;
public class TestContinue {
public void f()
{
//loop breaks
a:
for (int p = 0; p < 10;)
{
int x = 1;
x = x + 1;
if (x == 1)
{
continue;
} else
{
for (int q : new int[20])
{
if (q == 1)
{
continue;
} else if (q == 2)
{
continue a;
}
q = 12;
}
}
}
int y = 12;
while (y != 13)
{
if (y == 1)
{
continue;
} else
{
do
{
if (y == 2)
{
continue;
}
y = y + 2;
} while (y == 1);
y = 12;
}
y = 15;
}
y = 13;
while (y != 12)
{
if (y != 6)
continue;
else
break;
}
}
}
| 684 | 10.416667 | 30 | java |
codeql | codeql-master/java/ql/test/library-tests/successors/TestContinue/PopulateRuntimeException.java | // make sure java.lang.RuntimeException is extracted
class MyRuntimeException extends RuntimeException {} | 105 | 52 | 52 | java |
codeql | codeql-master/java/ql/test/library-tests/successors/TestBreak/TestBreak.java | package successors;
public class TestBreak {
public void f()
{
//loop breaks
a:
for (;;)
{
int x = 1;
x = x + 1;
if (x == 1)
{
break;
} else
{
for (int q : new int[20])
{
if (q == 1)
{
break;
} else
{
break a;
}
}
}
}
int y = 12;
while (true)
{
if (y == 1)
{
break;
} else
{
do
{
if (y == 2)
{
break;
}
y = y + 2;
} while (y == 1);
y = 12;
}
}
y = 13;
//switch breaks
int x =12;
switch (x)
{
case 1:
x = x + 1;
y = y + 1;
case 2:
x = x + 2;
y = y + 2;
break;
case 3:
case 4:
x = x + 3;
y = y + 4;
break;
case 5:
case 6:
x = x + 5;
y = y + 6;
default:
x = y;
y = x;
}
//no default
switch(x)
{
case 1:
x = 1;
break;
case 2:
x = 2;
break;
}
}
}
| 908 | 9.448276 | 30 | java |
codeql | codeql-master/java/ql/test/library-tests/successors/TestBreak/PopulateRuntimeException.java | // make sure java.lang.RuntimeException is extracted
class MyRuntimeException extends RuntimeException {} | 105 | 52 | 52 | java |
codeql | codeql-master/java/ql/test/library-tests/successors/TestThrow2/TestThrow2.java | package successors;
class TestThrow2 {
native void thrower() throws Throwable;
{
try {
thrower();
} catch (Exception e) {
;
}
}
} | 145 | 11.166667 | 40 | java |
codeql | codeql-master/java/ql/test/library-tests/successors/TestThrow2/PopulateRuntimeException.java | // make sure java.lang.RuntimeException is extracted
class MyRuntimeException extends RuntimeException {} | 105 | 52 | 52 | java |
codeql | codeql-master/java/ql/test/library-tests/javadoc/javadoc/Test.java | package javadoc;
/** A test class. */
public class Test {
/** A javadoc
* comment */
void f() {}
/** Another javadoc comment */
// and a normal comment
void g() {}
/* another normal comment */
int x;
int y;
/** @deprecated */
void h() {}
} | 260 | 12.736842 | 33 | java |
codeql | codeql-master/java/ql/test/library-tests/controlflow/dominance/Test.java | class Test {
int test(int x, int w, int z) {
int j;
long y = 50;
// if-else, multiple statements in block
if (x > 0) {
y = 20;
z = 10;
} else {
y = 30;
}
z = (int) (x + y);
// if-else with return in one branch
if (x < 0)
y = 40;
else
return z;
// this is not the start of a BB due to the return
z = 10;
// single-branch if-else
if (x == 0) {
y = 60;
z = 10;
}
z += x;
// while loop
while (x > 0) {
y = 10;
x--;
}
z += y;
// for loop
for (j = 0; j < 10; j++) {
y = 0;
w = 10;
}
z += w;
// nested control flow
for (j = 0; j < 10; j++) {
y = 30;
if (z > 0)
if (y > 0) {
w = 0;
break;
} else {
w = 20;
}
else {
w = 10;
continue;
}
x = 0;
}
z += x + y + w;
// nested control-flow
w = 40;
return w;
}
int test2(int a) {
/* Some more complex flow control */
int b;
int c;
c = 0;
while(true) {
b = 10;
if (a > 100) {
c = 10;
b = c;
}
if (a == 10)
break;
if (a == 20)
return c;
}
return b;
}
} | 1,094 | 10.774194 | 52 | java |
codeql | codeql-master/java/ql/test/library-tests/controlflow/dominance/Test2.java | import java.math.*;
class MyExn extends Throwable {}
public class Test2 {
void f() throws Throwable {}
void g(boolean b) throws Throwable {
while (b) {
if (b) {
} else {
try {
f();
} catch (MyExn e) {}
;
}
}
}
void t(int x) {
if (x < 0) {
return;
}
while(x >= 0) {
if (x > 10) {
try {
BigInteger n = new BigInteger( "wrong" );
} catch ( NumberFormatException e ) { // unchecked exception
}
}
x--;
}
}
} | 479 | 13.117647 | 64 | java |
codeql | codeql-master/java/ql/test/library-tests/controlflow/paths/A.java | public class A {
public void action() { }
public void always_dom1() {
action();
}
public void always_dom2(boolean b) {
if (b) { } else { }
action();
}
public void always_path(boolean b) {
if (b) {
action();
} else {
action();
}
}
public void always_w_call(boolean b1, boolean b2) {
if (b1) {
action();
} else if (b2) {
always_dom2(b1);
} else {
always_path(b2);
}
}
public void not_always_none() {
}
public void not_always_one(boolean b) {
if (b) {
action();
}
}
public void not_always_two(boolean b1, boolean b2) {
if (b1) {
if (b2) {
action();
} else {
action();
}
}
}
}
| 736 | 13.74 | 54 | java |
codeql | codeql-master/java/ql/test/library-tests/controlflow/basic/Test.java | package dominance;
public class Test {
public void test() {
int x = 0;
long y = 50;
int z = 0;
int w = 0;
// if-else, multiple statements in block
if (x > 0) {
y = 20;
z = 10;
} else {
y = 30;
}
z = 0;
// if-else with return in one branch
if(x < 0)
y = 40;
else
return;
// this is not the start of a BB due to the return
z = 10;
// single-branch if-else
if (x == 0) {
y = 60;
z = 10;
}
z = 20;
// while loop
while(x > 0) {
y = 10;
x--;
}
z = 30;
// for loop
for(int j = 0; j < 10; j++) {
y = 0;
w = 10;
}
z = 40;
// nested control flow
for(int j = 0; j < 10; j++) {
y = 30;
if(z > 0)
if(y > 0) {
w = 0;
break;
} else {
w = 20;
}
else {
w = 10;
continue;
}
x = 0;
}
z = 50;
// nested control-flow
w = 40;
return;
}
} | 910 | 10.831169 | 52 | java |
codeql | codeql-master/java/ql/test/library-tests/types/A.java | public class A {
boolean b = new Boolean(true);
byte y = new Byte((byte)23);
char c = new Character('a');
short s = new Short((short)42);
int i = new Integer(56);
long l = new Long(72l);
double d = new Double(2.3d);
float f = new Float(4.2);
} | 251 | 24.2 | 32 | java |
codeql | codeql-master/java/ql/test/library-tests/generics/generics/A.java | package generics;
import java.util.HashMap;
import java.util.Map;
public class A<T> {
class B { }
}
class C {
A<String> f;
A<String>.B b;
Map<String, Object> m = new HashMap<String, Object>();
}
class D<V extends Number> {
D<?> d1;
D<? extends Object> d2;
D<? extends Float> d3;
D<? super Double> d4;
{ java.util.Arrays.asList(); }
} | 347 | 14.818182 | 55 | java |
codeql | codeql-master/java/ql/test/library-tests/locations/locations/F.java | public class F {
void m() throws RuntimeException {}
} | 55 | 17.666667 | 36 | java |
codeql | codeql-master/java/ql/test/library-tests/locations/locations/G.java | public class G {
{
G[] g;
Object[][] o;
}
}
| 50 | 6.285714 | 16 | java |
codeql | codeql-master/java/ql/test/library-tests/locations/locations/B.java | package locations;
// empty class, just so we have something to put into the snapshot
public class B {
}
| 107 | 14.428571 | 66 | java |
codeql | codeql-master/java/ql/test/library-tests/locations/locations/D.java | package locations;
public class D {
class Inner {}
{ new D().new Inner(); }
}
| 81 | 10.714286 | 25 | java |
codeql | codeql-master/java/ql/test/library-tests/locations/locations/A.java | package locations;
@interface TestAnnotation {
public int foo();
}
@TestAnnotation(foo=-42)
public class A {
{ int x = -23; }
{ System.out.println("Hello, " + "world!"); }
{ System.out.println("Hello" + ", " + "world!"); }
{ String s = null; }
}
| 253 | 17.142857 | 51 | java |
codeql | codeql-master/java/ql/test/library-tests/locations/locations/E.java | enum E {
First,
Second,
Third
} | 34 | 6 | 8 | java |
codeql | codeql-master/java/ql/test/library-tests/locations/locations/C.java | package locations;
import java.util.List;
public class C {
List<?> stuff;
List<? extends Number> numbers;
List<? super Double> more_numbers;
}
| 148 | 13.9 | 35 | java |
codeql | codeql-master/java/ql/test/library-tests/gwt/JSNI.java | class JSNI {
class Element {}
// this is a JSNI comment
public native void scrollTo1(Element elem) /*-{
elem.scrollIntoView(true);
}-*/;
// this is not a JSNI comment: method is not declared `native`
public void scrollTo2(Element elem) /*-{
elem.scrollIntoView(true);
}-*/ {}
// this is not a JSNI comment: comment must be part of the method definition
public native void scrollTo3(Element elem);
/*-{
elem.scrollIntoView(true);
}-*/
// this is not a JSNI comment: extra content
public native void scrollTo4(Element elem) /* hi -{
elem.scrollIntoView(true);
}-*/;
// this is not a JSNI comment: extra content
public native void scrollTo5(Element elem) /* -{
elem.scrollIntoView(true);
}- ho*/;
// this is not a JSNI comment: no closing delimiter
public native void scrollTo6(Element elem) /*-{
elem.scrollIntoView(true);
}*/;
} | 957 | 27.176471 | 80 | java |
codeql | codeql-master/java/ql/test/library-tests/properties/Test.java | public class Test { }
| 22 | 10.5 | 21 | java |
codeql | codeql-master/java/ql/test/library-tests/RelativePaths/Test.java | class Test {
public static void main(String[] args) {
// Relative paths
Runtime.getRuntime().exec("make");
Runtime.getRuntime().exec("m");
Runtime.getRuntime().exec(new String[] { "make" });
Runtime.getRuntime().exec("c:make");
Runtime.getRuntime().exec("make " + args[0]);
// Absolute paths
Runtime.getRuntime().exec("/usr/bin/make");
Runtime.getRuntime().exec("bin/make");
Runtime.getRuntime().exec("\\Program Files\\Gnu Make\\Bin\\Make.exe");
Runtime.getRuntime().exec(new String[] { "/usr/bin/make" });
Runtime.getRuntime().exec("c:\\make");
Runtime.getRuntime().exec("/usr/bin/make " + args[0]);
}
}
| 634 | 32.421053 | 72 | java |
codeql | codeql-master/java/ql/test/library-tests/modifiers/Test.java | public class Test {
enum FinalEnum { RED, GREEN, BLUE };
enum NonFinalEnum {
RED() { @Override public String toString() { return "red"; } },
GREEN,
BLUE
};
} | 166 | 19.875 | 65 | java |
codeql | codeql-master/java/ql/test/library-tests/overrides/ConstructedOverrides.java |
public class ConstructedOverrides {
{
new Sub().used("");
new Super<String>().used("");
new Super<String>().usedGeneric(1, "");
}
public <S> S indirectUse(S t) { return new Super<S>().usedGeneric(null, t); }
}
class Super<T> {
public T used(T t) { return t; }
public T unused(T t) { return t; }
public <U> U usedGeneric(U u, T t) { return u; }
public <U> U unusedGeneric(U u, T t) { return u; }
}
class Sub extends Super<String> {
@Override public String used(String s) { return s; }
@Override public String unused(String s) { return s; }
@Override public <U> U usedGeneric(U u, String t) { return u; }
}
class Sub2 extends Sub {
@Override public <V> V usedGeneric(V u, String t) { return u; }
@Override public <V> V unusedGeneric(V u, String t) { return u; }
}
| 783 | 28.037037 | 78 | java |
codeql | codeql-master/java/ql/test/library-tests/UnsafeDeserialization/Test.java | import java.io.IOException;
import java.io.ObjectInputStream;
import org.apache.commons.io.serialization.ValidatingObjectInputStream;
class Test {
public void test() throws IOException, ClassNotFoundException {
ObjectInputStream objectStream = new ObjectInputStream(null);
ObjectInputStream validating = new ValidatingObjectInputStream(null);
objectStream.readObject();
validating.readObject();
}
}
| 410 | 30.615385 | 71 | java |
codeql | codeql-master/java/ql/test/library-tests/ssa/Test.java | class Test {
int field;
int f(int param) {
field = 3;
int x = 1;
int y;
int z;
if (param > 2) {
x++;
y = ++x;
z = 3;
} else {
y = 2;
y += 4;
field = 10;
z = 4;
}
;
while (x < y) {
if (param++ > 4) {
break;
}
y -= 1;
}
;
for (int i = 0; i<10; i++) {
x += i;
}
;
return x + y;
}
} | 349 | 9.606061 | 30 | java |
codeql | codeql-master/java/ql/test/library-tests/ssa/Fields.java | class Fields {
public int[] xs;
public static int[] stat;
public Fields() { upd(); }
public void upd() {
xs = new int[1];
stat = new int[0];
}
public void f() {
int[] x = xs;
upd();
x = xs;
if (x[0] > 2)
upd();
x = this.xs;
xs = new int[2];
x = xs;
}
public void g() {
Fields f = new Fields();
int[] y = f.xs;
int[] z = xs;
int[] w = stat;
this.f();
y = f.xs;
z = xs;
w = stat;
f.f();
y = f.xs;
z = xs;
w = stat;
xs = new int[3];
y = f.xs;
z = xs;
f.xs = new int[4];
y = f.xs;
z = xs;
if (z[0] > 2)
f = new Fields();
y = f.xs;
new Fields();
y = f.xs;
z = xs;
w = stat;
}
}
| 739 | 13.509804 | 28 | java |
codeql | codeql-master/java/ql/test/library-tests/ssa/Nested.java | import java.util.*;
class Nested {
Iterable<Integer> get1(int p1) {
int x1 = 5;
return () -> new Iterator() {
public boolean hasNext() { return true; }
public Integer next() { return p1 + x1 + x1 + x1; }
};
}
interface IntGetter { int getInt(); }
void methodRef() {
Object obj = new Object();
IntGetter hash = obj::hashCode;
int x2 = 19;
IntGetter h2 = new IntGetter() {
public int getInt() {
IntGetter hnest = obj::hashCode;
return x2 + hash.getInt() + hnest.getInt();
}
};
Object obj2 = new Object();
if (h2.getInt() > 3) {
obj2 = new Object();
} else {
obj2 = new Object();
}
IntGetter hash2 = obj2::hashCode;
}
IntGetter lambda1(int p3) {
int x3;
if (p3 > 7) {
x3 = 1;
return () -> x3 + 1;
} else {
x3 = 2;
return () -> x3 + 2;
}
}
}
| 900 | 19.477273 | 57 | java |
codeql | codeql-master/java/ql/test/library-tests/ssa/TestInstanceOfPattern.java | class TestInstanceOfPattern {
private String s = "field";
void test(Object obj) {
if (obj instanceof String s) {
if (s.contains("abc")) {}
} else {
if (s.contains("def")) {}
}
}
void test2(Object obj) {
if (!(obj instanceof String s)) {
if (s.contains("abc")) {}
} else {
if (s.contains("def")) {}
}
}
void test3(Object obj) {
if (obj instanceof String s && s.length() > 5) {
if (s.contains("abc")) {}
} else {
if (s.contains("def")) {}
}
}
void test4(Object obj) {
if (obj instanceof String s || s.length() > 5) {
if (s.contains("abc")) {}
} else {
if (s.contains("def")) {}
}
}
}
| 639 | 19 | 50 | java |
codeql | codeql-master/java/ql/test/library-tests/guards/Test.java | class Test {
private int z;
void test(int x) {
z = 0;
if (x < 0) {
throw new Exception();
}
int y = 0;
while(x >= 0) {
if (z >= 0)
y++;
if (y > 10) {
z++;
y++;
z--;
} else if (y < 10) {
y--;
} else if (y == 10) {
y++;
}
x--;
}
}
void test2(int x) {
int y = 0;
if (x > 5) {
y++;
int w = (x++ < 2) ? 0 : 1;
y += x + w;
} else {
y++;
if ((x = 4) < 4)
y++;
y += x;
}
}
}
| 461 | 10.846154 | 29 | java |
codeql | codeql-master/java/ql/test/library-tests/guards/Logic.java | public class Logic {
boolean g(int i) {
return i < 2;
}
void f(int[] a, String s) {
boolean b =
((g(1)) ?
g(2) :
true);
if (b != false) {
} else {
}
int sz = a != null ? a.length : 0;
for (int i = 0; i < sz; i++) {
int e = a[i];
if (e > 2) break;
}
if (g(3))
s = "bar";
switch (s) {
case "bar":
break;
case "foo":
break;
default:
break;
}
Object o = g(4) ? null : s;
if (o instanceof String) {
}
}
void f2(int i) {
checkTrue(i > 0, "i pos");
checkFalse(g(100), "g");
if (i > 10) {
checkTrue(i > 20, "");
}
int dummy = 0;
}
private static void checkTrue(boolean b, String msg) {
if (!b) throw new Exception(msg);
}
private static void checkFalse(boolean b, String msg) {
checkTrue(!b, msg);
}
}
| 892 | 16.509804 | 57 | java |
codeql | codeql-master/java/ql/test/library-tests/GeneratedFiles/Test.java | /* Warning: Generated code, any modifications to this file will be lost. */
public class Test {
} | 97 | 31.666667 | 75 | java |
codeql | codeql-master/java/ql/test/library-tests/GeneratedFiles/HasBeenGenerated.java | // ===========================================================================
// This file has been generated by
// Typical, version 1.13.3,
// (C) 2004-2007 Robert Grimm and New York University,
// on Wednesday, February 27, 2008 at 5:11:34 PM.
// Edit at your own risk.
// ===========================================================================
class HasBeenGenerated {}
| 378 | 41.111111 | 78 | java |
codeql | codeql-master/java/ql/test/library-tests/GeneratedFiles/FollowingCodeGenerated.java | //----------------------------------------------------
// The following code was generated by CUP v0.10k TUM Edition 20050516
// Fri Nov 11 20:53:50 CET 2005
//----------------------------------------------------
class FollowingCodeGenerated {}
| 245 | 40 | 70 | java |
codeql | codeql-master/java/ql/test/library-tests/GeneratedFiles/Test2.java | // This file was auto generated by me
public class Test2 {} | 60 | 19.333333 | 37 | java |
codeql | codeql-master/java/ql/test/library-tests/GeneratedFiles/JavaCharStream.java | /* Generated By:JavaCC: Do not edit this line. JavaCharStream.java Version 4.1 */
/* JavaCCOptions:STATIC=false */
public class JavaCharStream {
}
| 148 | 23.833333 | 81 | java |
codeql | codeql-master/java/ql/test/library-tests/GeneratedFiles/Mithra.java | /**
* This file was automatically generated
*/
public class Mithra {
}
| 73 | 11.333333 | 40 | java |
codeql | codeql-master/java/ql/test/library-tests/GeneratedFiles/StandardCharsets.java | /*
* Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
// -- This file was mechanically generated: Do not edit! -- //
public class StandardCharsets
{
} | 1,317 | 40.1875 | 79 | java |
codeql | codeql-master/java/ql/test/library-tests/GeneratedFiles/JavaParserTokenManager.java | /* Generated By:JJTree&JavaCC: Do not edit this line. JavaParserTokenManager.java */
/** Token Manager. */
public class JavaParserTokenManager {
} | 147 | 28.6 | 84 | java |
codeql | codeql-master/java/ql/test/library-tests/GeneratedFiles/FacebookAutoGen.java | /**
* This class is auto-genereated. [sic]
*
* For any issues or feature requests related to this class, please let us know
* on github and we'll fix in our codegen framework. We'll not be able to accept
* pull request for this class.
*
*/
public class FacebookAutoGen {}
| 279 | 27 | 80 | java |
codeql | codeql-master/java/ql/test/library-tests/GeneratedFiles/QLParser.java | // Generated from QL.g4 by ANTLR 4.4
@SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"})
public class QLParser {
} | 133 | 25.8 | 69 | java |
codeql | codeql-master/java/ql/test/library-tests/GeneratedFiles/test/ThriftCompiler.java | /**
* Autogenerated by Thrift Compiler (0.9.3)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package test;
// The `@generated` Javadoc tag is non-standard, so we detect this
// file based on the marker comment added by the Thrift Compiler.
class ThriftCompiler {}
| 311 | 23 | 67 | java |
codeql | codeql-master/java/ql/test/library-tests/defUse/Test.java | package defUse;
public class Test {
public void ifs(long w) {
int x = 0;
long y = 50;
use(y);
use(w);
if (x > 0) {
y = 20;
use(y);
} else {
y = 30;
w = 10;
use(w);
}
use(y);
use(w);
if(x < 0) {
y = 40;
w = 20;
}
else
return;
use(y);
use(w);
if (x == 0) {
y = 60;
}
use(y);
return;
}
public static void use(long u) { return; }
} | 421 | 8.813953 | 43 | java |
codeql | codeql-master/java/ql/test/library-tests/stmts/stmts/B.java | package stmts;
public class B {
public void foo(boolean b, boolean c) {
outer:
for (int i=0; i<10; ++i) {
if (b)
break;
if (b)
continue;
while (i < 20) {
if (c)
break;
if (b && c)
break outer;
if (b)
continue;
if (c && b)
continue outer;
switch (i) {
case 23:
break;
case 42:
break outer;
case 56:
continue;
}
}
}
}
} | 417 | 12.483871 | 40 | java |
codeql | codeql-master/java/ql/test/library-tests/stmts/stmts/A.java | package stmts;
public class A {
public int foo(int x) {
switch(x) {
case 23:
return 42;
case 42:
return 23;
default:
return x;
}
}
}
| 155 | 9.4 | 24 | java |
codeql | codeql-master/java/ql/test/library-tests/fields/fields/FieldTest.java | package fields;
public class FieldTest {
float ff, g = 2.3f, hhh;
static Object obj = null, obj2;
@SuppressWarnings("rawtypes") java.util.List l, m;
}
| 176 | 21.125 | 58 | java |
codeql | codeql-master/java/ql/test/experimental/Security/CWE/CWE-327/UnsafeTlsVersion.java | import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class UnsafeTlsVersion {
public static void testSslContextWithProtocol() throws NoSuchAlgorithmException {
// unsafe
SSLContext.getInstance("SSL");
SSLContext.getInstance("SSLv2");
SSLContext.getInstance("SSLv3");
SSLContext.getInstance("TLS");
SSLContext.getInstance("TLSv1");
SSLContext.getInstance("TLSv1.1");
// safe
SSLContext.getInstance("TLSv1.2");
SSLContext.getInstance("TLSv1.3");
}
public static void testCreateSslParametersWithProtocol(String[] cipherSuites) {
// unsafe
createSslParameters(cipherSuites, "SSLv3");
createSslParameters(cipherSuites, "TLS");
createSslParameters(cipherSuites, "TLSv1");
createSslParameters(cipherSuites, "TLSv1.1");
createSslParameters(cipherSuites, "TLSv1", "TLSv1.1", "TLSv1.2");
createSslParameters(cipherSuites, "TLSv1.2");
// safe
createSslParameters(cipherSuites, "TLSv1.2");
createSslParameters(cipherSuites, "TLSv1.3");
}
public static SSLParameters createSslParameters(String[] cipherSuites, String... protocols) {
return new SSLParameters(cipherSuites, protocols);
}
public static void testSettingProtocolsForSslParameters() {
// unsafe
new SSLParameters().setProtocols(new String[] { "SSLv3" });
new SSLParameters().setProtocols(new String[] { "TLS" });
new SSLParameters().setProtocols(new String[] { "TLSv1" });
new SSLParameters().setProtocols(new String[] { "TLSv1.1" });
SSLParameters parameters = new SSLParameters();
parameters.setProtocols(new String[] { "TLSv1.1", "TLSv1.2" });
// safe
new SSLParameters().setProtocols(new String[] { "TLSv1.2" });
parameters = new SSLParameters();
parameters.setProtocols(new String[] { "TLSv1.2", "TLSv1.3" });
}
public static void testSettingProtocolForSslSocket() throws IOException {
// unsafe
createSslSocket("SSLv3");
createSslSocket("TLS");
createSslSocket("TLSv1");
createSslSocket("TLSv1.1");
createSslSocket("TLSv1.1", "TLSv1.2");
// safe
createSslSocket("TLSv1.2");
createSslSocket("TLSv1.3");
}
public static SSLSocket createSslSocket(String... protocols) throws IOException {
SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
socket.setEnabledProtocols(protocols);
return socket;
}
public static void testSettingProtocolForSslServerSocket() throws IOException {
// unsafe
createSslServerSocket("SSLv3");
createSslServerSocket("TLS");
createSslServerSocket("TLSv1");
createSslServerSocket("TLSv1.1");
createSslServerSocket("TLSv1.1", "TLSv1.2");
// safe
createSslServerSocket("TLSv1.2");
createSslServerSocket("TLSv1.3");
}
public static SSLServerSocket createSslServerSocket(String... protocols) throws IOException {
SSLServerSocket socket = (SSLServerSocket) SSLServerSocketFactory.getDefault().createServerSocket();
socket.setEnabledProtocols(protocols);
return socket;
}
public static void testSettingProtocolForSslEngine() throws NoSuchAlgorithmException {
// unsafe
createSslEngine("SSLv3");
createSslEngine("TLS");
createSslEngine("TLSv1");
createSslEngine("TLSv1.1");
createSslEngine("TLSv1.1", "TLSv1.2");
// safe
createSslEngine("TLSv1.2");
createSslEngine("TLSv1.3");
}
public static SSLEngine createSslEngine(String... protocols) throws NoSuchAlgorithmException {
SSLEngine engine = SSLContext.getDefault().createSSLEngine();
engine.setEnabledProtocols(protocols);
return engine;
}
}
| 3,907 | 30.264 | 104 | java |
codeql | codeql-master/java/ql/test/experimental/Security/CWE/CWE-094/MvelInjection.java | import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.Socket;
import java.util.HashMap;
import javax.script.CompiledScript;
import javax.script.SimpleScriptContext;
import org.mvel2.MVEL;
import org.mvel2.MVELRuntime;
import org.mvel2.ParserContext;
import org.mvel2.compiler.CompiledAccExpression;
import org.mvel2.compiler.CompiledExpression;
import org.mvel2.compiler.ExecutableStatement;
import org.mvel2.compiler.ExpressionCompiler;
import org.mvel2.integration.impl.ImmutableDefaultFactory;
import org.mvel2.jsr223.MvelCompiledScript;
import org.mvel2.jsr223.MvelScriptEngine;
import org.mvel2.templates.CompiledTemplate;
import org.mvel2.templates.TemplateCompiler;
import org.mvel2.templates.TemplateRuntime;
public class MvelInjection {
public static void testWithMvelEval(Socket socket) throws IOException {
MVEL.eval(read(socket));
}
public static void testWithMvelCompileAndExecute(Socket socket) throws IOException {
Serializable expression = MVEL.compileExpression(read(socket));
MVEL.executeExpression(expression);
}
public static void testWithExpressionCompiler(Socket socket) throws IOException {
ExpressionCompiler compiler = new ExpressionCompiler(read(socket));
ExecutableStatement statement = compiler.compile();
statement.getValue(new Object(), new ImmutableDefaultFactory());
statement.getValue(new Object(), new Object(), new ImmutableDefaultFactory());
}
public static void testWithCompiledExpressionGetDirectValue(Socket socket) throws IOException {
ExpressionCompiler compiler = new ExpressionCompiler(read(socket));
CompiledExpression expression = compiler.compile();
expression.getDirectValue(new Object(), new ImmutableDefaultFactory());
}
public static void testCompiledAccExpressionGetValue(Socket socket) throws IOException {
CompiledAccExpression expression = new CompiledAccExpression(
read(socket).toCharArray(), Object.class, new ParserContext());
expression.getValue(new Object(), new ImmutableDefaultFactory());
}
public static void testMvelScriptEngineCompileAndEvaluate(Socket socket) throws Exception {
String input = read(socket);
MvelScriptEngine engine = new MvelScriptEngine();
CompiledScript compiledScript = engine.compile(input);
compiledScript.eval();
Serializable script = engine.compiledScript(input);
engine.evaluate(script, new SimpleScriptContext());
}
public static void testMvelCompiledScriptCompileAndEvaluate(Socket socket) throws Exception {
MvelScriptEngine engine = new MvelScriptEngine();
ExpressionCompiler compiler = new ExpressionCompiler(read(socket));
ExecutableStatement statement = compiler.compile();
MvelCompiledScript script = new MvelCompiledScript(engine, statement);
script.eval(new SimpleScriptContext());
}
public static void testTemplateRuntimeEval(Socket socket) throws Exception {
TemplateRuntime.eval(read(socket), new HashMap());
}
public static void testTemplateRuntimeCompileTemplateAndExecute(Socket socket) throws Exception {
TemplateRuntime.execute(
TemplateCompiler.compileTemplate(read(socket)), new HashMap());
}
public static void testTemplateRuntimeCompileAndExecute(Socket socket) throws Exception {
TemplateCompiler compiler = new TemplateCompiler(read(socket));
TemplateRuntime.execute(compiler.compile(), new HashMap());
}
public static void testMvelRuntimeExecute(Socket socket) throws Exception {
ExpressionCompiler compiler = new ExpressionCompiler(read(socket));
CompiledExpression expression = compiler.compile();
MVELRuntime.execute(false, expression, new Object(), new ImmutableDefaultFactory());
}
public static String read(Socket socket) throws IOException {
try (InputStream is = socket.getInputStream()) {
byte[] bytes = new byte[1024];
int n = is.read(bytes);
return new String(bytes, 0, n);
}
}
}
| 3,975 | 39.161616 | 99 | java |
codeql | codeql-master/java/ql/test/experimental/Security/CWE/CWE-094/SpelInjection.java | import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.SimpleEvaluationContext;
import org.springframework.expression.spel.support.StandardEvaluationContext;
public class SpelInjection {
private static final ExpressionParser PARSER = new SpelExpressionParser();
public void testGetValue(Socket socket) throws IOException {
InputStream in = socket.getInputStream();
byte[] bytes = new byte[1024];
int n = in.read(bytes);
String input = new String(bytes, 0, n);
ExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression(input);
expression.getValue();
}
public void testGetValueWithChainedCalls(Socket socket) throws IOException {
InputStream in = socket.getInputStream();
byte[] bytes = new byte[1024];
int n = in.read(bytes);
String input = new String(bytes, 0, n);
Expression expression = new SpelExpressionParser().parseExpression(input);
expression.getValue();
}
public void testSetValueWithRootObject(Socket socket) throws IOException {
InputStream in = socket.getInputStream();
byte[] bytes = new byte[1024];
int n = in.read(bytes);
String input = new String(bytes, 0, n);
Expression expression = new SpelExpressionParser().parseExpression(input);
Object root = new Object();
Object value = new Object();
expression.setValue(root, value);
}
public void testGetValueWithStaticParser(Socket socket) throws IOException {
InputStream in = socket.getInputStream();
byte[] bytes = new byte[1024];
int n = in.read(bytes);
String input = new String(bytes, 0, n);
Expression expression = PARSER.parseExpression(input);
expression.getValue();
}
public void testGetValueType(Socket socket) throws IOException {
InputStream in = socket.getInputStream();
byte[] bytes = new byte[1024];
int n = in.read(bytes);
String input = new String(bytes, 0, n);
Expression expression = PARSER.parseExpression(input);
expression.getValueType();
}
public void testWithStandardEvaluationContext(Socket socket) throws IOException {
InputStream in = socket.getInputStream();
byte[] bytes = new byte[1024];
int n = in.read(bytes);
String input = new String(bytes, 0, n);
Expression expression = PARSER.parseExpression(input);
StandardEvaluationContext context = new StandardEvaluationContext();
expression.getValue(context);
}
public void testWithSimpleEvaluationContext(Socket socket) throws IOException {
InputStream in = socket.getInputStream();
byte[] bytes = new byte[1024];
int n = in.read(bytes);
String input = new String(bytes, 0, n);
Expression expression = PARSER.parseExpression(input);
SimpleEvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().build();
// the expression is evaluated in a limited context
expression.getValue(context);
}
}
| 3,199 | 30.683168 | 96 | java |
codeql | codeql-master/java/ql/test/experimental/Security/CWE/CWE-299/DisabledRevocationChecking.java | import java.security.KeyStore;
import java.security.cert.CertPath;
import java.security.cert.CertPathValidator;
import java.security.cert.PKIXCertPathChecker;
import java.security.cert.PKIXParameters;
import java.security.cert.PKIXRevocationChecker;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class DisabledRevocationChecking {
private boolean flag = true;
public void disableRevocationChecking() {
flag = false;
}
public void testDisabledRevocationChecking(KeyStore cacerts, CertPath certPath) throws Exception {
disableRevocationChecking();
validate(cacerts, certPath);
}
public void validate(KeyStore cacerts, CertPath certPath) throws Exception {
CertPathValidator validator = CertPathValidator.getInstance("PKIX");
PKIXParameters params = new PKIXParameters(cacerts);
params.setRevocationEnabled(flag);
validator.validate(certPath, params);
}
public void testSettingRevocationCheckerWithCollectionsSingletonList(KeyStore cacerts, CertPath certPath) throws Exception {
CertPathValidator validator = CertPathValidator.getInstance("PKIX");
PKIXParameters params = new PKIXParameters(cacerts);
params.setRevocationEnabled(false);
PKIXRevocationChecker checker = (PKIXRevocationChecker) validator.getRevocationChecker();
params.setCertPathCheckers(Collections.singletonList(checker));
validator.validate(certPath, params);
}
public void testSettingRevocationCheckerWithArraysAsList(KeyStore cacerts, CertPath certPath) throws Exception {
CertPathValidator validator = CertPathValidator.getInstance("PKIX");
PKIXParameters params = new PKIXParameters(cacerts);
params.setRevocationEnabled(false);
PKIXRevocationChecker checker = (PKIXRevocationChecker) validator.getRevocationChecker();
params.setCertPathCheckers(Arrays.asList(checker));
validator.validate(certPath, params);
}
public void testSettingRevocationCheckerWithAddingToArrayList(KeyStore cacerts, CertPath certPath) throws Exception {
CertPathValidator validator = CertPathValidator.getInstance("PKIX");
PKIXParameters params = new PKIXParameters(cacerts);
params.setRevocationEnabled(false);
PKIXRevocationChecker checker = (PKIXRevocationChecker) validator.getRevocationChecker();
List<PKIXCertPathChecker> checkers = new ArrayList<>();
checkers.add(checker);
params.setCertPathCheckers(checkers);
validator.validate(certPath, params);
}
public void testSettingRevocationCheckerWithListOf(KeyStore cacerts, CertPath certPath) throws Exception {
CertPathValidator validator = CertPathValidator.getInstance("PKIX");
PKIXParameters params = new PKIXParameters(cacerts);
params.setRevocationEnabled(false);
PKIXRevocationChecker checker = (PKIXRevocationChecker) validator.getRevocationChecker();
List<PKIXCertPathChecker> checkers = List.of(checker);
params.setCertPathCheckers(checkers);
validator.validate(certPath, params);
}
public void testAddingRevocationChecker(KeyStore cacerts, CertPath certPath) throws Exception {
CertPathValidator validator = CertPathValidator.getInstance("PKIX");
PKIXParameters params = new PKIXParameters(cacerts);
params.setRevocationEnabled(false);
PKIXRevocationChecker checker = (PKIXRevocationChecker) validator.getRevocationChecker();
params.addCertPathChecker(checker);
validator.validate(certPath, params);
}
}
| 3,486 | 42.049383 | 126 | java |
codeql | codeql-master/java/ql/test/experimental/query-tests/security/CWE-917/OgnlInjection.java | import ognl.Node;
import ognl.Ognl;
import java.util.HashMap;
import com.opensymphony.xwork2.ognl.OgnlUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class OgnlInjection {
@RequestMapping
public void testOgnlParseExpression(@RequestParam String expr) throws Exception {
Object tree = Ognl.parseExpression(expr);
Ognl.getValue(tree, new HashMap<>(), new Object());
Ognl.setValue(tree, new HashMap<>(), new Object());
Node node = (Node) tree;
node.getValue(null, new Object());
node.setValue(null, new Object(), new Object());
}
@RequestMapping
public void testOgnlCompileExpression(@RequestParam String expr) throws Exception {
Node tree = Ognl.compileExpression(null, new Object(), expr);
Ognl.getValue(tree, new HashMap<>(), new Object());
Ognl.setValue(tree, new HashMap<>(), new Object());
tree.getValue(null, new Object());
tree.setValue(null, new Object(), new Object());
}
@RequestMapping
public void testOgnlDirectlyToGetSet(@RequestParam String expr) throws Exception {
Ognl.getValue(expr, new Object());
Ognl.setValue(expr, new Object(), new Object());
}
@RequestMapping
public void testStruts(@RequestParam String expr) throws Exception {
OgnlUtil ognl = new OgnlUtil();
ognl.getValue(expr, new HashMap<>(), new Object());
ognl.setValue(expr, new HashMap<>(), new Object(), new Object());
new OgnlUtil().callMethod(expr, new HashMap<>(), new Object());
}
}
| 1,619 | 32.061224 | 85 | java |
codeql | codeql-master/java/ql/test/experimental/query-tests/security/CWE-522/InsecureBasicAuth.java | import org.apache.http.RequestLine;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.message.BasicRequestLine;
import java.net.URI;
import java.net.URL;
import java.net.HttpURLConnection;
import java.net.URLConnection;
import java.util.Base64;
public class InsecureBasicAuth {
/**
* Test basic authentication with Apache HTTP POST request using string constructor.
*/
public void testApacheHttpRequest(String username, String password) {
String host = "www.example.com";
HttpRequestBase post = new HttpPost("http://"+host+"/rest/getuser.do?uid=abcdx");
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
String authString = username + ":" + password;
byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes());
String authStringEnc = new String(authEncBytes);
post.addHeader("Authorization", "Basic " + authStringEnc);
}
/**
* Test basic authentication with Apache HTTP GET request.
*/
public void testApacheHttpRequest2(String url) throws java.io.IOException {
String urlStr = "http://www.example.com:8000/payment/retrieve";
HttpGet get = new HttpGet(urlStr);
get.setHeader("Accept", "application/json");
get.setHeader("Authorization", "Basic " + new String(Base64.getEncoder().encode("admin:test".getBytes())));
}
/**
* Test basic authentication with Apache HTTP POST request using URI create method.
*/
public void testApacheHttpRequest3(String username, String password) {
String uriStr = "http://www.example.com/rest/getuser.do?uid=abcdx";
HttpRequestBase post = new HttpPost(URI.create(uriStr));
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
String authString = username + ":" + password;
byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes());
String authStringEnc = new String(authEncBytes);
post.addHeader("Authorization", "Basic " + authStringEnc);
}
/**
* Test basic authentication with Apache HTTP POST request using the URI constructor with one argument.
*/
public void testApacheHttpRequest4(String username, String password) {
String uriStr = "http://www.example.com/rest/getuser.do?uid=abcdx";
URI uri = new URI(uriStr);
HttpRequestBase post = new HttpPost(uri);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
String authString = username + ":" + password;
byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes());
String authStringEnc = new String(authEncBytes);
post.addHeader("Authorization", "Basic " + authStringEnc);
}
/**
* Test basic authentication with Apache HTTP POST request using a URI constructor with multiple arguments.
*/
public void testApacheHttpRequest5(String username, String password) {
HttpRequestBase post = new HttpPost(new URI("http", "www.example.com", "/test", "abc=123", null));
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
String authString = username + ":" + password;
byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes());
String authStringEnc = new String(authEncBytes);
post.addHeader("Authorization", "Basic " + authStringEnc);
}
/**
* Test basic authentication with Apache HTTP `BasicHttpRequest` using string constructor.
*/
public void testApacheHttpRequest6(String username, String password) {
String uriStr = "http://www.example.com/rest/getuser.do?uid=abcdx";
BasicHttpRequest post = new BasicHttpRequest("POST", uriStr);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
String authString = username + ":" + password;
byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes());
String authStringEnc = new String(authEncBytes);
post.addHeader("Authorization", "Basic " + authStringEnc);
}
/**
* Test basic authentication with Apache HTTP `BasicHttpRequest` using `RequestLine`.
*/
public void testApacheHttpRequest7(String username, String password) {
String uriStr = "http://www.example.com/rest/getuser.do?uid=abcdx";
RequestLine requestLine = new BasicRequestLine("POST", uriStr, null);
BasicHttpRequest post = new BasicHttpRequest(requestLine);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
String authString = username + ":" + password;
byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes());
String authStringEnc = new String(authEncBytes);
post.addHeader("Authorization", "Basic " + authStringEnc);
}
/**
* Test basic authentication with Java HTTP URL connection using the `URL(String spec)` constructor.
*/
public void testHttpUrlConnection(String username, String password) {
String urlStr = "http://www.example.com/rest/getuser.do?uid=abcdx";
String authString = username + ":" + password;
String encoding = Base64.getEncoder().encodeToString(authString.getBytes("UTF-8"));
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Authorization", "Basic " + encoding);
}
/**
* Test basic authentication with Java HTTP URL connection using the `URL(String protocol, String host, String file)` constructor.
*/
public void testHttpUrlConnection2(String username, String password) {
String host = "www.example.com";
String path = "/rest/getuser.do?uid=abcdx";
String protocol = "http";
String authString = username + ":" + password;
String encoding = Base64.getEncoder().encodeToString(authString.getBytes("UTF-8"));
URL url = new URL(protocol, host, path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Authorization", "Basic " + encoding);
}
/**
* Test basic authentication with Java HTTP URL connection using a constructor with private URL.
*/
public void testHttpUrlConnection3(String username, String password) {
String host = "LOCALHOST";
String authString = username + ":" + password;
String encoding = Base64.getEncoder().encodeToString(authString.getBytes("UTF-8"));
HttpURLConnection conn = (HttpURLConnection) new URL("http://"+(((host+"/rest/getuser.do")+"?uid=abcdx"))).openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Authorization", "Basic " + encoding);
}
} | 6,734 | 40.067073 | 131 | java |
codeql | codeql-master/java/ql/test/experimental/query-tests/security/CWE-074/JndiInjection.java | import java.io.IOException;
import java.util.Hashtable;
import java.util.Properties;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.naming.CompositeName;
import javax.naming.CompoundName;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.ldap.InitialLdapContext;
import org.springframework.jndi.JndiTemplate;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.ContextMapper;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.NameClassPairCallbackHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class JndiInjection {
@RequestMapping
public void testInitialContextBad1(@RequestParam String nameStr) throws NamingException {
Name name = new CompositeName(nameStr);
InitialContext ctx = new InitialContext();
ctx.lookup(nameStr);
ctx.lookupLink(nameStr);
InitialContext.doLookup(nameStr);
ctx.rename(nameStr, "");
ctx.list(nameStr);
ctx.listBindings(nameStr);
ctx.lookup(name);
ctx.lookupLink(name);
InitialContext.doLookup(name);
ctx.rename(name, null);
ctx.list(name);
ctx.listBindings(name);
}
@RequestMapping
public void testInitialDirContextBad1(@RequestParam String nameStr) throws NamingException {
Name name = new CompoundName(nameStr, new Properties());
InitialDirContext ctx = new InitialDirContext();
ctx.lookup(nameStr);
ctx.lookupLink(nameStr);
ctx.rename(nameStr, "");
ctx.list(nameStr);
ctx.listBindings(nameStr);
ctx.lookup(name);
ctx.lookupLink(name);
ctx.rename(name, null);
ctx.list(name);
ctx.listBindings(name);
}
@RequestMapping
public void testInitialLdapContextBad1(@RequestParam String nameStr) throws NamingException {
Name name = new CompositeName(nameStr);
InitialLdapContext ctx = new InitialLdapContext();
ctx.lookup(nameStr);
ctx.lookupLink(nameStr);
ctx.rename(nameStr, "");
ctx.list(nameStr);
ctx.listBindings(nameStr);
ctx.lookup(name);
ctx.lookupLink(name);
ctx.rename(name, null);
ctx.list(name);
ctx.listBindings(name);
}
@RequestMapping
public void testSpringJndiTemplateBad1(@RequestParam String nameStr) throws NamingException {
JndiTemplate ctx = new JndiTemplate();
ctx.lookup(nameStr);
ctx.lookup(nameStr, null);
}
@RequestMapping
public void testSpringLdapTemplateBad1(@RequestParam String nameStr) throws NamingException {
LdapTemplate ctx = new LdapTemplate();
Name name = new CompositeName(nameStr);
ctx.lookup(nameStr);
ctx.lookupContext(nameStr);
ctx.findByDn(name, null);
ctx.rename(name, null);
ctx.list(name);
ctx.listBindings(name);
ctx.unbind(nameStr, true);
ctx.search(nameStr, "", 0, true, null);
ctx.search(nameStr, "", 0, new String[] {}, (ContextMapper<Object>) new Object());
ctx.search(nameStr, "", 0, (ContextMapper<Object>) new Object());
ctx.search(nameStr, "", (ContextMapper) new Object());
ctx.searchForObject(nameStr, "", (ContextMapper) new Object());
}
@RequestMapping
public void testShiroJndiTemplateBad1(@RequestParam String nameStr) throws NamingException {
org.apache.shiro.jndi.JndiTemplate ctx = new org.apache.shiro.jndi.JndiTemplate();
ctx.lookup(nameStr);
ctx.lookup(nameStr, null);
}
@RequestMapping
public void testJMXServiceUrlBad1(@RequestParam String urlStr) throws IOException {
JMXConnectorFactory.connect(new JMXServiceURL(urlStr));
JMXServiceURL url = new JMXServiceURL(urlStr);
JMXConnector connector = JMXConnectorFactory.newJMXConnector(url, null);
connector.connect();
}
@RequestMapping
public void testEnvBad1(@RequestParam String urlStr) throws NamingException {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
env.put(Context.PROVIDER_URL, urlStr);
new InitialContext(env);
}
@RequestMapping
public void testEnvBad2(@RequestParam String urlStr) throws NamingException {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
env.put("java.naming.provider.url", urlStr);
new InitialDirContext(env);
}
@RequestMapping
public void testSpringJndiTemplatePropertiesBad1(@RequestParam String urlStr) throws NamingException {
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
props.put(Context.PROVIDER_URL, urlStr);
new JndiTemplate(props);
}
@RequestMapping
public void testSpringJndiTemplatePropertiesBad2(@RequestParam String urlStr) throws NamingException {
Properties props = new Properties();
props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
props.setProperty("java.naming.provider.url", urlStr);
new JndiTemplate(props);
}
@RequestMapping
public void testSpringJndiTemplatePropertiesBad3(@RequestParam String urlStr) throws NamingException {
Properties props = new Properties();
props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
props.setProperty("java.naming.provider.url", urlStr);
JndiTemplate template = new JndiTemplate();
template.setEnvironment(props);
}
@RequestMapping
public void testSpringLdapTemplateOk1(@RequestParam String nameStr) throws NamingException {
LdapTemplate ctx = new LdapTemplate();
ctx.unbind(nameStr);
ctx.unbind(nameStr, false);
ctx.search(nameStr, "", 0, false, null);
ctx.search(nameStr, "", new SearchControls(), (NameClassPairCallbackHandler) new Object());
ctx.search(nameStr, "", new SearchControls(), (NameClassPairCallbackHandler) new Object(), null);
ctx.search(nameStr, "", (NameClassPairCallbackHandler) new Object());
ctx.search(nameStr, "", 0, new String[] {}, (AttributesMapper<Object>) new Object());
ctx.search(nameStr, "", 0, (AttributesMapper<Object>) new Object());
ctx.search(nameStr, "", (AttributesMapper) new Object());
ctx.search(nameStr, "", new SearchControls(), (ContextMapper) new Object());
ctx.search(nameStr, "", new SearchControls(), (AttributesMapper) new Object());
ctx.search(nameStr, "", new SearchControls(), (ContextMapper) new Object(), null);
ctx.search(nameStr, "", new SearchControls(), (AttributesMapper) new Object(), null);
ctx.searchForObject(nameStr, "", new SearchControls(), (ContextMapper) new Object());
}
@RequestMapping
public void testEnvOk1(@RequestParam String urlStr) throws NamingException {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
env.put(Context.SECURITY_PRINCIPAL, urlStr);
new InitialContext(env);
}
@RequestMapping
public void testEnvOk2(@RequestParam String urlStr) throws NamingException {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
env.put("java.naming.security.principal", urlStr);
new InitialContext(env);
}
}
| 7,828 | 36.280952 | 107 | java |
codeql | codeql-master/java/ql/test/experimental/query-tests/security/CWE-273/UnsafeCertTrustTest.java | import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.net.Socket;
import javax.net.SocketFactory;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
//import com.rabbitmq.client.ConnectionFactory;
public class UnsafeCertTrustTest {
/**
* Test the implementation of trusting all server certs as a variable
*/
public SSLSocketFactory testTrustAllCertManager() {
try {
final SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[] { TRUST_ALL_CERTIFICATES }, null);
final SSLSocketFactory socketFactory = context.getSocketFactory();
return socketFactory;
} catch (final Exception x) {
throw new RuntimeException(x);
}
}
/**
* Test the implementation of trusting all server certs as an anonymous class
*/
public SSLSocketFactory testTrustAllCertManagerOfVariable() {
try {
SSLContext context = SSLContext.getInstance("TLS");
TrustManager[] serverTMs = new TrustManager[] { new X509TrustAllManager() };
context.init(null, serverTMs, null);
final SSLSocketFactory socketFactory = context.getSocketFactory();
return socketFactory;
} catch (final Exception x) {
throw new RuntimeException(x);
}
}
/**
* Test the implementation of trusting all hostnames as an anonymous class
*/
public void testTrustAllHostnameOfAnonymousClass() {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true; // Noncompliant
}
});
}
/**
* Test the implementation of trusting all hostnames as a variable
*/
public void testTrustAllHostnameOfVariable() {
HostnameVerifier verifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true; // Noncompliant
}
};
HttpsURLConnection.setDefaultHostnameVerifier(verifier);
}
private static final X509TrustManager TRUST_ALL_CERTIFICATES = new X509TrustManager() {
@Override
public void checkClientTrusted(final X509Certificate[] chain, final String authType)
throws CertificateException {
}
@Override
public void checkServerTrusted(final X509Certificate[] chain, final String authType)
throws CertificateException {
// Noncompliant
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null; // Noncompliant
}
};
private class X509TrustAllManager implements X509TrustManager {
@Override
public void checkClientTrusted(final X509Certificate[] chain, final String authType)
throws CertificateException {
}
@Override
public void checkServerTrusted(final X509Certificate[] chain, final String authType)
throws CertificateException {
// Noncompliant
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null; // Noncompliant
}
};
public static final HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true; // Noncompliant
}
};
/**
* Test the endpoint identification of SSL engine is set to null
*/
public void testSSLEngineEndpointIdSetNull() {
SSLContext sslContext = SSLContext.getInstance("TLS");
SSLEngine sslEngine = sslContext.createSSLEngine();
SSLParameters sslParameters = sslEngine.getSSLParameters();
sslParameters.setEndpointIdentificationAlgorithm(null);
sslEngine.setSSLParameters(sslParameters);
}
/**
* Test the endpoint identification of SSL engine is not set
*/
public void testSSLEngineEndpointIdNotSet() {
SSLContext sslContext = SSLContext.getInstance("TLS");
SSLEngine sslEngine = sslContext.createSSLEngine();
}
/**
* Test the endpoint identification of SSL socket is not set
*/
public void testSSLSocketEndpointIdNotSet() {
SSLContext sslContext = SSLContext.getInstance("TLS");
final SSLSocketFactory socketFactory = sslContext.getSocketFactory();
SSLSocket socket = (SSLSocket) socketFactory.createSocket("www.example.com", 443);
}
/**
* Test the endpoint identification of regular socket is not set
*/
public void testSocketEndpointIdNotSet() {
SocketFactory socketFactory = SocketFactory.getDefault();
Socket socket = socketFactory.createSocket("www.example.com", 80);
}
// /**
// * Test the enableHostnameVerification of RabbitMQConnectionFactory is not set
// */
// public void testEnableHostnameVerificationOfRabbitMQFactoryNotSet() {
// ConnectionFactory connectionFactory = new ConnectionFactory();
// connectionFactory.useSslProtocol();
// }
} | 4,920 | 29.376543 | 92 | java |
codeql | codeql-master/java/ql/test/experimental/query-tests/security/CWE-297/InsecureJavaMail.java | import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.SimpleEmail;
import java.util.Properties;
class InsecureJavaMail {
public void testJavaMail() {
final Properties properties = new Properties();
properties.put("mail.transport.protocol", "protocol");
properties.put("mail.smtp.host", "hostname");
properties.put("mail.smtp.socketFactory.class", "classname");
final javax.mail.Authenticator authenticator = new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
};
if (null != authenticator) {
properties.put("mail.smtp.auth", "true");
// properties.put("mail.smtp.ssl.checkserveridentity", "true");
}
final Session session = Session.getInstance(properties, authenticator);
}
public void testSimpleMail() {
Email email = new SimpleEmail();
email.setHostName("config.hostName");
email.setSmtpPort(25);
email.setAuthenticator(new DefaultAuthenticator("config.username", "config.password"));
email.setSSLOnConnect(true);
// email.setSSLCheckServerIdentity(true);
email.setFrom("fromAddress");
email.setSubject("subject");
email.setMsg("body");
email.addTo("toAddress");
email.send();
}
} | 1,452 | 31.288889 | 89 | java |
codeql | codeql-master/java/ql/test/experimental/query-tests/security/CWE-016/SpringBootActuators.java | import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
public class SpringBootActuators {
protected void configure(HttpSecurity http) throws Exception {
http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests(requests -> requests.anyRequest().permitAll());
}
protected void configure2(HttpSecurity http) throws Exception {
http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests().requestMatchers(EndpointRequest.toAnyEndpoint()).permitAll();
}
protected void configure3(HttpSecurity http) throws Exception {
http.requestMatchers(matcher -> EndpointRequest.toAnyEndpoint()).authorizeRequests().requestMatchers(EndpointRequest.toAnyEndpoint()).permitAll();
}
protected void configure4(HttpSecurity http) throws Exception {
http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests().anyRequest().permitAll();
}
protected void configure5(HttpSecurity http) throws Exception {
http.authorizeRequests().requestMatchers(EndpointRequest.toAnyEndpoint()).permitAll();
}
protected void configure6(HttpSecurity http) throws Exception {
http.authorizeRequests(requests -> requests.requestMatchers(EndpointRequest.toAnyEndpoint()).permitAll());
}
protected void configure7(HttpSecurity http) throws Exception {
http.requestMatchers(matcher -> EndpointRequest.toAnyEndpoint()).authorizeRequests().anyRequest().permitAll();
}
protected void configureOk1(HttpSecurity http) throws Exception {
http.requestMatcher(EndpointRequest.toAnyEndpoint());
}
protected void configureOk2(HttpSecurity http) throws Exception {
http.requestMatchers().requestMatchers(EndpointRequest.toAnyEndpoint());
}
protected void configureOk3(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().permitAll();
}
protected void configureOk4(HttpSecurity http) throws Exception {
http.authorizeRequests(authz -> authz.anyRequest().permitAll());
}
protected void configureOkSafeEndpoints1(HttpSecurity http) throws Exception {
http.requestMatcher(EndpointRequest.to("health", "info")).authorizeRequests(requests -> requests.anyRequest().permitAll());
}
protected void configureOkSafeEndpoints2(HttpSecurity http) throws Exception {
http.requestMatcher(EndpointRequest.to("health")).authorizeRequests().requestMatchers(EndpointRequest.to("health")).permitAll();
}
protected void configureOkSafeEndpoints3(HttpSecurity http) throws Exception {
http.requestMatchers(matcher -> EndpointRequest.to("health", "info")).authorizeRequests().requestMatchers(EndpointRequest.to("health", "info")).permitAll();
}
protected void configureOkSafeEndpoints4(HttpSecurity http) throws Exception {
http.requestMatcher(EndpointRequest.to("health", "info")).authorizeRequests().anyRequest().permitAll();
}
protected void configureOkSafeEndpoints5(HttpSecurity http) throws Exception {
http.authorizeRequests().requestMatchers(EndpointRequest.to("health", "info")).permitAll();
}
protected void configureOkSafeEndpoints6(HttpSecurity http) throws Exception {
http.authorizeRequests(requests -> requests.requestMatchers(EndpointRequest.to("health", "info")).permitAll());
}
protected void configureOkSafeEndpoints7(HttpSecurity http) throws Exception {
http.requestMatchers(matcher -> EndpointRequest.to("health", "info")).authorizeRequests().anyRequest().permitAll();
}
protected void configureOkNoPermitAll1(HttpSecurity http) throws Exception {
http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests(requests -> requests.anyRequest());
}
protected void configureOkNoPermitAll2(HttpSecurity http) throws Exception {
http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests().requestMatchers(EndpointRequest.toAnyEndpoint());
}
protected void configureOkNoPermitAll3(HttpSecurity http) throws Exception {
http.requestMatchers(matcher -> EndpointRequest.toAnyEndpoint()).authorizeRequests().requestMatchers(EndpointRequest.toAnyEndpoint());
}
protected void configureOkNoPermitAll4(HttpSecurity http) throws Exception {
http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests().anyRequest();
}
protected void configureOkNoPermitAll5(HttpSecurity http) throws Exception {
http.authorizeRequests().requestMatchers(EndpointRequest.toAnyEndpoint());
}
protected void configureOkNoPermitAll6(HttpSecurity http) throws Exception {
http.authorizeRequests(requests -> requests.requestMatchers(EndpointRequest.toAnyEndpoint()));
}
protected void configureOkNoPermitAll7(HttpSecurity http) throws Exception {
http.requestMatchers(matcher -> EndpointRequest.toAnyEndpoint()).authorizeRequests().anyRequest();
}
}
| 4,887 | 45.552381 | 160 | java |
codeql | codeql-master/java/ql/test/experimental/stubs/shiro-core-1.5.2/org/apache/shiro/jndi/JndiTemplate.java | package org.apache.shiro.jndi;
import javax.naming.NamingException;
public class JndiTemplate {
public Object lookup(final String name) throws NamingException {
return new Object();
}
public Object lookup(String name, Class requiredType) throws NamingException {
return new Object();
}
} | 308 | 22.769231 | 80 | java |
codeql | codeql-master/java/ql/test/experimental/stubs/ognl-3.2.14/ognl/OgnlException.java | package ognl;
public class OgnlException extends Exception {} | 62 | 20 | 47 | java |
codeql | codeql-master/java/ql/test/experimental/stubs/ognl-3.2.14/ognl/Node.java | package ognl;
public interface Node extends JavaSource {
public Object getValue(OgnlContext context, Object source) throws OgnlException;
public void setValue(OgnlContext context, Object target, Object value) throws OgnlException;
}
| 238 | 33.142857 | 94 | java |
codeql | codeql-master/java/ql/test/experimental/stubs/ognl-3.2.14/ognl/OgnlContext.java | package ognl;
import java.util.*;
public class OgnlContext extends Object implements Map {
@Override
public int size() {
return 0;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public boolean containsKey(Object key) {
return true;
}
@Override
public boolean containsValue(Object value) {
return true;
}
@Override
public Object get(Object key) {
return new Object();
}
@Override
public Object put(Object key, Object value) {
return new Object();
}
@Override
public Object remove(Object key) {
return new Object();
}
@Override
public void putAll(Map t) { }
@Override
public void clear() {}
@Override
public Set keySet() {
return new HashSet();
}
@Override
public Collection values() {
return new HashSet();
}
@Override
public Set entrySet() {
return new HashSet();
}
@Override
public boolean equals(Object o) {
return true;
}
@Override
public int hashCode() {
return 0;
}
} | 1,041 | 13.676056 | 56 | java |
codeql | codeql-master/java/ql/test/experimental/stubs/ognl-3.2.14/ognl/Ognl.java | package ognl;
import java.util.*;
public abstract class Ognl {
public static Object parseExpression(String expression) throws OgnlException {
return new Object();
}
public static Object getValue(Object tree, Map context, Object root) throws OgnlException {
return new Object();
}
public static void setValue(Object tree, Object root, Object value) throws OgnlException {}
public static Node compileExpression(OgnlContext context, Object root, String expression)
throws Exception {
return null;
}
public static Object getValue(String expression, Object root) throws OgnlException {
return new Object();
}
public static void setValue(String expression, Object root, Object value) throws OgnlException {}
}
| 759 | 27.148148 | 99 | java |
codeql | codeql-master/java/ql/test/experimental/stubs/ognl-3.2.14/ognl/JavaSource.java | package ognl;
public interface JavaSource {}
| 46 | 10.75 | 30 | java |
codeql | codeql-master/java/ql/test/experimental/stubs/struts2-core-2.5.22/com/opensymphony/xwork2/ognl/OgnlUtil.java | package com.opensymphony.xwork2.ognl;
import java.util.*;
import ognl.OgnlException;
public class OgnlUtil {
public Object getValue(final String name, final Map<String, Object> context, final Object root) throws OgnlException {
return new Object();
}
public void setValue(final String name, final Map<String, Object> context, final Object root, final Object value) throws OgnlException {}
public Object callMethod(final String name, final Map<String, Object> context, final Object root) throws OgnlException {
return new Object();
}
} | 556 | 33.8125 | 139 | java |
codeql | codeql-master/java/ql/test/query-tests/definitions/Test.java | class Test implements Func {
public boolean test() { return false; }
public static void test2(Func func) {
}
{
test2(this::test);
}
}
interface Func {
public boolean test();
}
class Test2 {
{
new Test().test2(() -> {
Func f = () -> false;
return false;
});
}
}
class Test3 {
public abstract class SourceType2 {}
public abstract class SourceType<T, U> {}
private final java.util.concurrent.ConcurrentHashMap<String, Test3.SourceType<SourceType2, byte[]>> cache =
new java.util.concurrent.ConcurrentHashMap<>();
{
cache.computeIfAbsent(
null,
dummy-> {
return null;
});
}
}
| 757 | 20.055556 | 111 | java |
codeql | codeql-master/java/ql/test/query-tests/Naming/NamingTest.java | import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class NamingTest {
public boolean equals(Object other) { return false; }
public boolean equals(NamingTest other) { return true; }
public void visit(Object node) {}
public void visit(NamingTest t) {}
public class Elem<T> {}
public Object get(List<Elem<String>> lll) {
Predicate<?> p = null;
p.test(null);
return lll.stream().map(l -> l).filter(Objects::nonNull).collect(Collectors.toList());
}
}
| 495 | 23.8 | 88 | java |
codeql | codeql-master/java/ql/test/query-tests/Nullness/F.java | public class F {
public void m1(Object obj) {
if (obj == null)
throwMyException();
obj.hashCode(); // OK
}
public void m2(Object obj) {
if (obj == null)
doStuff();
obj.hashCode(); // NPE
}
public void m3(Object obj) {
if (obj == null)
doStuffOrThrow(0);
obj.hashCode(); // NPE
}
public static class MyException extends RuntimeException {
}
public void throwMyException() { // meant to always throw
throw new MyException();
}
public void doStuff() { // meant to be overridden as indicated by UnsupportedOperationException
throw new UnsupportedOperationException();
}
public void doStuffOrThrow(int i) { // meant to be overridden as indicated by unused parameter
throw new MyException();
}
}
| 778 | 21.257143 | 97 | java |
codeql | codeql-master/java/ql/test/query-tests/Nullness/B.java | public class B {
private boolean maybe;
public final boolean flag;
public B(boolean b, boolean f) {
this.maybe = b;
this.flag = f;
}
public void caller() {
callee1(new Object());
callee1(null);
callee2(new Object());
}
public void callee1(Object param) {
param.toString(); // NPE
}
public void callee2(Object param) {
if (param != null) {
param.toString(); // OK
}
param.toString(); // NPE
}
private static boolean customIsNull(Object x) {
if (x instanceof String) return false;
if (x == null) return true;
return x == null;
}
public void nullGuards() {
Object o1 = maybe ? null : new Object();
if (o1 != null) o1.hashCode(); // OK
Object o2 = maybe ? null : "";
if (o2 instanceof String) o2.hashCode(); // OK
Object o3 = null;
if ((o3 = maybe ? null : "") != null) o3.hashCode(); // OK
Object o4 = maybe ? null : "";
if ((2 > 1 && o4 != null) != false) o4.hashCode(); // OK
Object o5 = (o4 != null) ? "" : null;
if (o5 != null) o4.hashCode(); // OK
if (o4 != null) o5.hashCode(); // OK
Object o6 = maybe ? null : "";
if (!customIsNull(o6)) o6.hashCode(); // OK
Object o7 = maybe ? null : "";
boolean ok = o7 != null && 2 > 1;
if (ok)
o7.hashCode(); // OK
else
o7.hashCode(); // NPE
Object o8 = maybe ? null : "";
int track = o8 == null ? 42 : 1+1;
if (track == 2) o8.hashCode(); // OK
if (track != 42) o8.hashCode(); // OK
if (track < 42) o8.hashCode(); // OK
if (track <= 41) o8.hashCode(); // OK
}
public void deref() {
int[] xs = maybe ? null : new int[2];
if (2 > 1) xs[0] = 5; // NPE
if (2 > 1) maybe = xs[1] > 5; // NPE
if (2 > 1) {
int l = xs.length; // NPE
}
if (2 > 1) {
for (int i : xs) { } // NPE
}
if (2 > 1) {
synchronized(xs) { // NPE
xs.hashCode(); // Not reported - same basic block
}
}
if (4 > 3) {
assert xs != null;
xs[0] = xs[1]; // OK
}
}
public void f(boolean b) {
String x = b ? null : "abc";
x = x == null ? "" : x;
if (x == null)
x.hashCode(); // OK - dead
else
x.hashCode(); // OK
}
public void lengthGuard(int[] a, int[] b) {
int alen = a == null ? 0 : a.length; // OK
int blen = b == null ? 0 : b.length; // OK
int sum = 0;
if (alen == blen) {
for(int i = 0; i < alen; i++) {
sum += a[i]; // OK
sum += b[i]; // OK
}
}
int alen2;
if (a != null)
alen2 = a.length; // OK
else
alen2 = 0;
for(int i = 1; i <= alen2; ++i) {
sum += a[i-1]; // OK
}
}
public void missedGuard(Object obj) {
obj.hashCode(); // NPE
int x = obj != null ? 1 : 0;
}
private Object mkMaybe() {
if (maybe) throw new RuntimeException();
return new Object();
}
public void exceptions() {
Object obj = null;
try {
obj = mkMaybe();
} catch(Exception e) {
}
obj.hashCode(); // NPE
Object obj2 = null;
try {
obj2 = mkMaybe();
} catch(Exception e) {
assert false;
}
obj2.hashCode(); // OK
Object obj3 = null;
try {
obj3 = mkMaybe();
} finally {
//cleanup
}
obj3.hashCode(); // OK
}
public void clearNotNull() {
Object o = new Object();
if (o == null) o.hashCode(); // OK
o.hashCode(); // OK
try {
mkMaybe();
} catch(Exception e) {
if (e == null) e.hashCode(); // OK
e.hashCode(); // OK
}
Object n = null;
Object o2 = n == null ? new Object() : n;
o2.hashCode(); // OK
Object o3 = "abc";
if (o3 == null) o3.hashCode(); // OK
o3.hashCode(); // OK
Object o4 = "" + null;
if (o4 == null) o4.hashCode(); // OK
o4.hashCode(); // OK
}
public void correlatedConditions(boolean cond, int num) {
Object o = null;
if (cond) o = new Object();
if (cond) o.hashCode(); // OK
o = null;
if (flag) o = "";
if (flag) o.hashCode(); // OK
o = null;
Object other = maybe ? null : "";
if (other == null) o = "";
if (other != null)
o.hashCode(); // NPE
else
o.hashCode(); // OK
Object o2 = (num < 0) ? null : "";
if (num < 0)
o2 = "";
else
o2.hashCode(); // OK
}
public void trackingVariable(int[] a) {
Object o = null;
Object other = null;
if (maybe) {
o = "abc";
other = "def";
}
if (other instanceof String) o.hashCode(); // OK
o = null;
int count = 0;
boolean found = false;
for (int i = 0; i < a.length; i++) {
if (a[i] == 42) {
o = ((Integer)a[i]).toString();
count++;
if (2 > 1) { }
found = true;
}
if (a[i] > 10000) {
o = null;
count = 0;
if (2 > 1) { }
found = false;
}
}
if (count > 3) o.hashCode(); // OK
if (found) o.hashCode(); // OK
Object prev = null;
for (int i = 0; i < a.length; ++i) {
if (i != 0) prev.hashCode(); // OK
prev = a[i];
}
String s = null;
if (2 > 1) {
boolean s_null = true;
for (int i : a) {
s_null = false;
s = "" + a;
}
if (!s_null) s.hashCode(); // OK
}
Object r = null;
MyStatus stat = MyStatus.INIT;
while (stat == MyStatus.INIT && stat != MyStatus.READY) {
r = mkMaybe();
if (2 > 1)
stat = MyStatus.READY;
}
r.hashCode(); // OK
}
public enum MyStatus {
READY,
INIT
}
public void g(Object obj) {
String msg = null;
if(obj == null)
msg = "foo";
else if(obj.hashCode() > 7) { // OK
msg = "bar";
}
if(msg != null) {
msg += "foobar";
throw new RuntimeException(msg);
}
obj.hashCode(); // OK
}
public void loopCorr(int iters) {
int[] a = null;
if (iters > 0) a = new int[iters];
for (int i = 0; i < iters; ++i)
a[i] = 0; // NPE - false positive
if (iters > 0) {
String last = null;
for (int i = 0; i < iters; i++) last = "abc";
last.hashCode(); // OK
}
int[] b = maybe ? null : new int[iters];
if (iters > 0 && (b == null || b.length < iters)) {
throw new RuntimeException();
}
for (int i = 0; i < iters; ++i) {
b[i] = 0; // NPE - false positive
}
}
void test(Exception e, boolean b) {
Exception ioe = null;
if (b) {
ioe = new Exception("");
}
if (ioe != null) {
ioe = e;
} else {
ioe.getMessage(); // NPE; always
}
}
public void lengthGuard2(int[] a, int[] b) {
int alen = a == null ? 0 : a.length; // OK
int sum = 0;
int i;
for(i = 0; i < alen; i++) {
sum += a[i]; // OK
}
int blen = b == null ? 0 : b.length; // OK
for(i = 0; i < blen; i++) {
sum += b[i]; // OK
}
i = -3;
}
public void corrConds2(Object x, Object y) {
if ((x != null && y == null) || (x == null && y != null)) return;
if (x != null) y.hashCode(); // OK
if (y != null) x.hashCode(); // OK
}
public void corrConds3(Object y) {
Object x = null;
if(y instanceof String) {
x = new Object();
}
if(y instanceof String) {
x.hashCode(); // OK
}
}
public void corrConds4(Object y) {
Object x = null;
if(!(y instanceof String)) {
x = new Object();
}
if(!(y instanceof String)) {
x.hashCode(); // OK
}
}
public void corrConds5(Object y, Object z) {
Object x = null;
if(y == z) {
x = new Object();
}
if(y == z) {
x.hashCode(); // OK
}
Object x2 = null;
if(y != z) {
x2 = new Object();
}
if(y != z) {
x2.hashCode(); // OK
}
Object x3 = null;
if(y != z) {
x3 = new Object();
}
if(!(y == z)) {
x3.hashCode(); // OK
}
}
}
| 7,908 | 20.090667 | 69 | java |
codeql | codeql-master/java/ql/test/query-tests/Nullness/D.java | import java.util.*;
public class D {
public static List<Object> p;
void init() {
List<Object> l = new ArrayList<Object>();
p = l;
}
void f() {
int n = p == null ? 0 : p.size();
for (int i = 0; i < n; i++) {
Object o = p.get(i); // OK
}
}
public static class MyList<T> extends ArrayList<T> {
@Override
public int size() {
p = new ArrayList<Object>();
return super.size();
}
}
}
| 445 | 16.153846 | 54 | java |
codeql | codeql-master/java/ql/test/query-tests/Nullness/A.java | import java.util.Iterator;
import java.util.List;
import static org.junit.Assert.*;
import static org.hamcrest.core.IsNull.*;
import static org.hamcrest.MatcherAssert.*;
public class A {
public void notTest() {
Object not_ok = null;
if (!(!(!(not_ok == null)))) {
not_ok.hashCode();
}
Object not = null;
if (!(not != null)) {
not.hashCode();
}
}
public void assertNull(Object o) {
if (o != null)
throw new RuntimeException("assert failed");
}
private static boolean isNull(Object o) {
return o == null;
}
private static boolean isNotNull(Object o) {
return o != null;
}
public void assertNonNull(Object o, String msg) {
if (o == null)
throw new RuntimeException("assert failed: " + msg);
}
public void assertNotNullTest() {
Object assertNotNull_ok1 = maybe() ? null : new Object();
assertNotNull(assertNotNull_ok1);
assertNotNull_ok1.toString();
Object assertNotNull_ok2 = maybe() ? null : new Object();
assertNotNull("", assertNotNull_ok2);
assertNotNull_ok2.toString();
Object assertNotNull_ok3 = maybe() ? null : new Object();
assertNonNull(assertNotNull_ok3, "");
assertNotNull_ok3.toString();
}
public void assertTrueTest() {
String assertTrue = "";
assertTrue(assertTrue == null);
assertTrue.toString();
String assertTrue_ok = maybe() ? null : "";
assertTrue(assertTrue_ok != null);
assertTrue_ok.toString();
}
public void assertFalseTest() {
String assertFalse = "";
assertFalse(assertFalse != null);
assertFalse.toString();
String assertFalse_ok = maybe() ? null : "";
assertFalse(assertFalse_ok == null);
assertFalse_ok.toString();
}
public void assertNullTest() {
String assertNull = "";
assertNull(assertNull);
assertNull.toString();
}
public void testNull() {
String testNull_ok1 = null;
if (isNotNull(testNull_ok1)) {
testNull_ok1.toString();
}
String testNull_ok2 = null;
if (!isNull(testNull_ok2)) {
testNull_ok2.toString();
}
}
public void instanceOf() {
Object instanceof_ok = null;
if (instanceof_ok instanceof String) {
instanceof_ok.hashCode();
}
}
public void synchronised() {
Object synchronized_always = null;
synchronized(synchronized_always) {
synchronized_always.hashCode();
}
}
public void loop1(List<Integer> list){
for (Integer loop1_ok : list) {
loop1_ok.toString();
loop1_ok = null;
}
}
public void loop2(Iterator<Integer> iter){
for (Integer loop2_ok = 0; iter.hasNext(); loop2_ok = iter.next()) {
loop2_ok.toString();
loop2_ok = null;
}
}
public void conditional(){
String colours = null;
String colour = (((colours == null)) || colours.isEmpty()) ? "Black" : colours.toString();
}
public void simple() {
String[] children = null;
String comparator = "";
if (children == null) {
children = new String[0];
}
if (children.length > 1) { }
}
public void assignIf() {
String xx;
String ok = null;
if ((ok = (xx = null)) == null || ok.isEmpty()) {
}
}
public void assignIf2() {
String ok2 = null;
if (foo(ok2 = "hello") || ok2.isEmpty()) {
}
}
public void assignIfAnd() {
String xx;
String ok3 = null;
if ((xx = (ok3 = null)) != null && ok3.isEmpty() ) {
}
}
public boolean foo(String o) { return false; }
public void dowhile() {
String do_ok = "";
do {
System.out.println(do_ok.length());
do_ok = null;
} while((do_ok != null));
String do_always = null;
do {
System.out.println(do_always.length());
do_always = null;
} while(do_always != null);
String do_maybe1 = null;
do {
System.out.println(do_maybe1.length());
} while(do_maybe1 != null);
String do_maybe = "";
do {
System.out.println(do_maybe.length());
do_maybe = null;
} while(true);
}
public void while_() {
String while_ok = "";
while(while_ok != null) {
System.out.println(while_ok.length());
while_ok = null;
}
boolean TRUE = true;
String while_always = null;
while(TRUE) {
System.out.println(while_always.length());
while_always = null;
}
String while_maybe = "";
while(true) {
System.out.println(while_maybe.length());
while_maybe = null;
}
}
public void if_() {
String if_ok = "";
if (if_ok != null) {
System.out.println(if_ok.length());
if_ok = null;
}
String if_always = null;
if (if_always == null) {
System.out.println(if_always.length());
if_always = null;
}
String if_maybe = "";
if (if_maybe != null && if_maybe.length() % 2 == 0) {
if_maybe = null;
}
System.out.println(if_maybe.length());
}
public void for_() {
String for_ok ;
for (for_ok = ""; for_ok != null; for_ok = null) {
System.out.println(for_ok.length());
}
System.out.println(for_ok.length());
for (String for_always = null; ((for_always == null)); for_always = null) {
System.out.println(for_always.length());
}
for (String for_maybe = ""; ; for_maybe = null) {
System.out.println(for_maybe.length());
}
}
public void array_assign_test() {
int[] array_null = null;
array_null[0] = 10;
int[] array_ok;
array_ok = new int[10];
array_ok[0] = 42;
}
public void access() {
int[] arrayaccess = null;
String[] fieldaccess = null;
Object methodaccess = null;
System.out.println(arrayaccess[1]);
System.out.println(fieldaccess.length);
System.out.println(methodaccess.toString());
System.out.println(arrayaccess[1]);
System.out.println(fieldaccess.length);
System.out.println(methodaccess.toString());
}
public void enhanced_for() {
List<String> for_ok = java.util.Collections.emptyList();
for (String s : for_ok)
System.out.println(s);
System.out.println(for_ok.size());
List<String> for_always = null;
for (String s : for_always)
System.out.println(s);
System.out.println(for_always.size());
List<String> for_maybe = java.util.Collections.emptyList();
for (String s : for_maybe) {
System.out.println(s);
for_maybe = null;
}
System.out.println(for_maybe.size());
}
public void assertFalseInstanceofTest() {
Object s = String.valueOf(1);
assertFalse(s instanceof Number);
s.toString().isEmpty();
}
public void assertVariousTest() {
Object s = String.valueOf(1);
assertNotNull(s);
assertFalse(s instanceof Number);
assertTrue(s.toString().contains("1"));
assertFalse(s.toString().isEmpty());
}
public void assertFalseNotNullNestedTest() {
Object s = String.valueOf(1);
assertFalse(s != null || !"1".equals("1")); // assertTrue(s==null)
s.toString().isEmpty();
}
public void testForLoopCondition(Iterable iter) {
Iterator it = null;
for (it = iter.iterator(); !!it.hasNext(); ) {}
}
public void assertThatTest() {
Object assertThat_ok1 = maybe() ? null : new Object();
assertThat(assertThat_ok1, notNullValue());
assertThat_ok1.toString();
}
private boolean m;
A(boolean m) {
this.m = m;
}
boolean maybe() {
return this.m;
}
}
| 7,395 | 22.405063 | 94 | java |
codeql | codeql-master/java/ql/test/query-tests/Nullness/E.java | import org.junit.jupiter.api.Test;
public class E {
public void f(Object obj) {
obj.hashCode();
}
@Test
public void fTest() {
f(null);
}
public interface I {
void run();
}
public void runI(I i) {
i.run();
}
@Test
public void fTest2() {
runI(() -> f(null));
}
}
| 310 | 10.961538 | 34 | java |
codeql | codeql-master/java/ql/test/query-tests/Nullness/ExprDeref.java | public class ExprDeref {
Integer getBoxed() {
return 0;
}
int unboxBad(boolean b) {
return (b ? null : getBoxed()); // NPE
}
}
| 144 | 13.5 | 42 | java |
codeql | codeql-master/java/ql/test/query-tests/Nullness/C.java | import java.util.*;
public class C {
public void ex1(long[][][] a1, int ix, int len) {
long[][] a2 = null;
boolean haveA2 = ix < len && (a2 = a1[ix]) != null;
long[] a3 = null;
final boolean haveA3 = haveA2 && (a3 = a2[ix]) != null; // NPE - false positive
if (haveA3) a3[0] = 0; // NPE - false positive
}
public void ex2(boolean x, boolean y) {
String s1 = x ? null : "";
String s2 = (s1 == null) ? null : "";
if (s2 == null) {
s1 = y ? null : "";
s2 = (s1 == null) ? null : "";
}
if (s2 != null)
s1.hashCode(); // NPE - false positive
}
public void ex3(List<String> ss) {
String last = null;
for (String s : new String[] { "aa", "bb" }) {
last = s;
}
last.hashCode(); // OK
last = null;
if (!ss.isEmpty()) {
for (String s : ss) {
last = s;
}
last.hashCode(); // OK
}
}
public void ex4(Iterable<String> list, int step) {
int index = 0;
List<List<String>> result = new ArrayList<>();
List<String> slice = null;
Iterator<String> iter = list.iterator();
while (iter.hasNext()) {
String str = iter.next();
if (index % step == 0) {
slice = new ArrayList<>();
result.add(slice);
}
slice.add(str); // NPE - false positive
++index;
iter.remove();
}
}
public void ex5(boolean hasArr, int[] arr) {
int arrLen = 0;
if (hasArr) {
arrLen = arr == null ? 0 : arr.length;
}
if (arrLen > 0) {
arr[0] = 0; // NPE - false positive
}
}
public final int MY_CONST_A = 1;
public final int MY_CONST_B = 2;
public final int MY_CONST_C = 3;
public void ex6(int[] vals, boolean b1, boolean b2) {
final int switchguard;
if (vals != null && b1) {
switchguard = MY_CONST_A;
} else if (vals != null && b2) {
switchguard = MY_CONST_B;
} else {
switchguard = MY_CONST_C;
}
switch (switchguard) {
case MY_CONST_A:
vals[0] = 0; // OK
break;
case MY_CONST_C:
break;
case MY_CONST_B:
vals[0] = 0; // OK
break;
default:
throw new RuntimeException();
}
}
public void ex7(int[] arr1) {
int[] arr2 = null;
if (arr1.length > 0) {
arr2 = new int[arr1.length];
}
for (int i = 0; i < arr1.length; i++)
arr2[i] = arr1[i]; // NPE - false positive
}
public void ex8(int x, int lim) {
boolean stop = x < 1;
int i = 0;
Object obj = new Object();
while (!stop) {
int j = 0;
while (!stop && j < lim) {
int step = (j * obj.hashCode()) % 10; // NPE - false positive
if (step == 0) {
obj.hashCode();
i += 1;
stop = i >= x;
if (!stop) {
obj = new Object();
} else {
obj = null;
}
continue;
}
j += step;
}
}
}
public void ex9(boolean cond, Object obj1) {
if (cond) {
return;
}
Object obj2 = obj1;
if (obj2 != null && obj2.hashCode() % 5 > 2) {
obj2.hashCode();
cond = true;
}
if (cond) {
obj2.hashCode(); // NPE - false positive
}
}
public void ex10(int[] a) {
int n = a == null ? 0 : a.length;
for (int i = 0; i < n; i++) {
int x = a[i]; // NPE - false positive
if (x > 7)
a = new int[n];
}
}
public void ex11(Object obj, Boolean b1) {
Boolean b2 = obj == null ? Boolean.FALSE : b1;
if (b2 == null) {
obj.hashCode(); // OK
}
if (obj == null) {
b1 = Boolean.TRUE;
}
if (b1 == null) {
obj.hashCode(); // OK
}
}
private final Object finalObj = new Object();
public void ex12() {
finalObj.hashCode(); // OK
if (finalObj != null) {
finalObj.hashCode(); // OK
}
}
private void verifyBool(boolean b) {
if (!b) {
throw new Exception();
}
}
public void ex13(int[] a) {
int i = 0;
boolean b = false;
Object obj = null;
while (a[++i] != 0) {
if (a[i] == 1) {
obj = new Object();
b = true;
} else if (a[i] == 2) {
verifyBool(b);
obj.hashCode(); // NPE - false positive
}
}
}
private void verifyNotNull(Object obj) {
if (obj == null) {
throw new Exception();
}
}
public void ex14(int[] a) {
int i = 0;
Object obj = null;
while (a[++i] != 0) {
if (a[i] == 1) {
obj = new Object();
} else if (a[i] == 2) {
verifyNotNull(obj);
obj.hashCode(); // NPE - false positive
}
}
}
public void ex15(Object o1, Object o2) {
if (o1 == null && o2 != null) {
return;
}
if (o1 == o2) {
return;
}
if (o1.equals(o2)) { // NPE - false positive
return;
}
}
private Object foo16;
private Object getFoo16() {
return this.foo16;
}
public static void ex16(C c) {
int[] xs = c.getFoo16() != null ? new int[5] : null;
if (c.getFoo16() != null) {
xs[0]++; // NPE - false positive
}
}
public static final int MAXLEN = 1024;
public void ex17() {
int[] xs = null;
// loop executes at least once
for (int i = 32; i <= MAXLEN; i *= 2) {
xs = new int[5];
}
xs[0]++; // OK
}
}
| 5,323 | 20.467742 | 83 | java |
codeql | codeql-master/java/ql/test/query-tests/BusyWait/BusyWaits.java | class BusyWaits {
public void badWait() throws InterruptedException {
while(this.hashCode() != 0)
Thread.sleep(1);
}
public void badWait2() throws InterruptedException, CloneNotSupportedException {
while (this.hashCode() < 3) {
for (int i = 0; i < this.hashCode(); this.clone())
Thread.sleep(new String[1].length);
}
}
public void noError() throws InterruptedException {
while(this.hashCode() < 0) {
this.wait();
this.notify();
if (1 < 2)
Thread.sleep(2);
}
}
public void noError2() {
while (this.hashCode() < 0)
synchronized(this) {
System.out.println("foo");
}
}
} | 625 | 20.586207 | 81 | java |
codeql | codeql-master/java/ql/test/query-tests/ContinueInFalseLoop/A.java | public class A {
public interface Cond {
boolean cond();
}
void test1(int x, Cond c) {
int i;
// --- do loops ---
do {
if (c.cond())
continue; // BAD
if (c.cond())
break;
} while (false);
do {
if (c.cond())
continue;
if (c.cond())
break;
} while (true);
do {
if (c.cond())
continue;
if (c.cond())
break;
} while (c.cond());
// --- while, for loops ---
while (false) {
if (c.cond())
continue; // GOOD [never reached, if the condition changed so it was then the result would no longer apply]
if (c.cond())
break;
}
for (i = 0; false; i++) {
if (c.cond())
continue; // GOOD [never reached, if the condition changed so it was then the result would no longer apply]
if (c.cond())
break;
}
// --- nested loops ---
do {
do {
if (c.cond())
continue; // BAD
if (c.cond())
break;
} while (false);
if (c.cond())
break;
} while (true);
do {
do {
if (c.cond())
continue; // GOOD
if (c.cond())
break;
} while (true);
} while (false);
do {
switch (x) {
case 1:
// do [1]
break; // break out of the switch
default:
// do [2]
// break out of the loop entirely, skipping [3]
continue; // BAD; labelled break is better
};
// do [3]
} while (false);
}
}
| 1,559 | 17.352941 | 115 | java |
codeql | codeql-master/java/ql/test/query-tests/maven-dependencies/another-project/src/main/java/Library.java |
public class Library {
public static void test() {
}
}
| 67 | 6.555556 | 29 | java |
codeql | codeql-master/java/ql/test/query-tests/maven-dependencies/my-project/src/main/java/Test.java |
public class Test {
public Test() {
}
}
| 47 | 5 | 19 | java |
codeql | codeql-master/java/ql/test/query-tests/DefineEqualsWhenAddingFields/I.java | interface I {
boolean equals(Object o);
} | 42 | 13.333333 | 26 | java |
codeql | codeql-master/java/ql/test/query-tests/DefineEqualsWhenAddingFields/DelegateEq.java |
public class DelegateEq {
abstract class Super {
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
return doEquals((Super)obj);
}
abstract boolean doEquals(Super sup);
}
class Sub extends Super {
int i; // OK
@Override
boolean doEquals(Super sup) {
return this.i == ((Sub)sup).i;
}
}
}
| 430 | 16.958333 | 53 | java |
codeql | codeql-master/java/ql/test/query-tests/DefineEqualsWhenAddingFields/B.java | class B implements I {
private int f;
} | 40 | 12.666667 | 22 | java |
codeql | codeql-master/java/ql/test/query-tests/DefineEqualsWhenAddingFields/MyFragment.java |
public class MyFragment extends Fragment {
// OK: super class enforces reference equality
private int anotherField;
}
| 121 | 19.333333 | 47 | java |
codeql | codeql-master/java/ql/test/query-tests/DefineEqualsWhenAddingFields/A.java | class A {
// OK: super class is Object
public int f;
} | 56 | 13.25 | 29 | java |
codeql | codeql-master/java/ql/test/query-tests/DefineEqualsWhenAddingFields/RefEq.java |
public class RefEq {
{
class Super {
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
}
class Sub extends Super {
int i; // OK
}
}
{
class Super {
@Override
public boolean equals(Object obj) {
return (obj==this);
}
}
class Sub extends Super {
int i; // OK
}
}
{
class Super {
@Override
public boolean equals(Object obj) {
if (obj==this)
return true;
else
return false;
}
}
class Sub extends Super {
int i; // OK
}
}
}
| 536 | 12.425 | 38 | java |
codeql | codeql-master/java/ql/test/query-tests/DefineEqualsWhenAddingFields/Fragment.java |
public class Fragment {
private int field;
// Enforce reference equality
@Override
final public boolean equals(Object o) {
return super.equals(o);
}
@Override
public final int hashCode() {
return super.hashCode();
}
}
| 233 | 13.625 | 40 | java |
codeql | codeql-master/java/ql/test/query-tests/CompareIdenticalValues/A.java |
class Super {
int foo;
}
public class A extends Super {
class B extends Super {
{
if (this.foo == this.foo)
;
if (B.this.foo == this.foo)
;
if (super.foo == foo)
;
if (B.super.foo == foo)
;
if (A.this.foo != this.foo)
;
if (A.super.foo == foo)
;
}
}
{
Double d = Double.NaN;
if (d == d); // !Double.isNan(d)
if (d <= d); // !Double.isNan(d), but unlikely to be intentional
if (d >= d); // !Double.isNan(d), but unlikely to be intentional
if (d != d); // Double.isNan(d)
if (d > d); // always false
if (d < d); // always false
float f = Float.NaN;
if (f == f); // !Float.isNan(f)
if (f <= f); // !Float.isNan(f), but unlikely to be intentional
if (f >= f); // !Float.isNan(f), but unlikely to be intentional
if (f != f); // Float.isNan(f)
if (f > f); // always false
if (f < f); // always false
int i = 0;
if (i == i);
if (i != i);
}
}
| 925 | 19.130435 | 66 | java |
codeql | codeql-master/java/ql/test/query-tests/InconsistentOperations/Test3.java | public class Test3 {
static class A { void bar() {} }
static A foo() { return new A(); }
void test() {
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
}
{ A a = foo(); /* no a.bar();*/ } // NOT OK
} | 410 | 21.833333 | 45 | java |
codeql | codeql-master/java/ql/test/query-tests/InconsistentOperations/Operations.java |
public class Operations implements AutoCloseable {
interface NoBodies {
NoBodies append(String s);
}
interface NoBodiesSubtype extends NoBodies {
NoBodies append(String s);
}
public Operations open() { return this; }
public Operations create() { return this; }
public boolean isOpen() { return true; }
public void close() { return; }
public boolean add(String s) { return true; }
public boolean addAll(String...strings) { return true; }
public Operations chain() { return this; }
public void missingClose() {
{ Operations ops = open(); if (ops.isOpen()) ops.close(); }
{ Operations ops = open(); if (ops.isOpen()) ops.close(); }
{ Operations ops = open(); if (ops.isOpen()) ops.close(); }
{ Operations ops = open(); if (ops.isOpen()) ops.close(); }
{ Operations ops = open(); if (ops.isOpen()) ops.close(); }
{ Operations ops = open(); if (ops.isOpen()) ops.close(); }
{ Operations ops = open(); if (ops.isOpen()) ops.close(); }
{ Operations ops = open(); if (ops.isOpen()) ops.close(); }
{ Operations ops = open(); if (ops.isOpen()) ops.close(); }
{ Operations ops = open(); if (ops.isOpen()) ops.close(); }
{ Operations ops = open(); if (ops.isOpen()) ops.close(); }
{ Operations ops = open(); if (ops.isOpen()) ops.close(); }
{ Operations ops = open(); if (ops.isOpen()) ops.close(); }
{ Operations ops = open(); if (ops.isOpen()) ops.close(); }
{ Operations ops = open(); if (ops.isOpen()) ops.close(); }
{ Operations ops = open(); if (ops.isOpen()) ops.close(); }
{ Operations ops = open(); if (ops.isOpen()) ops.close(); }
{ Operations ops = open(); if (ops.isOpen()) ops.close(); }
{ Operations ops = open(); if (ops.isOpen()) ops.close(); }
{ Operations ops = open(); if (ops.isOpen()) ops.open(); }
}
public void missingAdd() {
{ Operations ops = create(); if (ops.isOpen()) ops.add("something"); }
{ Operations ops = create(); if (ops.isOpen()) ops.add("something"); }
{ Operations ops = create(); if (ops.isOpen()) ops.add("something"); }
{ Operations ops = create(); if (ops.isOpen()) ops.add("something"); }
{ Operations ops = create(); if (ops.isOpen()) ops.add("something"); }
{ Operations ops = create(); if (ops.isOpen()) ops.add("something"); }
{ Operations ops = create(); if (ops.isOpen()) ops.add("something"); }
{ Operations ops = create(); if (ops.isOpen()) ops.add("something"); }
{ Operations ops = create(); if (ops.isOpen()) ops.add("something"); }
{ Operations ops = create(); if (ops.isOpen()) ops.add("something"); }
{ Operations ops = create(); if (ops.isOpen()) ops.add("something"); }
{ Operations ops = create(); if (ops.isOpen()) ops.add("something"); }
{ Operations ops = create(); if (ops.isOpen()) ops.add("something"); }
{ Operations ops = create(); if (ops.isOpen()) ops.add("something"); }
{ Operations ops = create(); if (ops.isOpen()) ops.add("something"); }
{ Operations ops = create(); if (ops.isOpen()) ops.add("something"); }
{ Operations ops = create(); if (ops.isOpen()) ops.add("something"); }
{ Operations ops = create(); if (ops.isOpen()) ops.add("something"); }
{ Operations ops = create(); if (ops.isOpen()) ops.add("something"); }
{ Operations ops = create(); if (ops.isOpen()) ops.addAll("the", "things"); }
}
public void missingUse() {
System.out.println(this.toString());
System.out.println(this.toString());
System.out.println(this.toString());
System.out.println(this.toString());
System.out.println(this.toString());
System.out.println(this.toString());
System.out.println(this.toString());
System.out.println(this.toString());
System.out.println(this.toString());
System.out.println(this.toString());
System.out.println(this.toString());
System.out.println(this.toString());
System.out.println(this.toString());
System.out.println(this.toString());
System.out.println(this.toString());
System.out.println(this.toString());
System.out.println(this.toString());
System.out.println(this.toString());
System.out.println(this.toString());
System.out.println(this.toString());
this.toString();
}
public void designedForChaining() {
StringBuilder b = new StringBuilder();
{ Object use = b.append("a").append("b"); }
{ Object use = b.append("a").append("b"); }
{ Object use = b.append("a").append("b"); }
{ Object use = b.append("a").append("b"); }
{ Object use = b.append("a").append("b"); }
{ Object use = b.append("a").append("b"); }
{ Object use = b.append("a").append("b"); }
{ Object use = b.append("a").append("b"); }
{ Object use = b.append("a").append("b"); }
{ Object use = b.append("a").append("b"); }
{ Object unchainedUse = b.append("c"); }
{ Object unchainedUse = b.append("c"); }
{ Object unchainedUse = b.append("c"); }
{ Object unchainedUse = b.append("c"); }
{ Object unchainedUse = b.append("c"); }
{ Object unchainedUse = b.append("c"); }
{ Object unchainedUse = b.append("c"); }
{ Object unchainedUse = b.append("c"); }
{ Object unchainedUse = b.append("c"); }
{ Object unchainedUse = b.append("c"); }
b.append("d");
}
public void noBodies() {
NoBodiesSubtype t = null;
{ Object use = t.append("a").append("b"); }
{ Object use = t.append("a").append("b"); }
{ Object use = t.append("a").append("b"); }
{ Object use = t.append("a").append("b"); }
{ Object use = t.append("a").append("b"); }
{ Object use = t.append("a").append("b"); }
{ Object use = t.append("a").append("b"); }
{ Object use = t.append("a").append("b"); }
{ Object use = t.append("a").append("b"); }
{ Object use = t.append("a").append("b"); }
{ Object unchainedUse = t.append("c"); }
{ Object unchainedUse = t.append("c"); }
{ Object unchainedUse = t.append("c"); }
{ Object unchainedUse = t.append("c"); }
{ Object unchainedUse = t.append("c"); }
{ Object unchainedUse = t.append("c"); }
{ Object unchainedUse = t.append("c"); }
{ Object unchainedUse = t.append("c"); }
{ Object unchainedUse = t.append("c"); }
{ Object unchainedUse = t.append("c"); }
t.append("d");
}
public void notMissingAfterAll(Operations ops) {
ops = open(); ops.close();
}
private static class Builder {
private int val;
public Builder withVal(int val) {
this.val = val;
return this;
}
public String build() {
return Integer.toString(val);
}
}
public void missingBuild() {
Builder builder = new Builder();
String result;
result = builder.build();
result = builder.build();
result = builder.build();
result = builder.build();
result = builder.build();
result = builder.build();
result = builder.build();
result = builder.build();
result = builder.build();
result = builder.build();
result = builder.build();
result = builder.build();
result = builder.build();
result = builder.build();
result = builder.build();
result = builder.build();
result = builder.build();
result = builder.build();
result = builder.build();
result = builder.build();
result = builder.build();
result = builder.build();
result = builder.withVal(1).build();
}
public void testConn(java.sql.Connection conn) throws java.sql.SQLException {
java.sql.PreparedStatement pstmt = null;
java.sql.ResultSet rs = null;
try {
pstmt = conn.prepareStatement("SELECT something FROM table");
rs = pstmt.executeQuery();
while(rs.next()) { // OK
}
pstmt.executeQuery().next();
pstmt.executeQuery().next();
pstmt.executeQuery().next();
pstmt.executeQuery().next();
pstmt.executeQuery().next();
pstmt.executeQuery().next();
pstmt.executeQuery().next();
pstmt.executeQuery().next();
pstmt.executeQuery().next();
pstmt.executeQuery().next();
pstmt.executeQuery().next();
pstmt.executeQuery().next();
pstmt.executeQuery().next();
pstmt.executeQuery().next();
pstmt.executeQuery().next();
} finally {
}
}
{
String test = "test";
test = searchReplace(test);
test = searchReplace(test);
test = searchReplace(test);
test = searchReplace(test);
test = searchReplace(test);
test = searchReplace(test);
test = searchReplace(test);
test = searchReplace(test);
test = searchReplace(test);
test = searchReplace(test);
test = searchReplace(test);
test = searchReplace(test);
test = searchReplace(test);
test = searchReplace(test);
test = searchReplace(test);
test = searchReplace(test);
String test2 = "test2";
test2 = searchReplace(test2); // OK (do not report methods called on their own result)
}
private String searchReplace(String s) {
return s;
}
public void autoClose() {
try(Operations ops = open()) {
if (ops.isOpen()) ops.open();
}
}
}
| 8,665 | 34.662551 | 88 | java |
codeql | codeql-master/java/ql/test/query-tests/InconsistentOperations/Test2.java | public class Test2 {
static class A { void bar() {} }
static A foo() { return new A(); }
void test() {
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); /* no a.bar();*/ } // NOT OK
}
} | 410 | 23.176471 | 46 | java |
codeql | codeql-master/java/ql/test/query-tests/InconsistentOperations/Test6.java | public class Test6 {
static class A { void bar() {} }
static A foo() { return new A(); }
void test() {
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
}
Object o = new Object() {
A a = foo(); // OK
};
} | 416 | 19.85 | 35 | java |
codeql | codeql-master/java/ql/test/query-tests/InconsistentOperations/Test4.java | public class Test4 {
static class A { void bar() {} }
static A foo() { return new A(); }
void test() {
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
}
A a = foo(); // OK
} | 384 | 20.388889 | 35 | java |
codeql | codeql-master/java/ql/test/query-tests/InconsistentOperations/Test5.java | public class Test5 {
static class A { void bar() {} }
static A foo() { return new A(); }
void test() {
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
{ A a = foo(); a.bar(); }
}
static A a = foo(); // OK
} | 391 | 20.777778 | 35 | java |
codeql | codeql-master/java/ql/test/query-tests/security/CWE-190/semmle/tests/Test.java | // Semmle test case for CWE-190: Integer Overflow or Wraparound
// http://cwe.mitre.org/data/definitions/190.html
package test.cwe190.semmle.tests;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.HashMap;
class Test {
public static void main(String[] args) {
// IntMultToLong
{
int timeInSeconds = 1000000;
// BAD: result of multiplication will be too large for
// int, and will overflow before being stored in the long
long timeInNanos = timeInSeconds * 1000000000;
}
{
int timeInSeconds = 1000000;
// BAD
long timeInNanos = timeInSeconds * 1000000000 + 4;
}
{
int timeInSeconds = 1000000;
// BAD
long timeInNanos = true ? timeInSeconds * 1000000000 + 4 : 0;
}
{
long timeInSeconds = 10000000L;
// same problem, but with longs; not reported as the conversion to double is not sufficient indication of a large number
double timeInNanos = timeInSeconds * 10000000L;
}
{
int timeInSeconds = 1000000;
// GOOD: one of the arguments is cast to long before multiplication
// so the multiplication will take place in the long
long timeInNanos = (long) timeInSeconds * 1000000000;
}
{
int timeInSeconds = 1;
// GOOD: both arguments are constants that are small
// enough to allow the multiplication in int without
// overflow
long timeInNanos = timeInSeconds * 1000000000;
}
// InformationLoss
{
int i = 0;
while (i < 1000000) {
// BAD: getLargeNumber is implicitly narrowed to an integer
// which will result in overflows if it is large
i += getLargeNumber();
}
}
{
long i = 0;
while (i < 1000000) {
// GOOD: i is a long, so no narrowing occurs
i += getLargeNumber();
}
}
{
int i = 0;
long j = 100;
// FALSE POSITIVE: the query check purely based on the type, it
// can't try to
// determine whether the value may in fact always be in bounds
i += j;
}
// ArithmeticWithExtremeValues
{
int i = 0;
i = Integer.MAX_VALUE;
int j = 0;
// BAD: overflow
j = i + 1;
}
{
int i = 0;
i = Integer.MAX_VALUE;
int j = 0;
i = 0;
// GOOD: reassigned before usage
j = i + 1;
}
{
long i = Long.MIN_VALUE;
// BAD: overflow
long j = i - 1;
}
{
long i = Long.MAX_VALUE;
// GOOD: no overflow
long j = i - 1;
}
{
int i = Integer.MAX_VALUE;
// GOOD: no overflow
long j = (long) i - 1;
}
{
int i = Integer.MAX_VALUE;
// GOOD: guarded
if (i < Integer.MAX_VALUE) {
long j = i + 1;
}
}
{
int i = Integer.MAX_VALUE;
if (i < Integer.MAX_VALUE) {
// BAD: reassigned after guard
i = Integer.MAX_VALUE;
long j = i + 1;
}
}
{
int i = Integer.MAX_VALUE;
// BAD: guarded the wrong way
if (i > Integer.MIN_VALUE) {
long j = i + 1;
}
}
{
int i = Integer.MAX_VALUE;
// GOOD: The query can detect custom guards.
if (properlyBounded(i)) {
long j = i + 1;
}
}
{
byte b = Byte.MAX_VALUE;
// GOOD: extreme byte value is widened to type int, thus avoiding
// overflow
// (see binary numeric promotions in JLS 5.6.2)
int i = b + 1;
}
{
short s = Short.MAX_VALUE;
// GOOD: extreme short value is widened to type int, thus avoiding
// overflow
// (see binary numeric promotions in JLS 5.6.2)
int i = s + 1;
}
{
int i = Integer.MAX_VALUE;
// GOOD: extreme int value is widened to type long, thus avoiding
// overflow
// (see binary numeric promotions in JLS 5.6.2)
long l = i + 1L;
}
{
byte b = Byte.MAX_VALUE;
// BAD: extreme byte value is widened to type int, but subsequently
// cast to narrower type byte
byte widenedThenNarrowed = (byte) (b + 1);
}
{
short s = Short.MAX_VALUE;
// BAD: extreme short value is widened to type int, but subsequently
// cast to narrower type short
short widenedThenNarrowed = (short) (s + 1);
}
{
int i = Integer.MAX_VALUE;
// BAD: extreme int value is widened to type long, but subsequently
// cast to narrower type int
int widenedThenNarrowed = (int) (i + 1L);
}
// ArithmeticUncontrolled
int data = (new java.security.SecureRandom()).nextInt();
{
// BAD: may overflow if data is large
int output = data + 1;
}
{
// GOOD: guarded
if (data < Integer.MAX_VALUE) {
int output = data + 1;
}
}
{
// guard against underflow
if (data > Integer.MIN_VALUE) {
int stillLarge = data - 1;
// FALSE NEGATIVE: stillLarge could still be very large, even
// after
// it has had arithmetic done on it
int output = stillLarge + 100;
}
}
{
// GOOD: uncontrolled int value is widened to type long, thus
// avoiding overflow
// (see binary numeric promotions in JLS 5.6.2)
long widened = data + 10L;
}
{
// BAD: uncontrolled int value is widened to type long, but
// subsequently cast to narrower type int
int widenedThenNarrowed = (int) (data + 10L);
}
}
public static long getLargeNumber() {
return Long.MAX_VALUE / 2;
}
public static boolean properlyBounded(int i) {
return i < Integer.MAX_VALUE;
}
}
| 5,240 | 19.797619 | 123 | java |
codeql | codeql-master/java/ql/test/query-tests/security/CWE-190/semmle/tests/ArithmeticTainted.java | // Semmle test case for CWE-190: Integer Overflow or Wraparound
// http://cwe.mitre.org/data/definitions/190.html
package test.cwe190.semmle.tests;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ArithmeticTainted {
public void main(String[] args) {
BufferedReader readerBuffered;
InputStreamReader readerInputStream;
int data;
try {
readerInputStream = new InputStreamReader(System.in, "UTF-8");
readerBuffered = new BufferedReader(readerInputStream);
String stringNumber = readerBuffered.readLine();
if (stringNumber != null) {
data = Integer.parseInt(stringNumber.trim());
} else {
data = 0;
}
} catch (IOException exceptIO) {
// fail
data = 0;
}
{
// BAD: may overflow if input data is very large
int scaled = data + 10;
}
{
// BAD: guard and then bypass
if (data > Integer.MIN_VALUE) {
System.out.println("I'm guarded");
}
int output = data - 10;
}
{
// BAD: guard and use after both branches
if (data < Integer.MAX_VALUE) {
System.out.println("I'm guarded");
} else {
System.out.println("I'm not guarded");
}
int output = data + 1;
}
{
// GOOD: use a guard to ensure no overflows occur
int scaled;
if (data < Integer.MAX_VALUE / 10 && data > Integer.MIN_VALUE / 10)
scaled = data * 10;
else
scaled = Integer.MAX_VALUE;
}
{
Holder tainted = new Holder(1);
tainted.setData(data);
Holder safe = new Holder(1);
int herring = tainted.getData();
int ok = safe.getData();
// GOOD
int output_ok = ok + 1;
// BAD
int output = herring + 1;
}
{
// guard against underflow
if (data > Integer.MIN_VALUE) {
int stillTainted = data - 1;
// FALSE NEGATIVE: stillTainted could still be very large, even
// after
// it has had arithmetic done on it
int output = stillTainted + 100;
}
}
{
// GOOD: tainted int value is widened to type long, thus avoiding
// overflow
// (see binary numeric promotions in JLS 5.6.2)
long widened = data + 10L;
}
{
// BAD: tainted int value is widened to type long, but subsequently
// cast to narrower type int
int widenedThenNarrowed = (int) (data + 10L);
}
// The following test case has an arbitrary guard on hashcode
// because otherwise the return statement causes 'data' to be guarded
// in the subsequent test cases.
if (this.hashCode() > 0) {
// GOOD: guard and return if bad
if (data < Integer.MAX_VALUE) {
System.out.println("I'm guarded");
} else {
return;
}
int output = data + 1;
}
{
double x= Double.MAX_VALUE;
// OK: CWE-190 only pertains to integer arithmetic
double y = x * 2;
}
{
test(data);
test2(data);
test3(data);
test4(data);
}
}
public static void test(int data) {
// BAD: may overflow if input data is very large
data++;
}
public static void test2(int data) {
// BAD: may overflow if input data is very large
++data;
}
public static void test3(int data) {
// BAD: may underflow if input data is very small
data--;
}
public static void test4(int data) {
// BAD: may underflow if input data is very small
--data;
}
}
| 3,259 | 21.957746 | 71 | java |
codeql | codeql-master/java/ql/test/query-tests/security/CWE-190/semmle/tests/Test2.java | public class Test2 {
// IntMultToLong
void foo() {
for (int k = 1; k < 10; k++) {
long res = k * 1000; // OK
}
}
}
| 135 | 14.111111 | 34 | java |
codeql | codeql-master/java/ql/test/query-tests/security/CWE-190/semmle/tests/Holder.java | // Semmle test case for CWE-190: Integer Overflow or Wraparound
// http://cwe.mitre.org/data/definitions/190.html
package test.cwe190.semmle.tests;
public class Holder {
public int dat;
public Holder(int d) {
dat = d;
}
public void setData(int d) {
dat = d;
}
public int getData() {
return dat;
}
}
| 316 | 14.85 | 63 | java |
codeql | codeql-master/java/ql/test/query-tests/security/CWE-676/semmle/tests/Test.java | // Semmle test case for CWE-676: Use of Potentially Dangerous Function
// http://cwe.mitre.org/data/definitions/676.html
package test.cwe676.semmle.tests;
class Test {
private Thread worker;
public Test(Thread worker) {
this.worker = worker;
}
public void quit() {
// Stop
worker.stop(); // BAD: Thread.stop can result in corrupted data
}
}
| 356 | 20 | 70 | java |
codeql | codeql-master/java/ql/test/query-tests/security/CWE-681/semmle/tests/Test.java | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Test {
public static void main(String[] args) throws IOException {
{
long data;
BufferedReader readerBuffered = new BufferedReader(
new InputStreamReader(System.in, "UTF-8"));
String stringNumber = readerBuffered.readLine();
if (stringNumber != null) {
data = Long.parseLong(stringNumber.trim());
} else {
data = 0;
}
// AVOID: potential truncation if input data is very large, for example
// 'Long.MAX_VALUE'
int scaled = (int)data;
//...
// GOOD: use a guard to ensure no truncation occurs
int scaled2;
if (data > Integer.MIN_VALUE && data < Integer.MAX_VALUE)
scaled2 = (int)data;
else
throw new IllegalArgumentException("Invalid input");
}
}
} | 820 | 23.878788 | 74 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.