Search in sources :

Example 1 with EvaluatorException

use of org.mozilla.javascript.EvaluatorException in project OpenAM by OpenRock.

the class StandardScriptValidator method getScriptErrors.

/**
     * Convert from ScriptException to ScriptError.
     *
     * @param script the script that was validated.
     * @param se the error thrown by the validation task.
     * @return the converted script error.
     */
private List<ScriptError> getScriptErrors(ScriptObject script, ScriptException se) {
    final List<ScriptError> scriptErrorList = new ArrayList<ScriptError>();
    final Throwable cause = se.getCause();
    // with useful information so we have to retrieve it from the cause exception.
    if (cause instanceof EvaluatorException) {
        final EvaluatorException ee = (EvaluatorException) cause;
        final ScriptError error = new ScriptError();
        error.setScriptName(script.getName());
        error.setMessage(ee.details());
        error.setLineNumber(ee.lineNumber());
        error.setColumnNumber(ee.columnNumber());
        scriptErrorList.add(error);
    } else if (cause instanceof MultipleCompilationErrorsException) {
        ErrorCollector errorCollector = ((MultipleCompilationErrorsException) cause).getErrorCollector();
        for (int i = 0; i < errorCollector.getErrorCount(); i++) {
            final SyntaxException syntaxException = errorCollector.getSyntaxError(i);
            final ScriptError error = new ScriptError();
            error.setScriptName(script.getName());
            error.setMessage(syntaxException.getOriginalMessage());
            error.setLineNumber(syntaxException.getLine());
            error.setColumnNumber(syntaxException.getStartColumn());
            scriptErrorList.add(error);
        }
    } else {
        final ScriptError error = new ScriptError();
        error.setScriptName(script.getName());
        error.setMessage(se.getMessage());
        error.setLineNumber(se.getLineNumber());
        error.setColumnNumber(se.getColumnNumber());
        scriptErrorList.add(error);
    }
    return scriptErrorList;
}
Also used : EvaluatorException(org.mozilla.javascript.EvaluatorException) SyntaxException(org.codehaus.groovy.syntax.SyntaxException) ArrayList(java.util.ArrayList) ErrorCollector(org.codehaus.groovy.control.ErrorCollector) MultipleCompilationErrorsException(org.codehaus.groovy.control.MultipleCompilationErrorsException)

Example 2 with EvaluatorException

use of org.mozilla.javascript.EvaluatorException in project hackpad by dropbox.

the class Main method exec.

private int exec(String[] args) {
    R = new ToolErrorReporter(true, System.err);
    int arg_count = process_options(args);
    if (arg_count == 0) {
        option_error(ToolErrorReporter.getMessage("msg.idswitch.no_file_argument"));
        return -1;
    }
    if (arg_count > 1) {
        option_error(ToolErrorReporter.getMessage("msg.idswitch.too_many_arguments"));
        return -1;
    }
    P = new CodePrinter();
    P.setIndentStep(4);
    P.setIndentTabSize(0);
    try {
        process_file(args[0]);
    } catch (IOException ex) {
        print_error(ToolErrorReporter.getMessage("msg.idswitch.io_error", ex.toString()));
        return -1;
    } catch (EvaluatorException ex) {
        return -1;
    }
    return 0;
}
Also used : EvaluatorException(org.mozilla.javascript.EvaluatorException) ToolErrorReporter(org.mozilla.javascript.tools.ToolErrorReporter)

Example 3 with EvaluatorException

use of org.mozilla.javascript.EvaluatorException in project hackpad by dropbox.

the class StrictModeApiTest method testStrictModeError.

public void testStrictModeError() {
    contextFactory = new MyContextFactory();
    Context cx = contextFactory.enterContext();
    try {
        global = cx.initStandardObjects();
        try {
            runScript("({}.nonexistent);");
            fail();
        } catch (EvaluatorException e) {
            assertTrue(e.getMessage().startsWith("Reference to undefined property"));
        }
    } finally {
        Context.exit();
    }
}
Also used : Context(org.mozilla.javascript.Context) EvaluatorException(org.mozilla.javascript.EvaluatorException)

Example 4 with EvaluatorException

use of org.mozilla.javascript.EvaluatorException 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 5 with EvaluatorException

use of org.mozilla.javascript.EvaluatorException 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

EvaluatorException (org.mozilla.javascript.EvaluatorException)7 Context (org.mozilla.javascript.Context)2 ErrorReporter (org.mozilla.javascript.ErrorReporter)2 NativeJavaObject (org.mozilla.javascript.NativeJavaObject)2 CssCompressor (com.yahoo.platform.yui.compressor.CssCompressor)1 JavaScriptCompressor (com.yahoo.platform.yui.compressor.JavaScriptCompressor)1 CmdLineParser (jargs.gnu.CmdLineParser)1 File (java.io.File)1 PrintWriter (java.io.PrintWriter)1 StringReader (java.io.StringReader)1 StringWriter (java.io.StringWriter)1 ArrayList (java.util.ArrayList)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 HttpServletRequestWrapper (javax.servlet.http.HttpServletRequestWrapper)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1