public void run()

in src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/control/HttpMirrorThread.java [86:294]


    public void run() {
        log.debug("Starting thread");
        BufferedInputStream in = null;
        BufferedOutputStream out = null;

        try {
            in = new BufferedInputStream(clientSocket.getInputStream());

            // Read the header part, we will be looking for a content-length
            // header, so we know how much we should read.
            // We assume headers are in ISO_8859_1
            // If we do not find such a header, we will just have to read until
            // we have to block to read more, until we support chunked transfer
            int contentLength = -1;
            boolean isChunked = false;
            byte[] buffer = new byte[1024];
            StringBuilder headers = new StringBuilder();
            int length = 0;
            int positionOfBody = 0;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while(positionOfBody <= 0 && ((length = in.read(buffer)) != -1)) {
                log.debug("Write body");
                baos.write(buffer, 0, length); // echo back
                headers.append(new String(buffer, 0, length, ISO_8859_1));
                // Check if we have read all the headers
                positionOfBody = getPositionOfBody(headers.toString());
            }

            baos.close();
            final String headerString = headers.toString();
            if(headerString.isEmpty() || headerString.indexOf('\r') < 0) {
                log.error("Invalid request received:'{}'", headerString);
                return;
            }
            log.debug("Received => '{}'", headerString);
            final String firstLine = headerString.substring(0, headerString.indexOf('\r'));
            final String[] requestParts = firstLine.split("\\s+");
            final String requestMethod = requestParts[0];
            final String requestPath = requestParts[1];
            final HashMap<String, String> parameters = new HashMap<>();
            if (HTTPConstants.GET.equals(requestMethod)) {
                int querypos = requestPath.indexOf('?');
                if (querypos >= 0) {
                    String query;
                    try {
                        URI uri = new URI(requestPath); // Use URI because it will decode the query
                        query = uri.getQuery();
                    } catch (URISyntaxException e) {
                        log.warn(e.getMessage());
                        query=requestPath.substring(querypos+1);
                    }
                    if (query != null) {
                        String[] params = query.split("&");
                        for(String param : params) {
                            String[] parts = param.split("=",2);
                            if (parts.length==2) {
                                parameters.put(parts[0], parts[1]);
                            } else { // allow for parameter name only
                                parameters.put(parts[0], "");
                            }
                        }
                    }
                }
            }

            final boolean verbose = parameters.containsKey(VERBOSE);

            if (verbose) {
                System.out.println(firstLine); // NOSONAR
                log.info(firstLine);
            }

            // Look for special Response Length header
            String responseStatusValue = getRequestHeaderValue(headerString, "X-ResponseStatus"); //$NON-NLS-1$
            if(responseStatusValue == null) {
                responseStatusValue = "200 OK";
            }
            // Do this before the status check so can override the status, e.g. with a different redirect type
            if (parameters.containsKey(REDIRECT)) {
                responseStatusValue = "302 Temporary Redirect";
            }
            if (parameters.containsKey(STATUS)) {
                responseStatusValue = parameters.get(STATUS);
            }

            log.debug("Write headers");
            out = new BufferedOutputStream(clientSocket.getOutputStream());
            // The headers are written using ISO_8859_1 encoding
            out.write(("HTTP/1.0 "+responseStatusValue).getBytes(ISO_8859_1)); //$NON-NLS-1$
            out.write(CRLF);
            out.write("Content-Type: text/plain".getBytes(ISO_8859_1)); //$NON-NLS-1$
            out.write(CRLF);

            if (parameters.containsKey(REDIRECT)) {
                final String redirectLocation =
                        HTTPConstants.HEADER_LOCATION + ": " + parameters.get(REDIRECT);
                if (verbose) {
                    System.out.println(redirectLocation); // NOSONAR
                    log.info(redirectLocation);
                }
                out.write(redirectLocation.getBytes(ISO_8859_1));
                out.write(CRLF);
            }

            // Look for special Header request
            String headersValue = getRequestHeaderValue(headerString, "X-SetHeaders"); //$NON-NLS-1$
            if (headersValue != null) {
                String[] headersToSet = headersValue.split("\\|");
                for (String string : headersToSet) {
                    out.write(string.getBytes(ISO_8859_1));
                    out.write(CRLF);
                }
            }

            // Look for special Response Length header
            String responseLengthValue = getRequestHeaderValue(headerString, "X-ResponseLength"); //$NON-NLS-1$
            int responseLength=-1;
            if(responseLengthValue != null) {
                responseLength = Integer.parseInt(responseLengthValue);
            }

            // Look for special Cookie request
            String cookieHeaderValue = getRequestHeaderValue(headerString, "X-SetCookie"); //$NON-NLS-1$
            if (cookieHeaderValue != null) {
                out.write("Set-Cookie: ".getBytes(ISO_8859_1));
                out.write(cookieHeaderValue.getBytes(ISO_8859_1));
                out.write(CRLF);
            }
            out.write(CRLF);
            out.flush();

            if(responseLength>=0) {
                out.write(baos.toByteArray(), 0, Math.min(baos.toByteArray().length, responseLength));
            } else {
                out.write(baos.toByteArray());
            }
            // Check if we have found a content-length header
            String contentLengthHeaderValue = getRequestHeaderValue(headerString, HTTPConstants.HEADER_CONTENT_LENGTH);
            if(contentLengthHeaderValue != null) {
                contentLength = Integer.parseInt(contentLengthHeaderValue);
            }
            // Look for special Sleep request
            String sleepHeaderValue = getRequestHeaderValue(headerString, "X-Sleep"); //$NON-NLS-1$
            if(sleepHeaderValue != null) {
                TimeUnit.MILLISECONDS.sleep(Integer.parseInt(sleepHeaderValue));
            }
            String transferEncodingHeaderValue = getRequestHeaderValue(headerString, HTTPConstants.TRANSFER_ENCODING);
            if(transferEncodingHeaderValue != null) {
                isChunked = transferEncodingHeaderValue.equalsIgnoreCase("chunked"); //$NON-NLS-1$
                // We only support chunked transfer encoding
                if(!isChunked) {
                    log.error("Transfer-Encoding header set, the value is not supported : {}", transferEncodingHeaderValue);
                }
            }

            // If we know the content length, we can allow the reading of
            // the request to block until more data arrives.
            // If it is chunked transfer, we cannot allow the reading to
            // block, because we do not know when to stop reading, because
            // the chunked transfer is not properly supported yet
            length = 0;
            if(contentLength > 0) {
                // Check how much of the body we have already read as part of reading
                // the headers
                // We subtract two bytes for the crlf divider between header and body
                int totalReadBytes = headerString.length() - positionOfBody - 2;

                // We know when to stop reading, so we can allow the read method to block
                log.debug("Reading, {} < {}", totalReadBytes, contentLength);
                while((totalReadBytes < contentLength) && ((length = in.read(buffer)) != -1)) {
                    log.debug("Read bytes: {}", length);
                    out.write(buffer, 0, length);

                    totalReadBytes += length;
                    log.debug("totalReadBytes: {}", totalReadBytes);
                }
            }
            else if (isChunked) {
                // It is chunked transfer encoding, which we do not really support yet.
                // So we just read without blocking, because we do not know when to
                // stop reading, so we cannot block
                // TODO properly implement support for chunked transfer, i.e. to
                // know when we have read the whole request, and therefore allow
                // the reading to block
                log.debug("Chunked");
                while(in.available() > 0 && ((length = in.read(buffer)) != -1)) {
                    out.write(buffer, 0, length);
                }
            }
            else {
                // The request has no body, or it has a transfer encoding we do not support.
                // In either case, we read any data available
                log.debug("Other");
                while(in.available() > 0 && ((length = in.read(buffer)) != -1)) {
                    log.debug("Read bytes: {}", length);
                    out.write(buffer, 0, length);
                }
            }
            log.debug("Flush");
            out.flush();
        } catch (IOException | InterruptedException e) {
            log.error("", e);
        } finally {
            JOrphanUtils.closeQuietly(out);
            JOrphanUtils.closeQuietly(in);
            JOrphanUtils.closeQuietly(clientSocket);
        }
        log.debug("End of Thread");
    }