Search in sources :

Example 1 with Binding

use of groovy.lang.Binding in project groovy by apache.

the class GroovyMain method process.

/**
     * Process the users request.
     *
     * @param line the parsed command line.
     * @throws ParseException if invalid options are chosen
     */
private static boolean process(CommandLine line) throws ParseException, IOException {
    List args = line.getArgList();
    if (line.hasOption('D')) {
        String[] values = line.getOptionValues('D');
        for (int i = 0; i < values.length; i++) {
            setSystemPropertyFrom(values[i]);
        }
    }
    GroovyMain main = new GroovyMain();
    // add the ability to parse scripts with a specified encoding
    main.conf.setSourceEncoding(line.getOptionValue('c', main.conf.getSourceEncoding()));
    main.isScriptFile = !line.hasOption('e');
    main.debug = line.hasOption('d');
    main.conf.setDebug(main.debug);
    main.conf.setParameters(line.hasOption("pa"));
    main.processFiles = line.hasOption('p') || line.hasOption('n');
    main.autoOutput = line.hasOption('p');
    main.editFiles = line.hasOption('i');
    if (main.editFiles) {
        main.backupExtension = line.getOptionValue('i');
    }
    main.autoSplit = line.hasOption('a');
    String sp = line.getOptionValue('a');
    if (sp != null)
        main.splitPattern = sp;
    if (main.isScriptFile) {
        if (args.isEmpty())
            throw new ParseException("neither -e or filename provided");
        main.script = (String) args.remove(0);
        if (main.script.endsWith(".java"))
            throw new ParseException("error: cannot compile file with .java extension: " + main.script);
    } else {
        main.script = line.getOptionValue('e');
    }
    main.processSockets = line.hasOption('l');
    if (main.processSockets) {
        // default port to listen to
        String p = line.getOptionValue('l', "1960");
        main.port = Integer.parseInt(p);
    }
    // we use "," as default, because then split will create
    // an empty array if no option is set
    String disabled = line.getOptionValue("disableopt", ",");
    String[] deopts = disabled.split(",");
    for (String deopt_i : deopts) {
        main.conf.getOptimizationOptions().put(deopt_i, false);
    }
    if (line.hasOption("indy")) {
        CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", true);
        main.conf.getOptimizationOptions().put("indy", true);
    }
    if (line.hasOption("basescript")) {
        main.conf.setScriptBaseClass(line.getOptionValue("basescript"));
    }
    if (line.hasOption("configscript")) {
        String path = line.getOptionValue("configscript");
        File groovyConfigurator = new File(path);
        Binding binding = new Binding();
        binding.setVariable("configuration", main.conf);
        CompilerConfiguration configuratorConfig = new CompilerConfiguration();
        ImportCustomizer customizer = new ImportCustomizer();
        customizer.addStaticStars("org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder");
        configuratorConfig.addCompilationCustomizers(customizer);
        GroovyShell shell = new GroovyShell(binding, configuratorConfig);
        shell.evaluate(groovyConfigurator);
    }
    main.args = args;
    return main.run();
}
Also used : Binding(groovy.lang.Binding) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) List(java.util.List) ImportCustomizer(org.codehaus.groovy.control.customizers.ImportCustomizer) ParseException(org.apache.commons.cli.ParseException) GroovyShell(groovy.lang.GroovyShell)

Example 2 with Binding

use of groovy.lang.Binding in project intellij-community by JetBrains.

the class GroovyModelInitializer method run.

@Override
public void run(JpsModel model) {
    Map<String, Object> variables = new HashMap<>();
    variables.put("project", model.getProject());
    variables.put("global", model.getGlobal());
    try {
        new GroovyShell(new Binding(variables)).evaluate(myScriptFile);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : Binding(groovy.lang.Binding) HashMap(java.util.HashMap) IOException(java.io.IOException) GroovyShell(groovy.lang.GroovyShell)

Example 3 with Binding

use of groovy.lang.Binding in project grails-core by grails.

the class DefaultUrlMappingEvaluatorTests method testRedirectMappings.

public void testRedirectMappings() throws Exception {
    GroovyShell shell = new GroovyShell();
    Binding binding = new Binding();
    Script script = shell.parse("mappings = {\n" + "\"/first\"(redirect:[controller: 'foo', action: 'bar'])\n" + "\"/second\"(redirect: '/bing/bang')\n" + "}");
    script.setBinding(binding);
    script.run();
    Closure closure = (Closure) binding.getVariable("mappings");
    List<UrlMapping> mappings = evaluator.evaluateMappings(closure);
    assertEquals(2, mappings.size());
    Object redirectInfo = mappings.get(0).getRedirectInfo();
    assertTrue(redirectInfo instanceof Map);
    Map redirectMap = (Map) redirectInfo;
    assertEquals(2, redirectMap.size());
    assertEquals("foo", redirectMap.get("controller"));
    assertEquals("bar", redirectMap.get("action"));
    assertEquals("/bing/bang", mappings.get(1).getRedirectInfo());
}
Also used : Binding(groovy.lang.Binding) UrlMapping(grails.web.mapping.UrlMapping) Script(groovy.lang.Script) Closure(groovy.lang.Closure) Map(java.util.Map) GroovyShell(groovy.lang.GroovyShell)

Example 4 with Binding

use of groovy.lang.Binding in project grails-core by grails.

the class UrlMappingUtils method includeForUrlMappingInfo.

/**
     * Include whatever the given UrlMappingInfo maps to within the current response
     *
     * @param request The request
     * @param response The response
     * @param info The UrlMappingInfo
     * @param model The model
     *
     * @return The included content
     */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static IncludedContent includeForUrlMappingInfo(HttpServletRequest request, HttpServletResponse response, UrlMappingInfo info, Map model) {
    String includeUrl = buildDispatchUrlForMapping(info, true);
    final GrailsWebRequest webRequest = GrailsWebRequest.lookup(request);
    String currentController = null;
    String currentAction = null;
    String currentId = null;
    ModelAndView currentMv = null;
    Binding currentPageBinding = null;
    Map currentParams = null;
    Object currentLayoutAttribute = null;
    Object currentRenderingView = null;
    if (webRequest != null) {
        currentPageBinding = (Binding) webRequest.getAttribute(GrailsApplicationAttributes.PAGE_SCOPE, 0);
        webRequest.removeAttribute(GrailsApplicationAttributes.PAGE_SCOPE, 0);
        currentLayoutAttribute = webRequest.getAttribute(WebUtils.LAYOUT_ATTRIBUTE, 0);
        if (currentLayoutAttribute != null) {
            webRequest.removeAttribute(WebUtils.LAYOUT_ATTRIBUTE, 0);
        }
        currentRenderingView = webRequest.getAttribute(WebUtils.RENDERING_VIEW, 0);
        if (currentRenderingView != null) {
            webRequest.removeAttribute(WebUtils.RENDERING_VIEW, 0);
        }
        currentController = webRequest.getControllerName();
        currentAction = webRequest.getActionName();
        currentId = webRequest.getId();
        currentParams = new HashMap();
        currentParams.putAll(webRequest.getParameterMap());
        currentMv = (ModelAndView) webRequest.getAttribute(GrailsApplicationAttributes.MODEL_AND_VIEW, 0);
    }
    try {
        if (webRequest != null) {
            webRequest.getParameterMap().clear();
            info.configure(webRequest);
            webRequest.getParameterMap().putAll(info.getParameters());
            webRequest.removeAttribute(GrailsApplicationAttributes.MODEL_AND_VIEW, 0);
        }
        return includeForUrl(includeUrl, request, response, model);
    } finally {
        if (webRequest != null) {
            webRequest.setAttribute(GrailsApplicationAttributes.PAGE_SCOPE, currentPageBinding, 0);
            if (currentLayoutAttribute != null) {
                webRequest.setAttribute(WebUtils.LAYOUT_ATTRIBUTE, currentLayoutAttribute, 0);
            }
            if (currentRenderingView != null) {
                webRequest.setAttribute(WebUtils.RENDERING_VIEW, currentRenderingView, 0);
            }
            webRequest.getParameterMap().clear();
            webRequest.getParameterMap().putAll(currentParams);
            webRequest.setId(currentId);
            webRequest.setControllerName(currentController);
            webRequest.setActionName(currentAction);
            if (currentMv != null) {
                webRequest.setAttribute(GrailsApplicationAttributes.MODEL_AND_VIEW, currentMv, 0);
            }
        }
    }
}
Also used : Binding(groovy.lang.Binding) HashMap(java.util.HashMap) ModelAndView(org.springframework.web.servlet.ModelAndView) GrailsWebRequest(org.grails.web.servlet.mvc.GrailsWebRequest) HashMap(java.util.HashMap) Map(java.util.Map)

Example 5 with Binding

use of groovy.lang.Binding in project grails-core by grails.

the class TagBodyClosure method captureClosureOutput.

private Object captureClosureOutput(Object args, boolean hasArgument) {
    final GroovyPageTagWriter capturedOut = new GroovyPageTagWriter();
    Binding currentBinding = outputContext.getBinding();
    Map<String, Object> savedVariablesMap = null;
    Object originalIt = null;
    try {
        pushCapturedOut(capturedOut);
        Object bodyResult;
        if (currentBinding != null) {
            if (hasArgument) {
                originalIt = saveItVariable(currentBinding, args);
            }
            if (args instanceof Map && ((Map) args).size() > 0) {
                // The body can be passed a set of variables as a map that
                // are then made available in the binding. This allows the
                // contents of the body to reference any of these variables
                // directly.
                //
                // For example, body(foo: 1, bar: 'test') would allow this
                // GSP fragment to work:
                //
                // <td>Foo: ${foo} and bar: ${bar}</td>
                //
                // Note that any variables with the same name as one of the
                // new ones will be overridden for the scope of the host
                // tag's body.
                // GRAILS-2675: Copy the current binding so that we can
                // restore
                // it to its original state.
                // Binding is only changed currently when body gets a map
                // argument
                savedVariablesMap = addAndSaveVariables(currentBinding, (Map) args);
            }
        }
        bodyResult = executeClosure(args);
        if (!capturedOut.isUsed() && bodyResult != null && !(bodyResult instanceof Writer)) {
            return bodyResult;
        }
        return capturedOut.getBuffer();
    } finally {
        if (currentBinding != null) {
            restoreVariables(currentBinding, savedVariablesMap);
            if (hasArgument) {
                restoreItVariable(currentBinding, originalIt);
            }
        }
        popCapturedOut();
    }
}
Also used : Binding(groovy.lang.Binding) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Writer(java.io.Writer)

Aggregations

Binding (groovy.lang.Binding)219 GroovyShell (groovy.lang.GroovyShell)77 Script (groovy.lang.Script)58 Test (org.junit.Test)39 IOException (java.io.IOException)30 File (java.io.File)24 HashMap (java.util.HashMap)24 Closure (groovy.lang.Closure)23 CompilerConfiguration (org.codehaus.groovy.control.CompilerConfiguration)23 Map (java.util.Map)21 GroovyService (eu.esdihumboldt.util.groovy.sandbox.GroovyService)13 CompilationFailedException (org.codehaus.groovy.control.CompilationFailedException)13 ImportCustomizer (org.codehaus.groovy.control.customizers.ImportCustomizer)12 MissingPropertyException (groovy.lang.MissingPropertyException)11 GroovyClassLoader (groovy.lang.GroovyClassLoader)10 InputStreamReader (java.io.InputStreamReader)10 StringWriter (java.io.StringWriter)10 Writer (java.io.Writer)10 InstanceBuilder (eu.esdihumboldt.hale.common.instance.groovy.InstanceBuilder)9 InvocationTargetException (java.lang.reflect.InvocationTargetException)9