@SuppressWarnings("unchecked") private void configureUrlMapping(UrlMapping urlMapping) { if (binding != null) { Map<String, Object> vars = binding.getVariables(); for (String key : vars.keySet()) { if (isNotCoreMappingKey(key)) { parameterValues.put(key, vars.get(key)); } } binding.getVariables().clear(); } // Add the controller and action to the params map if // they are set. This ensures consistency of behaviour // for the application, i.e. "controller" and "action" // parameters will always be available to it. if (urlMapping.getControllerName() != null) { parameterValues.put("controller", urlMapping.getControllerName()); } if (urlMapping.getActionName() != null) { parameterValues.put("action", urlMapping.getActionName()); } urlMapping.setParameterValues(parameterValues); urlMappings.add(urlMapping); }
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; }
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 } }
@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."); }
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; }
public static JUnitReportsFactory createFromBuildBinding(Binding buildBinding) { // This is not great, the phase and type names probably shouldn't be sourced from the binding. return new JUnitReportsFactory( (String) buildBinding.getProperty("currentTestPhaseName"), (String) buildBinding.getProperty("currentTestTypeName"), (File) buildBinding.getProperty("testReportsDir"), (List<String>) buildBinding.getProperty("reportFormats")); }
// забайндить переменные для Groovy public void bindGroovy(List<Obj> lobj) { // забайндить само приложение, как другой тип объекта binding.setVariable(this.appCd, this); // забайндить загруженные объекты for (Obj obj : (List<Obj>) lobj) { binding.setVariable(obj.getCd(), obj); } }
private Binding addStaticBindings(Binding binding) { binding.setProperty("logger", new LogUtils()); binding.setProperty("ui", new UITools()); binding.setProperty("htmlUtils", HtmlUtils.getInstance()); binding.setProperty("textUtils", new TextUtils()); binding.setProperty("menuUtils", new MenuUtils()); binding.setProperty("config", new ConfigProperties()); return binding; }
@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); }
/** 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(); }
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; }
static GroovyShell shellFactory() { // todo: add other variables in the Binding context? Binding binding = new Binding(); // just says you have a variable that points to a ComponentBuilder // useless right now ComponentBuilder builder = new ComponentBuilder(); binding.setProperty("builder", builder); // ClassLoader loader = Thread.currentThread().getContextClassLoader(); // GroovyClassLoader groovyLoader = new GroovyClassLoader(loader) ; // GroovyShell shell = new GroovyShell(groovyLoader, binding) ; GroovyShell shell = new GroovyShell(binding); return shell; }
/** * @param args * @param instrumentation */ public static void agentmain(final String args, final Instrumentation instrumentation) throws Exception { profilerController = new ProfilerControllerImpl(instrumentation); StaticProfilerInterface.initialize(profilerController); profilerController.initialize(); final Binding binding = new Binding(); binding.setProperty("profiler", StaticProfilerInterface.INSTANCE.getProfiler()); shellServer = new ShellServer(7000, binding); shell.execute(shellServer); }
/** * 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); }
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); }
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); } }
public Object run() { source = (File) getBinding().getProperty("specification.source"); if (LOGGER.isInfoEnabled()) { LOGGER.info("load specification from {}", source); } resolveBeans(); specificationBody(); Binding binding = getBinding(); binding.setProperty("errors", errors); binding.setProperty("constraints", constraints); return null; }
/** 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); } }
/** 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)); } }
/** 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; }
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)); } }
@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)); } }
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; }
@SuppressWarnings("unchecked") public static void bindingsToVelocityInternalContext( Binding binding, InternalContextAdapter context) { if (context == null || binding == null) return; for (Object e : binding.getVariables().entrySet()) { Entry<String, Object> var = (Entry<String, Object>) e; context.put(var.getKey(), var.getValue()); } }
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()); } }
/** * 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; }
/** * This method overrides property retrieval in the scope of the {@code GroovyBeanDefinitionReader} * to either: * * <ul> * <li>Retrieve a variable from the bean builder's binding if it exists * <li>Retrieve a RuntimeBeanReference for a specific bean if it exists * <li>Otherwise just delegate to MetaClass.getProperty which will resolve properties from the * {@code GroovyBeanDefinitionReader} itself * </ul> */ public Object getProperty(String name) { Binding binding = getBinding(); if (binding != null && binding.hasVariable(name)) { return binding.getVariable(name); } else { if (this.namespaces.containsKey(name)) { return createDynamicElementReader(name); } if (getRegistry().containsBeanDefinition(name)) { GroovyBeanDefinitionWrapper beanDefinition = (GroovyBeanDefinitionWrapper) getRegistry() .getBeanDefinition(name) .getAttribute(GroovyBeanDefinitionWrapper.class.getName()); if (beanDefinition != null) { return new GroovyRuntimeBeanReference(name, beanDefinition, false); } else { return new RuntimeBeanReference(name, false); } } // This is to deal with the case where the property setter is the last // statement in a closure (hence the return value) else if (this.currentBeanDefinition != null) { MutablePropertyValues pvs = this.currentBeanDefinition.getBeanDefinition().getPropertyValues(); if (pvs.contains(name)) { return pvs.get(name); } else { DeferredProperty dp = this.deferredProperties.get(this.currentBeanDefinition.getBeanName() + name); if (dp != null) { return dp.value; } else { return getMetaClass().getProperty(this, name); } } } else { return getMetaClass().getProperty(this, name); } } }
@SuppressWarnings("unchecked") private void inheritBinding(final Binding binding) { if (binding == null) { return; } for (Object field : binding.getVariables().entrySet()) { this.binding.setVariable( ((Map.Entry<String, Object>) field).getKey(), ((Map.Entry<String, Object>) field).getValue()); } }