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

com.devops4j.embedded.handler.StaticHttpHandler Maven / Gradle / Ivy

package com.devops4j.embedded.handler;

import com.devops4j.embedded.servlet.EmbeddedHttpServletRequest;
import com.devops4j.embedded.httpserver.HttpExchange;
import com.devops4j.embedded.httpserver.HttpHandler;
import com.devops4j.message.MessageFormatter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletResponse;

import com.devops4j.embedded.servlet.EmbeddedHttpServletResponse;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.concurrent.Executor;

/**
 * Created by devops4j on 2018/1/26.
 */
@Slf4j
public class StaticHttpHandler implements HttpHandler {
    Executor executor;
    ClassLoader classLoader;
    final boolean forceHttps;
    final String webapp;
    public StaticHttpHandler(ClassLoader classLoader, Executor executor, boolean forceHttps, String webapp) {
        this.classLoader = classLoader;
        this.executor = executor;
        this.forceHttps = forceHttps;
        this.webapp = webapp;
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        final EmbeddedHttpServletRequest request = new EmbeddedHttpServletRequest(exchange);
        final EmbeddedHttpServletResponse response = new EmbeddedHttpServletResponse(exchange);
        this.executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    if(forceHttps && request.getScheme().equalsIgnoreCase("http")){
                        String newUrl =  "https://" + request.getServerName()  + request.getContextPath();
                        if (!request.getQueryString().isEmpty()) {
                            newUrl += "?" + request.getQueryString();
                        }
                        response.sendRedirect(newUrl);
                        return;
                    }
                    if (request.getRequestURI().equals("/")) {
                        response.sendRedirect("/index.html");
                    } else {
                        //加载静态资源
                        staticResource(request, response);
                    }
                } catch (IOException e) {
                    try {
                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getLocalizedMessage());
                    } catch (IOException e1) {
                        //nothing
                    }
                } finally {
                    try {
                        response.flushBuffer();
                    } catch (IOException e) {
                        throw new RuntimeException("写入结果发生异常", e);
                    }
                }
            }
        });
    }


    /**
     * 静态资源
     *
     * @param request  请求
     * @param response 应答
     * @throws IOException 异常
     */
    boolean staticResource(EmbeddedHttpServletRequest request, EmbeddedHttpServletResponse response) throws IOException {
        String url =  request.getScheme() + "://" + request.getServerName()  + request.getContextPath();
        if (!request.getQueryString().isEmpty()) {
            url += "?" + request.getQueryString();
        }
        //路径
        String path = "";
        //文件名
        String fileName = request.getRequestURI().replaceAll("\\\\", "/");
        if(fileName.startsWith("/")){
            fileName = fileName.substring(1);
        }
        int lastPos = fileName.lastIndexOf("/");
        if (lastPos > -1) {
            path = fileName.substring(0, lastPos);
            fileName = fileName.substring(lastPos + 1);
            if (path.endsWith("/")) {
                path = path.substring(0, path.length() - 1);
            }
        }
        int lastFilePos = fileName.lastIndexOf(".");
        //文件资源必须有后缀名
        if (lastFilePos > -1) {
            String suffix = fileName.substring(lastFilePos + 1);
            suffix = suffix.toLowerCase();
            if ("css".equals(suffix)) {
                response.setHeader("Content-Type", "text/css; charset=UTF-8");
            } else if ("js".equals(suffix)) {
                response.setHeader("Content-Type", "application/x-javascript; charset=UTF-8");
            } else if ("jpg".equals(suffix) || "jpeg".equals(suffix)) {
                response.setHeader("Content-Type", "image/jpeg");
            } else if ("gif".equals(suffix)) {
                response.setHeader("Content-Type", "image/gif");
            } else if ("png".equals(suffix)) {
                response.setHeader("Content-Type", "image/png");
            } else if ("ico".equals(suffix)) {
                response.setHeader("Content-Type", "image/x-icon");
            } else if ("htm".equals(suffix) || "html".equals(suffix)) {
                response.setHeader("Content-Type", "text/html; charset=UTF-8");
            } else if ("xml".equals(suffix)) {
                response.setHeader("Content-Type", "text/xml; charset=UTF-8");
            } else if ("svg".equals(suffix)) {
                response.setHeader("Content-Type", "image/svg+xml; charset=UTF-8");
            } else if ("svg".equals(suffix)) {
                response.setHeader("Content-Type", "image/svg+xml; charset=UTF-8");
            } else if ("woff".equals(suffix)) {
                response.setHeader("Content-Type", "application/x-font-woff; charset=UTF-8");
            } else if ("woff2".equals(suffix)) {
                response.setHeader("Content-Type", "application/octet-stream");
            } else if ("eot".equals(suffix)) {
                response.setHeader("Content-Type", "application/vnd.ms-fontobject");
            } else if ("ttf".equals(suffix)) {
                response.setHeader("Content-Type", "application/x-font-ttf");
            } else {
                response.setHeader("Content-Type", "application/octet-stream");
            }
        }
        InputStream is = null;
        try {
            String name = webapp + "/";
            if (path.isEmpty()) {
                name += fileName;
            } else {
                name += path + "/" + fileName;
            }
            URL url_ = classLoader.getResource(name);
            if (url_ == null) {
                throw new FileNotFoundException(MessageFormatter.format("file '{}' is not found!", name));
            }
            byte[] temp = new byte[100];
            is = url_.openStream();
            int byteReadLen = 0;
            while ((byteReadLen = is.read(temp)) != -1) {
                if (byteReadLen == 100) {
                    response.write(temp);
                } else {
                    byte[] data = new byte[byteReadLen];
                    System.arraycopy(temp, 0, data, 0, byteReadLen);
                    response.write(data);
                }
            }
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        } catch (FileNotFoundException e) {
            log.error("file is not found", e);
            response.write(url + " is not found!");
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return false;
        } catch (Exception e) {
            log.error("happens unknown error!", e);
            response.write(url + " server happens unknown error! cause :'" + e + "'");
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return false;
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy