@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.");
  }
Esempio n. 2
0
  @Override
  @SuppressWarnings("unchecked")
  protected void evaluationRequest(Script script) {
    super.evaluationRequest(script);

    Object property = null;

    if (getValueOptions() != null) {

      if (getValueOptions().contains("endings")) {
        property = script.getProperty("endings");
      }

      if (property != null) {
        getFileFilter().setAcceptedEndings((ArrayList<String>) property);
      }

      property = null;

      if (getValueOptions().contains("description")) {
        property = script.getProperty("description");
      }

      if (property != null) {
        getFileFilter().setDescription((String) property);
      }
    }
  }
Esempio n. 3
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();
  }
 @Override
 public Object execute(Object compiledScript, Map<String, Object> vars) {
   try {
     Map<String, Object> allVars = new HashMap<>();
     if (vars != null) {
       allVars.putAll(vars);
     }
     Script scriptObject = createScript(compiledScript, allVars);
     return scriptObject.run();
   } catch (Exception e) {
     throw new ScriptException("failed to execute script", e);
   }
 }
Esempio n. 8
0
  private Map<String, Object> serviceInvoker(
      String localName, ModelService modelService, Map<String, Object> context)
      throws GenericServiceException {
    if (UtilValidate.isEmpty(modelService.location)) {
      throw new GenericServiceException("Cannot run Groovy service with empty location");
    }
    Map<String, Object> params = FastMap.newInstance();
    params.putAll(context);
    context.put(ScriptUtil.PARAMETERS_KEY, params);

    DispatchContext dctx = dispatcher.getLocalContext(localName);
    context.put("dctx", dctx);
    context.put("dispatcher", dctx.getDispatcher());
    context.put("delegator", dispatcher.getDelegator());
    try {
      ScriptContext scriptContext = ScriptUtil.createScriptContext(context, protectedKeys);
      ScriptHelper scriptHelper =
          (ScriptHelper) scriptContext.getAttribute(ScriptUtil.SCRIPT_HELPER_KEY);
      if (scriptHelper != null) {
        context.put(ScriptUtil.SCRIPT_HELPER_KEY, scriptHelper);
      }
      Script script =
          InvokerHelper.createScript(
              GroovyUtil.getScriptClassFromLocation(
                  this.getLocation(modelService), groovyClassLoader),
              GroovyUtil.getBinding(context));
      Object resultObj = null;
      if (UtilValidate.isEmpty(modelService.invoke)) {
        resultObj = script.run();
      } else {
        resultObj = script.invokeMethod(modelService.invoke, EMPTY_ARGS);
      }
      if (resultObj == null) {
        resultObj = scriptContext.getAttribute(ScriptUtil.RESULT_KEY);
      }
      if (resultObj != null && resultObj instanceof Map<?, ?>) {
        return cast(resultObj);
      }
      Map<String, Object> result = ServiceUtil.returnSuccess();
      result.putAll(
          modelService.makeValid(scriptContext.getBindings(ScriptContext.ENGINE_SCOPE), "OUT"));
      return result;
    } catch (GeneralException ge) {
      throw new GenericServiceException(ge);
    } catch (Exception e) {
      return ServiceUtil.returnError(e.getMessage());
    }
  }
Esempio n. 9
0
 @Override
 public void setProperty(final String name, final Object value) {
   DSLEntryResult result = methodMissingImpl(name, value);
   if (!result.isSuccess()) {
     super.setProperty(name, value);
   }
 }
 @Override
 @SuppressWarnings("unchecked")
 protected void fillNonArtifactMemberProperties(
     @Nonnull String type, @Nonnull Object member, @Nonnull Map<String, Object> args) {
   if (member instanceof Script) {
     ((Script) member).getBinding().getVariables().putAll(args);
   }
 }
 /** Evaluate an expression. */
 public Object eval(String source, int lineNo, int columnNo, Object script) throws BSFException {
   try {
     Class scriptClass = evalScripts.get(script);
     if (scriptClass == null) {
       scriptClass = loader.parseClass(script.toString(), source);
       evalScripts.put(script, scriptClass);
     } else {
       LOG.fine("eval() - Using cached script...");
     }
     // can't cache the script because the context may be different.
     // but don't bother loading parsing the class again
     Script s = InvokerHelper.createScript(scriptClass, context);
     return s.run();
   } catch (Exception e) {
     throw new BSFException(BSFException.REASON_EXECUTION_ERROR, "exception from Groovy: " + e, e);
   }
 }
 public GroovyScript(Script script, SearchLookup lookup) {
   this.script = script;
   this.lookup = lookup;
   this.variables = script.getBinding().getVariables();
   this.score = new UpdateableFloat(0);
   // Add the _score variable, which will be updated per-document by
   // setting .value on the UpdateableFloat instance
   this.variables.put("_score", this.score);
 }
  @Override
  public void run(JobToRun job) {
    RunnerFilterChain<JobStoryRunContext> chain = createFilterChain();
    StoryFilterChainAdapter adapter = new StoryFilterChainAdapter(job, chain);
    DslBuilderAndRun.setFilterChainCurrentThread(adapter);
    try {
      Class<?> clazz = Class.forName(job.getStoryClassName());

      if (!(clazz.getSuperclass().getName().equals("groovy.lang.Script"))) {
        throw new RuntimeException(job.getStoryClassName() + " is not a groovy script");
      }

      Script script = (Script) clazz.newInstance();
      script.run();

    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
 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);
    }
  }
  /**
   * Executes the groovy script with the given binding.
   *
   * @param binding Binding
   * @return PicoContainer
   */
  private PicoContainer runGroovyScript(Binding binding) {
    Script script = createGroovyScript(binding);

    Object result = script.run();
    Object picoVariable;
    try {
      picoVariable = binding.getVariable("pico");
    } catch (MissingPropertyException e) {
      picoVariable = result;
    }
    if (picoVariable == null) {
      throw new NullPointerException("Groovy Script Variable: pico");
    }

    if (picoVariable instanceof PicoContainer) {
      return (PicoContainer) picoVariable;
    } else if (picoVariable instanceof NanoContainer) {
      return ((NanoContainer) picoVariable);
    } else {
      throw new NanoContainerMarkupException(
          "Bad type for pico:" + picoVariable.getClass().getName());
    }
  }
Esempio n. 17
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;
  }
Esempio n. 19
0
  /**
   * Process a script against a single input file.
   *
   * @param s script to execute.
   * @param reader input file.
   * @param pw output sink.
   */
  private void processReader(Script s, BufferedReader reader, PrintWriter pw) throws IOException {
    String line;
    String lineCountName = "count";
    s.setProperty(lineCountName, BigInteger.ZERO);
    String autoSplitName = "split";
    s.setProperty("out", pw);

    try {
      InvokerHelper.invokeMethod(s, "begin", null);
    } catch (MissingMethodException mme) {
      // ignore the missing method exception
      // as it means no begin() method is present
    }

    while ((line = reader.readLine()) != null) {
      s.setProperty("line", line);
      s.setProperty(lineCountName, ((BigInteger) s.getProperty(lineCountName)).add(BigInteger.ONE));

      if (autoSplit) {
        s.setProperty(autoSplitName, line.split(splitPattern));
      }

      Object o = s.run();

      if (autoOutput && o != null) {
        pw.println(o);
      }
    }

    try {
      InvokerHelper.invokeMethod(s, "end", null);
    } catch (MissingMethodException mme) {
      // ignore the missing method exception
      // as it means no end() method is present
    }
  }
Esempio n. 20
0
 public void run() {
   try {
     String line = null;
     script.setProperty("out", writer);
     script.setProperty("socket", socket);
     script.setProperty("init", Boolean.TRUE);
     while ((line = reader.readLine()) != null) {
       // System.out.println(line);
       script.setProperty("line", line);
       Object o = script.run();
       script.setProperty("init", Boolean.FALSE);
       if (o != null) {
         if ("success".equals(o)) {
           break; // to close sockets gracefully etc...
         } else {
           if (autoOutputFlag) {
             writer.println(o);
           }
         }
       }
       writer.flush();
     }
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       writer.flush();
       writer.close();
     } finally {
       try {
         socket.close();
       } catch (IOException e3) {
         e3.printStackTrace();
       }
     }
   }
 }
 @Override
 public Object run() {
   return script.run();
 }
 @Override
 public void setBinding(Binding binding) {
   super.setBinding(addStaticBindings(binding));
   initBinding();
 }
Esempio n. 23
0
 private Object runScript(final String testScript) throws Exception {
   Script script = shell.parse(testScript);
   return script.run();
 }
  /** Apply the groovy script changes to the top level pom. */
  @Override
  public Set<Project> applyChanges(final List<Project> projects, final ManipulationSession session)
      throws ManipulationException {
    final GroovyState state = session.getState(GroovyState.class);
    if (!session.isEnabled() || !state.isEnabled()) {
      logger.debug(getClass().getSimpleName() + ": Nothing to do!");
      return Collections.emptySet();
    }

    final Set<Project> changed = new HashSet<>();
    final List<ArtifactRef> scripts = state.getGroovyScripts();

    for (ArtifactRef ar : scripts) {
      logger.info(
          "Attempting to read GAV {} with classifier {} and type {} ",
          ar.asProjectVersionRef(),
          ar.getClassifier(),
          ar.getType());

      final File groovyScript = modelBuilder.resolveRawFile(ar);

      GroovyShell shell = new GroovyShell();
      Script script;

      for (final Project project : projects) {
        if (project.isExecutionRoot()) {
          logger.info("Executing {} on {}", groovyScript, project);

          try {
            script = shell.parse(groovyScript);

            script.invokeMethod(
                "setValues", new Object[] {session.getUserProperties(), projects, project});
          } catch (MissingMethodException e) {
            try {
              logger.debug(
                  "Failure when injecting into script {} ",
                  FileUtils.readFileToString(groovyScript));
            } catch (IOException e1) {
              logger.debug("Unable to read script file {} for debugging! {} ", groovyScript, e1);
            }
            throw new ManipulationException("Unable to inject values into base script", e);
          } catch (CompilationFailedException e) {
            try {
              logger.debug(
                  "Failure when parsing script {} ", FileUtils.readFileToString(groovyScript));
            } catch (IOException e1) {
              logger.debug("Unable to read script file {} for debugging! {} ", groovyScript, e1);
            }
            throw new ManipulationException("Unable to parse script", e);
          } catch (IOException e) {
            throw new ManipulationException("Unable to parse script", e);
          }
          try {
            script.run();
          } catch (Exception e) {
            throw new ManipulationException("Unable to parse script", e);
          }

          changed.add(project);
        }
      }
    }
    return changed;
  }
Esempio n. 25
0
  public Object eval(final Context context, final Bindings request, final Bindings... scopes)
      throws ScriptException {

    final Map<String, Object> bindings = mergeBindings(context, request, scopes);

    // Bindings so script has access to this environment.
    // Only initialize once.
    if (null == bindings.get("context")) {
      // add context to bindings
      // ctx.setAttribute("context", ctx);

      // direct output to ctx.getWriter
      // If we're wrapping with a PrintWriter here,
      // enable autoFlush because otherwise it might not get done!
      final Writer writer = engine.getWriter();
      bindings.put("out", (writer instanceof PrintWriter) ? writer : new PrintWriter(writer, true));

      // Not going to do this after all (at least for now).
      // Scripts can use context.{reader, writer, errorWriter}.
      // That is a modern version of System.{in, out, err} or
      // Console.{reader, writer}().
      //
      // // New I/O names consistent with ScriptContext and
      // java.io.Console.
      //
      // ctx.setAttribute("writer", writer, ScriptContext.ENGINE_SCOPE);
      //
      // // Direct errors to ctx.getErrorWriter
      // final Writer errorWriter = ctx.getErrorWriter();
      // ctx.setAttribute("errorWriter", (errorWriter instanceof
      // PrintWriter) ?
      // errorWriter :
      // new PrintWriter(errorWriter),
      // ScriptContext.ENGINE_SCOPE);
      //
      // // Get input from ctx.getReader
      // // We don't wrap with BufferedReader here because we expect that
      // if
      // // the host wants that they do it. Either way Groovy scripts will
      // // always have readLine because the GDK supplies it for Reader.
      // ctx.setAttribute("reader", ctx.getReader(),
      // ScriptContext.ENGINE_SCOPE);
    }

    // Fix for GROOVY-3669: Can't use several times the same JSR-223
    // ScriptContext for differents groovy script
    // if (ctx.getWriter() != null) {
    // ctx.setAttribute("out", new PrintWriter(ctx.getWriter(), true),
    // DefaultScriptContext.REQUEST_SCOPE);
    // }

    try {
      Script scriptObject = engine.createScript(scriptName, new Binding(bindings));

      // create a Map of MethodClosures from this new script object
      Method[] methods = scriptObject.getClass().getMethods();
      final Map<String, Closure> closures = new HashMap<String, Closure>();
      for (Method m : methods) {
        String name = m.getName();
        closures.put(name, new MethodClosure(scriptObject, name));
      }

      MetaClass oldMetaClass = scriptObject.getMetaClass();

      /*
       * We override the MetaClass of this script object so that we can
       * forward calls to global closures (of previous or future "eval"
       * calls) This gives the illusion of working on the same "global"
       * scope.
       */
      scriptObject.setMetaClass(
          new DelegatingMetaClass(oldMetaClass) {
            @Override
            public Object invokeMethod(Object object, String name, Object args) {
              if (args == null) {
                return invokeMethod(object, name, MetaClassHelper.EMPTY_ARRAY);
              }
              if (args instanceof Tuple) {
                return invokeMethod(object, name, ((Tuple) args).toArray());
              }
              if (args instanceof Object[]) {
                return invokeMethod(object, name, (Object[]) args);
              } else {
                return invokeMethod(object, name, new Object[] {args});
              }
            }

            @Override
            public Object invokeMethod(Object object, String name, Object[] args) {
              try {
                return super.invokeMethod(object, name, args);
              } catch (MissingMethodException mme) {
                return callGlobal(name, args, bindings);
              }
            }

            @Override
            public Object invokeStaticMethod(Object object, String name, Object[] args) {
              try {
                return super.invokeStaticMethod(object, name, args);
              } catch (MissingMethodException mme) {
                return callGlobal(name, args, bindings);
              }
            }

            private Object callGlobal(String name, Object[] args, Map<String, Object> ctx) {
              Closure closure = closures.get(name);
              if (closure != null) {
                return closure.call(args);
              } else {
                // Look for closure valued variable in the
                // given ScriptContext. If available, call it.
                Object value = ctx.get(name);
                if (value instanceof Closure) {
                  return ((Closure) value).call(args);
                } // else fall thru..
              }
              throw new MissingMethodException(name, getClass(), args);
            }
          });

      try {
        return scriptObject.run();
      } catch (Exception e) {
        throw new ScriptThrownException(e.getMessage(), e);
      }
    } catch (ScriptException e) {
      throw e;
    } catch (CompilationFailedException e) {
      throw new ScriptCompilationException(e);
    } catch (Exception e) {
      throw new ScriptException(e);
    } finally {
      // Fix for GROOVY-3669: Can't use several times the same JSR-223
      // ScriptContext for different groovy script
      // Groovy's scripting engine implementation adds those two variables
      // in the binding
      // but should clean up afterwards
      // ctx.removeAttribute("context",
      // DefaultScriptContext.REQUEST_SCOPE);
      // ctx.removeAttribute("out", DefaultScriptContext.REQUEST_SCOPE);
    }
  }