| 1 | |
package kg.apc.jmeter.functions; |
| 2 | |
|
| 3 | |
import org.apache.jmeter.engine.util.CompoundVariable; |
| 4 | |
import org.apache.jmeter.functions.AbstractFunction; |
| 5 | |
import org.apache.jmeter.functions.InvalidVariableException; |
| 6 | |
import org.apache.jmeter.samplers.SampleResult; |
| 7 | |
import org.apache.jmeter.samplers.Sampler; |
| 8 | |
import org.apache.jmeter.threads.JMeterVariables; |
| 9 | |
|
| 10 | |
import java.util.Collection; |
| 11 | |
import java.util.LinkedList; |
| 12 | |
import java.util.List; |
| 13 | |
import java.util.Random; |
| 14 | |
|
| 15 | |
public class ChooseRandom extends AbstractFunction { |
| 16 | |
|
| 17 | 1 | private static final List<String> desc = new LinkedList<String>(); |
| 18 | |
private static final String KEY = "__chooseRandom"; |
| 19 | 1 | private static final Random random = new Random(System.currentTimeMillis()); |
| 20 | |
|
| 21 | |
static { |
| 22 | 1 | desc.add("Any number of values to choose from"); |
| 23 | 1 | desc.add("Last value must be variable name where choice will be stored"); |
| 24 | 1 | } |
| 25 | |
|
| 26 | |
private Object[] values; |
| 27 | |
|
| 28 | |
|
| 29 | |
|
| 30 | |
|
| 31 | 4 | public ChooseRandom() { |
| 32 | 4 | } |
| 33 | |
|
| 34 | |
|
| 35 | |
|
| 36 | |
|
| 37 | |
@Override |
| 38 | |
public synchronized String execute(SampleResult previousResult, Sampler currentSampler) |
| 39 | |
throws InvalidVariableException { |
| 40 | 2 | JMeterVariables vars = getVariables(); |
| 41 | 2 | String varName = ((CompoundVariable) values[values.length - 1]).execute().trim(); |
| 42 | 2 | int index = random.nextInt(values.length - 1); |
| 43 | 2 | String choice = ((CompoundVariable) values[index]).execute(); |
| 44 | |
|
| 45 | 2 | if (vars != null && varName != null && varName.length() > 0) { |
| 46 | 2 | vars.put(varName, choice); |
| 47 | |
} |
| 48 | |
|
| 49 | 2 | return choice; |
| 50 | |
} |
| 51 | |
|
| 52 | |
|
| 53 | |
|
| 54 | |
|
| 55 | |
@Override |
| 56 | |
public synchronized void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException { |
| 57 | 2 | checkMinParameterCount(parameters, 3); |
| 58 | 2 | values = parameters.toArray(); |
| 59 | 2 | } |
| 60 | |
|
| 61 | |
|
| 62 | |
|
| 63 | |
|
| 64 | |
@Override |
| 65 | |
public String getReferenceKey() { |
| 66 | 1 | return KEY; |
| 67 | |
} |
| 68 | |
|
| 69 | |
|
| 70 | |
|
| 71 | |
|
| 72 | |
@Override |
| 73 | |
public List<String> getArgumentDesc() { |
| 74 | 1 | return desc; |
| 75 | |
} |
| 76 | |
} |