Remove Java rule compiling and loading code

This commit is contained in:
Riccardo Azzolini 2019-02-11 15:55:29 +01:00
parent fd074b16b7
commit e86a7a6346
8 changed files with 7 additions and 221 deletions

View File

@ -66,8 +66,6 @@ public interface Platform {
void unzip(String targetZipFilePath, String destinationFolderPath, String password); void unzip(String targetZipFilePath, String destinationFolderPath, String password);
boolean compile(String[] command, PrintWriter printWriter, PrintWriter errors);
public interface Gpio { public interface Gpio {
int valueOutput(); int valueOutput();

View File

@ -1,22 +1,13 @@
package it.cavallium.warppi.math.rules; package it.cavallium.warppi.math.rules;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream; import java.util.stream.Stream;
import it.cavallium.warppi.Engine; import it.cavallium.warppi.Engine;
import it.cavallium.warppi.Platform.ConsoleUtils; import it.cavallium.warppi.Platform.ConsoleUtils;
import it.cavallium.warppi.Platform.StorageUtils; import it.cavallium.warppi.Platform.StorageUtils;
import it.cavallium.warppi.Platform.URLClassLoader;
import it.cavallium.warppi.StaticVars;
import it.cavallium.warppi.math.Function; import it.cavallium.warppi.math.Function;
import it.cavallium.warppi.math.MathContext; import it.cavallium.warppi.math.MathContext;
import it.cavallium.warppi.math.functions.Expression; import it.cavallium.warppi.math.functions.Expression;
@ -45,123 +36,15 @@ public class RulesManager {
loadBuiltinRules(); loadBuiltinRules();
try { if (Engine.getPlatform().isJavascript()) {
if (!Engine.getPlatform().isJavascript()) { Engine.getPlatform().loadPlatformRules();
loadDslRules(); } else {
}
boolean compiledSomething = false;
InputStream defaultRulesList;
try { try {
defaultRulesList = Engine.getPlatform().getStorageUtils().getResourceStream("/default-rules.lst"); loadDslRules();
} catch (final IOException ex) { } catch (IOException | DslAggregateException e) {
throw new FileNotFoundException("default-rules.lst not found!"); e.printStackTrace();
Engine.getPlatform().exit(1);
} }
final List<String> ruleLines = new ArrayList<>();
final File rulesPath = Engine.getPlatform().getStorageUtils().get("rules/");
if (rulesPath.exists()) {
for (final File f : Engine.getPlatform().getStorageUtils().walk(rulesPath)) {
if (f.toString().endsWith(".java")) {
String path = Engine.getPlatform().getStorageUtils().relativize(rulesPath, f).toString();
path = path.substring(0, path.length() - ".java".length());
ruleLines.add(path);
Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_NODEBUG, "RulesManager", "Found external rule: " + f.getAbsolutePath());
}
}
}
ruleLines.addAll(Engine.getPlatform().getStorageUtils().readAllLines(defaultRulesList));
final File tDir = Engine.getPlatform().getStorageUtils().resolve(Engine.getPlatform().getStorageUtils().get(System.getProperty("java.io.tmpdir"), "WarpPi-Calculator"), "rules-rt");
// try {
// final Path defaultResource = Utils.getResource("/math-rules-cache.zip");
// }
InputStream cacheFileStream = null;
File cacheFilePath = null;
cacheFilePath = new File("math-rules-cache.zip");
boolean cacheFileExists = false;
if (Engine.getPlatform().isJavascript()) {
Engine.getPlatform().loadPlatformRules();
} else {
if (cacheFilePath.exists()) {
cacheFileExists = true;
cacheFileStream = new FileInputStream(cacheFilePath);
} else {
try {
cacheFileStream = Engine.getPlatform().getStorageUtils().getResourceStream("/math-rules-cache.zip");//Paths.get(Utils.getJarDirectory().toString()).resolve("math-rules-cache.zip").toAbsolutePath(
org.apache.commons.io.FileUtils.copyInputStreamToFile(cacheFileStream, cacheFilePath);
cacheFileExists = true;
} catch (final IOException ex) { //File does not exists.
}
}
boolean useCache = false;
if (cacheFileExists) {
try {
if (tDir.exists()) {
tDir.delete();
}
Engine.getPlatform().unzip(cacheFilePath.toString(), tDir.getParent().toString(), "");
useCache = !StaticVars.startupArguments.isUncached();
} catch (final Exception ex) {
ex.printStackTrace();
}
}
for (final String rulesLine : ruleLines) {
if (rulesLine.length() > 0) {
final String[] ruleDetails = rulesLine.split(",", 1);
final String ruleName = ruleDetails[0];
final String ruleNameEscaped = ruleName.replace(".", "_");
Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_MIN, "RulesManager", "Evaluating /rules/" + ruleNameEscaped + ".java");
final String pathWithoutExtension = "/rules/" + ruleNameEscaped;
final String scriptFile = pathWithoutExtension + ".java";
final InputStream resourcePath = Engine.getPlatform().getStorageUtils().getResourceStream(scriptFile);
if (resourcePath == null) {
System.err.println(new FileNotFoundException("/rules/" + ruleName + ".java not found!"));
} else {
Rule r = null;
if (useCache) {
try {
Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_MIN, "RulesManager", ruleName, "Trying to load cached rule");
r = RulesManager.loadClassRuleFromSourceFile(scriptFile, tDir);
if (r != null) {
Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_MIN, "RulesManager", ruleName, "Loaded cached rule");
}
} catch (final Exception e) {
e.printStackTrace();
Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_NODEBUG, "RulesManager", ruleName, "Can't load the rule " + ruleNameEscaped + "!");
}
}
if (r == null || !useCache) {
Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_MIN, "RulesManager", ruleName, "This rule is not cached. Compiling");
try {
r = RulesManager.compileJavaRule(scriptFile, tDir);
compiledSomething = true;
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | IOException e) {
e.printStackTrace();
}
}
if (r != null) {
RulesManager.addRule(r);
}
}
}
}
}
Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_NODEBUG, "RulesManager", "Loaded all the rules successfully");
if (!Engine.getPlatform().isJavascript() && compiledSomething) {
if (cacheFileExists || cacheFilePath.exists()) {
cacheFilePath.delete();
}
Engine.getPlatform().zip(tDir.toString(), cacheFilePath.toString(), "");
Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_NODEBUG, "RulesManager", "Cached the compiled rules");
}
if (cacheFileStream != null) {
cacheFileStream.close();
}
} catch (URISyntaxException | IOException | DslAggregateException e) {
e.printStackTrace();
Engine.getPlatform().exit(1);
} }
} }
@ -211,75 +94,6 @@ public class RulesManager {
} }
} }
public static Rule compileJavaRule(final String scriptFile, final File tDir) throws IOException, URISyntaxException,
InstantiationException, IllegalAccessException, ClassNotFoundException {
final InputStream resource = Engine.getPlatform().getStorageUtils().getResourceStream(scriptFile);
final String text = Engine.getPlatform().getStorageUtils().read(resource);
final String[] textArray = text.split("\\n", 6);
if (textArray[3].contains("PATH=")) {
final String javaClassDeclaration = textArray[3].substring(6);
int extIndex = javaClassDeclaration.lastIndexOf('.');
final String javaClassNameOnly = javaClassDeclaration.substring(extIndex + 1, javaClassDeclaration.length());
final String javaClassNameAndPath = new StringBuilder("it.cavallium.warppi.math.rules.").append(javaClassDeclaration).toString();
extIndex = javaClassNameAndPath.lastIndexOf('.');
final String javaCode = new StringBuilder("package ").append(javaClassNameAndPath.substring(0, extIndex >= 0 ? extIndex : javaClassNameAndPath.length())).append(";\n").append(textArray[5]).toString();
final File tDirPath = Engine.getPlatform().getStorageUtils().getParent(Engine.getPlatform().getStorageUtils().resolve(tDir, javaClassNameAndPath.replace('.', File.separatorChar)));
final File tFileJava = Engine.getPlatform().getStorageUtils().resolve(tDirPath, javaClassNameOnly + ".java");
final File tFileClass = Engine.getPlatform().getStorageUtils().resolve(tDirPath, javaClassNameOnly + ".class");
if (!tDirPath.exists()) {
Engine.getPlatform().getStorageUtils().createDirectories(tDirPath);
}
if (tFileJava.exists()) {
tFileJava.delete();
}
Engine.getPlatform().getStorageUtils();
Engine.getPlatform().getStorageUtils();
Engine.getPlatform().getStorageUtils().write(tFileJava, javaCode.getBytes("UTF-8"), StorageUtils.OpenOptionWrite, StorageUtils.OpenOptionCreate);
final boolean compiled = Engine.getPlatform().compile(new String[] { "-nowarn", "-1.8", "-proc:none", tFileJava.toString() }, new PrintWriter(System.out), new PrintWriter(System.err));
if (StaticVars.startupArguments.isUncached()) {
tFileJava.deleteOnExit();
} else {
tFileJava.delete();
}
if (compiled) {
tFileClass.deleteOnExit();
return RulesManager.loadClassRuleDirectly(javaClassNameAndPath, tDir);
} else {
throw new IOException("Can't build script file '" + scriptFile + "'");
}
} else {
throw new IOException("Can't build script file '" + scriptFile + "', the header is missing or wrong.");
}
}
public static Rule loadClassRuleFromSourceFile(final String scriptFile, final File tDir) throws IOException,
URISyntaxException, InstantiationException, IllegalAccessException, ClassNotFoundException {
final InputStream resource = Engine.getPlatform().getStorageUtils().getResourceStream(scriptFile);
final String text = Engine.getPlatform().getStorageUtils().read(resource);
final String[] textArray = text.split("\\n", 6);
if (textArray[3].contains("PATH=")) {
final String javaClassName = textArray[3].substring(6);
Engine.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_VERBOSE, "RulesManager", "Rule java class name: " + javaClassName);
final String javaClassNameAndPath = new StringBuilder("it.cavallium.warppi.math.rules.").append(javaClassName).toString();
try {
return RulesManager.loadClassRuleDirectly(javaClassNameAndPath, tDir);
} catch (final Exception ex) {
ex.printStackTrace();
return null;
}
} else {
throw new IOException("Can't load script file '" + scriptFile + "', the header is missing or wrong.");
}
}
public static Rule loadClassRuleDirectly(final String javaClassNameAndPath, final File tDir) throws IOException,
URISyntaxException, InstantiationException, IllegalAccessException, ClassNotFoundException {
final URLClassLoader cl = Engine.getPlatform().newURLClassLoader(new URL[] { tDir.toURI().toURL() });
final Class<?> aClass = cl.loadClass(javaClassNameAndPath);
cl.close();
return (Rule) aClass.newInstance();
}
public static void warmUp() throws Error, InterruptedException { public static void warmUp() throws Error, InterruptedException {
ObjectArrayList<Function> uselessResult = null; ObjectArrayList<Function> uselessResult = null;
boolean uselessVariable = false; boolean uselessVariable = false;

View File

@ -33,11 +33,6 @@
<artifactId>zip4j</artifactId> <artifactId>zip4j</artifactId>
<version>1.3.2</version> <version>1.3.2</version>
</dependency> </dependency>
<dependency>
<groupId>org.eclipse.tycho</groupId>
<artifactId>org.eclipse.jdt.core</artifactId>
<version>3.14.0.v20171206-0802</version>
</dependency>
<dependency> <dependency>
<groupId>ar.com.hjg</groupId> <groupId>ar.com.hjg</groupId>
<artifactId>pngj</artifactId> <artifactId>pngj</artifactId>

View File

@ -201,11 +201,6 @@ public class DesktopPlatform implements Platform {
} }
} }
@Override
public boolean compile(final String[] command, final PrintWriter printWriter, final PrintWriter errors) {
return org.eclipse.jdt.internal.compiler.batch.Main.compile(command, printWriter, errors, null);
}
@Override @Override
public void setRunningOnRaspberry(boolean b) { public void setRunningOnRaspberry(boolean b) {
if (isRunningOnRaspberry()) { if (isRunningOnRaspberry()) {

View File

@ -35,11 +35,6 @@
<artifactId>zip4j</artifactId> <artifactId>zip4j</artifactId>
<version>1.3.2</version> <version>1.3.2</version>
</dependency> </dependency>
<dependency>
<groupId>org.eclipse.jdt.core.compiler</groupId>
<artifactId>ecj</artifactId>
<version>4.6.1</version>
</dependency>
<dependency> <dependency>
<groupId>ar.com.hjg</groupId> <groupId>ar.com.hjg</groupId>
<artifactId>pngj</artifactId> <artifactId>pngj</artifactId>

View File

@ -190,11 +190,6 @@ public class HardwarePlatform implements Platform {
} }
} }
@Override
public boolean compile(final String[] command, final PrintWriter printWriter, final PrintWriter errors) {
return org.eclipse.jdt.internal.compiler.batch.Main.compile(command, printWriter, errors, null);
}
@Override @Override
public void setRunningOnRaspberry(boolean b) { public void setRunningOnRaspberry(boolean b) {
runningOnRaspberryOverride = b; runningOnRaspberryOverride = b;

View File

@ -1,6 +1,5 @@
package it.cavallium.warppi.teavm; package it.cavallium.warppi.teavm;
import java.io.PrintWriter;
import java.net.URL; import java.net.URL;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -204,11 +203,6 @@ public class TeaVMPlatform implements Platform {
throw new java.lang.UnsupportedOperationException("Not implemented."); throw new java.lang.UnsupportedOperationException("Not implemented.");
} }
@Override
public boolean compile(final String[] command, final PrintWriter printWriter, final PrintWriter errors) {
throw new java.lang.UnsupportedOperationException("Not implemented.");
}
@Override @Override
public void setRunningOnRaspberry(boolean b) { public void setRunningOnRaspberry(boolean b) {
} }