Search in sources :

Example 6 with CssCompressor

use of com.yahoo.platform.yui.compressor.CssCompressor in project htmlcompressor by hazendaz.

the class YuiCssCompressor method compress.

@Override
public String compress(String source) {
    StringWriter result = new StringWriter();
    try {
        CssCompressor compressor = new CssCompressor(new StringReader(source));
        compressor.compress(result, lineBreak);
    } catch (IOException e) {
        result.write(source);
        logger.error("", e);
    }
    return result.toString();
}
Also used : StringWriter(java.io.StringWriter) CssCompressor(com.yahoo.platform.yui.compressor.CssCompressor) StringReader(java.io.StringReader) IOException(java.io.IOException)

Example 7 with CssCompressor

use of com.yahoo.platform.yui.compressor.CssCompressor 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 zimbraXZimletCompatibleWith = req.getParameter("zimbraXZimletCompatibleWith");
    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");
            String mintext = null;
            if (zimbraXZimletCompatibleWith != null) {
                mintext = compile(text);
            } else {
                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);
                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) SourceFile(com.google.javascript.jscomp.SourceFile) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 8 with CssCompressor

use of com.yahoo.platform.yui.compressor.CssCompressor in project xwiki-platform by xwiki.

the class CssExtension method getCompressor.

@Override
public SxCompressor getCompressor() {
    return new SxCompressor() {

        @Override
        public String compress(String source) {
            try {
                CssCompressor compressor = new CssCompressor(new StringReader(source));
                StringWriter out = new StringWriter();
                compressor.compress(out, -1);
                return out.toString();
            } catch (IOException ex) {
                LOGGER.warn("Exception compressing SSX code", ex);
            }
            return source;
        }
    };
}
Also used : StringWriter(java.io.StringWriter) CssCompressor(com.yahoo.platform.yui.compressor.CssCompressor) StringReader(java.io.StringReader) IOException(java.io.IOException)

Example 9 with CssCompressor

use of com.yahoo.platform.yui.compressor.CssCompressor in project wombat by PLOS.

the class AssetServiceImpl method compileAsset.

/**
 * Minifies the given asset file and returns the file and its contents.
 *
 * @param uncompiled uncompiled asset file
 * @return File that has been minified.  The file name will contain a hash reflecting the file's contents.
 * @throws IOException
 */
private CompiledAsset compileAsset(AssetType assetType, File uncompiled) throws IOException {
    // Compile to memory instead of a file directly, since we will need the raw bytes
    // in order to generate a hash (which appears in the filename).
    ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFFER_SIZE);
    try (InputStreamReader isr = new InputStreamReader(new FileInputStream(uncompiled));
        OutputStreamWriter osw = new OutputStreamWriter(baos)) {
        if (assetType == AssetType.CSS) {
            CssCompressor compressor = new CssCompressor(isr);
            compressor.compress(osw, -1);
        } else if (assetType == AssetType.JS) {
            JavaScriptCompressor compressor = new JavaScriptCompressor(isr, new JsErrorReporter());
            compressor.compress(osw, -1, true, false, true, false);
        } else {
            throw new IllegalArgumentException("Unexpected asset type " + assetType);
        }
    }
    byte[] contents = baos.toByteArray();
    String contentHash = CacheKey.createContentHash(contents);
    CompiledDigest digest = new CompiledDigest(AssetUrls.COMPILED_NAME_PREFIX + contentHash + assetType.getExtension());
    File file = digest.getFile();
    // Overwrite if the file already exists.
    if (file.exists()) {
        file.delete();
    }
    try (OutputStream os = new FileOutputStream(file)) {
        IOUtils.write(contents, os);
    }
    return new CompiledAsset(digest, contents);
}
Also used : InputStreamReader(java.io.InputStreamReader) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) CssCompressor(com.yahoo.platform.yui.compressor.CssCompressor) ByteArrayOutputStream(java.io.ByteArrayOutputStream) JavaScriptCompressor(com.yahoo.platform.yui.compressor.JavaScriptCompressor) FileInputStream(java.io.FileInputStream) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File)

Example 10 with CssCompressor

use of com.yahoo.platform.yui.compressor.CssCompressor in project jmix by jmix-framework.

the class ThemeCompile method performCssCompression.

protected void performCssCompression(File themeDir, File cssFile) {
    getLogger().info("[ThemeCompile] compress theme '{}'", themeDir.getName());
    File compressedFile = new File(cssFile.getAbsolutePath() + ".compressed");
    try (FileReader cssReader = new FileReader(cssFile);
        Writer out = new BufferedWriter(new FileWriter(compressedFile))) {
        CssCompressor compressor = new CssCompressor(cssReader);
        compressor.compress(out, 0);
    } catch (IOException e) {
        throw new GradleException("Unable to minify CSS theme " + themeDir.getName(), e);
    }
    if (compressedFile.exists()) {
        try {
            FileUtils.forceDelete(cssFile);
        } catch (IOException e) {
            throw new GradleException("Unable to delete CSS file " + cssFile.getAbsolutePath(), e);
        }
        boolean renamed = compressedFile.renameTo(cssFile);
        if (!renamed) {
            throw new GradleException("Unable to move file " + cssFile.getAbsolutePath());
        }
    }
}
Also used : GradleException(org.gradle.api.GradleException) CssCompressor(com.yahoo.platform.yui.compressor.CssCompressor)

Aggregations

CssCompressor (com.yahoo.platform.yui.compressor.CssCompressor)10 JavaScriptCompressor (com.yahoo.platform.yui.compressor.JavaScriptCompressor)5 StringReader (java.io.StringReader)5 StringWriter (java.io.StringWriter)5 IOException (java.io.IOException)3 File (java.io.File)2 FileOutputStream (java.io.FileOutputStream)2 InputStreamReader (java.io.InputStreamReader)2 OutputStreamWriter (java.io.OutputStreamWriter)2 Reader (java.io.Reader)2 Writer (java.io.Writer)2 SourceFile (com.google.javascript.jscomp.SourceFile)1 HtmlCompressor (com.googlecode.htmlcompressor.compressor.HtmlCompressor)1 XmlCompressor (com.googlecode.htmlcompressor.compressor.XmlCompressor)1 EvaluatorException (com.yahoo.platform.yui.org.mozilla.javascript.EvaluatorException)1 BufferedOutputStream (java.io.BufferedOutputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 FileInputStream (java.io.FileInputStream)1 OutputStream (java.io.OutputStream)1 PrintWriter (java.io.PrintWriter)1