Search in sources :

Example 1 with ErrorReporter

use of org.mozilla.javascript.ErrorReporter in project yuicompressor by yui.

the class YUICompressor method main.

public static void main(String[] args) {
    CmdLineParser parser = new CmdLineParser();
    CmdLineParser.Option typeOpt = parser.addStringOption("type");
    CmdLineParser.Option versionOpt = parser.addBooleanOption('V', "version");
    CmdLineParser.Option verboseOpt = parser.addBooleanOption('v', "verbose");
    CmdLineParser.Option nomungeOpt = parser.addBooleanOption("nomunge");
    CmdLineParser.Option linebreakOpt = parser.addStringOption("line-break");
    CmdLineParser.Option preserveSemiOpt = parser.addBooleanOption("preserve-semi");
    CmdLineParser.Option disableOptimizationsOpt = parser.addBooleanOption("disable-optimizations");
    CmdLineParser.Option helpOpt = parser.addBooleanOption('h', "help");
    CmdLineParser.Option charsetOpt = parser.addStringOption("charset");
    CmdLineParser.Option outputFilenameOpt = parser.addStringOption('o', "output");
    CmdLineParser.Option mungemapFilenameOpt = parser.addStringOption('m', "mungemap");
    CmdLineParser.Option preserveUnknownHintsOpt = parser.addBooleanOption('p', "preservehints");
    Reader in = null;
    Writer out = null;
    Writer mungemap = null;
    try {
        parser.parse(args);
        Boolean help = (Boolean) parser.getOptionValue(helpOpt);
        if (help != null && help.booleanValue()) {
            usage();
            System.exit(0);
        }
        Boolean version = (Boolean) parser.getOptionValue(versionOpt);
        if (version != null && version.booleanValue()) {
            version();
            System.exit(0);
        }
        boolean verbose = parser.getOptionValue(verboseOpt) != null;
        String charset = (String) parser.getOptionValue(charsetOpt);
        if (charset == null || !Charset.isSupported(charset)) {
            // charset = System.getProperty("file.encoding");
            // if (charset == null) {
            // charset = "UTF-8";
            // }
            // UTF-8 seems to be a better choice than what the system is reporting
            charset = "UTF-8";
            if (verbose) {
                System.err.println("\n[INFO] Using charset " + charset);
            }
        }
        int linebreakpos = -1;
        String linebreakstr = (String) parser.getOptionValue(linebreakOpt);
        if (linebreakstr != null) {
            try {
                linebreakpos = Integer.parseInt(linebreakstr, 10);
            } catch (NumberFormatException e) {
                usage();
                System.exit(1);
            }
        }
        String typeOverride = (String) parser.getOptionValue(typeOpt);
        if (typeOverride != null && !typeOverride.equalsIgnoreCase("js") && !typeOverride.equalsIgnoreCase("css")) {
            usage();
            System.exit(1);
        }
        boolean munge = parser.getOptionValue(nomungeOpt) == null;
        boolean preserveAllSemiColons = parser.getOptionValue(preserveSemiOpt) != null;
        boolean disableOptimizations = parser.getOptionValue(disableOptimizationsOpt) != null;
        boolean preserveUnknownHints = parser.getOptionValue(preserveUnknownHintsOpt) != null;
        String[] fileArgs = parser.getRemainingArgs();
        java.util.List files = java.util.Arrays.asList(fileArgs);
        if (files.isEmpty()) {
            if (typeOverride == null) {
                usage();
                System.exit(1);
            }
            files = new java.util.ArrayList();
            // read from stdin
            files.add("-");
        }
        String output = (String) parser.getOptionValue(outputFilenameOpt);
        String[] pattern;
        if (output == null) {
            pattern = new String[0];
        } else if (output.matches("(?i)^[a-z]\\:\\\\.*")) {
            // if output is with something like c:\ dont split it
            pattern = new String[] { output };
        } else {
            pattern = output.split(":");
        }
        try {
            String mungemapFilename = (String) parser.getOptionValue(mungemapFilenameOpt);
            if (mungemapFilename != null) {
                mungemap = new OutputStreamWriter(new FileOutputStream(mungemapFilename), charset);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
        java.util.Iterator filenames = files.iterator();
        while (filenames.hasNext()) {
            String inputFilename = (String) filenames.next();
            String type = null;
            try {
                if (inputFilename.equals("-")) {
                    in = new InputStreamReader(System.in, charset);
                    type = typeOverride;
                } else {
                    if (typeOverride != null) {
                        type = typeOverride;
                    } else {
                        int idx = inputFilename.lastIndexOf('.');
                        if (idx >= 0 && idx < inputFilename.length() - 1) {
                            type = inputFilename.substring(idx + 1);
                        }
                    }
                    if (type == null || !type.equalsIgnoreCase("js") && !type.equalsIgnoreCase("css")) {
                        usage();
                        System.exit(1);
                    }
                    in = new InputStreamReader(new FileInputStream(inputFilename), charset);
                }
                String outputFilename = output;
                // if a substitution pattern was passed in
                if (pattern.length > 1 && files.size() > 0) {
                    outputFilename = inputFilename.replaceFirst(pattern[0], pattern[1]);
                }
                if (type.equalsIgnoreCase("js")) {
                    try {
                        final String localFilename = inputFilename;
                        JavaScriptCompressor compressor = new JavaScriptCompressor(in, new ErrorReporter() {

                            public void warning(String message, String sourceName, int line, String lineSource, int lineOffset) {
                                System.err.println("\n[WARNING] in " + localFilename);
                                if (line < 0) {
                                    System.err.println("  " + message);
                                } else {
                                    System.err.println("  " + line + ':' + lineOffset + ':' + message);
                                }
                            }

                            public void error(String message, String sourceName, int line, String lineSource, int lineOffset) {
                                System.err.println("[ERROR] in " + localFilename);
                                if (line < 0) {
                                    System.err.println("  " + message);
                                } else {
                                    System.err.println("  " + line + ':' + lineOffset + ':' + message);
                                }
                            }

                            public EvaluatorException runtimeError(String message, String sourceName, int line, String lineSource, int lineOffset) {
                                error(message, sourceName, line, lineSource, lineOffset);
                                return new EvaluatorException(message);
                            }
                        });
                        // Close the input stream first, and then open the output stream,
                        // in case the output file should override the input file.
                        in.close();
                        in = null;
                        if (outputFilename == null) {
                            out = new OutputStreamWriter(System.out, charset);
                        } else {
                            out = new OutputStreamWriter(new FileOutputStream(outputFilename), charset);
                            if (mungemap != null) {
                                mungemap.write("\n\nFile: " + outputFilename + "\n\n");
                            }
                        }
                        compressor.compress(out, mungemap, linebreakpos, munge, verbose, preserveAllSemiColons, disableOptimizations, preserveUnknownHints);
                    } catch (EvaluatorException e) {
                        e.printStackTrace();
                        // Return a special error code used specifically by the web front-end.
                        System.exit(2);
                    }
                } else if (type.equalsIgnoreCase("css")) {
                    CssCompressor compressor = new CssCompressor(in);
                    // Close the input stream first, and then open the output stream,
                    // in case the output file should override the input file.
                    in.close();
                    in = null;
                    if (outputFilename == null) {
                        out = new OutputStreamWriter(System.out, charset);
                    } else {
                        out = new OutputStreamWriter(new FileOutputStream(outputFilename), charset);
                    }
                    compressor.compress(out, linebreakpos);
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    } catch (CmdLineParser.OptionException e) {
        usage();
        System.exit(1);
    } finally {
        if (mungemap != null) {
            try {
                mungemap.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
Also used : CmdLineParser(jargs.gnu.CmdLineParser) ErrorReporter(org.mozilla.javascript.ErrorReporter) EvaluatorException(org.mozilla.javascript.EvaluatorException)

Example 2 with ErrorReporter

use of org.mozilla.javascript.ErrorReporter in project scout.rt by eclipse.

the class MinifyJsWithYui method run.

public String run(String content, boolean munge) throws IOException {
    try (StringReader reader = new StringReader(content);
        StringWriter writer = new StringWriter()) {
        // Yui uses a modified version of rhino files (org.mozilla.javascript). If you get any class incompatibility errors this may be the reason.
        ErrorReporter errorReporter = new ErrorReporter() {

            @Override
            public void warning(String message, String sourceName, int line, String lineSource, int lineOffset) {
                System.out.println(MinifyJsWithYui.class.getSimpleName() + " warning: " + message);
            }

            @Override
            public EvaluatorException runtimeError(String message, String sourceName, int line, String lineSource, int lineOffset) {
                System.out.println(MinifyJsWithYui.class.getSimpleName() + " error: " + message);
                return null;
            }

            @Override
            public void error(String message, String sourceName, int line, String lineSource, int lineOffset) {
                System.out.println(MinifyJsWithYui.class.getSimpleName() + " error: " + message);
            }
        };
        JavaScriptCompressor compressor = new JavaScriptCompressor(reader, errorReporter);
        boolean verbose = false;
        boolean preserveAllSemicolons = false;
        boolean disableOptimizations = false;
        compressor.compress(writer, -1, munge, verbose, preserveAllSemicolons, disableOptimizations);
        writer.flush();
        return writer.toString();
    }
}
Also used : ErrorReporter(org.mozilla.javascript.ErrorReporter) StringWriter(java.io.StringWriter) StringReader(java.io.StringReader) JavaScriptCompressor(com.yahoo.platform.yui.compressor.JavaScriptCompressor)

Example 3 with ErrorReporter

use of org.mozilla.javascript.ErrorReporter 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 4 with ErrorReporter

use of org.mozilla.javascript.ErrorReporter in project pentaho-kettle by pentaho.

the class ScriptDialog method parseVariables.

// This could be useful for further improvements
public static ScriptNode parseVariables(Context cx, Scriptable scope, String source, String sourceName, int lineno, Object securityDomain) {
    // Interpreter compiler = new Interpreter();
    CompilerEnvirons evn = new CompilerEnvirons();
    // evn.setLanguageVersion(Context.VERSION_1_5);
    evn.setOptimizationLevel(-1);
    evn.setGeneratingSource(true);
    evn.setGenerateDebugInfo(true);
    ErrorReporter errorReporter = new ToolErrorReporter(false);
    Parser p = new Parser(evn, errorReporter);
    // IOException
    ScriptNode tree = p.parse(source, "", 0);
    new NodeTransformer().transform(tree);
    // Script result = (Script)compiler.compile(scope, evn, tree, p.getEncodedSource(),false, null);
    return tree;
}
Also used : ToolErrorReporter(org.mozilla.javascript.tools.ToolErrorReporter) ErrorReporter(org.mozilla.javascript.ErrorReporter) NodeTransformer(org.mozilla.javascript.NodeTransformer) CompilerEnvirons(org.mozilla.javascript.CompilerEnvirons) ToolErrorReporter(org.mozilla.javascript.tools.ToolErrorReporter) ScriptNode(org.mozilla.javascript.ast.ScriptNode) Parser(org.mozilla.javascript.Parser)

Example 5 with ErrorReporter

use of org.mozilla.javascript.ErrorReporter in project pentaho-kettle by pentaho.

the class ScriptValuesModDialog method parseVariables.

// This could be useful for further improvements
public static ScriptNode parseVariables(Context cx, Scriptable scope, String source, String sourceName, int lineno, Object securityDomain) {
    // Interpreter compiler = new Interpreter();
    CompilerEnvirons evn = new CompilerEnvirons();
    // evn.setLanguageVersion(Context.VERSION_1_5);
    evn.setOptimizationLevel(-1);
    evn.setGeneratingSource(true);
    evn.setGenerateDebugInfo(true);
    ErrorReporter errorReporter = new ToolErrorReporter(false);
    Parser p = new Parser(evn, errorReporter);
    // IOException
    ScriptNode tree = p.parse(source, "", 0);
    new NodeTransformer().transform(tree);
    // Script result = (Script)compiler.compile(scope, evn, tree, p.getEncodedSource(),false, null);
    return tree;
}
Also used : ToolErrorReporter(org.mozilla.javascript.tools.ToolErrorReporter) ErrorReporter(org.mozilla.javascript.ErrorReporter) NodeTransformer(org.mozilla.javascript.NodeTransformer) CompilerEnvirons(org.mozilla.javascript.CompilerEnvirons) ToolErrorReporter(org.mozilla.javascript.tools.ToolErrorReporter) ScriptNode(org.mozilla.javascript.ast.ScriptNode) Parser(org.mozilla.javascript.Parser)

Aggregations

ErrorReporter (org.mozilla.javascript.ErrorReporter)5 JavaScriptCompressor (com.yahoo.platform.yui.compressor.JavaScriptCompressor)2 StringReader (java.io.StringReader)2 StringWriter (java.io.StringWriter)2 CompilerEnvirons (org.mozilla.javascript.CompilerEnvirons)2 EvaluatorException (org.mozilla.javascript.EvaluatorException)2 NodeTransformer (org.mozilla.javascript.NodeTransformer)2 Parser (org.mozilla.javascript.Parser)2 ScriptNode (org.mozilla.javascript.ast.ScriptNode)2 ToolErrorReporter (org.mozilla.javascript.tools.ToolErrorReporter)2 SourceFile (com.google.javascript.jscomp.SourceFile)1 CssCompressor (com.yahoo.platform.yui.compressor.CssCompressor)1 CmdLineParser (jargs.gnu.CmdLineParser)1 File (java.io.File)1 PrintWriter (java.io.PrintWriter)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