本文整理匯總了Java中javax.script.Compilable類的典型用法代碼示例。如果您正苦於以下問題:Java Compilable類的具體用法?Java Compilable怎麽用?Java Compilable使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Compilable類屬於javax.script包,在下文中一共展示了Compilable類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: invokeFunctionWithCustomScriptContextTest
import javax.script.Compilable; //導入依賴的package包/類
@Test
public void invokeFunctionWithCustomScriptContextTest() throws Exception {
final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// create an engine and a ScriptContext, but don't set it as default
final ScriptContext scriptContext = new SimpleScriptContext();
// Set some value in the context
scriptContext.setAttribute("myString", "foo", ScriptContext.ENGINE_SCOPE);
// Evaluate script with custom context and get back a function
final String script = "function (c) { return myString.indexOf(c); }";
final CompiledScript compiledScript = ((Compilable)engine).compile(script);
final Object func = compiledScript.eval(scriptContext);
// Invoked function should be able to see context it was evaluated with
final Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
assertTrue(((Number)result).intValue() == 1);
}
示例2: init
import javax.script.Compilable; //導入依賴的package包/類
private void init(Snapshot snapshot) throws RuntimeException {
this.snapshot = snapshot;
try {
ScriptEngineManager manager = new ScriptEngineManager();
engine = manager.getEngineByName("JavaScript"); // NOI18N
InputStream strm = getInitStream();
CompiledScript cs = ((Compilable)engine).compile(new InputStreamReader(strm));
cs.eval();
Object heap = ((Invocable)engine).invokeFunction("wrapHeapSnapshot", snapshot); // NOI18N
engine.put("heap", heap); // NOI18N
engine.put("cancelled", cancelled); // NOI18N
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, "Error initializing snapshot", ex); // NOI18N
throw new RuntimeException(ex);
}
}
示例3: ScriptExecutor
import javax.script.Compilable; //導入依賴的package包/類
/**
* Construct a new script executors
*
* @param engine
* the script engine to use, must not be <code>null</code>
* @param command
* the command to execute, may be <code>null</code>
* @param classLoader
* the class loader to use when executing, may be
* <code>null</code>
* @throws ScriptException
*/
public ScriptExecutor ( final ScriptEngine engine, final String command, final ClassLoader classLoader, final String sourceName ) throws Exception
{
this.engine = engine;
this.command = command;
this.commandUrl = null;
this.classLoader = classLoader;
this.sourceName = sourceName;
if ( command != null && engine instanceof Compilable && !Boolean.getBoolean ( PROP_NAME_DISABLE_COMPILE ) )
{
if ( sourceName != null )
{
engine.put ( ScriptEngine.FILENAME, sourceName );
}
Scripts.executeWithClassLoader ( classLoader, new Callable<Void> () {
@Override
public Void call () throws Exception
{
ScriptExecutor.this.compiledScript = ( (Compilable)engine ).compile ( command );
return null;
}
} );
}
}
示例4: createScriptEngine
import javax.script.Compilable; //導入依賴的package包/類
@Override
protected ScriptEngine createScriptEngine() {
String scripEngineName = SCRIPT_ENGINE_NAME;
// ScriptEngine result = new ScriptEngineManager().getEngineByName(scripEngineName);
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
ScriptEngine result = factory.getScriptEngine("-scripting");
Validate.isInstanceOf(Compilable.class, result, "ScriptingEngine %s doesn't implement Compilable", scripEngineName);
Validate.isInstanceOf(Invocable.class, result, "ScriptingEngine %s doesn't implement Invocable", scripEngineName);
PROCESSOR_CLASSES.forEach((interfaceClass, scriptClass) -> addImport(result, scriptClass, interfaceClass.getSimpleName()));
addImport(result, NashornPlugin.class, Plugin.class.getSimpleName());
getStandardImportClasses().forEach(cls -> addImport(result, cls));
result.put(KnowledgeBaseConstants.VAR_ENGINE_OPERATIONS, getEngineOperations());
eval(result, "load(\"classpath:" + INITIAL_SCRIPT + "\");");
return result;
}
示例5: createScriptEngine
import javax.script.Compilable; //導入依賴的package包/類
@Override
protected ScriptEngine createScriptEngine() {
String scripEngineName = SCRIPT_ENGINE_NAME;
ScriptEngine result = new ScriptEngineManager().getEngineByName(scripEngineName);
Validate.isInstanceOf(Compilable.class, result, "ScriptingEngine %s doesn't implement Compilable", scripEngineName);
Validate.isInstanceOf(Invocable.class, result, "ScriptingEngine %s doesn't implement Invocable", scripEngineName);
KotlinConstants.PROCESSOR_CLASSES
.forEach((interfaceClass, scriptClass) -> addImport(result, scriptClass, interfaceClass.getSimpleName()));
addImport(result, KPlugin.class, Plugin.class.getSimpleName());
// TODO The line below performs very slow in Kotlin
eval(result, getStandardImportClasses().stream().map(cls -> "import " + cls.getName()).collect(Collectors.joining("\n")));
setVariable(result, KnowledgeBaseConstants.VAR_ENGINE_OPERATIONS, getEngineOperations());
return result;
}
示例6: test
import javax.script.Compilable; //導入依賴的package包/類
@Test
public final void test() throws Exception {
String csvMapperScript = "mapFunction = function(inputHeaders, inputField, inputValue, outputField, line) return inputValue end";
String simpleScript = "return inputValue";
CompiledScript compiledScript = (CompiledScript) ((Compilable) scriptEngine).compile(simpleScript);
Bindings bindings = scriptEngine.createBindings();
// inputHeaders, inputField, inputValue, outputField, line
bindings.put("inputHeaders", "");
bindings.put("inputField", "");
bindings.put("inputValue", "testreturnvalue");
bindings.put("outputField", "");
bindings.put("line", "");
String result = (String) compiledScript.eval(bindings);
System.out.println(result);
assertEquals("testreturnvalue", result);
}
示例7: init
import javax.script.Compilable; //導入依賴的package包/類
private void init() throws ProcessingException {
// check formula
if (StringUtility.isNullOrEmpty(StringUtility.trim(script))) {
throw new VetoException(Texts.get("FormulaEmptyMessage"));
}
// Script
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// Compile Formula
Compilable compilingEngine = (Compilable) engine;
try {
compiledScript = compilingEngine.compile(script);
}
catch (ScriptException e) {
handleScriptException(e, script);
}
bindings = engine.createBindings();
}
示例8: initialize
import javax.script.Compilable; //導入依賴的package包/類
@Override
public void initialize(final InputSplit genericSplit, final TaskAttemptContext context) throws IOException {
this.lineRecordReader.initialize(genericSplit, context);
final Configuration configuration = context.getConfiguration();
if (configuration.get(Constants.GREMLIN_HADOOP_GRAPH_FILTER, null) != null)
this.graphFilter = VertexProgramHelper.deserialize(ConfUtil.makeApacheConfiguration(configuration), Constants.GREMLIN_HADOOP_GRAPH_FILTER);
this.engine = new GremlinGroovyScriptEngine((CompilerCustomizerProvider) new DefaultImportCustomizerProvider());
//this.engine = ScriptEngineCache.get(configuration.get(SCRIPT_ENGINE, ScriptEngineCache.DEFAULT_SCRIPT_ENGINE));
final FileSystem fs = FileSystem.get(configuration);
try (final InputStream stream = fs.open(new Path(configuration.get(SCRIPT_FILE)));
final InputStreamReader reader = new InputStreamReader(stream)) {
this.parse = String.join("\n", IOUtils.toString(reader), READ_CALL);
script = ((Compilable) engine).compile(this.parse);
} catch (ScriptException e) {
throw new IOException(e.getMessage(), e);
}
}
示例9: invokeFunctionWithCustomScriptContextTest
import javax.script.Compilable; //導入依賴的package包/類
@Test
public void invokeFunctionWithCustomScriptContextTest() throws Exception {
final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// create an engine and a ScriptContext, but don't set it as default
ScriptContext scriptContext = new SimpleScriptContext();
// Set some value in the context
scriptContext.setAttribute("myString", "foo", ScriptContext.ENGINE_SCOPE);
// Evaluate script with custom context and get back a function
final String script = "function (c) { return myString.indexOf(c); }";
CompiledScript compiledScript = ((Compilable)engine).compile(script);
Object func = compiledScript.eval(scriptContext);
// Invoked function should be able to see context it was evaluated with
Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
assertTrue(((Number)result).intValue() == 1);
}
示例10: prepare
import javax.script.Compilable; //導入依賴的package包/類
@Override
public void prepare() throws PreparationException
{
if( adapter.isCompilable() )
{
ScriptEngine scriptEngine = adapter.getStaticScriptEngine();
if( scriptEngine instanceof Compilable )
{
try
{
compiledScript = ( (Compilable) scriptEngine ).compile( sourceCode );
}
catch( ScriptException x )
{
String scriptEngineName = (String) adapter.getAttributes().get( Jsr223LanguageAdapter.JSR223_SCRIPT_ENGINE_NAME );
throw new PreparationException( executable.getDocumentName(), startLineNumber, startColumnNumber, "Compilation error in " + scriptEngineName, x );
}
}
}
}
示例11: EBusConfigurationProvider
import javax.script.Compilable; //導入依賴的package包/類
/**
* Constructor
*/
public EBusConfigurationProvider() {
final ScriptEngineManager mgr = new ScriptEngineManager();
// load script engine if available
if(mgr != null) {
final ScriptEngine engine = mgr.getEngineByName("JavaScript");
if(engine == null) {
logger.warn("Unable to load \"JavaScript\" engine! Skip every eBus value calculated by JavaScript.");
} else if (engine instanceof Compilable) {
compEngine = (Compilable) engine;
}
}
}
示例12: setup
import javax.script.Compilable; //導入依賴的package包/類
@Before
public void setup() {
ScriptEngineManager scriptEngineManager = spy(new ScriptEngineManager());
when(scriptEngineManager.getEngineByName(anyString())).then(new Answer<ScriptEngine>() {
public ScriptEngine answer(InvocationOnMock invocation) throws Throwable {
scriptEngineSpy = spy((ScriptEngine) invocation.callRealMethod());
compilableSpy = (Compilable) scriptEngineSpy;
return scriptEngineSpy;
}
});
DefaultDmnEngineConfiguration configuration = new DefaultDmnEngineConfiguration();
configuration.setScriptEngineResolver(new DefaultScriptEngineResolver(scriptEngineManager));
configuration.init();
elProviderSpy = spy(configuration.getElProvider());
configuration.setElProvider(elProviderSpy);
expressionEvaluationHandler = new ExpressionEvaluationHandler(configuration);
}
示例13: AttributeEvalParser
import javax.script.Compilable; //導入依賴的package包/類
/**
* @see #instance(Attribute, String, Map)
* @param attribute
* @param scriptText
* @param constVars
*/
private AttributeEvalParser(
Attribute<T> attribute,
String scriptText,
Map<String, Comparable<?>> constVars) {
this.attribute = attribute;
this.type = (Class<T>) attribute.getType();
this.scriptText = scriptText;
manager = new ScriptEngineManager();
engine = manager.getEngineByName("js"); // javascript
// compile to make script run faster on each execution
try {
script = ((Compilable) engine).compile(scriptText);
} catch (ScriptException e) {
e.printStackTrace();
}
// bindings for vars
bindings = engine.createBindings();
// add vars from constants
bindings.putAll(constVars);
}
示例14: testCompileFromFile2
import javax.script.Compilable; //導入依賴的package包/類
@Test
public void testCompileFromFile2() throws FileNotFoundException, ScriptException {
InputStreamReader code = getStream("nameread.kt");
CompiledScript result = ((Compilable) engine).compile(code);
assertNotNull(result);
// First time
Bindings bnd1 = engine.createBindings();
StringWriter ret1;
bnd1.put("out", new PrintWriter(ret1 = new StringWriter()));
assertNotNull(result.eval(bnd1));
assertEquals("Provide a name", ret1.toString().trim());
// Second time
Bindings bnd2 = engine.createBindings();
bnd2.put(ScriptEngine.ARGV, new String[] { "Amadeus" });
StringWriter ret2;
bnd2.put("out", new PrintWriter(ret2 = new StringWriter()));
assertNotNull(result.eval(bnd2));
assertEquals("Hello, Amadeus!", ret2.toString().trim());
}
示例15: getElValue
import javax.script.Compilable; //導入依賴的package包/類
@SuppressWarnings("unchecked")
@Override
public <T> T getElValue(String exp, Object target, Object[] arguments, Object retVal, boolean hasRetVal, Class<T> valueType) throws Exception {
Bindings bindings=new SimpleBindings();
bindings.put(TARGET, target);
bindings.put(ARGS, arguments);
if(hasRetVal) {
bindings.put(RET_VAL, retVal);
}
CompiledScript script=expCache.get(exp);
if(null != script) {
return (T)script.eval(bindings);
}
if(engine instanceof Compilable) {
Compilable compEngine=(Compilable)engine;
script=compEngine.compile(funcs + exp);
expCache.put(exp, script);
return (T)script.eval(bindings);
} else {
return (T)engine.eval(funcs + exp, bindings);
}
}