Example usage for org.apache.commons.httpclient HttpStatus SC_PARTIAL_CONTENT

List of usage examples for org.apache.commons.httpclient HttpStatus SC_PARTIAL_CONTENT

Introduction

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

Prototype

int SC_PARTIAL_CONTENT

To view the source code for org.apache.commons.httpclient HttpStatus SC_PARTIAL_CONTENT.

Click Source Link

Document

<tt>206 Partial Content</tt> (HTTP/1.1 - RFC 2616)

Usage

From source file:com.bigdata.rdf.sail.remoting.GraphRepositoryClient.java

/**
 * Construct and select are sent across the wire in exactly the same way.
 *//* w w w  .  j av  a 2 s  .  co  m*/
private String executeQuery(final String query, final QueryLanguage ql, final boolean includeInferred)
        throws Exception {

    GetMethod get = new GetMethod(servletURL);
    // just to be nice.
    get.addRequestHeader(new Header("Accept", "application/rdf+xml"));
    // and say what we want.
    get.addRequestHeader(new Header("Accept-Charset", "UTF-8"));

    try {

        // add the range and include inferred headers
        get.addRequestHeader(
                new Header(GraphRepositoryServlet.X_INCLUDE_INFERRED, String.valueOf(includeInferred)));
        if (query != null) {
            // add the range header
            String range = ql.toString().toLowerCase() + "[" + trim(query) + "]";
            get.addRequestHeader(new Header(GraphRepositoryServlet.HTTP_RANGE, range));
        }

        // Execute the method.
        int sc = getHttpClient().executeMethod(get);
        if (sc != HttpStatus.SC_OK && sc != HttpStatus.SC_PARTIAL_CONTENT) {
            throw new IOException("HTTP-GET failed: " + get.getStatusLine());
        }

        // Read the response body.
        String response = IOUtils.readString(get.getResponseBodyAsStream(), get.getResponseCharSet());
        return response;

    } finally {
        // Release the connection.
        get.releaseConnection();
    }

}

From source file:com.bigdata.rdf.sail.remoting.GraphRepositoryServlet.java

/**
 * Perform an HTTP GET, which corresponds to the basic CRUD operation "read"
 * according to the generic interaction semantics of HTTP REST.
 * <p>/* www.j  a v a 2  s . c om*/
 * <ul>
 * <li>BODY ignored for READ</li> 
 * <li>no RANGE retrieves the entire graph</li> 
 * <li>RANGE(&lt;query language&gt;[&lt;query&gt;]) performs a query</li>
 * </ul>
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String range = request.getHeader(HTTP_RANGE);
    boolean includeInferred = Boolean.valueOf(request.getHeader(X_INCLUDE_INFERRED));

    if (log.isInfoEnabled()) {
        log.info("doGet: " + range);
    }

    try {

        // set the content type and the _encoding_
        response.setContentType(RDF_XML);

        // obtain the writer -- it will use the specified encoding.
        PrintWriter out = response.getWriter();
        String query = null;
        QueryLanguage ql = null;
        int status = 0;
        if (range == null || range.length() == 0) {
            // proper semantics are to provide the entire graph, per above
            status = HttpStatus.SC_OK;
        } else {
            // sparql[select ...]
            final int i = range.indexOf('[');
            ql = QueryLanguage.valueOf(range.substring(0, i));
            if (ql == null) {
                throw new RuntimeException("unrecognized query language: " + range);
            }
            query = range.substring(i + 1, range.length() - 1);
            /*
             MetadataRepositoryHelper.doQuery(graph, query, ql,
             includeInferred);
             */
            status = HttpStatus.SC_PARTIAL_CONTENT;
        }

        String results = read(query, ql, includeInferred);
        out.print(results);
        out.flush();
        response.setStatus(status);

    } catch (Exception ex) {
        ex.printStackTrace();
        response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
    }

}

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:/*from   w w  w . java2 s  . co  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:org.apache.excalibur.source.factories.HTTPClientSource.java

/**
 * Method to update whether a referenced resource exists, after
 * executing a particular {@link HttpMethod}.
 *
 * <p>REVISIT: exists() would be better called canRead()
 * or similar, as a resource can exist but not be readable.</p>
 *
 * @param method {@link HttpMethod} executed.
 *//*from  w  w w .j  av  a 2s.c o m*/
private void updateExists(final HttpMethod method) {
    final int response = method.getStatusCode();

    // The following returns true, if the user can successfully get
    // an InputStream without receiving errors? ie. if we receive a
    // HTTP 200 (OK), 201 (CREATED), 206 (PARTIAL CONTENT)

    // REVISIT(MC): need a special way to handle 304 (NOT MODIFIED)
    // 204 & 205 in the future

    // resource does not exist if HttpClient returns a 404 or a 410
    this.m_exists = (response == HttpStatus.SC_OK || response == HttpStatus.SC_CREATED
            || response == HttpStatus.SC_PARTIAL_CONTENT);
}

From source file:org.cryptomator.webdav.jackrabbit.DavResourceFactoryImpl.java

@Override
public DavResource createResource(DavResourceLocator locator, DavServletRequest request,
        DavServletResponse response) throws DavException {
    final Path path = ResourcePathUtils.getPhysicalPath(locator);
    final String rangeHeader = request.getHeader(HttpHeader.RANGE.asString());

    if (Files.isRegularFile(path) && DavMethods.METHOD_GET.equals(request.getMethod()) && rangeHeader != null) {
        response.setStatus(HttpStatus.SC_PARTIAL_CONTENT);
        return createFilePart(locator, request.getDavSession(), request);
    } else if (Files.isRegularFile(path) || DavMethods.METHOD_PUT.equals(request.getMethod())) {
        return createFile(locator, request.getDavSession());
    } else if (Files.isDirectory(path) || DavMethods.METHOD_MKCOL.equals(request.getMethod())) {
        return createDirectory(locator, request.getDavSession());
    } else {/*from  w  w  w .  j  a  v  a2  s  . c o  m*/
        return createNonExisting(locator, request.getDavSession());
    }
}

From source file:org.mimacom.maven.plugins.liferay.prepare.MultithreadedDownloader.java

private boolean canPartialDownload(HttpMethod method) throws IOException {
    method.setRequestHeader("Range", "bytes=0-1");
    int status = httpClient.executeMethod(method);
    return (status == HttpStatus.SC_PARTIAL_CONTENT);
}

From source file:org.opens.tanaguru.util.http.HttpRequestHandler.java

private int computeStatus(int status) {
    switch (status) {
    case HttpStatus.SC_FORBIDDEN:
    case HttpStatus.SC_METHOD_NOT_ALLOWED:
    case HttpStatus.SC_BAD_REQUEST:
    case HttpStatus.SC_UNAUTHORIZED:
    case HttpStatus.SC_PAYMENT_REQUIRED:
    case HttpStatus.SC_NOT_FOUND:
    case HttpStatus.SC_NOT_ACCEPTABLE:
    case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
    case HttpStatus.SC_REQUEST_TIMEOUT:
    case HttpStatus.SC_CONFLICT:
    case HttpStatus.SC_GONE:
    case HttpStatus.SC_LENGTH_REQUIRED:
    case HttpStatus.SC_PRECONDITION_FAILED:
    case HttpStatus.SC_REQUEST_TOO_LONG:
    case HttpStatus.SC_REQUEST_URI_TOO_LONG:
    case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE:
    case HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE:
    case HttpStatus.SC_EXPECTATION_FAILED:
    case HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE:
    case HttpStatus.SC_METHOD_FAILURE:
    case HttpStatus.SC_UNPROCESSABLE_ENTITY:
    case HttpStatus.SC_LOCKED:
    case HttpStatus.SC_FAILED_DEPENDENCY:
    case HttpStatus.SC_INTERNAL_SERVER_ERROR:
    case HttpStatus.SC_NOT_IMPLEMENTED:
    case HttpStatus.SC_BAD_GATEWAY:
    case HttpStatus.SC_SERVICE_UNAVAILABLE:
    case HttpStatus.SC_GATEWAY_TIMEOUT:
    case HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED:
    case HttpStatus.SC_INSUFFICIENT_STORAGE:
        return 0;
    case HttpStatus.SC_CONTINUE:
    case HttpStatus.SC_SWITCHING_PROTOCOLS:
    case HttpStatus.SC_PROCESSING:
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
    case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
    case HttpStatus.SC_NO_CONTENT:
    case HttpStatus.SC_RESET_CONTENT:
    case HttpStatus.SC_PARTIAL_CONTENT:
    case HttpStatus.SC_MULTI_STATUS:
    case HttpStatus.SC_MULTIPLE_CHOICES:
    case HttpStatus.SC_MOVED_PERMANENTLY:
    case HttpStatus.SC_MOVED_TEMPORARILY:
    case HttpStatus.SC_SEE_OTHER:
    case HttpStatus.SC_NOT_MODIFIED:
    case HttpStatus.SC_USE_PROXY:
    case HttpStatus.SC_TEMPORARY_REDIRECT:
        return 1;
    default://from   w ww  .  j av a  2 s.co  m
        return 1;
    }
}

From source file:osl.examples.gui.downloader.DLWorker.java

@message
public void downloadChunk(String url, Integer offset, Integer length, Long total, Integer chunkNumber,
        File tempDir, ActorName manager) {
    System.out.println("offset: " + offset + ", length: " + length);
    HttpClient client = new HttpClient();
    GetMethod request = new GetMethod(url);
    request.addRequestHeader("Range", "bytes=" + offset + "-" + (offset + length - 1)
    // + "/" + total
    );/*  w w w  . j  ava 2s .  c  o m*/
    try {
        if (client.executeMethod(request) != HttpStatus.SC_PARTIAL_CONTENT) {
            System.out.println("Error in download");
            return;
        }

        BufferedInputStream in = new BufferedInputStream(request.getResponseBodyAsStream());
        File tempFile = new File(tempDir, "_" + offset + "_" + (new Random().nextInt(10000) + 1000) + ".part");
        FileOutputStream fos = new FileOutputStream(tempFile);

        // /*
        byte[] b = new byte[8192];
        int readSize = in.read(b);
        int totalW = 0;
        while (readSize != -1) {
            totalW += readSize;
            // System.out.println(chunkNumber+" <> "+readSize);
            fos.write(b, 0, readSize);
            readSize = in.read(b);
            // System.out.println(new Float(totalW+0.0)/(length+0.0));
            // if (((totalW+0.0)/(length+0.0)*100) % 8 < 3) {
            // System.out.println(new
            // Integer((int)((100.0*totalW)/(length+0.0))).toString());
            send(manager, "percentComplete", new Integer((int) ((100.0 * totalW) / (length + 0.0))),
                    chunkNumber);
            // }
        }
        // */
        /*
         * int readSize = in.read(); int totalW = 0; while (readSize != -1)
         * { fos.write(readSize); readSize = in.read(); totalW ++; }
         */
        // System.out.println(chunkNumber + ", totalW: " + totalW);
        fos.close();
        in.close();
        send(manager, "done", chunkNumber, tempFile.toString());
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}