All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.femo.http.handlers.StreamHandler Maven / Gradle / Ivy

Go to download

An easy to use HTTP API, that supports synchronous and asynchronous execution of HTTP request. On android only asynchronous driver is supported. This library has been backported to jdk 7 to retain compatibility with android!

The newest version!
package io.femo.http.handlers;

import io.femo.http.*;
import io.femo.http.helper.HttpCacheControl;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

/**
 * Created by felix on 7/12/16.
 */
public class StreamHandler implements HttpHandler {

    private byte[] buffer;
    private String mimeType;
    private String etag;
    private boolean replace;

    public StreamHandler(String mimeType, String etag, InputStream inputStream) throws IOException {
        this.mimeType = mimeType;
        this.etag = etag;
        this.buffer = IOUtils.toByteArray(inputStream);
    }

    public StreamHandler(String mimeType, String etag, InputStream inputStream, boolean replace) throws IOException {
        this.buffer = IOUtils.toByteArray(inputStream);
        this.mimeType = mimeType;
        this.etag = etag;
        this.replace = replace;
    }

    @Override
    public boolean handle(HttpRequest request, HttpResponse response) throws HttpHandleException {
        if(Objects.equals(request.method(), Http.GET)) {
            if(!HttpCacheControl.cacheControl(request, response, 3600, etag)) {
                response.header("Content-Type", mimeType).entity(buffer);
            }
            if(replace)
                response.header("X-Replace-Env", "true");
            return true;
        } else {
            response.status(StatusCode.METHOD_NOT_ALLOWED)
                    .entity("Method " + request.method().toUpperCase() + " not allowed")
                    .header("Accept", Http.GET);
            return false;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy