@Override
 public final SampleResult runTest(JavaSamplerContext context) {
   if (setupError != null) {
     SampleResult errorResult = new SampleResult();
     errorResult.setSuccessful(false);
     errorResult.setResponseMessage(setupError);
     errorResult.setStopTest(true);
     return errorResult;
   } else {
     try {
       SampleResult result = doRunTest(context);
       if (result != null && !result.isSuccessful() && stopOnError) {
         result.setStopTest(true);
       }
       return result;
     } catch (Throwable t) {
       SampleResult errorResult = new SampleResult();
       errorResult.setSuccessful(false);
       errorResult.setStopTest(stopOnError);
       String message =
           "Unexpected exception during test execution: "
               + t
               + " (sampler "
               + getClass().getSimpleName()
               + ")";
       errorResult.setResponseMessage(message);
       logError(message, t);
       return errorResult;
     }
   }
 }
  /** 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;
  }
  // @Override
  public SampleResult runTest(JavaSamplerContext arg0) {
    JMeterVariables vars = JMeterContextService.getContext().getVariables();
    vars.put("demo", "demoVariableContent");

    setupValues(arg0);
    SampleResult sampleResult = new SampleResult();
    sampleResult.sampleStart();

    System.out.println("/level/du/parents: " + level + ", " + du + ", " + parents);
    // JUnitCore junit = new JUnitCore();
    // Result result = junit.run(AuthenticationTest.class);

    //		if (result.getFailureCount() > 0) {
    //			sampleResult.setSuccessful(false);
    //			sampleResult.setResponseCode("301");
    //			sampleResult.setResponseMessage("FailureCount: "
    //					+ result.getFailureCount());
    //		} else {
    sampleResult.setSuccessful(true);
    sampleResult.setResponseCodeOK();
    sampleResult.setResponseMessageOK();
    //		}
    sampleResult.sampleEnd();
    return sampleResult;
  }
 public SampleResult runTest(JavaSamplerContext arg0) {
   log.info("<<<发送地址:" + conf.getBaseUri() + conf.getApiUri());
   log.info("<<<发送数据:" + sb.toString());
   try {
     HttpSend.doPost(conf, headMsg, sb.toString(), log);
   } catch (Exception e) {
     log.info("ERROR...", e);
   }
   results.setSuccessful(true);
   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 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;
  }
Exemple #8
0
 @Override
 public SampleResult runTest(JavaSamplerContext arg0) {
   SampleResult results = new SampleResult();
   results.setSamplerData(String.valueOf(da));
   results.setSamplerData(String.valueOf(db));
   results.sampleStart();
   //		Random rand = new Random();
   for (int i = 0; i < 1; i++) {
     //			System.out.println("da=" + da + ",db=" + db);
     double d = compute();
     //			System.out.println("result="+ d);
     results.setSamplerData(String.valueOf(d));
     //			compute(rand.nextDouble(), rand.nextDouble());
   }
   results.sampleEnd();
   results.setSuccessful(true);
   return results;
 }
  @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;
  }
 protected static void assertTrue(boolean value, String message, SampleResult result) {
   if (!value) {
     result.setSuccessful(false);
     result.setResponseMessage(message);
   }
 }
  /** {@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;
  }