org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase Java Examples

The following examples show how to use org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase. 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: JMeterRecorder.java    From jsflight with Apache License 2.0 6 votes vote down vote up
private void placeAndProcessTestElements(HashTree hashTree, List<TestElement> samples)
{
    for (TestElement element : samples)
    {
        List<TestElement> descendants = findAndRemoveHeaderManagers(element);
        HashTree parent = hashTree.add(element);
        descendants.forEach(parent::add);

        if (element instanceof HTTPSamplerBase)
        {
            HTTPSamplerBase http = (HTTPSamplerBase)element;

            LOG.info("Start sampler processing");
            scriptProcessor.processScenario(http, parent, vars, this);
            LOG.info("Stop sampler processing");
        }
    }
}
 
Example #2
Source File: JMeterRecorder.java    From jsflight with Apache License 2.0 6 votes vote down vote up
private List<TestElement> extractAppropriateTestElements(RecordingController recordingController)
{
    List<TestElement> samples = new ArrayList<>();

    for (TestElement sample; (sample = recordingController.next()) != null;)
    {
        // skip unknown nasty requests
        if (sample instanceof HTTPSamplerBase)
        {
            HTTPSamplerBase http = (HTTPSamplerBase)sample;
            if (http.getArguments().getArgumentCount() > 0
                    && http.getArguments().getArgument(0).getValue().startsWith("0Q0O0M0K0I0"))
            {
                continue;
            }
        }
        samples.add(sample);
    }

    Collections.sort(samples, (o1, o2) -> {
        String num1 = o1.getName().split(" ")[0];
        String num2 = o2.getName().split(" ")[0];
        return ((Integer)Integer.parseInt(num1)).compareTo(Integer.parseInt(num2));
    });
    return samples;
}
 
Example #3
Source File: JMeterScriptProcessor.java    From jsflight with Apache License 2.0 6 votes vote down vote up
/**
 * Post process every stored request just before it get saved to disk
 *
 * @param sampler recorded http-request (sampler)
 * @param tree   HashTree (XML like data structure) that represents exact recorded sampler
 */
public void processScenario(HTTPSamplerBase sampler, HashTree tree, Arguments userVariables, JMeterRecorder recorder)
{
    Binding binding = new Binding();
    binding.setVariable(ScriptBindingConstants.LOGGER, LOG);
    binding.setVariable(ScriptBindingConstants.SAMPLER, sampler);
    binding.setVariable(ScriptBindingConstants.TREE, tree);
    binding.setVariable(ScriptBindingConstants.CONTEXT, recorder.getContext());
    binding.setVariable(ScriptBindingConstants.JSFLIGHT, JMeterJSFlightBridge.getInstance());
    binding.setVariable(ScriptBindingConstants.USER_VARIABLES, userVariables);
    binding.setVariable(ScriptBindingConstants.CLASSLOADER, classLoader);

    Script compiledProcessScript = ScriptEngine.getScript(getScenarioProcessorScript());
    if (compiledProcessScript == null)
    {
        return;
    }
    compiledProcessScript.setBinding(binding);
    LOG.info("Run compiled script");
    try {
        compiledProcessScript.run();
    } catch (Throwable throwable) {
        LOG.error(throwable.getMessage(), throwable);
    }
}
 
Example #4
Source File: HTTP2Sampler.java    From jmeter-http2-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void addTestElement(TestElement el) {
    if (el instanceof HeaderManager) {
        HeaderManager value = (HeaderManager) el;
        HeaderManager currentHeaderManager = getHeaderManager();
        if (currentHeaderManager != null) {
            value = currentHeaderManager.merge(value, true);
        }
        setProperty(new TestElementProperty(HTTPSamplerBase.HEADER_MANAGER, value));
    } else {
        super.addTestElement(el);
    }
}
 
Example #5
Source File: HTTP2Sampler.java    From jmeter-http2-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public SampleResult sample(Entry e)
{
    log.debug("sample()");

    // Load test elements
    HeaderManager headerManager = (HeaderManager)getProperty(HTTPSamplerBase.HEADER_MANAGER).getObjectValue();

    // Send H2 request
    NettyHttp2Client client = new NettyHttp2Client(getMethod(), getDomain(), getPort(), getPath(), headerManager);
    SampleResult res = client.request();
    res.setSampleLabel(getName());

    return res;
}
 
Example #6
Source File: JMeterProxyControl.java    From jsflight with Apache License 2.0 5 votes vote down vote up
private boolean filterUrl(HTTPSamplerBase sampler)
{
    String domain = sampler.getDomain();
    if (domain == null || domain.length() == 0)
    {
        return false;
    }

    String url = generateMatchUrl(sampler);
    CollectionProperty includePatterns = getIncludePatterns();
    if (includePatterns.size() > 0)
    {
        if (!matchesPatterns(url, includePatterns))
        {
            return false;
        }
    }

    CollectionProperty excludePatterns = getExcludePatterns();
    if (excludePatterns.size() > 0)
    {
        if (matchesPatterns(url, excludePatterns))
        {
            return false;
        }
    }

    return true;
}
 
Example #7
Source File: JMeterProxyControl.java    From jsflight with Apache License 2.0 5 votes vote down vote up
private void placeSampler(final HTTPSamplerBase sampler, final TestElement[] subConfigs, final TestElement myTarget)
{
    try
    {
        JMeterUtils.runSafe(() -> myTarget.addTestElement(sampler));
    }
    catch (Exception e)
    {
        JMeterUtils.reportErrorToUser(e.getMessage());
    }
}
 
Example #8
Source File: JMeterProxyControl.java    From jsflight with Apache License 2.0 5 votes vote down vote up
/**
 * Remove from the sampler all values which match the one provided by the
 * first configuration in the given collection which provides a value for
 * that property.
 *
 * @param sampler        Sampler to remove values from.
 * @param configurations ConfigTestElements in descending priority.
 */
private void removeValuesFromSampler(HTTPSamplerBase sampler, Collection<ConfigTestElement> configurations)
{
    for (PropertyIterator props = sampler.propertyIterator(); props.hasNext();)
    {
        JMeterProperty prop = props.next();
        String name = prop.getName();
        String value = prop.getStringValue();

        // There's a few properties which are excluded from this processing:
        if (name.equals(TestElement.ENABLED) || name.equals(TestElement.GUI_CLASS) || name.equals(TestElement.NAME)
                || name.equals(TestElement.TEST_CLASS))
        {
            continue; // go on with next property.
        }

        for (ConfigTestElement config : configurations)
        {
            String configValue = config.getPropertyAsString(name);

            if (configValue != null && configValue.length() > 0)
            {
                if (configValue.equals(value))
                {
                    sampler.setProperty(name, ""); // $NON-NLS-1$
                }
                // Property was found in a config element. Whether or not
                // it matched the value in the sampler, we're done with
                // this property -- don't look at lower-priority configs:
                break;
            }
        }
    }
}
 
Example #9
Source File: JMeterProxyControl.java    From jsflight with Apache License 2.0 5 votes vote down vote up
private String generateMatchUrl(HTTPSamplerBase sampler)
{
    StringBuilder buf = new StringBuilder(sampler.getDomain());
    buf.append(':'); // $NON-NLS-1$
    buf.append(sampler.getPort());
    buf.append(sampler.getPath());
    if (sampler.getQueryString().length() > 0)
    {
        buf.append('?'); // $NON-NLS-1$
        buf.append(sampler.getQueryString());
    }
    return buf.toString();
}
 
Example #10
Source File: JMeterScriptProcessor.java    From jsflight with Apache License 2.0 5 votes vote down vote up
/**
 * Post process sample with groovy script.
 *
 * @param sampler
 * @param result
 * @param recorder
 * @return is sample ok
 */
public boolean processSampleDuringRecord(HTTPSamplerBase sampler, SampleResult result, JMeterRecorder recorder)
{
    Binding binding = new Binding();
    binding.setVariable(ScriptBindingConstants.LOGGER, LOG);
    binding.setVariable(ScriptBindingConstants.SAMPLER, sampler);
    binding.setVariable(ScriptBindingConstants.SAMPLE, result);
    binding.setVariable(ScriptBindingConstants.CONTEXT, recorder.getContext());
    binding.setVariable(ScriptBindingConstants.JSFLIGHT, JMeterJSFlightBridge.getInstance());
    binding.setVariable(ScriptBindingConstants.CLASSLOADER, classLoader);

    Script script = ScriptEngine.getScript(getStepProcessorScript());
    if (script == null)
    {
        LOG.warn(sampler.getName() + ". No script found. Default result is " + SHOULD_BE_PROCESSED_DEFAULT);
        return SHOULD_BE_PROCESSED_DEFAULT;
    }
    script.setBinding(binding);
    LOG.info(sampler.getName() + ". Running compiled script");
    Object scriptResult = script.run();

    boolean shouldBeProcessed;
    if (scriptResult != null && scriptResult instanceof Boolean)
    {
        shouldBeProcessed = (boolean)scriptResult;
        LOG.info(sampler.getName() + ". Script result " + shouldBeProcessed);
    }
    else
    {
        shouldBeProcessed = SHOULD_BE_PROCESSED_DEFAULT;
        LOG.warn(sampler.getName() + ". Script result UNDEFINED. Default result is " + SHOULD_BE_PROCESSED_DEFAULT);
    }

    return shouldBeProcessed;
}
 
Example #11
Source File: ParallelHTTPSamplerMock.java    From jmeter-bzm-plugins with Apache License 2.0 4 votes vote down vote up
public HCMock(HTTPSamplerBase testElement) {
    super(testElement);
}
 
Example #12
Source File: HTTP2Sampler.java    From jmeter-http2-plugin with Apache License 2.0 4 votes vote down vote up
private HeaderManager getHeaderManager() {
    return (HeaderManager)getProperty(HTTPSamplerBase.HEADER_MANAGER).getObjectValue();
}
 
Example #13
Source File: JMeterProxyControl.java    From jsflight with Apache License 2.0 4 votes vote down vote up
/**
 * Receives the recorded sampler from the proxy server for placing in the
 * test tree; this is skipped if the sampler is null (e.g. for recording SSL errors)
 * Always sends the result to any registered sample listeners.
 *
 * @param sampler    the sampler, may be null
 * @param subConfigs the configuration elements to be added (e.g. header namager)
 * @param result     the sample result, not null
 *                   TODO param serverResponse to be added to allow saving of the
 *                   server's response while recording.
 */
public synchronized void deliverSampler(final HTTPSamplerBase sampler, final TestElement[] subConfigs,
        final SampleResult result)
{
    if (sampler != null)
    {
        if (ATTEMPT_REDIRECT_DISABLING && (samplerRedirectAutomatically || samplerFollowRedirects))
        {
            if (result instanceof HTTPSampleResult)
            {
                final HTTPSampleResult httpSampleResult = (HTTPSampleResult)result;
                final String urlAsString = httpSampleResult.getUrlAsString();
                if (urlAsString.equals(LAST_REDIRECT))
                { // the url matches the last redirect
                    sampler.setEnabled(false);
                    sampler.setComment("Detected a redirect from the previous sample");
                }
                else
                { // this is not the result of a redirect
                    LAST_REDIRECT = null; // so break the chain
                }
                if (httpSampleResult.isRedirect())
                { // Save Location so resulting sample can be disabled
                    if (LAST_REDIRECT == null)
                    {
                        sampler.setComment("Detected the start of a redirect chain");
                    }
                    LAST_REDIRECT = httpSampleResult.getRedirectLocation();
                }
                else
                {
                    LAST_REDIRECT = null;
                }
            }
        }
        if (filterContentType(result) && filterUrl(sampler))
        {
            if (currentSamplerIndex >= maxSamplersPerJmx)
            {
                recorder.splitScenario();
                currentSamplerIndex = 0;
            }
            TestElement myTarget = target;
            sampler.setAutoRedirects(samplerRedirectAutomatically);
            sampler.setFollowRedirects(samplerFollowRedirects);
            sampler.setUseKeepAlive(useKeepAlive);
            sampler.setImageParser(samplerDownloadImages);

            Authorization authorization = createAuthorization(subConfigs, sampler);

            placeSampler(sampler, subConfigs, myTarget);
            currentSamplerIndex++;
        }
        else
        {
            if (LOG.isDebugEnabled())
            {
                LOG.debug("Sample excluded based on url or content-type: " + result.getUrlAsString() + " - "
                        + result.getContentType());
            }
            result.setSampleLabel("[" + result.getSampleLabel() + "]");
        }
    }
}