Search in sources :

Example 21 with Arguments

use of org.apache.jmeter.config.Arguments in project jmeter by apache.

the class HTTPHC4Impl method sendEntityData.

/**
 * Creates the entity data to be sent.
 * <p>
 * If there is a file entry with a non-empty MIME type we use that to
 * set the request Content-Type header, otherwise we default to whatever
 * header is present from a Header Manager.
 * <p>
 * If the content charset {@link #getContentEncoding()} is null or empty
 * we use the HC4 default provided by {@link HTTP#DEF_CONTENT_CHARSET} which is
 * ISO-8859-1.
 *
 * @param entity to be processed, e.g. PUT or PATCH
 * @return the entity content, may be empty
 * @throws  UnsupportedEncodingException for invalid charset name
 * @throws IOException cannot really occur for ByteArrayOutputStream methods
 */
protected String sendEntityData(HttpEntityEnclosingRequestBase entity) throws IOException {
    boolean hasEntityBody = false;
    final HTTPFileArg[] files = getHTTPFiles();
    // Allow the mimetype of the file to control the content type
    // This is not obvious in GUI if you are not uploading any files,
    // but just sending the content of nameless parameters
    final HTTPFileArg file = files.length > 0 ? files[0] : null;
    String contentTypeValue;
    if (file != null && file.getMimeType() != null && file.getMimeType().length() > 0) {
        contentTypeValue = file.getMimeType();
        // we provide the MIME type here
        entity.setHeader(HEADER_CONTENT_TYPE, contentTypeValue);
    }
    // Check for local contentEncoding (charset) override; fall back to default for content body
    // we do this here rather so we can use the same charset to retrieve the data
    final String charset = getContentEncoding(HTTP.DEF_CONTENT_CHARSET.name());
    // If there are no arguments, we can send a file as the body of the request
    if (!hasArguments() && getSendFileAsPostBody()) {
        hasEntityBody = true;
        // If getSendFileAsPostBody returned true, it's sure that file is not null
        File reservedFile = FileServer.getFileServer().getResolvedFile(files[0].getPath());
        // no need for content-type here
        FileEntity fileRequestEntity = new FileEntity(reservedFile);
        entity.setEntity(fileRequestEntity);
    } else // just send all the values as the entity body
    if (getSendParameterValuesAsPostBody()) {
        hasEntityBody = true;
        // Just append all the parameter values, and use that as the entity body
        Arguments arguments = getArguments();
        StringBuilder entityBodyContent = new StringBuilder(arguments.getArgumentCount() * 15);
        for (JMeterProperty jMeterProperty : arguments) {
            HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
            // Note: if "Encoded?" is not selected, arg.getEncodedValue is equivalent to arg.getValue
            if (charset != null) {
                entityBodyContent.append(arg.getEncodedValue(charset));
            } else {
                entityBodyContent.append(arg.getEncodedValue());
            }
        }
        StringEntity requestEntity = new StringEntity(entityBodyContent.toString(), charset);
        entity.setEntity(requestEntity);
    } else if (hasArguments()) {
        hasEntityBody = true;
        entity.setEntity(createUrlEncodedFormEntity(getContentEncodingOrNull()));
    }
    // Check if we have any content to send for body
    if (hasEntityBody) {
        // If the request entity is repeatable, we can send it first to
        // our own stream, so we can return it
        final HttpEntity entityEntry = entity.getEntity();
        // Buffer to hold the entity body
        StringBuilder entityBody = new StringBuilder(65);
        writeEntityToSB(entityBody, entityEntry, EMPTY_FILE_BODIES, charset);
        return entityBody.toString();
    }
    // may be the empty string
    return "";
}
Also used : StringEntity(org.apache.http.entity.StringEntity) FileEntity(org.apache.http.entity.FileEntity) JMeterProperty(org.apache.jmeter.testelement.property.JMeterProperty) HTTPArgument(org.apache.jmeter.protocol.http.util.HTTPArgument) HttpEntity(org.apache.http.HttpEntity) Arguments(org.apache.jmeter.config.Arguments) HTTPFileArg(org.apache.jmeter.protocol.http.util.HTTPFileArg) File(java.io.File)

Example 22 with Arguments

use of org.apache.jmeter.config.Arguments in project jmeter by apache.

the class ProxyControl method deliverSampler.

/**
 * 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 testElements the test elements to be added (e.g. header manager) under the Sampler
 * @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[] testElements, final SampleResult result) {
    boolean notifySampleListeners = true;
    if (sampler != null) {
        if (USE_REDIRECT_DISABLING && (samplerRedirectAutomatically || samplerFollowRedirects) && 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
                // so break the chain
                LAST_REDIRECT = null;
            }
            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)) {
            JMeterTreeNode myTarget = findTargetControllerNode();
            // OK, because find only returns correct element types
            @SuppressWarnings("unchecked") Collection<ConfigTestElement> defaultConfigurations = (Collection<ConfigTestElement>) findApplicableElements(myTarget, ConfigTestElement.class, false);
            // OK, because find only returns correct element types
            @SuppressWarnings("unchecked") Collection<Arguments> userDefinedVariables = (Collection<Arguments>) findApplicableElements(myTarget, Arguments.class, true);
            removeValuesFromSampler(sampler, defaultConfigurations);
            replaceValues(sampler, testElements, userDefinedVariables);
            sampler.setAutoRedirects(samplerRedirectAutomatically);
            sampler.setFollowRedirects(samplerFollowRedirects);
            sampler.setUseKeepAlive(useKeepAlive);
            sampler.setImageParser(samplerDownloadImages);
            Authorization authorization = createAuthorization(testElements, result);
            if (authorization != null) {
                setAuthorization(authorization, myTarget);
            }
            sampleQueue.add(new SamplerInfo(sampler, testElements, myTarget, getPrefixHTTPSampleName(), groupingMode));
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Sample excluded based on url or content-type: {} - {}", result.getUrlAsString(), result.getContentType());
            }
            notifySampleListeners = notifyChildSamplerListenersOfFilteredSamples;
            result.setSampleLabel("[" + result.getSampleLabel() + "]");
        }
    }
    if (notifySampleListeners) {
        // SampleEvent is not passed JMeterVariables, because they don't make sense for Proxy Recording
        notifySampleListeners(new SampleEvent(result, "WorkBench"));
    } else {
        log.debug("Sample not delivered to Child Sampler Listener based on url or content-type: {} - {}", result.getUrlAsString(), result.getContentType());
    }
}
Also used : Arguments(org.apache.jmeter.config.Arguments) SampleEvent(org.apache.jmeter.samplers.SampleEvent) Authorization(org.apache.jmeter.protocol.http.control.Authorization) HTTPSampleResult(org.apache.jmeter.protocol.http.sampler.HTTPSampleResult) JMeterTreeNode(org.apache.jmeter.gui.tree.JMeterTreeNode) Collection(java.util.Collection) ConfigTestElement(org.apache.jmeter.config.ConfigTestElement)

Example 23 with Arguments

use of org.apache.jmeter.config.Arguments in project jmeter by apache.

the class ProxyControl method findApplicableElements.

/**
 * Finds all configuration objects of the given class applicable to the
 * recorded samplers, that is:
 * <ul>
 * <li>All such elements directly within the HTTP(S) Test Script Recorder (these have
 * the highest priority).
 * <li>All such elements directly within the target controller (higher
 * priority) or directly within any containing controller (lower priority),
 * including the Test Plan itself (lowest priority).
 * </ul>
 *
 * @param myTarget  tree node for the recording target controller.
 * @param myClass   Class of the elements to be found.
 * @param ascending true if returned elements should be ordered in ascending
 *                  priority, false if they should be in descending priority.
 * @return a collection of applicable objects of the given class.
 */
// TODO - could be converted to generic class?
@SuppressWarnings("JdkObsolete")
private Collection<?> findApplicableElements(JMeterTreeNode myTarget, Class<? extends TestElement> myClass, boolean ascending) {
    JMeterTreeModel treeModel = getJmeterTreeModel();
    Deque<TestElement> elements = new ArrayDeque<>();
    // Look for elements directly within the HTTP proxy:
    JMeterTreeNode node = treeModel.getNodeOf(this);
    if (node != null) {
        Enumeration<?> kids = node.children();
        while (kids.hasMoreElements()) {
            JMeterTreeNode subNode = (JMeterTreeNode) kids.nextElement();
            if (subNode.isEnabled()) {
                TestElement element = (TestElement) subNode.getUserObject();
                if (myClass.isInstance(element)) {
                    if (ascending) {
                        elements.addFirst(element);
                    } else {
                        elements.add(element);
                    }
                }
            }
        }
    }
    // Look for arguments elements in the target controller or higher up:
    for (JMeterTreeNode controller = myTarget; controller != null; controller = (JMeterTreeNode) controller.getParent()) {
        Enumeration<?> kids = controller.children();
        while (kids.hasMoreElements()) {
            JMeterTreeNode subNode = (JMeterTreeNode) kids.nextElement();
            if (subNode.isEnabled()) {
                TestElement element = (TestElement) subNode.getUserObject();
                if (myClass.isInstance(element)) {
                    log.debug("Applicable: {}", element.getName());
                    if (ascending) {
                        elements.addFirst(element);
                    } else {
                        elements.add(element);
                    }
                }
                // Special case for the TestPlan's Arguments sub-element:
                if (element instanceof TestPlan) {
                    TestPlan tp = (TestPlan) element;
                    Arguments args = tp.getArguments();
                    if (myClass.isInstance(args)) {
                        if (ascending) {
                            elements.addFirst(args);
                        } else {
                            elements.add(args);
                        }
                    }
                }
            }
        }
    }
    return elements;
}
Also used : JMeterTreeModel(org.apache.jmeter.gui.tree.JMeterTreeModel) TestPlan(org.apache.jmeter.testelement.TestPlan) Arguments(org.apache.jmeter.config.Arguments) JMeterTreeNode(org.apache.jmeter.gui.tree.JMeterTreeNode) TestElement(org.apache.jmeter.testelement.TestElement) ConfigTestElement(org.apache.jmeter.config.ConfigTestElement) NonTestElement(org.apache.jmeter.testelement.NonTestElement) ArrayDeque(java.util.ArrayDeque)

Example 24 with Arguments

use of org.apache.jmeter.config.Arguments in project jmeter by apache.

the class HtmlParsingUtils method isAnchorMatched.

/**
 * Check if anchor matches by checking against:
 * - protocol
 * - domain
 * - path
 * - parameter names
 *
 * @param newLink target to match
 * @param config pattern to match against
 *
 * @return true if target URL matches pattern URL
 */
public static boolean isAnchorMatched(HTTPSamplerBase newLink, HTTPSamplerBase config) {
    String query;
    try {
        query = URLDecoder.decode(newLink.getQueryString(), StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        // UTF-8 unsupported? You must be joking!
        log.error("UTF-8 encoding not supported!");
        throw new Error("Should not happen: " + e.toString(), e);
    }
    final Arguments arguments = config.getArguments();
    final Perl5Matcher matcher = JMeterUtils.getMatcher();
    final PatternCacheLRU patternCache = JMeterUtils.getPatternCache();
    if (!isEqualOrMatches(newLink.getProtocol(), config.getProtocol(), matcher, patternCache)) {
        return false;
    }
    final String domain = config.getDomain();
    if (domain != null && domain.length() > 0) {
        if (!isEqualOrMatches(newLink.getDomain(), domain, matcher, patternCache)) {
            return false;
        }
    }
    final String path = config.getPath();
    if (!newLink.getPath().equals(path) && !matcher.matches(newLink.getPath(), // $NON-NLS-1$
    patternCache.getPattern(// $NON-NLS-1$
    "[/]*" + path, Perl5Compiler.READ_ONLY_MASK))) {
        return false;
    }
    for (JMeterProperty argument : arguments) {
        Argument item = (Argument) argument.getObjectValue();
        final String name = item.getName();
        if (!query.contains(name + "=")) {
            // $NON-NLS-1$
            if (!matcher.contains(query, patternCache.getPattern(name, Perl5Compiler.READ_ONLY_MASK))) {
                return false;
            }
        }
    }
    return true;
}
Also used : JMeterProperty(org.apache.jmeter.testelement.property.JMeterProperty) Argument(org.apache.jmeter.config.Argument) Arguments(org.apache.jmeter.config.Arguments) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Perl5Matcher(org.apache.oro.text.regex.Perl5Matcher) PatternCacheLRU(org.apache.oro.text.PatternCacheLRU)

Example 25 with Arguments

use of org.apache.jmeter.config.Arguments in project jmeter by apache.

the class HTTPSamplerBase method replace.

/**
 * Replace by replaceBy in path and body (arguments) properties
 */
@Override
public int replace(String regex, String replaceBy, boolean caseSensitive) throws Exception {
    int totalReplaced = 0;
    for (JMeterProperty jMeterProperty : getArguments()) {
        HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
        totalReplaced += JOrphanUtils.replaceValue(regex, replaceBy, caseSensitive, arg.getValue(), arg::setValue);
    }
    totalReplaced += JOrphanUtils.replaceValue(regex, replaceBy, caseSensitive, getPath(), this::setPath);
    totalReplaced += JOrphanUtils.replaceValue(regex, replaceBy, caseSensitive, getDomain(), this::setDomain);
    for (String key : Arrays.asList(PORT, PROTOCOL)) {
        totalReplaced += JOrphanUtils.replaceValue(regex, replaceBy, caseSensitive, getPropertyAsString(key), s -> setProperty(key, s));
    }
    return totalReplaced;
}
Also used : HTTPFileArgs(org.apache.jmeter.protocol.http.util.HTTPFileArgs) Arrays(java.util.Arrays) HeaderManager(org.apache.jmeter.protocol.http.control.HeaderManager) MetricUtils(org.apache.jmeter.report.utils.MetricUtils) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) StringProperty(org.apache.jmeter.testelement.property.StringProperty) AuthManager(org.apache.jmeter.protocol.http.control.AuthManager) LoggerFactory(org.slf4j.LoggerFactory) SampleResult(org.apache.jmeter.samplers.SampleResult) TestElement(org.apache.jmeter.testelement.TestElement) StringUtils(org.apache.commons.lang3.StringUtils) DirectAccessByteArrayOutputStream(org.apache.jmeter.protocol.http.util.DirectAccessByteArrayOutputStream) Future(java.util.concurrent.Future) BooleanProperty(org.apache.jmeter.testelement.property.BooleanProperty) Map(java.util.Map) AsynSamplerResultHolder(org.apache.jmeter.protocol.http.sampler.ResourcesDownloader.AsynSamplerResultHolder) TestStateListener(org.apache.jmeter.testelement.TestStateListener) TestElementProperty(org.apache.jmeter.testelement.property.TestElementProperty) Cookie(org.apache.jmeter.protocol.http.control.Cookie) HTTPFileArg(org.apache.jmeter.protocol.http.util.HTTPFileArg) ConfigTestElement(org.apache.jmeter.config.ConfigTestElement) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Pattern(org.apache.oro.text.regex.Pattern) Set(java.util.Set) ConversionUtils(org.apache.jmeter.protocol.http.util.ConversionUtils) CollectionProperty(org.apache.jmeter.testelement.property.CollectionProperty) LoopIterationEvent(org.apache.jmeter.engine.event.LoopIterationEvent) IOUtils(org.apache.commons.io.IOUtils) EncoderCache(org.apache.jmeter.protocol.http.util.EncoderCache) List(java.util.List) AbstractSampler(org.apache.jmeter.samplers.AbstractSampler) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Argument(org.apache.jmeter.config.Argument) DNSCacheManager(org.apache.jmeter.protocol.http.control.DNSCacheManager) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HTTPConstants(org.apache.jmeter.protocol.http.util.HTTPConstants) JMeterUtils(org.apache.jmeter.util.JMeterUtils) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CookieManager(org.apache.jmeter.protocol.http.control.CookieManager) MalformedCachePatternException(org.apache.oro.text.MalformedCachePatternException) MessageDigest(java.security.MessageDigest) JOrphanUtils(org.apache.jorphan.util.JOrphanUtils) Callable(java.util.concurrent.Callable) HTTPConstantsInterface(org.apache.jmeter.protocol.http.util.HTTPConstantsInterface) ThreadListener(org.apache.jmeter.testelement.ThreadListener) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) JMeterContext(org.apache.jmeter.threads.JMeterContext) KeystoreConfig(org.apache.jmeter.config.KeystoreConfig) Entry(org.apache.jmeter.samplers.Entry) Arguments(org.apache.jmeter.config.Arguments) JMeterContextService(org.apache.jmeter.threads.JMeterContextService) JMeterProperty(org.apache.jmeter.testelement.property.JMeterProperty) CacheManager(org.apache.jmeter.protocol.http.control.CacheManager) OutputStream(java.io.OutputStream) PrintStream(java.io.PrintStream) BaseParser(org.apache.jmeter.protocol.http.parser.BaseParser) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) MalformedURLException(java.net.MalformedURLException) PropertyIterator(org.apache.jmeter.testelement.property.PropertyIterator) LinkExtractorParseException(org.apache.jmeter.protocol.http.parser.LinkExtractorParseException) IOException(java.io.IOException) HTTPArgument(org.apache.jmeter.protocol.http.util.HTTPArgument) Perl5Matcher(org.apache.oro.text.regex.Perl5Matcher) LinkExtractorParser(org.apache.jmeter.protocol.http.parser.LinkExtractorParser) ExecutionException(java.util.concurrent.ExecutionException) Replaceable(org.apache.jmeter.gui.Replaceable) Closeable(java.io.Closeable) TestIterationListener(org.apache.jmeter.testelement.TestIterationListener) Collections(java.util.Collections) IntegerProperty(org.apache.jmeter.testelement.property.IntegerProperty) InputStream(java.io.InputStream) JMeterProperty(org.apache.jmeter.testelement.property.JMeterProperty) HTTPArgument(org.apache.jmeter.protocol.http.util.HTTPArgument)

Aggregations

Arguments (org.apache.jmeter.config.Arguments)96 Test (org.junit.jupiter.api.Test)32 HTTPSamplerBase (org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase)18 SampleResult (org.apache.jmeter.samplers.SampleResult)17 Argument (org.apache.jmeter.config.Argument)15 HTTPArgument (org.apache.jmeter.protocol.http.util.HTTPArgument)10 JMeterProperty (org.apache.jmeter.testelement.property.JMeterProperty)8 HTTPFileArg (org.apache.jmeter.protocol.http.util.HTTPFileArg)7 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)7 ConfigTestElement (org.apache.jmeter.config.ConfigTestElement)6 TestElement (org.apache.jmeter.testelement.TestElement)6 TestElementProperty (org.apache.jmeter.testelement.property.TestElementProperty)5 Test (org.junit.Test)5 HTTPFileArgs (org.apache.jmeter.protocol.http.util.HTTPFileArgs)4 JMeterVariables (org.apache.jmeter.threads.JMeterVariables)4 IOException (java.io.IOException)3 URL (java.net.URL)3 Iterator (java.util.Iterator)3 JMeterTreeNode (org.apache.jmeter.gui.tree.JMeterTreeNode)3 CollectionProperty (org.apache.jmeter.testelement.property.CollectionProperty)3