Example usage for org.apache.http.util EntityUtils toByteArray

List of usage examples for org.apache.http.util EntityUtils toByteArray

Introduction

In this page you can find the example usage for org.apache.http.util EntityUtils toByteArray.

Prototype

public static byte[] toByteArray(HttpEntity httpEntity) throws IOException 

Source Link

Usage

From source file:ste.web.http.handlers.FileHandler.java

@Override
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {

    checkHttpMethod(request);//from   w ww .  j  av  a2  s.  co  m

    String target = request.getRequestLine().getUri();

    for (String exclude : excludePatterns) {
        if (target.matches(exclude)) {
            notFound(target, response);

            return;
        }
    }
    if (StringUtils.isNotBlank(webContext) && target.startsWith(webContext)) {
        target = target.substring(webContext.length());
    }

    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
        byte[] entityContent = EntityUtils.toByteArray(entity);
    }

    URI uri = null;
    try {
        uri = new URI(target);
    } catch (URISyntaxException x) {
        throw new HttpException("malformed URL '" + target + "'");
    }
    final File file = new File(this.docRoot, uri.getPath());
    if (!file.exists()) {
        notFound(target, response);
    } else if (!file.canRead() || file.isDirectory()) {
        response.setStatusCode(HttpStatus.SC_FORBIDDEN);
        StringEntity entity = new StringEntity("<html><body><h1>Access denied</h1></body></html>",
                ContentType.TEXT_HTML);
        response.setEntity(entity);
    } else {
        response.setStatusCode(HttpStatus.SC_OK);

        String mimeType = MimeUtils.getInstance().getMimeType(file);
        ContentType type = MimeUtils.MIME_UNKNOWN.equals(mimeType) ? ContentType.APPLICATION_OCTET_STREAM
                : ContentType.create(mimeType);
        FileEntity body = new FileEntity(file, type);
        response.setEntity(body);
    }
}