Search in sources :

Example 1 with JavaScriptCompressor

use of com.yahoo.platform.yui.compressor.JavaScriptCompressor in project yui-compressor-ant-task by n0ha.

the class YuiCompressorTask method compressFile.

private void compressFile(final File inFile, final File outFile, final String fileType) throws EvaluatorException, BuildException {
    // always recompress when outFile and inFile are exactly the same file
    if (outFile.isFile() && !inFile.getAbsolutePath().equals(outFile.getAbsolutePath())) {
        if (outFile.lastModified() >= inFile.lastModified()) {
            return;
        }
    }
    try {
        // prepare input file
        Reader in = openFile(inFile);
        // prepare output file
        outFile.getParentFile().mkdirs();
        Writer out = new OutputStreamWriter(new FileOutputStream(outFile), charset);
        if (fileType.equals(FileType.JS_FILE)) {
            final JavaScriptCompressor compressor = createJavaScriptCompressor(in);
            compressor.compress(out, lineBreakPosition, munge, warn, preserveAllSemiColons, !optimize);
        } else if (fileType.equals(FileType.CSS_FILE)) {
            final CssCompressor compressor = new CssCompressor(in);
            compressor.compress(out, lineBreakPosition);
        } else if (fileType.equals(FileType.HTML_FILE) || fileType.equals(FileType.XHTML_FILE)) {
            final HtmlCompressor compressor = new HtmlCompressor();
            out.write(compressor.compress(readerToString(in)));
        } else if (fileType.equals(FileType.XML_FILE)) {
            final XmlCompressor compressor = new XmlCompressor();
            out.write(compressor.compress(readerToString(in)));
        }
        // close all streams
        in.close();
        in = null;
        out.close();
        out = null;
        if (verbose) {
            log(stats.getFileStats(inFile, outFile, fileType));
        }
    } catch (final IOException ioe) {
        throw new BuildException("I/O Error when compressing file", ioe);
    }
}
Also used : FileOutputStream(java.io.FileOutputStream) CssCompressor(com.yahoo.platform.yui.compressor.CssCompressor) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) XmlCompressor(com.googlecode.htmlcompressor.compressor.XmlCompressor) OutputStreamWriter(java.io.OutputStreamWriter) HtmlCompressor(com.googlecode.htmlcompressor.compressor.HtmlCompressor) IOException(java.io.IOException) BuildException(org.apache.tools.ant.BuildException) JavaScriptCompressor(com.yahoo.platform.yui.compressor.JavaScriptCompressor) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter)

Example 2 with JavaScriptCompressor

use of com.yahoo.platform.yui.compressor.JavaScriptCompressor in project zm-mailbox by Zimbra.

the class ZimletResources method service.

@Override
public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException {
    if (flushCache(request)) {
        return;
    }
    ZimbraLog.clearContext();
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    String uri = req.getRequestURI();
    String pathInfo = req.getPathInfo();
    if (pathInfo == null) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    @SuppressWarnings("unchecked") Set<String> zimletNames = (Set<String>) req.getAttribute(ZimletFilter.ALLOWED_ZIMLETS);
    Set<String> allZimletNames = (Set<String>) req.getAttribute(ZimletFilter.ALL_ZIMLETS);
    if (!pathInfo.startsWith(RESOURCE_PATH)) {
        // handle requests for individual files included in zimlet in case dev=1 is set.
        ServletContext targetContext = getServletConfig().getServletContext().getContext("/zimlet");
        if (targetContext == null) {
            throw new ServletException("Could not forward the request to zimlet webapp, possible misconfiguration.");
        }
        RequestDispatcher dispatcher = targetContext.getRequestDispatcher(pathInfo);
        dispatcher.forward(req, resp);
        return;
    }
    String contentType = getContentType(uri);
    String type = contentType.replaceAll("^.*/", "");
    boolean debug = req.getParameter(P_DEBUG) != null;
    boolean compress = !debug && supportsGzip && uri.endsWith(COMPRESSED_EXT);
    String cacheId = getCacheId(req, type, zimletNames, allZimletNames);
    if (ZimbraLog.zimlet.isDebugEnabled()) {
        ZimbraLog.zimlet.debug("DEBUG: uri=" + uri);
        ZimbraLog.zimlet.debug("DEBUG: cacheId=" + cacheId);
        ZimbraLog.zimlet.debug("DEBUG: contentType=" + contentType);
        ZimbraLog.zimlet.debug("DEBUG: type=" + type);
    }
    // generate buffer
    File file = !debug ? getCacheFile(cacheId) : null;
    String text = null;
    if (file == null || !file.exists()) {
        StringWriter writer = new StringWriter();
        PrintWriter printer = new PrintWriter(writer);
        // zimlet messages
        if (type.equals(T_JAVASCRIPT)) {
            ServletConfig config = this.getServletConfig();
            ServletContext baseContext = config.getServletContext();
            RequestDispatcher dispatcher = baseContext.getRequestDispatcher(RESOURCE_PATH);
            // NOTE: descriptions can be translated.
            for (String zimletName : allZimletNames) {
                RequestWrapper wrappedReq = new RequestWrapper(req, RESOURCE_PATH + zimletName);
                ResponseWrapper wrappedResp = new ResponseWrapper(resp, printer);
                // bug 45922: avoid cached messages
                wrappedReq.setParameter("debug", "1");
                //this will activate ZimletProps2JsServlet
                dispatcher.include(wrappedReq, wrappedResp);
            }
        }
        // zimlet resources
        if (ZimbraLog.zimlet.isDebugEnabled()) {
            ZimbraLog.zimlet.debug("DEBUG: generating buffer");
        }
        generate(zimletNames, type, printer);
        text = writer.toString();
        // minimize css
        if (type.equals(T_CSS) && !debug) {
            CssCompressor compressor = new CssCompressor(new StringReader(text));
            StringWriter out = new StringWriter();
            compressor.compress(out, 0);
            text = out.toString();
        }
        if (type.equals(T_JAVASCRIPT) && !debug) {
            // compress JS code
            text = text.replaceAll("(^|\n)\\s*DBG\\.\\w+\\(.*\\);\\s*(\n|$)", "\n");
            JavaScriptCompressor compressor = new JavaScriptCompressor(new StringReader(text), new ErrorReporter() {

                @Override
                public void warning(String message, String sourceName, int line, String lineSource, int lineOffset) {
                    if (line < 0) {
                        ZimbraLog.zimlet.warn("\n" + message);
                    } else {
                        ZimbraLog.zimlet.warn("\n" + line + ':' + lineOffset + ':' + message);
                    }
                }

                @Override
                public void error(String message, String sourceName, int line, String lineSource, int lineOffset) {
                    if (line < 0) {
                        ZimbraLog.zimlet.error("\n" + message);
                    } else {
                        ZimbraLog.zimlet.error("\n" + line + ':' + lineOffset + ':' + message);
                    }
                }

                @Override
                public EvaluatorException runtimeError(String message, String sourceName, int line, String lineSource, int lineOffset) {
                    error(message, sourceName, line, lineSource, lineOffset);
                    return new EvaluatorException(message);
                }
            });
            StringWriter out = new StringWriter();
            compressor.compress(out, 0, true, false, false, false);
            String mintext = out.toString();
            if (mintext == null) {
                ZimbraLog.zimlet.info("unable to minimize zimlet JS source");
            } else {
                text = mintext;
            }
        }
        // store buffer
        if (!debug) {
            // NOTE: This assumes that the cacheId will *end* with the compressed
            // NOTE: extension. Therefore, make sure to keep getCacheId in sync.
            String uncompressedCacheId = compress ? cacheId.substring(0, cacheId.length() - COMPRESSED_EXT.length()) : cacheId;
            // store uncompressed file in cache
            file = createCacheFile(uncompressedCacheId, type);
            if (ZimbraLog.zimlet.isDebugEnabled()) {
                ZimbraLog.zimlet.debug("DEBUG: buffer file: " + file);
            }
            copy(text, file);
            putCacheFile(uncompressedCacheId, file);
            // store compressed file in cache
            if (compress) {
                String compressedCacheId = cacheId;
                File gzfile = createCacheFile(compressedCacheId, type + DiskCacheServlet.EXT_COMPRESSED);
                if (ZimbraLog.zimlet.isDebugEnabled()) {
                    ZimbraLog.zimlet.debug("DEBUG: buffer file: " + gzfile);
                }
                file = compress(file, gzfile);
                putCacheFile(compressedCacheId, file);
            }
        }
    } else {
        if (ZimbraLog.zimlet.isDebugEnabled()) {
            ZimbraLog.zimlet.debug("DEBUG: using previous buffer");
        }
    }
    // write buffer
    try {
        // We browser sniff so need to make sure any caches do the same.
        resp.addHeader("Vary", "User-Agent");
        if (file == null || req.getProtocol().endsWith("1.0")) {
            // Bug 20626: We're no longer caching zimlets
            // Set to expire far in the past.
            resp.setHeader("Expires", "Tue, 24 Jan 2000 17:46:50 GMT");
            // Set standard HTTP/1.1 no-cache headers.
            resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
            // Set standard HTTP/1.0 no-cache header.
            resp.setHeader("Pragma", "no-cache");
        } else {
            // force cache revalidation but allow client cache
            resp.setHeader("Cache-Control", "must-revalidate, max-age=0");
            if (file.lastModified() <= req.getDateHeader("If-Modified-Since")) {
                resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                return;
            }
            resp.setDateHeader("Last-Modified", file.lastModified());
        }
        resp.setContentType(contentType);
        if (compress && file != null) {
            resp.setHeader("Content-Encoding", "gzip");
        }
        // NOTE: the contents of the generated file to the stream.
        if (!compress || file != null) {
            resp.setContentLength(file != null ? (int) file.length() : text.getBytes("UTF-8").length);
        }
    } catch (IllegalStateException e) {
        // ignore -- thrown if called from including JSP
        ZimbraLog.zimlet.debug("zimletres: " + cacheId);
        ZimbraLog.zimlet.debug("zimletres: " + e.getMessage());
    }
    if (file != null) {
        // NOTE: If we saved the buffer to a file and compression is
        // NOTE: enabled then the file has *already* been compressed
        // NOTE: and the Content-Encoding header has been added.
        copy(file, resp, false);
    } else {
        copy(text, resp, compress);
    }
}
Also used : Set(java.util.Set) ServletConfig(javax.servlet.ServletConfig) CssCompressor(com.yahoo.platform.yui.compressor.CssCompressor) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpServletResponseWrapper(javax.servlet.http.HttpServletResponseWrapper) JavaScriptCompressor(com.yahoo.platform.yui.compressor.JavaScriptCompressor) RequestDispatcher(javax.servlet.RequestDispatcher) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ErrorReporter(org.mozilla.javascript.ErrorReporter) StringWriter(java.io.StringWriter) EvaluatorException(org.mozilla.javascript.EvaluatorException) StringReader(java.io.StringReader) ServletContext(javax.servlet.ServletContext) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) File(java.io.File) PrintWriter(java.io.PrintWriter)

Aggregations

CssCompressor (com.yahoo.platform.yui.compressor.CssCompressor)2 JavaScriptCompressor (com.yahoo.platform.yui.compressor.JavaScriptCompressor)2 HtmlCompressor (com.googlecode.htmlcompressor.compressor.HtmlCompressor)1 XmlCompressor (com.googlecode.htmlcompressor.compressor.XmlCompressor)1 File (java.io.File)1 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 OutputStreamWriter (java.io.OutputStreamWriter)1 PrintWriter (java.io.PrintWriter)1 Reader (java.io.Reader)1 StringReader (java.io.StringReader)1 StringWriter (java.io.StringWriter)1 Writer (java.io.Writer)1 Set (java.util.Set)1 RequestDispatcher (javax.servlet.RequestDispatcher)1 ServletConfig (javax.servlet.ServletConfig)1 ServletContext (javax.servlet.ServletContext)1 ServletException (javax.servlet.ServletException)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1