Exemplo n.º 1
0
  /** Process the input files. */
  private void processFiles() throws CompilationFailedException, IOException {
    GroovyShell groovy = new GroovyShell(conf);

    Script s;

    if (isScriptFile) {
      if (isScriptUrl(script)) {
        s = groovy.parse(getText(script), script.substring(script.lastIndexOf("/") + 1));
      } else {
        s = groovy.parse(huntForTheScriptFile(script));
      }
    } else {
      s = groovy.parse(script, "main");
    }

    if (args.isEmpty()) {
      BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
      PrintWriter writer = new PrintWriter(System.out);

      try {
        processReader(s, reader, writer);
      } finally {
        reader.close();
        writer.close();
      }

    } else {
      Iterator i = args.iterator();
      while (i.hasNext()) {
        String filename = (String) i.next();
        File file = huntForTheScriptFile(filename);
        processFile(s, file);
      }
    }
  }
  private boolean executePresendScript(
      AbstractBuild<?, ?> build,
      BuildListener listener,
      MimeMessage msg,
      EmailTrigger trigger,
      Map<String, EmailTrigger> triggered)
      throws RuntimeException {
    boolean cancel = false;
    presendScript = new ContentBuilder().transformText(presendScript, this, build, listener);
    if (StringUtils.isNotBlank(presendScript)) {
      listener.getLogger().println("Executing pre-send script");
      ClassLoader cl = Jenkins.getInstance().getPluginManager().uberClassLoader;
      ScriptSandbox sandbox = null;
      CompilerConfiguration cc = new CompilerConfiguration();
      cc.addCompilationCustomizers(
          new ImportCustomizer()
              .addStarImports("jenkins", "jenkins.model", "hudson", "hudson.model"));

      if (ExtendedEmailPublisher.DESCRIPTOR.isSecurityEnabled()) {
        debug(listener.getLogger(), "Setting up sandbox for pre-send script");
        cc.addCompilationCustomizers(new SandboxTransformer());
        sandbox = new ScriptSandbox();
      }

      Binding binding = new Binding();
      binding.setVariable("build", build);
      binding.setVariable("msg", msg);
      binding.setVariable("logger", listener.getLogger());
      binding.setVariable("cancel", cancel);
      binding.setVariable("trigger", trigger);
      binding.setVariable("triggered", Collections.unmodifiableMap(triggered));

      GroovyShell shell = new GroovyShell(cl, binding, cc);
      StringWriter out = new StringWriter();
      PrintWriter pw = new PrintWriter(out);

      if (sandbox != null) {
        sandbox.register();
      }

      try {
        Object output = shell.evaluate(presendScript);
        if (output != null) {
          pw.println("Result: " + output);
          cancel = ((Boolean) shell.getVariable("cancel")).booleanValue();
          debug(listener.getLogger(), "Pre-send script set cancel to %b", cancel);
        }
      } catch (SecurityException e) {
        listener
            .getLogger()
            .println("Pre-send script tried to access secured objects: " + e.getMessage());
      } catch (Throwable t) {
        t.printStackTrace(pw);
        listener.getLogger().println(out.toString());
        // should we cancel the sending of the email???
      }
      debug(listener.getLogger(), out.toString());
    }
    return !cancel;
  }
Exemplo n.º 3
0
  public static CompilerConfiguration generateCompilerConfigurationFromOptions(CommandLine cli)
      throws IOException {
    //
    // Setup the configuration data

    CompilerConfiguration configuration = new CompilerConfiguration();

    if (cli.hasOption("classpath")) {
      configuration.setClasspath(cli.getOptionValue("classpath"));
    }

    if (cli.hasOption('d')) {
      configuration.setTargetDirectory(cli.getOptionValue('d'));
    }

    if (cli.hasOption("encoding")) {
      configuration.setSourceEncoding(cli.getOptionValue("encoding"));
    }

    if (cli.hasOption("basescript")) {
      configuration.setScriptBaseClass(cli.getOptionValue("basescript"));
    }

    // joint compilation parameters
    if (cli.hasOption('j')) {
      Map<String, Object> compilerOptions = new HashMap<String, Object>();

      String[] opts = cli.getOptionValues("J");
      compilerOptions.put("namedValues", opts);

      opts = cli.getOptionValues("F");
      compilerOptions.put("flags", opts);

      configuration.setJointCompilationOptions(compilerOptions);
    }

    if (cli.hasOption("indy")) {
      configuration.getOptimizationOptions().put("int", false);
      configuration.getOptimizationOptions().put("indy", true);
    }

    if (cli.hasOption("configscript")) {
      String path = cli.getOptionValue("configscript");
      File groovyConfigurator = new File(path);
      Binding binding = new Binding();
      binding.setVariable("configuration", configuration);

      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);
    }

    return configuration;
  }
Exemplo n.º 4
0
 // *** TODO: this should throw errors if the wrong field name is requested
 private void registerTupleTypes(GroovyShell shell) {
   shell.evaluate(
       TupleImpl.class.getName()
           + ".metaClass.getProperty = { name -> if (contains(name)) getValueByField(name); else throw new NoSuchFieldError(name) }");
   shell.evaluate(
       SimpleTuple.class.getName()
           + ".metaClass.getProperty = { name -> if (contains(name)) getValueByField(name); else throw new NoSuchFieldError(name) }");
 }
Exemplo n.º 5
0
 public static DescriptiveNode getComponentNodeFromGroovy(String scriptString) {
   GroovyShell shell = shellFactory();
   Object res = shell.evaluate(scriptString);
   if (!(res instanceof DescriptiveNode)) {
     throw new IllegalArgumentException(
         "described object not a ComponentNode but " + res.getClass());
   }
   return (DescriptiveNode) res;
 }
 private static void assertEvaluate(
     Whitelist whitelist, final Object expected, final String script) {
   final GroovyShell shell = new GroovyShell(GroovySandbox.createSecureCompilerConfiguration());
   Object actual = GroovySandbox.run(shell.parse(script), whitelist);
   if (actual instanceof GString) {
     actual = actual.toString(); // for ease of comparison
   }
   assertEquals(expected, actual);
 }
Exemplo n.º 7
0
  @Override
  public Object execute(final String script) {
    final Binding binding = new Binding();
    binding.setVariable("container", SingletonLaContainerFactory.getContainer());
    binding.setVariable("executor", this);

    final GroovyShell shell = new GroovyShell(binding);
    return shell.evaluate(script);
  }
Exemplo n.º 8
0
 /** Process Sockets. */
 private void processSockets() throws CompilationFailedException, IOException {
   GroovyShell groovy = new GroovyShell(conf);
   // check the script is currently valid before starting a server against the script
   if (isScriptFile) {
     groovy.parse(getText(script));
   } else {
     groovy.parse(script);
   }
   new GroovySocketServer(groovy, isScriptFile, script, autoOutput, port);
 }
Exemplo n.º 9
0
 // todo: should be a DescriptiveNode
 public static DescriptiveNode getComponentNodeFromGroovy(InputStream inputStream, String encoding)
     throws Exception {
   GroovyShell shell = shellFactory();
   InputStreamReader reader = new InputStreamReader(inputStream, encoding);
   Object res = shell.evaluate(reader);
   if (!(res instanceof DescriptiveNode)) {
     throw new IllegalArgumentException(
         " described object not a ComponentNode but " + res.getClass());
   }
   return (DescriptiveNode) res;
 }
Exemplo n.º 10
0
  /**
   * Evaluates the specified script and returns the result.
   *
   * @param resources The plugin resources.
   * @param script The script path relative to the scripts directory.
   * @param values Any variable name / value pairs for the script.
   * @return The result of evaluating the supplied script.
   */
  public static Object evaluateScript(
      PluginResources resources, String script, Map<String, Object> values) throws Exception {
    Binding binding = new Binding(values);
    GroovyShell shell = new GroovyShell(binding);

    String path = FileUtils.separatorsToUnix(FileUtils.concat(SCRIPT_PATH, script));
    InputStream stream = resources.getResourceAsStream(path);
    if (stream == null) {
      throw new IllegalArgumentException(Services.getMessage("script.not.found", path));
    }
    return shell.evaluate(stream);
  }
Exemplo n.º 11
0
  /** Process the standard, single script with args. */
  private void processOnce() throws CompilationFailedException, IOException {
    GroovyShell groovy = new GroovyShell(conf);

    if (isScriptFile) {
      if (isScriptUrl(script)) {
        groovy.run(getText(script), script.substring(script.lastIndexOf("/") + 1), args);
      } else {
        groovy.run(huntForTheScriptFile(script), args);
      }
    } else {
      groovy.run(script, "script_from_command_line", args);
    }
  }
Exemplo n.º 12
0
 public Object eval(String expr, Map params) {
   expr = expr.replaceAll("#\\{|\\}", "");
   Object bean = params.get("bean");
   GroovyShell ge = null;
   try {
     Binding binding = new Binding(BeanUtils.describe(bean));
     ge = new GroovyShell(binding);
     return ge.evaluate(expr);
   } catch (Exception ex) {
     throw new IllegalStateException(ex);
   } finally {
     ge = null;
   }
 }
Exemplo n.º 13
0
 private String evaluateGroovyExpression(String key, String expression) {
   Binding binding = new Binding();
   binding.setVariable("env", environmentVariables);
   GroovyShell shell = new GroovyShell(binding);
   Object result = null;
   try {
     String groovy = expression.substring(2, expression.length() - 1);
     if (StringUtils.isNotEmpty(groovy)) {
       result = shell.evaluate(groovy);
     }
   } catch (GroovyRuntimeException e) {
     LOGGER.warn("Failed to evaluate build info expression '%s' for key %s", expression, key);
   }
   return (result != null) ? result.toString() : expression;
 }
 private void compileScriptIfNotYetDone() {
   synchronized (script) {
     if (compiled == null) {
       GroovyShell shell = new GroovyShell(WarningsDescriptor.class.getClassLoader());
       try {
         compiled = shell.parse(script);
       } catch (CompilationFailedException exception) {
         LOGGER.log(
             Level.SEVERE,
             "Groovy dynamic warnings parser: exception during compiling: ",
             exception);
       }
     }
   }
 }
Exemplo n.º 15
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);
    }
  }
  @Override
  public boolean trigger(AbstractBuild<?, ?> build, TaskListener listener) {
    boolean result = false;
    GroovyShell engine = createEngine(build, listener);
    if (engine != null && !StringUtils.isEmpty(triggerScript)) {
      try {
        Object res = engine.evaluate(triggerScript);
        if (res != null) {
          result = (Boolean) res;
        }
      } finally {

      }
    }
    return result;
  }
  /**
   * Load bean definitions from the specified Groovy script or XML file.
   *
   * <p>Note that {@code ".xml"} files will be parsed as XML content; all other kinds of resources
   * will be parsed as Groovy scripts.
   *
   * @param encodedResource the resource descriptor for the Groovy script or XML file, allowing
   *     specification of an encoding to use for parsing the file
   * @return the number of bean definitions found
   * @throws BeanDefinitionStoreException in case of loading or parsing errors
   */
  public int loadBeanDefinitions(EncodedResource encodedResource)
      throws BeanDefinitionStoreException {
    // Check for XML files and redirect them to the "standard" XmlBeanDefinitionReader
    String filename = encodedResource.getResource().getFilename();
    if (StringUtils.endsWithIgnoreCase(filename, ".xml")) {
      return this.standardXmlBeanDefinitionReader.loadBeanDefinitions(encodedResource);
    }

    Closure beans =
        new Closure(this) {
          public Object call(Object[] args) {
            invokeBeanDefiningClosure((Closure) args[0]);
            return null;
          }
        };
    Binding binding =
        new Binding() {
          @Override
          public void setVariable(String name, Object value) {
            if (currentBeanDefinition != null) {
              applyPropertyToBeanDefinition(name, value);
            } else {
              super.setVariable(name, value);
            }
          }
        };
    binding.setVariable("beans", beans);

    int countBefore = getRegistry().getBeanDefinitionCount();
    try {
      GroovyShell shell = new GroovyShell(getResourceLoader().getClassLoader(), binding);
      shell.evaluate(encodedResource.getReader(), "beans");
    } catch (Throwable ex) {
      throw new BeanDefinitionParsingException(
          new Problem(
              "Error evaluating Groovy script: " + ex.getMessage(),
              new Location(encodedResource.getResource()),
              null,
              ex));
    }
    return getRegistry().getBeanDefinitionCount() - countBefore;
  }
Exemplo n.º 18
0
  @Override
  public Integer call() throws Exception {

    if (script == null) {
      throw new NullPointerException("No script.");
    }

    GroovyShell shell = new GroovyShell(classLoader, binding);

    evalResult = shell.evaluate(script);

    if (binding.hasVariable(OddjobWriteBinding.ODDJOB_RESULT_BINDING)) {
      Object result = binding.getVariable(OddjobWriteBinding.ODDJOB_RESULT_BINDING);
      if (result instanceof Number) {
        return ((Number) result).intValue();
      }
    }

    return 0;
  }
Exemplo n.º 19
0
 public void run() {
   try {
     ServerSocket serverSocket = new ServerSocket(url.getPort());
     while (true) {
       // Create one script per socket connection.
       // This is purposefully not caching the Script
       // so that the script source file can be changed on the fly,
       // as each connection is made to the server.
       Script script;
       if (isScriptFile) {
         GroovyMain gm = new GroovyMain();
         script = groovy.parse(new FileInputStream(gm.huntForTheScriptFile(scriptFilenameOrText)));
       } else {
         script = groovy.parse(scriptFilenameOrText);
       }
       new GroovyClientConnection(script, autoOutput, serverSocket.accept());
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 20
0
    public String call() throws RuntimeException {
      // if we run locally, cl!=null. Otherwise the delegating classloader will be available as
      // context classloader.
      if (cl == null) cl = Thread.currentThread().getContextClassLoader();
      CompilerConfiguration cc = new CompilerConfiguration();
      cc.addCompilationCustomizers(
          new ImportCustomizer()
              .addStarImports("jenkins", "jenkins.model", "hudson", "hudson.model"));
      GroovyShell shell = new GroovyShell(cl, new Binding(), cc);

      StringWriter out = new StringWriter();
      PrintWriter pw = new PrintWriter(out);
      shell.setVariable("out", pw);
      try {
        Object output = shell.evaluate(script);
        if (output != null) pw.println("Result: " + output);
      } catch (Throwable t) {
        t.printStackTrace(pw);
      }
      return out.toString();
    }
 @Test
 public void specialScript() throws Exception {
   CompilerConfiguration cc = GroovySandbox.createSecureCompilerConfiguration();
   cc.setScriptBaseClass(SpecialScript.class.getName());
   GroovyShell shell = new GroovyShell(cc);
   Whitelist wl =
       new AbstractWhitelist() {
         @Override
         public boolean permitsMethod(Method method, Object receiver, Object[] args) {
           return method.getDeclaringClass() == GroovyObject.class
               && method.getName().equals("getProperty")
               && receiver instanceof SpecialScript
               && args[0].equals("magic");
         }
       };
   assertEquals(42, GroovySandbox.run(shell.parse("magic"), wl));
   try {
     GroovySandbox.run(shell.parse("boring"), wl);
   } catch (MissingPropertyException x) {
     assertEquals("boring", x.getProperty());
   }
 }
Exemplo n.º 22
0
  void readConfig() {
    File config = new File(new File(rootdir), "imprempta.groovy");
    if (config.exists()) {
      Binding binding = new Binding();
      binding.setVariable("binder", this);
      binding.setVariable("ext", ext);

      CompilerConfiguration conf = new CompilerConfiguration();
      conf.setVerbose(true);
      GroovyShell shell = new GroovyShell(binding, conf);

      try {
        String s = new Scanner(new FileInputStream(config)).useDelimiter("\\Z").next();
        s =
            "import net.anzix.imprempta.api.*;\n"
                + "import net.anzix.imprempta.impl.*;\n"
                + "import static net.anzix.imprempta.api.Phase.*;\n\n"
                + s;
        shell.evaluate(s);
      } catch (IOException e) {
        throw new GeneratorException("Can't execute config file", e);
      }
    }
  }
Exemplo n.º 23
0
 private Object runScript(final String testScript) throws Exception {
   Script script = shell.parse(testScript);
   return script.run();
 }
Exemplo n.º 24
0
 private Closure compileClosure() {
   CompilerConfiguration compiler = new CompilerConfiguration();
   GroovyShell shell = new GroovyShell();
   registerTupleTypes(shell);
   return (Closure) shell.evaluate(mergeScript);
 }
Exemplo n.º 25
0
 public void evaluate(final String script) {
   shell.evaluate(script);
 }
Exemplo n.º 26
0
 @Override
 public void release() {
   invokeClosure(true, false, "onRelease");
   shell.resetLoadedClasses();
 }
  /** 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;
  }