Search in sources :

Example 1 with PropertyIterator

use of org.apache.jmeter.testelement.property.PropertyIterator in project jmeter by apache.

the class HTTPHC4Impl method sendPostData.

// TODO needs cleaning up
/**
     * 
     * @param post {@link HttpPost}
     * @return String posted body if computable
     * @throws IOException if sending the data fails due to I/O
     */
protected String sendPostData(HttpPost post) throws IOException {
    // Buffer to hold the post body, except file content
    StringBuilder postedBody = new StringBuilder(1000);
    HTTPFileArg[] files = getHTTPFiles();
    final String contentEncoding = getContentEncodingOrNull();
    final boolean haveContentEncoding = contentEncoding != null;
    // application/x-www-form-urlencoded post request
    if (getUseMultipartForPost()) {
        // If a content encoding is specified, we use that as the
        // encoding of any parameter values
        Charset charset = null;
        if (haveContentEncoding) {
            charset = Charset.forName(contentEncoding);
        } else {
            charset = MIME.DEFAULT_CHARSET;
        }
        if (log.isDebugEnabled()) {
            log.debug("Building multipart with:getDoBrowserCompatibleMultipart(): {}, with charset:{}, haveContentEncoding:{}", getDoBrowserCompatibleMultipart(), charset, haveContentEncoding);
        }
        // Write the request to our own stream
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setCharset(charset);
        if (getDoBrowserCompatibleMultipart()) {
            multipartEntityBuilder.setLaxMode();
        } else {
            multipartEntityBuilder.setStrictMode();
        }
        // Add any parameters
        for (JMeterProperty jMeterProperty : getArguments()) {
            HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
            String parameterName = arg.getName();
            if (arg.isSkippable(parameterName)) {
                continue;
            }
            StringBody stringBody = new StringBody(arg.getValue(), ContentType.create("text/plain", charset));
            FormBodyPart formPart = FormBodyPartBuilder.create(parameterName, stringBody).build();
            multipartEntityBuilder.addPart(formPart);
        }
        // Add any files
        // Cannot retrieve parts once added to the MultiPartEntity, so have to save them here.
        ViewableFileBody[] fileBodies = new ViewableFileBody[files.length];
        for (int i = 0; i < files.length; i++) {
            HTTPFileArg file = files[i];
            File reservedFile = FileServer.getFileServer().getResolvedFile(file.getPath());
            fileBodies[i] = new ViewableFileBody(reservedFile, file.getMimeType());
            multipartEntityBuilder.addPart(file.getParamName(), fileBodies[i]);
        }
        HttpEntity entity = multipartEntityBuilder.build();
        post.setEntity(entity);
        if (entity.isRepeatable()) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            for (ViewableFileBody fileBody : fileBodies) {
                fileBody.hideFileData = true;
            }
            entity.writeTo(bos);
            for (ViewableFileBody fileBody : fileBodies) {
                fileBody.hideFileData = false;
            }
            bos.flush();
            // We get the posted bytes using the encoding used to create it
            postedBody.append(bos.toString(// $NON-NLS-1$ this is the default used by HttpClient
            contentEncoding == null ? // $NON-NLS-1$ this is the default used by HttpClient
            "US-ASCII" : contentEncoding));
            bos.close();
        } else {
            // $NON-NLS-1$
            postedBody.append("<Multipart was not repeatable, cannot view what was sent>");
        }
    //            // Set the content type TODO - needed?
    //            String multiPartContentType = multiPart.getContentType().getValue();
    //            post.setHeader(HEADER_CONTENT_TYPE, multiPartContentType);
    } else {
        // not multipart
        // Check if the header manager had a content type header
        // This allows the user to specify his own content-type for a POST request
        Header contentTypeHeader = post.getFirstHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        boolean hasContentTypeHeader = contentTypeHeader != null && contentTypeHeader.getValue() != null && contentTypeHeader.getValue().length() > 0;
        // TODO: needs a multiple file upload scenerio
        if (!hasArguments() && getSendFileAsPostBody()) {
            // If getSendFileAsPostBody returned true, it's sure that file is not null
            HTTPFileArg file = files[0];
            if (!hasContentTypeHeader) {
                // Allow the mimetype of the file to control the content type
                if (file.getMimeType() != null && file.getMimeType().length() > 0) {
                    post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
                } else {
                    post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                }
            }
            // TODO is null correct?
            FileEntity fileRequestEntity = new FileEntity(new File(file.getPath()), (ContentType) null);
            post.setEntity(fileRequestEntity);
            // We just add placeholder text for file content
            postedBody.append("<actual file content, not shown here>");
        } else {
            // the post body will be encoded in the specified content encoding
            if (haveContentEncoding) {
                post.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, contentEncoding);
            }
            // just send all the values as the post body
            if (getSendParameterValuesAsPostBody()) {
                // TODO: needs a multiple file upload scenerio
                if (!hasContentTypeHeader) {
                    HTTPFileArg file = files.length > 0 ? files[0] : null;
                    if (file != null && file.getMimeType() != null && file.getMimeType().length() > 0) {
                        post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
                    } else {
                        // TODO - is this the correct default?
                        post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                    }
                }
                // Just append all the parameter values, and use that as the post body
                StringBuilder postBody = new StringBuilder();
                for (JMeterProperty jMeterProperty : getArguments()) {
                    HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
                    // Note: if "Encoded?" is not selected, arg.getEncodedValue is equivalent to arg.getValue
                    if (haveContentEncoding) {
                        postBody.append(arg.getEncodedValue(contentEncoding));
                    } else {
                        postBody.append(arg.getEncodedValue());
                    }
                }
                // Let StringEntity perform the encoding
                StringEntity requestEntity = new StringEntity(postBody.toString(), contentEncoding);
                post.setEntity(requestEntity);
                postedBody.append(postBody.toString());
            } else {
                // Set the content type
                if (!hasContentTypeHeader) {
                    post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                }
                // Add the parameters
                PropertyIterator args = getArguments().iterator();
                List<NameValuePair> nvps = new ArrayList<>();
                String urlContentEncoding = contentEncoding;
                if (urlContentEncoding == null || urlContentEncoding.length() == 0) {
                    // Use the default encoding for urls
                    urlContentEncoding = EncoderCache.URL_ARGUMENT_ENCODING;
                }
                while (args.hasNext()) {
                    HTTPArgument arg = (HTTPArgument) args.next().getObjectValue();
                    // The HTTPClient always urlencodes both name and value,
                    // so if the argument is already encoded, we have to decode
                    // it before adding it to the post request
                    String parameterName = arg.getName();
                    if (arg.isSkippable(parameterName)) {
                        continue;
                    }
                    String parameterValue = arg.getValue();
                    if (!arg.isAlwaysEncoded()) {
                        // The value is already encoded by the user
                        // Must decode the value now, so that when the
                        // httpclient encodes it, we end up with the same value
                        // as the user had entered.
                        parameterName = URLDecoder.decode(parameterName, urlContentEncoding);
                        parameterValue = URLDecoder.decode(parameterValue, urlContentEncoding);
                    }
                    // Add the parameter, httpclient will urlencode it
                    nvps.add(new BasicNameValuePair(parameterName, parameterValue));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps, urlContentEncoding);
                post.setEntity(entity);
                if (entity.isRepeatable()) {
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    post.getEntity().writeTo(bos);
                    bos.flush();
                    // We get the posted bytes using the encoding used to create it
                    postedBody.append(bos.toString(contentEncoding != null ? contentEncoding : SampleResult.DEFAULT_HTTP_ENCODING));
                    bos.close();
                } else {
                    postedBody.append("<RequestEntity was not repeatable, cannot view what was sent>");
                }
            }
        }
    }
    return postedBody.toString();
}
Also used : MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) JMeterProperty(org.apache.jmeter.testelement.property.JMeterProperty) HttpEntity(org.apache.http.HttpEntity) ArrayList(java.util.ArrayList) FormBodyPart(org.apache.http.entity.mime.FormBodyPart) StringEntity(org.apache.http.entity.StringEntity) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) FileEntity(org.apache.http.entity.FileEntity) PropertyIterator(org.apache.jmeter.testelement.property.PropertyIterator) Charset(java.nio.charset.Charset) ByteArrayOutputStream(java.io.ByteArrayOutputStream) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) HTTPFileArg(org.apache.jmeter.protocol.http.util.HTTPFileArg) HTTPArgument(org.apache.jmeter.protocol.http.util.HTTPArgument) Header(org.apache.http.Header) BufferedHeader(org.apache.http.message.BufferedHeader) StringBody(org.apache.http.entity.mime.content.StringBody) File(java.io.File)

Example 2 with PropertyIterator

use of org.apache.jmeter.testelement.property.PropertyIterator in project jmeter-plugins by undera.

the class FreeFormArrivalsThreadGroupGui method updateChart.

protected void updateChart(AbstractDynamicThreadGroup tg) {
    FreeFormArrivalsThreadGroup atg = (FreeFormArrivalsThreadGroup) tg;
    CollectionProperty data = atg.getData();
    chartModel.clear();
    previewChart.clearErrorMessage();
    AbstractGraphRow row = new GraphRowExactValues();
    row.setColor(getRowColor());
    row.setDrawLine(true);
    row.setMarkerSize(AbstractGraphRow.MARKER_SIZE_NONE);
    row.setDrawThickLines(true);
    // initial value to force min Y
    row.add(0, 0);
    JMeterVariableEvaluator evaluator = new JMeterVariableEvaluator();
    int offset = 0;
    double totalArrivals = 0;
    PropertyIterator it = data.iterator();
    while (it.hasNext()) {
        CollectionProperty record = (CollectionProperty) it.next();
        double from = evaluator.getDouble(record.get(0));
        double to = evaluator.getDouble(record.get(1));
        double during = evaluator.getDouble(record.get(2));
        row.add(offset * 1000, from);
        offset += during * tg.getUnitFactor();
        row.add(offset * 1000, to);
        totalArrivals += during * from + during * (to - from) / 2;
    }
    previewChart.setxAxisLabelRenderer(new DateTimeRenderer(DateTimeRenderer.HHMMSS, 0));
    chartModel.put(getRowLabel(totalArrivals), row);
}
Also used : AbstractGraphRow(kg.apc.charting.AbstractGraphRow) CollectionProperty(org.apache.jmeter.testelement.property.CollectionProperty) DateTimeRenderer(kg.apc.charting.DateTimeRenderer) PropertyIterator(org.apache.jmeter.testelement.property.PropertyIterator) JMeterVariableEvaluator(kg.apc.jmeter.JMeterVariableEvaluator) GraphRowExactValues(kg.apc.charting.rows.GraphRowExactValues)

Example 3 with PropertyIterator

use of org.apache.jmeter.testelement.property.PropertyIterator in project jmeter-plugins by undera.

the class PageDataExtractorOverTimeGui method add.

@Override
public void add(SampleResult res) {
    super.add(res);
    if (regExps == null && cmdRegExps == null) {
        return;
    }
    String pageBody = res.getResponseDataAsString();
    long time = normalizeTime(res.getEndTime());
    if (cmdRegExps == null) {
        PropertyIterator iter = regExps.iterator();
        while (iter.hasNext()) {
            CollectionProperty props = (CollectionProperty) iter.next();
            String label = props.get(0).getStringValue();
            String regExpValue = props.get(1).getStringValue();
            Boolean isDelta = props.get(2).getBooleanValue();
            Boolean isLabelRegExp = props.get(3).getBooleanValue();
            if (isLabelRegExp) {
                processPageRegExpLabel(pageBody, label, regExpValue, isDelta, time);
            } else {
                processPageLabel(pageBody, label, regExpValue, isDelta, time);
            }
        }
    } else {
        Iterator<Object> regExpIter = cmdRegExps.iterator();
        while (regExpIter.hasNext()) {
            String label = (String) regExpIter.next();
            String regExpValue = (String) regExpIter.next();
            boolean isDelta = (Boolean) regExpIter.next();
            boolean isLabelRegExp = (Boolean) regExpIter.next();
            if (isLabelRegExp) {
                processPageRegExpLabel(pageBody, label, regExpValue, isDelta, time);
            } else {
                processPageLabel(pageBody, label, regExpValue, isDelta, time);
            }
        }
    }
    updateGui(null);
}
Also used : CollectionProperty(org.apache.jmeter.testelement.property.CollectionProperty) PropertyIterator(org.apache.jmeter.testelement.property.PropertyIterator)

Example 4 with PropertyIterator

use of org.apache.jmeter.testelement.property.PropertyIterator in project jmeter-plugins by undera.

the class CompositeGraphGui method setConfig.

private void setConfig(CollectionProperty properties) {
    PropertyIterator iter = properties.iterator();
    CollectionProperty testplans = (CollectionProperty) iter.next();
    CollectionProperty rows = (CollectionProperty) iter.next();
    if (rows.size() > 0) {
        PropertyIterator iterTestplans = testplans.iterator();
        PropertyIterator iterRows = rows.iterator();
        while (iterTestplans.hasNext() && iterRows.hasNext()) {
            String testplan = iterTestplans.next().getStringValue();
            String row = iterRows.next().getStringValue();
            compositeRowsSelectorPanel.addItemsToComposite(testplan, row);
        }
    }
}
Also used : CollectionProperty(org.apache.jmeter.testelement.property.CollectionProperty) PropertyIterator(org.apache.jmeter.testelement.property.PropertyIterator)

Example 5 with PropertyIterator

use of org.apache.jmeter.testelement.property.PropertyIterator in project jmeter by apache.

the class HTTPHC4Impl method createUrlEncodedFormEntity.

/**
 * Create UrlEncodedFormEntity from parameters
 * @param contentEncoding Content encoding may be null or empty
 * @return {@link UrlEncodedFormEntity}
 * @throws UnsupportedEncodingException
 */
private UrlEncodedFormEntity createUrlEncodedFormEntity(final String contentEncoding) throws UnsupportedEncodingException {
    // It is a normal request, with parameter names and values
    // Add the parameters
    PropertyIterator args = getArguments().iterator();
    List<NameValuePair> nvps = new ArrayList<>();
    String urlContentEncoding = contentEncoding;
    if (urlContentEncoding == null || urlContentEncoding.length() == 0) {
        // Use the default encoding for urls
        urlContentEncoding = EncoderCache.URL_ARGUMENT_ENCODING;
    }
    while (args.hasNext()) {
        HTTPArgument arg = (HTTPArgument) args.next().getObjectValue();
        // The HTTPClient always urlencodes both name and value,
        // so if the argument is already encoded, we have to decode
        // it before adding it to the post request
        String parameterName = arg.getName();
        if (arg.isSkippable(parameterName)) {
            continue;
        }
        String parameterValue = arg.getValue();
        if (!arg.isAlwaysEncoded()) {
            // The value is already encoded by the user
            // Must decode the value now, so that when the
            // httpclient encodes it, we end up with the same value
            // as the user had entered.
            parameterName = URLDecoder.decode(parameterName, urlContentEncoding);
            parameterValue = URLDecoder.decode(parameterValue, urlContentEncoding);
        }
        // Add the parameter, httpclient will urlencode it
        nvps.add(new BasicNameValuePair(parameterName, parameterValue));
    }
    return new UrlEncodedFormEntity(nvps, urlContentEncoding);
}
Also used : NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HTTPArgument(org.apache.jmeter.protocol.http.util.HTTPArgument) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) PropertyIterator(org.apache.jmeter.testelement.property.PropertyIterator) ArrayList(java.util.ArrayList) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity)

Aggregations

PropertyIterator (org.apache.jmeter.testelement.property.PropertyIterator)36 JMeterProperty (org.apache.jmeter.testelement.property.JMeterProperty)12 CollectionProperty (org.apache.jmeter.testelement.property.CollectionProperty)8 ArrayList (java.util.ArrayList)4 Argument (org.apache.jmeter.config.Argument)4 HTTPArgument (org.apache.jmeter.protocol.http.util.HTTPArgument)3 Test (org.junit.jupiter.api.Test)3 BasicAttribute (javax.naming.directory.BasicAttribute)2 ModificationItem (javax.naming.directory.ModificationItem)2 NameValuePair (org.apache.http.NameValuePair)2 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)2 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)2 Customizer (java.beans.Customizer)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 MalformedURLException (java.net.MalformedURLException)1 Charset (java.nio.charset.Charset)1 HashMap (java.util.HashMap)1 LinkedHashMap (java.util.LinkedHashMap)1