Java Code Examples for org.apache.jmeter.samplers.SampleResult#sampleEnd()

The following examples show how to use org.apache.jmeter.samplers.SampleResult#sampleEnd() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ThreadsStateOverTimeGuiTest.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
/**
 * Test of add method, of class ThreadsStateOverTimeGui.
 */
@Test
public void testAdd()
{
   System.out.println("add");
   SampleResult res = new SampleResult();
   res.sampleStart();
   res.setAllThreads(1);
   res.setThreadName("test 1-2");
   res.sampleEnd();
   instance.add(res);
   
   try
   {
      Thread.sleep(2000);
   }
   catch (InterruptedException ex)
   {
      Logger.getLogger(ThreadsStateOverTimeGuiTest.class.getName()).log(Level.SEVERE, null, ex);
   }
   
   SampleResult res2 = new SampleResult(res);
   res2.setAllThreads(1);
   res2.setThreadName("test 1-2");
   instance.add(res);
}
 
Example 2
Source File: WeEventProducer.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Override
public SampleResult runTest(JavaSamplerContext context) {
    SampleResult result = new SampleResult();
    result.setSampleLabel("producer");
    try {
        result.sampleStart();
        SendResult sendResult = this.weEventClient.publish(this.weEvent);
        result.sampleEnd();
        result.setSuccessful(sendResult.getStatus() == SendResult.SendResultStatus.SUCCESS && sendResult.getEventId().length() > 0);
        result.setResponseMessage(sendResult.getEventId());
        result.setResponseHeaders(sendResult.getStatus().toString());
        result.setResponseData(sendResult.toString(), Charset.defaultCharset().name());
        getNewLogger().info("sendResult:{}", sendResult);
    } catch (Exception e) {
        getNewLogger().error("publish exception", e);
        result.sampleEnd();
        result.setSuccessful(false);
        result.setResponseMessage(e.getMessage());
    }
    return result;
}
 
Example 3
Source File: TransactionsPerSecondGuiTest.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
/**
 * Test of add method, of class TransactionsPerSecondGui.
 */
@Test
public void testAdd()
{
    System.out.println("add");

    SampleResult res = new SampleResult();
    res.setAllThreads(1);
    res.setThreadName("test 1-2");
    TransactionsPerSecondGui instance = new TransactionsPerSecondGui();
    instance.add(res);
    res.sampleStart();
    try
    {
        Thread.sleep(10);
    } catch (InterruptedException ex)
    {
    }
    res.sampleEnd();
    instance.add(res);
}
 
Example 4
Source File: FlowerSyncClient.java    From flower with Apache License 2.0 6 votes vote down vote up
@Override
public SampleResult runTest(JavaSamplerContext arg0) {
  SampleResult result = new SampleResult();
  result.sampleStart();
  try {
    long begin = System.currentTimeMillis();
    String ret = (String) flowRouter.syncCallService(message);
    long cost = (System.currentTimeMillis() - begin);
    logger.info("ret : {}, cost:[{}ms]", ret, cost);
    if (message.equals(ret)) {
      result.setSuccessful(true);
    }
  } catch (Exception e) {
    result.setSuccessful(false);
    logger.error("", e);

  } finally {
    result.sampleEnd();
  }
  return result;
}
 
Example 5
Source File: ResponseCodesPerSecondGuiTest.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
/**
 * Test of add method, of class ResponseCodesPerSecondGui.
 */
@Test
public void testAdd()
{
    System.out.println("add");
    SampleResult res = new SampleResult();
    res.setAllThreads(1);
    res.setThreadName("test 1-2");
    res.setResponseCode("200");
    ResponseCodesPerSecondGui instance = new ResponseCodesPerSecondGui();
    instance.add(res);
    res.sampleStart();
    try
    {
        Thread.sleep(10);
    } catch (InterruptedException ex)
    {
    }
    res.sampleEnd();
    instance.add(res);
}
 
Example 6
Source File: BlurSamplerClient.java    From incubator-retired-blur with Apache License 2.0 6 votes vote down vote up
@Override
public SampleResult runTest(JavaSamplerContext context) {
  SampleResult sampleResult = new SampleResult();
  BlurResults blurResults = null;
  try {
    BlurQuery blurQuery = getBlurQuery();
    sampleResult.sampleStart();
    blurResults = _client.query(_table, blurQuery);
    sampleResult.sampleEnd();
    int size = getBytes(blurResults);
    sampleResult.setBytes(size);
    sampleResult.setSuccessful(true);
    sampleResult.setResponseOK();
  } catch (Throwable t) {
    sampleResult.setResponseMessage("Exception " + t.getMessage());
    sampleResult.setSuccessful(false);
    LOG.error("Unknown error.", t);
  } finally {
    processResults(blurResults);
  }
  return sampleResult;
}
 
Example 7
Source File: LoadosophiaUploaderTest.java    From jmeter-bzm-plugins with Apache License 2.0 6 votes vote down vote up
@Test
public void testTestEndedWithNoStoreDir() throws IOException {
    System.out.println("testEnded");
    JMeterUtils.setProperty("loadosophia.address", "http://localhost/");
    LoadosophiaUploader instance = new LoadosophiaUploaderEmul();
    instance.setStoreDir("");
    instance.setTitle("UnitTest");
    instance.setColorFlag("gray");
    instance.setProject("DEFAULT");
    instance.setUploadToken("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
    instance.testStarted();

    SampleResult res = new SampleResult();
    res.sampleStart();
    res.sampleEnd();
    SampleEvent event = new SampleEvent(res, "test");
    instance.sampleOccurred(event);

    instance.testEnded();
}
 
Example 8
Source File: UDPSampler.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
private ByteArrayOutputStream readResponse(SampleResult res) throws IOException {
    ByteArrayOutputStream response = new ByteArrayOutputStream();
    int cnt;
    ByteBuffer recvBuf = getRecvBuf();
    recvBuf.clear();
    if ((cnt = channel.read(recvBuf)) != -1) {
        res.latencyEnd();
        //log.debug("Read " + recvBuf.toString());
        recvBuf.flip();
        byte[] bytes = new byte[cnt];
        recvBuf.get(bytes);
        response.write(bytes);
        recvBuf.clear();
    }
    res.latencyEnd();
    res.sampleEnd();
    res.setBytes(response.size());
    return response;
}
 
Example 9
Source File: SubSampler.java    From mqtt-jmeter with Apache License 2.0 6 votes vote down vote up
private SampleResult fillFailedResult(SampleResult result, String code, String message) {
	result.sampleStart();
	result.setResponseCode(code); // 5xx means various failures
	result.setSuccessful(false);
	result.setResponseMessage(message);
	if (clientId != null) {
		result.setResponseData(MessageFormat.format("Client [{0}]: {1}", clientId, message).getBytes());
	} else {
		result.setResponseData(message.getBytes());
	}
	result.sampleEnd();
	
	// avoid massive repeated "early stage" failures in a short period of time
	// which probably overloads JMeter CPU and distorts test metrics such as TPS, avg response time
	try {
		TimeUnit.MILLISECONDS.sleep(SUB_FAIL_PENALTY);
	} catch (InterruptedException e) {
		logger.log(Level.INFO, "Received exception when waiting for notification signal", e);
	}
	return result;
}
 
Example 10
Source File: JMeterTest.java    From learning-hadoop with Apache License 2.0 5 votes vote down vote up
public SampleResult runTest(JavaSamplerContext context) {
		SampleResult sampleResult = new SampleResult();
		sampleResult.sampleStart();
		String key = String.valueOf(String.valueOf(new Random().nextInt(keyNumLength)).hashCode());
		
		try {
			if (methedType.equals("put")) {
				put = new Put(Bytes.toBytes(key));
				put.setWriteToWAL(writeToWAL);
				for (int j = 0; j < cfs.length; j++) {
					for (int n = 0; n < qualifiers.length; n++) {
					put.add(Bytes.toBytes(cfs[j]),
							Bytes.toBytes(qualifiers[n]),
							Bytes.toBytes(values));
					table.put(put);
					}
				}
			} else if (methedType.equals("get")) {
				get = new Get((key ).getBytes());
				table.get(get);
//				Result rs = table.get(get);
			}
			sampleResult.setSuccessful(true);
		} catch (Throwable e) {
			sampleResult.setSuccessful(false);
		} finally {
			sampleResult.sampleEnd();
		}
		// // 返回是否处理成功
		return sampleResult;
	}
 
Example 11
Source File: AbstractDynamicThreadGroupModel.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
protected void saveLogRecord(String marker, String threadName, String arrivalID) {
    SampleResult res = new SampleResult();
    res.sampleStart();
    res.setSampleLabel(arrivalID);
    res.setResponseMessage(marker);
    res.setThreadName(threadName);
    res.sampleEnd();
    SampleEvent evt = new SampleEvent(res, getName());
    logFile.sampleOccurred(evt);
}
 
Example 12
Source File: UDPSampler.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
private byte[] noResponseFinish(SampleResult res) throws IOException {
    res.latencyEnd();
    res.sampleEnd();

    if (isCloseChannel()) {
        channel.close();
    }

    return new byte[0];
}
 
Example 13
Source File: BaseBotSampler.java    From BotServiceStressToolkit with MIT License 5 votes vote down vote up
protected SampleResult setErrorResponse(String message, Exception e, SampleResult res) {
	log.error(message, e);
	res.setResponseData(e.getMessage(), "UTF-8");
	res.sampleEnd();
	res.setSuccessful(false);

	return res;
}
 
Example 14
Source File: LicenseActivateCheckDeactivate.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SampleResult runTest(JavaSamplerContext context) {
	results = new SampleResult();
	results.sampleStart();

	licenseID = context.getParameter("LicenseID");
	hardwareCode = context.getParameter("HardwareCode");
	installCode = context.getParameter("InstallCode");
	waitTimeMillis = Integer.valueOf(context.getParameter("WaitSeconds")) * 1000;
	intervalTimeMillis = Integer.valueOf(context
			.getParameter("IntervalSeconds")) * 1000;
	strResult = licenseID + ":\n";
	startTime = System.currentTimeMillis();

	// 检查许可证状态,应为未激活,然后激活
	check(NextAction.ACTIVATE, "不通过");

	// 等待两次测试之间的间隔时间
	wait(intervalTimeMillis);

	pastTime = System.currentTimeMillis() - startTime - waitTimeMillis
			* waitCount - intervalTimeMillis;

	results.setResponseMessage(strResult + "\n实际耗时(毫秒):" + pastTime);
	results.sampleEnd();
	return results;
}
 
Example 15
Source File: DisConnectSampler.java    From mqtt-jmeter with Apache License 2.0 4 votes vote down vote up
@Override
public SampleResult sample(Entry entry) {
	SampleResult result = new SampleResult();
	result.setSampleLabel(getName());
	
	JMeterVariables vars = JMeterContextService.getContext().getVariables();
	connection = (MQTTConnection) vars.getObject("conn");
	String clientId = (String) vars.getObject("clientId");
	if (connection == null) {
		result.sampleStart();
		result.setSuccessful(false);
		result.setResponseMessage("Connection not found.");
		result.setResponseData("Failed. Connection not found.".getBytes());
		result.setResponseCode("500");
		result.sampleEnd(); // avoid endtime=0 exposed in trace log
		return result;
	}
	
	try {
		result.sampleStart();
		
		if (connection != null) {
			logger.info(MessageFormat.format("Disconnect connection {0}.", connection));
			connection.disconnect();
			vars.remove("conn"); // clean up thread local var as well
			topicSubscribed.remove(clientId);
		}
		
		result.sampleEnd();
		
		result.setSuccessful(true);
		result.setResponseData("Successful.".getBytes());
		result.setResponseMessage(MessageFormat.format("Connection {0} disconnected.", connection));
		result.setResponseCodeOK();
	} catch (Exception e) {
		logger.log(Level.SEVERE, "Failed to disconnect Connection" + connection, e);
		if (result.getEndTime() == 0) result.sampleEnd(); //avoid re-enter sampleEnd()
		result.setSuccessful(false);
		result.setResponseMessage(MessageFormat.format("Failed to disconnect Connection {0}.", connection));
		result.setResponseData(MessageFormat.format("Client [{0}] failed. Couldn't disconnect connection.", (clientId == null ? "null" : clientId)).getBytes());
		result.setResponseCode("501");
	}
	return result;
}
 
Example 16
Source File: CassandraSampler.java    From jmeter-cassandra with Apache License 2.0 4 votes vote down vote up
@Override
    public SampleResult sample(Entry e) {
        log.debug("sampling CQL");

        SampleResult res = new SampleResult();
        res.setSampleLabel(getName());
        res.setSamplerData(toString());
        res.setDataType(SampleResult.TEXT);
        res.setContentType("text/plain"); // $NON-NLS-1$
        res.setDataEncoding(ENCODING);

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


        res.sampleStart();
        Session conn = null;

        try {
            if(JOrphanUtils.isBlank(getSessionName())) {
                throw new IllegalArgumentException("Variable Name must not be null in "+getName());
            }

            try {
                conn = CassandraConnection.getSession(getSessionName());
            } finally {
                res.latencyEnd(); // use latency to measure connection time
            }
            res.setResponseHeaders(conn.toString());
            res.setResponseData(execute(conn));
        }  catch (Exception ex) {
            res.setResponseMessage(ex.toString());
            res.setResponseCode("000");
            res.setResponseData(ex.getMessage().getBytes());
            res.setSuccessful(false);
        }
// Doesn't apply
//        finally {
//            close(conn);
//        }

        // TODO: process warnings? Set Code and Message to success?
        res.sampleEnd();
        return res;
    }
 
Example 17
Source File: HonoSender.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Publishes a message to Hono.
 *
 * @param sampleResult The result object representing the outcome of the sample.
 * @param deviceId The identifier if the device to send a message for.
 * @param waitForDeliveryResult A flag indicating whether to wait for the result of the send operation.
 */
public void send(final SampleResult sampleResult, final String deviceId, final boolean waitForDeliveryResult) {

    final String endpoint = sampler.getEndpoint();
    final String tenant = sampler.getTenant();

    final Future<DownstreamSender> senderFuture = getSender(endpoint, tenant);
    final CompletableFuture<SampleResult> tracker = new CompletableFuture<>();
    final Promise<ProtonDelivery> deliveryTracker = Promise.promise();
    deliveryTracker.future()
    .onComplete(s -> {
        if (s.succeeded()) {
            sampleResult.setResponseMessage(MessageFormat.format("{0}/{1}/{2}", endpoint, tenant, deviceId));
            sampleResult.setSentBytes(payload.length);
            sampleResult.setSampleCount(1);
            tracker.complete(sampleResult);
        } else {
            tracker.completeExceptionally(s.cause());
        }
    });

    // start sample
    sampleResult.sampleStart();
    senderFuture.map(sender -> {

        final Message msg = ProtonHelper.message();
        msg.setAddress(sender.getEndpoint() + "/" + tenant);
        MessageHelper.setPayload(msg, sampler.getContentType(), Buffer.buffer(sampler.getData()));
        MessageHelper.addDeviceId(msg, deviceId);
        if (sampler.isSetSenderTime()) {
            MessageHelper.addProperty(msg, TIME_STAMP_VARIABLE, System.currentTimeMillis());
        }

        LOGGER.trace("sending message for device [{}]; credit: {}", deviceId, sender.getCredit());

        final Handler<Void> sendHandler = s -> {
            if (waitForDeliveryResult) {
                sender.sendAndWaitForOutcome(msg).onComplete(deliveryTracker);
            } else {
                sender.send(msg).onComplete(ar -> {
                    if (ar.succeeded()) {
                        LOGGER.debug("{}: got delivery result for message sent for device [{}]: remoteState={}, localState={}",
                                sampler.getThreadName(), deviceId, ar.result().getRemoteState(),
                                ar.result().getLocalState());
                    } else {
                        LOGGER.warn("{}: error getting delivery result for message sent for device [{}]", sampler.getThreadName(), deviceId, ar.cause());
                    }
                });
                deliveryTracker.complete();
            }
        };

        ctx.runOnContext(send -> {
            if (sender.getCredit() > 0) {
                sendHandler.handle(null);
            } else {
                sender.sendQueueDrainHandler(sendHandler);
            }
        });

        return null;

    }).otherwise(t -> {
        tracker.completeExceptionally(t);
        return null;
    });

    try {
        tracker.get(sampler.getSendTimeoutOrDefaultAsInt(), TimeUnit.MILLISECONDS);
        LOGGER.debug("{}: sent message for device [{}]", sampler.getThreadName(), deviceId);
    } catch (InterruptedException | CancellationException | ExecutionException | TimeoutException e) {
        sampleResult.setSuccessful(false);
        if (e.getCause() instanceof ServiceInvocationException) {
            final ServiceInvocationException sie = (ServiceInvocationException) e.getCause();
            sampleResult.setResponseMessage(sie.getMessage());
            sampleResult.setResponseCode(String.valueOf(sie.getErrorCode()));
        } else {
            String uncompletedFutureHint = "";
            if (e instanceof TimeoutException) {
                uncompletedFutureHint = !senderFuture.isComplete() ? " - timeout waiting for sender link"
                        : !deliveryTracker.future().isComplete() ? " - timeout waiting for message delivery" : "";
            }
            sampleResult.setResponseMessage((e.getCause() != null ? e.getCause().getMessage() : e.getClass().getSimpleName()) + uncompletedFutureHint);
            sampleResult.setResponseCode(String.valueOf(HttpURLConnection.HTTP_INTERNAL_ERROR));
        }
        LOGGER.debug("{}: error sending message for device [{}]: {}", sampler.getThreadName(), deviceId, sampleResult.getResponseMessage());
        if (e instanceof InterruptedException) {
            Thread.currentThread().interrupt();
        }
    }
    sampleResult.sampleEnd();
}
 
Example 18
Source File: LicenseCheck.java    From translationstudio8 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public SampleResult runTest(JavaSamplerContext context) {
	SampleResult results = new SampleResult();
	results.sampleStart();

	String licenseID = context.getParameter("LicenseID");
	String hardwareCode = context.getParameter("HardwareCode");
	String installCode = context.getParameter("InstallCode");
	int intervalTime = Integer.valueOf(context
			.getParameter("IntervalSeconds")) * 1000;
	String strResult = licenseID + ":\n";
	long startTime = System.currentTimeMillis();

	// 验证许可证的激活状态
	try {
		String result = ServiceUtilTest.check(licenseID, hardwareCode,
				installCode);
		if (result.equals("Check Success")) {
			results.setSuccessful(true);
			results.setResponseCodeOK();
			strResult += "验证通过!\n";
		} else {
			results.setSuccessful(true);
			results.setResponseCodeOK();
			strResult += "验证未通过,返回结果为:" + result + "\n";
		}
	} catch (Exception e) {
		results.setSuccessful(false);
		strResult += "验证失败,异常信息:\n" + e.getMessage() + "\n";
	}

	// 等待两次测试之间的间隔
	if (intervalTime != 0) {
		try {
			Thread.sleep(intervalTime);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
	}

	long pastTime = System.currentTimeMillis() - startTime - intervalTime;

	results.setResponseMessage(strResult + "\n实际耗时(毫秒):" + pastTime);
	results.sampleEnd();
	return results;
}
 
Example 19
Source File: HTTPRawSampler.java    From jmeter-plugins with Apache License 2.0 4 votes vote down vote up
protected byte[] readResponse(SocketChannel channel, SampleResult res) throws IOException {
    ByteArrayOutputStream response = new ByteArrayOutputStream();
    
    ByteBuffer recvBuf = getRecvBuf();
    recvBuf.clear();
    
    boolean firstPack = true;
    int cnt;
    int responseSize = 0;
    
    if (log.isDebugEnabled()) {
        log.debug("Start reading response");
    }
    
    try {
        while ((cnt = channel.read(recvBuf)) != -1) {
            responseSize += cnt;
            if (firstPack) {
                res.latencyEnd();
                firstPack = false;
            }
            recvBuf.flip();
            if (response.size() <= recvDataLimit) {
                byte[] bytes = new byte[cnt];
                recvBuf.get(bytes);
                response.write(bytes);
            }
            
            recvBuf.clear();
        }
        
        if (response.size() < 1) {
            log.warn("Read no bytes from socket, seems it was closed. Let it be so.");
            channel.close();
        }
    } catch (IOException ex) {
        channel.close();
        throw ex;
    }
    
    if (log.isDebugEnabled()) {
        log.debug("Done reading response");
    }
    
    res.sampleEnd();
    if (!isUseKeepAlive()) {
        channel.close();
    }
    
    res.setBytes(responseSize);
    return response.toByteArray();
}
 
Example 20
Source File: SessionPermissions.java    From directory-fortress-core with Apache License 2.0 4 votes vote down vote up
/**224
     * Description of the Method
     *
     * @param samplerContext Description of the Parameter
     * @return Description of the Return Value
     */
    public SampleResult runTest( JavaSamplerContext samplerContext )
    {
        SampleResult sampleResult = new SampleResult();
        try
        {
            sampleResult.sampleStart();
            String message;
            if(isFortress)
            {
                message = "FT ";
            }
            else
            {
                message = "AC ";
            }

            message += "SessionPermissions isFortress: " + isFortress + ", userId: " + userId;
/*
            LOG.info( message );
            System.out.println( message );
*/
            assertNotNull( session );
            assertTrue( session.isAuthenticated() );
            List<Permission> result;
            if(isFortress)
            {
                assertNotNull( accessMgr );
                result = accessMgr.sessionPermissions( session );
            }
            else
            {
                assertNotNull( accelMgr );
                result = accelMgr.sessionPermissions( session );
            }

            // positive test case:
            assertNotNull( message, result );
            assertTrue( message, result.size() > 0 );
            sampleResult.sampleEnd();
            sampleResult.setBytes(1);
            sampleResult.setResponseMessage("test sessionPermissions completed, message=" + message);
            sampleResult.setSuccessful(true);
        }
        catch ( org.apache.directory.fortress.core.SecurityException se )
        {
            String error = "ThreadId:" + getThreadId() + "Error running test: " + se;
            LOG.error( error );
            System.out.println( error );
            se.printStackTrace();
            fail( error );
            sampleResult.setSuccessful( false );
        }

        return sampleResult;
    }