Java Code Examples for org.apache.jmeter.samplers.SampleResult#setSuccessful()
The following examples show how to use
org.apache.jmeter.samplers.SampleResult#setSuccessful() .
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: FlexibleFileWriterTest.java From jmeter-plugins with Apache License 2.0 | 7 votes |
@Test public void testSampleOccurred_phout() throws IOException { System.out.println("sampleOccurred_phout"); SampleResult res = new SampleResult(); res.sampleStart(); res.setResponseData("test".getBytes()); res.setResponseCode("200"); res.setLatency(4); res.setSuccessful(true); res.sampleEnd(); SampleEvent e = new SampleEvent(res, "Test"); FlexibleFileWriter instance = new FlexibleFileWriter(); instance.setFilename(File.createTempFile("ffw_test_", ".txt").getAbsolutePath()); instance.setColumns("endTimeMillis|\\t\\t|responseTimeMicros|\\t|latencyMicros|\\t|sentBytes|\\t|receivedBytes|\\t|isSuccsessful|\\t|responseCode|\\t|connectTime|\\r\\n"); instance.testStarted(); instance.sampleOccurred(e); //String written = JMeterPluginsUtils.byteBufferToString(instance.fileEmul.getWrittenBytes()); //System.out.println(written); //assertEquals(8, written.split("\t").length); instance.testEnded(); }
Example 2
Source File: SubSampler.java From mqtt-jmeter with Apache License 2.0 | 6 votes |
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 3
Source File: BlurSamplerClient.java From incubator-retired-blur with Apache License 2.0 | 6 votes |
@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 4
Source File: JSONToXMLConverter.java From jmeter-plugins with Apache License 2.0 | 6 votes |
@Override public SampleResult sample(Entry e) { SampleResult result = new SampleResult(); result.setSampleLabel(getName()); result.setSamplerData(this.getJsonInput()); result.setDataType(SampleResult.TEXT); result.sampleStart(); if (!getJsonInput().equalsIgnoreCase("")) { try { this.convertToXML(); result.setResponseData(this.getXmlOutput().getBytes()); result.setSuccessful(true); } catch (Exception e1) { result.setResponseData(e1.getMessage().getBytes()); result.setSuccessful(false); } } result.sampleEnd(); return result; }
Example 5
Source File: SendMessage.java From jmeter-bzm-plugins with Apache License 2.0 | 6 votes |
private SampleResult waitResponse(SampleResult res, String recipient) throws InterruptedException, SmackException { long time = 0; do { Iterator<Message> packets = responseMessages.iterator(); Thread.sleep(conn.getPacketReplyTimeout() / 100); // optimistic while (packets.hasNext()) { Packet packet = packets.next(); Message response = (Message) packet; if (XmppStringUtils.parseBareAddress(response.getFrom()).equals(recipient)) { packets.remove(); res.setResponseData(response.toXML().toString().getBytes()); if (response.getError() != null) { res.setSuccessful(false); res.setResponseCode("500"); res.setResponseMessage(response.getError().toString()); } return res; } } time += conn.getPacketReplyTimeout() / 10; Thread.sleep(conn.getPacketReplyTimeout() / 10); } while (time < conn.getPacketReplyTimeout()); throw new SmackException.NoResponseException(); }
Example 6
Source File: AbstractIPSampler.java From jmeter-plugins with Apache License 2.0 | 6 votes |
@Override public SampleResult sample(Entry entry) { SampleResult res = new SampleResult(); res.setSampleLabel(getName()); res.setSamplerData(getRequestData()); res.sampleStart(); res.setDataType(SampleResult.TEXT); res.setSuccessful(true); res.setResponseCode(RC200); try { res.setResponseData(processIO(res)); } catch (Exception ex) { if (!(ex instanceof SocketTimeoutException)) { log.error(getHostName(), ex); } res.sampleEnd(); res.setSuccessful(false); res.setResponseCode(RC500); res.setResponseMessage(ex.toString()); res.setResponseData((ex.toString() + CRLF + ExceptionUtils.getStackTrace(ex)).getBytes()); } return res; }
Example 7
Source File: TopicMessageGeneratorClient.java From hedera-mirror-node with Apache License 2.0 | 5 votes |
/** * 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 8
Source File: CountTypeUpdaterTest.java From jmeter-prometheus-plugin with Apache License 2.0 | 5 votes |
public static SampleResult newSampleResult(boolean success) { SampleResult res = new SampleResult(); res.setSampleLabel(TestUtilities.TEST_SAMPLER_NAME); res.setSuccessful(success); return res; }
Example 9
Source File: KafkaProducerSampler.java From kafkameter with Apache License 2.0 | 5 votes |
/** * 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 10
Source File: AccelCreateSession.java From directory-fortress-core with Apache License 2.0 | 5 votes |
/** * 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 = "FT CreateSession TID: " + getThreadId() + " UID:" + userId + " CTR:" + ctr++; //LOG.info( message ); //System.out.println( message ); assertNotNull( accelMgr ); Session session; User user = new User(); // positive test case: user.setUserId( userId ); user.setPassword( "secret" ); session = accelMgr.createSession( user, false ); assertNotNull( session ); assertTrue( session.isAuthenticated() ); sampleResult.sampleEnd(); sampleResult.setBytes(1); sampleResult.setResponseMessage("AC test completed TID: " + getThreadId() + " UID: " + userId); sampleResult.setSuccessful(true); } catch ( org.apache.directory.fortress.core.SecurityException se ) { System.out.println( "ThreadId:" + getThreadId() + "Error running test: " + se ); se.printStackTrace(); sampleResult.setSuccessful( false ); } return sampleResult; }
Example 11
Source File: JMeterXMPPSampler.java From jmeter-bzm-plugins with Apache License 2.0 | 4 votes |
@Override public SampleResult sample(Entry entry) { SampleResult res = new SampleResult(); res.setSampleLabel(getName()); res.setDataType(SampleResult.TEXT); res.setSuccessful(true); res.setResponseCode("200"); res.setResponseMessage("OK"); res.sampleStart(); try { if (connConfig == null) { throw new RuntimeException("Cannot sample XMPP without XMPP Connection component"); } XMPPConnection conn = getXMPPConnection(); if (conn == null) { throw new RuntimeException("No XMPP Connection available"); } String headers = "Connection ID: " + conn.getConnectionID() + "\r\n"; String action = getAction(); if (!conn.isConnected() && !action.equals(Connect.class.getCanonicalName())) { log.error("Please call Connect before calling other actions"); throw new SmackException.NotConnectedException(); } headers += "User: " + conn.getUser() + "\r\n"; res.setRequestHeaders(headers); AbstractXMPPAction actObject = connConfig.getActions().get(action); if (actObject.perform(this, res) == null) { return null; } } catch (Exception e) { log.error("Error in XMPP Sampler: ", e); res.setSuccessful(false); res.setResponseCode("500"); res.setResponseMessage((e.getMessage() == null || e.getMessage().isEmpty()) ? e.toString() : e.getMessage()); res.setResponseData(ExceptionUtils.getStackTrace(e).getBytes()); } res.sampleEnd(); return res; }
Example 12
Source File: CheckAccess.java From directory-fortress-core with Apache License 2.0 | 4 votes |
/**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 { int opCount = ++ctr % 10; if( opCount == 0 ) opCount = 10; int objCount = (ctr / 10) + 1; if(objCount > 10) { objCount = objCount % 10; } if(objCount == 0) { objCount = 1; } //int objCount = ((ctr / 10) + 1) % 10; String opName = "oper" + opCount; String objName = "loadtestobject" + objCount; sampleResult.sampleStart(); String message; if(isFortress) { message = "FT "; } else { message = "AC "; } message += "CheckAccess isFortress: " + isFortress + ", userId: " + userId + ", objName:" + objName + ", opName: " + opName; /* LOG.info( message ); System.out.println( message ); */ assertNotNull( session ); assertTrue( session.isAuthenticated() ); Permission perm = new Permission(); perm.setObjName( objName ); perm.setOpName( opName ); boolean result; if(isFortress) { assertNotNull( accessMgr ); result = accessMgr.checkAccess( session, perm ); } else { assertNotNull( accelMgr ); result = accelMgr.checkAccess( session, perm ); } // positive test case: assertTrue( message, result ); sampleResult.sampleEnd(); sampleResult.setBytes(1); sampleResult.setResponseMessage("test checkAccess completed"); 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; }
Example 13
Source File: DisConnectSampler.java From mqtt-jmeter with Apache License 2.0 | 4 votes |
@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 14
Source File: LicenseCheck.java From tmxeditor8 with GNU General Public License v2.0 | 4 votes |
@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 15
Source File: SessionPermissions.java From directory-fortress-core with Apache License 2.0 | 4 votes |
/**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; }
Example 16
Source File: HonoReceiver.java From hono with Eclipse Public License 2.0 | 4 votes |
/** * 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 17
Source File: HonoSender.java From hono with Eclipse Public License 2.0 | 4 votes |
/** * 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 18
Source File: HonoSender.java From hono with Eclipse Public License 2.0 | 4 votes |
/** * 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 19
Source File: SubscriberSampler.java From mqtt-jmeter with Apache License 2.0 | 4 votes |
/** * {@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 20
Source File: KafkaProducerSampler.java From kafkameter with Apache License 2.0 | 2 votes |
/** * Mark the sample result as @{code end}ed and not {@code successful}, and set the * {@code responseCode} to {@code reason}. * * @param result the sample result to change * @param reason the failure reason */ private void sampleResultFailed(SampleResult result, String reason) { result.sampleEnd(); result.setSuccessful(false); result.setResponseCode(reason); }