Add CodeQL GitHub code scanning workflow (#2076)

* Add CodeQL GitHub code scanning workflow

* Only compile main sources for code scanning

* Move test .proto  files to test sources

`annotations.proto` also seems to be only relevant for tests because the test
explicitly registers them as extensions. By default the Proto adapter does not
consider them.

* Address some code scanning findings

* Fix some more findings
This commit is contained in:
Marcono1234 2022-02-18 03:40:40 +01:00 committed by GitHub
parent d19e9fe0af
commit 49ddab9eeb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
29 changed files with 111 additions and 54 deletions

46
.github/workflows/codeql-analysis.yml vendored Normal file
View File

@ -0,0 +1,46 @@
# Based on default config generated by GitHub, see also https://github.com/github/codeql-action
name: "CodeQL"
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
schedule:
# Run every Monday at 16:10
- cron: '10 16 * * 1'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'java' ]
steps:
- name: Checkout repository
uses: actions/checkout@v2
# Initializes the CodeQL tools for scanning
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
with:
languages: ${{ matrix.language }}
# Run all security queries and maintainability and reliability queries
queries: +security-and-quality
# Only compile main sources, but ignore test sources because findings for them might not
# be that relevant (though GitHub security view also allows filtering by source type)
# Can replace this with github/codeql-action/autobuild action to run complete build
- name: Compile sources
run: |
mvn compile
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1

View File

@ -12,7 +12,7 @@ import java.io.IOException;
* A type adapter factory that implements {@code @Intercept}.
*/
public final class InterceptorFactory implements TypeAdapterFactory {
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
Intercept intercept = type.getRawType().getAnnotation(Intercept.class);
if (intercept == null) {
return null;

View File

@ -141,7 +141,7 @@ public final class InterceptorTest extends TestCase {
}
public static final class UserValidator implements JsonPostDeserializer<User> {
public void postDeserialize(User user) {
@Override public void postDeserialize(User user) {
if (user.name == null || user.password == null) {
throw new JsonSyntaxException("name and password are required fields.");
}
@ -161,7 +161,7 @@ public final class InterceptorTest extends TestCase {
}
public static final class AddressValidator implements JsonPostDeserializer<Address> {
public void postDeserialize(Address address) {
@Override public void postDeserialize(Address address) {
if (address.city == null || address.state == null || address.zip == null) {
throw new JsonSyntaxException("Address city, state and zip are required fields.");
}

View File

@ -70,6 +70,7 @@ public class PostConstructAdapterFactoryTest extends TestCase {
}
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
@ -95,6 +96,7 @@ public class PostConstructAdapterFactoryTest extends TestCase {
this.sandwiches = sandwiches;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;

View File

@ -16,18 +16,16 @@
package com.google.gson.typeadapters;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import com.google.gson.JsonParseException;
import junit.framework.TestCase;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public final class UtcDateTypeAdapterTest extends TestCase {
private final Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new UtcDateTypeAdapter())
@ -83,7 +81,7 @@ public final class UtcDateTypeAdapterTest extends TestCase {
gson.fromJson("2017-06-20T14:32:30", Date.class);
fail("No exception");
} catch (JsonParseException exe) {
assertEquals(exe.getMessage(), "java.text.ParseException: Failed to parse date ['2017-06-20T14']: 2017-06-20T14");
assertEquals("java.text.ParseException: Failed to parse date ['2017-06-20T14']: 2017-06-20T14", exe.getMessage());
}
}
}

View File

@ -187,6 +187,7 @@ public final class JsonArray extends JsonElement implements Iterable<JsonElement
*
* @return an iterator to navigate the elements of the array.
*/
@Override
public Iterator<JsonElement> iterator() {
return elements.iterator();
}
@ -341,13 +342,12 @@ public final class JsonArray extends JsonElement implements Iterable<JsonElement
throw new IllegalStateException();
}
@Deprecated
@Override
public char getAsCharacter() {
if (elements.size() == 1) {
JsonElement element = elements.get(0);
@SuppressWarnings("deprecation")
char result = element.getAsCharacter();
return result;
return element.getAsCharacter();
}
throw new IllegalStateException();
}

View File

@ -59,7 +59,7 @@ public final class JsonStreamParser implements Iterator<JsonElement> {
* @since 1.4
*/
public JsonStreamParser(String json) {
this(new StringReader(json));
this(new StringReader(json));
}
/**
@ -81,6 +81,7 @@ public final class JsonStreamParser implements Iterator<JsonElement> {
* @throws NoSuchElementException if no {@code JsonElement} is available.
* @since 1.4
*/
@Override
public JsonElement next() throws JsonParseException {
if (!hasNext()) {
throw new NoSuchElementException();
@ -103,6 +104,7 @@ public final class JsonStreamParser implements Iterator<JsonElement> {
* @throws JsonSyntaxException if the incoming stream is malformed JSON.
* @since 1.4
*/
@Override
public boolean hasNext() {
synchronized (lock) {
try {
@ -120,6 +122,7 @@ public final class JsonStreamParser implements Iterator<JsonElement> {
* implemented.
* @since 1.4
*/
@Override
public void remove() {
throw new UnsupportedOperationException();
}

View File

@ -505,15 +505,15 @@ public final class $Gson$Types {
}
}
public Type[] getActualTypeArguments() {
@Override public Type[] getActualTypeArguments() {
return typeArguments.clone();
}
public Type getRawType() {
@Override public Type getRawType() {
return rawType;
}
public Type getOwnerType() {
@Override public Type getOwnerType() {
return ownerType;
}
@ -552,7 +552,7 @@ public final class $Gson$Types {
this.componentType = canonicalize(componentType);
}
public Type getGenericComponentType() {
@Override public Type getGenericComponentType() {
return componentType;
}
@ -601,11 +601,11 @@ public final class $Gson$Types {
}
}
public Type[] getUpperBounds() {
@Override public Type[] getUpperBounds() {
return new Type[] { upperBound };
}
public Type[] getLowerBounds() {
@Override public Type[] getLowerBounds() {
return lowerBound != null ? new Type[] { lowerBound } : EMPTY_TYPE_ARRAY;
}

View File

@ -108,7 +108,7 @@ public final class Excluder implements TypeAdapterFactory, Cloneable {
return result;
}
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
@Override public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
Class<?> rawType = type.getRawType();
boolean excludeClass = excludeClassChecks(rawType);

View File

@ -41,7 +41,7 @@ import java.util.Set;
public final class LinkedTreeMap<K, V> extends AbstractMap<K, V> implements Serializable {
@SuppressWarnings({ "unchecked", "rawtypes" }) // to avoid Comparable<Comparable<Comparable<...>>>
private static final Comparator<Comparable> NATURAL_ORDER = new Comparator<Comparable>() {
public int compare(Comparable a, Comparable b) {
@Override public int compare(Comparable a, Comparable b) {
return a.compareTo(b);
}
};
@ -466,15 +466,15 @@ public final class LinkedTreeMap<K, V> extends AbstractMap<K, V> implements Seri
next.prev = this;
}
public K getKey() {
@Override public K getKey() {
return key;
}
public V getValue() {
@Override public V getValue() {
return value;
}
public V setValue(V value) {
@Override public V setValue(V value) {
V oldValue = this.value;
this.value = value;
return oldValue;
@ -534,7 +534,7 @@ public final class LinkedTreeMap<K, V> extends AbstractMap<K, V> implements Seri
LinkedTreeMapIterator() {
}
public final boolean hasNext() {
@Override public final boolean hasNext() {
return next != header;
}
@ -550,7 +550,7 @@ public final class LinkedTreeMap<K, V> extends AbstractMap<K, V> implements Seri
return lastReturned = e;
}
public final void remove() {
@Override public final void remove() {
if (lastReturned == null) {
throw new IllegalStateException();
}
@ -567,7 +567,7 @@ public final class LinkedTreeMap<K, V> extends AbstractMap<K, V> implements Seri
@Override public Iterator<Entry<K, V>> iterator() {
return new LinkedTreeMapIterator<Entry<K, V>>() {
public Entry<K, V> next() {
@Override public Entry<K, V> next() {
return nextNode();
}
};
@ -602,7 +602,7 @@ public final class LinkedTreeMap<K, V> extends AbstractMap<K, V> implements Seri
@Override public Iterator<K> iterator() {
return new LinkedTreeMapIterator<K>() {
public K next() {
@Override public K next() {
return nextNode().key;
}
};

View File

@ -105,13 +105,13 @@ public final class Streams {
*/
static class CurrentWrite implements CharSequence {
char[] chars;
public int length() {
@Override public int length() {
return chars.length;
}
public char charAt(int i) {
@Override public char charAt(int i) {
return chars[i];
}
public CharSequence subSequence(int start, int end) {
@Override public CharSequence subSequence(int start, int end) {
return new String(chars, start, end - start);
}
}

View File

@ -1212,7 +1212,7 @@ public class JsonReader implements Closeable {
/**
* Closes this JSON reader and the underlying {@link java.io.Reader}.
*/
public void close() throws IOException {
@Override public void close() throws IOException {
peeked = PEEKED_NONE;
stack[0] = JsonScope.CLOSED;
stackSize = 1;

View File

@ -571,7 +571,7 @@ public class JsonWriter implements Closeable, Flushable {
* Ensures all buffered data is written to the underlying {@link Writer}
* and flushes that writer.
*/
public void flush() throws IOException {
@Override public void flush() throws IOException {
if (stackSize == 0) {
throw new IllegalStateException("JsonWriter is closed.");
}
@ -583,7 +583,7 @@ public class JsonWriter implements Closeable, Flushable {
*
* @throws IOException if the JSON document is incomplete.
*/
public void close() throws IOException {
@Override public void close() throws IOException {
out.close();
int size = stackSize;

View File

@ -130,7 +130,7 @@ public class GsonTypeAdapterTest extends TestCase {
private void assertSerialized(String expected, Class<?> instanceType, boolean registerAbstractDeserializer,
boolean registerAbstractHierarchyDeserializer, Object instance) {
JsonDeserializer<Abstract> deserializer = new JsonDeserializer<Abstract>() {
public Abstract deserialize(JsonElement json, Type typeOfT,
@Override public Abstract deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
throw new AssertionError();
}

View File

@ -79,7 +79,7 @@ public class CircularReferenceTest extends TestCase {
ClassWithSelfReference obj = new ClassWithSelfReference();
obj.child = obj;
Gson gson = new GsonBuilder().registerTypeAdapter(ClassWithSelfReference.class, new JsonSerializer<ClassWithSelfReference>() {
public JsonElement serialize(ClassWithSelfReference src, Type typeOfSrc,
@Override public JsonElement serialize(ClassWithSelfReference src, Type typeOfSrc,
JsonSerializationContext context) {
JsonObject obj = new JsonObject();
obj.addProperty("property", "value");

View File

@ -328,7 +328,7 @@ public class CollectionTest extends TestCase {
public void testUserCollectionTypeAdapter() {
Type listOfString = new TypeToken<List<String>>() {}.getType();
Object stringListSerializer = new JsonSerializer<List<String>>() {
public JsonElement serialize(List<String> src, Type typeOfSrc,
@Override public JsonElement serialize(List<String> src, Type typeOfSrc,
JsonSerializationContext context) {
return new JsonPrimitive(src.get(0) + ";" + src.get(1));
}

View File

@ -71,7 +71,7 @@ public class ConcurrencyTest extends TestCase {
ExecutorService executor = Executors.newFixedThreadPool(10);
for (int taskCount = 0; taskCount < 10; taskCount++) {
executor.execute(new Runnable() {
public void run() {
@Override public void run() {
MyObject myObj = new MyObject();
try {
startLatch.await();
@ -102,7 +102,7 @@ public class ConcurrencyTest extends TestCase {
ExecutorService executor = Executors.newFixedThreadPool(10);
for (int taskCount = 0; taskCount < 10; taskCount++) {
executor.execute(new Runnable() {
public void run() {
@Override public void run() {
try {
startLatch.await();
for (int i = 0; i < 10; i++) {

View File

@ -91,7 +91,7 @@ public class CustomSerializerTest extends TestCase {
public void testSerializerReturnsNull() {
Gson gson = new GsonBuilder()
.registerTypeAdapter(Base.class, new JsonSerializer<Base>() {
public JsonElement serialize(Base src, Type typeOfSrc, JsonSerializationContext context) {
@Override public JsonElement serialize(Base src, Type typeOfSrc, JsonSerializationContext context) {
return null;
}
})

View File

@ -470,7 +470,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
Gson gson = new GsonBuilder()
.setDateFormat(pattern)
.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
public Date deserialize(JsonElement json, Type typeOfT,
@Override public Date deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context)
throws JsonParseException {
return new Date(1315806903103L);

View File

@ -40,6 +40,7 @@ public class GsonVersionDiagnosticsTest extends TestCase {
private Gson gson;
@Before
@Override
public void setUp() {
gson = new GsonBuilder().registerTypeAdapter(TestType.class, new TypeAdapter<TestType>() {
@Override public void write(JsonWriter out, TestType value) {

View File

@ -88,7 +88,7 @@ public final class JsonAdapterAnnotationOnClassesTest extends TestCase {
*/
public void testRegisteredSerializerOverridesJsonAdapter() {
JsonSerializer<A> serializer = new JsonSerializer<A>() {
public JsonElement serialize(A src, Type typeOfSrc,
@Override public JsonElement serialize(A src, Type typeOfSrc,
JsonSerializationContext context) {
return new JsonPrimitive("registeredSerializer");
}
@ -107,7 +107,7 @@ public final class JsonAdapterAnnotationOnClassesTest extends TestCase {
*/
public void testRegisteredDeserializerOverridesJsonAdapter() {
JsonDeserializer<A> deserializer = new JsonDeserializer<A>() {
public A deserialize(JsonElement json, Type typeOfT,
@Override public A deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
return new A("registeredDeserializer");
}

View File

@ -284,7 +284,7 @@ public class MapTest extends TestCase {
public void testMapSubclassDeserialization() {
Gson gson = new GsonBuilder().registerTypeAdapter(MyMap.class, new InstanceCreator<MyMap>() {
public MyMap createInstance(Type type) {
@Override public MyMap createInstance(Type type) {
return new MyMap();
}
}).create();
@ -299,7 +299,7 @@ public class MapTest extends TestCase {
null, Map.class, String.class, Long.class);
Gson gson = new GsonBuilder()
.registerTypeAdapter(type, new JsonSerializer<Map<String, Long>>() {
public JsonElement serialize(Map<String, Long> src, Type typeOfSrc,
@Override public JsonElement serialize(Map<String, Long> src, Type typeOfSrc,
JsonSerializationContext context) {
JsonArray array = new JsonArray();
for (long value : src.values()) {
@ -493,7 +493,7 @@ public class MapTest extends TestCase {
+ "\"subs\":{\"Test\":" + subTypeJson + "}}";
JsonSerializer<TestTypes.Base> baseTypeAdapter = new JsonSerializer<TestTypes.Base>() {
public JsonElement serialize(TestTypes.Base src, Type typeOfSrc,
@Override public JsonElement serialize(TestTypes.Base src, Type typeOfSrc,
JsonSerializationContext context) {
return baseTypeJsonElement;
}

View File

@ -298,7 +298,7 @@ public class ObjectTest extends TestCase {
gson = new GsonBuilder()
.registerTypeHierarchyAdapter(ClassWithNoFields.class,
new JsonSerializer<ClassWithNoFields>() {
public JsonElement serialize(
@Override public JsonElement serialize(
ClassWithNoFields src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonObject();
}
@ -342,7 +342,7 @@ public class ObjectTest extends TestCase {
final Parent p = new Parent();
Gson gson = new GsonBuilder().registerTypeAdapter(
Parent.Child.class, new InstanceCreator<Parent.Child>() {
public Parent.Child createInstance(Type type) {
@Override public Parent.Child createInstance(Type type) {
return p.new Child();
}
}).create();

View File

@ -155,7 +155,7 @@ public final class StreamingTypeAdaptersTest extends TestCase {
String[] values = in.nextString().split(",");
return new Person(values[0], Integer.parseInt(values[1]));
}
public void write(JsonWriter out, Person person) throws IOException {
@Override public void write(JsonWriter out, Person person) throws IOException {
out.value(person.name + "," + person.age);
}
};

View File

@ -21,9 +21,6 @@ import com.google.gson.TypeAdapter;
import com.google.gson.internal.$Gson$Types;
import junit.framework.TestCase;
import java.io.PrintStream;
import java.lang.ref.WeakReference;
/**
* Test fixes for infinite recursion on {@link $Gson$Types#resolve(java.lang.reflect.Type, Class,
* java.lang.reflect.Type)}, described at <a href="https://github.com/google/gson/issues/440">Issue #440</a>

View File

@ -19,6 +19,7 @@ package com.google.gson.metrics;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonFactoryBuilder;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
@ -224,7 +225,8 @@ public final class ParseBenchmark {
com.fasterxml.jackson.core.JsonParser jp = jsonFactory.createParser(new CharArrayReader(data));
int depth = 0;
do {
switch (jp.nextToken()) {
JsonToken token = jp.nextToken();
switch (token) {
case START_OBJECT:
case START_ARRAY:
depth++;
@ -243,6 +245,15 @@ public final class ParseBenchmark {
case VALUE_NUMBER_FLOAT:
jp.getLongValue();
break;
case VALUE_TRUE:
case VALUE_FALSE:
jp.getBooleanValue();
break;
case VALUE_NULL:
// Do nothing; nextToken() will advance in stream
break;
default:
throw new IllegalArgumentException("Unexpected token " + token);
}
} while (depth > 0);
jp.close();

View File

@ -75,7 +75,6 @@
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>