com.log4ic.compressor.servlet.CompressionServlet.java Source code

Java tutorial

Introduction

Here is the source code for com.log4ic.compressor.servlet.CompressionServlet.java

Source

/*
 * Dynamic Compressor - Java Library
 * Copyright (c) 2011-2012, IntelligentCode ZhangLixin.
 * All rights reserved.
 * intelligentcodemail@gmail.com
 *
 * GUN GPL 3.0 License
 *
 * http://www.gnu.org/licenses/gpl.html
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.log4ic.compressor.servlet;

import com.google.common.css.compiler.ast.GssParserException;
import com.log4ic.compressor.cache.CacheManager;
import com.log4ic.compressor.cache.CacheType;
import com.log4ic.compressor.cache.impl.simple.SimpleCacheManager;
import com.log4ic.compressor.exception.CompressionException;
import com.log4ic.compressor.exception.QueryStringEmptyException;
import com.log4ic.compressor.exception.UnsupportedFileTypeException;
import com.log4ic.compressor.utils.Compressor;
import com.log4ic.compressor.utils.FileUtils;
import com.log4ic.compressor.utils.less.exception.LessException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * JS CSS Servlet
 *
 * @author  IntelligentCode
 */
public class CompressionServlet extends HttpServlet {

    private static CacheManager cacheManager = null;
    private static boolean initialized = false;
    private static String fileDomain = null;
    private static Logger logger = LoggerFactory.getLogger(CompressionServlet.class);

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf8");
        PrintWriter writer = resp.getWriter();
        //TODO ?,?
        try {
            Compressor.compress(req, resp, cacheManager, fileDomain);
        } catch (QueryStringEmptyException e) {
            logger.error("?.", e);
            //501 - Not Implemented ?????
            resp.setStatus(501);
            writer.write("?." + e.getMessage());
        } catch (UnsupportedFileTypeException e) {
            logger.error("???.", e);
            //501 - Not Implemented ?????
            resp.setStatus(501);
            writer.write("???." + e.getMessage());
        } catch (CompressionException e) {
            logger.error("?.", e);
            //501 - Not Implemented ?????
            resp.setStatus(501);
            writer.write("?." + e.getMessage());
        } catch (GssParserException e) {
            logger.error("?,CSS.", e);
            //501 - Not Implemented ?????
            resp.setStatus(501);
            writer.write("?,CSS." + e.getMessage());
        } catch (LessException e) {
            logger.error("?,CSS.", e);
            //501 - Not Implemented ?????
            resp.setStatus(501);
            writer.write("?,CSS." + e.getMessage());
        }
    }

    protected String getRootAbsolutePath(ServletContext context) {
        String prefix = context.getRealPath("/");

        if (StringUtils.isBlank(prefix)) {
            java.net.URL url = this.getClass().getResource("/");
            prefix = url.getFile();
        }
        if (!prefix.endsWith("/")) {
            prefix += "/";
        }
        return prefix;
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        if (!initialized) {
            String cacheDir;
            CacheType cacheType = null;
            Integer cacheCount = null;
            boolean autoClean = true;
            int cleanHourAgo = 4;
            int lowHit = 3;
            if (config != null) {
                //?
                cacheDir = config.getInitParameter("cacheDir");
                if (StringUtils.isNotBlank(cacheDir)) {
                    if (cacheDir.startsWith("{contextPath}")) {
                        cacheDir = getRootAbsolutePath(config.getServletContext())
                                + cacheDir.replace("{contextPath}", "");
                    }
                    cacheDir = FileUtils.appendSeparator(cacheDir);
                } else {
                    cacheDir = getRootAbsolutePath(config.getServletContext()) + "static/compressed/";
                }
                //
                String cacheTypeStr = config.getInitParameter("cacheType");
                if (StringUtils.isNotBlank(cacheTypeStr)) {
                    try {
                        cacheType = CacheType.valueOf(cacheTypeStr.toUpperCase());
                    } catch (IllegalArgumentException e) {
                    }
                }
                if ("none".equals(cacheTypeStr)) {
                    cacheType = null;
                }
                //
                String cacheCountStr = config.getInitParameter("cacheCount");
                if (StringUtils.isNotBlank(cacheCountStr)) {
                    try {
                        cacheCount = Integer.parseInt(cacheCountStr);
                    } catch (Exception e) {
                    }
                }
                if (cacheCount == null) {
                    cacheCount = 5000;
                }

                String autoCleanStr = config.getInitParameter("autoClean");

                if (StringUtils.isNotBlank(autoCleanStr)) {
                    try {
                        autoClean = Boolean.parseBoolean(autoCleanStr);
                    } catch (Exception e) {
                    }
                }

                String fileDomain = config.getInitParameter("fileDomain");

                if (StringUtils.isNotBlank(fileDomain)) {
                    CompressionServlet.fileDomain = fileDomain;
                }

                Class cacheManagerClass = null;
                String cacheManagerClassStr = config.getInitParameter("cacheManager");
                if (StringUtils.isNotBlank(cacheManagerClassStr)) {
                    try {
                        cacheManagerClass = CompressionServlet.class.getClassLoader()
                                .loadClass(cacheManagerClassStr);
                    } catch (ClassNotFoundException e) {
                        logger.error("??!", e);
                    }
                } else {
                    cacheManagerClass = SimpleCacheManager.class;
                }

                if (autoClean) {
                    String cleanIntervalStr = config.getInitParameter("cleanInterval");
                    long cleanInterval = 1000 * 60 * 60 * 5L;
                    if (StringUtils.isNotBlank(cleanIntervalStr)) {
                        try {
                            cleanInterval = Long.parseLong(cleanIntervalStr);
                        } catch (Exception e) {
                        }
                    }
                    String lowHitStr = config.getInitParameter("cleanLowHit");

                    if (StringUtils.isNotBlank(lowHitStr)) {
                        try {
                            lowHit = Integer.parseInt(autoCleanStr);
                        } catch (Exception e) {
                        }
                    }
                    String cleanHourAgoStr = config.getInitParameter("cleanHourAgo");

                    if (StringUtils.isNotBlank(cleanHourAgoStr)) {
                        try {
                            cleanHourAgo = Integer.parseInt(cleanHourAgoStr);
                        } catch (Exception e) {
                        }
                    }
                    if (cacheType != null) {
                        try {
                            Constructor constructor = cacheManagerClass.getConstructor(CacheType.class, int.class,
                                    int.class, int.class, long.class, String.class);
                            cacheManager = (CacheManager) constructor.newInstance(cacheType, cacheCount, lowHit,
                                    cleanHourAgo, cleanInterval, cacheDir);
                        } catch (NoSuchMethodException e) {
                            logger.error("??", e);
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        } catch (InstantiationException e) {
                            logger.error("??", e);
                        } catch (IllegalAccessException e) {
                            logger.error("??", e);
                        } catch (Exception e) {
                            logger.error("??", e);
                        }
                    }
                } else {
                    if (cacheType != null) {
                        try {
                            Constructor constructor = cacheManagerClass.getConstructor(CacheType.class, int.class,
                                    String.class);
                            cacheManager = (CacheManager) constructor.newInstance(cacheType, cacheCount, cacheDir);
                        } catch (NoSuchMethodException e) {
                            logger.error("??", e);
                        } catch (InvocationTargetException e) {
                            logger.error("??", e);
                        } catch (InstantiationException e) {
                            logger.error("??", e);
                        } catch (IllegalAccessException e) {
                            logger.error("??", e);
                        } catch (Exception e) {
                            logger.error("??", e);
                        }
                    }
                }
            }
            initialized = true;
        }
    }
}