Resclone/src/main/java/io/gitlab/jfronny/resclone/util/config/RescloneConfigTypeAdapter.java

66 lines
3.1 KiB
Java

package io.gitlab.jfronny.resclone.util.config;
import com.google.gson.reflect.TypeToken;
import io.gitlab.jfronny.commons.serialize.gson.api.v1.GsonHolders;
import io.gitlab.jfronny.gson.JsonParseException;
import io.gitlab.jfronny.gson.TypeAdapter;
import io.gitlab.jfronny.gson.stream.*;
import io.gitlab.jfronny.resclone.data.PackMetaUnloaded;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Set;
public class RescloneConfigTypeAdapter extends TypeAdapter<RescloneConfig> {
private static final String PACKS = "packs";
private static final String PRUNE_UNUSED = "pruneUnused";
private static final Type META_SET = new TypeToken<Set<PackMetaUnloaded>>(){}.getType();
@Override
public RescloneConfig read(JsonReader jsonReader) throws IOException {
if (jsonReader.peek() == JsonToken.BEGIN_ARRAY) {
// Legacy format compatibility
return new RescloneConfig(GsonHolders.CONFIG.getGson().fromJson(jsonReader, META_SET), false, true);
} else if (jsonReader.peek() == JsonToken.BEGIN_OBJECT) {
// New format
jsonReader.beginObject();
Set<PackMetaUnloaded> packs = null;
Boolean pruneUnused = null;
boolean updateRequired = false;
while (jsonReader.peek() != JsonToken.END_OBJECT) {
final String name = jsonReader.nextName();
switch (name) {
case PACKS -> {
if (packs != null) throw new JsonParseException("Unexpected duplicate \"" + PACKS + "\" in Resclone config");
packs = GsonHolders.CONFIG.getGson().fromJson(jsonReader, META_SET);
}
case PRUNE_UNUSED -> {
if (pruneUnused != null) throw new JsonParseException("Unexpected duplicate \"" + PRUNE_UNUSED + "\" in Resclone config");
pruneUnused = jsonReader.nextBoolean();
}
default -> throw new JsonParseException("Unexpected element: \"" + name + "\" in Resclone config");
}
}
jsonReader.endObject();
if (packs == null) throw new JsonParseException("Expected Resclone config object to contain packs");
if (pruneUnused == null) {
pruneUnused = true;
updateRequired = true;
}
return new RescloneConfig(packs, pruneUnused, updateRequired);
} else throw new JsonParseException("Expected Resclone config to be an object or array");
}
@Override
public void write(JsonWriter jsonWriter, RescloneConfig rescloneConfig) throws IOException {
jsonWriter.beginObject()
.comment("The packs to be loaded by resclone")
.name(PACKS);
GsonHolders.CONFIG.getGson().toJson(rescloneConfig.packs(), META_SET, jsonWriter);
jsonWriter.comment("Whether to prune unused packs from the cache")
.name(PRUNE_UNUSED)
.value(rescloneConfig.pruneUnused())
.endObject();
}
}