WarpPI/src/main/java/org/warp/picalculator/math/rules/RulesManager.java

235 lines
9.7 KiB
Java
Raw Normal View History

2017-12-21 23:21:29 +01:00
package org.warp.picalculator.math.rules;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
2017-12-23 01:14:38 +01:00
import java.io.InputStream;
2018-03-22 20:40:41 +01:00
import java.io.PrintWriter;
2017-12-21 23:21:29 +01:00
import java.net.URISyntaxException;
import java.net.URL;
2018-03-22 20:40:41 +01:00
import java.net.URLClassLoader;
2017-12-21 23:21:29 +01:00
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
2018-03-22 10:06:31 +01:00
import java.nio.file.StandardOpenOption;
2018-05-09 22:54:00 +02:00
import java.util.ArrayList;
2017-12-21 23:21:29 +01:00
import java.util.List;
2018-05-09 22:54:00 +02:00
import java.util.stream.Stream;
2017-12-23 15:20:42 +01:00
import org.warp.picalculator.Error;
2017-12-22 22:39:58 +01:00
import org.warp.picalculator.Utils;
2017-12-23 15:20:42 +01:00
import org.warp.picalculator.math.Function;
2017-12-21 23:21:29 +01:00
import org.warp.picalculator.math.MathContext;
2017-12-23 15:20:42 +01:00
import org.warp.picalculator.math.functions.Expression;
2017-12-21 23:21:29 +01:00
import org.warp.picalculator.math.functions.Variable;
import org.warp.picalculator.math.functions.Variable.V_TYPE;
2018-03-01 09:54:14 +01:00
import org.warp.picalculator.math.solver.MathSolver;
2017-12-21 23:21:29 +01:00
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
public class RulesManager {
2018-05-12 21:18:29 +02:00
2017-12-21 23:21:29 +01:00
public static ObjectArrayList<Rule>[] rules;
2018-05-12 21:18:29 +02:00
private RulesManager() {}
2017-12-21 23:21:29 +01:00
@SuppressWarnings("unchecked")
public static void initialize() {
2018-03-22 20:40:41 +01:00
Utils.out.println(Utils.OUTPUTLEVEL_NODEBUG, "RulesManager", "Loading the rules");
2017-12-21 23:21:29 +01:00
rules = new ObjectArrayList[RuleType.values().length];
2018-05-12 21:18:29 +02:00
for (final RuleType val : RuleType.values()) {
rules[val.ordinal()] = new ObjectArrayList<>();
2017-12-21 23:21:29 +01:00
}
try {
2018-03-26 09:01:26 +02:00
boolean compiledSomething = false;
2018-05-09 22:54:00 +02:00
final Path defaultRulesPath = Utils.getResource("/default-rules.lst");
if (!Files.exists(defaultRulesPath)) {
throw new FileNotFoundException("default-rules.lst not found!");
2017-12-21 23:21:29 +01:00
}
2018-05-12 21:18:29 +02:00
final List<String> ruleLines = new ArrayList<>();
final Path rulesPath = Paths.get("rules/");
2018-05-09 22:54:00 +02:00
if (rulesPath.toFile().exists()) {
try (Stream<Path> paths = Files.walk(rulesPath)) {
2018-05-12 21:18:29 +02:00
paths.filter(Files::isRegularFile).forEach((Path p) -> {
if (p.toString().endsWith(".java")) {
String path = rulesPath.relativize(p).toString();
path = path.substring(0, path.length() - ".java".length());
ruleLines.add(path);
Utils.out.println(Utils.OUTPUTLEVEL_NODEBUG, "RulesManager", "Found external rule: " + p.toAbsolutePath().toString());
System.err.println(path);
}
});
}
2018-05-09 22:54:00 +02:00
}
ruleLines.addAll(Files.readAllLines(defaultRulesPath));
2018-05-12 21:18:29 +02:00
2018-03-22 20:40:41 +01:00
boolean useCache = false;
2018-05-12 21:18:29 +02:00
final Path tDir = Paths.get(System.getProperty("java.io.tmpdir"), "WarpPi-Calculator").resolve("rules-rt");
2018-03-26 09:01:26 +02:00
// try {
// final Path defaultResource = Utils.getResource("/math-rules-cache.zip");
// }
2018-05-12 21:18:29 +02:00
final Path cacheFilePath = Utils.getResource("/math-rules-cache.zip");//Paths.get(Utils.getJarDirectory().toString()).resolve("math-rules-cache.zip").toAbsolutePath();
2018-03-22 20:40:41 +01:00
if (cacheFilePath.toFile().exists()) {
try {
if (tDir.toFile().exists()) {
tDir.toFile().delete();
}
Utils.unzip(cacheFilePath.toString(), tDir.getParent().toString(), "");
2018-03-26 09:01:26 +02:00
useCache = !Utils.debugCache;
2018-05-12 21:18:29 +02:00
} catch (final Exception ex) {
2018-03-22 20:40:41 +01:00
ex.printStackTrace();
}
}
2018-05-12 21:18:29 +02:00
for (final String rulesLine : ruleLines) {
2017-12-24 11:59:09 +01:00
if (rulesLine.length() > 0) {
2018-05-12 21:18:29 +02:00
final String[] ruleDetails = rulesLine.split(",", 1);
final String ruleName = ruleDetails[0];
final String ruleNameEscaped = ruleName.replace(".", "_");
2018-03-22 20:40:41 +01:00
Utils.out.println(Utils.OUTPUTLEVEL_NODEBUG, "RulesManager", "Evaluating /rules/" + ruleNameEscaped + ".java");
2018-05-12 21:18:29 +02:00
final String pathWithoutExtension = "/rules/" + ruleNameEscaped;
final String scriptFile = pathWithoutExtension + ".java";
final InputStream resourcePath = Utils.getResourceStream(scriptFile);
2017-12-24 11:59:09 +01:00
if (resourcePath == null) {
2018-03-22 10:06:31 +01:00
System.err.println(new FileNotFoundException("/rules/" + ruleName + ".java not found!"));
2017-12-24 11:59:09 +01:00
} else {
2018-03-22 20:40:41 +01:00
Rule r = null;
if (useCache) {
try {
Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_MIN, "RulesManager", ruleName, "Trying to load cached rule");
r = loadClassRuleFromSourceFile(scriptFile, tDir);
if (r != null) {
Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_MIN, "RulesManager", ruleName, "Loaded cached rule");
2018-03-22 10:06:31 +01:00
}
2018-05-12 21:18:29 +02:00
} catch (final Exception e) {
2018-03-22 20:40:41 +01:00
e.printStackTrace();
Utils.out.println(Utils.OUTPUTLEVEL_NODEBUG, "RulesManager", ruleName, "Can't load the rule!");
2018-03-22 10:06:31 +01:00
}
}
2018-03-22 20:40:41 +01:00
if (r == null || !useCache) {
Utils.out.println(Utils.OUTPUTLEVEL_DEBUG_MIN, "RulesManager", ruleName, "This rule is not cached. Compiling");
2018-03-22 10:06:31 +01:00
try {
2018-03-22 20:40:41 +01:00
r = compileJavaRule(scriptFile, tDir);
2018-03-26 09:01:26 +02:00
compiledSomething = true;
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | IOException e) {
2018-03-22 10:06:31 +01:00
e.printStackTrace();
}
2018-05-12 21:18:29 +02:00
2018-03-22 10:06:31 +01:00
}
if (r != null) {
RulesManager.addRule(r);
}
2017-12-24 11:59:09 +01:00
}
2017-12-21 23:21:29 +01:00
}
}
2018-03-22 20:40:41 +01:00
Utils.out.println(Utils.OUTPUTLEVEL_NODEBUG, "RulesManager", "Loaded all the rules successfully");
2018-03-26 09:01:26 +02:00
if (compiledSomething) {
2018-05-09 22:30:15 +02:00
if (cacheFilePath.toFile().exists()) {
cacheFilePath.toFile().delete();
}
2018-03-26 09:01:26 +02:00
Utils.zip(tDir.toString(), cacheFilePath.toString(), "");
Utils.out.println(Utils.OUTPUTLEVEL_NODEBUG, "RulesManager", "Cached the compiled rules");
}
2017-12-21 23:21:29 +01:00
} catch (URISyntaxException | IOException e) {
e.printStackTrace();
System.exit(1);
}
}
2018-05-12 21:18:29 +02:00
public static Rule compileJavaRule(String scriptFile, Path tDir) throws IOException, URISyntaxException,
InstantiationException, IllegalAccessException, ClassNotFoundException {
final InputStream resource = Utils.getResourceStream(scriptFile);
final String text = Utils.read(resource);
final String[] textArray = text.split("\\n", 5);
final String javaClassDeclaration = textArray[2].substring(6);
int extIndex = javaClassDeclaration.lastIndexOf('.');
2018-05-12 21:18:29 +02:00
final String javaClassNameOnly = javaClassDeclaration.substring(extIndex + 1, javaClassDeclaration.length());
final String javaClassNameAndPath = new StringBuilder("org.warp.picalculator.math.rules.").append(javaClassDeclaration).toString();
extIndex = javaClassNameAndPath.lastIndexOf('.');
2018-05-12 21:18:29 +02:00
final String javaCode = new StringBuilder("package ").append(javaClassNameAndPath.substring(0, extIndex >= 0 ? extIndex : javaClassNameAndPath.length())).append(";\n").append(textArray[4]).toString();
final Path tDirPath = tDir.resolve(javaClassNameAndPath.replace('.', File.separatorChar)).getParent();
final Path tFileJava = tDirPath.resolve(javaClassNameOnly + ".java");
final Path tFileClass = tDirPath.resolve(javaClassNameOnly + ".class");
2018-03-22 20:40:41 +01:00
if (!tDirPath.toFile().exists()) {
Files.createDirectories(tDirPath);
}
2018-03-26 09:01:26 +02:00
if (tFileJava.toFile().exists()) {
tFileJava.toFile().delete();
}
2018-03-22 20:40:41 +01:00
Files.write(tFileJava, javaCode.getBytes("UTF-8"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
2018-05-12 21:18:29 +02:00
final boolean compiled = org.eclipse.jdt.internal.compiler.batch.Main.compile(new String[] { "-nowarn", "-1.8", tFileJava.toString() }, new PrintWriter(System.out), new PrintWriter(System.err), null);
2018-03-26 09:01:26 +02:00
if (Utils.debugCache) {
2018-03-22 20:40:41 +01:00
tFileJava.toFile().deleteOnExit();
} else {
tFileJava.toFile().delete();
}
if (compiled) {
tFileClass.toFile().deleteOnExit();
return loadClassRuleDirectly(javaClassNameAndPath, tDir);
} else {
throw new IOException("Can't build script file '" + scriptFile + "'");
}
}
2018-05-12 21:18:29 +02:00
public static Rule loadClassRuleFromSourceFile(String scriptFile, Path tDir) throws IOException, URISyntaxException,
InstantiationException, IllegalAccessException, ClassNotFoundException {
final InputStream resource = Utils.getResourceStream(scriptFile);
final String text = Utils.read(resource);
final String[] textArray = text.split("\\n", 5);
final String javaClassName = textArray[2].substring(6);
final String javaClassNameAndPath = new StringBuilder("org.warp.picalculator.math.rules.").append(javaClassName).toString();
2018-03-22 20:40:41 +01:00
try {
return loadClassRuleDirectly(javaClassNameAndPath, tDir);
2018-05-12 21:18:29 +02:00
} catch (final Exception ex) {
2018-03-22 20:40:41 +01:00
ex.printStackTrace();
return null;
}
}
2018-05-12 21:18:29 +02:00
public static Rule loadClassRuleDirectly(String javaClassNameAndPath, Path tDir) throws IOException,
URISyntaxException, InstantiationException, IllegalAccessException, ClassNotFoundException {
final URLClassLoader cl = new URLClassLoader(new URL[] { tDir.toUri().toURL() });
final Class<?> aClass = cl.loadClass(javaClassNameAndPath);
2018-03-22 20:40:41 +01:00
cl.close();
return (Rule) aClass.newInstance();
2018-03-22 10:06:31 +01:00
}
2018-05-12 21:18:29 +02:00
public static void warmUp() throws Error, InterruptedException {
2017-12-23 15:20:42 +01:00
ObjectArrayList<Function> uselessResult = null;
boolean uselessVariable = false;
2018-05-12 21:18:29 +02:00
for (final RuleType val : RuleType.values()) {
2017-12-23 15:20:42 +01:00
final ObjectArrayList<Rule> ruleList = rules[val.ordinal()];
for (final Rule rule : ruleList) {
String ruleName = "<null>";
try {
ruleName = rule.getRuleName();
2018-05-12 21:18:29 +02:00
final ObjectArrayList<Function> uselessResult2 = rule.execute(generateUselessExpression());
uselessVariable = (uselessResult == null ? new ObjectArrayList<>() : uselessResult).equals(uselessResult2);
uselessResult = uselessResult2;
2018-05-12 21:18:29 +02:00
} catch (final Exception e) {
if (uselessVariable || true) {
System.err.println("Exception thrown by rule '" + ruleName + "'!");
e.printStackTrace();
}
}
2017-12-23 15:20:42 +01:00
}
}
try {
new MathSolver(generateUselessExpression()).solveAllSteps();
} catch (InterruptedException | Error e) {
e.printStackTrace();
}
}
2018-05-12 21:18:29 +02:00
2017-12-24 11:59:09 +01:00
private static Function generateUselessExpression() {
2018-05-12 21:18:29 +02:00
final MathContext mc = new MathContext();
2017-12-24 11:59:09 +01:00
Function expr = new Expression(mc);
expr = expr.setParameter(0, new Variable(mc, 'x', V_TYPE.VARIABLE));
2017-12-23 15:20:42 +01:00
return expr;
}
2018-05-12 21:18:29 +02:00
2017-12-21 23:21:29 +01:00
public static void addRule(Rule rule) {
2017-12-22 22:39:58 +01:00
rules[rule.getRuleType().ordinal()].add(rule);
2018-03-22 20:40:41 +01:00
Utils.out.println(Utils.OUTPUTLEVEL_NODEBUG, "RulesManager", rule.getRuleName(), "Loaded as " + rule.getRuleType() + " rule");
2017-12-21 23:21:29 +01:00
}
}