@Test
  public void testProcess_list() {
    System.out.println("process list");
    JMeterContext context = JMeterContextService.getContext();
    SampleResult res = new SampleResult();
    res.setResponseData("{\"myval\": [{\"test\":1},{\"test\":2},{\"test\":null}]}".getBytes());
    context.setPreviousResult(res);

    JSONPathExtractor instance = new JSONPathExtractor();
    instance.setDefaultValue("DEFAULT");
    instance.setVar("test");
    instance.setJsonPath("$.myval[*].test");
    instance.process();
    JMeterVariables vars = context.getVariables();
    assertEquals("[1,2,null]", vars.get("test"));
    assertEquals("1", vars.get("test_1"));
    assertEquals("2", vars.get("test_2"));
    assertEquals("null", vars.get("test_3"));

    // test for cleaning prev vars
    res.setResponseData("{\"myval\": [{\"test\":1},{\"test\":2}]}".getBytes());
    instance.process();
    assertEquals("[1,2]", vars.get("test"));
    assertEquals("1", vars.get("test_1"));
    assertEquals("2", vars.get("test_2"));
    assertEquals(null, vars.get("test_3"));
  }
  /** Returns last line of output from the command */
  public SampleResult sample(Entry e) {
    SampleResult res = new SampleResult();
    res.setSampleLabel(
        getName() + ":(" + getUsername() + "@" + getHostname() + ":" + getPort() + ")");

    // Set up sampler return types
    res.setSamplerData(action + " " + source);

    res.setDataType(SampleResult.TEXT);
    res.setContentType("text/plain");

    String response;
    if (getSession() == null) {
      connect();
    }

    try {
      if (getSession() == null) {
        log.error(
            "Failed to connect to server with credentials "
                + getUsername()
                + "@"
                + getHostname()
                + ":"
                + getPort()
                + " pw="
                + getPassword());
        throw new NullPointerException("Failed to connect to server: " + getFailureReason());
      }

      response = doFileTransfer(getSession(), source, destination, res);
      res.setResponseData(response.getBytes());

      res.setSuccessful(true);

      res.setResponseMessageOK();
    } catch (JSchException e1) {
      res.setSuccessful(false);
      res.setResponseCode("JSchException");
      res.setResponseMessage(e1.getMessage());
    } catch (SftpException e1) {
      res.setSuccessful(false);
      res.setResponseCode("SftpException");
      res.setResponseMessage(e1.getMessage());
    } catch (IOException e1) {
      res.setSuccessful(false);
      res.setResponseCode("IOException");
      res.setResponseMessage(e1.getMessage());
    } catch (NullPointerException e1) {
      res.setSuccessful(false);
      res.setResponseCode("Connection Failed");
      res.setResponseMessage(e1.getMessage());
    } finally {
      // Try a disconnect/sesson = null here instead of in finalize.
      disconnect();
      setSession(null);
    }
    return res;
  }
Exemple #3
0
  /**
   * Perform a single sample.<br>
   * In this case, this method will simply sleep for some amount of time.
   *
   * <p>This method returns a <code>SampleResult</code> object.
   *
   * <pre>
   *
   *  The following fields are always set:
   *  - responseCode (default &quot;&quot;)
   *  - responseMessage (default &quot;&quot;)
   *  - label (set from LABEL_NAME parameter if it exists, else element name)
   *  - success (default true)
   *
   * </pre>
   *
   * The following fields are set from the user-defined parameters, if supplied:
   *
   * <pre>
   * -samplerData - responseData
   * </pre>
   *
   * @see org.apache.jmeter.samplers.SampleResult#sampleStart()
   * @see org.apache.jmeter.samplers.SampleResult#sampleEnd()
   * @see org.apache.jmeter.samplers.SampleResult#setSuccessful(boolean)
   * @see org.apache.jmeter.samplers.SampleResult#setSampleLabel(String)
   * @see org.apache.jmeter.samplers.SampleResult#setResponseCode(String)
   * @see org.apache.jmeter.samplers.SampleResult#setResponseMessage(String)
   * @see org.apache.jmeter.samplers.SampleResult#setResponseData(byte [])
   * @see org.apache.jmeter.samplers.SampleResult#setDataType(String)
   * @param context the context to run with. This provides access to initialization parameters.
   * @return a SampleResult giving the results of this sample.
   */
  @Override
  public SampleResult runTest(JavaSamplerContext context) {
    setupValues(context);

    SampleResult results = new SampleResult();

    results.setResponseCode(responseCode);
    results.setResponseMessage(responseMessage);
    results.setSampleLabel(label);

    if (samplerData != null && samplerData.length() > 0) {
      results.setSamplerData(samplerData);
    }

    if (resultData != null && resultData.length() > 0) {
      results.setResponseData(resultData, null);
      results.setDataType(SampleResult.TEXT);
    }

    // Record sample start time.
    results.sampleStart();

    long sleep = sleepTime;
    if (sleepTime > 0 && sleepMask > 0) { // / Only do the calculation if
      // it is needed
      long start = System.currentTimeMillis();
      // Generate a random-ish offset value using the current time.
      sleep = sleepTime + (start % sleepMask);
    }

    try {
      // Execute the sample. In this case sleep for the
      // specified time, if any
      if (sleep > 0) {
        TimeUnit.MILLISECONDS.sleep(sleep);
      }
      results.setSuccessful(success);
    } catch (InterruptedException e) {
      LOG.warn("JavaTest: interrupted.");
      results.setSuccessful(true);
    } catch (Exception e) {
      LOG.error("JavaTest: error during sample", e);
      results.setSuccessful(false);
    } finally {
      // Record end time and populate the results.
      results.sampleEnd();
    }

    if (LOG.isDebugEnabled()) {
      LOG.debug(whoAmI() + "\trunTest()" + "\tTime:\t" + results.getTime());
      listParameters(context);
    }

    return results;
  }
 /**
  * 結果の作成補助関数
  *
  * @param result resultオブジェクト
  * @param reason 文字列の結果データ
  * @param success 成功したかどうかフラグ
  */
 protected void setupResult(SampleResult result, String reason, boolean success) {
   // サンプル動作完了
   result.sampleEnd();
   StringBuilder str = new StringBuilder();
   str.append(getName());
   str.append("[");
   str.append(Thread.currentThread().getName());
   str.append("]");
   result.setSampleLabel(str.toString());
   result.setSuccessful(success);
   result.setResponseData(reason.getBytes());
   result.setDataType(SampleResult.TEXT);
 }
 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());
 }
 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 run() {
   ResponseAssertion assertion = new ResponseAssertion(RESPONSE_DATA, CONTAINS, TEST_PATTERN);
   SampleResult response = new SampleResult();
   response.setResponseData(TEST_STRING.getBytes());
   for (int i = 0; i < 100; i++) {
     AssertionResult result;
     result = assertion.evaluateResponse(response);
     if (result.isFailure() || result.isError()) {
       failed++;
     }
   }
   synchronized (Test.this) {
     threadsRunning--;
     Test.this.notify();
   }
 }
  @Test
  public void testReported1_3() {
    System.out.println("process reported");
    JMeterContext context = JMeterContextService.getContext();
    SampleResult res = new SampleResult();
    res.setResponseData(json2.getBytes());
    context.setPreviousResult(res);

    JSONPathExtractor instance = new JSONPathExtractor();
    instance.setVar("GroupID");
    instance.setJsonPath("$.data.groups[?(@.name==Avtovaz)].id");
    instance.setDefaultValue("NOTFOUND");
    instance.process();
    JMeterVariables vars = context.getVariables();
    assertEquals("NOTFOUND", vars.get("GroupID"));
  }
  @Test
  public void testReported1_1() {
    System.out.println("process reported");
    JMeterContext context = JMeterContextService.getContext();
    SampleResult res = new SampleResult();
    res.setResponseData(json2.getBytes());
    context.setPreviousResult(res);

    JSONPathExtractor instance = new JSONPathExtractor();
    instance.setVar("GroupID");
    instance.setJsonPath("$.data.groups[*].id");
    instance.setDefaultValue("NOTFOUND");
    instance.process();
    JMeterVariables vars = context.getVariables();
    assertNotEquals("NOTFOUND", vars.get("GroupID"));
    assertEquals("e02991f4-a95d-43dd-8eb0-fbc44349e238", vars.get("GroupID_1"));
  }
  @Ignore
  @Test // FIXME: we need to solve this one day
  public void testReported2() {
    System.out.println("process reported");
    JMeterContext context = JMeterContextService.getContext();
    SampleResult res = new SampleResult();
    res.setResponseData(json3.getBytes());
    context.setPreviousResult(res);

    JSONPathExtractor instance = new JSONPathExtractor();
    instance.setVar("var");
    instance.setJsonPath("$.data[?(@.attr.value>0)][0].attr");
    instance.setDefaultValue("NOTFOUND");
    instance.process();
    JMeterVariables vars = context.getVariables();
    assertNotEquals("NOTFOUND", vars.get("var"));
    assertEquals("{value=1}", vars.get("var"));
  }
  @Test
  public void testProcess() {
    System.out.println("process");
    JMeterContext context = JMeterContextService.getContext();
    SampleResult res = new SampleResult();
    res.setResponseData(json.getBytes());
    context.setPreviousResult(res);

    JSONPathExtractor instance = new JSONPathExtractor();
    instance.setDefaultValue("DEFAULT");
    instance.setVar("test");
    instance.setJsonPath("$.store.book[*].author");
    instance.process();
    JMeterVariables vars = context.getVariables();
    assertEquals(
        "[\"Nigel Rees\",\"Evelyn Waugh\",\"Herman Melville\",\"J. R. R. Tolkien\"]",
        vars.get("test"));
  }
 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 SampleResult sample(Entry arg0) {
    SampleResult result = new SampleResult();
    result.setDataType(SampleResult.TEXT);
    result.setContentType("text/plain");
    result.setSampleLabel(getName());
    result.setSamplerData(query);

    // Assume we will be successful
    result.setSuccessful(true);
    result.setResponseMessageOK();
    result.setResponseCodeOK();

    Statement statement = configure(getStatement());

    result.sampleStart(); // sampleStart()  e sampleEnd() vengono usati da JMeter per calcolare i
    // response times
    try {
      /**
       * ORIGINALE - SINCRONO ResultSet data = getSession(keySpace).execute(statement);
       * result.setResponseData(getStringFrom(data).getBytes());
       * result.setResponseMessage(data.toString());
       */

      /** Modifica 22/02/2016 - ASINCRONO * */
      @SuppressWarnings("unused")
      ResultSetFuture datafuture = getSession(keySpace).executeAsync(statement);

    } catch (Exception ex) {
      log.error(String.format("Error executing CQL statement [%s]", getQuery()), ex);
      result.setResponseMessage(ex.toString());
      result.setResponseData(ex.getMessage().getBytes());
      result.setSuccessful(false);
    }

    result.sampleEnd();

    return result;
  }
  @Override
  public SampleResult sample(Entry entry) {
    ServiceSocket socket = null;
    SampleResult sampleResult = new SampleResult();
    sampleResult.setSampleLabel(getName());
    sampleResult.setDataEncoding(getContentEncoding());

    StringBuilder errorList = new StringBuilder();
    errorList.append("\n\n[Problems]\n");

    boolean isOK = false;

    String payloadMessage = getRequestPayload();
    sampleResult.setSamplerData(payloadMessage);
    sampleResult.sampleStart();

    try {
      socket = getConnectionSocket();
      if (socket == null) {
        sampleResult.setResponseCode("500");
        sampleResult.setSuccessful(false);
        sampleResult.sampleEnd();
        sampleResult.setResponseMessage(errorList.toString());
        errorList.append(" - Connection couldn't be opened").append("\n");
        return sampleResult;
      }

      if (!payloadMessage.isEmpty()) {
        socket.sendMessage(payloadMessage);
      }

      int responseTimeout = Integer.parseInt(getResponseTimeout());
      socket.awaitClose(responseTimeout, TimeUnit.MILLISECONDS);

      if (socket.getResponseMessage() == null || socket.getResponseMessage().isEmpty()) {
        sampleResult.setResponseCode("204");
      }

      if (socket.getError() != 0) {
        isOK = false;
        sampleResult.setResponseCode(socket.getError().toString());
      } else {
        sampleResult.setResponseCodeOK();
        isOK = true;
      }

      sampleResult.setResponseData(socket.getResponseMessage(), getContentEncoding());

    } catch (URISyntaxException e) {
      errorList
          .append(" - Invalid URI syntax: ")
          .append(e.getMessage())
          .append("\n")
          .append(StringUtils.join(e.getStackTrace(), "\n"))
          .append("\n");
    } catch (IOException e) {
      errorList
          .append(" - IO Exception: ")
          .append(e.getMessage())
          .append("\n")
          .append(StringUtils.join(e.getStackTrace(), "\n"))
          .append("\n");
    } catch (NumberFormatException e) {
      errorList
          .append(" - Cannot parse number: ")
          .append(e.getMessage())
          .append("\n")
          .append(StringUtils.join(e.getStackTrace(), "\n"))
          .append("\n");
    } catch (InterruptedException e) {
      errorList
          .append(" - Execution interrupted: ")
          .append(e.getMessage())
          .append("\n")
          .append(StringUtils.join(e.getStackTrace(), "\n"))
          .append("\n");
    } catch (Exception e) {
      errorList
          .append(" - Unexpected error: ")
          .append(e.getMessage())
          .append("\n")
          .append(StringUtils.join(e.getStackTrace(), "\n"))
          .append("\n");
    }

    sampleResult.sampleEnd();
    sampleResult.setSuccessful(isOK);

    String logMessage = (socket != null) ? socket.getLogMessage() : "";
    sampleResult.setResponseMessage(logMessage + errorList);
    return sampleResult;
  }
  public SampleResult runTest(JavaSamplerContext runTestContext) {
    String indexFileSystemPath = runTestContext.getParameter("indexfilesystem.path");

    String timeStamp =
        new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime());
    resultObj.put("Date and Execution Time", timeStamp);

    resultObj.put("Execution Plan", "Sequential Performance of Indexes FS");
    try {
      resultObj.put("Host", InetAddress.getLocalHost().getHostAddress());
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }

    SampleResult result = new SampleResult();

    try {
      result.sampleStart();
      preallocateTestFile(FILE_NAME);

      for (final PerfTestCase testCase : testCases) {
        JSONArray readDuration = new JSONArray();
        JSONArray bytesRead = new JSONArray();
        JSONArray bytesWrite = new JSONArray();
        for (int i = 0; i < 5; i++) {
          System.gc();
          long writeDurationMs = testCase.test(PerfTestCase.Type.WRITE, FILE_NAME);
          System.gc();
          long readDurationMs = testCase.test(PerfTestCase.Type.READ, FILE_NAME);
          long bytesReadPerSec = (FILE_SIZE * 1000L) / readDurationMs;
          long bytesWrittenPerSec = (FILE_SIZE * 1000L) / writeDurationMs;
          readDuration.add(readDurationMs);
          bytesRead.add(bytesReadPerSec);
          bytesWrite.add(bytesWrittenPerSec);

          out.format(
              "%s\twrite=%,d\tread=%,d bytes/sec\n",
              testCase.getName(), bytesWrittenPerSec, bytesReadPerSec);

          String output =
              out.format(
                      "%s\twrite=%,d\tread=%,d bytes/sec\n",
                      testCase.getName(), bytesWrittenPerSec, bytesReadPerSec)
                  .toString();
          result.setSamplerData(testCase.getName() + "-- IO RESULTS --- " + output);
          // resultIo.setSamplerData(testCase.getName() + "-- Writen Bytes per second:" +
          // bytesWrittenPerSec + "-- Read Bytes per second:" + bytesReadPerSec);
          result.addSubResult(result);
        }

        resultObj.put(testCase.getName(), readDuration);
        resultObj.put(testCase.getName(), bytesRead);
        resultObj.put(testCase.getName(), bytesWrite);
      }

      deleteFile(indexFileSystemPath + "/" + FILE_NAME);

      try {

        FileWriter file = new FileWriter(resultsDirectory + "/" + OUTPUT_JSON_FILE_NAME);
        file.write(resultObj.toJSONString());
        file.flush();
        file.close();

      } catch (IOException e) {
        e.printStackTrace();
      }

      result.sampleEnd();
      result.setSuccessful(true);
      logger.info("Successfully Tested Index Disk IO  at path: " + indexFileSystemPath);
      result.setResponseMessage("Successfully Tested IO at  Indexes Disk");
      result.setResponseCodeOK();
    } catch (Exception e) {
      result.sampleEnd();
      result.setSuccessful(false);
      result.setResponseMessage("Failed to TestIO: " + e);
      StringWriter stringWriter = new StringWriter();
      e.printStackTrace(new PrintWriter(stringWriter));
      result.setResponseData(stringWriter.toString().getBytes());
      result.setDataType(SampleResult.TEXT);
      result.setResponseCode("500");
    }
    return result;
  }
  /** {@inheritDoc} */
  @Override
  public SampleResult sample(Entry entry) {
    SampleResult result = new SampleResult();
    result.setSampleLabel(getName());
    result.setSuccessful(false);
    result.setResponseCode("500");

    QueueingConsumer consumer;
    String consumerTag;

    trace("AMQPConsumer.sample()");

    try {
      initChannel();

      consumer = new QueueingConsumer(channel);
      channel.basicQos(1); // TODO: make prefetchCount configurable?
      consumerTag = channel.basicConsume(getQueue(), autoAck(), consumer);
    } catch (IOException ex) {
      log.error("Failed to initialize channel", ex);
      return result;
    }

    result.setSampleLabel(getTitle());
    /*
     * Perform the sampling
     */
    result.sampleStart(); // Start timing
    try {
      QueueingConsumer.Delivery delivery = consumer.nextDelivery(getReceiveTimeoutAsInt());

      if (delivery == null) {
        log.warn("nextDelivery timed out");
        return result;
      }

      /*
       * Set up the sample result details
       */
      result.setSamplerData(new String(delivery.getBody()));

      result.setResponseData("OK", null);
      result.setDataType(SampleResult.TEXT);

      result.setResponseCodeOK();
      result.setResponseMessage("OK");
      result.setSuccessful(true);

      if (!autoAck()) channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);

    } catch (ShutdownSignalException e) {
      log.warn("AMQP consumer failed to consume", e);
      result.setResponseCode("400");
      result.setResponseMessage(e.toString());
      interrupt();
    } catch (ConsumerCancelledException e) {
      log.warn("AMQP consumer failed to consume", e);
      result.setResponseCode("300");
      result.setResponseMessage(e.toString());
      interrupt();
    } catch (InterruptedException e) {
      log.info("interuppted while attempting to consume");
      result.setResponseCode("200");
      result.setResponseMessage(e.toString());
    } catch (IOException e) {
      log.warn("AMQP consumer failed to consume", e);
      result.setResponseCode("100");
      result.setResponseMessage(e.toString());
    } finally {
      try {
        channel.basicCancel(consumerTag);
      } catch (IOException e) {
        log.error("Couldn't safely cancel the sample's consumer", e);
      }
    }

    result.sampleEnd(); // End timimg
    trace("AMQPConsumer.sample ended");

    return result;
  }