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 "";
}
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());
}
}
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;
}
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;
}
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;
}
Aggregations