@SuppressWarnings({"unchecked", "rawtypes"})
  public List evaluateMappings(Class theClass) {
    GroovyObject obj = (GroovyObject) BeanUtils.instantiateClass(theClass);

    if (obj instanceof Script) {
      Script script = (Script) obj;
      Binding b = new Binding();

      MappingCapturingClosure closure = new MappingCapturingClosure(script);
      b.setVariable("mappings", closure);
      script.setBinding(b);

      script.run();

      Closure mappings = closure.getMappings();

      Binding binding = script.getBinding();
      return evaluateMappings(script, mappings, binding);
    }

    throw new UrlMappingException(
        "Unable to configure URL mappings for class ["
            + theClass
            + "]. A URL mapping must be an instance of groovy.lang.Script.");
  }
Exemplo n.º 2
0
  /** Initializes the script, loading any required dependencies and running the script. */
  private void init() {
    int repos = 0;
    for (String repo : script.getHeaders("m2repo")) {
      Map<String, Object> args = Maps.newHashMap();
      args.put("name", "repo_" + repos++);
      args.put("root", repo);
      args.put("m2compatible", true);
      Grape.addResolver(args);
    }

    for (String dependency : script.getHeaders("dependency")) {
      String[] parts = dependency.split(":");
      if (parts.length >= 3) classLoader.loadDependency(parts[0], parts[1], parts[2]);
    }

    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    try {
      Thread.currentThread().setContextClassLoader(classLoader);

      Script groovyScript = shell.parse(script.getBody(), scriptName);
      binding.setProperty("log", log);
      groovyScript.setMetaClass(new ScriptMetaClass(groovyScript.getMetaClass()));

      groovyScript.setBinding(binding);
      groovyScript.run();
    } catch (CompilationFailedException e) {
      log.error("Compilation of Groovy script failed: ", e);
      throw new RuntimeException("Compilation of Groovy script failed", e);
    } finally {
      Thread.currentThread().setContextClassLoader(cl);
    }
  }
 public IPointcut createPointcut(String expression) {
   GroovyCodeSource source =
       new GroovyCodeSource(expression, DEFAULT_SCRIPT_NAME, GroovyShell.DEFAULT_CODE_BASE);
   Script script = new GroovyShell(this.getClass().getClassLoader()).parse(source);
   script.setBinding(new PoincutBinding());
   Object res = script.run();
   return res instanceof IPointcut ? (IPointcut) res : null;
 }
 /** Return a script object with the given vars from the compiled script object */
 private Script createScript(Object compiledScript, Map<String, Object> vars)
     throws InstantiationException, IllegalAccessException {
   Class scriptClass = (Class) compiledScript;
   Script scriptObject = (Script) scriptClass.newInstance();
   Binding binding = new Binding();
   binding.getVariables().putAll(vars);
   scriptObject.setBinding(binding);
   return scriptObject;
 }
  /**
   * Runs the groovy script. No exceptions are caught.
   *
   * @param matcher the regular expression matcher
   * @param lineNumber the current line number
   * @return unchecked result of the script
   */
  public Object run(final Matcher matcher, final int lineNumber) {
    compileScriptIfNotYetDone();

    Binding binding = new Binding();
    binding.setVariable("matcher", matcher);
    binding.setVariable("lineNumber", lineNumber);

    compiled.setBinding(binding);
    return compiled.run();
  }
Exemplo n.º 6
0
  public void internalRenderTemplate(Map<String, Object> args, boolean startingNewRendering)
      throws GTTemplateNotFoundWithSourceInfo, GTRuntimeException {

    if (startingNewRendering) {
      // start with fresh tag-stack
      GTTagContext.singleton.init();
    }

    try {

      // must store a copy of args, so we can pass the same (unchnaged) args to an extending
      // template.
      this.orgArgs = new HashMap<String, Object>(args);
      this.binding =
          new Binding(
              new HashMap<String, Object>(
                  args)); // Must create a new map to prevent script-generated variables to leak out
      this.binding.setProperty("java_class", this);
      // must init our groovy script

      // groovyScript = InvokerHelper.createScript(groovyClass, binding);
      groovyScript = groovyClass.newInstance();
      groovyScript.setBinding(binding);

      // create a property in groovy so that groovy can find us (this)

      // call _renderTemplate directly
      _renderTemplate();

      // check if "we" have extended another template..
      if (extendsTemplateLocation != null) {
        // yes, we've extended another template
        // Get the template we are extending
        extendedTemplate = templateRepo.getTemplateInstance(extendsTemplateLocation);

        // tell it that "we" extended it..
        extendedTemplate.extendingTemplate = this;

        // ok, render it with original args..
        extendedTemplate.internalRenderTemplate(orgArgs, false);
      }

    } catch (GTCompilationException e) {
      // just throw it
      throw e;
    } catch (Throwable e) {
      // wrap it in a GTRuntimeException
      throw templateRepo.fixException(e);
    }
  }
  @Nonnull
  @Override
  @SuppressWarnings("unchecked")
  protected Map<String, Object> instantiateMembers(
      @Nonnull Map<String, ClassHolder> classMap, @Nonnull Map<String, Object> args) {
    Map<String, Object> map = super.instantiateMembers(classMap, args);
    FactoryBuilderSupport builder = createBuilder(getApplication());
    map.put(BUILDER, builder);

    for (Object member : map.values()) {
      // all scripts get the builder as their binding
      if (member instanceof Script) {
        builder.getVariables().putAll(((Script) member).getBinding().getVariables());
        ((Script) member).setBinding(builder);
      }
    }

    return map;
  }
 public Object build(Script script) {
   // this used to be synchronized, but we also used to remove the
   // metaclass.  Since adding the metaclass is now a side effect, we
   // don't need to ensure the meta-class won't be observed and don't
   // need to hide the side effect.
   MetaClass scriptMetaClass = script.getMetaClass();
   script.setMetaClass(new FactoryInterceptorMetaClass(scriptMetaClass, this));
   script.setBinding(this);
   Object oldScriptName = getProxyBuilder().getVariables().get(SCRIPT_CLASS_NAME);
   try {
     getProxyBuilder().setVariable(SCRIPT_CLASS_NAME, script.getClass().getName());
     return script.run();
   } finally {
     if (oldScriptName != null) {
       getProxyBuilder().setVariable(SCRIPT_CLASS_NAME, oldScriptName);
     } else {
       getProxyBuilder().getVariables().remove(SCRIPT_CLASS_NAME);
     }
   }
 }
  public void loadEventsScript(File eventScript) {
    if (eventScript == null) {
      return;
    }

    GrailsConsole console = GrailsConsole.getInstance();
    try {
      Class<?> scriptClass = classLoader.parseClass(eventScript);
      if (scriptClass == null) {
        console.error("Could not load event script (script may be empty): " + eventScript);
        return;
      }

      Script script = (Script) scriptClass.newInstance();
      script.setBinding(
          new Binding(binding.getVariables()) {
            @SuppressWarnings("rawtypes")
            @Override
            public void setVariable(String var, Object o) {
              final Matcher matcher = EVENT_NAME_PATTERN.matcher(var);
              if (matcher.matches() && (o instanceof Closure)) {
                String eventName = matcher.group(1);
                List<Closure> hooks = globalEventHooks.get(eventName);
                if (hooks == null) {
                  hooks = new ArrayList<Closure>();
                  globalEventHooks.put(eventName, hooks);
                }
                hooks.add((Closure<?>) o);
              }
              super.setVariable(var, o);
            }
          });
      script.run();
    } catch (Throwable e) {
      StackTraceUtils.deepSanitize(e);
      console.error(
          "Error loading event script from file [" + eventScript + "] " + e.getMessage(), e);
    }
  }
Exemplo n.º 10
0
 @Override
 public void setBinding(Binding binding) {
   super.setBinding(addStaticBindings(binding));
   initBinding();
 }