Example usage for org.apache.commons.httpclient ChunkedInputStream ChunkedInputStream

List of usage examples for org.apache.commons.httpclient ChunkedInputStream ChunkedInputStream

Introduction

In this page you can find the example usage for org.apache.commons.httpclient ChunkedInputStream ChunkedInputStream.

Prototype

public ChunkedInputStream(InputStream paramInputStream) throws IOException 

Source Link

Usage

From source file:com.tasktop.c2c.server.scm.web.GitHandler.java

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    final boolean containerSupportsChunkedIO = computeContainerSupportsChunkedIO();

    String pathInfo = request.getPathInfo();
    log.info("Git request: " + request.getMethod() + " " + request.getRequestURI() + " " + pathInfo);

    Repository repository = null;/*from w w w.  j a  v  a  2s  .c  om*/
    try {
        // only work on Git requests
        Matcher matcher = pathInfo == null ? null : GIT_COMMAND_PATTERN.matcher(pathInfo);
        if (matcher == null || !matcher.matches()) {
            log.info("Unexpected path: " + pathInfo);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        String requestCommand = matcher.group(1);
        String requestPath = matcher.group(2);

        // sanity check on path, disallow path separator components
        if (requestPath == null || requestPath.contains("/") || requestPath.contains("..")) {
            badPathResponse();
        }

        repository = repositoryResolver.open(request, requestPath);

        InputStream requestInput = request.getInputStream();
        if (!containerSupportsChunkedIO) {
            requestInput = new ChunkedInputStream(requestInput);
        }

        MultiplexingOutputStream mox = createMultiplexingOutputStream(response, containerSupportsChunkedIO);
        // indicate that we're ok to handle the request
        // note that following this there will be a two-way communication with the process
        // that might still encounter errors. That's ok.
        startOkResponse(response, containerSupportsChunkedIO);

        // identify the git command
        GitCommand command = GitCommand.fromCommandName(requestCommand);
        if (command != null) {
            // permissions check
            if (!Security.hasOneOfRoles(command.getRoles())) {
                log.info("Access denied to " + Security.getCurrentUser() + " for " + command.getCommandName()
                        + " on " + TenancyUtil.getCurrentTenantProjectIdentifer() + " " + requestPath);
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
            switch (command) {
            case RECEIVE_PACK:
                ReceivePack rp = new ReceivePack(repository);
                rp.setPostReceiveHook(postReceiveHook);
                rp.receive(requestInput, mox.stream(PacketType.STDOUT), mox.stream(PacketType.STDERR));
                break;
            case UPLOAD_PACK:
                UploadPack up = new UploadPack(repository);
                up.upload(requestInput, mox.stream(PacketType.STDOUT), mox.stream(PacketType.STDERR));
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
        }

        // at this stage we're done with IO
        // send the exit value and closing chunk
        try {
            int exitValue = 0;

            if (exitValue != 0) {
                log.info("Exit value: " + exitValue);
            }
            mox.writeExitCode(exitValue);
            mox.close();
        } catch (IOException e) {
            // ignore
            log.debug("Cannot complete writing exit state", e);
        }

        // clear interrupt status
        Thread.interrupted();

    } catch (ErrorResponseException e) {
        createGitErrorResponse(response, containerSupportsChunkedIO, e.getMessage());
    } catch (ServiceNotAuthorizedException e) {
        createGitErrorResponse(response, containerSupportsChunkedIO, e.getMessage());
    } catch (ServiceNotEnabledException e) {
        createGitErrorResponse(response, containerSupportsChunkedIO, e.getMessage());
    } finally {
        log.info("Git request complete");
        if (repository != null) {
            repository.close();
        }
    }
}

From source file:com.cloud.storage.template.HttpTemplateDownloader.java

@Override
public long download(boolean resume, DownloadCompleteCallback callback) {
    switch (status) {
    case ABORTED:
    case UNRECOVERABLE_ERROR:
    case DOWNLOAD_FINISHED:
        return 0;
    default:/* w  ww.jav a2 s. c  o  m*/

    }
    int bytes = 0;
    File file = new File(toFile);
    try {

        long localFileSize = 0;
        if (file.exists() && resume) {
            localFileSize = file.length();
            s_logger.info("Resuming download to file (current size)=" + localFileSize);
        }

        Date start = new Date();

        int responseCode = 0;

        if (localFileSize > 0) {
            // require partial content support for resume
            request.addRequestHeader("Range", "bytes=" + localFileSize + "-");
            if (client.executeMethod(request) != HttpStatus.SC_PARTIAL_CONTENT) {
                errorString = "HTTP Server does not support partial get";
                status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
                return 0;
            }
        } else if ((responseCode = client.executeMethod(request)) != HttpStatus.SC_OK) {
            status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
            errorString = " HTTP Server returned " + responseCode + " (expected 200 OK) ";
            return 0; //FIXME: retry?
        }

        Header contentLengthHeader = request.getResponseHeader("Content-Length");
        boolean chunked = false;
        long remoteSize2 = 0;
        if (contentLengthHeader == null) {
            Header chunkedHeader = request.getResponseHeader("Transfer-Encoding");
            if (chunkedHeader == null || !"chunked".equalsIgnoreCase(chunkedHeader.getValue())) {
                status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
                errorString = " Failed to receive length of download ";
                return 0; //FIXME: what status do we put here? Do we retry?
            } else if ("chunked".equalsIgnoreCase(chunkedHeader.getValue())) {
                chunked = true;
            }
        } else {
            remoteSize2 = Long.parseLong(contentLengthHeader.getValue());
        }

        if (remoteSize == 0) {
            remoteSize = remoteSize2;
        }

        if (remoteSize > MAX_TEMPLATE_SIZE_IN_BYTES) {
            s_logger.info("Remote size is too large: " + remoteSize + " , max=" + MAX_TEMPLATE_SIZE_IN_BYTES);
            status = Status.UNRECOVERABLE_ERROR;
            errorString = "Download file size is too large";
            return 0;
        }

        if (remoteSize == 0) {
            remoteSize = MAX_TEMPLATE_SIZE_IN_BYTES;
        }

        InputStream in = !chunked ? new BufferedInputStream(request.getResponseBodyAsStream())
                : new ChunkedInputStream(request.getResponseBodyAsStream());

        RandomAccessFile out = new RandomAccessFile(file, "rwd");
        out.seek(localFileSize);

        s_logger.info("Starting download from " + getDownloadUrl() + " to " + toFile + " remoteSize="
                + remoteSize + " , max size=" + MAX_TEMPLATE_SIZE_IN_BYTES);

        byte[] block = new byte[CHUNK_SIZE];
        long offset = 0;
        boolean done = false;
        status = TemplateDownloader.Status.IN_PROGRESS;
        while (!done && status != Status.ABORTED && offset <= remoteSize) {
            if ((bytes = in.read(block, 0, CHUNK_SIZE)) > -1) {
                out.write(block, 0, bytes);
                offset += bytes;
                out.seek(offset);
                totalBytes += bytes;
            } else {
                done = true;
            }
        }
        Date finish = new Date();
        String downloaded = "(incomplete download)";
        if (totalBytes >= remoteSize) {
            status = TemplateDownloader.Status.DOWNLOAD_FINISHED;
            downloaded = "(download complete remote=" + remoteSize + "bytes)";
        }
        errorString = "Downloaded " + totalBytes + " bytes " + downloaded;
        downloadTime += finish.getTime() - start.getTime();
        out.close();

        return totalBytes;
    } catch (HttpException hte) {
        status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
        errorString = hte.getMessage();
    } catch (IOException ioe) {
        status = TemplateDownloader.Status.UNRECOVERABLE_ERROR; //probably a file write error?
        errorString = ioe.getMessage();
    } finally {
        if (status == Status.UNRECOVERABLE_ERROR && file.exists() && !file.isDirectory()) {
            file.delete();
        }
        request.releaseConnection();
        if (callback != null) {
            callback.downloadComplete(status);
        }
    }
    return 0;
}

From source file:com.tasktop.c2c.server.ssh.server.commands.AbstractInteractiveProxyCommand.java

protected void performCommand(Environment env, ProjectService service, String projectId, String path,
        String requestPath, RequestHeadersSupport headers) throws CommandException {
    String internalProxyUri = service.computeInternalProxyBaseUri(false);
    if (internalProxyUri == null) {
        throw new IllegalStateException();
    }// w w  w .j ava  2s. c  om
    URI targetUri;
    try {
        if (!internalProxyUri.endsWith("/")) {
            internalProxyUri += "/";
        }
        internalProxyUri += getName() + '/' + path;

        targetUri = new URI(internalProxyUri);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    String host = targetUri.getHost();
    int port = targetUri.getPort();
    if (port < 0) {
        port = 80;
    }
    if (targetUri.getScheme() == null || !targetUri.getScheme().equalsIgnoreCase("http")) {
        throw new IllegalStateException("scheme " + targetUri.getScheme() + " is not supported");
    }
    HeaderGroup headerGroup = computeHeaders(targetUri);
    for (Entry<String, List<String>> headerEntry : headers.getRequestHeaders().entrySet()) {
        for (String value : headerEntry.getValue()) {
            headerGroup.addHeader(new Header(headerEntry.getKey(), value));
        }
    }
    getLogger().info("Proxying " + getName() + " to " + targetUri);
    try {
        Socket socket = socketFactory.openConnection(host, port);
        try {
            // initiate an HTTP request with Transfer-Encoding: chunked
            OutputStream proxyOut = socket.getOutputStream();
            emitHttpRequestLine(proxyOut, targetUri);
            emitHeaders(proxyOut, headerGroup);

            proxyOut.flush();

            List<Callable<Void>> tasks = new ArrayList<Callable<Void>>(3);
            FlushingChunkedOutputStream chunkedRequestOut = new FlushingChunkedOutputStream(proxyOut);
            tasks.add(new InputPipe(in, chunkedRequestOut, bufferSize, Thread.currentThread()).flush(true));

            // start these pipes
            ExecutorService executor = Executors.newFixedThreadPool(tasks.size());
            try {
                for (Callable<Void> task : tasks) {
                    executor.submit(task);
                }

                InputStream proxyInput = socket.getInputStream();
                try {
                    readHttpResponse(proxyInput);
                    MultiplexingInputStream input = new MultiplexingInputStream(
                            new ChunkedInputStream(proxyInput));
                    for (;;) {
                        PacketType packetType = input.getPacketType();
                        if (packetType == null) {
                            break;
                        }
                        int length = input.getPacketLength();

                        processData(input, packetType, length);
                    }
                } finally {
                    try {
                        executor.shutdown();
                        executor.awaitTermination(1000L, TimeUnit.MILLISECONDS);
                    } catch (InterruptedException e) {
                        // ignore
                    }
                }
            } finally {
                executor.shutdownNow();
                try {
                    executor.awaitTermination(3000L, TimeUnit.MILLISECONDS);
                } catch (InterruptedException e) {
                    // ignore
                }
                Thread.interrupted();

                try {
                    // attempt to close the chunked output, since this will make us a well-behaved client
                    // by sending the closing chunk.
                    chunkedRequestOut.close();
                } catch (Throwable t) {
                    // ignore
                }
            }
        } finally {
            socket.close();
        }
    } catch (ConnectException e) {
        getLogger().error(e.getMessage(), e);
        throw new CommandException(-1, "Service temporarily unavailable");
    } catch (IOException e) {
        getLogger().warn(e.getMessage(), e);
        throw new CommandException(-1, e.getMessage());
    }
}

From source file:ed.net.httpclient.HttpConnection.java

public void go() throws IOException {

    boolean doIWantKeepAlive = true;

    _lastAccess = System.currentTimeMillis();

    if (_sock == null) {
        int port = _currentUrl.getPort();
        if (port < 0) {
            if (_currentUrl.getProtocol().equalsIgnoreCase("https"))
                port = 443;//from   ww  w.ja  v  a  2s.  c  o m
            else
                port = 80;
        }

        if (DEBUG)
            LOGGER.debug("creating new socket to " + _key.getAddress());
        InetSocketAddress isa = new InetSocketAddress(_key.getAddress(), port);

        _sock = new Socket();

        _sock.connect(isa, _timeout);
        _sock.setSoTimeout(_timeout * 5);

        if (_currentUrl.getProtocol().equalsIgnoreCase("https")) {
            try {
                _sock = getDefaultSSLSocketFactory().createSocket(_sock, _currentUrl.getHost(), port, true);
                _usingSLL = true;
                doIWantKeepAlive = false; // don't trust this with SSL yet
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        if (_sock == null) {
            RuntimeException re = new RuntimeException("_sock can't be null here.  close called? " + _closed);
            re.fillInStackTrace();
            LOGGER.error("weird...", re);
            throw re;
        }

        if (_sock.getInputStream() == null)
            throw new RuntimeException("_sock.getInputStream() is null!!"); // should never happen, should be IOException
        _in = new BufferedInputStream(_sock.getInputStream());
    }

    StringBuilder buf = new StringBuilder();

    // First Line
    buf.append(_requestMethod).append(" ");
    String f = _currentUrl.getFile();

    if (f == null || f.trim().length() == 0)
        f = "/";
    buf.append(f.replace(' ', '+'));
    buf.append(" HTTP/1.1\r\n");

    for (Iterator i = _headers.keySet().iterator(); i.hasNext();) {
        String name = (String) i.next();
        String value = String.valueOf(_headers.get(name));

        buf.append(name).append(": ").append(value).append("\r\n");

        if (name.equalsIgnoreCase("connection") && value.equalsIgnoreCase("close"))
            doIWantKeepAlive = false;
    }
    buf.append("\r\n");

    String headerString = buf.toString();
    if (DEBUG)
        System.out.println(headerString);
    try {
        _sock.getOutputStream().write(headerString.getBytes());

        if (_postData != null)
            _sock.getOutputStream().write(_postData);

        int timeoutSeconds = 60;

        _timeOutKeeper.add(this, timeoutSeconds);

        _in.mark(10);
        if (_in.read() < 0)
            throw new IOException("stream closed on be ya bastard");
        _in.reset();
        if (DEBUG)
            System.out.println("sent header and seems to be ok");
    } catch (IOException ioe) {
        if (_keepAlive) {
            if (DEBUG)
                LOGGER.debug("trying again");
            // if we previously had a keep alive connection, maybe it died, so rety
            _keepAlive = false;
            _key.reset();
            close();
            reset(_currentUrl, false);
            go();
            return;
        }
        throw ioe;
    }

    // need to look for end of headers

    byte currentLine[] = new byte[2048];
    int idx = 0;
    boolean gotStatus = false;
    boolean chunked = false;
    int lineNumber = 0;
    boolean previousSlashR = false;
    while (true) {
        if (idx >= currentLine.length) {
            byte temp[] = new byte[currentLine.length * 2];
            for (int i = 0; i < currentLine.length; i++)
                temp[i] = currentLine[i];
            currentLine = temp;
        }
        int t = -1;
        try {
            t = _in.read();
        } catch (NullPointerException e) {
            throw new IOException("input stream was closed while parsing headers");
        }

        if (t < 0)
            throw new IOException("input stream got closed while parsing headers");

        currentLine[idx] = (byte) t;
        if (currentLine[idx] == '\r') {
            currentLine[idx] = ' ';
        } else if (currentLine[idx] == '\n') {
            String line = new String(currentLine, 0, idx).trim();
            if (DEBUG)
                System.out.println(line);
            if (line.length() == 0) {
                if (DEBUG)
                    System.out.println("rc:" + _rc);
                if (_rc == 100) {
                    if (DEBUG)
                        System.out.println("got Continue");
                    gotStatus = false;
                    lineNumber = 0;
                    idx = 0;
                    continue;
                }
                break;
            }

            if (!gotStatus) {
                gotStatus = true;

                Matcher m = STATUS_PATTERN.matcher(line);
                if (!m.find())
                    throw new IOException("invalid status line:" + line);

                _httpVersion = Double.parseDouble(m.group(1));
                _rc = Integer.parseInt(m.group(2));
                _message = m.group(3);

                _responseHeaderFields[0] = line;
            } else {
                int colon = line.indexOf(":");
                if (colon < 0) {
                    //throw new IOException("invalid header[" + line + "]");
                    LOGGER.error("weird error : {" + line
                            + "} does not have a colon, using the whole line as the value and SWBadHeader as the key");
                    line = "SWBadHeader:" + line;
                    colon = line.indexOf(":");
                }
                String name = line.substring(0, colon).trim();
                String value = line.substring(colon + 1).trim();

                _responseHeaders.put(name, value);

                if (name.equalsIgnoreCase("Transfer-Encoding") && value.equalsIgnoreCase("chunked"))
                    chunked = true;

                if (lineNumber >= (_responseHeaderFields.length - 2)) {
                    // need to enlarge header...

                    String keys[] = new String[_responseHeaderFieldKeys.length * 2];
                    String values[] = new String[_responseHeaderFields.length * 2];

                    for (int i = 0; i < lineNumber; i++) {
                        keys[i] = _responseHeaderFieldKeys[i];
                        values[i] = _responseHeaderFields[i];
                    }

                    _responseHeaderFieldKeys = keys;
                    _responseHeaderFields = values;
                }

                _responseHeaderFieldKeys[lineNumber] = name;
                _responseHeaderFields[lineNumber] = value;

            }
            if (DEBUG)
                System.out.println(
                        "\t" + _responseHeaderFieldKeys[lineNumber] + ":" + _responseHeaderFields[lineNumber]);
            lineNumber++;
            idx = -1;
        }
        idx++;
    }

    _responseHeaderFieldKeys[lineNumber] = null;
    _responseHeaderFields[lineNumber] = null;

    // TODO: obey max? etc...?

    _keepAlive = false;
    if (doIWantKeepAlive && (chunked || getContentLength() >= 0 || _rc == 304)) {
        String hf = null;

        if (hf == null)
            hf = "Connection";

        if (_httpVersion > 1) {
            _keepAlive = getHeaderField(hf) == null || getHeaderField(hf).toLowerCase().indexOf("close") < 0;
        } else {
            _keepAlive = getHeaderField(hf) != null
                    && getHeaderField(hf).toLowerCase().indexOf("keep-alive") >= 0;
        }
    }

    if (DEBUG)
        System.out.println("_keepAlive=" + _keepAlive);

    /* DM: TODO --------------------------------
       fix keepalive it's not set if no content length
    */

    if (!_requestMethod.equals("HEAD")) {
        if (chunked) {
            _userIn = new ChunkedInputStream(_in);
        } else if (_keepAlive || _usingSLL) {
            _userIn = new MaxReadInputStream(_in, getContentLength());
        } else {
            _userIn = _in; // just pass throgh
        }
    }

    _lastAccess = System.currentTimeMillis();

}

From source file:org.archive.util.Recorder.java

/**
 * Get a raw replay of the 'entity'. For the common case of 
 * HTTP, this is the message-body after any (usually-unnecessary)
 * transfer-decoding but before any content-encoding (eg gzip) decoding
 * /*from   w  ww . jav  a 2  s . c om*/
 * @return A replay input stream.
 * @throws IOException
 */
public InputStream getEntityReplayInputStream() throws IOException {
    if (inputIsChunked) {
        return new ChunkedInputStream(getRecordedInput().getMessageBodyReplayInputStream());
    } else {
        return getRecordedInput().getMessageBodyReplayInputStream();
    }
}

From source file:org.archive.wayback.core.Resource.java

/**
 * indicate that there is a {@code Transfer-Encoding: chunked} header, so the input
 *   data should be dechunked as it is read. This method actually peeks
 *   ahead to verify that there is a hex-encoded chunk length before
 *   assuming the data is chunked.//from  w  ww. j av a2 s  . c  o  m
 * @throws IOException for usual reasons
 */
public void setChunkedEncoding() throws IOException {
    validate();
    // peek ahead and make sure we have a line with hex numbers:
    int max = 50;
    is.mark(max + 2);
    int cur = 0;
    int hexFound = 0;
    boolean isChunked = false;
    while (cur < max) {
        int nextC = is.read();
        // allow CRLF and plain ole LF:
        if ((nextC == 13) || (nextC == 10)) {
            // must have read at least 1 hex char:
            if (hexFound > 0) {
                if (nextC == 10) {
                    isChunked = true;
                    break;
                }
                nextC = is.read();
                if (nextC == 10) {
                    isChunked = true;
                    break;
                }
            }
            // keep looking to allow some blank lines.
        } else {
            // better be a hex character:
            if (isHex(nextC)) {
                hexFound++;
            } else if (nextC != ' ') {
                // allow whitespace before or after chunk...
                // not a hex digit: not a chunked stream.
                break;
            }
        }
        cur++;
    }
    is.reset();
    if (isChunked) {
        setInputStream(new ChunkedInputStream(is));
    }
}

From source file:org.archive.wayback.resourcestore.locationdb.FileProxyServlet.java

private DataSource locationToDataSource(String location, long offset) throws IOException {
    DataSource ds = null;/*from  ww  w  .j av  a2s  .c  om*/
    if (location.startsWith("http://")) {
        URL url = new URL(location);
        String hostname = url.getHost();
        int port = url.getPort();
        if (port == -1) {
            port = 80;
        }
        byte GET[] = "GET".getBytes();
        byte HTTP11[] = "HTTP/1.1".getBytes();
        InetAddress addr = InetAddress.getByName(hostname);
        HttpRequestMessage requestMessage = new HttpRequestMessage(GET, url.getFile().getBytes(), HTTP11);
        ANVLRecord headers = new ANVLRecord();
        headers.addLabelValue("Host", hostname);

        if (offset != 0) {
            headers.addLabelValue(RANGE_HTTP_HEADER,
                    HEADER_BYTES_PREFIX + String.valueOf(offset) + HEADER_BYTES_SUFFIX);
        }
        InetSocketAddress sockAddr = new InetSocketAddress(addr, port);
        Socket socket = new Socket();
        socket.setSoTimeout(socketTimeoutMs);
        socket.setReceiveBufferSize(BUF_SIZE);

        socket.connect(sockAddr, connectTimeoutMs);
        OutputStream socketOut = socket.getOutputStream();
        InputStream socketIn = socket.getInputStream();
        socketOut.write(requestMessage.getBytes(true));
        socketOut.write(headers.getUTF8Bytes());
        socketOut.flush();
        HttpResponse response = HttpResponse.load(socketIn);
        String contentType = response.getHeaders().asMap().get("Content-Type");
        if (contentType == null) {
            contentType = "application/unknown";
        }
        String xferEncoding = response.getHeaders().asMap().get("Transfer-Encoding");

        if (xferEncoding != null) {
            if (xferEncoding.equals("chunked")) {
                socketIn = new ChunkedInputStream(socketIn);
            }
        }

        ds = new URLDataSource(socketIn, contentType);

    } else {
        // assume a local file path:
        File f = new File(location);
        if (f.isFile() && f.canRead()) {
            long size = f.length();
            if (size < offset) {
                throw new IOException("short file " + location + " cannot" + " seek to offset " + offset);
            }
            RandomAccessFile raf = new RandomAccessFile(f, "r");
            raf.seek(offset);
            // BUGBUG: is it compressed?
            ds = new FileDataSource(raf, DEFAULT_CONTENT_TYPE);

        } else {
            throw new IOException("No readable file at " + location);
        }

    }

    return ds;
}

From source file:org.mule.providers.http.HttpMessageReceiver.java

protected Object parseRequest(InputStream is, Properties p) throws IOException {
    RequestInputStream req = new RequestInputStream(is);
    Object payload = null;//from  w w w .  ja  v  a  2  s .c om
    String startLine = null;
    do {
        try {
            startLine = req.readline();
        } catch (IOException e) {
            logger.debug(e.getMessage());
        }
        if (startLine == null)
            return null;
    } while (startLine.trim().length() == 0);

    StringTokenizer tokenizer = new StringTokenizer(startLine);
    String method = tokenizer.nextToken();
    String request = tokenizer.nextToken();
    String httpVersion = tokenizer.nextToken();

    p.setProperty(HttpConnector.HTTP_METHOD_PROPERTY, method);
    p.setProperty(HttpConnector.HTTP_REQUEST_PROPERTY, request);
    p.setProperty(HttpConnector.HTTP_VERSION_PROPERTY, httpVersion);

    // Read headers from the request as set them as properties on the event
    readHeaders(req, p);

    if (method.equals(HttpConstants.METHOD_GET)) {
        payload = request.getBytes();
    } else {
        boolean multipart = p.getProperty(HttpConstants.HEADER_CONTENT_TYPE, "")
                .indexOf("multipart/related") > -1;
        String contentLengthHeader = p.getProperty(HttpConstants.HEADER_CONTENT_LENGTH, null);
        String chunkedString = PropertiesHelper.getStringProperty(p, HttpConstants.HEADER_TRANSFER_ENCODING,
                null);
        boolean chunked = "chunked".equalsIgnoreCase(chunkedString);
        if (contentLengthHeader == null && !chunked) {
            throw new IllegalStateException(HttpConstants.HEADER_CONTENT_LENGTH + " header must be set");
        }

        if (chunked) {
            byte[] buffer = new byte[1024 * 32];
            int totalLength = 0;
            int length = 0;
            ChunkedInputStream cis = new ChunkedInputStream(req);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            //ast: change the chunked method to avoid original mule limitation of 32768 bytes
            do {
                length = cis.read(buffer, 0, buffer.length);
                if (length >= 0) {
                    baos.write(buffer, 0, length);
                    totalLength += length;
                }
            } while (length >= 0);

            if ((length == -1) && (totalLength == 0)) {
                return null;
            }

            payload = baos.toByteArray();
        } else {
            int contentLength = Integer.parseInt(contentLengthHeader);

            if (multipart) {
                byte[] buffer = new byte[1024];

                payload = File.createTempFile("mime", ".att");
                ((File) payload).deleteOnExit();
                FileOutputStream os = new FileOutputStream((File) payload);

                int length = -1;
                int offset = 0;
                while (offset != contentLength) {
                    buffer = new byte[1024];
                    length = is.read(buffer);
                    if (length != -1) {
                        os.write(buffer, 0, length);
                        offset += length;
                    }
                }
                os.close();
            } else {
                byte[] buffer = new byte[contentLength];

                int length = -1;
                int offset = req.read(buffer);
                while (offset >= 0 && offset < buffer.length) {
                    length = req.read(buffer, offset, buffer.length - offset);
                    if (length == -1) {
                        break;
                    }
                    offset += length;
                }
                payload = buffer;
            }
        }
    }
    return payload;
}

From source file:org.mule.transport.http.HttpRequest.java

public HttpRequest(final RequestLine requestLine, final Header[] headers, final InputStream content,
        String defaultEncoding) throws IOException {
    super();//w  w w  .  j  a  va2  s .c  o  m
    if (requestLine == null) {
        throw new IllegalArgumentException("Request line may not be null");
    }
    this.defaultEncoding = defaultEncoding;
    this.requestLine = requestLine;
    if (headers != null) {
        this.headers.setHeaders(headers);
    }
    if (content != null) {
        // only PUT and POST have content
        String methodname = requestLine.getMethod();
        if (HttpConstants.METHOD_POST.equalsIgnoreCase(methodname)
                || HttpConstants.METHOD_PUT.equalsIgnoreCase(methodname)) {
            Header contentLength = this.headers.getFirstHeader(HttpConstants.HEADER_CONTENT_LENGTH);
            Header transferEncoding = this.headers.getFirstHeader(HttpConstants.HEADER_TRANSFER_ENCODING);
            InputStream in = content;
            if (transferEncoding != null) {
                if (transferEncoding.getValue().indexOf(HttpConstants.TRANSFER_ENCODING_CHUNKED) != -1) {
                    in = new ChunkedInputStream(in);
                }
            } else if (contentLength != null) {
                long len = getContentLength();
                if (len >= 0) {
                    in = new ContentLengthInputStream(in, len);
                }
            }
            this.entity = in;
        }
    }
}

From source file:org.mule.transport.http.HttpResponse.java

public HttpResponse(final StatusLine statusline, final Header[] headers, final InputStream content)
        throws IOException {
    super();// www  .j a  va 2  s  .com
    if (statusline == null) {
        throw new IllegalArgumentException("Status line may not be null");
    }
    setStatusLine(HttpVersion.parse(statusline.getHttpVersion()), statusline.getStatusCode(),
            statusline.getReasonPhrase());
    setHeaders(headers);
    if (content != null) {
        InputStream in = content;
        Header contentLength = this.headers.getFirstHeader(HttpConstants.HEADER_CONTENT_LENGTH);
        Header transferEncoding = this.headers.getFirstHeader(HttpConstants.HEADER_TRANSFER_ENCODING);

        if (transferEncoding != null) {
            if (transferEncoding.getValue().indexOf(HttpConstants.TRANSFER_ENCODING_CHUNKED) != -1) {
                in = new ChunkedInputStream(in);
            }
        } else if (contentLength != null) {
            long len = getContentLength();
            if (len >= 0) {
                in = new ContentLengthInputStream(in, len);
            }
        }
    }
}