Respackopts/src/main/java/io/gitlab/jfronny/respackopts/filters/util/FileExpansionProvider.java

46 lines
2.0 KiB
Java
Raw Normal View History

2021-09-15 16:45:54 +02:00
package io.gitlab.jfronny.respackopts.filters.util;
2021-08-24 17:42:46 +02:00
import io.gitlab.jfronny.libjf.data.ResourcePath;
import io.gitlab.jfronny.libjf.data.WrappedPack;
import io.gitlab.jfronny.respackopts.Respackopts;
import io.gitlab.jfronny.respackopts.data.FileRpo;
2021-08-24 17:42:46 +02:00
import meteordevelopment.starscript.Script;
import java.io.*;
import java.util.Map;
2021-09-15 16:45:54 +02:00
public class FileExpansionProvider {
2021-08-24 17:42:46 +02:00
public static synchronized InputStream replace(InputStream is, Map<String, Script> expansions) throws IOException {
String s = new String(is.readAllBytes());
for (Map.Entry<String, Script> entry : expansions.entrySet()) {
s = s.replace("${" + entry.getKey() + "}", Respackopts.STAR_SCRIPT.run(entry.getValue()));
}
return new ByteArrayInputStream(s.getBytes());
}
//TODO move check to see if file has rpo (and parse it if it does) to shared location
public static InputStream replace(InputStream inputStream, WrappedPack pack, String name, IOException ex) throws IOException {
if (name.endsWith(Respackopts.FILE_EXTENSION))
return inputStream;
ResourcePath rpoPath;
try {
rpoPath = new ResourcePath(name + Respackopts.FILE_EXTENSION);
if (!pack.contains(rpoPath.getType(), rpoPath.getId()))
return inputStream;
} catch (Throwable e) {
Respackopts.LOGGER.error("Could not check file filter status", e);
return inputStream;
}
try (InputStream stream = pack.open(rpoPath.getType(), rpoPath.getId()); Reader w = new InputStreamReader(stream)) {
FileRpo rpo = Respackopts.GSON.fromJson(w, FileRpo.class);
2021-08-24 17:42:46 +02:00
if (rpo.expansions == null || rpo.expansions.isEmpty())
return inputStream;
return replace(inputStream, rpo.expansions);
}
catch (Exception e) {
Respackopts.LOGGER.error("Could not generate replacement for " + name + " in " + pack.getName(), e);
}
throw ex;
}
}