Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change json dependency to use org.json #123

Open
wants to merge 6 commits into
base: nimak/add-werror
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 22 additions & 26 deletions annotator-core/src/main/java/edu/ucr/cs/riple/core/Config.java
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,8 @@
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.JSONArray;
import org.json.JSONObject;

/**
* Config class for Annotator. Different flags can be set with either command line arguments or an
Expand Down Expand Up @@ -470,13 +469,11 @@ public Config(Path configPath) {
Preconditions.checkNotNull(configPath);
JSONObject jsonObject;
try {
Object obj =
new JSONParser().parse(Files.newBufferedReader(configPath, Charset.defaultCharset()));
jsonObject = (JSONObject) obj;
jsonObject = new JSONObject(Files.readString(configPath, Charset.defaultCharset()));
} catch (Exception e) {
throw new RuntimeException("Error in reading/parsing config at path: " + configPath, e);
}
this.depth = getValueFromKey(jsonObject, "DEPTH", Long.class).orElse((long) 1).intValue();
this.depth = getValueFromKey(jsonObject, "DEPTH", Integer.class).orElse(1);
this.chain = getValueFromKey(jsonObject, "CHAIN", Boolean.class).orElse(false);
this.redirectBuildOutputToStdErr =
getValueFromKey(jsonObject, "REDIRECT_BUILD_OUTPUT_TO_STDERR", Boolean.class).orElse(false);
Expand All @@ -501,7 +498,7 @@ public Config(Path configPath) {
getArrayValueFromKey(
jsonObject,
"CONFIG_PATHS",
instance -> ModuleInfo.buildFromJson(getNextModuleUniqueID(), globalDir, instance),
instance -> ModuleInfo.buildFromMap(getNextModuleUniqueID(), globalDir, instance),
ModuleInfo.class)
.orElse(Collections.emptyList());
this.target = moduleInfoList.get(0);
Expand Down Expand Up @@ -646,24 +643,24 @@ private <T> OrElse<T> getValueFromKey(JSONObject json, String key, Class<T> klas
try {
ArrayList<String> keys = new ArrayList<>(Arrays.asList(key.split(":")));
while (keys.size() != 1) {
if (json.containsKey(keys.get(0))) {
if (json.has(keys.get(0))) {
json = (JSONObject) json.get(keys.get(0));
keys.remove(0);
} else {
return new OrElse<>(null, klass);
}
}
return json.containsKey(keys.get(0))
return json.has(keys.get(0))
? new OrElse<>(json.get(keys.get(0)), klass)
: new OrElse<>(null, klass);
} catch (Exception e) {
return new OrElse<>(null, klass);
}
}

@SuppressWarnings({"SameParameterValue", "unchecked"})
@SuppressWarnings("SameParameterValue")
private <T> ListOrElse<T> getArrayValueFromKey(
JSONObject json, String key, Function<JSONObject, T> mapper, Class<T> klass) {
JSONObject json, String key, Function<Map<?, ?>, T> mapper, Class<T> klass) {
if (json == null) {
return new ListOrElse<>(null, klass);
}
Expand All @@ -672,7 +669,9 @@ private <T> ListOrElse<T> getArrayValueFromKey(
return new ListOrElse<>(null, klass);
} else {
if (jsonValue.value instanceof JSONArray) {
return new ListOrElse<>(((JSONArray) jsonValue.value).stream().map(mapper), klass);
return new ListOrElse<>(
((JSONArray) jsonValue.value).toList().stream().map(o -> mapper.apply((Map<?, ?>) o)),
klass);
}
throw new IllegalStateException(
"Expected type to be json array, found: " + jsonValue.value.getClass());
Expand Down Expand Up @@ -742,7 +741,6 @@ public static class Builder {
public Set<SourceType> sourceTypes = new HashSet<>();
public int depth = 1;

@SuppressWarnings("unchecked")
public void write(Path path) {
Preconditions.checkNotNull(
buildCommand, "Build command must be initialized to construct the config.");
Expand Down Expand Up @@ -773,16 +771,15 @@ public void write(Path path) {
json.put("FORCE_RESOLVE", forceResolveActivation);
json.put("INFERENCE_ACTIVATION", inferenceActivated);
JSONArray configPathsJson = new JSONArray();
configPathsJson.addAll(
configPaths.stream()
.map(
info -> {
JSONObject res = new JSONObject();
res.put("NULLAWAY", info.nullawayConfig.toString());
res.put("SCANNER", info.scannerConfig.toString());
return res;
})
.collect(Collectors.toList()));
configPaths.stream()
.map(
info -> {
JSONObject res = new JSONObject();
res.put("NULLAWAY", info.nullawayConfig.toString());
res.put("SCANNER", info.scannerConfig.toString());
return res;
})
.forEach(configPathsJson::put);
json.put("CONFIG_PATHS", configPathsJson);
JSONObject downstreamDependency = new JSONObject();
downstreamDependency.put("ACTIVATION", downStreamDependenciesAnalysisActivated);
Expand All @@ -809,10 +806,9 @@ public void write(Path path) {
processors.put(sourceType.name(), st);
});
json.put("PROCESSORS", processors);

try (BufferedWriter file =
Files.newBufferedWriter(path.toFile().toPath(), Charset.defaultCharset())) {
file.write(json.toJSONString());
json.write(file);
} catch (IOException e) {
System.err.println("Error happened in writing config json: " + e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Objects;
import org.json.simple.JSONObject;

/** Container class to hold paths to nullaway and scanner config files. */
public class ModuleInfo {
Expand All @@ -41,16 +41,19 @@ public class ModuleInfo {
public final Path dir;

/**
* Creates an instance of {@link ModuleInfo} from the given json object.
* Creates an instance of {@link ModuleInfo} from the given map object. This method is used in
* constructing {@link ModuleInfo} instances from a JSON object. Please note that array of
* dictionaries in json are parsed to {@link org.json.JSONArray} of maps. This method is called on
* each dictionary stored in the parsed collection to create the corresponding instance.
*
* @param id Global unique id for this module.
* @param globalDir Global path for all Annotator/Scanner/NullAway outputs.
* @param jsonObject Json Object to retrieve values.
* @param mapFromJSON Map Object to retrieve require values.
* @return An instance of {@link ModuleInfo}.
*/
public static ModuleInfo buildFromJson(int id, Path globalDir, JSONObject jsonObject) {
String nullawayConfigPath = (String) jsonObject.get("NULLAWAY");
String scannerConfigPath = (String) jsonObject.get("SCANNER");
public static ModuleInfo buildFromMap(int id, Path globalDir, Map<?, ?> mapFromJSON) {
String nullawayConfigPath = (String) mapFromJSON.get("NULLAWAY");
String scannerConfigPath = (String) mapFromJSON.get("SCANNER");
if (nullawayConfigPath == null || scannerConfigPath == null) {
throw new IllegalArgumentException(
"Both paths to NullAway and Scanner config files must be set with NULLAWAY and SCANNER keys!");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
import edu.ucr.cs.riple.injector.location.OnParameter;
import java.util.Objects;
import java.util.function.Consumer;
import org.json.simple.JSONObject;
import org.json.JSONObject;

/**
* Stores information suggesting adding @Nullable on an element in source code. These suggestions
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
import java.nio.file.Path;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
Expand All @@ -60,8 +61,8 @@
import javax.xml.transform.stream.StreamResult;
import me.tongfei.progressbar.ProgressBar;
import me.tongfei.progressbar.ProgressBarStyle;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

Expand Down Expand Up @@ -98,11 +99,10 @@ public static void executeCommand(Config config, String command) {
* @param config Annotator config.
* @param reports Immutable set of reports.
*/
@SuppressWarnings("unchecked")
public static void writeReports(Config config, ImmutableSet<Report> reports) {
Path reportsPath = config.globalDir.resolve("reports.json");
JSONObject result = new JSONObject();
JSONArray reportsJson = new JSONArray();
List<JSONObject> reportsList = new ArrayList<>();
for (Report report : reports) {
JSONObject reportJson = report.root.getJson();
reportJson.put("LOCAL EFFECT", report.localEffect);
Expand All @@ -112,23 +112,25 @@ public static void writeReports(Config config, ImmutableSet<Report> reports) {
reportJson.put("FINISHED", !report.requiresFurtherProcess(config));
JSONArray followUps = new JSONArray();
if (config.chain && report.localEffect < 1) {
followUps.addAll(report.tree.stream().map(Fix::getJson).collect(Collectors.toList()));
report.tree.remove(report.root);
report.tree.stream().map(Fix::getJson).forEach(followUps::put);
}
reportJson.put("TREE", followUps);
reportsJson.add(reportJson);
reportsList.add(reportJson);
}
// Sort by overall effect.
reportsJson.sort(
reportsList.sort(
(o1, o2) -> {
int first = (Integer) ((JSONObject) o1).get("OVERALL EFFECT");
int second = (Integer) ((JSONObject) o2).get("OVERALL EFFECT");
int first = (Integer) o1.get("OVERALL EFFECT");
int second = (Integer) o2.get("OVERALL EFFECT");
return Integer.compare(second, first);
});
JSONArray reportsJson = new JSONArray();
reportsList.forEach(reportsJson::put);
result.put("REPORTS", reportsJson);
try (BufferedWriter writer =
Files.newBufferedWriter(reportsPath.toFile().toPath(), Charset.defaultCharset())) {
writer.write(result.toJSONString().replace("\\/", "/").replace("\\\\\\", "\\"));
writer.flush();
result.write(writer);
} catch (IOException e) {
throw new RuntimeException(
"Could not create the Annotator report json file: " + reportsPath, e);
Expand Down
4 changes: 2 additions & 2 deletions gradle/dependencies.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def versions = [
errorProneApi : project.hasProperty("epApiVersion") ? epApiVersion : oldestErrorProneApi,
autoService : "1.0-rc7",
javaparser : "3.24.0",
json : "1.1.1",
json : "20220924",
guava : "31.0.1-jre",
cli : "1.5.0",
commonsio : "2.11.0",
Expand All @@ -52,7 +52,7 @@ def apt = [

def build = [
guava : "com.google.guava:guava:${versions.guava}",
json : "com.googlecode.json-simple:json-simple:${versions.json}",
json : "org.json:json:${versions.json}",
progressbar : "me.tongfei:progressbar:${versions.progressbar}",
javaparser : "com.github.javaparser:javaparser-core:${versions.javaparser}",
commonscli : "commons-cli:commons-cli:${versions.cli}",
Expand Down
1 change: 1 addition & 0 deletions injector/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ dependencies {
implementation deps.build.progressbar

testImplementation deps.build.commonsio
testImplementation 'junit:junit:4.13.1'
}

compileJava.mustRunAfter verifyGoogleJavaFormat
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

import edu.ucr.cs.riple.injector.location.Location;
import java.util.Objects;
import org.json.simple.JSONObject;
import org.json.JSONObject;

/** Used to add annotations on elements in source code. */
public abstract class AddAnnotation extends Change {
Expand All @@ -34,7 +34,6 @@ public AddAnnotation(Location location, String annotation) {
}

@Override
@SuppressWarnings("unchecked")
public JSONObject getJson() {
JSONObject res = super.getJson();
res.put("INJECT", true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
import edu.ucr.cs.riple.injector.modifications.Modification;
import java.util.Objects;
import javax.annotation.Nullable;
import org.json.simple.JSONObject;
import org.json.JSONObject;

/** Represents a change in the AST of the source code. */
public abstract class Change {
Expand Down Expand Up @@ -86,7 +86,6 @@ public int hashCode() {
return Objects.hash(location, annotation);
}

@SuppressWarnings("unchecked")
public JSONObject getJson() {
JSONObject res = new JSONObject();
res.put("LOCATION", location.getJson());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Nullable;
import org.json.simple.JSONObject;
import org.json.JSONObject;

/**
* Used to remove <a
Expand Down Expand Up @@ -65,7 +65,6 @@ public <T extends NodeWithAnnotations<?> & NodeWithRange<?>> Modification visit(
}

@Override
@SuppressWarnings("unchecked")
public JSONObject getJson() {
JSONObject res = super.getJson();
res.put("INJECT", false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
import java.util.Objects;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import org.json.simple.JSONObject;
import org.json.JSONObject;

/** Represents a location of an element in the source code. */
public abstract class Location {
Expand Down Expand Up @@ -154,12 +154,11 @@ public Modification apply(CompilationUnit tree, Change change) {
return applyToMember(clazz, change);
}

@SuppressWarnings("unchecked")
public JSONObject getJson() {
JSONObject res = new JSONObject();
res.put(KEYS.CLASS, clazz);
res.put(KEYS.KIND, type.toString());
res.put(KEYS.PATH, path);
res.put(KEYS.CLASS.toString(), clazz);
res.put(KEYS.KIND.toString(), type.toString());
res.put(KEYS.PATH.toString(), path);
fillJsonInformation(res);
return res;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
import java.util.Optional;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import org.json.simple.JSONObject;
import org.json.JSONObject;

/** Represents a location for class element. This location is used to apply changes to a class. */
public class OnClass extends Location {
Expand Down Expand Up @@ -67,6 +67,9 @@ protected Modification applyToMember(NodeList<BodyDeclaration<?>> members, Chang
return change.visit(((BodyDeclaration<?>) optionalClass.get()));
}

@Override
protected void fillJsonInformation(JSONObject res) {}

/**
* Checks if flat name is for an anonymous class.
*
Expand All @@ -76,11 +79,6 @@ public static boolean isAnonymousClassFlatName(String flatName) {
return anonymousClassPattern.matcher(flatName).matches();
}

@Override
protected void fillJsonInformation(JSONObject res) {
// no op
}

@Override
public String toString() {
return "OnClass{" + "type=" + type + ", clazz='" + clazz + '\'' + ", path=" + path + '}';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.JSONArray;
import org.json.JSONObject;

/**
* Represents a location for field element. This location is used to apply changes to a class field.
Expand Down Expand Up @@ -68,12 +68,11 @@ public OnField(String path, String clazz, Set<String> variables) {
this(Helper.deserializePath(path), clazz, variables);
}

@SuppressWarnings("unchecked")
@Override
protected void fillJsonInformation(JSONObject res) {
JSONArray fields = new JSONArray();
fields.addAll(variables);
res.put(KEYS.VARIABLES, fields);
variables.forEach(fields::put);
res.put(KEYS.VARIABLES.toString(), fields);
}

@Override
Expand Down
Loading