Example usage for org.apache.http.entity.mime MultipartEntity isRepeatable

List of usage examples for org.apache.http.entity.mime MultipartEntity isRepeatable

Introduction

In this page you can find the example usage for org.apache.http.entity.mime MultipartEntity isRepeatable.

Prototype

public boolean isRepeatable() 

Source Link

Usage

From source file:it.staiger.jmeter.protocol.http.sampler.HTTPHC4DynamicFilePost.java

/**
 * //from  w  w  w  .j  a v  a2s .  co  m
 * @param post {@link HttpPost}
 * @return String posted body if computable
 * @throws IOException if sending the data fails due to I/O
 */
@Override
protected String sendPostData(HttpPost post) throws IOException {
    // Buffer to hold the post body, except file content
    StringBuilder postedBody = new StringBuilder(1000);
    FileContentServer contentServer = FileContentServer.getServer();
    HTTPFileArg staticFiles[] = getHTTPFiles();
    HTTPFileArg dynFiles[] = testElement.getDynamicFiles();
    VariableFileArg variableFiles[] = testElement.getVariableFiles();
    String[] attachmentsNumber = null;
    boolean thresholdCheck = testElement.getRecordType() >= testElement.getThreshold();

    final String contentEncoding = getContentEncodingOrNull();
    final boolean haveContentEncoding = contentEncoding != null;
    boolean hasContent = false;

    // 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);
    }

    // Write the request to our own stream
    MultipartEntity multiPart = new MultipartEntity(
            getDoBrowserCompatibleMultipart() ? HttpMultipartMode.BROWSER_COMPATIBLE : HttpMultipartMode.STRICT,
            null, charset);
    // Create the parts
    // Add any parameters
    PropertyIterator args = getArguments().iterator();
    while (args.hasNext()) {
        HTTPArgument arg = (HTTPArgument) args.next().getObjectValue();
        String parameterName = arg.getName();
        if (arg.isSkippable(parameterName)) {
            continue;
        }
        FormBodyPart formPart;
        StringBody stringBody = new StringBody(arg.getValue(), charset);
        formPart = new FormBodyPart(arg.getName(), stringBody);
        multiPart.addPart(formPart);
        hasContent = true;
    }
    /*
     * set parameters controlled by threshold
     */
    if (!testElement.getArgumentThreshold() || thresholdCheck) {
        args = testElement.getOwnArguments().iterator();
        while (args.hasNext()) {
            HTTPArgument arg = (HTTPArgument) args.next().getObjectValue();
            String parameterName = arg.getName();
            if (arg.isSkippable(parameterName)) {
                continue;
            }
            FormBodyPart formPart;
            StringBody stringBody = new StringBody(arg.getValue(), charset);
            formPart = new FormBodyPart(arg.getName(), stringBody);
            multiPart.addPart(formPart);
            hasContent = true;
        }
    }

    // Add all files
    // Cannot retrieve parts once added to the MultiPartEntity, so have to save them here.
    ViewableByteBody[] viewableByteBodies = new ViewableByteBody[variableFiles.length + staticFiles.length
            + dynFiles.length];

    int i = 0;

    //Variable Files
    if (!testElement.getVariableThreshold() || thresholdCheck)
        for (int j = 0; j < variableFiles.length; j++, i++) {
            VariableFileArg file = variableFiles[j];

            viewableByteBodies[i] = new ViewableByteBody(file.getContent().getBytes(), file.getMimeType(),
                    file.getName());
            multiPart.addPart(file.getParamName(), viewableByteBodies[i]);
            hasContent = true;
        }

    //Static Files
    if (!testElement.getStaticThreshold() || thresholdCheck)
        for (i = 0; i < staticFiles.length; i++) {
            HTTPFileArg file = staticFiles[i];

            viewableByteBodies[i] = new ViewableByteBody(contentServer.getFileContent(file.getPath()),
                    file.getMimeType(), new File(file.getPath()).getName());
            multiPart.addPart(file.getParamName(), viewableByteBodies[i]);
            hasContent = true;
        }

    //Dynamic Files
    if (!testElement.getDynamicThreshold() || thresholdCheck) {

        attachmentsNumber = testElement.getAttachmentNumbers().split(",");

        for (int j = 0; j < attachmentsNumber.length && !attachmentsNumber[j].isEmpty(); i++, j++) {
            int fileNum = Integer.parseInt(attachmentsNumber[j]) - 1;
            if (fileNum >= dynFiles.length) {
                log.warn("trying to send file out of dynamic files range (" + Integer.toString(fileNum + 1)
                        + " of " + Integer.toString(dynFiles.length) + ")\nfile was skipped");
                i--;
                continue;
            }
            HTTPFileArg file = dynFiles[fileNum];

            viewableByteBodies[i] = new ViewableByteBody(contentServer.getFileContent(file.getPath()),
                    file.getMimeType(), new File(file.getPath()).getName());
            multiPart.addPart(file.getParamName(), viewableByteBodies[i]);
            hasContent = true;
        }
    }

    post.setEntity(multiPart);
    if (!hasContent)
        log.warn("POST has no content!");

    if (multiPart.isRepeatable()) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        //stop the content from appearing in sampler result
        if (!testElement.getLogFiles()) {
            for (ViewableByteBody fileBody : viewableByteBodies) {
                if (fileBody != null)
                    fileBody.hideFileData = true;
                else
                    break;
            }
        }

        multiPart.writeTo(bos);

        //Set it back, in order for the content to be sent
        if (!testElement.getLogFiles()) {
            for (ViewableByteBody fileBody : viewableByteBodies) {
                if (fileBody != null)
                    fileBody.hideFileData = false;
                else
                    break;
            }
        }
        bos.flush();
        // We get the posted bytes using the encoding used to create it
        postedBody.append(new String(bos.toByteArray(), contentEncoding == null ? "US-ASCII" // $NON-NLS-1$ this is the default used by HttpClient
                : contentEncoding));
        bos.close();
    } else {
        postedBody.append("<Multipart was not repeatable, cannot view what was sent>"); // $NON-NLS-1$
    }

    return postedBody.toString();
}