1 18 19 package org.apache.jmeter.functions; 20 21 import java.io.Serializable ; 22 import java.util.Collection ; 23 import java.util.LinkedList ; 24 import java.util.List ; 25 26 import org.apache.jmeter.engine.util.CompoundVariable; 27 import org.apache.jmeter.samplers.SampleResult; 28 import org.apache.jmeter.samplers.Sampler; 29 import org.apache.jmeter.threads.JMeterVariables; 30 import org.apache.jmeter.util.JMeterUtils; 31 import org.apache.jorphan.logging.LoggingManager; 32 import org.apache.log.Logger; 33 import org.mozilla.javascript.Context; 34 import org.mozilla.javascript.EcmaError; 35 import org.mozilla.javascript.JavaScriptException; 36 import org.mozilla.javascript.Scriptable; 37 import org.mozilla.javascript.WrappedException; 38 39 public class JavaScript extends AbstractFunction implements Serializable 40 { 41 42 private static final List desc = new LinkedList (); 43 private static final String KEY = "__javaScript"; 44 private static Logger log = LoggingManager.getLoggerForClass(); 45 46 static { 47 desc.add("JavaScript expression to evaluate"); 48 desc.add(JMeterUtils.getResString("function_name_param")); 49 } 50 51 private Object [] values; 52 53 public JavaScript() 54 { 55 } 56 57 public Object clone() 58 { 59 JavaScript newJavaScript = new JavaScript(); 60 return newJavaScript; 61 } 62 63 66 public synchronized String execute( 67 SampleResult previousResult, 68 Sampler currentSampler) 69 throws InvalidVariableException 70 { 71 72 JMeterVariables vars = getVariables(); 73 74 String script = ((CompoundVariable) values[0]).execute(); 75 String varName = 76 ((CompoundVariable) values[1]).execute(); 77 String resultStr = ""; 78 79 Context cx = Context.enter(); 80 try 81 { 82 83 Scriptable scope = cx.initStandardObjects(null); 84 Object result = cx.evaluateString(scope, script, "<cmd>", 1, null); 85 86 resultStr = Context.toString(result); 87 vars.put(varName, resultStr); 88 89 } 90 catch (WrappedException e) 91 { 92 log.error("Error processing Javascript",e); 93 throw new InvalidVariableException(); 94 } 95 catch (EcmaError e) 96 { 97 log.error("Error processing Javascript",e); 98 throw new InvalidVariableException(); 99 } 100 catch (JavaScriptException e) 101 { 102 log.error("Error processing Javascript",e); 103 throw new InvalidVariableException(); 104 } 105 finally 106 { 107 Context.exit(); 108 } 109 110 return resultStr; 111 112 } 113 114 117 public void setParameters(Collection parameters) 118 throws InvalidVariableException 119 { 120 121 values = parameters.toArray(); 122 123 if (values.length != 2) 124 { 125 throw new InvalidVariableException( 126 "Expecting 2 parameters, but found " + values.length); } 128 129 } 130 131 134 public String getReferenceKey() 135 { 136 return KEY; 137 } 138 139 142 public List getArgumentDesc() 143 { 144 return desc; 145 } 146 147 } 148 | Popular Tags |