Skip to content

Commit

Permalink
Merge pull request #43039 from Shadow-Devil/simpler-typetoken-usage
Browse files Browse the repository at this point in the history
[Refactoring] Simpler usage of TypeToken for Gson deserialization
  • Loading branch information
gimantha authored Sep 14, 2024
2 parents 124fdd1 + 1b4b5b2 commit 347ff76
Show file tree
Hide file tree
Showing 12 changed files with 85 additions and 113 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -173,9 +173,7 @@ public static void createReflectConfig(Path nativeConfigPath, Package currentPac
if (mockedFunctionClassFile.isFile()) {
BufferedReader br = Files.newBufferedReader(mockedFunctionClassPath, StandardCharsets.UTF_8);
Gson gsonRead = new Gson();
Map<String, String[]> testFileMockedFunctionMapping = gsonRead.fromJson(br,
new TypeToken<Map<String, String[]>>() {
}.getType());
Map<String, String[]> testFileMockedFunctionMapping = gsonRead.fromJson(br, new TypeToken<>() { });
if (!testFileMockedFunctionMapping.isEmpty()) {
ReflectConfigClass originalTestFileRefConfClz;
for (Map.Entry<String, String[]> testFileMockedFunctionMappingEntry :
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -426,8 +426,7 @@ private static void writeDeprecatedMsg(Path metaFilePath, LogFormatter logFormat
* @return converted list of strings
*/
static List<String> getAsList(String arrayString) {
return new Gson().fromJson(arrayString, new TypeToken<List<String>>() {
}.getType());
return new Gson().fromJson(arrayString, new TypeToken<>() { });
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
Expand Down Expand Up @@ -111,8 +110,7 @@ private static InputStream getSyntaxTreeStream(TreeGenConfig config) {
private static HashMap<String, SyntaxNodeMetadata> getNodeMetadataMap(TreeGenConfig config) {
try (InputStreamReader reader =
new InputStreamReader(getNodeMetadataMapStream(config), StandardCharsets.UTF_8)) {
Type mapType = new TypeToken<HashMap<String, SyntaxNodeMetadata>>() { }.getType();
return new Gson().fromJson(reader, mapType);
return new Gson().fromJson(reader, new TypeToken<>() { });
} catch (Throwable e) {
throw new TreeGenException("Failed to parse syntax node metadata. Reason: " + e.getMessage(), e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
import org.testng.annotations.Test;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Map;
Expand All @@ -55,9 +54,7 @@ public void test(String configFileName) throws IOException {
.resolve("schema_visitor").resolve("schema").resolve(schemaFile).toString());

Gson gson = new Gson();
Type collectionType = new TypeToken<Map<String, Map<String, CompletionItem>>>() {
}.getType();
Map<String, Map<String, CompletionItem>> expectedMap = gson.fromJson(expected, collectionType);
Map<String, Map<String, CompletionItem>> expectedMap = gson.fromJson(expected, new TypeToken<>() { });

Schema validationSchema = Schema.from(schemaString);
TomlSchemaVisitor visitor = new TomlSchemaVisitor();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@

import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
Expand All @@ -50,8 +49,7 @@
public class BallerinaExampleService implements ExtendedLanguageServerService {
private static final String BBE_DEF_JSON = "index.json";
private static final String EXAMPLES_DIR = "examples";
private static final Type EXAMPLE_CATEGORY_TYPE = new TypeToken<List<BallerinaExampleCategory>>() {
}.getType();
private static final TypeToken<List<BallerinaExampleCategory>> EXAMPLE_CATEGORY_TYPE = new TypeToken<>() { };
private LSClientLogger clientLogger;

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@
*/
package org.ballerinalang.langserver.codeaction;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import org.ballerinalang.langserver.AbstractLSTest;
import org.ballerinalang.langserver.common.constants.CommandConstants;
import org.ballerinalang.langserver.common.utils.PathUtil;
Expand Down Expand Up @@ -52,7 +52,6 @@

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
Expand Down Expand Up @@ -161,9 +160,7 @@ public void test(String config) throws IOException, WorkspaceDocumentException {
.getAsJsonArray().get(0).getAsJsonObject().get("edits");
}

Type type = new TypeToken<List<TextEdit>>() {
}.getType();
List<TextEdit> actualEdit = gson.fromJson(editsElement, type);
List<TextEdit> actualEdit = gson.fromJson(editsElement, new TypeToken<>() { });
List<TextEdit> expEdit = expected.edits;
actual.edits = actualEdit;
if (!expEdit.equals(actualEdit)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
Expand Down Expand Up @@ -68,10 +67,8 @@ public void test(String config, String configPath) throws WorkspaceDocumentExcep
TestConfig testConfig = gson.fromJson(Files.newBufferedReader(configJsonPath), TestConfig.class);
String response = getResponse(testConfig);
JsonObject json = JsonParser.parseString(response).getAsJsonObject();
Type collectionType = new TypeToken<List<CompletionItem>>() {
}.getType();
JsonArray resultList = json.getAsJsonObject("result").getAsJsonArray("left");
List<CompletionItem> responseItemList = gson.fromJson(resultList, collectionType);
List<CompletionItem> responseItemList = gson.fromJson(resultList, new TypeToken<>() { });

boolean result = CompletionTestUtil.isSubList(testConfig.getItems(), responseItemList);
if (!result) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@
*/
package org.ballerinalang.langserver.inlayhint;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import org.ballerinalang.langserver.AbstractLSTest;
import org.ballerinalang.langserver.commons.workspace.WorkspaceDocumentException;
import org.ballerinalang.langserver.util.FileUtils;
Expand All @@ -38,7 +38,6 @@

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
Expand Down Expand Up @@ -72,13 +71,11 @@ public void test(String config, String source) throws WorkspaceDocumentException
inlayHintParams.setTextDocument(textDocumentIdentifier);
Range range = testConfig.range;

Type collectionType = new TypeToken<List<InlayHint>>() {
}.getType();
String response = getResponse(sourcePath.toString(), range, sourcePath.toString());
JsonObject json = JsonParser.parseString(response).getAsJsonObject();

JsonArray resultList = json.getAsJsonArray("result");
List<InlayHint> responseItemList = gson.fromJson(resultList, collectionType);
List<InlayHint> responseItemList = gson.fromJson(resultList, new TypeToken<>() { });

if (responseItemList.size() != testConfig.getResult().size()) {
// updateConfig(configPath, testConfig, responseItemList);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -437,9 +437,7 @@ private String getGeneratedRecordMapping(CodeActionContext context, String found
rightRecordJSON.addProperty(TYPE, "object");
rightRecordJSON.add(PROPERTIES, rightSchema);

Map<String, Object> rightSchemaMap = new Gson().fromJson(rightSchema,
new TypeToken<HashMap<String, Object>>() {
}.getType());
Map<String, Object> rightSchemaMap = new Gson().fromJson(rightSchema, new TypeToken<>() { });
this.isOptionalMap.clear();
generateOptionalMap(rightSchemaMap, foundTypeRight);

Expand All @@ -452,9 +450,7 @@ private String getGeneratedRecordMapping(CodeActionContext context, String found
leftRecordJSON.addProperty(TYPE, "object");
leftRecordJSON.add(PROPERTIES, leftSchema);

Map<String, Object> leftSchemaMap = new Gson().fromJson(leftSchema,
new TypeToken<HashMap<String, Object>>() {
}.getType());
Map<String, Object> leftSchemaMap = new Gson().fromJson(leftSchema, new TypeToken<>() { });
this.leftFieldMap.clear();
getLeftFields(leftSchemaMap, "");
}
Expand Down Expand Up @@ -876,8 +872,7 @@ private String generateMappingFunction(String mappingFromServer, String foundTyp
try {
Map<String, Object> responseMap = new Gson().fromJson(
JsonParser.parseString(mappingFromServer).getAsJsonObject(),
new TypeToken<HashMap<String, Object>>() {
}.getType());
new TypeToken<>() { });
getResponseKeys(responseMap, "");
HashSet<String> unionKeys = new HashSet<>(this.responseFieldMap.keySet());
unionKeys.addAll(this.leftFieldMap.keySet());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,85 +81,82 @@ public static void main(String[] args) throws IOException {
int exitStatus = 0;
int result;

if (args.length >= 4) { //running using the suite json
boolean isFatJarExecution = Boolean.parseBoolean(args[0]);
Path testSuiteJsonPath = Paths.get(args[1]);
Path targetPath = Paths.get(args[2]);
Path testCache = targetPath.resolve(ProjectConstants.CACHES_DIR_NAME)
.resolve(ProjectConstants.TESTS_CACHE_DIR_NAME);
String jacocoAgentJarPath = args[3];
boolean report = Boolean.parseBoolean(args[4]);
boolean coverage = Boolean.parseBoolean(args[5]);

if (report || coverage) {
testReport = new TestReport();
}
if (args.length < 4) {
Runtime.getRuntime().exit(1);
}
//running using the suite json
boolean isFatJarExecution = Boolean.parseBoolean(args[0]);
Path testSuiteJsonPath = Paths.get(args[1]);
Path targetPath = Paths.get(args[2]);
Path testCache = targetPath.resolve(ProjectConstants.CACHES_DIR_NAME)
.resolve(ProjectConstants.TESTS_CACHE_DIR_NAME);
String jacocoAgentJarPath = args[3];
boolean report = Boolean.parseBoolean(args[4]);
boolean coverage = Boolean.parseBoolean(args[5]);

if (report || coverage) {
testReport = new TestReport();
}

out.println();
out.print("Running Tests");
if (coverage) {
out.print(" with Coverage");
}
out.println();

out.println();
out.print("Running Tests");
if (coverage) {
out.print(" with Coverage");
try (InputStream is = isFatJarExecution ?
BTestMain.class.getResourceAsStream(TesterinaConstants.PATH_SEPARATOR + testSuiteJsonPath) : null) {
BufferedReader br;
if (is != null) {
br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
} else {
br = Files.newBufferedReader(testSuiteJsonPath, StandardCharsets.UTF_8);
}
out.println();

try (InputStream is = isFatJarExecution ?
BTestMain.class.getResourceAsStream(TesterinaConstants.PATH_SEPARATOR
+ testSuiteJsonPath)
: null) {
BufferedReader br;
if (is != null) {
br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
} else {
br = Files.newBufferedReader(testSuiteJsonPath, StandardCharsets.UTF_8);
}
Gson gson = new Gson();
Map<String, TestSuite> testSuiteMap = gson.fromJson(br,
new TypeToken<Map<String, TestSuite>>() { }.getType());
if (!testSuiteMap.isEmpty()) {
for (Map.Entry<String, TestSuite> entry : testSuiteMap.entrySet()) {
String moduleName = entry.getKey();
TestSuite testSuite = entry.getValue();
String packageName = testSuite.getPackageName();
out.println("\n\t" + (moduleName.equals(packageName) ?
(moduleName.equals(TesterinaConstants.DOT) ? testSuite.getSourceFileName() : moduleName)
: packageName + TesterinaConstants.DOT + moduleName));

testSuite.setModuleName(moduleName);
List<String> testExecutionDependencies = testSuite.getTestExecutionDependencies();

if (isFatJarExecution && !testSuite.getMockFunctionNamesMap().isEmpty()) {
classLoader = createInitialCustomClassLoader();
} else {
// Even if it is fat jar execution but there are no mock functions,
// We can use the URLClassLoader
classLoader = createURLClassLoader(getURLList(testExecutionDependencies));
}
Gson gson = new Gson();
Map<String, TestSuite> testSuiteMap = gson.fromJson(br, new TypeToken<>() { });
if (!testSuiteMap.isEmpty()) {
for (Map.Entry<String, TestSuite> entry : testSuiteMap.entrySet()) {
String moduleName = entry.getKey();
TestSuite testSuite = entry.getValue();
String packageName = testSuite.getPackageName();
out.println("\n\t" + (moduleName.equals(packageName) ?
(moduleName.equals(TesterinaConstants.DOT) ? testSuite.getSourceFileName() : moduleName)
: packageName + TesterinaConstants.DOT + moduleName));

testSuite.setModuleName(moduleName);
List<String> testExecutionDependencies = testSuite.getTestExecutionDependencies();

if (isFatJarExecution && !testSuite.getMockFunctionNamesMap().isEmpty()) {
classLoader = createInitialCustomClassLoader();
} else {
// Even if it is fat jar execution but there are no mock functions,
// We can use the URLClassLoader
classLoader = createURLClassLoader(getURLList(testExecutionDependencies));
}

if (!testSuite.getMockFunctionNamesMap().isEmpty()) {
if (coverage) {
testExecutionDependencies.add(jacocoAgentJarPath);
}
String instrumentDir = testCache.resolve(TesterinaConstants.COVERAGE_DIR)
.resolve(TesterinaConstants.JACOCO_INSTRUMENTED_DIR).toString();
replaceMockedFunctions(testSuite, testExecutionDependencies, instrumentDir,
coverage, isFatJarExecution);
}
String[] testArgs = new String[]{targetPath.toString(), packageName, moduleName};
for (int i = 4; i < args.length; i++) {
testArgs = Arrays.copyOf(testArgs, testArgs.length + 1);
testArgs[testArgs.length - 1] = args[i];
if (!testSuite.getMockFunctionNamesMap().isEmpty()) {
if (coverage) {
testExecutionDependencies.add(jacocoAgentJarPath);
}
result = startTestSuit(Paths.get(testSuite.getSourceRootPath()), testSuite, classLoader,
testArgs);
exitStatus = (result == 1) ? result : exitStatus;
String instrumentDir = testCache.resolve(TesterinaConstants.COVERAGE_DIR)
.resolve(TesterinaConstants.JACOCO_INSTRUMENTED_DIR).toString();
replaceMockedFunctions(testSuite, testExecutionDependencies, instrumentDir,
coverage, isFatJarExecution);
}
} else {
exitStatus = 1;
String[] testArgs = new String[]{targetPath.toString(), packageName, moduleName};
for (int i = 4; i < args.length; i++) {
testArgs = Arrays.copyOf(testArgs, testArgs.length + 1);
testArgs[testArgs.length - 1] = args[i];
}
result = startTestSuit(Paths.get(testSuite.getSourceRootPath()), testSuite, classLoader,
testArgs);
exitStatus = (result == 1) ? result : exitStatus;
}
br.close();
} else {
exitStatus = 1;
}
} else {
exitStatus = 1;
br.close();
}
Runtime.getRuntime().exit(exitStatus);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ private void modifyCoverageNumbers() {

/**
* As implemented in Jacoco API.
* org.jacoco.core.internal.analysis.CounterImpl#getValue(org.jacoco.core.analysis.ICounter.CounterValue)
* {@link org.jacoco.core.internal.analysis.CounterImpl#getValue(org.jacoco.core.analysis.ICounter.CounterValue)}
*/
@Override
public double getValue(CounterValue value) {
Expand Down Expand Up @@ -94,7 +94,7 @@ public double getMissedRatio() {
}

/**
* As implemented in org.jacoco.core.internal.analysis.CounterImpl#getStatus().
* As implemented in {@link org.jacoco.core.internal.analysis.CounterImpl#getStatus()}.
*/
@Override
public int getStatus() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
Expand Down Expand Up @@ -169,7 +168,7 @@ private static String normalizeRegexPattern(String pattern) {
private static boolean isIncluded(String path, String includesInCoverage) {
boolean isIncluded = false;
if (includesInCoverage != null) {
List<String> includedPackages = Arrays.asList(includesInCoverage.split(":"));
String[] includedPackages = includesInCoverage.split(":");
for (String packageName : includedPackages) {
packageName = packageName.replace(".", "/");
Pattern pattern = Pattern.compile(normalizeRegexPattern(packageName));
Expand Down

0 comments on commit 347ff76

Please sign in to comment.