Exemplo n.º 1
0
  public void makeApiAvailableToScripts(final Binding binding, final Object cla) {
    final Method[] declaredMethods = cla.getClass().getDeclaredMethods();
    for (Method method : declaredMethods) {
      final String name = method.getName();

      final int modifiers = method.getModifiers();
      if (Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers)) {
        binding.setVariable(name, new MethodClosure(cla, name));
      }
    }

    PropertyDescriptor[] propertyDescriptors;
    try {
      propertyDescriptors = Introspector.getBeanInfo(cla.getClass()).getPropertyDescriptors();
      for (PropertyDescriptor pd : propertyDescriptors) {
        final Method readMethod = pd.getReadMethod();
        if (readMethod != null) {
          if (isDeclared(cla, readMethod)) {
            binding.setVariable(pd.getName(), invokeMethod(readMethod, cla));
          }
        }
      }
    } catch (IntrospectionException e1) {
      // ignore
    }
  }
  private GroovyShell createEngine(AbstractBuild<?, ?> build, TaskListener listener) {

    ClassLoader cl = Jenkins.getInstance().getPluginManager().uberClassLoader;
    ScriptSandbox sandbox = null;
    CompilerConfiguration cc = new CompilerConfiguration();
    cc.addCompilationCustomizers(
        new ImportCustomizer()
            .addStarImports("jenkins", "jenkins.model", "hudson", "hudson.model"));

    ExtendedEmailPublisher publisher =
        build.getProject().getPublishersList().get(ExtendedEmailPublisher.class);
    if (publisher.getDescriptor().isSecurityEnabled()) {
      cc.addCompilationCustomizers(new SandboxTransformer());
      sandbox = new ScriptSandbox();
    }

    Binding binding = new Binding();
    binding.setVariable("build", build);
    binding.setVariable("project", build.getParent());
    binding.setVariable("rooturl", publisher.getDescriptor().getHudsonUrl());
    binding.setVariable("out", listener.getLogger());

    GroovyShell shell = new GroovyShell(cl, binding, cc);

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

    return shell;
  }
Exemplo n.º 3
0
  // забайндить переменные для Groovy
  public void bindGroovy(List<Obj> lobj) {
    // забайндить само приложение, как другой тип объекта
    binding.setVariable(this.appCd, this);

    // забайндить загруженные объекты
    for (Obj obj : (List<Obj>) lobj) {
      binding.setVariable(obj.getCd(), obj);
    }
  }
Exemplo n.º 4
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);
  }
  /**
   * 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();
  }
  protected PicoContainer createContainerFromScript(
      PicoContainer parentContainer, Object assemblyScope) {

    Binding binding = new Binding();
    if (parentContainer == null) {
      parentContainer =
          new DefaultNanoContainer(
              getClassLoader(), new DefaultPicoContainer(new Caching(), new EmptyPicoContainer()));
    }
    binding.setVariable("parent", parentContainer);
    binding.setVariable("builder", createGroovyNodeBuilder());
    binding.setVariable("assemblyScope", assemblyScope);
    handleBinding(binding);
    return runGroovyScript(binding);
  }
  @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.º 8
0
 /** Initialize the engine. */
 public void initialize(final BSFManager mgr, String lang, Vector declaredBeans)
     throws BSFException {
   super.initialize(mgr, lang, declaredBeans);
   ClassLoader parent = mgr.getClassLoader();
   if (parent == null) parent = GroovyShell.class.getClassLoader();
   final ClassLoader finalParent = parent;
   this.loader =
       (GroovyClassLoader)
           AccessController.doPrivileged(
               new PrivilegedAction() {
                 public Object run() {
                   CompilerConfiguration configuration = new CompilerConfiguration();
                   configuration.setClasspath(mgr.getClassPath());
                   return new GroovyClassLoader(finalParent, configuration);
                 }
               });
   execScripts = new HashMap();
   evalScripts = new HashMap();
   context = shell.getContext();
   // create a shell
   // register the mgr with object name "bsf"
   context.setVariable("bsf", new BSFFunctions(mgr, this));
   int size = declaredBeans.size();
   for (int i = 0; i < size; i++) {
     declareBean((BSFDeclaredBean) declaredBeans.elementAt(i));
   }
 }
Exemplo n.º 9
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.º 10
0
  /** Create the Spring application context that will hold CAS filters. */
  protected WebApplicationContext getApplicationContext() {
    if (this.applicationContext == null) {
      Binding binding = new Binding();
      binding.setVariable("securityRealm", this);
      binding.setVariable("casProtocol", this.casProtocol);

      BeanBuilder builder = new BeanBuilder(getClass().getClassLoader());
      builder.parse(
          getClass()
              .getClassLoader()
              .getResourceAsStream(getClass().getName().replace('.', '/') + ".groovy"),
          binding);

      this.applicationContext = builder.createApplicationContext();
    }
    return this.applicationContext;
  }
Exemplo n.º 11
0
 public static void velocityInternalContextToBindings(
     InternalContextAdapter context, Binding binding) {
   if (context == null || binding == null) return;
   for (Object k : context.getKeys()) {
     String key = k.toString();
     binding.setVariable(key, context.get(key));
   }
 }
Exemplo n.º 12
0
  public void runTest() {

    Map<String, Object> map = this.parent.getMap();
    map.put("url", this.urlName);
    try {
      String scriptText = TestUtils.readUrlText(this.urlName);
      Class scriptClass = GroovyUtil.parseClass(scriptText);

      Binding binding = new Binding();
      binding.setVariable("context", map);
      binding.setVariable("seleniumXml", this.parent);
      InvokerHelper.createScript(scriptClass, binding).run();
    } catch (MalformedURLException e) {
      System.out.println("Scriptrunner, runTest, MalformedURLException error: " + e.getMessage());
    } catch (IOException e) {
      System.out.println("Scriptrunner, runTest, IOException error: " + e.getMessage());
    }
  }
Exemplo n.º 13
0
  protected Binding createBinding() {
    Binding binding = new Binding();

    if (bindings != null) {
      for (Map.Entry<String, Object> nextBinding : bindings.entrySet()) {
        binding.setVariable(nextBinding.getKey(), nextBinding.getValue());
      }
    }

    return binding;
  }
Exemplo n.º 14
0
  public void doWithRuntimeConfiguration(RuntimeSpringConfiguration springConfig) {

    if (pluginBean.isReadableProperty(DO_WITH_SPRING)) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Plugin " + this + " is participating in Spring configuration...");
      }

      Closure c = (Closure) plugin.getProperty(DO_WITH_SPRING);
      BeanBuilder bb = new BeanBuilder(getParentCtx(), springConfig, application.getClassLoader());
      Binding b = new Binding();
      b.setVariable("application", application);
      b.setVariable("manager", getManager());
      b.setVariable("plugin", this);
      b.setVariable("parentCtx", getParentCtx());
      b.setVariable("resolver", getResolver());
      bb.setBinding(b);
      c.setDelegate(bb);
      bb.invokeMethod("beans", new Object[] {c});
    }
  }
  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.º 16
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.º 17
0
 /**
  * Writes out a GPathResult (i.e. the result of parsing XML using XmlSlurper) to the given writer.
  *
  * @param result The root node of the XML to write out.
  * @param output Where to write the XML to.
  * @throws IOException If the writing fails due to a closed stream or unwritable file.
  * @deprecated Will be removed in a future release
  */
 @Deprecated
 public static void writeSlurperResult(GPathResult result, Writer output) throws IOException {
   Binding b = new Binding();
   b.setVariable("node", result);
   // this code takes the XML parsed by XmlSlurper and writes it out using StreamingMarkupBuilder
   // don't ask me how it works, refer to John Wilson ;-)
   Writable w =
       (Writable)
           new GroovyShell(b)
               .evaluate(
                   "new groovy.xml.StreamingMarkupBuilder().bind {"
                       + " mkp.declareNamespace(\"\":  \"http://java.sun.com/xml/ns/j2ee\");"
                       + " mkp.yield node}");
   w.writeTo(output);
 }
Exemplo n.º 18
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 applyScript(Scope type, Map<String, Object> vars) {
   try {
     String root = null;
     String script = null;
     switch (type) {
       case GLOBAL_REQUEST:
         root = (String) vars.get(ROOT_PATH);
         script = "GlobalRequest.groovy";
         break;
       case GLOBAL_RESPONSE:
         root = (String) vars.get(ROOT_PATH);
         script = "GlobalResponse.groovy";
         break;
       case LOCAL_RESPONSE:
         SimulatorResponse simulatorResponse = (SimulatorResponse) vars.get(SIMULATOR_RESPONSE);
         if (simulatorResponse != null && simulatorResponse.getMatchingRequest() != null) {
           root = simulatorResponse.getMatchingRequest().getParentFile().getPath();
           script =
               simulatorResponse
                   .getMatchingRequest()
                   .getName()
                   .replaceAll(GROOVY_PATTERN, ".groovy");
         }
         break;
       default:
         break;
     }
     File file =
         new File(
             new StringBuilder().append(root).append(File.separator).append(script).toString());
     if (file.exists()) {
       log.debug("Applying script {} of type: {}, with vars: {}", new Object[] {file, type, vars});
       String[] roots = new String[] {root};
       GroovyScriptEngine gse = new GroovyScriptEngine(roots);
       Binding binding = new Binding();
       binding.setVariable("vars", vars);
       gse.run(script, binding);
       log.debug(
           "Applied script {} of type: {}, and updated vars are: {}",
           new Object[] {file, type, vars});
     } else {
       log.debug(
           "When applying script of type {}, script path {} is not an existing file", type, root);
     }
   } catch (Exception e) {
     log.error("Script error.", e);
   }
 }
 /** Initialize the engine. */
 public void initialize(final BSFManager mgr, String lang, Vector declaredBeans)
     throws BSFException {
   super.initialize(mgr, lang, declaredBeans);
   ClassLoader parent = mgr.getClassLoader();
   if (parent == null) parent = GroovyShell.class.getClassLoader();
   setLoader(mgr, parent);
   execScripts = new HashMap<Object, Class>();
   evalScripts = new HashMap<Object, Class>();
   context = shell.getContext();
   // create a shell
   // register the mgr with object name "bsf"
   context.setVariable("bsf", new BSFFunctions(mgr, this));
   int size = declaredBeans.size();
   for (int i = 0; i < size; i++) {
     declareBean((BSFDeclaredBean) declaredBeans.elementAt(i));
   }
 }
  @Override
  public SecurityComponents createSecurityComponents() {
    Binding binding = new Binding();
    binding.setVariable("instance", this);

    BeanBuilder builder = new BeanBuilder(Jenkins.getInstance().pluginManager.uberClassLoader);

    String fileName;
    if (getLDAPURL() != null) {
      fileName = "ReverseProxyLDAPSecurityRealm.groovy";
    } else {
      fileName = "ReverseProxySecurityRealm.groovy";
    }

    try {
      File override = new File(Jenkins.getInstance().getRootDir(), fileName);
      builder.parse(
          override.exists()
              ? new AutoCloseInputStream(new FileInputStream(override))
              : getClass().getResourceAsStream(fileName),
          binding);
    } catch (FileNotFoundException e) {
      throw new Error("Failed to load " + fileName, e);
    }
    WebApplicationContext appContext = builder.createApplicationContext();

    if (getLDAPURL() == null) {
      proxyTemplate = new ReverseProxySearchTemplate();

      return new SecurityComponents(
          findBean(AuthenticationManager.class, appContext),
          new ReverseProxyUserDetailsService(appContext));
    } else {
      ldapTemplate = new LdapTemplate(findBean(InitialDirContextFactory.class, appContext));

      if (groupMembershipFilter != null) {
        ProxyLDAPAuthoritiesPopulator authoritiesPopulator =
            findBean(ProxyLDAPAuthoritiesPopulator.class, appContext);
        authoritiesPopulator.setGroupSearchFilter(groupMembershipFilter);
      }

      return new SecurityComponents(
          findBean(AuthenticationManager.class, appContext),
          new ProxyLDAPUserDetailsService(this, appContext));
    }
  }
Exemplo n.º 22
0
  @Override
  public void run() {
    PrintStream out = null;
    InputStream in = null;

    try {
      out = new PrintStream(socket.getOutputStream());
      in = socket.getInputStream();

      binding.setVariable(OUT_KEY, out);

      final IO io = new IO(in, out, out);
      final Groovysh groovy = new Groovysh(Main.class.getClassLoader(), binding, io);

      try {
        groovy.run();
      } catch (final Exception e) {
        logger.log(Level.SEVERE, "Exception encountered while running shell", e);
      }

      if (!socket.isClosed()) {
        socket.close();
      }

    } catch (final Exception e) {
      logger.log(Level.SEVERE, "Exception encountered while creating shell", e);
    } finally {
      if (out != null) {
        try {
          out.close();
        } catch (final Exception e) {
          // Intentionally left blank
        }
      }

      if (in != null) {
        try {
          in.close();
        } catch (final Exception e) {
          // Intentionally left blank
        }
      }
    }
  }
  /**
   * 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;
  }
 private void doSetVariable(String name, Object value) {
   super.setVariable(name, value);
 }
    @Override
    protected void handleBinding(final Binding binding) {
      super.handleBinding(binding);

      binding.setVariable("foo", "bar");
    }
Exemplo n.º 26
0
 /**
  * Run a script identified by name with a single argument.
  *
  * @param scriptName name of the script to run
  * @param argument a single argument passed as a variable named <code>arg</code> in the binding
  * @return a <code>toString()</code> representation of the result of the execution of the script
  * @throws ResourceException if there is a problem accessing the script
  * @throws ScriptException if there is a problem parsing the script
  */
 public String run(String scriptName, String argument) throws ResourceException, ScriptException {
   Binding binding = new Binding();
   binding.setVariable("arg", argument);
   Object result = run(scriptName, binding);
   return result == null ? "" : result.toString();
 }
Exemplo n.º 27
0
 // забайндить переменные для Groovy
 public void bindEvent(Obj obj, EvQue e) {
   // забайндить объект+событие, которое произошло по нему
   binding.setVariable("o", obj);
   binding.setVariable("e", e);
 }
  /**
   * execute sql query
   *
   * @throws Exception
   */
  private void executeQuery() {
    Connection con = null;
    try {
      InputStream catExtIs =
          ScriptableMondrianDrillThroughTableModel.class
              .getClassLoader()
              .getResourceAsStream("/" + catalogExtension);
      if (catExtIs != null) {
        Digester catExtDigester = new Digester();
        catExtDigester.setClassLoader(
            ScriptableMondrianDrillThroughTableModel.class.getClassLoader());
        catExtDigester.push(this);
        catExtDigester.addSetProperties("extension");
        catExtDigester.addObjectCreate(
            "extension/script", "com.tonbeller.jpivot.mondrian.script.ScriptColumn");
        catExtDigester.addSetProperties("extension/script");
        catExtDigester.addSetNext("extension/script", "addScript");
        catExtDigester.parse(catExtIs);

        URL scriptsBaseURL =
            Thread.currentThread().getContextClassLoader().getResource(scriptRootUrl);
        scriptEngine = new GroovyScriptEngine(new URL[] {scriptsBaseURL});
      }
      con = getConnection();
      Statement s = con.createStatement();
      s.setMaxRows(maxResults);
      ResultSet rs = s.executeQuery(sql);
      ResultSetMetaData md = rs.getMetaData();
      int numCols = md.getColumnCount();
      List columnTitlesList = new ArrayList();
      // set column headings
      for (int i = 0; i < numCols; i++) {
        //	columns are 1 based
        columnTitlesList.add(i, md.getColumnName(i + 1));
      }
      // loop on script columns
      for (ListIterator sIt = scripts.listIterator(); sIt.hasNext(); ) {
        final ScriptColumn sc = (ScriptColumn) sIt.next();
        columnTitlesList.add(sc.getPosition() - 1, sc.getTitle());
      }
      columnTitles = (String[]) columnTitlesList.toArray(new String[0]);
      // loop through rows
      List tempRows = new ArrayList();
      Map scriptInput = new HashMap();
      Binding binding = new Binding();
      while (rs.next()) {
        List rowList = new ArrayList();
        scriptInput.clear();
        // loop on columns, 1 based
        for (int i = 0; i < numCols; i++) {
          rowList.add(i, rs.getObject(i + 1));
          scriptInput.put(columnTitles[i], rs.getObject(i + 1));
        }
        binding.setVariable("input", scriptInput);
        // loop on script columns
        for (ListIterator sIt = scripts.listIterator(); sIt.hasNext(); ) {
          final ScriptColumn sc = (ScriptColumn) sIt.next();
          scriptEngine.run(sc.getFile(), binding);
          final Object output = binding.getVariable("output");
          if (output instanceof Map) {
            Map outMap = (Map) output;
            rowList.add(
                sc.getPosition() - 1,
                new DefaultCell((String) outMap.get("URL"), (String) outMap.get("Value")));
          } else if (output instanceof String) {
            rowList.add(sc.getPosition() - 1, (String) output);
          } else {
            throw new Exception("Unknown groovy script return type (not a Map nor String).");
          }
        }
        tempRows.add(new DefaultTableRow(rowList.toArray()));
      }
      rs.close();
      rows = (TableRow[]) tempRows.toArray(new TableRow[0]);
    } catch (Exception e) {
      e.printStackTrace();
      logger.error("?", e);
      // problem occured, set table model to zero size
      rows = new TableRow[1];
      columnTitles = new String[1];
      columnTitles[0] = "An error occured";
      Object[] row = new Object[1];
      row[0] = e.toString();
      rows[0] = new DefaultTableRow(row);
      ready = false;
      return;
    } finally {
      try {
        con.close();
      } catch (Exception e1) {
        // ignore
      }
    }
    ready = true;
  }
Exemplo n.º 29
0
 public String render(Map<String, Object> args) {
     compile();
     Binding binding = new Binding(args);
     binding.setVariable("play", new Play());
     binding.setVariable("messages", new Messages());
     binding.setVariable("lang", Lang.get());
     StringWriter writer = null;
     Boolean applyLayouts = false;
     if (!args.containsKey("out")) {
         applyLayouts = true;
         layout.set(null);
         writer = new StringWriter();
         binding.setProperty("out", new PrintWriter(writer));
         currentTemplate.set(this);
     }
     if (!args.containsKey("_body") && !args.containsKey("_isLayout") && !args.containsKey("_isInclude")) {
         layoutData.set(new HashMap<Object, Object>());
         TagContext.init();
     }
     ExecutableTemplate t = (ExecutableTemplate) InvokerHelper.createScript(compiledTemplate, binding);
     t.template = this;
     Monitor monitor = null;
     try {
         monitor = MonitorFactory.start(name);
         long start = System.currentTimeMillis();
         t.run();
         monitor.stop();
         monitor = null;
         Logger.trace("%sms to render template %s", System.currentTimeMillis() - start, name);
     } catch (NoRouteFoundException e) {
         if (e.isSourceAvailable()) {
             throw e;
         }
         throwException(e);
     } catch (PlayException e) {
         throw (PlayException) cleanStackTrace(e);
     } catch (DoBodyException e) {
         if (Play.mode == Mode.DEV) {
             compiledTemplate = null;
             BytecodeCache.deleteBytecode(name);
         }
         Exception ex = (Exception) e.getCause();
         throwException(ex);
     } catch (Throwable e) {
         if (Play.mode == Mode.DEV) {
             compiledTemplate = null;
             BytecodeCache.deleteBytecode(name);
         }
         throwException(e);
     } finally {
         if (monitor != null) {
             monitor.stop();
         }
     }
     if (applyLayouts && layout.get() != null) {
         Map<String, Object> layoutArgs = new HashMap<String, Object>(args);
         layoutArgs.remove("out");
         layoutArgs.put("_isLayout", true);
         String layoutR = layout.get().render(layoutArgs);
         return layoutR.replace("____%LAYOUT%____", writer.toString().trim());
     }
     if (writer != null) {
         return writer.toString();
     }
     return null;
 }