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

The following examples show how to use org.apache.jmeter.samplers.SampleResult#setResponseCodeOK() . 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: HonoSenderSampler.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public SampleResult sample(final Entry entry) {

    final SampleResult res = new SampleResult();
    res.setDataType(SampleResult.TEXT);
    res.setResponseOK();
    res.setResponseCodeOK();
    res.setSampleLabel(getName());
    if (getMessageCountPerSamplerRunAsInt() == 1) {
        honoSender.send(res, getDeviceId(), isWaitForDeliveryResult());
    } else {
        honoSender.send(res, getMessageCountPerSamplerRunAsInt(), getDeviceId(),
                isWaitForDeliveryResult());
    }
    return res;
}
 
Example 2
Source File: TopicMessageGeneratorClient.java    From hedera-mirror-node with Apache License 2.0 5 votes vote down vote up
/**
 * Runs test by calling sampler to manage topic message table. Reports success based on successful db operations
 *
 * @return Sample result
 */
@Override
public SampleResult runTest(JavaSamplerContext context) {
    SampleResult result = new SampleResult();

    try {
        // establish db connection in test to ensure failures are reported
        connectionHandler = new ConnectionHandler(host, port, dbName, dbUser, dbPassword);
        sampler = new TopicMessageGeneratorSampler(connectionHandler);

        MessageGenerator messageGen = MessageGenerator.builder()
                .topicNum(context.getLongParameter("topicID", 0))
                .historicMessagesCount(context.getIntParameter("historicMessagesCount", 0))
                .futureMessagesCount(context.getIntParameter("newTopicsMessageCount", 0))
                .topicMessageEmitCycles(context.getIntParameter("topicMessageEmitCycles", 0))
                .newTopicsMessageDelay(context.getLongParameter("newTopicsMessageDelay", 0L))
                .deleteFromSequence(context.getLongParameter("delSeqFrom", -1L))
                .build();

        result.sampleStart();
        sampler.populateTopicMessages(messageGen);
        result.sampleEnd();
        result.setResponseMessage("Successfully performed populateTopicMessages");
        result.setResponseCodeOK();
        result.setSuccessful(true);
    } catch (Exception ex) {
        log.error("Error populating topic messages", ex);
        StringWriter stringWriter = new StringWriter();
        ex.printStackTrace(new PrintWriter(stringWriter));
        result.sampleEnd();
        result.setResponseMessage("Exception: " + ex);
        result.setResponseData(stringWriter.toString().getBytes());
        result.setDataType(SampleResult.TEXT);
        result.setResponseCode("500");
    }

    return result;
}
 
Example 3
Source File: KafkaProducerSampler.java    From kafkameter with Apache License 2.0 5 votes vote down vote up
/**
 * Mark the sample result as {@code end}ed and {@code successful} with an "OK" {@code responseCode},
 * and if the response is not {@code null} then set the {@code responseData} to {@code response},
 * otherwise it is marked as not requiring a response.
 *
 * @param result sample result to change
 * @param response the successful result message, may be null.
 */
private void sampleResultSuccess(SampleResult result, /* @Nullable */ String response) {
  result.sampleEnd();
  result.setSuccessful(true);
  result.setResponseCodeOK();
  if (response != null) {
    result.setResponseData(response, ENCODING);
  }
  else {
    result.setResponseData("No response required", ENCODING);
  }
}
 
Example 4
Source File: MultiTopicHCSClient.java    From hedera-mirror-node with Apache License 2.0 4 votes vote down vote up
private SampleResult sequentialRun() {
    SampleResult result = new SampleResult();
    int successSamplesCount = 0;
    result.sampleStart();

    try {
        HCSSamplerResult response = null;
        for (TopicSubscription subscription : consensusServiceReactiveSamplers.keySet()) {
            if (subscription.getMilliSecWaitBefore() > 0) {
                log.debug("Waiting {} ms before subscribing", subscription.getMilliSecWaitBefore());
                Thread.sleep(subscription.getMilliSecWaitBefore(), 0);
            }

            MessageListener listener = MessageListener.builder()
                    .historicMessagesCount(subscription.getHistoricMessagesCount())
                    .futureMessagesCount(subscription.getIncomingMessageCount())
                    .messagesLatchWaitSeconds(subscription.getSubscribeTimeoutSeconds())
                    .build();

            response = consensusServiceReactiveSamplers.get(subscription).subscribeTopic(listener);

            if (!response.isSuccess()) {
                log.debug("Failure in subscribe topic test : " + subscription);
            } else {
                successSamplesCount++;
                log.debug("Successfully performed subscription : " + subscription);
            }
        }

        result.setResponseMessage("Successfully performed subscriptions");
        result.setResponseCodeOK();
        result.sampleEnd();
        result.setResponseData(response.toString().getBytes());
        result.setSuccessful(response.isSuccess());
    } catch (Exception ex) {
        log.error("Error subscribing to topic", ex);

        StringWriter stringWriter = new StringWriter();
        ex.printStackTrace(new PrintWriter(stringWriter));

        result.setResponseMessage("Failure in subscribes");
        result.setResponseCode("500");
        result.sampleEnd();
        result.setResponseMessage("Exception: " + ex);
        result.setResponseData(stringWriter.toString().getBytes());
        result.setDataType(SampleResult.TEXT);
        result.setResponseCode("500");
    }

    log.info("{} out of {} samples passed", successSamplesCount, clientCount);

    return result;
}
 
Example 5
Source File: SingleTopicHCSClient.java    From hedera-mirror-node with Apache License 2.0 4 votes vote down vote up
/**
 * Runs test by calling sampler subscribeTopic. Reports success based on call response from sampler
 */
@Override
public SampleResult runTest(JavaSamplerContext context) {
    SampleResult result = new SampleResult();
    HCSSamplerResult response = null;
    result.sampleStart();

    try {
        MessageListener listener = MessageListener.builder()
                .historicMessagesCount(propHandler.getIntClientTestParam("HistoricMessagesCount", 0, "0"))
                .futureMessagesCount(propHandler.getIntClientTestParam("IncomingMessageCount", 0, "0"))
                .messagesLatchWaitSeconds(propHandler.getIntClientTestParam("SubscribeTimeoutSeconds", 0, "60"))
                .build();

        response = hcsTopicSampler.subscribeTopic(listener);

        result.sampleEnd();
        result.setResponseData(response.toString().getBytes());
        result.setSuccessful(response.isSuccess());

        if (!response.isSuccess()) {
            result.setResponseMessage("Failure in subscribe topic test");
            result.setResponseCode("500");
        } else {
            result.setResponseMessage("Successfully performed subscribe topic test");
            result.setResponseCodeOK();
        }
    } catch (Exception ex) {
        log.error("Error subscribing to topic", ex);

        StringWriter stringWriter = new StringWriter();
        ex.printStackTrace(new PrintWriter(stringWriter));
        result.sampleEnd();
        result.setResponseMessage("Exception: " + ex);
        result.setResponseData(stringWriter.toString().getBytes());
        result.setDataType(SampleResult.TEXT);
        result.setResponseCode("500");
    }

    return result;
}
 
Example 6
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 7
Source File: HonoReceiver.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Takes a sample.
 *
 * @param result The result to set the sampler's current statistics on.
 */
public void sample(final SampleResult result) {
    synchronized (lock) {
        long elapsed = 0;
        result.setResponseCodeOK();
        result.setSuccessful(errorCount == 0 && !senderClockNotInSync);
        result.setSampleCount(messageCount);
        result.setErrorCount(errorCount); // NOTE: This method does nothing in JMeter 3.3/4.0
        result.setBytes(bytesReceived);
        if (messageCount > 0) {
            if (sampler.isUseSenderTime() && sampleStart != 0 && errorCount == 0) {
                // errorCount has to be 0 here - otherwise totalSampleDeliveryTime doesn't have a correct value
                elapsed = senderClockNotInSync ? -1 : totalSampleDeliveryTime / messageCount;
                result.setStampAndTime(sampleStart, elapsed);
            } else if (sampleStart != 0) {
                elapsed = System.currentTimeMillis() - sampleStart;
                result.setStampAndTime(sampleStart, elapsed);
                result.setIdleTime(elapsed);
            } else {
                LOGGER.warn("sampleStart hasn't been set - setting elapsed time to 0");
                result.setStampAndTime(System.currentTimeMillis(), 0);
                result.setIdleTime(0);
            }
        } else {
            // empty sample
            result.setStampAndTime(System.currentTimeMillis(), 0);
            result.setIdleTime(0);
        }
        String responseMessage = "";
        if (errorCount == 0) {
            final String formatString = sampler.isUseSenderTime() ? "{}: received batch of {} messages; average delivery time: {}ms"
                    : "{}: received batch of {} messages in {}ms";
            LOGGER.info(formatString, sampler.getThreadName(), messageCount, elapsed);
        } else {
            LOGGER.info("{}: received batch of {} messages with {} errors in {}ms", sampler.getThreadName(), messageCount, errorCount, elapsed);
            responseMessage = "got " + errorCount + " invalid messages";
        }
        if (senderClockNotInSync) {
            responseMessage = (responseMessage.isEmpty() ? "" : responseMessage + "; ") + "sender clock not in sync";
            LOGGER.error("The sender time extracted from at least one of the received messages is newer than the receiver time" +
                    " - sender and receiver clocks are not in sync. Consider deactivating usage of the sender time.");
        }
        result.setResponseMessage(responseMessage);

        // reset all fields
        totalSampleDeliveryTime = 0;
        senderClockNotInSync = false;
        bytesReceived = 0;
        messageCount = 0;
        errorCount = 0;
        sampleStart = 0;
    }
}
 
Example 8
Source File: HonoSender.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Publishes multiple messages to Hono.
 *
 * @param sampleResult The result object representing the combined outcome of the samples.
 * @param messageCount The number of messages to send
 * @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 int messageCount, final String deviceId,
                 final boolean waitForDeliveryResult) {
    final long sampleStart = System.currentTimeMillis();
    long addedSendDurations = 0;
    boolean isSuccessful = true;
    String firstResponseErrorMessage = "";
    String firstResponseErrorCode = "";
    long sentBytes = 0;
    int errorCount = 0;
    for (int i = 0; i < messageCount; i++) {
        final SampleResult subResult = new SampleResult();
        subResult.setDataType(SampleResult.TEXT);
        subResult.setResponseOK();
        subResult.setResponseCodeOK();
        subResult.setSampleLabel(sampleResult.getSampleLabel());
        // send the message
        send(subResult, deviceId, waitForDeliveryResult);
        // can't call sampleResult.addSubResult(subResult) here - this would prevent a later invocation of sampleResult.setStampAndTime()
        sampleResult.addRawSubResult(subResult);

        if (!subResult.isSuccessful()) {
            isSuccessful = false;
            errorCount++;
            if (firstResponseErrorMessage.isEmpty()) {
                firstResponseErrorMessage = subResult.getResponseMessage();
                firstResponseErrorCode = subResult.getResponseCode();
            }
        }
        sentBytes += subResult.getSentBytes();
        addedSendDurations += subResult.getTime();
    }
    sampleResult.setSuccessful(isSuccessful);
    final String responseMessage = MessageFormat.format("BatchResult {0}/{1}/{2}", sampler.getEndpoint(), sampler.getTenant(), deviceId);
    if (isSuccessful) {
        sampleResult.setResponseMessage(responseMessage);
    } else {
        sampleResult.setResponseMessage(responseMessage + ": " + errorCount + " errors - first: " + firstResponseErrorMessage);
        sampleResult.setResponseCode(firstResponseErrorCode);
    }
    sampleResult.setSentBytes(sentBytes);
    sampleResult.setSampleCount(messageCount);
    sampleResult.setErrorCount(errorCount); // NOTE: This method does nothing in JMeter 3.3/4.0
    final long averageElapsedTimePerMessage = addedSendDurations / messageCount;
    sampleResult.setStampAndTime(sampleStart, averageElapsedTimePerMessage);
}
 
Example 9
Source File: SubscriberSampler.java    From mqtt-jmeter with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public SampleResult sample(Entry entry) {
    SampleResult result = new SampleResult();
    result.setSampleLabel(getNameLabel());
    result.sampleStart();

    if (null != exceptionOccurred) {
        result.setSuccessful(false);
        result.setResponseMessage("Client is not connected." + lineSeparator + exceptionOccurred.toString());
        result.setResponseData(exceptionOccurred.toString().getBytes());
        result.sampleEnd();
        result.setResponseCode("FAILED");
        return result;
    }

    Message receivedMessage;
    while (!interrupted && null != client.getReceivedMessages() && null != client.getReceivedMessageCounter()) {
        receivedMessage = client.getReceivedMessages().poll();
        if (receivedMessage != null) {
            client.getReceivedMessageCounter().incrementAndGet();
            result.sampleEnd();
            result.setSuccessful(true);
            result.setResponseMessage(lineSeparator + "Received " + client.getReceivedMessageCounter().get() + " " +
                                      "messages." +
                                      lineSeparator + "Current message QOS : " + receivedMessage.getQos() +
                                      lineSeparator + "Is current message a duplicate : " + receivedMessage.isDup()
                                      + lineSeparator + "Received timestamp of current message : " +
                                      receivedMessage.getCurrentTimestamp() + lineSeparator + "Is current message" +
                                      " a retained message : " + receivedMessage.isRetained());
            result.setBytes(receivedMessage.getPayload().length);
            result.setResponseData(receivedMessage.getPayload());
            result.setResponseCodeOK();
            return result;
        }
    }

    result.setSuccessful(false);
    result.setResponseMessage("Client has been stopped or an error occurred while receiving messages. Received "  + " valid messages.");
    result.sampleEnd();
    result.setResponseCode("FAILED");
    return result;
}
 
Example 10
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 11
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 12
Source File: LicenseCheck.java    From tmxeditor8 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;
}