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

The following examples show how to use org.apache.jmeter.samplers.SampleResult#setResponseCode() . 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 vote down vote up
@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: 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 3
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 4
Source File: SendMessage.java    From jmeter-bzm-plugins with Apache License 2.0 6 votes vote down vote up
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 5
Source File: ConsoleStatusLoggerTest.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
/**
 * Test of sampleOccurred method, of class ConsoleStatusLogger.
 */
@Test
public void testSampleOccurred() throws InterruptedException {
    System.out.println("sampleOccurred");
    SampleResult res = new SampleResult();
    res.setResponseCode("200");
    SampleEvent se = new SampleEvent(res, "testTG");
    ConsoleStatusLogger instance = new ConsoleStatusLogger();
    instance.testStarted();
    instance.sampleOccurred(se);
    instance.sampleOccurred(se);
    Thread.sleep(1020);
    instance.sampleOccurred(se);
    instance.sampleOccurred(se);
    Thread.sleep(1020);
    instance.sampleOccurred(se);
    instance.sampleOccurred(se);
}
 
Example 6
Source File: AbstractUpdaterTest.java    From jmeter-prometheus-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testNulls() {
	BaseCollectorConfig base = TestUtilities.simpleCounterCfg();
	base.setLabels(new String[] {"be_null_one", "be_null_two", "code"});
	ListenerCollectorConfig cfg = new ListenerCollectorConfig(base);
	
	TestUpdater u = new TestUpdater(cfg);
	
	SampleResult res = new SampleResult();
	res.setResponseCode("304");
	SampleEvent event = new SampleEvent(res ,"tg1", new JMeterVariables());
	
	String[] labels = u.labelValues(event);
	
	Assert.assertTrue(labels.length == 3);
	Assert.assertArrayEquals(new String[] {"null", "null", "304"}, labels);
}
 
Example 7
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 8
Source File: SubSampler.java    From mqtt-jmeter with Apache License 2.0 5 votes vote down vote up
private SampleResult fillOKResult(SampleResult result, int size, String message, String contents) {
	result.setResponseCode("200");
	result.setSuccessful(true);
	result.setResponseMessage(message);
	result.setBodySize(size);
	result.setBytes(size);
	result.setResponseData(contents.getBytes());
	result.sampleEnd();
	return result;
}
 
Example 9
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 10
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 11
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 12
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 13
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 14
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 15
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 16
Source File: AggregatedTypeUpdaterTest.java    From jmeter-prometheus-plugin with Apache License 2.0 4 votes vote down vote up
@Test
public void testHistogramResponseTime() {
	BaseCollectorConfig base = TestUtilities.simpleHistogramCfg();
	base.setLabels(labels);
	ListenerCollectorConfig cfg = new ListenerCollectorConfig(base);
	cfg.setMeasuring(Measurable.ResponseTime.toString());
	cfg.setMetricName("ct_updater_test_hist_rt");

	Histogram collector = (Histogram) reg.getOrCreateAndRegister(cfg);
	AggregatedTypeUpdater u = new AggregatedTypeUpdater(cfg);
	
	SampleResult res = new SampleResult();
	res.setSampleLabel(name);
	int responseTime = 650;
	res.setStampAndTime(System.currentTimeMillis(), 650);
	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();
	assertEquals(1, metrics.size());
	MetricFamilySamples family = metrics.get(0);
	assertEquals(7, family.samples.size()); 	// 4 buckets + Inf + count + sum
	
	
	for(Sample sample : family.samples) {
		List<String> values = sample.labelValues;
		List<String> names = sample.labelNames;
		
		//correct labels without 'le' (bin size)
		boolean correctLabels = names.get(0).equals(labels[0]) && 
				names.get(1).equals(labels[1]) &&
				names.get(2).equals(labels[2]) &&
				values.get(0).equals(expectedLabels[0]) && 
				values.get(1).equals(expectedLabels[1]) &&
				values.get(2).equals(expectedLabels[2]);
		
		assertTrue(correctLabels);
		
		// _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(responseTime, sample.value, 0.1);
			}
			
		}else {
			assertTrue(values.size() == 4 && names.size() == 4);
			
			String leString = values.get(3);
			
			double le = (!leString.isEmpty() && !leString.equals("+Inf")) ? Double.parseDouble(leString) : Double.MAX_VALUE;
			
			if(le == Double.MAX_VALUE) {
				Assert.assertEquals(1, sample.value, 0.1);
			} else if(le < responseTime) {
				Assert.assertEquals(0, sample.value, 0.1);
			}else if(le > responseTime) {
				Assert.assertEquals(1, sample.value, 0.1);
			}
			
		}
	}
	
	
}
 
Example 17
Source File: JMeterXMPPSampler.java    From jmeter-bzm-plugins with Apache License 2.0 4 votes vote down vote up
@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 18
Source File: HTTPRawSampler.java    From jmeter-plugins with Apache License 2.0 4 votes vote down vote up
private void parseResponse(SampleResult res) {
    Scanner scanner = new Scanner(res.getResponseDataAsString());
    scanner.useDelimiter(RNpattern);
    
    if (!scanner.hasNextLine()) {
        return;
    }
    
    String httpStatus = scanner.nextLine();
    
    int s = httpStatus.indexOf(SPACE);
    int e = httpStatus.indexOf(SPACE, s + 1);
    if (s < e) {
        String rc = httpStatus.substring(s, e).trim();
        try {
            int rcInt = Integer.parseInt(rc);
            if (rcInt < 100 || rcInt > 599) {
                return;
            }
            res.setResponseCode(rc);
            res.setResponseMessage(httpStatus.substring(e).trim());
        } catch (NumberFormatException ex) {
            return;
        }
    } else {
        return;
    }
    
    if (!scanner.hasNextLine()) {
        return;
    }

    StringBuilder headers = new StringBuilder();
    String line;
    while (scanner.hasNextLine() && !(line = scanner.nextLine()).isEmpty()) {
        headers.append(line).append(CRLF);
    }
    res.setResponseHeaders(headers.toString());
    
    if (scanner.hasNext()) {
        res.setResponseData(scanner.next(anyContent).getBytes());
    } else {
        res.setResponseData("".getBytes());
    }
    
}
 
Example 19
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 20
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;
}