Java scripting engine simplifications.

This commit is contained in:
MobiusDevelopment
2019-04-12 17:49:14 +00:00
parent 4ba7bc7721
commit 988fc150ac
120 changed files with 1068 additions and 5821 deletions

View File

@@ -1,23 +1,23 @@
############################################################################### # ---------------------------------------------------------------------------
# Properties retrived with System.getProperty(String) can be used as values # Script Engine Settings
# ---------------------------------------------------------------------------
# Properties retrieved with System.getProperty(String) can be used as values
# by enclosing the property name with %. Eg.: %java.class.path% # by enclosing the property name with %. Eg.: %java.class.path%
###############################################################################
# The parent class loader for isolated script class loaders. # The parent class loader for isolated script class loaders.
# When this property is not specified, has an invalid value or is a class name which could not be found, the System classloader is used. # When this property is not specified, has an invalid value or is a class name which could not be found, the System classloader is used.
# Values: System, ThreadContext or a fully qualified java class name # Values: System, ThreadContext or a fully qualified java class name
language.Java.classloader=System classloader=System
#language.Java.classloader=ThreadContext #classloader=ThreadContext
# Source compatibility # Source compatibility.
language.Java.source=1.8 source=1.8
# The java sourcepath, when you have a different datapack root, you must change this too. # The java sourcepath, when you have a different datapack root, you must change this too.
language.Java.sourcepath=data/scripts sourcepath=data/scripts
# The java classpath # The java classpath.
language.Java.cp=%java.class.path% cp=%java.class.path%
# The debug informations to generate for compiled class files # The debug informations to generate for compiled class files.
language.Java.g=source,lines,vars g=source,lines,vars

View File

@@ -1,75 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
/**
* @author HorridoJoho
* @param <T>
*/
public abstract class AbstractExecutionContext<T extends IScriptingEngine> implements IExecutionContext
{
private final T _engine;
private final Map<String, String> _properties;
private volatile Path _currentExecutingScipt;
protected AbstractExecutionContext(T engine)
{
if (engine == null)
{
throw new IllegalArgumentException();
}
_engine = engine;
_properties = new HashMap<>();
}
protected final void setCurrentExecutingScript(Path currentExecutingScript)
{
_currentExecutingScipt = currentExecutingScript;
}
@Override
public final String setProperty(String key, String value)
{
return _properties.put(key, value);
}
@Override
public final String getProperty(String key)
{
if (!_properties.containsKey(key))
{
return _engine.getProperty(key);
}
return _properties.get(key);
}
@Override
public final Path getCurrentExecutingScript()
{
return _currentExecutingScipt;
}
@Override
public final T getScriptingEngine()
{
return _engine;
}
}

View File

@@ -1,74 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @author HorridoJoho
*/
public abstract class AbstractScriptingEngine implements IScriptingEngine
{
private final String _engineName;
private final String _engineVersion;
private final String[] _commonFileExtensions;
private final Map<String, String> _properties;
protected AbstractScriptingEngine(String engineName, String engineVersion, String... commonFileExtensions)
{
if ((engineName == null) || engineName.isEmpty() || (engineVersion == null) || engineVersion.isEmpty() || (commonFileExtensions == null) || (commonFileExtensions.length == 0))
{
throw new IllegalArgumentException();
}
_engineName = engineName;
_engineVersion = engineVersion;
_commonFileExtensions = commonFileExtensions;
_properties = new HashMap<>();
}
@Override
public final String setProperty(String key, String value)
{
return _properties.put(key, value);
}
@Override
public final String getProperty(String key)
{
return _properties.get(key);
}
@Override
public final String getEngineName()
{
return _engineName;
}
@Override
public final String getEngineVersion()
{
return _engineVersion;
}
@Override
public final String[] getCommonFileExtensions()
{
return Arrays.copyOf(_commonFileExtensions, _commonFileExtensions.length);
}
}

View File

@@ -1,71 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.nio.file.Path;
import java.util.Map;
import java.util.Map.Entry;
/**
* @author HorridoJoho
*/
public interface IExecutionContext
{
/**
* Properties set here override the settings from the IScriptEngine<br>
* this class was created from.
* @param key the key
* @param value the value
* @return the previous value, or null when this key was not present before
*/
String setProperty(String key, String value);
/**
* Executes all script in the iterable.
* @param sourcePaths the scripts to execute
* @return map of failed executions, Path=source file Throwable=thrown exception
* @throws Exception preparation for script execution failed
*/
Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception;
/**
* Executes a single file.
* @param sourcePath the script to execute
* @return entry of failed execution, Path=source file Throwable=thrown exception
* @throws Exception preparation for script execution failed
*/
Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception;
/**
* Method to get the specified property value.
* @param key the key
* @return the value, or null if the key is not present
*/
String getProperty(String key);
/**
* Method to get the current executing script file.
* @return the currently executing script file, null if non
*/
Path getCurrentExecutingScript();
/**
* Method to get the script engine this execution context belongs to.
* @return the script engine this execution context belongs to
*/
IScriptingEngine getScriptingEngine();
}

View File

@@ -1,75 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
/**
* @author HorridoJoho
*/
public interface IScriptingEngine
{
/**
* Sets script engine properties. The script values will be available<br>
* to the the insatnces created {@link IExecutionContext} implementation.
* @param key the key
* @param value the value
* @return the previous value, or null when this key was not present before
*/
String setProperty(String key, String value);
/**
* Creates an execution context.
* @return the created execution context.
*/
IExecutionContext createExecutionContext();
/**
* Method to get the specified property value.
* @param key the key
* @return the value,or null if the key is not present
*/
String getProperty(String key);
/**
* Method to get the engine name.
* @return the engine name
*/
String getEngineName();
/**
* Method to get the engine version.
* @return the engine version
*/
String getEngineVersion();
/**
* Method to get the scripting language name.
* @return the scripting engine name
*/
String getLanguageName();
/**
* Method to get the the language version.
* @return the language version
*/
String getLanguageVersion();
/**
* Method to retrive the commonly used file extensions for the language.
* @return the commonly used file extensions for the language
*/
String[] getCommonFileExtensions();
}

View File

@@ -17,7 +17,6 @@
package com.l2jmobius.gameserver.scripting; package com.l2jmobius.gameserver.scripting;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.file.FileVisitResult; import java.nio.file.FileVisitResult;
import java.nio.file.Files; import java.nio.file.Files;
@@ -31,9 +30,6 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Objects;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@@ -41,34 +37,27 @@ import org.w3c.dom.Document;
import com.l2jmobius.Config; import com.l2jmobius.Config;
import com.l2jmobius.commons.util.IXmlReader; import com.l2jmobius.commons.util.IXmlReader;
import com.l2jmobius.gameserver.scripting.java.JavaExecutionContext;
import com.l2jmobius.gameserver.scripting.java.JavaScriptingEngine; import com.l2jmobius.gameserver.scripting.java.JavaScriptingEngine;
/** /**
* Caches script engines and provides functionality for executing and managing scripts. * @author Mobius
* @author KenM, HorridoJoho
*/ */
public final class ScriptEngineManager implements IXmlReader public final class ScriptEngineManager implements IXmlReader
{ {
private static final Logger LOGGER = Logger.getLogger(ScriptEngineManager.class.getName()); private static final Logger LOGGER = Logger.getLogger(ScriptEngineManager.class.getName());
public static final Path SCRIPT_FOLDER = Config.SCRIPT_ROOT.toPath(); public static final Path SCRIPT_FOLDER = Config.SCRIPT_ROOT.toPath();
public static final Path MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "MasterHandler.java"); public static final Path MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "MasterHandler.java");
public static final Path EFFECT_MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "EffectMasterHandler.java"); public static final Path EFFECT_MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "EffectMasterHandler.java");
public static final Path SKILL_CONDITION_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "SkillConditionMasterHandler.java"); public static final Path SKILL_CONDITION_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "SkillConditionMasterHandler.java");
public static final Path CONDITION_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "ConditionMasterHandler.java"); public static final Path CONDITION_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "ConditionMasterHandler.java");
private IExecutionContext _javaExecutionContext = null; private static final JavaExecutionContext _javaExecutionContext = new JavaScriptingEngine().createExecutionContext();
static final List<String> _exclusions = new ArrayList<>(); protected static final List<String> _exclusions = new ArrayList<>();
protected ScriptEngineManager() protected ScriptEngineManager()
{ {
final Properties props = loadProperties();
// Default java engine implementation
registerEngine(new JavaScriptingEngine(), props);
// Load external script engines
ServiceLoader.load(IScriptingEngine.class).forEach(engine -> registerEngine(engine, props));
// Load Scripts.xml // Load Scripts.xml
load(); load();
} }
@@ -143,72 +132,6 @@ public final class ScriptEngineManager implements IXmlReader
} }
} }
private Properties loadProperties()
{
Properties props = null;
try (FileInputStream fis = new FileInputStream("config/ScriptEngine.ini"))
{
props = new Properties();
props.load(fis);
}
catch (Exception e)
{
props = null;
LOGGER.warning("Couldn't load ScriptEngine.ini: " + e.getMessage());
}
return props;
}
private void registerEngine(IScriptingEngine engine, Properties props)
{
maybeSetProperties("language." + engine.getLanguageName() + ".", props, engine);
_javaExecutionContext = engine.createExecutionContext();
LOGGER.info("ScriptEngine: " + engine.getEngineName() + " " + engine.getEngineVersion() + " (" + engine.getLanguageName() + " " + engine.getLanguageVersion() + ")");
}
private void maybeSetProperties(String propPrefix, Properties props, IScriptingEngine engine)
{
if (props == null)
{
return;
}
for (Entry<Object, Object> prop : props.entrySet())
{
String key = (String) prop.getKey();
String value = (String) prop.getValue();
if (key.startsWith(propPrefix))
{
key = key.substring(propPrefix.length());
if (value.startsWith("%") && value.endsWith("%"))
{
value = System.getProperty(value.substring(1, value.length() - 1));
}
engine.setProperty(key, value);
}
}
}
public void executeScriptList() throws Exception
{
if (Config.ALT_DEV_NO_QUESTS)
{
return;
}
final List<Path> files = new ArrayList<>();
processDirectory(SCRIPT_FOLDER.toFile(), files);
final Map<Path, Throwable> invokationErrors = _javaExecutionContext.executeScripts(files);
for (Entry<Path, Throwable> entry : invokationErrors.entrySet())
{
LOGGER.log(Level.WARNING, "ScriptEngine: " + entry.getKey() + " failed execution!", entry.getValue());
}
}
private void processDirectory(File dir, List<Path> files) private void processDirectory(File dir, List<Path> files)
{ {
for (File file : dir.listFiles()) for (File file : dir.listFiles())
@@ -230,15 +153,12 @@ public final class ScriptEngineManager implements IXmlReader
public void executeScript(Path sourceFile) throws Exception public void executeScript(Path sourceFile) throws Exception
{ {
Objects.requireNonNull(sourceFile);
if (!sourceFile.isAbsolute()) if (!sourceFile.isAbsolute())
{ {
sourceFile = SCRIPT_FOLDER.resolve(sourceFile); sourceFile = SCRIPT_FOLDER.resolve(sourceFile);
} }
sourceFile = sourceFile.toAbsolutePath(); sourceFile = sourceFile.toAbsolutePath();
Objects.requireNonNull(sourceFile, "ScriptFile: " + sourceFile + " does not have an extension to determine the script engine!");
final Entry<Path, Throwable> error = _javaExecutionContext.executeScript(sourceFile); final Entry<Path, Throwable> error = _javaExecutionContext.executeScript(sourceFile);
if (error != null) if (error != null)
@@ -247,6 +167,23 @@ public final class ScriptEngineManager implements IXmlReader
} }
} }
public void executeScriptList() throws Exception
{
if (Config.ALT_DEV_NO_QUESTS)
{
return;
}
final List<Path> files = new ArrayList<>();
processDirectory(SCRIPT_FOLDER.toFile(), files);
final Map<Path, Throwable> invokationErrors = _javaExecutionContext.executeScripts(files);
for (Entry<Path, Throwable> entry : invokationErrors.entrySet())
{
LOGGER.log(Level.WARNING, "ScriptEngine: " + entry.getKey() + " failed execution!", entry.getValue());
}
}
public Path getCurrentLoadingScript() public Path getCurrentLoadingScript()
{ {
return _javaExecutionContext.getCurrentExecutingScript(); return _javaExecutionContext.getCurrentExecutingScript();
@@ -254,11 +191,11 @@ public final class ScriptEngineManager implements IXmlReader
public static ScriptEngineManager getInstance() public static ScriptEngineManager getInstance()
{ {
return SingletonHolder._instance; return SingletonHolder.INSTANCE;
} }
private static class SingletonHolder private static class SingletonHolder
{ {
protected static final ScriptEngineManager _instance = new ScriptEngineManager(); protected static final ScriptEngineManager INSTANCE = new ScriptEngineManager();
} }
} }

View File

@@ -1,28 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting.java;
/**
* @author HorridoJoho
*/
public final class JavaCompilerException extends RuntimeException
{
public JavaCompilerException(String diagnostics)
{
super(diagnostics);
}
}

View File

@@ -22,9 +22,9 @@ import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.LinkedHashMap; import java.util.HashMap;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
@@ -34,22 +34,20 @@ import org.openjavac.tools.Diagnostic;
import org.openjavac.tools.DiagnosticCollector; import org.openjavac.tools.DiagnosticCollector;
import org.openjavac.tools.JavaFileObject; import org.openjavac.tools.JavaFileObject;
import com.l2jmobius.gameserver.scripting.AbstractExecutionContext;
import com.l2jmobius.gameserver.scripting.annotations.Disabled; import com.l2jmobius.gameserver.scripting.annotations.Disabled;
/** /**
* @author HorridoJoho * @author HorridoJoho
*/ */
public final class JavaExecutionContext extends AbstractExecutionContext<JavaScriptingEngine> public final class JavaExecutionContext extends JavaScriptingEngine
{ {
private static final Logger LOGGER = Logger.getLogger(JavaExecutionContext.class.getName()); private static final Logger LOGGER = Logger.getLogger(JavaExecutionContext.class.getName());
private static final List<String> _options = new LinkedList<>(); private static final List<String> _options = new ArrayList<>();
private static Path _currentExecutingScript;
JavaExecutionContext(JavaScriptingEngine engine) JavaExecutionContext(JavaScriptingEngine engine)
{ {
super(engine);
// Set options. // Set options.
addOptionIfNotNull(_options, getProperty("source"), "-source"); addOptionIfNotNull(_options, getProperty("source"), "-source");
addOptionIfNotNull(_options, getProperty("sourcepath"), "-sourcepath"); addOptionIfNotNull(_options, getProperty("sourcepath"), "-sourcepath");
@@ -76,7 +74,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
else else
{ {
throw new JavaCompilerException("Could not determine target version!"); throw new RuntimeException("Could not determine target version!");
} }
} }
} }
@@ -133,16 +131,15 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
} }
@Override
public Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception public Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception
{ {
final DiagnosticCollector<JavaFileObject> fileManagerDiagnostics = new DiagnosticCollector<>(); final DiagnosticCollector<JavaFileObject> fileManagerDiagnostics = new DiagnosticCollector<>();
final DiagnosticCollector<JavaFileObject> compilationDiagnostics = new DiagnosticCollector<>(); final DiagnosticCollector<JavaFileObject> compilationDiagnostics = new DiagnosticCollector<>();
try (ScriptingFileManager fileManager = new ScriptingFileManager(getScriptingEngine().getCompiler().getStandardFileManager(fileManagerDiagnostics, null, StandardCharsets.UTF_8))) try (ScriptingFileManager fileManager = new ScriptingFileManager(getCompiler().getStandardFileManager(fileManagerDiagnostics, null, StandardCharsets.UTF_8)))
{ {
// We really need an iterable of files or strings. // We really need an iterable of files or strings.
final List<String> sourcePathStrings = new LinkedList<>(); final List<String> sourcePathStrings = new ArrayList<>();
for (Path sourcePath : sourcePaths) for (Path sourcePath : sourcePaths)
{ {
sourcePathStrings.add(sourcePath.toString()); sourcePathStrings.add(sourcePath.toString());
@@ -150,7 +147,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
final StringWriter strOut = new StringWriter(); final StringWriter strOut = new StringWriter();
final PrintWriter out = new PrintWriter(strOut); final PrintWriter out = new PrintWriter(strOut);
final boolean compilationSuccess = getScriptingEngine().getCompiler().getTask(out, fileManager, compilationDiagnostics, _options, null, fileManager.getJavaFileObjectsFromStrings(sourcePathStrings)).call(); final boolean compilationSuccess = getCompiler().getTask(out, fileManager, compilationDiagnostics, _options, null, fileManager.getJavaFileObjectsFromStrings(sourcePathStrings)).call();
if (!compilationSuccess) if (!compilationSuccess)
{ {
out.println(); out.println();
@@ -175,12 +172,12 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
out.println("\t\tmessage: " + diagnostic.getMessage(null)); out.println("\t\tmessage: " + diagnostic.getMessage(null));
} }
throw new JavaCompilerException(strOut.toString()); throw new RuntimeException(strOut.toString());
} }
final ClassLoader parentClassLoader = determineScriptParentClassloader(); final ClassLoader parentClassLoader = determineScriptParentClassloader();
final Map<Path, Throwable> executionFailures = new LinkedHashMap<>(); final Map<Path, Throwable> executionFailures = new HashMap<>();
final Iterable<ScriptingOutputFileObject> compiledClasses = fileManager.getCompiledClasses(); final Iterable<ScriptingOutputFileObject> compiledClasses = fileManager.getCompiledClasses();
for (Path sourcePath : sourcePaths) for (Path sourcePath : sourcePaths)
{ {
@@ -199,7 +196,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
found = true; found = true;
setCurrentExecutingScript(compiledSourcePath); _currentExecutingScript = compiledSourcePath;
try try
{ {
final ScriptingClassLoader loader = new ScriptingClassLoader(parentClassLoader, compiledClasses); final ScriptingClassLoader loader = new ScriptingClassLoader(parentClassLoader, compiledClasses);
@@ -227,7 +224,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
finally finally
{ {
setCurrentExecutingScript(null); _currentExecutingScript = null;
} }
break; break;
@@ -244,7 +241,6 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
} }
@Override
public Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception public Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception
{ {
final Map<Path, Throwable> executionFailures = executeScripts(Arrays.asList(sourcePath)); final Map<Path, Throwable> executionFailures = executeScripts(Arrays.asList(sourcePath));
@@ -254,4 +250,9 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
return null; return null;
} }
public final Path getCurrentExecutingScript()
{
return _currentExecutingScript;
}
} }

View File

@@ -16,77 +16,66 @@
*/ */
package com.l2jmobius.gameserver.scripting.java; package com.l2jmobius.gameserver.scripting.java;
import java.util.Arrays; import java.io.FileInputStream;
import java.util.HashMap;
import javax.lang.model.SourceVersion; import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.logging.Logger;
import org.openjavac.tools.JavaCompiler; import org.openjavac.tools.JavaCompiler;
import org.openjavac.tools.javac.api.JavacTool; import org.openjavac.tools.javac.api.JavacTool;
import com.l2jmobius.gameserver.scripting.AbstractScriptingEngine;
import com.l2jmobius.gameserver.scripting.IExecutionContext;
/** /**
* @author HorridoJoho, Mobius * @author Mobius
*/ */
public final class JavaScriptingEngine extends AbstractScriptingEngine public class JavaScriptingEngine
{ {
private volatile JavaCompiler _compiler; private static final Logger LOGGER = Logger.getLogger(JavaScriptingEngine.class.getName());
private final static Map<String, String> _properties = new HashMap<>();
private final static JavaCompiler _compiler = JavacTool.create();
public JavaScriptingEngine() public JavaScriptingEngine()
{ {
super("Java Engine", "10", "java"); // Load config.
} Properties props = new Properties();
try (FileInputStream fis = new FileInputStream("config/ScriptEngine.ini"))
private void determineCompilerOrThrow()
{
if (_compiler == null)
{ {
_compiler = JavacTool.create(); props.load(fis);
}
catch (Exception e)
{
LOGGER.warning("Could not load ScriptEngine.ini: " + e.getMessage());
} }
if (_compiler == null) // Set properties.
for (Entry<Object, Object> prop : props.entrySet())
{ {
throw new IllegalStateException("No JavaCompiler service installed!"); String key = (String) prop.getKey();
} String value = (String) prop.getValue();
}
if (value.startsWith("%") && value.endsWith("%"))
private void ensureCompilerOrThrow()
{
if (_compiler == null)
{
synchronized (this)
{ {
if (_compiler == null) value = System.getProperty(value.substring(1, value.length() - 1));
{
determineCompilerOrThrow();
}
} }
_properties.put(key, value);
} }
} }
JavaCompiler getCompiler() public JavaExecutionContext createExecutionContext()
{ {
return _compiler;
}
@Override
public IExecutionContext createExecutionContext()
{
ensureCompilerOrThrow();
return new JavaExecutionContext(this); return new JavaExecutionContext(this);
} }
@Override public final String getProperty(String key)
public String getLanguageName()
{ {
return "Java"; return _properties.get(key);
} }
@Override public JavaCompiler getCompiler()
public String getLanguageVersion()
{ {
ensureCompilerOrThrow(); return _compiler;
return Arrays.deepToString(_compiler.getSourceVersions().toArray(new SourceVersion[0])).replace("RELEASE_", "");
} }
} }

View File

@@ -144,5 +144,4 @@ final class ScriptingOutputFileObject implements JavaFileObject
{ {
return null; return null;
} }
} }

View File

@@ -1,23 +1,23 @@
############################################################################### # ---------------------------------------------------------------------------
# Properties retrived with System.getProperty(String) can be used as values # Script Engine Settings
# ---------------------------------------------------------------------------
# Properties retrieved with System.getProperty(String) can be used as values
# by enclosing the property name with %. Eg.: %java.class.path% # by enclosing the property name with %. Eg.: %java.class.path%
###############################################################################
# The parent class loader for isolated script class loaders. # The parent class loader for isolated script class loaders.
# When this property is not specified, has an invalid value or is a class name which could not be found, the System classloader is used. # When this property is not specified, has an invalid value or is a class name which could not be found, the System classloader is used.
# Values: System, ThreadContext or a fully qualified java class name # Values: System, ThreadContext or a fully qualified java class name
language.Java.classloader=System classloader=System
#language.Java.classloader=ThreadContext #classloader=ThreadContext
# Source compatibility # Source compatibility.
language.Java.source=1.8 source=1.8
# The java sourcepath, when you have a different datapack root, you must change this too. # The java sourcepath, when you have a different datapack root, you must change this too.
language.Java.sourcepath=data/scripts sourcepath=data/scripts
# The java classpath # The java classpath.
language.Java.cp=%java.class.path% cp=%java.class.path%
# The debug informations to generate for compiled class files # The debug informations to generate for compiled class files.
language.Java.g=source,lines,vars g=source,lines,vars

View File

@@ -1,75 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
/**
* @author HorridoJoho
* @param <T>
*/
public abstract class AbstractExecutionContext<T extends IScriptingEngine> implements IExecutionContext
{
private final T _engine;
private final Map<String, String> _properties;
private volatile Path _currentExecutingScipt;
protected AbstractExecutionContext(T engine)
{
if (engine == null)
{
throw new IllegalArgumentException();
}
_engine = engine;
_properties = new HashMap<>();
}
protected final void setCurrentExecutingScript(Path currentExecutingScript)
{
_currentExecutingScipt = currentExecutingScript;
}
@Override
public final String setProperty(String key, String value)
{
return _properties.put(key, value);
}
@Override
public final String getProperty(String key)
{
if (!_properties.containsKey(key))
{
return _engine.getProperty(key);
}
return _properties.get(key);
}
@Override
public final Path getCurrentExecutingScript()
{
return _currentExecutingScipt;
}
@Override
public final T getScriptingEngine()
{
return _engine;
}
}

View File

@@ -1,74 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @author HorridoJoho
*/
public abstract class AbstractScriptingEngine implements IScriptingEngine
{
private final String _engineName;
private final String _engineVersion;
private final String[] _commonFileExtensions;
private final Map<String, String> _properties;
protected AbstractScriptingEngine(String engineName, String engineVersion, String... commonFileExtensions)
{
if ((engineName == null) || engineName.isEmpty() || (engineVersion == null) || engineVersion.isEmpty() || (commonFileExtensions == null) || (commonFileExtensions.length == 0))
{
throw new IllegalArgumentException();
}
_engineName = engineName;
_engineVersion = engineVersion;
_commonFileExtensions = commonFileExtensions;
_properties = new HashMap<>();
}
@Override
public final String setProperty(String key, String value)
{
return _properties.put(key, value);
}
@Override
public final String getProperty(String key)
{
return _properties.get(key);
}
@Override
public final String getEngineName()
{
return _engineName;
}
@Override
public final String getEngineVersion()
{
return _engineVersion;
}
@Override
public final String[] getCommonFileExtensions()
{
return Arrays.copyOf(_commonFileExtensions, _commonFileExtensions.length);
}
}

View File

@@ -1,71 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.nio.file.Path;
import java.util.Map;
import java.util.Map.Entry;
/**
* @author HorridoJoho
*/
public interface IExecutionContext
{
/**
* Properties set here override the settings from the IScriptEngine<br>
* this class was created from.
* @param key the key
* @param value the value
* @return the previous value, or null when this key was not present before
*/
String setProperty(String key, String value);
/**
* Executes all script in the iterable.
* @param sourcePaths the scripts to execute
* @return map of failed executions, Path=source file Throwable=thrown exception
* @throws Exception preparation for script execution failed
*/
Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception;
/**
* Executes a single file.
* @param sourcePath the script to execute
* @return entry of failed execution, Path=source file Throwable=thrown exception
* @throws Exception preparation for script execution failed
*/
Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception;
/**
* Method to get the specified property value.
* @param key the key
* @return the value, or null if the key is not present
*/
String getProperty(String key);
/**
* Method to get the current executing script file.
* @return the currently executing script file, null if non
*/
Path getCurrentExecutingScript();
/**
* Method to get the script engine this execution context belongs to.
* @return the script engine this execution context belongs to
*/
IScriptingEngine getScriptingEngine();
}

View File

@@ -1,75 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
/**
* @author HorridoJoho
*/
public interface IScriptingEngine
{
/**
* Sets script engine properties. The script values will be available<br>
* to the the insatnces created {@link IExecutionContext} implementation.
* @param key the key
* @param value the value
* @return the previous value, or null when this key was not present before
*/
String setProperty(String key, String value);
/**
* Creates an execution context.
* @return the created execution context.
*/
IExecutionContext createExecutionContext();
/**
* Method to get the specified property value.
* @param key the key
* @return the value,or null if the key is not present
*/
String getProperty(String key);
/**
* Method to get the engine name.
* @return the engine name
*/
String getEngineName();
/**
* Method to get the engine version.
* @return the engine version
*/
String getEngineVersion();
/**
* Method to get the scripting language name.
* @return the scripting engine name
*/
String getLanguageName();
/**
* Method to get the the language version.
* @return the language version
*/
String getLanguageVersion();
/**
* Method to retrive the commonly used file extensions for the language.
* @return the commonly used file extensions for the language
*/
String[] getCommonFileExtensions();
}

View File

@@ -17,7 +17,6 @@
package com.l2jmobius.gameserver.scripting; package com.l2jmobius.gameserver.scripting;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.file.FileVisitResult; import java.nio.file.FileVisitResult;
import java.nio.file.Files; import java.nio.file.Files;
@@ -31,9 +30,6 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Objects;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@@ -41,15 +37,16 @@ import org.w3c.dom.Document;
import com.l2jmobius.Config; import com.l2jmobius.Config;
import com.l2jmobius.commons.util.IXmlReader; import com.l2jmobius.commons.util.IXmlReader;
import com.l2jmobius.gameserver.scripting.java.JavaExecutionContext;
import com.l2jmobius.gameserver.scripting.java.JavaScriptingEngine; import com.l2jmobius.gameserver.scripting.java.JavaScriptingEngine;
/** /**
* Caches script engines and provides functionality for executing and managing scripts. * @author Mobius
* @author KenM, HorridoJoho
*/ */
public final class ScriptEngineManager implements IXmlReader public final class ScriptEngineManager implements IXmlReader
{ {
private static final Logger LOGGER = Logger.getLogger(ScriptEngineManager.class.getName()); private static final Logger LOGGER = Logger.getLogger(ScriptEngineManager.class.getName());
public static final Path SCRIPT_FOLDER = Config.SCRIPT_ROOT.toPath(); public static final Path SCRIPT_FOLDER = Config.SCRIPT_ROOT.toPath();
public static final Path MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "MasterHandler.java"); public static final Path MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "MasterHandler.java");
public static final Path EFFECT_MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "EffectMasterHandler.java"); public static final Path EFFECT_MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "EffectMasterHandler.java");
@@ -57,19 +54,11 @@ public final class ScriptEngineManager implements IXmlReader
public static final Path CONDITION_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "ConditionMasterHandler.java"); public static final Path CONDITION_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "ConditionMasterHandler.java");
public static final Path ONE_DAY_REWARD_MASTER_HANDLER = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "DailyMissionMasterHandler.java"); public static final Path ONE_DAY_REWARD_MASTER_HANDLER = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "DailyMissionMasterHandler.java");
private IExecutionContext _javaExecutionContext = null; private static final JavaExecutionContext _javaExecutionContext = new JavaScriptingEngine().createExecutionContext();
static final List<String> _exclusions = new ArrayList<>(); protected static final List<String> _exclusions = new ArrayList<>();
protected ScriptEngineManager() protected ScriptEngineManager()
{ {
final Properties props = loadProperties();
// Default java engine implementation
registerEngine(new JavaScriptingEngine(), props);
// Load external script engines
ServiceLoader.load(IScriptingEngine.class).forEach(engine -> registerEngine(engine, props));
// Load Scripts.xml // Load Scripts.xml
load(); load();
} }
@@ -144,71 +133,6 @@ public final class ScriptEngineManager implements IXmlReader
} }
} }
private Properties loadProperties()
{
Properties props = null;
try (FileInputStream fis = new FileInputStream("config/ScriptEngine.ini"))
{
props = new Properties();
props.load(fis);
}
catch (Exception e)
{
props = null;
LOGGER.warning("Couldn't load ScriptEngine.ini: " + e.getMessage());
}
return props;
}
private void registerEngine(IScriptingEngine engine, Properties props)
{
maybeSetProperties("language." + engine.getLanguageName() + ".", props, engine);
_javaExecutionContext = engine.createExecutionContext();
LOGGER.info("ScriptEngine: " + engine.getEngineName() + " " + engine.getEngineVersion() + " (" + engine.getLanguageName() + " " + engine.getLanguageVersion() + ")");
}
private void maybeSetProperties(String propPrefix, Properties props, IScriptingEngine engine)
{
if (props == null)
{
return;
}
for (Entry<Object, Object> prop : props.entrySet())
{
String key = (String) prop.getKey();
String value = (String) prop.getValue();
if (key.startsWith(propPrefix))
{
key = key.substring(propPrefix.length());
if (value.startsWith("%") && value.endsWith("%"))
{
value = System.getProperty(value.substring(1, value.length() - 1));
}
engine.setProperty(key, value);
}
}
}
public void executeScriptList() throws Exception
{
if (Config.ALT_DEV_NO_QUESTS)
{
return;
}
final List<Path> files = new ArrayList<>();
processDirectory(SCRIPT_FOLDER.toFile(), files);
final Map<Path, Throwable> invokationErrors = _javaExecutionContext.executeScripts(files);
for (Entry<Path, Throwable> entry : invokationErrors.entrySet())
{
LOGGER.log(Level.WARNING, "ScriptEngine: " + entry.getKey() + " failed execution!", entry.getValue());
}
}
private void processDirectory(File dir, List<Path> files) private void processDirectory(File dir, List<Path> files)
{ {
for (File file : dir.listFiles()) for (File file : dir.listFiles())
@@ -230,15 +154,12 @@ public final class ScriptEngineManager implements IXmlReader
public void executeScript(Path sourceFile) throws Exception public void executeScript(Path sourceFile) throws Exception
{ {
Objects.requireNonNull(sourceFile);
if (!sourceFile.isAbsolute()) if (!sourceFile.isAbsolute())
{ {
sourceFile = SCRIPT_FOLDER.resolve(sourceFile); sourceFile = SCRIPT_FOLDER.resolve(sourceFile);
} }
sourceFile = sourceFile.toAbsolutePath(); sourceFile = sourceFile.toAbsolutePath();
Objects.requireNonNull(sourceFile, "ScriptFile: " + sourceFile + " does not have an extension to determine the script engine!");
final Entry<Path, Throwable> error = _javaExecutionContext.executeScript(sourceFile); final Entry<Path, Throwable> error = _javaExecutionContext.executeScript(sourceFile);
if (error != null) if (error != null)
@@ -247,6 +168,23 @@ public final class ScriptEngineManager implements IXmlReader
} }
} }
public void executeScriptList() throws Exception
{
if (Config.ALT_DEV_NO_QUESTS)
{
return;
}
final List<Path> files = new ArrayList<>();
processDirectory(SCRIPT_FOLDER.toFile(), files);
final Map<Path, Throwable> invokationErrors = _javaExecutionContext.executeScripts(files);
for (Entry<Path, Throwable> entry : invokationErrors.entrySet())
{
LOGGER.log(Level.WARNING, "ScriptEngine: " + entry.getKey() + " failed execution!", entry.getValue());
}
}
public Path getCurrentLoadingScript() public Path getCurrentLoadingScript()
{ {
return _javaExecutionContext.getCurrentExecutingScript(); return _javaExecutionContext.getCurrentExecutingScript();
@@ -254,11 +192,11 @@ public final class ScriptEngineManager implements IXmlReader
public static ScriptEngineManager getInstance() public static ScriptEngineManager getInstance()
{ {
return SingletonHolder._instance; return SingletonHolder.INSTANCE;
} }
private static class SingletonHolder private static class SingletonHolder
{ {
protected static final ScriptEngineManager _instance = new ScriptEngineManager(); protected static final ScriptEngineManager INSTANCE = new ScriptEngineManager();
} }
} }

View File

@@ -1,28 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting.java;
/**
* @author HorridoJoho
*/
public final class JavaCompilerException extends RuntimeException
{
public JavaCompilerException(String diagnostics)
{
super(diagnostics);
}
}

View File

@@ -22,9 +22,9 @@ import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.LinkedHashMap; import java.util.HashMap;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
@@ -34,22 +34,20 @@ import org.openjavac.tools.Diagnostic;
import org.openjavac.tools.DiagnosticCollector; import org.openjavac.tools.DiagnosticCollector;
import org.openjavac.tools.JavaFileObject; import org.openjavac.tools.JavaFileObject;
import com.l2jmobius.gameserver.scripting.AbstractExecutionContext;
import com.l2jmobius.gameserver.scripting.annotations.Disabled; import com.l2jmobius.gameserver.scripting.annotations.Disabled;
/** /**
* @author HorridoJoho * @author HorridoJoho
*/ */
public final class JavaExecutionContext extends AbstractExecutionContext<JavaScriptingEngine> public final class JavaExecutionContext extends JavaScriptingEngine
{ {
private static final Logger LOGGER = Logger.getLogger(JavaExecutionContext.class.getName()); private static final Logger LOGGER = Logger.getLogger(JavaExecutionContext.class.getName());
private static final List<String> _options = new LinkedList<>(); private static final List<String> _options = new ArrayList<>();
private static Path _currentExecutingScript;
JavaExecutionContext(JavaScriptingEngine engine) JavaExecutionContext(JavaScriptingEngine engine)
{ {
super(engine);
// Set options. // Set options.
addOptionIfNotNull(_options, getProperty("source"), "-source"); addOptionIfNotNull(_options, getProperty("source"), "-source");
addOptionIfNotNull(_options, getProperty("sourcepath"), "-sourcepath"); addOptionIfNotNull(_options, getProperty("sourcepath"), "-sourcepath");
@@ -76,7 +74,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
else else
{ {
throw new JavaCompilerException("Could not determine target version!"); throw new RuntimeException("Could not determine target version!");
} }
} }
} }
@@ -133,16 +131,15 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
} }
@Override
public Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception public Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception
{ {
final DiagnosticCollector<JavaFileObject> fileManagerDiagnostics = new DiagnosticCollector<>(); final DiagnosticCollector<JavaFileObject> fileManagerDiagnostics = new DiagnosticCollector<>();
final DiagnosticCollector<JavaFileObject> compilationDiagnostics = new DiagnosticCollector<>(); final DiagnosticCollector<JavaFileObject> compilationDiagnostics = new DiagnosticCollector<>();
try (ScriptingFileManager fileManager = new ScriptingFileManager(getScriptingEngine().getCompiler().getStandardFileManager(fileManagerDiagnostics, null, StandardCharsets.UTF_8))) try (ScriptingFileManager fileManager = new ScriptingFileManager(getCompiler().getStandardFileManager(fileManagerDiagnostics, null, StandardCharsets.UTF_8)))
{ {
// We really need an iterable of files or strings. // We really need an iterable of files or strings.
final List<String> sourcePathStrings = new LinkedList<>(); final List<String> sourcePathStrings = new ArrayList<>();
for (Path sourcePath : sourcePaths) for (Path sourcePath : sourcePaths)
{ {
sourcePathStrings.add(sourcePath.toString()); sourcePathStrings.add(sourcePath.toString());
@@ -150,7 +147,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
final StringWriter strOut = new StringWriter(); final StringWriter strOut = new StringWriter();
final PrintWriter out = new PrintWriter(strOut); final PrintWriter out = new PrintWriter(strOut);
final boolean compilationSuccess = getScriptingEngine().getCompiler().getTask(out, fileManager, compilationDiagnostics, _options, null, fileManager.getJavaFileObjectsFromStrings(sourcePathStrings)).call(); final boolean compilationSuccess = getCompiler().getTask(out, fileManager, compilationDiagnostics, _options, null, fileManager.getJavaFileObjectsFromStrings(sourcePathStrings)).call();
if (!compilationSuccess) if (!compilationSuccess)
{ {
out.println(); out.println();
@@ -175,12 +172,12 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
out.println("\t\tmessage: " + diagnostic.getMessage(null)); out.println("\t\tmessage: " + diagnostic.getMessage(null));
} }
throw new JavaCompilerException(strOut.toString()); throw new RuntimeException(strOut.toString());
} }
final ClassLoader parentClassLoader = determineScriptParentClassloader(); final ClassLoader parentClassLoader = determineScriptParentClassloader();
final Map<Path, Throwable> executionFailures = new LinkedHashMap<>(); final Map<Path, Throwable> executionFailures = new HashMap<>();
final Iterable<ScriptingOutputFileObject> compiledClasses = fileManager.getCompiledClasses(); final Iterable<ScriptingOutputFileObject> compiledClasses = fileManager.getCompiledClasses();
for (Path sourcePath : sourcePaths) for (Path sourcePath : sourcePaths)
{ {
@@ -199,7 +196,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
found = true; found = true;
setCurrentExecutingScript(compiledSourcePath); _currentExecutingScript = compiledSourcePath;
try try
{ {
final ScriptingClassLoader loader = new ScriptingClassLoader(parentClassLoader, compiledClasses); final ScriptingClassLoader loader = new ScriptingClassLoader(parentClassLoader, compiledClasses);
@@ -227,7 +224,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
finally finally
{ {
setCurrentExecutingScript(null); _currentExecutingScript = null;
} }
break; break;
@@ -244,7 +241,6 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
} }
@Override
public Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception public Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception
{ {
final Map<Path, Throwable> executionFailures = executeScripts(Arrays.asList(sourcePath)); final Map<Path, Throwable> executionFailures = executeScripts(Arrays.asList(sourcePath));
@@ -254,4 +250,9 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
return null; return null;
} }
public final Path getCurrentExecutingScript()
{
return _currentExecutingScript;
}
} }

View File

@@ -16,77 +16,66 @@
*/ */
package com.l2jmobius.gameserver.scripting.java; package com.l2jmobius.gameserver.scripting.java;
import java.util.Arrays; import java.io.FileInputStream;
import java.util.HashMap;
import javax.lang.model.SourceVersion; import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.logging.Logger;
import org.openjavac.tools.JavaCompiler; import org.openjavac.tools.JavaCompiler;
import org.openjavac.tools.javac.api.JavacTool; import org.openjavac.tools.javac.api.JavacTool;
import com.l2jmobius.gameserver.scripting.AbstractScriptingEngine;
import com.l2jmobius.gameserver.scripting.IExecutionContext;
/** /**
* @author HorridoJoho, Mobius * @author Mobius
*/ */
public final class JavaScriptingEngine extends AbstractScriptingEngine public class JavaScriptingEngine
{ {
private volatile JavaCompiler _compiler; private static final Logger LOGGER = Logger.getLogger(JavaScriptingEngine.class.getName());
private final static Map<String, String> _properties = new HashMap<>();
private final static JavaCompiler _compiler = JavacTool.create();
public JavaScriptingEngine() public JavaScriptingEngine()
{ {
super("Java Engine", "10", "java"); // Load config.
} Properties props = new Properties();
try (FileInputStream fis = new FileInputStream("config/ScriptEngine.ini"))
private void determineCompilerOrThrow()
{
if (_compiler == null)
{ {
_compiler = JavacTool.create(); props.load(fis);
}
catch (Exception e)
{
LOGGER.warning("Could not load ScriptEngine.ini: " + e.getMessage());
} }
if (_compiler == null) // Set properties.
for (Entry<Object, Object> prop : props.entrySet())
{ {
throw new IllegalStateException("No JavaCompiler service installed!"); String key = (String) prop.getKey();
} String value = (String) prop.getValue();
}
if (value.startsWith("%") && value.endsWith("%"))
private void ensureCompilerOrThrow()
{
if (_compiler == null)
{
synchronized (this)
{ {
if (_compiler == null) value = System.getProperty(value.substring(1, value.length() - 1));
{
determineCompilerOrThrow();
}
} }
_properties.put(key, value);
} }
} }
JavaCompiler getCompiler() public JavaExecutionContext createExecutionContext()
{ {
return _compiler;
}
@Override
public IExecutionContext createExecutionContext()
{
ensureCompilerOrThrow();
return new JavaExecutionContext(this); return new JavaExecutionContext(this);
} }
@Override public final String getProperty(String key)
public String getLanguageName()
{ {
return "Java"; return _properties.get(key);
} }
@Override public JavaCompiler getCompiler()
public String getLanguageVersion()
{ {
ensureCompilerOrThrow(); return _compiler;
return Arrays.deepToString(_compiler.getSourceVersions().toArray(new SourceVersion[0])).replace("RELEASE_", "");
} }
} }

View File

@@ -144,5 +144,4 @@ final class ScriptingOutputFileObject implements JavaFileObject
{ {
return null; return null;
} }
} }

View File

@@ -1,23 +1,23 @@
############################################################################### # ---------------------------------------------------------------------------
# Properties retrived with System.getProperty(String) can be used as values # Script Engine Settings
# ---------------------------------------------------------------------------
# Properties retrieved with System.getProperty(String) can be used as values
# by enclosing the property name with %. Eg.: %java.class.path% # by enclosing the property name with %. Eg.: %java.class.path%
###############################################################################
# The parent class loader for isolated script class loaders. # The parent class loader for isolated script class loaders.
# When this property is not specified, has an invalid value or is a class name which could not be found, the System classloader is used. # When this property is not specified, has an invalid value or is a class name which could not be found, the System classloader is used.
# Values: System, ThreadContext or a fully qualified java class name # Values: System, ThreadContext or a fully qualified java class name
language.Java.classloader=System classloader=System
#language.Java.classloader=ThreadContext #classloader=ThreadContext
# Source compatibility # Source compatibility.
language.Java.source=1.8 source=1.8
# The java sourcepath, when you have a different datapack root, you must change this too. # The java sourcepath, when you have a different datapack root, you must change this too.
language.Java.sourcepath=data/scripts sourcepath=data/scripts
# The java classpath # The java classpath.
language.Java.cp=%java.class.path% cp=%java.class.path%
# The debug informations to generate for compiled class files # The debug informations to generate for compiled class files.
language.Java.g=source,lines,vars g=source,lines,vars

View File

@@ -1,75 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
/**
* @author HorridoJoho
* @param <T>
*/
public abstract class AbstractExecutionContext<T extends IScriptingEngine> implements IExecutionContext
{
private final T _engine;
private final Map<String, String> _properties;
private volatile Path _currentExecutingScipt;
protected AbstractExecutionContext(T engine)
{
if (engine == null)
{
throw new IllegalArgumentException();
}
_engine = engine;
_properties = new HashMap<>();
}
protected final void setCurrentExecutingScript(Path currentExecutingScript)
{
_currentExecutingScipt = currentExecutingScript;
}
@Override
public final String setProperty(String key, String value)
{
return _properties.put(key, value);
}
@Override
public final String getProperty(String key)
{
if (!_properties.containsKey(key))
{
return _engine.getProperty(key);
}
return _properties.get(key);
}
@Override
public final Path getCurrentExecutingScript()
{
return _currentExecutingScipt;
}
@Override
public final T getScriptingEngine()
{
return _engine;
}
}

View File

@@ -1,74 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @author HorridoJoho
*/
public abstract class AbstractScriptingEngine implements IScriptingEngine
{
private final String _engineName;
private final String _engineVersion;
private final String[] _commonFileExtensions;
private final Map<String, String> _properties;
protected AbstractScriptingEngine(String engineName, String engineVersion, String... commonFileExtensions)
{
if ((engineName == null) || engineName.isEmpty() || (engineVersion == null) || engineVersion.isEmpty() || (commonFileExtensions == null) || (commonFileExtensions.length == 0))
{
throw new IllegalArgumentException();
}
_engineName = engineName;
_engineVersion = engineVersion;
_commonFileExtensions = commonFileExtensions;
_properties = new HashMap<>();
}
@Override
public final String setProperty(String key, String value)
{
return _properties.put(key, value);
}
@Override
public final String getProperty(String key)
{
return _properties.get(key);
}
@Override
public final String getEngineName()
{
return _engineName;
}
@Override
public final String getEngineVersion()
{
return _engineVersion;
}
@Override
public final String[] getCommonFileExtensions()
{
return Arrays.copyOf(_commonFileExtensions, _commonFileExtensions.length);
}
}

View File

@@ -1,71 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.nio.file.Path;
import java.util.Map;
import java.util.Map.Entry;
/**
* @author HorridoJoho
*/
public interface IExecutionContext
{
/**
* Properties set here override the settings from the IScriptEngine<br>
* this class was created from.
* @param key the key
* @param value the value
* @return the previous value, or null when this key was not present before
*/
String setProperty(String key, String value);
/**
* Executes all script in the iterable.
* @param sourcePaths the scripts to execute
* @return map of failed executions, Path=source file Throwable=thrown exception
* @throws Exception preparation for script execution failed
*/
Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception;
/**
* Executes a single file.
* @param sourcePath the script to execute
* @return entry of failed execution, Path=source file Throwable=thrown exception
* @throws Exception preparation for script execution failed
*/
Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception;
/**
* Method to get the specified property value.
* @param key the key
* @return the value, or null if the key is not present
*/
String getProperty(String key);
/**
* Method to get the current executing script file.
* @return the currently executing script file, null if non
*/
Path getCurrentExecutingScript();
/**
* Method to get the script engine this execution context belongs to.
* @return the script engine this execution context belongs to
*/
IScriptingEngine getScriptingEngine();
}

View File

@@ -1,75 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
/**
* @author HorridoJoho
*/
public interface IScriptingEngine
{
/**
* Sets script engine properties. The script values will be available<br>
* to the the insatnces created {@link IExecutionContext} implementation.
* @param key the key
* @param value the value
* @return the previous value, or null when this key was not present before
*/
String setProperty(String key, String value);
/**
* Creates an execution context.
* @return the created execution context.
*/
IExecutionContext createExecutionContext();
/**
* Method to get the specified property value.
* @param key the key
* @return the value,or null if the key is not present
*/
String getProperty(String key);
/**
* Method to get the engine name.
* @return the engine name
*/
String getEngineName();
/**
* Method to get the engine version.
* @return the engine version
*/
String getEngineVersion();
/**
* Method to get the scripting language name.
* @return the scripting engine name
*/
String getLanguageName();
/**
* Method to get the the language version.
* @return the language version
*/
String getLanguageVersion();
/**
* Method to retrive the commonly used file extensions for the language.
* @return the commonly used file extensions for the language
*/
String[] getCommonFileExtensions();
}

View File

@@ -17,7 +17,6 @@
package com.l2jmobius.gameserver.scripting; package com.l2jmobius.gameserver.scripting;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.file.FileVisitResult; import java.nio.file.FileVisitResult;
import java.nio.file.Files; import java.nio.file.Files;
@@ -31,9 +30,6 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Objects;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@@ -41,15 +37,16 @@ import org.w3c.dom.Document;
import com.l2jmobius.Config; import com.l2jmobius.Config;
import com.l2jmobius.commons.util.IXmlReader; import com.l2jmobius.commons.util.IXmlReader;
import com.l2jmobius.gameserver.scripting.java.JavaExecutionContext;
import com.l2jmobius.gameserver.scripting.java.JavaScriptingEngine; import com.l2jmobius.gameserver.scripting.java.JavaScriptingEngine;
/** /**
* Caches script engines and provides functionality for executing and managing scripts. * @author Mobius
* @author KenM, HorridoJoho
*/ */
public final class ScriptEngineManager implements IXmlReader public final class ScriptEngineManager implements IXmlReader
{ {
private static final Logger LOGGER = Logger.getLogger(ScriptEngineManager.class.getName()); private static final Logger LOGGER = Logger.getLogger(ScriptEngineManager.class.getName());
public static final Path SCRIPT_FOLDER = Config.SCRIPT_ROOT.toPath(); public static final Path SCRIPT_FOLDER = Config.SCRIPT_ROOT.toPath();
public static final Path MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "MasterHandler.java"); public static final Path MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "MasterHandler.java");
public static final Path EFFECT_MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "EffectMasterHandler.java"); public static final Path EFFECT_MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "EffectMasterHandler.java");
@@ -57,19 +54,11 @@ public final class ScriptEngineManager implements IXmlReader
public static final Path CONDITION_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "ConditionMasterHandler.java"); public static final Path CONDITION_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "ConditionMasterHandler.java");
public static final Path ONE_DAY_REWARD_MASTER_HANDLER = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "DailyMissionMasterHandler.java"); public static final Path ONE_DAY_REWARD_MASTER_HANDLER = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "DailyMissionMasterHandler.java");
private IExecutionContext _javaExecutionContext = null; private static final JavaExecutionContext _javaExecutionContext = new JavaScriptingEngine().createExecutionContext();
static final List<String> _exclusions = new ArrayList<>(); protected static final List<String> _exclusions = new ArrayList<>();
protected ScriptEngineManager() protected ScriptEngineManager()
{ {
final Properties props = loadProperties();
// Default java engine implementation
registerEngine(new JavaScriptingEngine(), props);
// Load external script engines
ServiceLoader.load(IScriptingEngine.class).forEach(engine -> registerEngine(engine, props));
// Load Scripts.xml // Load Scripts.xml
load(); load();
} }
@@ -144,71 +133,6 @@ public final class ScriptEngineManager implements IXmlReader
} }
} }
private Properties loadProperties()
{
Properties props = null;
try (FileInputStream fis = new FileInputStream("config/ScriptEngine.ini"))
{
props = new Properties();
props.load(fis);
}
catch (Exception e)
{
props = null;
LOGGER.warning("Couldn't load ScriptEngine.ini: " + e.getMessage());
}
return props;
}
private void registerEngine(IScriptingEngine engine, Properties props)
{
maybeSetProperties("language." + engine.getLanguageName() + ".", props, engine);
_javaExecutionContext = engine.createExecutionContext();
LOGGER.info("ScriptEngine: " + engine.getEngineName() + " " + engine.getEngineVersion() + " (" + engine.getLanguageName() + " " + engine.getLanguageVersion() + ")");
}
private void maybeSetProperties(String propPrefix, Properties props, IScriptingEngine engine)
{
if (props == null)
{
return;
}
for (Entry<Object, Object> prop : props.entrySet())
{
String key = (String) prop.getKey();
String value = (String) prop.getValue();
if (key.startsWith(propPrefix))
{
key = key.substring(propPrefix.length());
if (value.startsWith("%") && value.endsWith("%"))
{
value = System.getProperty(value.substring(1, value.length() - 1));
}
engine.setProperty(key, value);
}
}
}
public void executeScriptList() throws Exception
{
if (Config.ALT_DEV_NO_QUESTS)
{
return;
}
final List<Path> files = new ArrayList<>();
processDirectory(SCRIPT_FOLDER.toFile(), files);
final Map<Path, Throwable> invokationErrors = _javaExecutionContext.executeScripts(files);
for (Entry<Path, Throwable> entry : invokationErrors.entrySet())
{
LOGGER.log(Level.WARNING, "ScriptEngine: " + entry.getKey() + " failed execution!", entry.getValue());
}
}
private void processDirectory(File dir, List<Path> files) private void processDirectory(File dir, List<Path> files)
{ {
for (File file : dir.listFiles()) for (File file : dir.listFiles())
@@ -230,15 +154,12 @@ public final class ScriptEngineManager implements IXmlReader
public void executeScript(Path sourceFile) throws Exception public void executeScript(Path sourceFile) throws Exception
{ {
Objects.requireNonNull(sourceFile);
if (!sourceFile.isAbsolute()) if (!sourceFile.isAbsolute())
{ {
sourceFile = SCRIPT_FOLDER.resolve(sourceFile); sourceFile = SCRIPT_FOLDER.resolve(sourceFile);
} }
sourceFile = sourceFile.toAbsolutePath(); sourceFile = sourceFile.toAbsolutePath();
Objects.requireNonNull(sourceFile, "ScriptFile: " + sourceFile + " does not have an extension to determine the script engine!");
final Entry<Path, Throwable> error = _javaExecutionContext.executeScript(sourceFile); final Entry<Path, Throwable> error = _javaExecutionContext.executeScript(sourceFile);
if (error != null) if (error != null)
@@ -247,6 +168,23 @@ public final class ScriptEngineManager implements IXmlReader
} }
} }
public void executeScriptList() throws Exception
{
if (Config.ALT_DEV_NO_QUESTS)
{
return;
}
final List<Path> files = new ArrayList<>();
processDirectory(SCRIPT_FOLDER.toFile(), files);
final Map<Path, Throwable> invokationErrors = _javaExecutionContext.executeScripts(files);
for (Entry<Path, Throwable> entry : invokationErrors.entrySet())
{
LOGGER.log(Level.WARNING, "ScriptEngine: " + entry.getKey() + " failed execution!", entry.getValue());
}
}
public Path getCurrentLoadingScript() public Path getCurrentLoadingScript()
{ {
return _javaExecutionContext.getCurrentExecutingScript(); return _javaExecutionContext.getCurrentExecutingScript();
@@ -254,11 +192,11 @@ public final class ScriptEngineManager implements IXmlReader
public static ScriptEngineManager getInstance() public static ScriptEngineManager getInstance()
{ {
return SingletonHolder._instance; return SingletonHolder.INSTANCE;
} }
private static class SingletonHolder private static class SingletonHolder
{ {
protected static final ScriptEngineManager _instance = new ScriptEngineManager(); protected static final ScriptEngineManager INSTANCE = new ScriptEngineManager();
} }
} }

View File

@@ -1,28 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting.java;
/**
* @author HorridoJoho
*/
public final class JavaCompilerException extends RuntimeException
{
public JavaCompilerException(String diagnostics)
{
super(diagnostics);
}
}

View File

@@ -22,9 +22,9 @@ import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.LinkedHashMap; import java.util.HashMap;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
@@ -34,22 +34,20 @@ import org.openjavac.tools.Diagnostic;
import org.openjavac.tools.DiagnosticCollector; import org.openjavac.tools.DiagnosticCollector;
import org.openjavac.tools.JavaFileObject; import org.openjavac.tools.JavaFileObject;
import com.l2jmobius.gameserver.scripting.AbstractExecutionContext;
import com.l2jmobius.gameserver.scripting.annotations.Disabled; import com.l2jmobius.gameserver.scripting.annotations.Disabled;
/** /**
* @author HorridoJoho * @author HorridoJoho
*/ */
public final class JavaExecutionContext extends AbstractExecutionContext<JavaScriptingEngine> public final class JavaExecutionContext extends JavaScriptingEngine
{ {
private static final Logger LOGGER = Logger.getLogger(JavaExecutionContext.class.getName()); private static final Logger LOGGER = Logger.getLogger(JavaExecutionContext.class.getName());
private static final List<String> _options = new LinkedList<>(); private static final List<String> _options = new ArrayList<>();
private static Path _currentExecutingScript;
JavaExecutionContext(JavaScriptingEngine engine) JavaExecutionContext(JavaScriptingEngine engine)
{ {
super(engine);
// Set options. // Set options.
addOptionIfNotNull(_options, getProperty("source"), "-source"); addOptionIfNotNull(_options, getProperty("source"), "-source");
addOptionIfNotNull(_options, getProperty("sourcepath"), "-sourcepath"); addOptionIfNotNull(_options, getProperty("sourcepath"), "-sourcepath");
@@ -76,7 +74,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
else else
{ {
throw new JavaCompilerException("Could not determine target version!"); throw new RuntimeException("Could not determine target version!");
} }
} }
} }
@@ -133,16 +131,15 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
} }
@Override
public Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception public Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception
{ {
final DiagnosticCollector<JavaFileObject> fileManagerDiagnostics = new DiagnosticCollector<>(); final DiagnosticCollector<JavaFileObject> fileManagerDiagnostics = new DiagnosticCollector<>();
final DiagnosticCollector<JavaFileObject> compilationDiagnostics = new DiagnosticCollector<>(); final DiagnosticCollector<JavaFileObject> compilationDiagnostics = new DiagnosticCollector<>();
try (ScriptingFileManager fileManager = new ScriptingFileManager(getScriptingEngine().getCompiler().getStandardFileManager(fileManagerDiagnostics, null, StandardCharsets.UTF_8))) try (ScriptingFileManager fileManager = new ScriptingFileManager(getCompiler().getStandardFileManager(fileManagerDiagnostics, null, StandardCharsets.UTF_8)))
{ {
// We really need an iterable of files or strings. // We really need an iterable of files or strings.
final List<String> sourcePathStrings = new LinkedList<>(); final List<String> sourcePathStrings = new ArrayList<>();
for (Path sourcePath : sourcePaths) for (Path sourcePath : sourcePaths)
{ {
sourcePathStrings.add(sourcePath.toString()); sourcePathStrings.add(sourcePath.toString());
@@ -150,7 +147,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
final StringWriter strOut = new StringWriter(); final StringWriter strOut = new StringWriter();
final PrintWriter out = new PrintWriter(strOut); final PrintWriter out = new PrintWriter(strOut);
final boolean compilationSuccess = getScriptingEngine().getCompiler().getTask(out, fileManager, compilationDiagnostics, _options, null, fileManager.getJavaFileObjectsFromStrings(sourcePathStrings)).call(); final boolean compilationSuccess = getCompiler().getTask(out, fileManager, compilationDiagnostics, _options, null, fileManager.getJavaFileObjectsFromStrings(sourcePathStrings)).call();
if (!compilationSuccess) if (!compilationSuccess)
{ {
out.println(); out.println();
@@ -175,12 +172,12 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
out.println("\t\tmessage: " + diagnostic.getMessage(null)); out.println("\t\tmessage: " + diagnostic.getMessage(null));
} }
throw new JavaCompilerException(strOut.toString()); throw new RuntimeException(strOut.toString());
} }
final ClassLoader parentClassLoader = determineScriptParentClassloader(); final ClassLoader parentClassLoader = determineScriptParentClassloader();
final Map<Path, Throwable> executionFailures = new LinkedHashMap<>(); final Map<Path, Throwable> executionFailures = new HashMap<>();
final Iterable<ScriptingOutputFileObject> compiledClasses = fileManager.getCompiledClasses(); final Iterable<ScriptingOutputFileObject> compiledClasses = fileManager.getCompiledClasses();
for (Path sourcePath : sourcePaths) for (Path sourcePath : sourcePaths)
{ {
@@ -199,7 +196,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
found = true; found = true;
setCurrentExecutingScript(compiledSourcePath); _currentExecutingScript = compiledSourcePath;
try try
{ {
final ScriptingClassLoader loader = new ScriptingClassLoader(parentClassLoader, compiledClasses); final ScriptingClassLoader loader = new ScriptingClassLoader(parentClassLoader, compiledClasses);
@@ -227,7 +224,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
finally finally
{ {
setCurrentExecutingScript(null); _currentExecutingScript = null;
} }
break; break;
@@ -244,7 +241,6 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
} }
@Override
public Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception public Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception
{ {
final Map<Path, Throwable> executionFailures = executeScripts(Arrays.asList(sourcePath)); final Map<Path, Throwable> executionFailures = executeScripts(Arrays.asList(sourcePath));
@@ -254,4 +250,9 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
return null; return null;
} }
public final Path getCurrentExecutingScript()
{
return _currentExecutingScript;
}
} }

View File

@@ -16,77 +16,66 @@
*/ */
package com.l2jmobius.gameserver.scripting.java; package com.l2jmobius.gameserver.scripting.java;
import java.util.Arrays; import java.io.FileInputStream;
import java.util.HashMap;
import javax.lang.model.SourceVersion; import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.logging.Logger;
import org.openjavac.tools.JavaCompiler; import org.openjavac.tools.JavaCompiler;
import org.openjavac.tools.javac.api.JavacTool; import org.openjavac.tools.javac.api.JavacTool;
import com.l2jmobius.gameserver.scripting.AbstractScriptingEngine;
import com.l2jmobius.gameserver.scripting.IExecutionContext;
/** /**
* @author HorridoJoho, Mobius * @author Mobius
*/ */
public final class JavaScriptingEngine extends AbstractScriptingEngine public class JavaScriptingEngine
{ {
private volatile JavaCompiler _compiler; private static final Logger LOGGER = Logger.getLogger(JavaScriptingEngine.class.getName());
private final static Map<String, String> _properties = new HashMap<>();
private final static JavaCompiler _compiler = JavacTool.create();
public JavaScriptingEngine() public JavaScriptingEngine()
{ {
super("Java Engine", "10", "java"); // Load config.
} Properties props = new Properties();
try (FileInputStream fis = new FileInputStream("config/ScriptEngine.ini"))
private void determineCompilerOrThrow()
{
if (_compiler == null)
{ {
_compiler = JavacTool.create(); props.load(fis);
}
catch (Exception e)
{
LOGGER.warning("Could not load ScriptEngine.ini: " + e.getMessage());
} }
if (_compiler == null) // Set properties.
for (Entry<Object, Object> prop : props.entrySet())
{ {
throw new IllegalStateException("No JavaCompiler service installed!"); String key = (String) prop.getKey();
} String value = (String) prop.getValue();
}
if (value.startsWith("%") && value.endsWith("%"))
private void ensureCompilerOrThrow()
{
if (_compiler == null)
{
synchronized (this)
{ {
if (_compiler == null) value = System.getProperty(value.substring(1, value.length() - 1));
{
determineCompilerOrThrow();
}
} }
_properties.put(key, value);
} }
} }
JavaCompiler getCompiler() public JavaExecutionContext createExecutionContext()
{ {
return _compiler;
}
@Override
public IExecutionContext createExecutionContext()
{
ensureCompilerOrThrow();
return new JavaExecutionContext(this); return new JavaExecutionContext(this);
} }
@Override public final String getProperty(String key)
public String getLanguageName()
{ {
return "Java"; return _properties.get(key);
} }
@Override public JavaCompiler getCompiler()
public String getLanguageVersion()
{ {
ensureCompilerOrThrow(); return _compiler;
return Arrays.deepToString(_compiler.getSourceVersions().toArray(new SourceVersion[0])).replace("RELEASE_", "");
} }
} }

View File

@@ -144,5 +144,4 @@ final class ScriptingOutputFileObject implements JavaFileObject
{ {
return null; return null;
} }
} }

View File

@@ -1,23 +1,23 @@
############################################################################### # ---------------------------------------------------------------------------
# Properties retrived with System.getProperty(String) can be used as values # Script Engine Settings
# ---------------------------------------------------------------------------
# Properties retrieved with System.getProperty(String) can be used as values
# by enclosing the property name with %. Eg.: %java.class.path% # by enclosing the property name with %. Eg.: %java.class.path%
###############################################################################
# The parent class loader for isolated script class loaders. # The parent class loader for isolated script class loaders.
# When this property is not specified, has an invalid value or is a class name which could not be found, the System classloader is used. # When this property is not specified, has an invalid value or is a class name which could not be found, the System classloader is used.
# Values: System, ThreadContext or a fully qualified java class name # Values: System, ThreadContext or a fully qualified java class name
language.Java.classloader=System classloader=System
#language.Java.classloader=ThreadContext #classloader=ThreadContext
# Source compatibility # Source compatibility.
language.Java.source=1.8 source=1.8
# The java sourcepath, when you have a different datapack root, you must change this too. # The java sourcepath, when you have a different datapack root, you must change this too.
language.Java.sourcepath=data/scripts sourcepath=data/scripts
# The java classpath # The java classpath.
language.Java.cp=%java.class.path% cp=%java.class.path%
# The debug informations to generate for compiled class files # The debug informations to generate for compiled class files.
language.Java.g=source,lines,vars g=source,lines,vars

View File

@@ -1,75 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
/**
* @author HorridoJoho
* @param <T>
*/
public abstract class AbstractExecutionContext<T extends IScriptingEngine> implements IExecutionContext
{
private final T _engine;
private final Map<String, String> _properties;
private volatile Path _currentExecutingScipt;
protected AbstractExecutionContext(T engine)
{
if (engine == null)
{
throw new IllegalArgumentException();
}
_engine = engine;
_properties = new HashMap<>();
}
protected final void setCurrentExecutingScript(Path currentExecutingScript)
{
_currentExecutingScipt = currentExecutingScript;
}
@Override
public final String setProperty(String key, String value)
{
return _properties.put(key, value);
}
@Override
public final String getProperty(String key)
{
if (!_properties.containsKey(key))
{
return _engine.getProperty(key);
}
return _properties.get(key);
}
@Override
public final Path getCurrentExecutingScript()
{
return _currentExecutingScipt;
}
@Override
public final T getScriptingEngine()
{
return _engine;
}
}

View File

@@ -1,74 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @author HorridoJoho
*/
public abstract class AbstractScriptingEngine implements IScriptingEngine
{
private final String _engineName;
private final String _engineVersion;
private final String[] _commonFileExtensions;
private final Map<String, String> _properties;
protected AbstractScriptingEngine(String engineName, String engineVersion, String... commonFileExtensions)
{
if ((engineName == null) || engineName.isEmpty() || (engineVersion == null) || engineVersion.isEmpty() || (commonFileExtensions == null) || (commonFileExtensions.length == 0))
{
throw new IllegalArgumentException();
}
_engineName = engineName;
_engineVersion = engineVersion;
_commonFileExtensions = commonFileExtensions;
_properties = new HashMap<>();
}
@Override
public final String setProperty(String key, String value)
{
return _properties.put(key, value);
}
@Override
public final String getProperty(String key)
{
return _properties.get(key);
}
@Override
public final String getEngineName()
{
return _engineName;
}
@Override
public final String getEngineVersion()
{
return _engineVersion;
}
@Override
public final String[] getCommonFileExtensions()
{
return Arrays.copyOf(_commonFileExtensions, _commonFileExtensions.length);
}
}

View File

@@ -1,71 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.nio.file.Path;
import java.util.Map;
import java.util.Map.Entry;
/**
* @author HorridoJoho
*/
public interface IExecutionContext
{
/**
* Properties set here override the settings from the IScriptEngine<br>
* this class was created from.
* @param key the key
* @param value the value
* @return the previous value, or null when this key was not present before
*/
String setProperty(String key, String value);
/**
* Executes all script in the iterable.
* @param sourcePaths the scripts to execute
* @return map of failed executions, Path=source file Throwable=thrown exception
* @throws Exception preparation for script execution failed
*/
Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception;
/**
* Executes a single file.
* @param sourcePath the script to execute
* @return entry of failed execution, Path=source file Throwable=thrown exception
* @throws Exception preparation for script execution failed
*/
Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception;
/**
* Method to get the specified property value.
* @param key the key
* @return the value, or null if the key is not present
*/
String getProperty(String key);
/**
* Method to get the current executing script file.
* @return the currently executing script file, null if non
*/
Path getCurrentExecutingScript();
/**
* Method to get the script engine this execution context belongs to.
* @return the script engine this execution context belongs to
*/
IScriptingEngine getScriptingEngine();
}

View File

@@ -1,75 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
/**
* @author HorridoJoho
*/
public interface IScriptingEngine
{
/**
* Sets script engine properties. The script values will be available<br>
* to the the insatnces created {@link IExecutionContext} implementation.
* @param key the key
* @param value the value
* @return the previous value, or null when this key was not present before
*/
String setProperty(String key, String value);
/**
* Creates an execution context.
* @return the created execution context.
*/
IExecutionContext createExecutionContext();
/**
* Method to get the specified property value.
* @param key the key
* @return the value,or null if the key is not present
*/
String getProperty(String key);
/**
* Method to get the engine name.
* @return the engine name
*/
String getEngineName();
/**
* Method to get the engine version.
* @return the engine version
*/
String getEngineVersion();
/**
* Method to get the scripting language name.
* @return the scripting engine name
*/
String getLanguageName();
/**
* Method to get the the language version.
* @return the language version
*/
String getLanguageVersion();
/**
* Method to retrive the commonly used file extensions for the language.
* @return the commonly used file extensions for the language
*/
String[] getCommonFileExtensions();
}

View File

@@ -17,7 +17,6 @@
package com.l2jmobius.gameserver.scripting; package com.l2jmobius.gameserver.scripting;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.file.FileVisitResult; import java.nio.file.FileVisitResult;
import java.nio.file.Files; import java.nio.file.Files;
@@ -31,9 +30,6 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Objects;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@@ -41,15 +37,16 @@ import org.w3c.dom.Document;
import com.l2jmobius.Config; import com.l2jmobius.Config;
import com.l2jmobius.commons.util.IXmlReader; import com.l2jmobius.commons.util.IXmlReader;
import com.l2jmobius.gameserver.scripting.java.JavaExecutionContext;
import com.l2jmobius.gameserver.scripting.java.JavaScriptingEngine; import com.l2jmobius.gameserver.scripting.java.JavaScriptingEngine;
/** /**
* Caches script engines and provides functionality for executing and managing scripts. * @author Mobius
* @author KenM, HorridoJoho
*/ */
public final class ScriptEngineManager implements IXmlReader public final class ScriptEngineManager implements IXmlReader
{ {
private static final Logger LOGGER = Logger.getLogger(ScriptEngineManager.class.getName()); private static final Logger LOGGER = Logger.getLogger(ScriptEngineManager.class.getName());
public static final Path SCRIPT_FOLDER = Config.SCRIPT_ROOT.toPath(); public static final Path SCRIPT_FOLDER = Config.SCRIPT_ROOT.toPath();
public static final Path MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "MasterHandler.java"); public static final Path MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "MasterHandler.java");
public static final Path EFFECT_MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "EffectMasterHandler.java"); public static final Path EFFECT_MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "EffectMasterHandler.java");
@@ -57,19 +54,11 @@ public final class ScriptEngineManager implements IXmlReader
public static final Path CONDITION_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "ConditionMasterHandler.java"); public static final Path CONDITION_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "ConditionMasterHandler.java");
public static final Path ONE_DAY_REWARD_MASTER_HANDLER = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "DailyMissionMasterHandler.java"); public static final Path ONE_DAY_REWARD_MASTER_HANDLER = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "DailyMissionMasterHandler.java");
private IExecutionContext _javaExecutionContext = null; private static final JavaExecutionContext _javaExecutionContext = new JavaScriptingEngine().createExecutionContext();
static final List<String> _exclusions = new ArrayList<>(); protected static final List<String> _exclusions = new ArrayList<>();
protected ScriptEngineManager() protected ScriptEngineManager()
{ {
final Properties props = loadProperties();
// Default java engine implementation
registerEngine(new JavaScriptingEngine(), props);
// Load external script engines
ServiceLoader.load(IScriptingEngine.class).forEach(engine -> registerEngine(engine, props));
// Load Scripts.xml // Load Scripts.xml
load(); load();
} }
@@ -144,71 +133,6 @@ public final class ScriptEngineManager implements IXmlReader
} }
} }
private Properties loadProperties()
{
Properties props = null;
try (FileInputStream fis = new FileInputStream("config/ScriptEngine.ini"))
{
props = new Properties();
props.load(fis);
}
catch (Exception e)
{
props = null;
LOGGER.warning("Couldn't load ScriptEngine.ini: " + e.getMessage());
}
return props;
}
private void registerEngine(IScriptingEngine engine, Properties props)
{
maybeSetProperties("language." + engine.getLanguageName() + ".", props, engine);
_javaExecutionContext = engine.createExecutionContext();
LOGGER.info("ScriptEngine: " + engine.getEngineName() + " " + engine.getEngineVersion() + " (" + engine.getLanguageName() + " " + engine.getLanguageVersion() + ")");
}
private void maybeSetProperties(String propPrefix, Properties props, IScriptingEngine engine)
{
if (props == null)
{
return;
}
for (Entry<Object, Object> prop : props.entrySet())
{
String key = (String) prop.getKey();
String value = (String) prop.getValue();
if (key.startsWith(propPrefix))
{
key = key.substring(propPrefix.length());
if (value.startsWith("%") && value.endsWith("%"))
{
value = System.getProperty(value.substring(1, value.length() - 1));
}
engine.setProperty(key, value);
}
}
}
public void executeScriptList() throws Exception
{
if (Config.ALT_DEV_NO_QUESTS)
{
return;
}
final List<Path> files = new ArrayList<>();
processDirectory(SCRIPT_FOLDER.toFile(), files);
final Map<Path, Throwable> invokationErrors = _javaExecutionContext.executeScripts(files);
for (Entry<Path, Throwable> entry : invokationErrors.entrySet())
{
LOGGER.log(Level.WARNING, "ScriptEngine: " + entry.getKey() + " failed execution!", entry.getValue());
}
}
private void processDirectory(File dir, List<Path> files) private void processDirectory(File dir, List<Path> files)
{ {
for (File file : dir.listFiles()) for (File file : dir.listFiles())
@@ -230,15 +154,12 @@ public final class ScriptEngineManager implements IXmlReader
public void executeScript(Path sourceFile) throws Exception public void executeScript(Path sourceFile) throws Exception
{ {
Objects.requireNonNull(sourceFile);
if (!sourceFile.isAbsolute()) if (!sourceFile.isAbsolute())
{ {
sourceFile = SCRIPT_FOLDER.resolve(sourceFile); sourceFile = SCRIPT_FOLDER.resolve(sourceFile);
} }
sourceFile = sourceFile.toAbsolutePath(); sourceFile = sourceFile.toAbsolutePath();
Objects.requireNonNull(sourceFile, "ScriptFile: " + sourceFile + " does not have an extension to determine the script engine!");
final Entry<Path, Throwable> error = _javaExecutionContext.executeScript(sourceFile); final Entry<Path, Throwable> error = _javaExecutionContext.executeScript(sourceFile);
if (error != null) if (error != null)
@@ -247,6 +168,23 @@ public final class ScriptEngineManager implements IXmlReader
} }
} }
public void executeScriptList() throws Exception
{
if (Config.ALT_DEV_NO_QUESTS)
{
return;
}
final List<Path> files = new ArrayList<>();
processDirectory(SCRIPT_FOLDER.toFile(), files);
final Map<Path, Throwable> invokationErrors = _javaExecutionContext.executeScripts(files);
for (Entry<Path, Throwable> entry : invokationErrors.entrySet())
{
LOGGER.log(Level.WARNING, "ScriptEngine: " + entry.getKey() + " failed execution!", entry.getValue());
}
}
public Path getCurrentLoadingScript() public Path getCurrentLoadingScript()
{ {
return _javaExecutionContext.getCurrentExecutingScript(); return _javaExecutionContext.getCurrentExecutingScript();
@@ -254,11 +192,11 @@ public final class ScriptEngineManager implements IXmlReader
public static ScriptEngineManager getInstance() public static ScriptEngineManager getInstance()
{ {
return SingletonHolder._instance; return SingletonHolder.INSTANCE;
} }
private static class SingletonHolder private static class SingletonHolder
{ {
protected static final ScriptEngineManager _instance = new ScriptEngineManager(); protected static final ScriptEngineManager INSTANCE = new ScriptEngineManager();
} }
} }

View File

@@ -1,28 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting.java;
/**
* @author HorridoJoho
*/
public final class JavaCompilerException extends RuntimeException
{
public JavaCompilerException(String diagnostics)
{
super(diagnostics);
}
}

View File

@@ -22,9 +22,9 @@ import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.LinkedHashMap; import java.util.HashMap;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
@@ -34,22 +34,20 @@ import org.openjavac.tools.Diagnostic;
import org.openjavac.tools.DiagnosticCollector; import org.openjavac.tools.DiagnosticCollector;
import org.openjavac.tools.JavaFileObject; import org.openjavac.tools.JavaFileObject;
import com.l2jmobius.gameserver.scripting.AbstractExecutionContext;
import com.l2jmobius.gameserver.scripting.annotations.Disabled; import com.l2jmobius.gameserver.scripting.annotations.Disabled;
/** /**
* @author HorridoJoho * @author HorridoJoho
*/ */
public final class JavaExecutionContext extends AbstractExecutionContext<JavaScriptingEngine> public final class JavaExecutionContext extends JavaScriptingEngine
{ {
private static final Logger LOGGER = Logger.getLogger(JavaExecutionContext.class.getName()); private static final Logger LOGGER = Logger.getLogger(JavaExecutionContext.class.getName());
private static final List<String> _options = new LinkedList<>(); private static final List<String> _options = new ArrayList<>();
private static Path _currentExecutingScript;
JavaExecutionContext(JavaScriptingEngine engine) JavaExecutionContext(JavaScriptingEngine engine)
{ {
super(engine);
// Set options. // Set options.
addOptionIfNotNull(_options, getProperty("source"), "-source"); addOptionIfNotNull(_options, getProperty("source"), "-source");
addOptionIfNotNull(_options, getProperty("sourcepath"), "-sourcepath"); addOptionIfNotNull(_options, getProperty("sourcepath"), "-sourcepath");
@@ -76,7 +74,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
else else
{ {
throw new JavaCompilerException("Could not determine target version!"); throw new RuntimeException("Could not determine target version!");
} }
} }
} }
@@ -133,16 +131,15 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
} }
@Override
public Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception public Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception
{ {
final DiagnosticCollector<JavaFileObject> fileManagerDiagnostics = new DiagnosticCollector<>(); final DiagnosticCollector<JavaFileObject> fileManagerDiagnostics = new DiagnosticCollector<>();
final DiagnosticCollector<JavaFileObject> compilationDiagnostics = new DiagnosticCollector<>(); final DiagnosticCollector<JavaFileObject> compilationDiagnostics = new DiagnosticCollector<>();
try (ScriptingFileManager fileManager = new ScriptingFileManager(getScriptingEngine().getCompiler().getStandardFileManager(fileManagerDiagnostics, null, StandardCharsets.UTF_8))) try (ScriptingFileManager fileManager = new ScriptingFileManager(getCompiler().getStandardFileManager(fileManagerDiagnostics, null, StandardCharsets.UTF_8)))
{ {
// We really need an iterable of files or strings. // We really need an iterable of files or strings.
final List<String> sourcePathStrings = new LinkedList<>(); final List<String> sourcePathStrings = new ArrayList<>();
for (Path sourcePath : sourcePaths) for (Path sourcePath : sourcePaths)
{ {
sourcePathStrings.add(sourcePath.toString()); sourcePathStrings.add(sourcePath.toString());
@@ -150,7 +147,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
final StringWriter strOut = new StringWriter(); final StringWriter strOut = new StringWriter();
final PrintWriter out = new PrintWriter(strOut); final PrintWriter out = new PrintWriter(strOut);
final boolean compilationSuccess = getScriptingEngine().getCompiler().getTask(out, fileManager, compilationDiagnostics, _options, null, fileManager.getJavaFileObjectsFromStrings(sourcePathStrings)).call(); final boolean compilationSuccess = getCompiler().getTask(out, fileManager, compilationDiagnostics, _options, null, fileManager.getJavaFileObjectsFromStrings(sourcePathStrings)).call();
if (!compilationSuccess) if (!compilationSuccess)
{ {
out.println(); out.println();
@@ -175,12 +172,12 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
out.println("\t\tmessage: " + diagnostic.getMessage(null)); out.println("\t\tmessage: " + diagnostic.getMessage(null));
} }
throw new JavaCompilerException(strOut.toString()); throw new RuntimeException(strOut.toString());
} }
final ClassLoader parentClassLoader = determineScriptParentClassloader(); final ClassLoader parentClassLoader = determineScriptParentClassloader();
final Map<Path, Throwable> executionFailures = new LinkedHashMap<>(); final Map<Path, Throwable> executionFailures = new HashMap<>();
final Iterable<ScriptingOutputFileObject> compiledClasses = fileManager.getCompiledClasses(); final Iterable<ScriptingOutputFileObject> compiledClasses = fileManager.getCompiledClasses();
for (Path sourcePath : sourcePaths) for (Path sourcePath : sourcePaths)
{ {
@@ -199,7 +196,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
found = true; found = true;
setCurrentExecutingScript(compiledSourcePath); _currentExecutingScript = compiledSourcePath;
try try
{ {
final ScriptingClassLoader loader = new ScriptingClassLoader(parentClassLoader, compiledClasses); final ScriptingClassLoader loader = new ScriptingClassLoader(parentClassLoader, compiledClasses);
@@ -227,7 +224,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
finally finally
{ {
setCurrentExecutingScript(null); _currentExecutingScript = null;
} }
break; break;
@@ -244,7 +241,6 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
} }
@Override
public Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception public Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception
{ {
final Map<Path, Throwable> executionFailures = executeScripts(Arrays.asList(sourcePath)); final Map<Path, Throwable> executionFailures = executeScripts(Arrays.asList(sourcePath));
@@ -254,4 +250,9 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
return null; return null;
} }
public final Path getCurrentExecutingScript()
{
return _currentExecutingScript;
}
} }

View File

@@ -16,77 +16,66 @@
*/ */
package com.l2jmobius.gameserver.scripting.java; package com.l2jmobius.gameserver.scripting.java;
import java.util.Arrays; import java.io.FileInputStream;
import java.util.HashMap;
import javax.lang.model.SourceVersion; import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.logging.Logger;
import org.openjavac.tools.JavaCompiler; import org.openjavac.tools.JavaCompiler;
import org.openjavac.tools.javac.api.JavacTool; import org.openjavac.tools.javac.api.JavacTool;
import com.l2jmobius.gameserver.scripting.AbstractScriptingEngine;
import com.l2jmobius.gameserver.scripting.IExecutionContext;
/** /**
* @author HorridoJoho, Mobius * @author Mobius
*/ */
public final class JavaScriptingEngine extends AbstractScriptingEngine public class JavaScriptingEngine
{ {
private volatile JavaCompiler _compiler; private static final Logger LOGGER = Logger.getLogger(JavaScriptingEngine.class.getName());
private final static Map<String, String> _properties = new HashMap<>();
private final static JavaCompiler _compiler = JavacTool.create();
public JavaScriptingEngine() public JavaScriptingEngine()
{ {
super("Java Engine", "10", "java"); // Load config.
} Properties props = new Properties();
try (FileInputStream fis = new FileInputStream("config/ScriptEngine.ini"))
private void determineCompilerOrThrow()
{
if (_compiler == null)
{ {
_compiler = JavacTool.create(); props.load(fis);
}
catch (Exception e)
{
LOGGER.warning("Could not load ScriptEngine.ini: " + e.getMessage());
} }
if (_compiler == null) // Set properties.
for (Entry<Object, Object> prop : props.entrySet())
{ {
throw new IllegalStateException("No JavaCompiler service installed!"); String key = (String) prop.getKey();
} String value = (String) prop.getValue();
}
if (value.startsWith("%") && value.endsWith("%"))
private void ensureCompilerOrThrow()
{
if (_compiler == null)
{
synchronized (this)
{ {
if (_compiler == null) value = System.getProperty(value.substring(1, value.length() - 1));
{
determineCompilerOrThrow();
}
} }
_properties.put(key, value);
} }
} }
JavaCompiler getCompiler() public JavaExecutionContext createExecutionContext()
{ {
return _compiler;
}
@Override
public IExecutionContext createExecutionContext()
{
ensureCompilerOrThrow();
return new JavaExecutionContext(this); return new JavaExecutionContext(this);
} }
@Override public final String getProperty(String key)
public String getLanguageName()
{ {
return "Java"; return _properties.get(key);
} }
@Override public JavaCompiler getCompiler()
public String getLanguageVersion()
{ {
ensureCompilerOrThrow(); return _compiler;
return Arrays.deepToString(_compiler.getSourceVersions().toArray(new SourceVersion[0])).replace("RELEASE_", "");
} }
} }

View File

@@ -144,5 +144,4 @@ final class ScriptingOutputFileObject implements JavaFileObject
{ {
return null; return null;
} }
} }

View File

@@ -1,23 +1,23 @@
############################################################################### # ---------------------------------------------------------------------------
# Properties retrived with System.getProperty(String) can be used as values # Script Engine Settings
# ---------------------------------------------------------------------------
# Properties retrieved with System.getProperty(String) can be used as values
# by enclosing the property name with %. Eg.: %java.class.path% # by enclosing the property name with %. Eg.: %java.class.path%
###############################################################################
# The parent class loader for isolated script class loaders. # The parent class loader for isolated script class loaders.
# When this property is not specified, has an invalid value or is a class name which could not be found, the System classloader is used. # When this property is not specified, has an invalid value or is a class name which could not be found, the System classloader is used.
# Values: System, ThreadContext or a fully qualified java class name # Values: System, ThreadContext or a fully qualified java class name
language.Java.classloader=System classloader=System
#language.Java.classloader=ThreadContext #classloader=ThreadContext
# Source compatibility # Source compatibility.
language.Java.source=1.8 source=1.8
# The java sourcepath, when you have a different datapack root, you must change this too. # The java sourcepath, when you have a different datapack root, you must change this too.
language.Java.sourcepath=data/scripts sourcepath=data/scripts
# The java classpath # The java classpath.
language.Java.cp=%java.class.path% cp=%java.class.path%
# The debug informations to generate for compiled class files # The debug informations to generate for compiled class files.
language.Java.g=source,lines,vars g=source,lines,vars

View File

@@ -1,75 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
/**
* @author HorridoJoho
* @param <T>
*/
public abstract class AbstractExecutionContext<T extends IScriptingEngine> implements IExecutionContext
{
private final T _engine;
private final Map<String, String> _properties;
private volatile Path _currentExecutingScipt;
protected AbstractExecutionContext(T engine)
{
if (engine == null)
{
throw new IllegalArgumentException();
}
_engine = engine;
_properties = new HashMap<>();
}
protected final void setCurrentExecutingScript(Path currentExecutingScript)
{
_currentExecutingScipt = currentExecutingScript;
}
@Override
public final String setProperty(String key, String value)
{
return _properties.put(key, value);
}
@Override
public final String getProperty(String key)
{
if (!_properties.containsKey(key))
{
return _engine.getProperty(key);
}
return _properties.get(key);
}
@Override
public final Path getCurrentExecutingScript()
{
return _currentExecutingScipt;
}
@Override
public final T getScriptingEngine()
{
return _engine;
}
}

View File

@@ -1,74 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @author HorridoJoho
*/
public abstract class AbstractScriptingEngine implements IScriptingEngine
{
private final String _engineName;
private final String _engineVersion;
private final String[] _commonFileExtensions;
private final Map<String, String> _properties;
protected AbstractScriptingEngine(String engineName, String engineVersion, String... commonFileExtensions)
{
if ((engineName == null) || engineName.isEmpty() || (engineVersion == null) || engineVersion.isEmpty() || (commonFileExtensions == null) || (commonFileExtensions.length == 0))
{
throw new IllegalArgumentException();
}
_engineName = engineName;
_engineVersion = engineVersion;
_commonFileExtensions = commonFileExtensions;
_properties = new HashMap<>();
}
@Override
public final String setProperty(String key, String value)
{
return _properties.put(key, value);
}
@Override
public final String getProperty(String key)
{
return _properties.get(key);
}
@Override
public final String getEngineName()
{
return _engineName;
}
@Override
public final String getEngineVersion()
{
return _engineVersion;
}
@Override
public final String[] getCommonFileExtensions()
{
return Arrays.copyOf(_commonFileExtensions, _commonFileExtensions.length);
}
}

View File

@@ -1,71 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.nio.file.Path;
import java.util.Map;
import java.util.Map.Entry;
/**
* @author HorridoJoho
*/
public interface IExecutionContext
{
/**
* Properties set here override the settings from the IScriptEngine<br>
* this class was created from.
* @param key the key
* @param value the value
* @return the previous value, or null when this key was not present before
*/
String setProperty(String key, String value);
/**
* Executes all script in the iterable.
* @param sourcePaths the scripts to execute
* @return map of failed executions, Path=source file Throwable=thrown exception
* @throws Exception preparation for script execution failed
*/
Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception;
/**
* Executes a single file.
* @param sourcePath the script to execute
* @return entry of failed execution, Path=source file Throwable=thrown exception
* @throws Exception preparation for script execution failed
*/
Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception;
/**
* Method to get the specified property value.
* @param key the key
* @return the value, or null if the key is not present
*/
String getProperty(String key);
/**
* Method to get the current executing script file.
* @return the currently executing script file, null if non
*/
Path getCurrentExecutingScript();
/**
* Method to get the script engine this execution context belongs to.
* @return the script engine this execution context belongs to
*/
IScriptingEngine getScriptingEngine();
}

View File

@@ -1,75 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
/**
* @author HorridoJoho
*/
public interface IScriptingEngine
{
/**
* Sets script engine properties. The script values will be available<br>
* to the the insatnces created {@link IExecutionContext} implementation.
* @param key the key
* @param value the value
* @return the previous value, or null when this key was not present before
*/
String setProperty(String key, String value);
/**
* Creates an execution context.
* @return the created execution context.
*/
IExecutionContext createExecutionContext();
/**
* Method to get the specified property value.
* @param key the key
* @return the value,or null if the key is not present
*/
String getProperty(String key);
/**
* Method to get the engine name.
* @return the engine name
*/
String getEngineName();
/**
* Method to get the engine version.
* @return the engine version
*/
String getEngineVersion();
/**
* Method to get the scripting language name.
* @return the scripting engine name
*/
String getLanguageName();
/**
* Method to get the the language version.
* @return the language version
*/
String getLanguageVersion();
/**
* Method to retrive the commonly used file extensions for the language.
* @return the commonly used file extensions for the language
*/
String[] getCommonFileExtensions();
}

View File

@@ -17,7 +17,6 @@
package com.l2jmobius.gameserver.scripting; package com.l2jmobius.gameserver.scripting;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.file.FileVisitResult; import java.nio.file.FileVisitResult;
import java.nio.file.Files; import java.nio.file.Files;
@@ -31,9 +30,6 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Objects;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@@ -41,15 +37,16 @@ import org.w3c.dom.Document;
import com.l2jmobius.Config; import com.l2jmobius.Config;
import com.l2jmobius.commons.util.IXmlReader; import com.l2jmobius.commons.util.IXmlReader;
import com.l2jmobius.gameserver.scripting.java.JavaExecutionContext;
import com.l2jmobius.gameserver.scripting.java.JavaScriptingEngine; import com.l2jmobius.gameserver.scripting.java.JavaScriptingEngine;
/** /**
* Caches script engines and provides functionality for executing and managing scripts. * @author Mobius
* @author KenM, HorridoJoho
*/ */
public final class ScriptEngineManager implements IXmlReader public final class ScriptEngineManager implements IXmlReader
{ {
private static final Logger LOGGER = Logger.getLogger(ScriptEngineManager.class.getName()); private static final Logger LOGGER = Logger.getLogger(ScriptEngineManager.class.getName());
public static final Path SCRIPT_FOLDER = Config.SCRIPT_ROOT.toPath(); public static final Path SCRIPT_FOLDER = Config.SCRIPT_ROOT.toPath();
public static final Path MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "MasterHandler.java"); public static final Path MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "MasterHandler.java");
public static final Path EFFECT_MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "EffectMasterHandler.java"); public static final Path EFFECT_MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "EffectMasterHandler.java");
@@ -57,19 +54,11 @@ public final class ScriptEngineManager implements IXmlReader
public static final Path CONDITION_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "ConditionMasterHandler.java"); public static final Path CONDITION_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "ConditionMasterHandler.java");
public static final Path ONE_DAY_REWARD_MASTER_HANDLER = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "DailyMissionMasterHandler.java"); public static final Path ONE_DAY_REWARD_MASTER_HANDLER = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "DailyMissionMasterHandler.java");
private IExecutionContext _javaExecutionContext = null; private static final JavaExecutionContext _javaExecutionContext = new JavaScriptingEngine().createExecutionContext();
static final List<String> _exclusions = new ArrayList<>(); protected static final List<String> _exclusions = new ArrayList<>();
protected ScriptEngineManager() protected ScriptEngineManager()
{ {
final Properties props = loadProperties();
// Default java engine implementation
registerEngine(new JavaScriptingEngine(), props);
// Load external script engines
ServiceLoader.load(IScriptingEngine.class).forEach(engine -> registerEngine(engine, props));
// Load Scripts.xml // Load Scripts.xml
load(); load();
} }
@@ -144,71 +133,6 @@ public final class ScriptEngineManager implements IXmlReader
} }
} }
private Properties loadProperties()
{
Properties props = null;
try (FileInputStream fis = new FileInputStream("config/ScriptEngine.ini"))
{
props = new Properties();
props.load(fis);
}
catch (Exception e)
{
props = null;
LOGGER.warning("Couldn't load ScriptEngine.ini: " + e.getMessage());
}
return props;
}
private void registerEngine(IScriptingEngine engine, Properties props)
{
maybeSetProperties("language." + engine.getLanguageName() + ".", props, engine);
_javaExecutionContext = engine.createExecutionContext();
LOGGER.info("ScriptEngine: " + engine.getEngineName() + " " + engine.getEngineVersion() + " (" + engine.getLanguageName() + " " + engine.getLanguageVersion() + ")");
}
private void maybeSetProperties(String propPrefix, Properties props, IScriptingEngine engine)
{
if (props == null)
{
return;
}
for (Entry<Object, Object> prop : props.entrySet())
{
String key = (String) prop.getKey();
String value = (String) prop.getValue();
if (key.startsWith(propPrefix))
{
key = key.substring(propPrefix.length());
if (value.startsWith("%") && value.endsWith("%"))
{
value = System.getProperty(value.substring(1, value.length() - 1));
}
engine.setProperty(key, value);
}
}
}
public void executeScriptList() throws Exception
{
if (Config.ALT_DEV_NO_QUESTS)
{
return;
}
final List<Path> files = new ArrayList<>();
processDirectory(SCRIPT_FOLDER.toFile(), files);
final Map<Path, Throwable> invokationErrors = _javaExecutionContext.executeScripts(files);
for (Entry<Path, Throwable> entry : invokationErrors.entrySet())
{
LOGGER.log(Level.WARNING, "ScriptEngine: " + entry.getKey() + " failed execution!", entry.getValue());
}
}
private void processDirectory(File dir, List<Path> files) private void processDirectory(File dir, List<Path> files)
{ {
for (File file : dir.listFiles()) for (File file : dir.listFiles())
@@ -230,15 +154,12 @@ public final class ScriptEngineManager implements IXmlReader
public void executeScript(Path sourceFile) throws Exception public void executeScript(Path sourceFile) throws Exception
{ {
Objects.requireNonNull(sourceFile);
if (!sourceFile.isAbsolute()) if (!sourceFile.isAbsolute())
{ {
sourceFile = SCRIPT_FOLDER.resolve(sourceFile); sourceFile = SCRIPT_FOLDER.resolve(sourceFile);
} }
sourceFile = sourceFile.toAbsolutePath(); sourceFile = sourceFile.toAbsolutePath();
Objects.requireNonNull(sourceFile, "ScriptFile: " + sourceFile + " does not have an extension to determine the script engine!");
final Entry<Path, Throwable> error = _javaExecutionContext.executeScript(sourceFile); final Entry<Path, Throwable> error = _javaExecutionContext.executeScript(sourceFile);
if (error != null) if (error != null)
@@ -247,6 +168,23 @@ public final class ScriptEngineManager implements IXmlReader
} }
} }
public void executeScriptList() throws Exception
{
if (Config.ALT_DEV_NO_QUESTS)
{
return;
}
final List<Path> files = new ArrayList<>();
processDirectory(SCRIPT_FOLDER.toFile(), files);
final Map<Path, Throwable> invokationErrors = _javaExecutionContext.executeScripts(files);
for (Entry<Path, Throwable> entry : invokationErrors.entrySet())
{
LOGGER.log(Level.WARNING, "ScriptEngine: " + entry.getKey() + " failed execution!", entry.getValue());
}
}
public Path getCurrentLoadingScript() public Path getCurrentLoadingScript()
{ {
return _javaExecutionContext.getCurrentExecutingScript(); return _javaExecutionContext.getCurrentExecutingScript();
@@ -254,11 +192,11 @@ public final class ScriptEngineManager implements IXmlReader
public static ScriptEngineManager getInstance() public static ScriptEngineManager getInstance()
{ {
return SingletonHolder._instance; return SingletonHolder.INSTANCE;
} }
private static class SingletonHolder private static class SingletonHolder
{ {
protected static final ScriptEngineManager _instance = new ScriptEngineManager(); protected static final ScriptEngineManager INSTANCE = new ScriptEngineManager();
} }
} }

View File

@@ -1,28 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting.java;
/**
* @author HorridoJoho
*/
public final class JavaCompilerException extends RuntimeException
{
public JavaCompilerException(String diagnostics)
{
super(diagnostics);
}
}

View File

@@ -22,9 +22,9 @@ import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.LinkedHashMap; import java.util.HashMap;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
@@ -34,22 +34,20 @@ import org.openjavac.tools.Diagnostic;
import org.openjavac.tools.DiagnosticCollector; import org.openjavac.tools.DiagnosticCollector;
import org.openjavac.tools.JavaFileObject; import org.openjavac.tools.JavaFileObject;
import com.l2jmobius.gameserver.scripting.AbstractExecutionContext;
import com.l2jmobius.gameserver.scripting.annotations.Disabled; import com.l2jmobius.gameserver.scripting.annotations.Disabled;
/** /**
* @author HorridoJoho * @author HorridoJoho
*/ */
public final class JavaExecutionContext extends AbstractExecutionContext<JavaScriptingEngine> public final class JavaExecutionContext extends JavaScriptingEngine
{ {
private static final Logger LOGGER = Logger.getLogger(JavaExecutionContext.class.getName()); private static final Logger LOGGER = Logger.getLogger(JavaExecutionContext.class.getName());
private static final List<String> _options = new LinkedList<>(); private static final List<String> _options = new ArrayList<>();
private static Path _currentExecutingScript;
JavaExecutionContext(JavaScriptingEngine engine) JavaExecutionContext(JavaScriptingEngine engine)
{ {
super(engine);
// Set options. // Set options.
addOptionIfNotNull(_options, getProperty("source"), "-source"); addOptionIfNotNull(_options, getProperty("source"), "-source");
addOptionIfNotNull(_options, getProperty("sourcepath"), "-sourcepath"); addOptionIfNotNull(_options, getProperty("sourcepath"), "-sourcepath");
@@ -76,7 +74,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
else else
{ {
throw new JavaCompilerException("Could not determine target version!"); throw new RuntimeException("Could not determine target version!");
} }
} }
} }
@@ -133,16 +131,15 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
} }
@Override
public Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception public Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception
{ {
final DiagnosticCollector<JavaFileObject> fileManagerDiagnostics = new DiagnosticCollector<>(); final DiagnosticCollector<JavaFileObject> fileManagerDiagnostics = new DiagnosticCollector<>();
final DiagnosticCollector<JavaFileObject> compilationDiagnostics = new DiagnosticCollector<>(); final DiagnosticCollector<JavaFileObject> compilationDiagnostics = new DiagnosticCollector<>();
try (ScriptingFileManager fileManager = new ScriptingFileManager(getScriptingEngine().getCompiler().getStandardFileManager(fileManagerDiagnostics, null, StandardCharsets.UTF_8))) try (ScriptingFileManager fileManager = new ScriptingFileManager(getCompiler().getStandardFileManager(fileManagerDiagnostics, null, StandardCharsets.UTF_8)))
{ {
// We really need an iterable of files or strings. // We really need an iterable of files or strings.
final List<String> sourcePathStrings = new LinkedList<>(); final List<String> sourcePathStrings = new ArrayList<>();
for (Path sourcePath : sourcePaths) for (Path sourcePath : sourcePaths)
{ {
sourcePathStrings.add(sourcePath.toString()); sourcePathStrings.add(sourcePath.toString());
@@ -150,7 +147,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
final StringWriter strOut = new StringWriter(); final StringWriter strOut = new StringWriter();
final PrintWriter out = new PrintWriter(strOut); final PrintWriter out = new PrintWriter(strOut);
final boolean compilationSuccess = getScriptingEngine().getCompiler().getTask(out, fileManager, compilationDiagnostics, _options, null, fileManager.getJavaFileObjectsFromStrings(sourcePathStrings)).call(); final boolean compilationSuccess = getCompiler().getTask(out, fileManager, compilationDiagnostics, _options, null, fileManager.getJavaFileObjectsFromStrings(sourcePathStrings)).call();
if (!compilationSuccess) if (!compilationSuccess)
{ {
out.println(); out.println();
@@ -175,12 +172,12 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
out.println("\t\tmessage: " + diagnostic.getMessage(null)); out.println("\t\tmessage: " + diagnostic.getMessage(null));
} }
throw new JavaCompilerException(strOut.toString()); throw new RuntimeException(strOut.toString());
} }
final ClassLoader parentClassLoader = determineScriptParentClassloader(); final ClassLoader parentClassLoader = determineScriptParentClassloader();
final Map<Path, Throwable> executionFailures = new LinkedHashMap<>(); final Map<Path, Throwable> executionFailures = new HashMap<>();
final Iterable<ScriptingOutputFileObject> compiledClasses = fileManager.getCompiledClasses(); final Iterable<ScriptingOutputFileObject> compiledClasses = fileManager.getCompiledClasses();
for (Path sourcePath : sourcePaths) for (Path sourcePath : sourcePaths)
{ {
@@ -199,7 +196,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
found = true; found = true;
setCurrentExecutingScript(compiledSourcePath); _currentExecutingScript = compiledSourcePath;
try try
{ {
final ScriptingClassLoader loader = new ScriptingClassLoader(parentClassLoader, compiledClasses); final ScriptingClassLoader loader = new ScriptingClassLoader(parentClassLoader, compiledClasses);
@@ -227,7 +224,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
finally finally
{ {
setCurrentExecutingScript(null); _currentExecutingScript = null;
} }
break; break;
@@ -244,7 +241,6 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
} }
@Override
public Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception public Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception
{ {
final Map<Path, Throwable> executionFailures = executeScripts(Arrays.asList(sourcePath)); final Map<Path, Throwable> executionFailures = executeScripts(Arrays.asList(sourcePath));
@@ -254,4 +250,9 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
return null; return null;
} }
public final Path getCurrentExecutingScript()
{
return _currentExecutingScript;
}
} }

View File

@@ -16,77 +16,66 @@
*/ */
package com.l2jmobius.gameserver.scripting.java; package com.l2jmobius.gameserver.scripting.java;
import java.util.Arrays; import java.io.FileInputStream;
import java.util.HashMap;
import javax.lang.model.SourceVersion; import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.logging.Logger;
import org.openjavac.tools.JavaCompiler; import org.openjavac.tools.JavaCompiler;
import org.openjavac.tools.javac.api.JavacTool; import org.openjavac.tools.javac.api.JavacTool;
import com.l2jmobius.gameserver.scripting.AbstractScriptingEngine;
import com.l2jmobius.gameserver.scripting.IExecutionContext;
/** /**
* @author HorridoJoho, Mobius * @author Mobius
*/ */
public final class JavaScriptingEngine extends AbstractScriptingEngine public class JavaScriptingEngine
{ {
private volatile JavaCompiler _compiler; private static final Logger LOGGER = Logger.getLogger(JavaScriptingEngine.class.getName());
private final static Map<String, String> _properties = new HashMap<>();
private final static JavaCompiler _compiler = JavacTool.create();
public JavaScriptingEngine() public JavaScriptingEngine()
{ {
super("Java Engine", "10", "java"); // Load config.
} Properties props = new Properties();
try (FileInputStream fis = new FileInputStream("config/ScriptEngine.ini"))
private void determineCompilerOrThrow()
{
if (_compiler == null)
{ {
_compiler = JavacTool.create(); props.load(fis);
}
catch (Exception e)
{
LOGGER.warning("Could not load ScriptEngine.ini: " + e.getMessage());
} }
if (_compiler == null) // Set properties.
for (Entry<Object, Object> prop : props.entrySet())
{ {
throw new IllegalStateException("No JavaCompiler service installed!"); String key = (String) prop.getKey();
} String value = (String) prop.getValue();
}
if (value.startsWith("%") && value.endsWith("%"))
private void ensureCompilerOrThrow()
{
if (_compiler == null)
{
synchronized (this)
{ {
if (_compiler == null) value = System.getProperty(value.substring(1, value.length() - 1));
{
determineCompilerOrThrow();
}
} }
_properties.put(key, value);
} }
} }
JavaCompiler getCompiler() public JavaExecutionContext createExecutionContext()
{ {
return _compiler;
}
@Override
public IExecutionContext createExecutionContext()
{
ensureCompilerOrThrow();
return new JavaExecutionContext(this); return new JavaExecutionContext(this);
} }
@Override public final String getProperty(String key)
public String getLanguageName()
{ {
return "Java"; return _properties.get(key);
} }
@Override public JavaCompiler getCompiler()
public String getLanguageVersion()
{ {
ensureCompilerOrThrow(); return _compiler;
return Arrays.deepToString(_compiler.getSourceVersions().toArray(new SourceVersion[0])).replace("RELEASE_", "");
} }
} }

View File

@@ -144,5 +144,4 @@ final class ScriptingOutputFileObject implements JavaFileObject
{ {
return null; return null;
} }
} }

View File

@@ -1,23 +1,23 @@
############################################################################### # ---------------------------------------------------------------------------
# Properties retrived with System.getProperty(String) can be used as values # Script Engine Settings
# ---------------------------------------------------------------------------
# Properties retrieved with System.getProperty(String) can be used as values
# by enclosing the property name with %. Eg.: %java.class.path% # by enclosing the property name with %. Eg.: %java.class.path%
###############################################################################
# The parent class loader for isolated script class loaders. # The parent class loader for isolated script class loaders.
# When this property is not specified, has an invalid value or is a class name which could not be found, the System classloader is used. # When this property is not specified, has an invalid value or is a class name which could not be found, the System classloader is used.
# Values: System, ThreadContext or a fully qualified java class name # Values: System, ThreadContext or a fully qualified java class name
language.Java.classloader=System classloader=System
#language.Java.classloader=ThreadContext #classloader=ThreadContext
# Source compatibility # Source compatibility.
language.Java.source=1.8 source=1.8
# The java sourcepath, when you have a different datapack root, you must change this too. # The java sourcepath, when you have a different datapack root, you must change this too.
language.Java.sourcepath=data/scripts sourcepath=data/scripts
# The java classpath # The java classpath.
language.Java.cp=%java.class.path% cp=%java.class.path%
# The debug informations to generate for compiled class files # The debug informations to generate for compiled class files.
language.Java.g=source,lines,vars g=source,lines,vars

View File

@@ -1,75 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
/**
* @author HorridoJoho
* @param <T>
*/
public abstract class AbstractExecutionContext<T extends IScriptingEngine> implements IExecutionContext
{
private final T _engine;
private final Map<String, String> _properties;
private volatile Path _currentExecutingScipt;
protected AbstractExecutionContext(T engine)
{
if (engine == null)
{
throw new IllegalArgumentException();
}
_engine = engine;
_properties = new HashMap<>();
}
protected final void setCurrentExecutingScript(Path currentExecutingScript)
{
_currentExecutingScipt = currentExecutingScript;
}
@Override
public final String setProperty(String key, String value)
{
return _properties.put(key, value);
}
@Override
public final String getProperty(String key)
{
if (!_properties.containsKey(key))
{
return _engine.getProperty(key);
}
return _properties.get(key);
}
@Override
public final Path getCurrentExecutingScript()
{
return _currentExecutingScipt;
}
@Override
public final T getScriptingEngine()
{
return _engine;
}
}

View File

@@ -1,74 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @author HorridoJoho
*/
public abstract class AbstractScriptingEngine implements IScriptingEngine
{
private final String _engineName;
private final String _engineVersion;
private final String[] _commonFileExtensions;
private final Map<String, String> _properties;
protected AbstractScriptingEngine(String engineName, String engineVersion, String... commonFileExtensions)
{
if ((engineName == null) || engineName.isEmpty() || (engineVersion == null) || engineVersion.isEmpty() || (commonFileExtensions == null) || (commonFileExtensions.length == 0))
{
throw new IllegalArgumentException();
}
_engineName = engineName;
_engineVersion = engineVersion;
_commonFileExtensions = commonFileExtensions;
_properties = new HashMap<>();
}
@Override
public final String setProperty(String key, String value)
{
return _properties.put(key, value);
}
@Override
public final String getProperty(String key)
{
return _properties.get(key);
}
@Override
public final String getEngineName()
{
return _engineName;
}
@Override
public final String getEngineVersion()
{
return _engineVersion;
}
@Override
public final String[] getCommonFileExtensions()
{
return Arrays.copyOf(_commonFileExtensions, _commonFileExtensions.length);
}
}

View File

@@ -1,71 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.nio.file.Path;
import java.util.Map;
import java.util.Map.Entry;
/**
* @author HorridoJoho
*/
public interface IExecutionContext
{
/**
* Properties set here override the settings from the IScriptEngine<br>
* this class was created from.
* @param key the key
* @param value the value
* @return the previous value, or null when this key was not present before
*/
String setProperty(String key, String value);
/**
* Executes all script in the iterable.
* @param sourcePaths the scripts to execute
* @return map of failed executions, Path=source file Throwable=thrown exception
* @throws Exception preparation for script execution failed
*/
Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception;
/**
* Executes a single file.
* @param sourcePath the script to execute
* @return entry of failed execution, Path=source file Throwable=thrown exception
* @throws Exception preparation for script execution failed
*/
Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception;
/**
* Method to get the specified property value.
* @param key the key
* @return the value, or null if the key is not present
*/
String getProperty(String key);
/**
* Method to get the current executing script file.
* @return the currently executing script file, null if non
*/
Path getCurrentExecutingScript();
/**
* Method to get the script engine this execution context belongs to.
* @return the script engine this execution context belongs to
*/
IScriptingEngine getScriptingEngine();
}

View File

@@ -1,75 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
/**
* @author HorridoJoho
*/
public interface IScriptingEngine
{
/**
* Sets script engine properties. The script values will be available<br>
* to the the insatnces created {@link IExecutionContext} implementation.
* @param key the key
* @param value the value
* @return the previous value, or null when this key was not present before
*/
String setProperty(String key, String value);
/**
* Creates an execution context.
* @return the created execution context.
*/
IExecutionContext createExecutionContext();
/**
* Method to get the specified property value.
* @param key the key
* @return the value,or null if the key is not present
*/
String getProperty(String key);
/**
* Method to get the engine name.
* @return the engine name
*/
String getEngineName();
/**
* Method to get the engine version.
* @return the engine version
*/
String getEngineVersion();
/**
* Method to get the scripting language name.
* @return the scripting engine name
*/
String getLanguageName();
/**
* Method to get the the language version.
* @return the language version
*/
String getLanguageVersion();
/**
* Method to retrive the commonly used file extensions for the language.
* @return the commonly used file extensions for the language
*/
String[] getCommonFileExtensions();
}

View File

@@ -17,7 +17,6 @@
package com.l2jmobius.gameserver.scripting; package com.l2jmobius.gameserver.scripting;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.file.FileVisitResult; import java.nio.file.FileVisitResult;
import java.nio.file.Files; import java.nio.file.Files;
@@ -31,9 +30,6 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Objects;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@@ -41,15 +37,16 @@ import org.w3c.dom.Document;
import com.l2jmobius.Config; import com.l2jmobius.Config;
import com.l2jmobius.commons.util.IXmlReader; import com.l2jmobius.commons.util.IXmlReader;
import com.l2jmobius.gameserver.scripting.java.JavaExecutionContext;
import com.l2jmobius.gameserver.scripting.java.JavaScriptingEngine; import com.l2jmobius.gameserver.scripting.java.JavaScriptingEngine;
/** /**
* Caches script engines and provides functionality for executing and managing scripts. * @author Mobius
* @author KenM, HorridoJoho
*/ */
public final class ScriptEngineManager implements IXmlReader public final class ScriptEngineManager implements IXmlReader
{ {
private static final Logger LOGGER = Logger.getLogger(ScriptEngineManager.class.getName()); private static final Logger LOGGER = Logger.getLogger(ScriptEngineManager.class.getName());
public static final Path SCRIPT_FOLDER = Config.SCRIPT_ROOT.toPath(); public static final Path SCRIPT_FOLDER = Config.SCRIPT_ROOT.toPath();
public static final Path MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "MasterHandler.java"); public static final Path MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "MasterHandler.java");
public static final Path EFFECT_MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "EffectMasterHandler.java"); public static final Path EFFECT_MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "EffectMasterHandler.java");
@@ -57,19 +54,11 @@ public final class ScriptEngineManager implements IXmlReader
public static final Path CONDITION_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "ConditionMasterHandler.java"); public static final Path CONDITION_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "ConditionMasterHandler.java");
public static final Path ONE_DAY_REWARD_MASTER_HANDLER = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "DailyMissionMasterHandler.java"); public static final Path ONE_DAY_REWARD_MASTER_HANDLER = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "DailyMissionMasterHandler.java");
private IExecutionContext _javaExecutionContext = null; private static final JavaExecutionContext _javaExecutionContext = new JavaScriptingEngine().createExecutionContext();
static final List<String> _exclusions = new ArrayList<>(); protected static final List<String> _exclusions = new ArrayList<>();
protected ScriptEngineManager() protected ScriptEngineManager()
{ {
final Properties props = loadProperties();
// Default java engine implementation
registerEngine(new JavaScriptingEngine(), props);
// Load external script engines
ServiceLoader.load(IScriptingEngine.class).forEach(engine -> registerEngine(engine, props));
// Load Scripts.xml // Load Scripts.xml
load(); load();
} }
@@ -144,71 +133,6 @@ public final class ScriptEngineManager implements IXmlReader
} }
} }
private Properties loadProperties()
{
Properties props = null;
try (FileInputStream fis = new FileInputStream("config/ScriptEngine.ini"))
{
props = new Properties();
props.load(fis);
}
catch (Exception e)
{
props = null;
LOGGER.warning("Couldn't load ScriptEngine.ini: " + e.getMessage());
}
return props;
}
private void registerEngine(IScriptingEngine engine, Properties props)
{
maybeSetProperties("language." + engine.getLanguageName() + ".", props, engine);
_javaExecutionContext = engine.createExecutionContext();
LOGGER.info("ScriptEngine: " + engine.getEngineName() + " " + engine.getEngineVersion() + " (" + engine.getLanguageName() + " " + engine.getLanguageVersion() + ")");
}
private void maybeSetProperties(String propPrefix, Properties props, IScriptingEngine engine)
{
if (props == null)
{
return;
}
for (Entry<Object, Object> prop : props.entrySet())
{
String key = (String) prop.getKey();
String value = (String) prop.getValue();
if (key.startsWith(propPrefix))
{
key = key.substring(propPrefix.length());
if (value.startsWith("%") && value.endsWith("%"))
{
value = System.getProperty(value.substring(1, value.length() - 1));
}
engine.setProperty(key, value);
}
}
}
public void executeScriptList() throws Exception
{
if (Config.ALT_DEV_NO_QUESTS)
{
return;
}
final List<Path> files = new ArrayList<>();
processDirectory(SCRIPT_FOLDER.toFile(), files);
final Map<Path, Throwable> invokationErrors = _javaExecutionContext.executeScripts(files);
for (Entry<Path, Throwable> entry : invokationErrors.entrySet())
{
LOGGER.log(Level.WARNING, "ScriptEngine: " + entry.getKey() + " failed execution!", entry.getValue());
}
}
private void processDirectory(File dir, List<Path> files) private void processDirectory(File dir, List<Path> files)
{ {
for (File file : dir.listFiles()) for (File file : dir.listFiles())
@@ -230,15 +154,12 @@ public final class ScriptEngineManager implements IXmlReader
public void executeScript(Path sourceFile) throws Exception public void executeScript(Path sourceFile) throws Exception
{ {
Objects.requireNonNull(sourceFile);
if (!sourceFile.isAbsolute()) if (!sourceFile.isAbsolute())
{ {
sourceFile = SCRIPT_FOLDER.resolve(sourceFile); sourceFile = SCRIPT_FOLDER.resolve(sourceFile);
} }
sourceFile = sourceFile.toAbsolutePath(); sourceFile = sourceFile.toAbsolutePath();
Objects.requireNonNull(sourceFile, "ScriptFile: " + sourceFile + " does not have an extension to determine the script engine!");
final Entry<Path, Throwable> error = _javaExecutionContext.executeScript(sourceFile); final Entry<Path, Throwable> error = _javaExecutionContext.executeScript(sourceFile);
if (error != null) if (error != null)
@@ -247,6 +168,23 @@ public final class ScriptEngineManager implements IXmlReader
} }
} }
public void executeScriptList() throws Exception
{
if (Config.ALT_DEV_NO_QUESTS)
{
return;
}
final List<Path> files = new ArrayList<>();
processDirectory(SCRIPT_FOLDER.toFile(), files);
final Map<Path, Throwable> invokationErrors = _javaExecutionContext.executeScripts(files);
for (Entry<Path, Throwable> entry : invokationErrors.entrySet())
{
LOGGER.log(Level.WARNING, "ScriptEngine: " + entry.getKey() + " failed execution!", entry.getValue());
}
}
public Path getCurrentLoadingScript() public Path getCurrentLoadingScript()
{ {
return _javaExecutionContext.getCurrentExecutingScript(); return _javaExecutionContext.getCurrentExecutingScript();
@@ -254,11 +192,11 @@ public final class ScriptEngineManager implements IXmlReader
public static ScriptEngineManager getInstance() public static ScriptEngineManager getInstance()
{ {
return SingletonHolder._instance; return SingletonHolder.INSTANCE;
} }
private static class SingletonHolder private static class SingletonHolder
{ {
protected static final ScriptEngineManager _instance = new ScriptEngineManager(); protected static final ScriptEngineManager INSTANCE = new ScriptEngineManager();
} }
} }

View File

@@ -1,28 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting.java;
/**
* @author HorridoJoho
*/
public final class JavaCompilerException extends RuntimeException
{
public JavaCompilerException(String diagnostics)
{
super(diagnostics);
}
}

View File

@@ -22,9 +22,9 @@ import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.LinkedHashMap; import java.util.HashMap;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
@@ -34,22 +34,20 @@ import org.openjavac.tools.Diagnostic;
import org.openjavac.tools.DiagnosticCollector; import org.openjavac.tools.DiagnosticCollector;
import org.openjavac.tools.JavaFileObject; import org.openjavac.tools.JavaFileObject;
import com.l2jmobius.gameserver.scripting.AbstractExecutionContext;
import com.l2jmobius.gameserver.scripting.annotations.Disabled; import com.l2jmobius.gameserver.scripting.annotations.Disabled;
/** /**
* @author HorridoJoho * @author HorridoJoho
*/ */
public final class JavaExecutionContext extends AbstractExecutionContext<JavaScriptingEngine> public final class JavaExecutionContext extends JavaScriptingEngine
{ {
private static final Logger LOGGER = Logger.getLogger(JavaExecutionContext.class.getName()); private static final Logger LOGGER = Logger.getLogger(JavaExecutionContext.class.getName());
private static final List<String> _options = new LinkedList<>(); private static final List<String> _options = new ArrayList<>();
private static Path _currentExecutingScript;
JavaExecutionContext(JavaScriptingEngine engine) JavaExecutionContext(JavaScriptingEngine engine)
{ {
super(engine);
// Set options. // Set options.
addOptionIfNotNull(_options, getProperty("source"), "-source"); addOptionIfNotNull(_options, getProperty("source"), "-source");
addOptionIfNotNull(_options, getProperty("sourcepath"), "-sourcepath"); addOptionIfNotNull(_options, getProperty("sourcepath"), "-sourcepath");
@@ -76,7 +74,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
else else
{ {
throw new JavaCompilerException("Could not determine target version!"); throw new RuntimeException("Could not determine target version!");
} }
} }
} }
@@ -133,16 +131,15 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
} }
@Override
public Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception public Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception
{ {
final DiagnosticCollector<JavaFileObject> fileManagerDiagnostics = new DiagnosticCollector<>(); final DiagnosticCollector<JavaFileObject> fileManagerDiagnostics = new DiagnosticCollector<>();
final DiagnosticCollector<JavaFileObject> compilationDiagnostics = new DiagnosticCollector<>(); final DiagnosticCollector<JavaFileObject> compilationDiagnostics = new DiagnosticCollector<>();
try (ScriptingFileManager fileManager = new ScriptingFileManager(getScriptingEngine().getCompiler().getStandardFileManager(fileManagerDiagnostics, null, StandardCharsets.UTF_8))) try (ScriptingFileManager fileManager = new ScriptingFileManager(getCompiler().getStandardFileManager(fileManagerDiagnostics, null, StandardCharsets.UTF_8)))
{ {
// We really need an iterable of files or strings. // We really need an iterable of files or strings.
final List<String> sourcePathStrings = new LinkedList<>(); final List<String> sourcePathStrings = new ArrayList<>();
for (Path sourcePath : sourcePaths) for (Path sourcePath : sourcePaths)
{ {
sourcePathStrings.add(sourcePath.toString()); sourcePathStrings.add(sourcePath.toString());
@@ -150,7 +147,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
final StringWriter strOut = new StringWriter(); final StringWriter strOut = new StringWriter();
final PrintWriter out = new PrintWriter(strOut); final PrintWriter out = new PrintWriter(strOut);
final boolean compilationSuccess = getScriptingEngine().getCompiler().getTask(out, fileManager, compilationDiagnostics, _options, null, fileManager.getJavaFileObjectsFromStrings(sourcePathStrings)).call(); final boolean compilationSuccess = getCompiler().getTask(out, fileManager, compilationDiagnostics, _options, null, fileManager.getJavaFileObjectsFromStrings(sourcePathStrings)).call();
if (!compilationSuccess) if (!compilationSuccess)
{ {
out.println(); out.println();
@@ -175,12 +172,12 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
out.println("\t\tmessage: " + diagnostic.getMessage(null)); out.println("\t\tmessage: " + diagnostic.getMessage(null));
} }
throw new JavaCompilerException(strOut.toString()); throw new RuntimeException(strOut.toString());
} }
final ClassLoader parentClassLoader = determineScriptParentClassloader(); final ClassLoader parentClassLoader = determineScriptParentClassloader();
final Map<Path, Throwable> executionFailures = new LinkedHashMap<>(); final Map<Path, Throwable> executionFailures = new HashMap<>();
final Iterable<ScriptingOutputFileObject> compiledClasses = fileManager.getCompiledClasses(); final Iterable<ScriptingOutputFileObject> compiledClasses = fileManager.getCompiledClasses();
for (Path sourcePath : sourcePaths) for (Path sourcePath : sourcePaths)
{ {
@@ -199,7 +196,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
found = true; found = true;
setCurrentExecutingScript(compiledSourcePath); _currentExecutingScript = compiledSourcePath;
try try
{ {
final ScriptingClassLoader loader = new ScriptingClassLoader(parentClassLoader, compiledClasses); final ScriptingClassLoader loader = new ScriptingClassLoader(parentClassLoader, compiledClasses);
@@ -227,7 +224,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
finally finally
{ {
setCurrentExecutingScript(null); _currentExecutingScript = null;
} }
break; break;
@@ -244,7 +241,6 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
} }
@Override
public Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception public Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception
{ {
final Map<Path, Throwable> executionFailures = executeScripts(Arrays.asList(sourcePath)); final Map<Path, Throwable> executionFailures = executeScripts(Arrays.asList(sourcePath));
@@ -254,4 +250,9 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
return null; return null;
} }
public final Path getCurrentExecutingScript()
{
return _currentExecutingScript;
}
} }

View File

@@ -16,77 +16,66 @@
*/ */
package com.l2jmobius.gameserver.scripting.java; package com.l2jmobius.gameserver.scripting.java;
import java.util.Arrays; import java.io.FileInputStream;
import java.util.HashMap;
import javax.lang.model.SourceVersion; import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.logging.Logger;
import org.openjavac.tools.JavaCompiler; import org.openjavac.tools.JavaCompiler;
import org.openjavac.tools.javac.api.JavacTool; import org.openjavac.tools.javac.api.JavacTool;
import com.l2jmobius.gameserver.scripting.AbstractScriptingEngine;
import com.l2jmobius.gameserver.scripting.IExecutionContext;
/** /**
* @author HorridoJoho, Mobius * @author Mobius
*/ */
public final class JavaScriptingEngine extends AbstractScriptingEngine public class JavaScriptingEngine
{ {
private volatile JavaCompiler _compiler; private static final Logger LOGGER = Logger.getLogger(JavaScriptingEngine.class.getName());
private final static Map<String, String> _properties = new HashMap<>();
private final static JavaCompiler _compiler = JavacTool.create();
public JavaScriptingEngine() public JavaScriptingEngine()
{ {
super("Java Engine", "10", "java"); // Load config.
} Properties props = new Properties();
try (FileInputStream fis = new FileInputStream("config/ScriptEngine.ini"))
private void determineCompilerOrThrow()
{
if (_compiler == null)
{ {
_compiler = JavacTool.create(); props.load(fis);
}
catch (Exception e)
{
LOGGER.warning("Could not load ScriptEngine.ini: " + e.getMessage());
} }
if (_compiler == null) // Set properties.
for (Entry<Object, Object> prop : props.entrySet())
{ {
throw new IllegalStateException("No JavaCompiler service installed!"); String key = (String) prop.getKey();
} String value = (String) prop.getValue();
}
if (value.startsWith("%") && value.endsWith("%"))
private void ensureCompilerOrThrow()
{
if (_compiler == null)
{
synchronized (this)
{ {
if (_compiler == null) value = System.getProperty(value.substring(1, value.length() - 1));
{
determineCompilerOrThrow();
}
} }
_properties.put(key, value);
} }
} }
JavaCompiler getCompiler() public JavaExecutionContext createExecutionContext()
{ {
return _compiler;
}
@Override
public IExecutionContext createExecutionContext()
{
ensureCompilerOrThrow();
return new JavaExecutionContext(this); return new JavaExecutionContext(this);
} }
@Override public final String getProperty(String key)
public String getLanguageName()
{ {
return "Java"; return _properties.get(key);
} }
@Override public JavaCompiler getCompiler()
public String getLanguageVersion()
{ {
ensureCompilerOrThrow(); return _compiler;
return Arrays.deepToString(_compiler.getSourceVersions().toArray(new SourceVersion[0])).replace("RELEASE_", "");
} }
} }

View File

@@ -144,5 +144,4 @@ final class ScriptingOutputFileObject implements JavaFileObject
{ {
return null; return null;
} }
} }

View File

@@ -1,23 +1,23 @@
############################################################################### # ---------------------------------------------------------------------------
# Properties retrived with System.getProperty(String) can be used as values # Script Engine Settings
# ---------------------------------------------------------------------------
# Properties retrieved with System.getProperty(String) can be used as values
# by enclosing the property name with %. Eg.: %java.class.path% # by enclosing the property name with %. Eg.: %java.class.path%
###############################################################################
# The parent class loader for isolated script class loaders. # The parent class loader for isolated script class loaders.
# When this property is not specified, has an invalid value or is a class name which could not be found, the System classloader is used. # When this property is not specified, has an invalid value or is a class name which could not be found, the System classloader is used.
# Values: System, ThreadContext or a fully qualified java class name # Values: System, ThreadContext or a fully qualified java class name
language.Java.classloader=System classloader=System
#language.Java.classloader=ThreadContext #classloader=ThreadContext
# Source compatibility # Source compatibility.
language.Java.source=1.8 source=1.8
# The java sourcepath, when you have a different datapack root, you must change this too. # The java sourcepath, when you have a different datapack root, you must change this too.
language.Java.sourcepath=data/scripts sourcepath=data/scripts
# The java classpath # The java classpath.
language.Java.cp=%java.class.path% cp=%java.class.path%
# The debug informations to generate for compiled class files # The debug informations to generate for compiled class files.
language.Java.g=source,lines,vars g=source,lines,vars

View File

@@ -1,75 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
/**
* @author HorridoJoho
* @param <T>
*/
public abstract class AbstractExecutionContext<T extends IScriptingEngine> implements IExecutionContext
{
private final T _engine;
private final Map<String, String> _properties;
private volatile Path _currentExecutingScipt;
protected AbstractExecutionContext(T engine)
{
if (engine == null)
{
throw new IllegalArgumentException();
}
_engine = engine;
_properties = new HashMap<>();
}
protected final void setCurrentExecutingScript(Path currentExecutingScript)
{
_currentExecutingScipt = currentExecutingScript;
}
@Override
public final String setProperty(String key, String value)
{
return _properties.put(key, value);
}
@Override
public final String getProperty(String key)
{
if (!_properties.containsKey(key))
{
return _engine.getProperty(key);
}
return _properties.get(key);
}
@Override
public final Path getCurrentExecutingScript()
{
return _currentExecutingScipt;
}
@Override
public final T getScriptingEngine()
{
return _engine;
}
}

View File

@@ -1,74 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @author HorridoJoho
*/
public abstract class AbstractScriptingEngine implements IScriptingEngine
{
private final String _engineName;
private final String _engineVersion;
private final String[] _commonFileExtensions;
private final Map<String, String> _properties;
protected AbstractScriptingEngine(String engineName, String engineVersion, String... commonFileExtensions)
{
if ((engineName == null) || engineName.isEmpty() || (engineVersion == null) || engineVersion.isEmpty() || (commonFileExtensions == null) || (commonFileExtensions.length == 0))
{
throw new IllegalArgumentException();
}
_engineName = engineName;
_engineVersion = engineVersion;
_commonFileExtensions = commonFileExtensions;
_properties = new HashMap<>();
}
@Override
public final String setProperty(String key, String value)
{
return _properties.put(key, value);
}
@Override
public final String getProperty(String key)
{
return _properties.get(key);
}
@Override
public final String getEngineName()
{
return _engineName;
}
@Override
public final String getEngineVersion()
{
return _engineVersion;
}
@Override
public final String[] getCommonFileExtensions()
{
return Arrays.copyOf(_commonFileExtensions, _commonFileExtensions.length);
}
}

View File

@@ -1,71 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.nio.file.Path;
import java.util.Map;
import java.util.Map.Entry;
/**
* @author HorridoJoho
*/
public interface IExecutionContext
{
/**
* Properties set here override the settings from the IScriptEngine<br>
* this class was created from.
* @param key the key
* @param value the value
* @return the previous value, or null when this key was not present before
*/
String setProperty(String key, String value);
/**
* Executes all script in the iterable.
* @param sourcePaths the scripts to execute
* @return map of failed executions, Path=source file Throwable=thrown exception
* @throws Exception preparation for script execution failed
*/
Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception;
/**
* Executes a single file.
* @param sourcePath the script to execute
* @return entry of failed execution, Path=source file Throwable=thrown exception
* @throws Exception preparation for script execution failed
*/
Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception;
/**
* Method to get the specified property value.
* @param key the key
* @return the value, or null if the key is not present
*/
String getProperty(String key);
/**
* Method to get the current executing script file.
* @return the currently executing script file, null if non
*/
Path getCurrentExecutingScript();
/**
* Method to get the script engine this execution context belongs to.
* @return the script engine this execution context belongs to
*/
IScriptingEngine getScriptingEngine();
}

View File

@@ -1,75 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
/**
* @author HorridoJoho
*/
public interface IScriptingEngine
{
/**
* Sets script engine properties. The script values will be available<br>
* to the the insatnces created {@link IExecutionContext} implementation.
* @param key the key
* @param value the value
* @return the previous value, or null when this key was not present before
*/
String setProperty(String key, String value);
/**
* Creates an execution context.
* @return the created execution context.
*/
IExecutionContext createExecutionContext();
/**
* Method to get the specified property value.
* @param key the key
* @return the value,or null if the key is not present
*/
String getProperty(String key);
/**
* Method to get the engine name.
* @return the engine name
*/
String getEngineName();
/**
* Method to get the engine version.
* @return the engine version
*/
String getEngineVersion();
/**
* Method to get the scripting language name.
* @return the scripting engine name
*/
String getLanguageName();
/**
* Method to get the the language version.
* @return the language version
*/
String getLanguageVersion();
/**
* Method to retrive the commonly used file extensions for the language.
* @return the commonly used file extensions for the language
*/
String[] getCommonFileExtensions();
}

View File

@@ -17,7 +17,6 @@
package com.l2jmobius.gameserver.scripting; package com.l2jmobius.gameserver.scripting;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.file.FileVisitResult; import java.nio.file.FileVisitResult;
import java.nio.file.Files; import java.nio.file.Files;
@@ -31,9 +30,6 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Objects;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@@ -41,15 +37,16 @@ import org.w3c.dom.Document;
import com.l2jmobius.Config; import com.l2jmobius.Config;
import com.l2jmobius.commons.util.IXmlReader; import com.l2jmobius.commons.util.IXmlReader;
import com.l2jmobius.gameserver.scripting.java.JavaExecutionContext;
import com.l2jmobius.gameserver.scripting.java.JavaScriptingEngine; import com.l2jmobius.gameserver.scripting.java.JavaScriptingEngine;
/** /**
* Caches script engines and provides functionality for executing and managing scripts. * @author Mobius
* @author KenM, HorridoJoho
*/ */
public final class ScriptEngineManager implements IXmlReader public final class ScriptEngineManager implements IXmlReader
{ {
private static final Logger LOGGER = Logger.getLogger(ScriptEngineManager.class.getName()); private static final Logger LOGGER = Logger.getLogger(ScriptEngineManager.class.getName());
public static final Path SCRIPT_FOLDER = Config.SCRIPT_ROOT.toPath(); public static final Path SCRIPT_FOLDER = Config.SCRIPT_ROOT.toPath();
public static final Path MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "MasterHandler.java"); public static final Path MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "MasterHandler.java");
public static final Path EFFECT_MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "EffectMasterHandler.java"); public static final Path EFFECT_MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "EffectMasterHandler.java");
@@ -57,19 +54,11 @@ public final class ScriptEngineManager implements IXmlReader
public static final Path CONDITION_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "ConditionMasterHandler.java"); public static final Path CONDITION_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "ConditionMasterHandler.java");
public static final Path ONE_DAY_REWARD_MASTER_HANDLER = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "DailyMissionMasterHandler.java"); public static final Path ONE_DAY_REWARD_MASTER_HANDLER = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "DailyMissionMasterHandler.java");
private IExecutionContext _javaExecutionContext = null; private static final JavaExecutionContext _javaExecutionContext = new JavaScriptingEngine().createExecutionContext();
static final List<String> _exclusions = new ArrayList<>(); protected static final List<String> _exclusions = new ArrayList<>();
protected ScriptEngineManager() protected ScriptEngineManager()
{ {
final Properties props = loadProperties();
// Default java engine implementation
registerEngine(new JavaScriptingEngine(), props);
// Load external script engines
ServiceLoader.load(IScriptingEngine.class).forEach(engine -> registerEngine(engine, props));
// Load Scripts.xml // Load Scripts.xml
load(); load();
} }
@@ -144,71 +133,6 @@ public final class ScriptEngineManager implements IXmlReader
} }
} }
private Properties loadProperties()
{
Properties props = null;
try (FileInputStream fis = new FileInputStream("config/ScriptEngine.ini"))
{
props = new Properties();
props.load(fis);
}
catch (Exception e)
{
props = null;
LOGGER.warning("Couldn't load ScriptEngine.ini: " + e.getMessage());
}
return props;
}
private void registerEngine(IScriptingEngine engine, Properties props)
{
maybeSetProperties("language." + engine.getLanguageName() + ".", props, engine);
_javaExecutionContext = engine.createExecutionContext();
LOGGER.info("ScriptEngine: " + engine.getEngineName() + " " + engine.getEngineVersion() + " (" + engine.getLanguageName() + " " + engine.getLanguageVersion() + ")");
}
private void maybeSetProperties(String propPrefix, Properties props, IScriptingEngine engine)
{
if (props == null)
{
return;
}
for (Entry<Object, Object> prop : props.entrySet())
{
String key = (String) prop.getKey();
String value = (String) prop.getValue();
if (key.startsWith(propPrefix))
{
key = key.substring(propPrefix.length());
if (value.startsWith("%") && value.endsWith("%"))
{
value = System.getProperty(value.substring(1, value.length() - 1));
}
engine.setProperty(key, value);
}
}
}
public void executeScriptList() throws Exception
{
if (Config.ALT_DEV_NO_QUESTS)
{
return;
}
final List<Path> files = new ArrayList<>();
processDirectory(SCRIPT_FOLDER.toFile(), files);
final Map<Path, Throwable> invokationErrors = _javaExecutionContext.executeScripts(files);
for (Entry<Path, Throwable> entry : invokationErrors.entrySet())
{
LOGGER.log(Level.WARNING, "ScriptEngine: " + entry.getKey() + " failed execution!", entry.getValue());
}
}
private void processDirectory(File dir, List<Path> files) private void processDirectory(File dir, List<Path> files)
{ {
for (File file : dir.listFiles()) for (File file : dir.listFiles())
@@ -230,15 +154,12 @@ public final class ScriptEngineManager implements IXmlReader
public void executeScript(Path sourceFile) throws Exception public void executeScript(Path sourceFile) throws Exception
{ {
Objects.requireNonNull(sourceFile);
if (!sourceFile.isAbsolute()) if (!sourceFile.isAbsolute())
{ {
sourceFile = SCRIPT_FOLDER.resolve(sourceFile); sourceFile = SCRIPT_FOLDER.resolve(sourceFile);
} }
sourceFile = sourceFile.toAbsolutePath(); sourceFile = sourceFile.toAbsolutePath();
Objects.requireNonNull(sourceFile, "ScriptFile: " + sourceFile + " does not have an extension to determine the script engine!");
final Entry<Path, Throwable> error = _javaExecutionContext.executeScript(sourceFile); final Entry<Path, Throwable> error = _javaExecutionContext.executeScript(sourceFile);
if (error != null) if (error != null)
@@ -247,6 +168,23 @@ public final class ScriptEngineManager implements IXmlReader
} }
} }
public void executeScriptList() throws Exception
{
if (Config.ALT_DEV_NO_QUESTS)
{
return;
}
final List<Path> files = new ArrayList<>();
processDirectory(SCRIPT_FOLDER.toFile(), files);
final Map<Path, Throwable> invokationErrors = _javaExecutionContext.executeScripts(files);
for (Entry<Path, Throwable> entry : invokationErrors.entrySet())
{
LOGGER.log(Level.WARNING, "ScriptEngine: " + entry.getKey() + " failed execution!", entry.getValue());
}
}
public Path getCurrentLoadingScript() public Path getCurrentLoadingScript()
{ {
return _javaExecutionContext.getCurrentExecutingScript(); return _javaExecutionContext.getCurrentExecutingScript();
@@ -254,11 +192,11 @@ public final class ScriptEngineManager implements IXmlReader
public static ScriptEngineManager getInstance() public static ScriptEngineManager getInstance()
{ {
return SingletonHolder._instance; return SingletonHolder.INSTANCE;
} }
private static class SingletonHolder private static class SingletonHolder
{ {
protected static final ScriptEngineManager _instance = new ScriptEngineManager(); protected static final ScriptEngineManager INSTANCE = new ScriptEngineManager();
} }
} }

View File

@@ -1,28 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting.java;
/**
* @author HorridoJoho
*/
public final class JavaCompilerException extends RuntimeException
{
public JavaCompilerException(String diagnostics)
{
super(diagnostics);
}
}

View File

@@ -22,9 +22,9 @@ import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.LinkedHashMap; import java.util.HashMap;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
@@ -34,22 +34,20 @@ import org.openjavac.tools.Diagnostic;
import org.openjavac.tools.DiagnosticCollector; import org.openjavac.tools.DiagnosticCollector;
import org.openjavac.tools.JavaFileObject; import org.openjavac.tools.JavaFileObject;
import com.l2jmobius.gameserver.scripting.AbstractExecutionContext;
import com.l2jmobius.gameserver.scripting.annotations.Disabled; import com.l2jmobius.gameserver.scripting.annotations.Disabled;
/** /**
* @author HorridoJoho * @author HorridoJoho
*/ */
public final class JavaExecutionContext extends AbstractExecutionContext<JavaScriptingEngine> public final class JavaExecutionContext extends JavaScriptingEngine
{ {
private static final Logger LOGGER = Logger.getLogger(JavaExecutionContext.class.getName()); private static final Logger LOGGER = Logger.getLogger(JavaExecutionContext.class.getName());
private static final List<String> _options = new LinkedList<>(); private static final List<String> _options = new ArrayList<>();
private static Path _currentExecutingScript;
JavaExecutionContext(JavaScriptingEngine engine) JavaExecutionContext(JavaScriptingEngine engine)
{ {
super(engine);
// Set options. // Set options.
addOptionIfNotNull(_options, getProperty("source"), "-source"); addOptionIfNotNull(_options, getProperty("source"), "-source");
addOptionIfNotNull(_options, getProperty("sourcepath"), "-sourcepath"); addOptionIfNotNull(_options, getProperty("sourcepath"), "-sourcepath");
@@ -76,7 +74,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
else else
{ {
throw new JavaCompilerException("Could not determine target version!"); throw new RuntimeException("Could not determine target version!");
} }
} }
} }
@@ -133,16 +131,15 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
} }
@Override
public Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception public Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception
{ {
final DiagnosticCollector<JavaFileObject> fileManagerDiagnostics = new DiagnosticCollector<>(); final DiagnosticCollector<JavaFileObject> fileManagerDiagnostics = new DiagnosticCollector<>();
final DiagnosticCollector<JavaFileObject> compilationDiagnostics = new DiagnosticCollector<>(); final DiagnosticCollector<JavaFileObject> compilationDiagnostics = new DiagnosticCollector<>();
try (ScriptingFileManager fileManager = new ScriptingFileManager(getScriptingEngine().getCompiler().getStandardFileManager(fileManagerDiagnostics, null, StandardCharsets.UTF_8))) try (ScriptingFileManager fileManager = new ScriptingFileManager(getCompiler().getStandardFileManager(fileManagerDiagnostics, null, StandardCharsets.UTF_8)))
{ {
// We really need an iterable of files or strings. // We really need an iterable of files or strings.
final List<String> sourcePathStrings = new LinkedList<>(); final List<String> sourcePathStrings = new ArrayList<>();
for (Path sourcePath : sourcePaths) for (Path sourcePath : sourcePaths)
{ {
sourcePathStrings.add(sourcePath.toString()); sourcePathStrings.add(sourcePath.toString());
@@ -150,7 +147,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
final StringWriter strOut = new StringWriter(); final StringWriter strOut = new StringWriter();
final PrintWriter out = new PrintWriter(strOut); final PrintWriter out = new PrintWriter(strOut);
final boolean compilationSuccess = getScriptingEngine().getCompiler().getTask(out, fileManager, compilationDiagnostics, _options, null, fileManager.getJavaFileObjectsFromStrings(sourcePathStrings)).call(); final boolean compilationSuccess = getCompiler().getTask(out, fileManager, compilationDiagnostics, _options, null, fileManager.getJavaFileObjectsFromStrings(sourcePathStrings)).call();
if (!compilationSuccess) if (!compilationSuccess)
{ {
out.println(); out.println();
@@ -175,12 +172,12 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
out.println("\t\tmessage: " + diagnostic.getMessage(null)); out.println("\t\tmessage: " + diagnostic.getMessage(null));
} }
throw new JavaCompilerException(strOut.toString()); throw new RuntimeException(strOut.toString());
} }
final ClassLoader parentClassLoader = determineScriptParentClassloader(); final ClassLoader parentClassLoader = determineScriptParentClassloader();
final Map<Path, Throwable> executionFailures = new LinkedHashMap<>(); final Map<Path, Throwable> executionFailures = new HashMap<>();
final Iterable<ScriptingOutputFileObject> compiledClasses = fileManager.getCompiledClasses(); final Iterable<ScriptingOutputFileObject> compiledClasses = fileManager.getCompiledClasses();
for (Path sourcePath : sourcePaths) for (Path sourcePath : sourcePaths)
{ {
@@ -199,7 +196,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
found = true; found = true;
setCurrentExecutingScript(compiledSourcePath); _currentExecutingScript = compiledSourcePath;
try try
{ {
final ScriptingClassLoader loader = new ScriptingClassLoader(parentClassLoader, compiledClasses); final ScriptingClassLoader loader = new ScriptingClassLoader(parentClassLoader, compiledClasses);
@@ -227,7 +224,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
finally finally
{ {
setCurrentExecutingScript(null); _currentExecutingScript = null;
} }
break; break;
@@ -244,7 +241,6 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
} }
@Override
public Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception public Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception
{ {
final Map<Path, Throwable> executionFailures = executeScripts(Arrays.asList(sourcePath)); final Map<Path, Throwable> executionFailures = executeScripts(Arrays.asList(sourcePath));
@@ -254,4 +250,9 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
return null; return null;
} }
public final Path getCurrentExecutingScript()
{
return _currentExecutingScript;
}
} }

View File

@@ -16,77 +16,66 @@
*/ */
package com.l2jmobius.gameserver.scripting.java; package com.l2jmobius.gameserver.scripting.java;
import java.util.Arrays; import java.io.FileInputStream;
import java.util.HashMap;
import javax.lang.model.SourceVersion; import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.logging.Logger;
import org.openjavac.tools.JavaCompiler; import org.openjavac.tools.JavaCompiler;
import org.openjavac.tools.javac.api.JavacTool; import org.openjavac.tools.javac.api.JavacTool;
import com.l2jmobius.gameserver.scripting.AbstractScriptingEngine;
import com.l2jmobius.gameserver.scripting.IExecutionContext;
/** /**
* @author HorridoJoho, Mobius * @author Mobius
*/ */
public final class JavaScriptingEngine extends AbstractScriptingEngine public class JavaScriptingEngine
{ {
private volatile JavaCompiler _compiler; private static final Logger LOGGER = Logger.getLogger(JavaScriptingEngine.class.getName());
private final static Map<String, String> _properties = new HashMap<>();
private final static JavaCompiler _compiler = JavacTool.create();
public JavaScriptingEngine() public JavaScriptingEngine()
{ {
super("Java Engine", "10", "java"); // Load config.
} Properties props = new Properties();
try (FileInputStream fis = new FileInputStream("config/ScriptEngine.ini"))
private void determineCompilerOrThrow()
{
if (_compiler == null)
{ {
_compiler = JavacTool.create(); props.load(fis);
}
catch (Exception e)
{
LOGGER.warning("Could not load ScriptEngine.ini: " + e.getMessage());
} }
if (_compiler == null) // Set properties.
for (Entry<Object, Object> prop : props.entrySet())
{ {
throw new IllegalStateException("No JavaCompiler service installed!"); String key = (String) prop.getKey();
} String value = (String) prop.getValue();
}
if (value.startsWith("%") && value.endsWith("%"))
private void ensureCompilerOrThrow()
{
if (_compiler == null)
{
synchronized (this)
{ {
if (_compiler == null) value = System.getProperty(value.substring(1, value.length() - 1));
{
determineCompilerOrThrow();
}
} }
_properties.put(key, value);
} }
} }
JavaCompiler getCompiler() public JavaExecutionContext createExecutionContext()
{ {
return _compiler;
}
@Override
public IExecutionContext createExecutionContext()
{
ensureCompilerOrThrow();
return new JavaExecutionContext(this); return new JavaExecutionContext(this);
} }
@Override public final String getProperty(String key)
public String getLanguageName()
{ {
return "Java"; return _properties.get(key);
} }
@Override public JavaCompiler getCompiler()
public String getLanguageVersion()
{ {
ensureCompilerOrThrow(); return _compiler;
return Arrays.deepToString(_compiler.getSourceVersions().toArray(new SourceVersion[0])).replace("RELEASE_", "");
} }
} }

View File

@@ -144,5 +144,4 @@ final class ScriptingOutputFileObject implements JavaFileObject
{ {
return null; return null;
} }
} }

View File

@@ -1,23 +1,23 @@
############################################################################### # ---------------------------------------------------------------------------
# Properties retrived with System.getProperty(String) can be used as values # Script Engine Settings
# ---------------------------------------------------------------------------
# Properties retrieved with System.getProperty(String) can be used as values
# by enclosing the property name with %. Eg.: %java.class.path% # by enclosing the property name with %. Eg.: %java.class.path%
###############################################################################
# The parent class loader for isolated script class loaders. # The parent class loader for isolated script class loaders.
# When this property is not specified, has an invalid value or is a class name which could not be found, the System classloader is used. # When this property is not specified, has an invalid value or is a class name which could not be found, the System classloader is used.
# Values: System, ThreadContext or a fully qualified java class name # Values: System, ThreadContext or a fully qualified java class name
language.Java.classloader=System classloader=System
#language.Java.classloader=ThreadContext #classloader=ThreadContext
# Source compatibility # Source compatibility.
language.Java.source=1.8 source=1.8
# The java sourcepath, when you have a different datapack root, you must change this too. # The java sourcepath, when you have a different datapack root, you must change this too.
language.Java.sourcepath=data/scripts sourcepath=data/scripts
# The java classpath # The java classpath.
language.Java.cp=%java.class.path% cp=%java.class.path%
# The debug informations to generate for compiled class files # The debug informations to generate for compiled class files.
language.Java.g=source,lines,vars g=source,lines,vars

View File

@@ -1,75 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
/**
* @author HorridoJoho
* @param <T>
*/
public abstract class AbstractExecutionContext<T extends IScriptingEngine> implements IExecutionContext
{
private final T _engine;
private final Map<String, String> _properties;
private volatile Path _currentExecutingScipt;
protected AbstractExecutionContext(T engine)
{
if (engine == null)
{
throw new IllegalArgumentException();
}
_engine = engine;
_properties = new HashMap<>();
}
protected final void setCurrentExecutingScript(Path currentExecutingScript)
{
_currentExecutingScipt = currentExecutingScript;
}
@Override
public final String setProperty(String key, String value)
{
return _properties.put(key, value);
}
@Override
public final String getProperty(String key)
{
if (!_properties.containsKey(key))
{
return _engine.getProperty(key);
}
return _properties.get(key);
}
@Override
public final Path getCurrentExecutingScript()
{
return _currentExecutingScipt;
}
@Override
public final T getScriptingEngine()
{
return _engine;
}
}

View File

@@ -1,74 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @author HorridoJoho
*/
public abstract class AbstractScriptingEngine implements IScriptingEngine
{
private final String _engineName;
private final String _engineVersion;
private final String[] _commonFileExtensions;
private final Map<String, String> _properties;
protected AbstractScriptingEngine(String engineName, String engineVersion, String... commonFileExtensions)
{
if ((engineName == null) || engineName.isEmpty() || (engineVersion == null) || engineVersion.isEmpty() || (commonFileExtensions == null) || (commonFileExtensions.length == 0))
{
throw new IllegalArgumentException();
}
_engineName = engineName;
_engineVersion = engineVersion;
_commonFileExtensions = commonFileExtensions;
_properties = new HashMap<>();
}
@Override
public final String setProperty(String key, String value)
{
return _properties.put(key, value);
}
@Override
public final String getProperty(String key)
{
return _properties.get(key);
}
@Override
public final String getEngineName()
{
return _engineName;
}
@Override
public final String getEngineVersion()
{
return _engineVersion;
}
@Override
public final String[] getCommonFileExtensions()
{
return Arrays.copyOf(_commonFileExtensions, _commonFileExtensions.length);
}
}

View File

@@ -1,71 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.nio.file.Path;
import java.util.Map;
import java.util.Map.Entry;
/**
* @author HorridoJoho
*/
public interface IExecutionContext
{
/**
* Properties set here override the settings from the IScriptEngine<br>
* this class was created from.
* @param key the key
* @param value the value
* @return the previous value, or null when this key was not present before
*/
String setProperty(String key, String value);
/**
* Executes all script in the iterable.
* @param sourcePaths the scripts to execute
* @return map of failed executions, Path=source file Throwable=thrown exception
* @throws Exception preparation for script execution failed
*/
Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception;
/**
* Executes a single file.
* @param sourcePath the script to execute
* @return entry of failed execution, Path=source file Throwable=thrown exception
* @throws Exception preparation for script execution failed
*/
Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception;
/**
* Method to get the specified property value.
* @param key the key
* @return the value, or null if the key is not present
*/
String getProperty(String key);
/**
* Method to get the current executing script file.
* @return the currently executing script file, null if non
*/
Path getCurrentExecutingScript();
/**
* Method to get the script engine this execution context belongs to.
* @return the script engine this execution context belongs to
*/
IScriptingEngine getScriptingEngine();
}

View File

@@ -1,75 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
/**
* @author HorridoJoho
*/
public interface IScriptingEngine
{
/**
* Sets script engine properties. The script values will be available<br>
* to the the insatnces created {@link IExecutionContext} implementation.
* @param key the key
* @param value the value
* @return the previous value, or null when this key was not present before
*/
String setProperty(String key, String value);
/**
* Creates an execution context.
* @return the created execution context.
*/
IExecutionContext createExecutionContext();
/**
* Method to get the specified property value.
* @param key the key
* @return the value,or null if the key is not present
*/
String getProperty(String key);
/**
* Method to get the engine name.
* @return the engine name
*/
String getEngineName();
/**
* Method to get the engine version.
* @return the engine version
*/
String getEngineVersion();
/**
* Method to get the scripting language name.
* @return the scripting engine name
*/
String getLanguageName();
/**
* Method to get the the language version.
* @return the language version
*/
String getLanguageVersion();
/**
* Method to retrive the commonly used file extensions for the language.
* @return the commonly used file extensions for the language
*/
String[] getCommonFileExtensions();
}

View File

@@ -17,7 +17,6 @@
package com.l2jmobius.gameserver.scripting; package com.l2jmobius.gameserver.scripting;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.file.FileVisitResult; import java.nio.file.FileVisitResult;
import java.nio.file.Files; import java.nio.file.Files;
@@ -31,9 +30,6 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Objects;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@@ -41,32 +37,25 @@ import org.w3c.dom.Document;
import com.l2jmobius.Config; import com.l2jmobius.Config;
import com.l2jmobius.commons.util.IXmlReader; import com.l2jmobius.commons.util.IXmlReader;
import com.l2jmobius.gameserver.scripting.java.JavaExecutionContext;
import com.l2jmobius.gameserver.scripting.java.JavaScriptingEngine; import com.l2jmobius.gameserver.scripting.java.JavaScriptingEngine;
/** /**
* Caches script engines and provides functionality for executing and managing scripts. * @author Mobius
* @author KenM, HorridoJoho
*/ */
public final class ScriptEngineManager implements IXmlReader public final class ScriptEngineManager implements IXmlReader
{ {
private static final Logger LOGGER = Logger.getLogger(ScriptEngineManager.class.getName()); private static final Logger LOGGER = Logger.getLogger(ScriptEngineManager.class.getName());
public static final Path SCRIPT_FOLDER = Config.SCRIPT_ROOT.toPath(); public static final Path SCRIPT_FOLDER = Config.SCRIPT_ROOT.toPath();
public static final Path MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "MasterHandler.java"); public static final Path MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "MasterHandler.java");
public static final Path EFFECT_MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "EffectMasterHandler.java"); public static final Path EFFECT_MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "EffectMasterHandler.java");
private IExecutionContext _javaExecutionContext = null; private static final JavaExecutionContext _javaExecutionContext = new JavaScriptingEngine().createExecutionContext();
static final List<String> _exclusions = new ArrayList<>(); protected static final List<String> _exclusions = new ArrayList<>();
protected ScriptEngineManager() protected ScriptEngineManager()
{ {
final Properties props = loadProperties();
// Default java engine implementation
registerEngine(new JavaScriptingEngine(), props);
// Load external script engines
ServiceLoader.load(IScriptingEngine.class).forEach(engine -> registerEngine(engine, props));
// Load Scripts.xml // Load Scripts.xml
load(); load();
} }
@@ -141,71 +130,6 @@ public final class ScriptEngineManager implements IXmlReader
} }
} }
private Properties loadProperties()
{
Properties props = null;
try (FileInputStream fis = new FileInputStream("config/ScriptEngine.ini"))
{
props = new Properties();
props.load(fis);
}
catch (Exception e)
{
props = null;
LOGGER.warning("Couldn't load ScriptEngine.ini: " + e.getMessage());
}
return props;
}
private void registerEngine(IScriptingEngine engine, Properties props)
{
maybeSetProperties("language." + engine.getLanguageName() + ".", props, engine);
_javaExecutionContext = engine.createExecutionContext();
LOGGER.info("ScriptEngine: " + engine.getEngineName() + " " + engine.getEngineVersion() + " (" + engine.getLanguageName() + " " + engine.getLanguageVersion() + ")");
}
private void maybeSetProperties(String propPrefix, Properties props, IScriptingEngine engine)
{
if (props == null)
{
return;
}
for (Entry<Object, Object> prop : props.entrySet())
{
String key = (String) prop.getKey();
String value = (String) prop.getValue();
if (key.startsWith(propPrefix))
{
key = key.substring(propPrefix.length());
if (value.startsWith("%") && value.endsWith("%"))
{
value = System.getProperty(value.substring(1, value.length() - 1));
}
engine.setProperty(key, value);
}
}
}
public void executeScriptList() throws Exception
{
if (Config.ALT_DEV_NO_QUESTS)
{
return;
}
final List<Path> files = new ArrayList<>();
processDirectory(SCRIPT_FOLDER.toFile(), files);
final Map<Path, Throwable> invokationErrors = _javaExecutionContext.executeScripts(files);
for (Entry<Path, Throwable> entry : invokationErrors.entrySet())
{
LOGGER.log(Level.WARNING, "ScriptEngine: " + entry.getKey() + " failed execution!", entry.getValue());
}
}
private void processDirectory(File dir, List<Path> files) private void processDirectory(File dir, List<Path> files)
{ {
for (File file : dir.listFiles()) for (File file : dir.listFiles())
@@ -227,15 +151,12 @@ public final class ScriptEngineManager implements IXmlReader
public void executeScript(Path sourceFile) throws Exception public void executeScript(Path sourceFile) throws Exception
{ {
Objects.requireNonNull(sourceFile);
if (!sourceFile.isAbsolute()) if (!sourceFile.isAbsolute())
{ {
sourceFile = SCRIPT_FOLDER.resolve(sourceFile); sourceFile = SCRIPT_FOLDER.resolve(sourceFile);
} }
sourceFile = sourceFile.toAbsolutePath(); sourceFile = sourceFile.toAbsolutePath();
Objects.requireNonNull(sourceFile, "ScriptFile: " + sourceFile + " does not have an extension to determine the script engine!");
final Entry<Path, Throwable> error = _javaExecutionContext.executeScript(sourceFile); final Entry<Path, Throwable> error = _javaExecutionContext.executeScript(sourceFile);
if (error != null) if (error != null)
@@ -244,6 +165,23 @@ public final class ScriptEngineManager implements IXmlReader
} }
} }
public void executeScriptList() throws Exception
{
if (Config.ALT_DEV_NO_QUESTS)
{
return;
}
final List<Path> files = new ArrayList<>();
processDirectory(SCRIPT_FOLDER.toFile(), files);
final Map<Path, Throwable> invokationErrors = _javaExecutionContext.executeScripts(files);
for (Entry<Path, Throwable> entry : invokationErrors.entrySet())
{
LOGGER.log(Level.WARNING, "ScriptEngine: " + entry.getKey() + " failed execution!", entry.getValue());
}
}
public Path getCurrentLoadingScript() public Path getCurrentLoadingScript()
{ {
return _javaExecutionContext.getCurrentExecutingScript(); return _javaExecutionContext.getCurrentExecutingScript();
@@ -251,11 +189,11 @@ public final class ScriptEngineManager implements IXmlReader
public static ScriptEngineManager getInstance() public static ScriptEngineManager getInstance()
{ {
return SingletonHolder._instance; return SingletonHolder.INSTANCE;
} }
private static class SingletonHolder private static class SingletonHolder
{ {
protected static final ScriptEngineManager _instance = new ScriptEngineManager(); protected static final ScriptEngineManager INSTANCE = new ScriptEngineManager();
} }
} }

View File

@@ -1,28 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting.java;
/**
* @author HorridoJoho
*/
public final class JavaCompilerException extends RuntimeException
{
public JavaCompilerException(String diagnostics)
{
super(diagnostics);
}
}

View File

@@ -22,9 +22,9 @@ import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.LinkedHashMap; import java.util.HashMap;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
@@ -34,22 +34,20 @@ import org.openjavac.tools.Diagnostic;
import org.openjavac.tools.DiagnosticCollector; import org.openjavac.tools.DiagnosticCollector;
import org.openjavac.tools.JavaFileObject; import org.openjavac.tools.JavaFileObject;
import com.l2jmobius.gameserver.scripting.AbstractExecutionContext;
import com.l2jmobius.gameserver.scripting.annotations.Disabled; import com.l2jmobius.gameserver.scripting.annotations.Disabled;
/** /**
* @author HorridoJoho * @author HorridoJoho
*/ */
public final class JavaExecutionContext extends AbstractExecutionContext<JavaScriptingEngine> public final class JavaExecutionContext extends JavaScriptingEngine
{ {
private static final Logger LOGGER = Logger.getLogger(JavaExecutionContext.class.getName()); private static final Logger LOGGER = Logger.getLogger(JavaExecutionContext.class.getName());
private static final List<String> _options = new LinkedList<>(); private static final List<String> _options = new ArrayList<>();
private static Path _currentExecutingScript;
JavaExecutionContext(JavaScriptingEngine engine) JavaExecutionContext(JavaScriptingEngine engine)
{ {
super(engine);
// Set options. // Set options.
addOptionIfNotNull(_options, getProperty("source"), "-source"); addOptionIfNotNull(_options, getProperty("source"), "-source");
addOptionIfNotNull(_options, getProperty("sourcepath"), "-sourcepath"); addOptionIfNotNull(_options, getProperty("sourcepath"), "-sourcepath");
@@ -76,7 +74,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
else else
{ {
throw new JavaCompilerException("Could not determine target version!"); throw new RuntimeException("Could not determine target version!");
} }
} }
} }
@@ -133,16 +131,15 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
} }
@Override
public Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception public Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception
{ {
final DiagnosticCollector<JavaFileObject> fileManagerDiagnostics = new DiagnosticCollector<>(); final DiagnosticCollector<JavaFileObject> fileManagerDiagnostics = new DiagnosticCollector<>();
final DiagnosticCollector<JavaFileObject> compilationDiagnostics = new DiagnosticCollector<>(); final DiagnosticCollector<JavaFileObject> compilationDiagnostics = new DiagnosticCollector<>();
try (ScriptingFileManager fileManager = new ScriptingFileManager(getScriptingEngine().getCompiler().getStandardFileManager(fileManagerDiagnostics, null, StandardCharsets.UTF_8))) try (ScriptingFileManager fileManager = new ScriptingFileManager(getCompiler().getStandardFileManager(fileManagerDiagnostics, null, StandardCharsets.UTF_8)))
{ {
// We really need an iterable of files or strings. // We really need an iterable of files or strings.
final List<String> sourcePathStrings = new LinkedList<>(); final List<String> sourcePathStrings = new ArrayList<>();
for (Path sourcePath : sourcePaths) for (Path sourcePath : sourcePaths)
{ {
sourcePathStrings.add(sourcePath.toString()); sourcePathStrings.add(sourcePath.toString());
@@ -150,7 +147,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
final StringWriter strOut = new StringWriter(); final StringWriter strOut = new StringWriter();
final PrintWriter out = new PrintWriter(strOut); final PrintWriter out = new PrintWriter(strOut);
final boolean compilationSuccess = getScriptingEngine().getCompiler().getTask(out, fileManager, compilationDiagnostics, _options, null, fileManager.getJavaFileObjectsFromStrings(sourcePathStrings)).call(); final boolean compilationSuccess = getCompiler().getTask(out, fileManager, compilationDiagnostics, _options, null, fileManager.getJavaFileObjectsFromStrings(sourcePathStrings)).call();
if (!compilationSuccess) if (!compilationSuccess)
{ {
out.println(); out.println();
@@ -175,12 +172,12 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
out.println("\t\tmessage: " + diagnostic.getMessage(null)); out.println("\t\tmessage: " + diagnostic.getMessage(null));
} }
throw new JavaCompilerException(strOut.toString()); throw new RuntimeException(strOut.toString());
} }
final ClassLoader parentClassLoader = determineScriptParentClassloader(); final ClassLoader parentClassLoader = determineScriptParentClassloader();
final Map<Path, Throwable> executionFailures = new LinkedHashMap<>(); final Map<Path, Throwable> executionFailures = new HashMap<>();
final Iterable<ScriptingOutputFileObject> compiledClasses = fileManager.getCompiledClasses(); final Iterable<ScriptingOutputFileObject> compiledClasses = fileManager.getCompiledClasses();
for (Path sourcePath : sourcePaths) for (Path sourcePath : sourcePaths)
{ {
@@ -199,7 +196,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
found = true; found = true;
setCurrentExecutingScript(compiledSourcePath); _currentExecutingScript = compiledSourcePath;
try try
{ {
final ScriptingClassLoader loader = new ScriptingClassLoader(parentClassLoader, compiledClasses); final ScriptingClassLoader loader = new ScriptingClassLoader(parentClassLoader, compiledClasses);
@@ -227,7 +224,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
finally finally
{ {
setCurrentExecutingScript(null); _currentExecutingScript = null;
} }
break; break;
@@ -244,7 +241,6 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
} }
@Override
public Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception public Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception
{ {
final Map<Path, Throwable> executionFailures = executeScripts(Arrays.asList(sourcePath)); final Map<Path, Throwable> executionFailures = executeScripts(Arrays.asList(sourcePath));
@@ -254,4 +250,9 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
return null; return null;
} }
public final Path getCurrentExecutingScript()
{
return _currentExecutingScript;
}
} }

View File

@@ -16,77 +16,66 @@
*/ */
package com.l2jmobius.gameserver.scripting.java; package com.l2jmobius.gameserver.scripting.java;
import java.util.Arrays; import java.io.FileInputStream;
import java.util.HashMap;
import javax.lang.model.SourceVersion; import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.logging.Logger;
import org.openjavac.tools.JavaCompiler; import org.openjavac.tools.JavaCompiler;
import org.openjavac.tools.javac.api.JavacTool; import org.openjavac.tools.javac.api.JavacTool;
import com.l2jmobius.gameserver.scripting.AbstractScriptingEngine;
import com.l2jmobius.gameserver.scripting.IExecutionContext;
/** /**
* @author HorridoJoho, Mobius * @author Mobius
*/ */
public final class JavaScriptingEngine extends AbstractScriptingEngine public class JavaScriptingEngine
{ {
private volatile JavaCompiler _compiler; private static final Logger LOGGER = Logger.getLogger(JavaScriptingEngine.class.getName());
private final static Map<String, String> _properties = new HashMap<>();
private final static JavaCompiler _compiler = JavacTool.create();
public JavaScriptingEngine() public JavaScriptingEngine()
{ {
super("Java Engine", "10", "java"); // Load config.
} Properties props = new Properties();
try (FileInputStream fis = new FileInputStream("config/ScriptEngine.ini"))
private void determineCompilerOrThrow()
{
if (_compiler == null)
{ {
_compiler = JavacTool.create(); props.load(fis);
}
catch (Exception e)
{
LOGGER.warning("Could not load ScriptEngine.ini: " + e.getMessage());
} }
if (_compiler == null) // Set properties.
for (Entry<Object, Object> prop : props.entrySet())
{ {
throw new IllegalStateException("No JavaCompiler service installed!"); String key = (String) prop.getKey();
} String value = (String) prop.getValue();
}
if (value.startsWith("%") && value.endsWith("%"))
private void ensureCompilerOrThrow()
{
if (_compiler == null)
{
synchronized (this)
{ {
if (_compiler == null) value = System.getProperty(value.substring(1, value.length() - 1));
{
determineCompilerOrThrow();
}
} }
_properties.put(key, value);
} }
} }
JavaCompiler getCompiler() public JavaExecutionContext createExecutionContext()
{ {
return _compiler;
}
@Override
public IExecutionContext createExecutionContext()
{
ensureCompilerOrThrow();
return new JavaExecutionContext(this); return new JavaExecutionContext(this);
} }
@Override public final String getProperty(String key)
public String getLanguageName()
{ {
return "Java"; return _properties.get(key);
} }
@Override public JavaCompiler getCompiler()
public String getLanguageVersion()
{ {
ensureCompilerOrThrow(); return _compiler;
return Arrays.deepToString(_compiler.getSourceVersions().toArray(new SourceVersion[0])).replace("RELEASE_", "");
} }
} }

View File

@@ -144,5 +144,4 @@ final class ScriptingOutputFileObject implements JavaFileObject
{ {
return null; return null;
} }
} }

View File

@@ -1,23 +1,23 @@
############################################################################### # ---------------------------------------------------------------------------
# Properties retrived with System.getProperty(String) can be used as values # Script Engine Settings
# ---------------------------------------------------------------------------
# Properties retrieved with System.getProperty(String) can be used as values
# by enclosing the property name with %. Eg.: %java.class.path% # by enclosing the property name with %. Eg.: %java.class.path%
###############################################################################
# The parent class loader for isolated script class loaders. # The parent class loader for isolated script class loaders.
# When this property is not specified, has an invalid value or is a class name which could not be found, the System classloader is used. # When this property is not specified, has an invalid value or is a class name which could not be found, the System classloader is used.
# Values: System, ThreadContext or a fully qualified java class name # Values: System, ThreadContext or a fully qualified java class name
language.Java.classloader=System classloader=System
#language.Java.classloader=ThreadContext #classloader=ThreadContext
# Source compatibility # Source compatibility.
language.Java.source=1.8 source=1.8
# The java sourcepath, when you have a different datapack root, you must change this too. # The java sourcepath, when you have a different datapack root, you must change this too.
language.Java.sourcepath=data/scripts sourcepath=data/scripts
# The java classpath # The java classpath.
language.Java.cp=%java.class.path% cp=%java.class.path%
# The debug informations to generate for compiled class files # The debug informations to generate for compiled class files.
language.Java.g=source,lines,vars g=source,lines,vars

View File

@@ -1,75 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
/**
* @author HorridoJoho
* @param <T>
*/
public abstract class AbstractExecutionContext<T extends IScriptingEngine> implements IExecutionContext
{
private final T _engine;
private final Map<String, String> _properties;
private volatile Path _currentExecutingScipt;
protected AbstractExecutionContext(T engine)
{
if (engine == null)
{
throw new IllegalArgumentException();
}
_engine = engine;
_properties = new HashMap<>();
}
protected final void setCurrentExecutingScript(Path currentExecutingScript)
{
_currentExecutingScipt = currentExecutingScript;
}
@Override
public final String setProperty(String key, String value)
{
return _properties.put(key, value);
}
@Override
public final String getProperty(String key)
{
if (!_properties.containsKey(key))
{
return _engine.getProperty(key);
}
return _properties.get(key);
}
@Override
public final Path getCurrentExecutingScript()
{
return _currentExecutingScipt;
}
@Override
public final T getScriptingEngine()
{
return _engine;
}
}

View File

@@ -1,74 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @author HorridoJoho
*/
public abstract class AbstractScriptingEngine implements IScriptingEngine
{
private final String _engineName;
private final String _engineVersion;
private final String[] _commonFileExtensions;
private final Map<String, String> _properties;
protected AbstractScriptingEngine(String engineName, String engineVersion, String... commonFileExtensions)
{
if ((engineName == null) || engineName.isEmpty() || (engineVersion == null) || engineVersion.isEmpty() || (commonFileExtensions == null) || (commonFileExtensions.length == 0))
{
throw new IllegalArgumentException();
}
_engineName = engineName;
_engineVersion = engineVersion;
_commonFileExtensions = commonFileExtensions;
_properties = new HashMap<>();
}
@Override
public final String setProperty(String key, String value)
{
return _properties.put(key, value);
}
@Override
public final String getProperty(String key)
{
return _properties.get(key);
}
@Override
public final String getEngineName()
{
return _engineName;
}
@Override
public final String getEngineVersion()
{
return _engineVersion;
}
@Override
public final String[] getCommonFileExtensions()
{
return Arrays.copyOf(_commonFileExtensions, _commonFileExtensions.length);
}
}

View File

@@ -1,71 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.nio.file.Path;
import java.util.Map;
import java.util.Map.Entry;
/**
* @author HorridoJoho
*/
public interface IExecutionContext
{
/**
* Properties set here override the settings from the IScriptEngine<br>
* this class was created from.
* @param key the key
* @param value the value
* @return the previous value, or null when this key was not present before
*/
String setProperty(String key, String value);
/**
* Executes all script in the iterable.
* @param sourcePaths the scripts to execute
* @return map of failed executions, Path=source file Throwable=thrown exception
* @throws Exception preparation for script execution failed
*/
Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception;
/**
* Executes a single file.
* @param sourcePath the script to execute
* @return entry of failed execution, Path=source file Throwable=thrown exception
* @throws Exception preparation for script execution failed
*/
Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception;
/**
* Method to get the specified property value.
* @param key the key
* @return the value, or null if the key is not present
*/
String getProperty(String key);
/**
* Method to get the current executing script file.
* @return the currently executing script file, null if non
*/
Path getCurrentExecutingScript();
/**
* Method to get the script engine this execution context belongs to.
* @return the script engine this execution context belongs to
*/
IScriptingEngine getScriptingEngine();
}

View File

@@ -1,75 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
/**
* @author HorridoJoho
*/
public interface IScriptingEngine
{
/**
* Sets script engine properties. The script values will be available<br>
* to the the insatnces created {@link IExecutionContext} implementation.
* @param key the key
* @param value the value
* @return the previous value, or null when this key was not present before
*/
String setProperty(String key, String value);
/**
* Creates an execution context.
* @return the created execution context.
*/
IExecutionContext createExecutionContext();
/**
* Method to get the specified property value.
* @param key the key
* @return the value,or null if the key is not present
*/
String getProperty(String key);
/**
* Method to get the engine name.
* @return the engine name
*/
String getEngineName();
/**
* Method to get the engine version.
* @return the engine version
*/
String getEngineVersion();
/**
* Method to get the scripting language name.
* @return the scripting engine name
*/
String getLanguageName();
/**
* Method to get the the language version.
* @return the language version
*/
String getLanguageVersion();
/**
* Method to retrive the commonly used file extensions for the language.
* @return the commonly used file extensions for the language
*/
String[] getCommonFileExtensions();
}

View File

@@ -17,7 +17,6 @@
package com.l2jmobius.gameserver.scripting; package com.l2jmobius.gameserver.scripting;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.file.FileVisitResult; import java.nio.file.FileVisitResult;
import java.nio.file.Files; import java.nio.file.Files;
@@ -31,9 +30,6 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Objects;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@@ -41,15 +37,16 @@ import org.w3c.dom.Document;
import com.l2jmobius.Config; import com.l2jmobius.Config;
import com.l2jmobius.commons.util.IXmlReader; import com.l2jmobius.commons.util.IXmlReader;
import com.l2jmobius.gameserver.scripting.java.JavaExecutionContext;
import com.l2jmobius.gameserver.scripting.java.JavaScriptingEngine; import com.l2jmobius.gameserver.scripting.java.JavaScriptingEngine;
/** /**
* Caches script engines and provides functionality for executing and managing scripts. * @author Mobius
* @author KenM, HorridoJoho
*/ */
public final class ScriptEngineManager implements IXmlReader public final class ScriptEngineManager implements IXmlReader
{ {
private static final Logger LOGGER = Logger.getLogger(ScriptEngineManager.class.getName()); private static final Logger LOGGER = Logger.getLogger(ScriptEngineManager.class.getName());
public static final Path SCRIPT_FOLDER = Config.SCRIPT_ROOT.toPath(); public static final Path SCRIPT_FOLDER = Config.SCRIPT_ROOT.toPath();
public static final Path MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "MasterHandler.java"); public static final Path MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "MasterHandler.java");
public static final Path EFFECT_MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "EffectMasterHandler.java"); public static final Path EFFECT_MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "EffectMasterHandler.java");
@@ -57,19 +54,11 @@ public final class ScriptEngineManager implements IXmlReader
public static final Path CONDITION_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "ConditionMasterHandler.java"); public static final Path CONDITION_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "ConditionMasterHandler.java");
public static final Path ONE_DAY_REWARD_MASTER_HANDLER = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "DailyMissionMasterHandler.java"); public static final Path ONE_DAY_REWARD_MASTER_HANDLER = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "DailyMissionMasterHandler.java");
private IExecutionContext _javaExecutionContext = null; private static final JavaExecutionContext _javaExecutionContext = new JavaScriptingEngine().createExecutionContext();
static final List<String> _exclusions = new ArrayList<>(); protected static final List<String> _exclusions = new ArrayList<>();
protected ScriptEngineManager() protected ScriptEngineManager()
{ {
final Properties props = loadProperties();
// Default java engine implementation
registerEngine(new JavaScriptingEngine(), props);
// Load external script engines
ServiceLoader.load(IScriptingEngine.class).forEach(engine -> registerEngine(engine, props));
// Load Scripts.xml // Load Scripts.xml
load(); load();
} }
@@ -144,71 +133,6 @@ public final class ScriptEngineManager implements IXmlReader
} }
} }
private Properties loadProperties()
{
Properties props = null;
try (FileInputStream fis = new FileInputStream("config/ScriptEngine.ini"))
{
props = new Properties();
props.load(fis);
}
catch (Exception e)
{
props = null;
LOGGER.warning("Couldn't load ScriptEngine.ini: " + e.getMessage());
}
return props;
}
private void registerEngine(IScriptingEngine engine, Properties props)
{
maybeSetProperties("language." + engine.getLanguageName() + ".", props, engine);
_javaExecutionContext = engine.createExecutionContext();
LOGGER.info("ScriptEngine: " + engine.getEngineName() + " " + engine.getEngineVersion() + " (" + engine.getLanguageName() + " " + engine.getLanguageVersion() + ")");
}
private void maybeSetProperties(String propPrefix, Properties props, IScriptingEngine engine)
{
if (props == null)
{
return;
}
for (Entry<Object, Object> prop : props.entrySet())
{
String key = (String) prop.getKey();
String value = (String) prop.getValue();
if (key.startsWith(propPrefix))
{
key = key.substring(propPrefix.length());
if (value.startsWith("%") && value.endsWith("%"))
{
value = System.getProperty(value.substring(1, value.length() - 1));
}
engine.setProperty(key, value);
}
}
}
public void executeScriptList() throws Exception
{
if (Config.ALT_DEV_NO_QUESTS)
{
return;
}
final List<Path> files = new ArrayList<>();
processDirectory(SCRIPT_FOLDER.toFile(), files);
final Map<Path, Throwable> invokationErrors = _javaExecutionContext.executeScripts(files);
for (Entry<Path, Throwable> entry : invokationErrors.entrySet())
{
LOGGER.log(Level.WARNING, "ScriptEngine: " + entry.getKey() + " failed execution!", entry.getValue());
}
}
private void processDirectory(File dir, List<Path> files) private void processDirectory(File dir, List<Path> files)
{ {
for (File file : dir.listFiles()) for (File file : dir.listFiles())
@@ -230,15 +154,12 @@ public final class ScriptEngineManager implements IXmlReader
public void executeScript(Path sourceFile) throws Exception public void executeScript(Path sourceFile) throws Exception
{ {
Objects.requireNonNull(sourceFile);
if (!sourceFile.isAbsolute()) if (!sourceFile.isAbsolute())
{ {
sourceFile = SCRIPT_FOLDER.resolve(sourceFile); sourceFile = SCRIPT_FOLDER.resolve(sourceFile);
} }
sourceFile = sourceFile.toAbsolutePath(); sourceFile = sourceFile.toAbsolutePath();
Objects.requireNonNull(sourceFile, "ScriptFile: " + sourceFile + " does not have an extension to determine the script engine!");
final Entry<Path, Throwable> error = _javaExecutionContext.executeScript(sourceFile); final Entry<Path, Throwable> error = _javaExecutionContext.executeScript(sourceFile);
if (error != null) if (error != null)
@@ -247,6 +168,23 @@ public final class ScriptEngineManager implements IXmlReader
} }
} }
public void executeScriptList() throws Exception
{
if (Config.ALT_DEV_NO_QUESTS)
{
return;
}
final List<Path> files = new ArrayList<>();
processDirectory(SCRIPT_FOLDER.toFile(), files);
final Map<Path, Throwable> invokationErrors = _javaExecutionContext.executeScripts(files);
for (Entry<Path, Throwable> entry : invokationErrors.entrySet())
{
LOGGER.log(Level.WARNING, "ScriptEngine: " + entry.getKey() + " failed execution!", entry.getValue());
}
}
public Path getCurrentLoadingScript() public Path getCurrentLoadingScript()
{ {
return _javaExecutionContext.getCurrentExecutingScript(); return _javaExecutionContext.getCurrentExecutingScript();
@@ -254,11 +192,11 @@ public final class ScriptEngineManager implements IXmlReader
public static ScriptEngineManager getInstance() public static ScriptEngineManager getInstance()
{ {
return SingletonHolder._instance; return SingletonHolder.INSTANCE;
} }
private static class SingletonHolder private static class SingletonHolder
{ {
protected static final ScriptEngineManager _instance = new ScriptEngineManager(); protected static final ScriptEngineManager INSTANCE = new ScriptEngineManager();
} }
} }

View File

@@ -1,28 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting.java;
/**
* @author HorridoJoho
*/
public final class JavaCompilerException extends RuntimeException
{
public JavaCompilerException(String diagnostics)
{
super(diagnostics);
}
}

View File

@@ -22,9 +22,9 @@ import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.LinkedHashMap; import java.util.HashMap;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
@@ -34,22 +34,20 @@ import org.openjavac.tools.Diagnostic;
import org.openjavac.tools.DiagnosticCollector; import org.openjavac.tools.DiagnosticCollector;
import org.openjavac.tools.JavaFileObject; import org.openjavac.tools.JavaFileObject;
import com.l2jmobius.gameserver.scripting.AbstractExecutionContext;
import com.l2jmobius.gameserver.scripting.annotations.Disabled; import com.l2jmobius.gameserver.scripting.annotations.Disabled;
/** /**
* @author HorridoJoho * @author HorridoJoho
*/ */
public final class JavaExecutionContext extends AbstractExecutionContext<JavaScriptingEngine> public final class JavaExecutionContext extends JavaScriptingEngine
{ {
private static final Logger LOGGER = Logger.getLogger(JavaExecutionContext.class.getName()); private static final Logger LOGGER = Logger.getLogger(JavaExecutionContext.class.getName());
private static final List<String> _options = new LinkedList<>(); private static final List<String> _options = new ArrayList<>();
private static Path _currentExecutingScript;
JavaExecutionContext(JavaScriptingEngine engine) JavaExecutionContext(JavaScriptingEngine engine)
{ {
super(engine);
// Set options. // Set options.
addOptionIfNotNull(_options, getProperty("source"), "-source"); addOptionIfNotNull(_options, getProperty("source"), "-source");
addOptionIfNotNull(_options, getProperty("sourcepath"), "-sourcepath"); addOptionIfNotNull(_options, getProperty("sourcepath"), "-sourcepath");
@@ -76,7 +74,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
else else
{ {
throw new JavaCompilerException("Could not determine target version!"); throw new RuntimeException("Could not determine target version!");
} }
} }
} }
@@ -133,16 +131,15 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
} }
@Override
public Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception public Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception
{ {
final DiagnosticCollector<JavaFileObject> fileManagerDiagnostics = new DiagnosticCollector<>(); final DiagnosticCollector<JavaFileObject> fileManagerDiagnostics = new DiagnosticCollector<>();
final DiagnosticCollector<JavaFileObject> compilationDiagnostics = new DiagnosticCollector<>(); final DiagnosticCollector<JavaFileObject> compilationDiagnostics = new DiagnosticCollector<>();
try (ScriptingFileManager fileManager = new ScriptingFileManager(getScriptingEngine().getCompiler().getStandardFileManager(fileManagerDiagnostics, null, StandardCharsets.UTF_8))) try (ScriptingFileManager fileManager = new ScriptingFileManager(getCompiler().getStandardFileManager(fileManagerDiagnostics, null, StandardCharsets.UTF_8)))
{ {
// We really need an iterable of files or strings. // We really need an iterable of files or strings.
final List<String> sourcePathStrings = new LinkedList<>(); final List<String> sourcePathStrings = new ArrayList<>();
for (Path sourcePath : sourcePaths) for (Path sourcePath : sourcePaths)
{ {
sourcePathStrings.add(sourcePath.toString()); sourcePathStrings.add(sourcePath.toString());
@@ -150,7 +147,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
final StringWriter strOut = new StringWriter(); final StringWriter strOut = new StringWriter();
final PrintWriter out = new PrintWriter(strOut); final PrintWriter out = new PrintWriter(strOut);
final boolean compilationSuccess = getScriptingEngine().getCompiler().getTask(out, fileManager, compilationDiagnostics, _options, null, fileManager.getJavaFileObjectsFromStrings(sourcePathStrings)).call(); final boolean compilationSuccess = getCompiler().getTask(out, fileManager, compilationDiagnostics, _options, null, fileManager.getJavaFileObjectsFromStrings(sourcePathStrings)).call();
if (!compilationSuccess) if (!compilationSuccess)
{ {
out.println(); out.println();
@@ -175,12 +172,12 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
out.println("\t\tmessage: " + diagnostic.getMessage(null)); out.println("\t\tmessage: " + diagnostic.getMessage(null));
} }
throw new JavaCompilerException(strOut.toString()); throw new RuntimeException(strOut.toString());
} }
final ClassLoader parentClassLoader = determineScriptParentClassloader(); final ClassLoader parentClassLoader = determineScriptParentClassloader();
final Map<Path, Throwable> executionFailures = new LinkedHashMap<>(); final Map<Path, Throwable> executionFailures = new HashMap<>();
final Iterable<ScriptingOutputFileObject> compiledClasses = fileManager.getCompiledClasses(); final Iterable<ScriptingOutputFileObject> compiledClasses = fileManager.getCompiledClasses();
for (Path sourcePath : sourcePaths) for (Path sourcePath : sourcePaths)
{ {
@@ -199,7 +196,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
found = true; found = true;
setCurrentExecutingScript(compiledSourcePath); _currentExecutingScript = compiledSourcePath;
try try
{ {
final ScriptingClassLoader loader = new ScriptingClassLoader(parentClassLoader, compiledClasses); final ScriptingClassLoader loader = new ScriptingClassLoader(parentClassLoader, compiledClasses);
@@ -227,7 +224,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
finally finally
{ {
setCurrentExecutingScript(null); _currentExecutingScript = null;
} }
break; break;
@@ -244,7 +241,6 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
} }
@Override
public Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception public Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception
{ {
final Map<Path, Throwable> executionFailures = executeScripts(Arrays.asList(sourcePath)); final Map<Path, Throwable> executionFailures = executeScripts(Arrays.asList(sourcePath));
@@ -254,4 +250,9 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
return null; return null;
} }
public final Path getCurrentExecutingScript()
{
return _currentExecutingScript;
}
} }

View File

@@ -16,77 +16,66 @@
*/ */
package com.l2jmobius.gameserver.scripting.java; package com.l2jmobius.gameserver.scripting.java;
import java.util.Arrays; import java.io.FileInputStream;
import java.util.HashMap;
import javax.lang.model.SourceVersion; import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.logging.Logger;
import org.openjavac.tools.JavaCompiler; import org.openjavac.tools.JavaCompiler;
import org.openjavac.tools.javac.api.JavacTool; import org.openjavac.tools.javac.api.JavacTool;
import com.l2jmobius.gameserver.scripting.AbstractScriptingEngine;
import com.l2jmobius.gameserver.scripting.IExecutionContext;
/** /**
* @author HorridoJoho, Mobius * @author Mobius
*/ */
public final class JavaScriptingEngine extends AbstractScriptingEngine public class JavaScriptingEngine
{ {
private volatile JavaCompiler _compiler; private static final Logger LOGGER = Logger.getLogger(JavaScriptingEngine.class.getName());
private final static Map<String, String> _properties = new HashMap<>();
private final static JavaCompiler _compiler = JavacTool.create();
public JavaScriptingEngine() public JavaScriptingEngine()
{ {
super("Java Engine", "10", "java"); // Load config.
} Properties props = new Properties();
try (FileInputStream fis = new FileInputStream("config/ScriptEngine.ini"))
private void determineCompilerOrThrow()
{
if (_compiler == null)
{ {
_compiler = JavacTool.create(); props.load(fis);
}
catch (Exception e)
{
LOGGER.warning("Could not load ScriptEngine.ini: " + e.getMessage());
} }
if (_compiler == null) // Set properties.
for (Entry<Object, Object> prop : props.entrySet())
{ {
throw new IllegalStateException("No JavaCompiler service installed!"); String key = (String) prop.getKey();
} String value = (String) prop.getValue();
}
if (value.startsWith("%") && value.endsWith("%"))
private void ensureCompilerOrThrow()
{
if (_compiler == null)
{
synchronized (this)
{ {
if (_compiler == null) value = System.getProperty(value.substring(1, value.length() - 1));
{
determineCompilerOrThrow();
}
} }
_properties.put(key, value);
} }
} }
JavaCompiler getCompiler() public JavaExecutionContext createExecutionContext()
{ {
return _compiler;
}
@Override
public IExecutionContext createExecutionContext()
{
ensureCompilerOrThrow();
return new JavaExecutionContext(this); return new JavaExecutionContext(this);
} }
@Override public final String getProperty(String key)
public String getLanguageName()
{ {
return "Java"; return _properties.get(key);
} }
@Override public JavaCompiler getCompiler()
public String getLanguageVersion()
{ {
ensureCompilerOrThrow(); return _compiler;
return Arrays.deepToString(_compiler.getSourceVersions().toArray(new SourceVersion[0])).replace("RELEASE_", "");
} }
} }

View File

@@ -144,5 +144,4 @@ final class ScriptingOutputFileObject implements JavaFileObject
{ {
return null; return null;
} }
} }

View File

@@ -1,23 +1,23 @@
############################################################################### # ---------------------------------------------------------------------------
# Properties retrived with System.getProperty(String) can be used as values # Script Engine Settings
# ---------------------------------------------------------------------------
# Properties retrieved with System.getProperty(String) can be used as values
# by enclosing the property name with %. Eg.: %java.class.path% # by enclosing the property name with %. Eg.: %java.class.path%
###############################################################################
# The parent class loader for isolated script class loaders. # The parent class loader for isolated script class loaders.
# When this property is not specified, has an invalid value or is a class name which could not be found, the System classloader is used. # When this property is not specified, has an invalid value or is a class name which could not be found, the System classloader is used.
# Values: System, ThreadContext or a fully qualified java class name # Values: System, ThreadContext or a fully qualified java class name
language.Java.classloader=System classloader=System
#language.Java.classloader=ThreadContext #classloader=ThreadContext
# Source compatibility # Source compatibility.
language.Java.source=1.8 source=1.8
# The java sourcepath, when you have a different datapack root, you must change this too. # The java sourcepath, when you have a different datapack root, you must change this too.
language.Java.sourcepath=data/scripts sourcepath=data/scripts
# The java classpath # The java classpath.
language.Java.cp=%java.class.path% cp=%java.class.path%
# The debug informations to generate for compiled class files # The debug informations to generate for compiled class files.
language.Java.g=source,lines,vars g=source,lines,vars

View File

@@ -1,75 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
/**
* @author HorridoJoho
* @param <T>
*/
public abstract class AbstractExecutionContext<T extends IScriptingEngine> implements IExecutionContext
{
private final T _engine;
private final Map<String, String> _properties;
private volatile Path _currentExecutingScipt;
protected AbstractExecutionContext(T engine)
{
if (engine == null)
{
throw new IllegalArgumentException();
}
_engine = engine;
_properties = new HashMap<>();
}
protected final void setCurrentExecutingScript(Path currentExecutingScript)
{
_currentExecutingScipt = currentExecutingScript;
}
@Override
public final String setProperty(String key, String value)
{
return _properties.put(key, value);
}
@Override
public final String getProperty(String key)
{
if (!_properties.containsKey(key))
{
return _engine.getProperty(key);
}
return _properties.get(key);
}
@Override
public final Path getCurrentExecutingScript()
{
return _currentExecutingScipt;
}
@Override
public final T getScriptingEngine()
{
return _engine;
}
}

View File

@@ -1,74 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @author HorridoJoho
*/
public abstract class AbstractScriptingEngine implements IScriptingEngine
{
private final String _engineName;
private final String _engineVersion;
private final String[] _commonFileExtensions;
private final Map<String, String> _properties;
protected AbstractScriptingEngine(String engineName, String engineVersion, String... commonFileExtensions)
{
if ((engineName == null) || engineName.isEmpty() || (engineVersion == null) || engineVersion.isEmpty() || (commonFileExtensions == null) || (commonFileExtensions.length == 0))
{
throw new IllegalArgumentException();
}
_engineName = engineName;
_engineVersion = engineVersion;
_commonFileExtensions = commonFileExtensions;
_properties = new HashMap<>();
}
@Override
public final String setProperty(String key, String value)
{
return _properties.put(key, value);
}
@Override
public final String getProperty(String key)
{
return _properties.get(key);
}
@Override
public final String getEngineName()
{
return _engineName;
}
@Override
public final String getEngineVersion()
{
return _engineVersion;
}
@Override
public final String[] getCommonFileExtensions()
{
return Arrays.copyOf(_commonFileExtensions, _commonFileExtensions.length);
}
}

View File

@@ -1,71 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
import java.nio.file.Path;
import java.util.Map;
import java.util.Map.Entry;
/**
* @author HorridoJoho
*/
public interface IExecutionContext
{
/**
* Properties set here override the settings from the IScriptEngine<br>
* this class was created from.
* @param key the key
* @param value the value
* @return the previous value, or null when this key was not present before
*/
String setProperty(String key, String value);
/**
* Executes all script in the iterable.
* @param sourcePaths the scripts to execute
* @return map of failed executions, Path=source file Throwable=thrown exception
* @throws Exception preparation for script execution failed
*/
Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception;
/**
* Executes a single file.
* @param sourcePath the script to execute
* @return entry of failed execution, Path=source file Throwable=thrown exception
* @throws Exception preparation for script execution failed
*/
Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception;
/**
* Method to get the specified property value.
* @param key the key
* @return the value, or null if the key is not present
*/
String getProperty(String key);
/**
* Method to get the current executing script file.
* @return the currently executing script file, null if non
*/
Path getCurrentExecutingScript();
/**
* Method to get the script engine this execution context belongs to.
* @return the script engine this execution context belongs to
*/
IScriptingEngine getScriptingEngine();
}

View File

@@ -1,75 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting;
/**
* @author HorridoJoho
*/
public interface IScriptingEngine
{
/**
* Sets script engine properties. The script values will be available<br>
* to the the insatnces created {@link IExecutionContext} implementation.
* @param key the key
* @param value the value
* @return the previous value, or null when this key was not present before
*/
String setProperty(String key, String value);
/**
* Creates an execution context.
* @return the created execution context.
*/
IExecutionContext createExecutionContext();
/**
* Method to get the specified property value.
* @param key the key
* @return the value,or null if the key is not present
*/
String getProperty(String key);
/**
* Method to get the engine name.
* @return the engine name
*/
String getEngineName();
/**
* Method to get the engine version.
* @return the engine version
*/
String getEngineVersion();
/**
* Method to get the scripting language name.
* @return the scripting engine name
*/
String getLanguageName();
/**
* Method to get the the language version.
* @return the language version
*/
String getLanguageVersion();
/**
* Method to retrive the commonly used file extensions for the language.
* @return the commonly used file extensions for the language
*/
String[] getCommonFileExtensions();
}

View File

@@ -17,7 +17,6 @@
package com.l2jmobius.gameserver.scripting; package com.l2jmobius.gameserver.scripting;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.file.FileVisitResult; import java.nio.file.FileVisitResult;
import java.nio.file.Files; import java.nio.file.Files;
@@ -31,9 +30,6 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Objects;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@@ -41,15 +37,16 @@ import org.w3c.dom.Document;
import com.l2jmobius.Config; import com.l2jmobius.Config;
import com.l2jmobius.commons.util.IXmlReader; import com.l2jmobius.commons.util.IXmlReader;
import com.l2jmobius.gameserver.scripting.java.JavaExecutionContext;
import com.l2jmobius.gameserver.scripting.java.JavaScriptingEngine; import com.l2jmobius.gameserver.scripting.java.JavaScriptingEngine;
/** /**
* Caches script engines and provides functionality for executing and managing scripts. * @author Mobius
* @author KenM, HorridoJoho
*/ */
public final class ScriptEngineManager implements IXmlReader public final class ScriptEngineManager implements IXmlReader
{ {
private static final Logger LOGGER = Logger.getLogger(ScriptEngineManager.class.getName()); private static final Logger LOGGER = Logger.getLogger(ScriptEngineManager.class.getName());
public static final Path SCRIPT_FOLDER = Config.SCRIPT_ROOT.toPath(); public static final Path SCRIPT_FOLDER = Config.SCRIPT_ROOT.toPath();
public static final Path MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "MasterHandler.java"); public static final Path MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "MasterHandler.java");
public static final Path EFFECT_MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "EffectMasterHandler.java"); public static final Path EFFECT_MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "EffectMasterHandler.java");
@@ -57,19 +54,11 @@ public final class ScriptEngineManager implements IXmlReader
public static final Path CONDITION_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "ConditionMasterHandler.java"); public static final Path CONDITION_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "ConditionMasterHandler.java");
public static final Path ONE_DAY_REWARD_MASTER_HANDLER = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "DailyMissionMasterHandler.java"); public static final Path ONE_DAY_REWARD_MASTER_HANDLER = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "DailyMissionMasterHandler.java");
private IExecutionContext _javaExecutionContext = null; private static final JavaExecutionContext _javaExecutionContext = new JavaScriptingEngine().createExecutionContext();
static final List<String> _exclusions = new ArrayList<>(); protected static final List<String> _exclusions = new ArrayList<>();
protected ScriptEngineManager() protected ScriptEngineManager()
{ {
final Properties props = loadProperties();
// Default java engine implementation
registerEngine(new JavaScriptingEngine(), props);
// Load external script engines
ServiceLoader.load(IScriptingEngine.class).forEach(engine -> registerEngine(engine, props));
// Load Scripts.xml // Load Scripts.xml
load(); load();
} }
@@ -144,71 +133,6 @@ public final class ScriptEngineManager implements IXmlReader
} }
} }
private Properties loadProperties()
{
Properties props = null;
try (FileInputStream fis = new FileInputStream("config/ScriptEngine.ini"))
{
props = new Properties();
props.load(fis);
}
catch (Exception e)
{
props = null;
LOGGER.warning("Couldn't load ScriptEngine.ini: " + e.getMessage());
}
return props;
}
private void registerEngine(IScriptingEngine engine, Properties props)
{
maybeSetProperties("language." + engine.getLanguageName() + ".", props, engine);
_javaExecutionContext = engine.createExecutionContext();
LOGGER.info("ScriptEngine: " + engine.getEngineName() + " " + engine.getEngineVersion() + " (" + engine.getLanguageName() + " " + engine.getLanguageVersion() + ")");
}
private void maybeSetProperties(String propPrefix, Properties props, IScriptingEngine engine)
{
if (props == null)
{
return;
}
for (Entry<Object, Object> prop : props.entrySet())
{
String key = (String) prop.getKey();
String value = (String) prop.getValue();
if (key.startsWith(propPrefix))
{
key = key.substring(propPrefix.length());
if (value.startsWith("%") && value.endsWith("%"))
{
value = System.getProperty(value.substring(1, value.length() - 1));
}
engine.setProperty(key, value);
}
}
}
public void executeScriptList() throws Exception
{
if (Config.ALT_DEV_NO_QUESTS)
{
return;
}
final List<Path> files = new ArrayList<>();
processDirectory(SCRIPT_FOLDER.toFile(), files);
final Map<Path, Throwable> invokationErrors = _javaExecutionContext.executeScripts(files);
for (Entry<Path, Throwable> entry : invokationErrors.entrySet())
{
LOGGER.log(Level.WARNING, "ScriptEngine: " + entry.getKey() + " failed execution!", entry.getValue());
}
}
private void processDirectory(File dir, List<Path> files) private void processDirectory(File dir, List<Path> files)
{ {
for (File file : dir.listFiles()) for (File file : dir.listFiles())
@@ -230,15 +154,12 @@ public final class ScriptEngineManager implements IXmlReader
public void executeScript(Path sourceFile) throws Exception public void executeScript(Path sourceFile) throws Exception
{ {
Objects.requireNonNull(sourceFile);
if (!sourceFile.isAbsolute()) if (!sourceFile.isAbsolute())
{ {
sourceFile = SCRIPT_FOLDER.resolve(sourceFile); sourceFile = SCRIPT_FOLDER.resolve(sourceFile);
} }
sourceFile = sourceFile.toAbsolutePath(); sourceFile = sourceFile.toAbsolutePath();
Objects.requireNonNull(sourceFile, "ScriptFile: " + sourceFile + " does not have an extension to determine the script engine!");
final Entry<Path, Throwable> error = _javaExecutionContext.executeScript(sourceFile); final Entry<Path, Throwable> error = _javaExecutionContext.executeScript(sourceFile);
if (error != null) if (error != null)
@@ -247,6 +168,23 @@ public final class ScriptEngineManager implements IXmlReader
} }
} }
public void executeScriptList() throws Exception
{
if (Config.ALT_DEV_NO_QUESTS)
{
return;
}
final List<Path> files = new ArrayList<>();
processDirectory(SCRIPT_FOLDER.toFile(), files);
final Map<Path, Throwable> invokationErrors = _javaExecutionContext.executeScripts(files);
for (Entry<Path, Throwable> entry : invokationErrors.entrySet())
{
LOGGER.log(Level.WARNING, "ScriptEngine: " + entry.getKey() + " failed execution!", entry.getValue());
}
}
public Path getCurrentLoadingScript() public Path getCurrentLoadingScript()
{ {
return _javaExecutionContext.getCurrentExecutingScript(); return _javaExecutionContext.getCurrentExecutingScript();
@@ -254,11 +192,11 @@ public final class ScriptEngineManager implements IXmlReader
public static ScriptEngineManager getInstance() public static ScriptEngineManager getInstance()
{ {
return SingletonHolder._instance; return SingletonHolder.INSTANCE;
} }
private static class SingletonHolder private static class SingletonHolder
{ {
protected static final ScriptEngineManager _instance = new ScriptEngineManager(); protected static final ScriptEngineManager INSTANCE = new ScriptEngineManager();
} }
} }

View File

@@ -1,28 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jmobius.gameserver.scripting.java;
/**
* @author HorridoJoho
*/
public final class JavaCompilerException extends RuntimeException
{
public JavaCompilerException(String diagnostics)
{
super(diagnostics);
}
}

View File

@@ -22,9 +22,9 @@ import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.LinkedHashMap; import java.util.HashMap;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
@@ -34,22 +34,20 @@ import org.openjavac.tools.Diagnostic;
import org.openjavac.tools.DiagnosticCollector; import org.openjavac.tools.DiagnosticCollector;
import org.openjavac.tools.JavaFileObject; import org.openjavac.tools.JavaFileObject;
import com.l2jmobius.gameserver.scripting.AbstractExecutionContext;
import com.l2jmobius.gameserver.scripting.annotations.Disabled; import com.l2jmobius.gameserver.scripting.annotations.Disabled;
/** /**
* @author HorridoJoho * @author HorridoJoho
*/ */
public final class JavaExecutionContext extends AbstractExecutionContext<JavaScriptingEngine> public final class JavaExecutionContext extends JavaScriptingEngine
{ {
private static final Logger LOGGER = Logger.getLogger(JavaExecutionContext.class.getName()); private static final Logger LOGGER = Logger.getLogger(JavaExecutionContext.class.getName());
private static final List<String> _options = new LinkedList<>(); private static final List<String> _options = new ArrayList<>();
private static Path _currentExecutingScript;
JavaExecutionContext(JavaScriptingEngine engine) JavaExecutionContext(JavaScriptingEngine engine)
{ {
super(engine);
// Set options. // Set options.
addOptionIfNotNull(_options, getProperty("source"), "-source"); addOptionIfNotNull(_options, getProperty("source"), "-source");
addOptionIfNotNull(_options, getProperty("sourcepath"), "-sourcepath"); addOptionIfNotNull(_options, getProperty("sourcepath"), "-sourcepath");
@@ -76,7 +74,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
else else
{ {
throw new JavaCompilerException("Could not determine target version!"); throw new RuntimeException("Could not determine target version!");
} }
} }
} }
@@ -133,16 +131,15 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
} }
@Override
public Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception public Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception
{ {
final DiagnosticCollector<JavaFileObject> fileManagerDiagnostics = new DiagnosticCollector<>(); final DiagnosticCollector<JavaFileObject> fileManagerDiagnostics = new DiagnosticCollector<>();
final DiagnosticCollector<JavaFileObject> compilationDiagnostics = new DiagnosticCollector<>(); final DiagnosticCollector<JavaFileObject> compilationDiagnostics = new DiagnosticCollector<>();
try (ScriptingFileManager fileManager = new ScriptingFileManager(getScriptingEngine().getCompiler().getStandardFileManager(fileManagerDiagnostics, null, StandardCharsets.UTF_8))) try (ScriptingFileManager fileManager = new ScriptingFileManager(getCompiler().getStandardFileManager(fileManagerDiagnostics, null, StandardCharsets.UTF_8)))
{ {
// We really need an iterable of files or strings. // We really need an iterable of files or strings.
final List<String> sourcePathStrings = new LinkedList<>(); final List<String> sourcePathStrings = new ArrayList<>();
for (Path sourcePath : sourcePaths) for (Path sourcePath : sourcePaths)
{ {
sourcePathStrings.add(sourcePath.toString()); sourcePathStrings.add(sourcePath.toString());
@@ -150,7 +147,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
final StringWriter strOut = new StringWriter(); final StringWriter strOut = new StringWriter();
final PrintWriter out = new PrintWriter(strOut); final PrintWriter out = new PrintWriter(strOut);
final boolean compilationSuccess = getScriptingEngine().getCompiler().getTask(out, fileManager, compilationDiagnostics, _options, null, fileManager.getJavaFileObjectsFromStrings(sourcePathStrings)).call(); final boolean compilationSuccess = getCompiler().getTask(out, fileManager, compilationDiagnostics, _options, null, fileManager.getJavaFileObjectsFromStrings(sourcePathStrings)).call();
if (!compilationSuccess) if (!compilationSuccess)
{ {
out.println(); out.println();
@@ -175,12 +172,12 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
out.println("\t\tmessage: " + diagnostic.getMessage(null)); out.println("\t\tmessage: " + diagnostic.getMessage(null));
} }
throw new JavaCompilerException(strOut.toString()); throw new RuntimeException(strOut.toString());
} }
final ClassLoader parentClassLoader = determineScriptParentClassloader(); final ClassLoader parentClassLoader = determineScriptParentClassloader();
final Map<Path, Throwable> executionFailures = new LinkedHashMap<>(); final Map<Path, Throwable> executionFailures = new HashMap<>();
final Iterable<ScriptingOutputFileObject> compiledClasses = fileManager.getCompiledClasses(); final Iterable<ScriptingOutputFileObject> compiledClasses = fileManager.getCompiledClasses();
for (Path sourcePath : sourcePaths) for (Path sourcePath : sourcePaths)
{ {
@@ -199,7 +196,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
found = true; found = true;
setCurrentExecutingScript(compiledSourcePath); _currentExecutingScript = compiledSourcePath;
try try
{ {
final ScriptingClassLoader loader = new ScriptingClassLoader(parentClassLoader, compiledClasses); final ScriptingClassLoader loader = new ScriptingClassLoader(parentClassLoader, compiledClasses);
@@ -227,7 +224,7 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
finally finally
{ {
setCurrentExecutingScript(null); _currentExecutingScript = null;
} }
break; break;
@@ -244,7 +241,6 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
} }
@Override
public Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception public Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception
{ {
final Map<Path, Throwable> executionFailures = executeScripts(Arrays.asList(sourcePath)); final Map<Path, Throwable> executionFailures = executeScripts(Arrays.asList(sourcePath));
@@ -254,4 +250,9 @@ public final class JavaExecutionContext extends AbstractExecutionContext<JavaScr
} }
return null; return null;
} }
public final Path getCurrentExecutingScript()
{
return _currentExecutingScript;
}
} }

View File

@@ -16,77 +16,66 @@
*/ */
package com.l2jmobius.gameserver.scripting.java; package com.l2jmobius.gameserver.scripting.java;
import java.util.Arrays; import java.io.FileInputStream;
import java.util.HashMap;
import javax.lang.model.SourceVersion; import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.logging.Logger;
import org.openjavac.tools.JavaCompiler; import org.openjavac.tools.JavaCompiler;
import org.openjavac.tools.javac.api.JavacTool; import org.openjavac.tools.javac.api.JavacTool;
import com.l2jmobius.gameserver.scripting.AbstractScriptingEngine;
import com.l2jmobius.gameserver.scripting.IExecutionContext;
/** /**
* @author HorridoJoho, Mobius * @author Mobius
*/ */
public final class JavaScriptingEngine extends AbstractScriptingEngine public class JavaScriptingEngine
{ {
private volatile JavaCompiler _compiler; private static final Logger LOGGER = Logger.getLogger(JavaScriptingEngine.class.getName());
private final static Map<String, String> _properties = new HashMap<>();
private final static JavaCompiler _compiler = JavacTool.create();
public JavaScriptingEngine() public JavaScriptingEngine()
{ {
super("Java Engine", "10", "java"); // Load config.
} Properties props = new Properties();
try (FileInputStream fis = new FileInputStream("config/ScriptEngine.ini"))
private void determineCompilerOrThrow()
{
if (_compiler == null)
{ {
_compiler = JavacTool.create(); props.load(fis);
}
catch (Exception e)
{
LOGGER.warning("Could not load ScriptEngine.ini: " + e.getMessage());
} }
if (_compiler == null) // Set properties.
for (Entry<Object, Object> prop : props.entrySet())
{ {
throw new IllegalStateException("No JavaCompiler service installed!"); String key = (String) prop.getKey();
} String value = (String) prop.getValue();
}
if (value.startsWith("%") && value.endsWith("%"))
private void ensureCompilerOrThrow()
{
if (_compiler == null)
{
synchronized (this)
{ {
if (_compiler == null) value = System.getProperty(value.substring(1, value.length() - 1));
{
determineCompilerOrThrow();
}
} }
_properties.put(key, value);
} }
} }
JavaCompiler getCompiler() public JavaExecutionContext createExecutionContext()
{ {
return _compiler;
}
@Override
public IExecutionContext createExecutionContext()
{
ensureCompilerOrThrow();
return new JavaExecutionContext(this); return new JavaExecutionContext(this);
} }
@Override public final String getProperty(String key)
public String getLanguageName()
{ {
return "Java"; return _properties.get(key);
} }
@Override public JavaCompiler getCompiler()
public String getLanguageVersion()
{ {
ensureCompilerOrThrow(); return _compiler;
return Arrays.deepToString(_compiler.getSourceVersions().toArray(new SourceVersion[0])).replace("RELEASE_", "");
} }
} }

View File

@@ -144,5 +144,4 @@ final class ScriptingOutputFileObject implements JavaFileObject
{ {
return null; return null;
} }
} }

Some files were not shown because too many files have changed in this diff Show More