Exemple #1
0
/**
 * @author mstover
 *     <p>To change this generated comment edit the template variable "typecomment":
 *     Window>Preferences>Java>Templates.
 */
public class RegexFunction extends AbstractFunction implements Serializable {
  private static transient Logger log =
      Hierarchy.getDefaultHierarchy().getLoggerFor("jmeter.elements");
  public static final String ALL = "ALL";
  public static final String RAND = "RAND";
  public static final String KEY = "__regexFunction";

  Object[] values;
  private static Random rand = new Random();
  private static List desc = new LinkedList();
  Pattern searchPattern;
  Object[] template;
  String valueIndex, defaultValue, between;
  transient PatternCompiler compiler = new Perl5Compiler();
  Pattern templatePattern;
  private String name;
  private static ThreadLocal localMatcher =
      new ThreadLocal() {
        protected Object initialValue() {
          return new Perl5Matcher();
        }
      };

  static {
    desc.add(JMeterUtils.getResString("regexfunc_param_1"));
    desc.add(JMeterUtils.getResString("regexfunc_param_2"));
    desc.add(JMeterUtils.getResString("regexfunc_param_3"));
    desc.add(JMeterUtils.getResString("regexfunc_param_4"));
    desc.add(JMeterUtils.getResString("regexfunc_param_5"));
    desc.add(JMeterUtils.getResString("function_name_param"));
  }

  public RegexFunction() {
    valueIndex = between = name = "";
    try {
      templatePattern = compiler.compile("\\$(\\d+)\\$");
    } catch (MalformedPatternException e) {
      log.error("", e);
    }
  }

  public String execute(SampleResult previousResult, Sampler currentSampler)
      throws InvalidVariableException {
    try {
      searchPattern = compiler.compile(((CompoundVariable) values[0]).execute());
      generateTemplate(((CompoundVariable) values[1]).execute());

      if (values.length > 2) {
        valueIndex = ((CompoundVariable) values[2]).execute();
      }
      if (valueIndex.equals("")) {
        valueIndex = "1";
      }

      if (values.length > 3) {
        between = ((CompoundVariable) values[3]).execute();
      }

      if (values.length > 4) {
        String dv = ((CompoundVariable) values[4]).execute();
        if (!dv.equals("")) {
          defaultValue = dv;
        }
      }

      if (values.length > 5) {
        name = ((CompoundVariable) values[values.length - 1]).execute();
      }
    } catch (MalformedPatternException e) {
      log.error("", e);
      throw new InvalidVariableException("Bad regex pattern");
    } catch (Exception e) {
      throw new InvalidVariableException(e.getMessage());
    }

    getVariables().put(name, defaultValue);
    if (previousResult == null || previousResult.getResponseData() == null) {
      return defaultValue;
    }

    List collectAllMatches = new ArrayList();
    try {
      PatternMatcher matcher = (PatternMatcher) localMatcher.get();
      String responseText = new String(previousResult.getResponseData());
      PatternMatcherInput input = new PatternMatcherInput(responseText);
      while (matcher.contains(input, searchPattern)) {
        MatchResult match = matcher.getMatch();
        collectAllMatches.add(match);
      }
    } catch (NumberFormatException e) {
      log.error("", e);
      return defaultValue;
    } catch (Exception e) {
      return defaultValue;
    }

    if (collectAllMatches.size() == 0) {
      return defaultValue;
    }

    if (valueIndex.equals(ALL)) {
      StringBuffer value = new StringBuffer();
      Iterator it = collectAllMatches.iterator();
      boolean first = true;
      while (it.hasNext()) {
        if (!first) {
          value.append(between);
        } else {
          first = false;
        }
        value.append(generateResult((MatchResult) it.next()));
      }
      return value.toString();
    } else if (valueIndex.equals(RAND)) {
      MatchResult result =
          (MatchResult) collectAllMatches.get(rand.nextInt(collectAllMatches.size()));
      return generateResult(result);
    } else {
      try {
        int index = Integer.parseInt(valueIndex) - 1;
        MatchResult result = (MatchResult) collectAllMatches.get(index);
        return generateResult(result);
      } catch (NumberFormatException e) {
        float ratio = Float.parseFloat(valueIndex);
        MatchResult result =
            (MatchResult) collectAllMatches.get((int) (collectAllMatches.size() * ratio + .5) - 1);
        return generateResult(result);
      } catch (IndexOutOfBoundsException e) {
        return defaultValue;
      }
    }
  }

  private void saveGroups(MatchResult result) {
    if (result != null) {
      JMeterVariables vars = getVariables();
      for (int x = 0; x < result.groups(); x++) {
        vars.put(name + "_g" + x, result.group(x));
      }
    }
  }

  public List getArgumentDesc() {
    return desc;
  }

  private String generateResult(MatchResult match) {
    saveGroups(match);
    StringBuffer result = new StringBuffer();
    for (int a = 0; a < template.length; a++) {
      if (template[a] instanceof String) {
        result.append(template[a]);
      } else {
        result.append(match.group(((Integer) template[a]).intValue()));
      }
    }
    JMeterVariables vars = getVariables();
    vars.put(name, result.toString());
    return result.toString();
  }

  public String getReferenceKey() {
    return KEY;
  }

  public void setParameters(Collection parameters) throws InvalidVariableException {
    values = parameters.toArray();
    if (values.length < 2) {
      throw new InvalidVariableException();
    }

    //		defaultValue = URLDecoder.decode(parameters);
    defaultValue = "";
  }

  private void generateTemplate(String rawTemplate) {
    List pieces = new ArrayList();
    List combined = new LinkedList();
    PatternMatcher matcher = new Perl5Matcher();
    Util.split(pieces, new Perl5Matcher(), templatePattern, rawTemplate);
    PatternMatcherInput input = new PatternMatcherInput(rawTemplate);
    int count = 0;
    Iterator iter = pieces.iterator();
    boolean startsWith = isFirstElementGroup(rawTemplate);
    while (iter.hasNext()) {
      boolean matchExists = matcher.contains(input, templatePattern);
      if (startsWith) {
        if (matchExists) {
          combined.add(new Integer(matcher.getMatch().group(1)));
        }
        combined.add(iter.next());
      } else {
        combined.add(iter.next());
        if (matchExists) {
          combined.add(new Integer(matcher.getMatch().group(1)));
        }
      }
    }
    if (matcher.contains(input, templatePattern)) {
      combined.add(new Integer(matcher.getMatch().group(1)));
    }
    template = combined.toArray();
  }

  private boolean isFirstElementGroup(String rawData) {
    try {
      Pattern pattern = compiler.compile("^\\$\\d+\\$");
      return new Perl5Matcher().contains(rawData, pattern);
    } catch (MalformedPatternException e) {
      log.error("", e);
      return false;
    }
  }

  /*	public static class Test extends TestCase
  {
  	RegexFunction variable;
  	SampleResult result;
  	Collection params;

  	public Test(String name)
  	{
  		super(name);
  	}

  	public void setUp()
  	{
  		variable = new RegexFunction();
  		result = new SampleResult();
  		String data = "<company-xmlext-query-ret><row><value field=\"RetCode\">LIS_OK</value><value"+
  		" field=\"RetCodeExtension\"></value><value field=\"alias\"></value><value"+
  		" field=\"positioncount\"></value><value field=\"invalidpincount\">0</value><value"+
  		" field=\"pinposition1\">1</value><value"+
  		" field=\"pinpositionvalue1\"></value><value"+
  		" field=\"pinposition2\">5</value><value"+
  		" field=\"pinpositionvalue2\"></value><value"+
  		" field=\"pinposition3\">6</value><value"+
  		" field=\"pinpositionvalue3\"></value></row></company-xmlext-query-ret>";
  		result.setResponseData(data.getBytes());
  	}

  	public void testVariableExtraction() throws Exception
  	{
  		params = new LinkedList();
  		params.add(ArgumentEncoder.encode("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
  		params.add("$2$");
  		params.add("2");
  		variable.setParameters(params);
  		variable.setJMeterVariables(new JMeterVariables());
  		String match = variable.execute(result,null);
  		assertEquals("5",match);
  	}

  	public void testVariableExtraction2() throws Exception
  	{
  		params = new LinkedList();
  		params.add(ArgumentEncoder.encode("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
  		params.add("$1$");
  		params.add("3");
  		variable.setParameters(params);
  		variable.setJMeterVariables(new JMeterVariables());
  		String match = variable.execute(result,null);
  		assertEquals("pinposition3",match);
  	}

  	public void testVariableExtraction5() throws Exception
  	{
  		params = new LinkedList();
  		params.add(ArgumentEncoder.encode("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
  		params.add("$1$");
  		params.add("All");
  		params.add("_");
  		variable.setParameters(params);
  		variable.setJMeterVariables(new JMeterVariables());
  		String match = variable.execute(result,null);
  		assertEquals("pinposition1_pinposition2_pinposition3",match);
  	}

  	public void testVariableExtraction6() throws Exception
  	{
  		params = new LinkedList();
  		params.add(	ArgumentEncoder.encode("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
  		params.add("$2$");
  		params.add("4");
  		params.add("");
  		params.add("default");
  		variable.setParameters(params);
  		variable.setJMeterVariables(new JMeterVariables());
  		String match = variable.execute(result,null);
  		assertEquals("default",match);
  	}

  	public void testComma() throws Exception
  	{
  		params = new LinkedList();
  		params.add(ArgumentEncoder.encode("<value,? field=\"(pinposition\\d+)\">(\\d+)</value>"));
  		params.add("$1$");
  		params.add("3");
  		variable.setParameters(params);
  		variable.setJMeterVariables(new JMeterVariables());
  		String match = variable.execute(result,null);
  		assertEquals("pinposition3",match);
  	}

  	public void testVariableExtraction3() throws Exception
  	{
  		params = new LinkedList();
  		params.add(ArgumentEncoder.encode("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
  		params.add("_$1$");
  		params.add("5");
  		variable.setParameters(params);
  		variable.setJMeterVariables(new JMeterVariables());
  		String match = variable.execute(result,null);
  		assertEquals("_pinposition2",match);
  	}

  	public void testVariableExtraction4() throws Exception
  	{
  		params = new LinkedList();
  		params.add(ArgumentEncoder.encode("<value field=\"(pinposition\\d+)\">(\\d+)</value>"));
  		params.add(ArgumentEncoder.encode("$2$, "));
  		params.add(".333");
  		variable.setParameters(params);
  		variable.setJMeterVariables(new JMeterVariables());

  		String match = variable.execute(result,null);
  		assertEquals("1, ",match);
  	}

  	public void testDefaultValue() throws Exception
  	{
  		params = new LinkedList();
  		params.add(ArgumentEncoder.encode("<value,, field=\"(pinposition\\d+)\">(\\d+)</value>"));
  		params.add(ArgumentEncoder.encode("$2$, "));
  		params.add(".333");
  		params.add("");
  		params.add("No Value Found");
  		variable.setParameters(params);
  		variable.setJMeterVariables(new JMeterVariables());

  		String match = variable.execute(result,null);
  		assertEquals("No Value Found",match);
  	}
  }*/

}
/**
 * @author mstover
 *     <p>To change this generated comment edit the template variable "typecomment":
 *     Window>Preferences>Java>Templates.
 */
public class URLRewritingModifier extends AbstractTestElement
    implements Serializable, PreProcessor {
  private static transient Logger log =
      Hierarchy.getDefaultHierarchy().getLoggerFor("jmeter.protocol.http");
  private Pattern case1, case2, case3, case4;
  transient Perl5Compiler compiler = new Perl5Compiler();
  private static final String ARGUMENT_NAME = "argument_name";
  private static final String PATH_EXTENSION = "path_extension";
  private static final String PATH_EXTENSION_NO_EQUALS = "path_extension_no_equals";

  public void process() {
    Sampler sampler = JMeterContextService.getContext().getCurrentSampler();
    SampleResult responseText = JMeterContextService.getContext().getPreviousResult();
    if (responseText == null) {
      return;
    }
    initRegex(getArgumentName());
    String text = new String(responseText.getResponseData());
    Perl5Matcher matcher = JMeterUtils.getMatcher();
    String value = "";
    if (matcher.contains(text, case1)) {
      MatchResult result = matcher.getMatch();
      value = result.group(1);
    } else if (matcher.contains(text, case2)) {
      MatchResult result = matcher.getMatch();
      value = result.group(1);
    } else if (matcher.contains(text, case3)) {
      MatchResult result = matcher.getMatch();
      value = result.group(1);
    } else if (matcher.contains(text, case4)) {
      MatchResult result = matcher.getMatch();
      value = result.group(1);
    }

    modify((HTTPSampler) sampler, value);
  }

  private void modify(HTTPSampler sampler, String value) {
    if (isPathExtension()) {
      if (isPathExtensionNoEquals()) {
        sampler.setPath(sampler.getPath() + ";" + getArgumentName() + value);
      } else {
        sampler.setPath(sampler.getPath() + ";" + getArgumentName() + "=" + value);
      }
    } else {
      sampler.getArguments().removeArgument(getArgumentName());
      sampler.getArguments().addArgument(new HTTPArgument(getArgumentName(), value, true));
    }
  }

  public void setArgumentName(String argName) {
    setProperty(ARGUMENT_NAME, argName);
  }

  private void initRegex(String argName) {
    case1 =
        JMeterUtils.getPatternCache()
            .getPattern(
                argName + "=([^\"'>& \n\r;]*)[& \\n\\r\"'>;]?$?", Perl5Compiler.MULTILINE_MASK);
    case2 =
        JMeterUtils.getPatternCache()
            .getPattern(
                "[Nn][Aa][Mm][Ee]=\"" + argName + "\"[^>]+[vV][Aa][Ll][Uu][Ee]=\"([^\"]*)\"",
                Perl5Compiler.MULTILINE_MASK);
    case3 =
        JMeterUtils.getPatternCache()
            .getPattern(
                "[vV][Aa][Ll][Uu][Ee]=\"([^\"]*)\"[^>]+[Nn][Aa][Mm][Ee]=\"" + argName + "\"",
                Perl5Compiler.MULTILINE_MASK);
    // case1 could be re-written "=?([^..."  instead of creating a new pattern?
    case4 =
        JMeterUtils.getPatternCache()
            .getPattern(
                argName + "([^\"'>& \n\r]*)[& \\n\\r\"'>]?$?", Perl5Compiler.MULTILINE_MASK);
  }

  public String getArgumentName() {
    return getPropertyAsString(ARGUMENT_NAME);
  }

  public void setPathExtension(boolean pathExt) {
    setProperty(new BooleanProperty(PATH_EXTENSION, pathExt));
  }

  public void setPathExtensionNoEquals(boolean pathExtNoEquals) {
    setProperty(new BooleanProperty(PATH_EXTENSION_NO_EQUALS, pathExtNoEquals));
  }

  public boolean isPathExtension() {
    return getPropertyAsBoolean(PATH_EXTENSION);
  }

  public boolean isPathExtensionNoEquals() {
    return getPropertyAsBoolean(PATH_EXTENSION_NO_EQUALS);
  }

  public static class Test extends TestCase {
    SampleResult response;
    JMeterContext context;

    public Test(String name) {
      super(name);
    }

    public void setUp() {
      context = JMeterContextService.getContext();
    }

    public void testGrabSessionId() throws Exception {
      String html =
          "location: http://server.com/index.html?session_id=jfdkjdkf%20jddkfdfjkdjfdf%22;";
      response = new SampleResult();
      response.setResponseData(html.getBytes());
      URLRewritingModifier mod = new URLRewritingModifier();
      mod.setArgumentName("session_id");
      HTTPSampler sampler = createSampler();
      sampler.addArgument("session_id", "adfasdfdsafasdfasd");
      context.setCurrentSampler(sampler);
      context.setPreviousResult(response);
      mod.process();
      Arguments args = sampler.getArguments();
      assertEquals(
          "jfdkjdkf jddkfdfjkdjfdf\"",
          ((Argument) args.getArguments().get(0).getObjectValue()).getValue());
      assertEquals(
          "http://server.com/index.html?session_id=jfdkjdkf+jddkfdfjkdjfdf%22", sampler.toString());
    }

    public void testGrabSessionId2() throws Exception {
      String html = "<a href=\"http://server.com/index.html?session_id=jfdkjdkfjddkfdfjkdjfdf\">";
      response = new SampleResult();
      response.setResponseData(html.getBytes());
      URLRewritingModifier mod = new URLRewritingModifier();
      mod.setArgumentName("session_id");
      HTTPSampler sampler = createSampler();
      context.setCurrentSampler(sampler);
      context.setPreviousResult(response);
      mod.process();
      Arguments args = sampler.getArguments();
      assertEquals(
          "jfdkjdkfjddkfdfjkdjfdf",
          ((Argument) args.getArguments().get(0).getObjectValue()).getValue());
    }

    private HTTPSampler createSampler() {
      HTTPSampler sampler = new HTTPSampler();
      sampler.setDomain("server.com");
      sampler.setPath("index.html");
      sampler.setMethod(HTTPSampler.GET);
      sampler.setProtocol("http");
      return sampler;
    }

    public void testGrabSessionId3() throws Exception {
      String html = "href='index.html?session_id=jfdkjdkfjddkfdfjkdjfdf'";
      response = new SampleResult();
      response.setResponseData(html.getBytes());
      URLRewritingModifier mod = new URLRewritingModifier();
      mod.setArgumentName("session_id");
      HTTPSampler sampler = createSampler();
      context.setCurrentSampler(sampler);
      context.setPreviousResult(response);
      mod.process();
      Arguments args = sampler.getArguments();
      assertEquals(
          "jfdkjdkfjddkfdfjkdjfdf",
          ((Argument) args.getArguments().get(0).getObjectValue()).getValue());
    }

    public void testGrabSessionId4() throws Exception {
      String html = "href='index.html;%24sid%24KQNq3AAADQZoEQAxlkX8uQV5bjqVBPbT'";
      response = new SampleResult();
      response.setResponseData(html.getBytes());
      URLRewritingModifier mod = new URLRewritingModifier();
      mod.setArgumentName("%24sid%24");
      mod.setPathExtension(true);
      mod.setPathExtensionNoEquals(true);
      HTTPSampler sampler = createSampler();
      context.setCurrentSampler(sampler);
      context.setPreviousResult(response);
      mod.process();
      Arguments args = sampler.getArguments();
      assertEquals("index.html;%24sid%24KQNq3AAADQZoEQAxlkX8uQV5bjqVBPbT", sampler.getPath());
    }
  }
}
Exemple #3
0
/**
 * The <code>JavaConfig</code> class contains the configuration data necessary for the Java
 * protocol. This data is used to configure a {@link
 * org.apache.jmeter.protocol.java.sampler.JavaSamplerClient} instance to perform performance test
 * samples.
 *
 * @author Brad Kiewel
 * @author <a href="mailto:[email protected]">Jeremy Arnold</a>
 * @version $Revision: 1.1 $
 */
public class JavaConfig extends ConfigTestElement implements Serializable {
  /** Logging */
  private static transient Logger log =
      Hierarchy.getDefaultHierarchy().getLoggerFor("jmeter.protocol.java");

  /** Constructor for the JavaConfig object */
  public JavaConfig() {
    setArguments(new Arguments());
  }

  /**
   * Sets the class name attribute of the JavaConfig object. This is the class name of the {@link
   * org.apache.jmeter.protocol.java.sampler.JavaSamplerClient} implementation which will be used to
   * execute the test.
   *
   * @param classname the new classname value
   */
  public void setClassname(String classname) {
    setProperty(JavaSampler.CLASSNAME, classname);
  }

  /**
   * Gets the class name attribute of the JavaConfig object. This is the class name of the {@link
   * org.apache.jmeter.protocol.java.sampler.JavaSamplerClient} implementation which will be used to
   * execute the test.
   *
   * @return the classname value
   */
  public String getClassname() {
    return getPropertyAsString(JavaSampler.CLASSNAME);
  }

  /**
   * Adds an argument to the list of arguments for this JavaConfig object. The {@link
   * org.apache.jmeter.protocol.java.sampler.JavaSamplerClient} implementation can access these
   * arguments through the {@link org.apache.jmeter.protocol.java.sampler.JavaSamplerContext}.
   *
   * @param name the name of the argument to be added
   * @param value the value of the argument to be added
   */
  public void addArgument(String name, String value) {
    Arguments args = this.getArguments();
    args.addArgument(name, value);
  }

  /** Removes all of the arguments associated with this JavaConfig object. */
  public void removeArguments() {
    setProperty(new TestElementProperty(JavaSampler.ARGUMENTS, new Arguments()));
  }

  /**
   * Set all of the arguments for this JavaConfig object. This will replace any previously added
   * arguments. The {@link org.apache.jmeter.protocol.java.sampler.JavaSamplerClient} implementation
   * can access these arguments through the {@link
   * org.apache.jmeter.protocol.java.sampler.JavaSamplerContext}.
   *
   * @param args the new arguments
   */
  public void setArguments(Arguments args) {
    setProperty(new TestElementProperty(JavaSampler.ARGUMENTS, args));
  }

  /**
   * Gets the arguments for this JavaConfig object. The {@link
   * org.apache.jmeter.protocol.java.sampler.JavaSamplerClient} implementation can access these
   * arguments through the {@link org.apache.jmeter.protocol.java.sampler.JavaSamplerContext}.
   *
   * @return the arguments
   */
  public Arguments getArguments() {
    return (Arguments) getProperty(JavaSampler.ARGUMENTS).getObjectValue();
  }
}