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

The following examples show how to use org.apache.jmeter.samplers.SampleResult#setSampleLabel() . 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: 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 2
Source File: ParallelListenerNotifier.java    From jmeter-bzm-plugins with Apache License 2.0 6 votes vote down vote up
@Override
public void notifyListeners(SampleEvent res, List<SampleListener> listeners) {
    log.debug("Adding subresult " + res.getResult());
    SampleResult result = res.getResult();
    String label = result.getSampleLabel();
    synchronized (this) {
        container.addSubResult(result);
        if (!res.getResult().isSuccessful()) {
            container.setSuccessful(false);
        }
    }
    // because https://bz.apache.org/bugzilla/show_bug.cgi?id=62550 in JMeter 5.0
    result.setSampleLabel(label);
    super.notifyListeners(res, listeners);
    log.debug("Added subresult " + res.getResult());
}
 
Example 3
Source File: JSONToXMLConverter.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
@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 4
Source File: AbstractUpdaterTest.java    From jmeter-prometheus-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testCombo() {
	BaseCollectorConfig base = TestUtilities.simpleCounterCfg();
	base.setLabels(new String[] {"foo", "code", "bar", "label"});
	ListenerCollectorConfig cfg = new ListenerCollectorConfig(base);
	
	TestUpdater u = new TestUpdater(cfg);

	JMeterVariables vars = new JMeterVariables();
	vars.put("foo", "funnier");
	vars.put("bar", "more banal");		
	JMeterContextService.getContext().setVariables(vars);
	
	SampleResult res = new SampleResult();
	res.setSampleLabel("one after the");
	res.setResponseCode("909");
	SampleEvent event = new SampleEvent(res,"tg1", vars);
	
	String[] labels = u.labelValues(event);

	Assert.assertTrue(labels.length == 4);
	Assert.assertArrayEquals(new String[] {"funnier", "909", "more banal", "one after the"}, labels);
}
 
Example 5
Source File: AbstractUpdaterTest.java    From jmeter-prometheus-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testKeywords() {
	BaseCollectorConfig base = TestUtilities.simpleCounterCfg();
	base.setLabels(new String[] {"label","code"});
	ListenerCollectorConfig cfg = new ListenerCollectorConfig(base);
	
	TestUpdater u = new TestUpdater(cfg);
	
	SampleResult res = new SampleResult();
	res.setSampleLabel("test_label");
	res.setResponseCode("204");
	SampleEvent event = new SampleEvent(res,"test_tg", new JMeterVariables());
	
	String[] labels = u.labelValues(event);
	

	Assert.assertTrue(labels.length == 2);
	Assert.assertArrayEquals(new String[] {"test_label", "204"}, labels);
}
 
Example 6
Source File: AbstractGraphPanelVisualizerTest.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
@Test
public void testIncludeExcludeRegex_none() {
    CorrectedResultCollector instance = new CorrectedResultCollector();
    instance.setProperty(CorrectedResultCollector.INCLUDE_SAMPLE_LABELS,
            "P[0-9].*");
    instance.testStarted();
    DebugVisualizer vis = new DebugVisualizer();
    instance.setListener(vis);
    vis.configure(instance);

    vis.lastLabel = null;
    SampleResult res2 = new SampleResult();
    res2.setSampleLabel("P1_TEST");
    instance.sampleOccurred(new SampleEvent(res2, "tg"));
    assertNull(vis.lastLabel);
}
 
Example 7
Source File: FlexibleFileWriterTest.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
@Test
public void testSampleOccurred_labels() throws IOException {
    System.out.println("sampleOccurred_labels");
    SampleResult res = new SampleResult();
    res.setResponseData("test".getBytes());
    FlexibleFileWriter instance = new FlexibleFileWriter();
    instance.setFilename(File.createTempFile("ffw_test_", ".txt").getAbsolutePath());
    instance.setColumns("threadName|\\t|sampleLabel");
    instance.testStarted();

    res.setSampleLabel("SAMPLELBL");
    res.setThreadName("THRDNAME");
    SampleEvent e = new SampleEvent(res, "Test");
    instance.sampleOccurred(e);
    //ByteBuffer written = instance.fileEmul.getWrittenBytes();
    //assertEquals(exp, JMeterPluginsUtils.byteBufferToString(written));

    instance.testEnded();
}
 
Example 8
Source File: AbstractGraphPanelVisualizerTest.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
@Test
public void testIncludeExcludeRegex_include_only() {
    CorrectedResultCollector instance = new CorrectedResultCollector();
    instance.setProperty(CorrectedResultCollector.INCLUDE_SAMPLE_LABELS,
            "P[0-9].*");
    instance.setProperty(
            CorrectedResultCollector.INCLUDE_REGEX_CHECKBOX_STATE, true);
    instance.testStarted();
    DebugVisualizer vis = new DebugVisualizer();
    instance.setListener(vis);
    vis.configure(instance);

    vis.lastLabel = null;
    SampleResult res = new SampleResult();
    res.setSampleLabel("P1_TEST");
    instance.sampleOccurred(new SampleEvent(res, "tg"));
    assertEquals("P1_TEST", vis.lastLabel);

    vis.lastLabel = null;
    SampleResult res1 = new SampleResult();
    res1.setSampleLabel("T1_TEST");
    instance.sampleOccurred(new SampleEvent(res1, "tg"));
    assertNull(vis.lastLabel);
}
 
Example 9
Source File: AbstractGraphPanelVisualizerTest.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
@Test
public void testMinMax_none() {
    CorrectedResultCollector instance = new CorrectedResultCollector();
    instance.testStarted();
    DebugVisualizer vis = new DebugVisualizer();
    vis.configure(instance);
    instance.setListener(vis);
    SampleResult res = SampleResult.createTestSample(21000, 30000);
    res.setSampleLabel("test");
    instance.sampleOccurred(new SampleEvent(res, "tg"));
    assertEquals("test", vis.lastLabel);
}
 
Example 10
Source File: HonoReceiverSampler.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public SampleResult sample(final Entry entry) {
    final SampleResult res = new SampleResult();
    res.setResponseOK();
    res.setDataType(SampleResult.TEXT);
    res.setSampleLabel(getName());
    honoReceiver.sample(res);
    return res;
}
 
Example 11
Source File: TestUtilities.java    From jmeter-prometheus-plugin with Apache License 2.0 5 votes vote down vote up
public static ResultAndVariables resultWithLabels() {
  	SampleResult result = new SampleResult();
  	
  	result.setSampleLabel(TEST_SAMPLER_NAME);
  	result.setResponseCode(TEST_SAMPLER_CODE);
  	
  	JMeterVariables vars = new JMeterVariables();
vars.put(TEST_VAR_NAME, TEST_VAR_VALUE);
JMeterContextService.getContext().setVariables(vars);

return new ResultAndVariables(result, vars);
  }
 
Example 12
Source File: AbstractGraphPanelVisualizerTest.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
@Test
public void testMinMax_min_max() {
    CorrectedResultCollector instance = new CorrectedResultCollector();
    instance.setStartOffset("10");
    instance.setEndOffset("20");
    instance.testStarted();
    DebugVisualizer vis = new DebugVisualizer();
    vis.configure(instance);
    instance.setListener(vis);
    vis.startTimeRef = 10300;
    vis.startTimeInf = 10000;
    vis.startTimeSup = 11000;

    vis.lastLabel = null;
    SampleResult res = SampleResult.createTestSample(31500, 32000);
    res.setSampleLabel("test");
    instance.sampleOccurred(new SampleEvent(res, "tg"));
    assertNull(vis.lastLabel);

    vis.lastLabel = null;
    SampleResult res1 = SampleResult.createTestSample(29000, 30000);
    res1.setSampleLabel("test1");
    instance.sampleOccurred(new SampleEvent(res1, "tg"));
    assertEquals("test1", vis.lastLabel);

    vis.lastLabel = null;
    SampleResult res2 = SampleResult.createTestSample(19000, 20000);
    res2.setSampleLabel("test2");
    instance.sampleOccurred(new SampleEvent(res2, "tg"));
    assertNull(vis.lastLabel);
}
 
Example 13
Source File: NoOp.java    From jmeter-bzm-plugins with Apache License 2.0 5 votes vote down vote up
@Override
public SampleResult perform(JMeterXMPPSampler sampler, SampleResult res) throws Exception {
    long counter = 0;
    for (Packet packet : incomingPackets) {
        incomingPackets.remove(packet);
        SampleResult subRes = new SampleResult();
        subRes.setSuccessful(true);
        subRes.setResponseCode("200");
        subRes.setResponseMessage("OK");
        subRes.setSampleLabel(packet.getClass().getSimpleName().isEmpty() ? packet.getClass().getName() : packet.getClass().getSimpleName());
        subRes.setResponseData(packet.toXML().toString().getBytes());

        if ((packet instanceof Presence) && (((Presence) packet).getType() == Presence.Type.error)) {
            subRes.setSuccessful(false);
            subRes.setResponseCode("500");
            subRes.setResponseMessage(packet.getError().toString());
        } else if ((packet instanceof Message) && (((Message) packet).getType() == Message.Type.error)) {
            subRes.setSuccessful(false);
            subRes.setResponseCode("500");
            subRes.setResponseMessage(packet.getError().toString());
        } else if ((packet instanceof IQ) && (((IQ) packet).getType() == IQ.Type.error)) {
            subRes.setSuccessful(false);
            subRes.setResponseCode("500");
            subRes.setResponseMessage(packet.getError().toString());
        }

        res.addSubResult(subRes);
        counter++;
    }
    res.setResponseData(("Received packets: " + counter).getBytes());
    return counter > 0 ? res : null;
}
 
Example 14
Source File: AbstractGraphPanelVisualizerTest.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
@Test
public void testMinMax_max_only() {
    CorrectedResultCollector instance = new CorrectedResultCollector();
    instance.setEndOffset("20");
    instance.testStarted();
    DebugVisualizer vis = new DebugVisualizer();
    vis.configure(instance);
    instance.setListener(vis);
    vis.startTimeRef = 10300;
    vis.startTimeInf = 10000;
    vis.startTimeSup = 11000;

    vis.lastLabel = null;
    SampleResult res = SampleResult.createTestSample(31500, 32000);
    res.setSampleLabel("test");
    instance.sampleOccurred(new SampleEvent(res, "tg"));
    assertNull(vis.lastLabel);

    vis.lastLabel = null;
    SampleResult res1 = SampleResult.createTestSample(29000, 30000);
    res1.setSampleLabel("test1");
    instance.sampleOccurred(new SampleEvent(res1, "tg"));
    assertEquals("test1", vis.lastLabel);

    instance.testEnded();
    instance.setEndOffset("20a");
    instance.testStarted();
    vis.configure(instance);
    instance.setListener(vis);

    vis.lastLabel = null;
    SampleResult res2 = SampleResult.createTestSample(31000, 32000);
    res2.setSampleLabel("test2");
    instance.sampleOccurred(new SampleEvent(res2, "tg"));
    assertEquals("test2", vis.lastLabel);
}
 
Example 15
Source File: MergeResultsGui.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
@Override
public void add(SampleResult res) {
    if (!isSampleIncluded(res)) {
        return;
    }

    res.setSaveConfig(collector.getSaveConfig());
    if (!prefixLabel.isEmpty()) {
        String resLabel = res.getSampleLabel();
        res.setSampleLabel(prefixLabel + resLabel);
    }
    res.setTimeStamp(res.getTimeStamp() - startTimeRef + REF_START_TIME);
    samples.add(res);
}
 
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: AggregatedTypeUpdaterTest.java    From jmeter-prometheus-plugin with Apache License 2.0 4 votes vote down vote up
@Test
public void testSummaryResponseSize() {
	BaseCollectorConfig base = TestUtilities.simpleSummaryCfg();
	base.setLabels(labels);
	ListenerCollectorConfig cfg = new ListenerCollectorConfig(base);
	cfg.setMetricName("ct_updater_test_summary_rsize");
	cfg.setMeasuring(Measurable.ResponseSize.toString());

	Summary collector = (Summary) reg.getOrCreateAndRegister(cfg);
	AggregatedTypeUpdater u = new AggregatedTypeUpdater(cfg);
	
	SampleResult res = new SampleResult();
	res.setSampleLabel(name);
	int responseSize = 650;
	res.setResponseData(new byte[responseSize]);
	res.setResponseCode(code);
	
	JMeterVariables vars = new JMeterVariables();
	vars.put("foo_label", var_value);
	JMeterContextService.getContext().setVariables(vars);
	SampleEvent e = new SampleEvent(res,"tg1", vars);
	
	
	String[] actualLabels = u.labelValues(e);
	Assert.assertArrayEquals(expectedLabels, actualLabels);
	
	u.update(e);
	
	List<MetricFamilySamples> metrics = collector.collect();
	Assert.assertEquals(1, metrics.size());
	MetricFamilySamples family = metrics.get(0);
	Assert.assertEquals(5, family.samples.size()); 	// 3 quantiles + count + sum
	
	
	for(Sample sample : family.samples) {
		List<String> values = sample.labelValues;
		List<String> names = sample.labelNames;
		
		this.correctLabels(names, values);
		
		// _sum and _count don't have an 'le' label
		if(sample.name.endsWith("count") || sample.name.endsWith("sum")) {
			assertTrue(values.size() == 3 && names.size() == 3);
			
			if(sample.name.endsWith("count")) {
				Assert.assertEquals(1, sample.value, 0.1);
			}else {
				Assert.assertEquals(responseSize, sample.value, 0.1);
			}
			
		}else {
			assertTrue(values.size() == 4 && names.size() == 4);
			Assert.assertEquals(responseSize, sample.value, 0.1);
		}
	}
}
 
Example 18
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 19
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 20
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;
}