private void applyConfigurationScript(File configScript, CompilerConfiguration configuration) { VersionNumber version = parseGroovyVersion(); if (version.compareTo(VersionNumber.parse("2.1")) < 0) { throw new GradleException("Using a Groovy compiler configuration script requires Groovy 2.1+ but found Groovy " + version + ""); } 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); try { shell.evaluate(configScript); } catch (Exception e) { throw new GradleException("Could not execute Groovy compiler configuration script: " + configScript.getAbsolutePath(), e); } }
@Override public void process(Network network, ComputationManager computationManager) throws Exception { if (Files.exists(script)) { LOGGER.debug("Execute groovy post processor {}", script); try (Reader reader = Files.newBufferedReader(script, StandardCharsets.UTF_8)) { CompilerConfiguration conf = new CompilerConfiguration(); Binding binding = new Binding(); binding.setVariable("network", network); binding.setVariable("computationManager", computationManager); GroovyShell shell = new GroovyShell(binding, conf); shell.evaluate(reader); } } }
private static Object getGroovyAttributeValue(final String groovyScript, final Map<String, Object> resolvedAttributes) { try { final Binding binding = new Binding(); final GroovyShell shell = new GroovyShell(binding); binding.setVariable("attributes", resolvedAttributes); binding.setVariable("logger", LOGGER); LOGGER.debug("Executing groovy script [{}] with attributes binding of [{}]", StringUtils.abbreviate(groovyScript, groovyScript.length() / 2), resolvedAttributes); final Object res = shell.evaluate(groovyScript); return res; } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return null; }
/** * Executes any script. * * @param scriptResourceKey current script resource key * @param proceedingLep method proceed for Around scripts * @param method LEP method * @param managerService LEP manager service * @param resourceExecutorSupplier LEP resource script executor supplier * @param methodResult LEP method result * @param overrodeArgValues arg values to override (can be {@code null}) * @return Groovy script binding * @throws LepInvocationCauseException when exception in script occurs */ static Object executeScript(UrlLepResourceKey scriptResourceKey, ProceedingLep proceedingLep, // can be null LepMethod method, LepManagerService managerService, Supplier<GroovyScriptRunner> resourceExecutorSupplier, LepMethodResult methodResult, // can be null Object... overrodeArgValues) throws LepInvocationCauseException { GroovyScriptRunner runner = resourceExecutorSupplier.get(); String scriptName = runner.getResourceKeyMapper().map(scriptResourceKey); Binding binding = buildBinding(scriptResourceKey, managerService, method, proceedingLep, methodResult, overrodeArgValues); return runner.runScript(scriptResourceKey, method, managerService, scriptName, binding); }
@Nonnull @Override public Object getValue(@Nonnull CpsScript script) throws Exception { Binding binding = script.getBinding(); script.println(); Object openshift; if (binding.hasVariable(getName())) { openshift = binding.getVariable(getName()); } else { // Note that if this were a method rather than a constructor, we // would need to mark it @NonCPS lest it throw // CpsCallableInvocation. openshift = script.getClass().getClassLoader() .loadClass("com.openshift.jenkins.plugins.OpenShiftDSL") .getConstructor(CpsScript.class).newInstance(script); binding.setVariable(getName(), openshift); } return openshift; }
private Binding createBinding(Map<String, Object> objects, OutputStream out, OutputStream err) throws UnsupportedEncodingException { Binding binding = new Binding(); if (objects != null) for (Map.Entry<String, Object> row : objects.entrySet()) binding.setVariable(row.getKey(), row.getValue()); binding.setVariable("out", createPrintStream(out)); binding.setVariable("err", createPrintStream(err)); binding.setVariable("activeSessions", new Closure<List<AbstractSession>>(this) { @Override public List<AbstractSession> call() { return sshd.getActiveSessions(); } }); return binding; }
@BeforeClass public static void initClassStubData() throws IOException { GroovyEvaluator groovyEvaluator = new GroovyEvaluator("123", "345"); GroovyDefaultVariables var = new GroovyDefaultVariables(); HashMap<String, Object> params = new HashMap<>(); params.put(KernelControlSetShellHandler.IMPORTS, var.getImports()); params.put(KernelControlSetShellHandler.CLASSPATH, var.getClassPath()); KernelParameters kernelParameters = new KernelParameters(params); groovyEvaluator.setShellOptions(kernelParameters); groovyClassLoader = groovyEvaluator.newEvaluator(); scriptBinding = new Binding(); scriptBinding.setVariable("beaker", NamespaceClient.getBeaker("345")); groovyKernel = new GroovyKernelMock(); KernelManager.register(groovyKernel); }
private Binding buildBinding(LepManagerService managerService, LepMethod method) { Binding binding = new Binding(); // add execution context values ScopedContext executionContext = managerService.getContext(ContextScopes.EXECUTION); if (executionContext != null) { executionContext.getValues().forEach(binding::setVariable); } // add method arg values final String[] parameterNames = method.getMethodSignature().getParameterNames(); final Object[] methodArgValues = method.getMethodArgValues(); for (int i = 0; i < parameterNames.length; i++) { String paramName = parameterNames[i]; Object paramValue = methodArgValues[i]; binding.setVariable(paramName, paramValue); } return binding; }
public static EObject interpret(String groovyScript) { EDataType data = EcorePackage.eINSTANCE.getEString(); Binding binding = new Binding(); //Binding setVariable allow to pass a variable from the moonti arc model to the groovy interpreter //binding.setVariable(name, value); GroovyShell shell = new GroovyShell(binding); Object result = shell.evaluate(groovyScript); //Binding.getVariable get the new value of this variable. // binding.getVariable(name) // data.setName(""+(rand.nextInt(100)+1)); data.setName(""+result); return data; }
/** Returns a <code>Binding</code> instance initialized with the * variables contained in <code>context</code>. If <code>context</code> * is <code>null</code>, an empty <code>Binding</code> is returned. * <p>The <code>context Map</code> is added to the <code>Binding</code> * as a variable called "context" so that variables can be passed * back to the caller. Any variables that are created in the script * are lost when the script ends unless they are copied to the * "context" <code>Map</code>.</p> * * @param context A <code>Map</code> containing initial variables * @return A <code>Binding</code> instance */ public static Binding getBinding(Map<String, Object> context) { Map<String, Object> vars = new HashMap<String, Object>(); if (context != null) { vars.putAll(context); vars.put("context", context); if (vars.get(ScriptUtil.SCRIPT_HELPER_KEY) == null) { ScriptContext scriptContext = ScriptUtil.createScriptContext(context); ScriptHelper scriptHelper = (ScriptHelper)scriptContext.getAttribute(ScriptUtil.SCRIPT_HELPER_KEY); if (scriptHelper != null) { vars.put(ScriptUtil.SCRIPT_HELPER_KEY, scriptHelper); } } } return new Binding(vars); }
/** * Instantiates a new groovy script. * * @param script * the script * @param timeout * @throws IOException * @throws CompilationFailedException * @throws IllegalAccessException * @throws InstantiationException * @throws ClassNotFoundException */ public GroovyScript(final String script, final String id, final WrappedProcess process, final String[] args, final int timeout, final InternalLogger logger, String encoding, boolean reload, int maxConcInvocations) throws CompilationFailedException, IOException, InstantiationException, IllegalAccessException, ClassNotFoundException { super(script, id, process, args, timeout, maxConcInvocations); _reload = reload; _encoding = encoding; // let's call some method on an instance _script = getScriptInstance(script, encoding); binding = (Binding) _script.invokeMethod("getBinding", null); binding.setVariable("args", args); binding.setVariable("callCount", 0); binding.setVariable("context", context); if (process != null && logger == null) _logger = process.getInternalWrapperLogger(); else _logger = logger; binding.setVariable("logger", _logger); }
@Override protected boolean evaluate(Object object, Binding parameters) { if (object instanceof GameCharacter) { GameCharacter character = (GameCharacter) object; Skill skill = Skill.valueOf(getParameter(XML_SKILL_NAME).toUpperCase(Locale.ENGLISH)); int rank = character.stats().skills().getSkillRank(skill); if (Boolean.valueOf(getParameter(XML_MINUMUM_SKILL_LEVEL))) { if (rank < character.stats().skills().getBaseSkillRank(skill)) { rank = character.stats().skills().getBaseSkillRank(skill); } } String minRank = getParameter(XML_MINUMUM_SKILL_LEVEL); if (minRank == null) { return rank > 0; } else { return rank >= Integer.parseInt(minRank); } } return false; }
private static void applyConfigurationScript(File configScript, CompilerConfiguration configuration) { 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); try { new GroovyShell(binding, configuratorConfig).evaluate(configScript); } catch (Exception e) { e.printStackTrace(); } }
@Override protected boolean evaluate(Object object, Binding parameters) { String itemId = getParameter(XML_ITEM_NAME); InventoryItem item = null; if (object instanceof GameCharacter) { item = ((GameCharacter) object).getInventory().getItem(itemId); } else if (object instanceof CharacterGroup) { for (GameCharacter character : ((CharacterGroup)object).getMembers()) { item = character.getInventory().getItem(itemId); } } if (item != null && item.getInventoryBag() == BagType.EQUIPPED) { return true; } return false; }
public static void runGroovy(int xmax, int ymax, int zmax) { Binding binding = new Binding(); GroovyShell shell = new GroovyShell(binding); String expression = "x + y*2 - z"; Integer result = 0; Date start = new Date(); for (int xval = 0; xval < xmax; xval++) { for (int yval = 0; yval < ymax; yval++) { for (int zval = 0; zval <= zmax; zval++) { binding.setVariable("x", xval); binding.setVariable("y", yval); binding.setVariable("z", zval); Integer cal = (Integer) shell.evaluate(expression); result += cal; } } } Date end = new Date(); System.out.println("Groovy:time is : " + (end.getTime() - start.getTime()) + ",result is " + result); }
/** * Matches according to GPath. */ public Closure<Boolean> gpath(final String condition) throws TestException { return new Closure<Boolean>(this, this) { @Override public Boolean call(Object request) { try { GPathResult gpathRequest = new XmlSlurper().parseText(request.toString()); Binding binding = getBinding(); binding.setVariable("request", gpathRequest); return (Boolean) new GroovyShell(binding).evaluate(condition); } catch (Exception ex) { ex.printStackTrace(getTestCaseRun().getLog()); getTestCaseRun().getLog().println("Failed to parse request as XML/JSON. Stub response: " + AdapterActivity.MAKE_ACTUAL_CALL); return false; } } }; }
/** * Standalone execution for Designer and Gradle. */ public void run() { startExecution(); CompilerConfiguration compilerConfig = new CompilerConfiguration(System.getProperties()); compilerConfig.setScriptBaseClass(TestCaseScript.class.getName()); Binding binding = new Binding(); binding.setVariable("testCaseRun", this); ClassLoader classLoader = this.getClass().getClassLoader(); GroovyShell shell = new GroovyShell(classLoader, binding, compilerConfig); shell.setProperty("out", getLog()); setupContextClassLoader(shell); try { shell.run(new GroovyCodeSource(getTestCase().file()), new String[0]); finishExecution(null); } catch (IOException ex) { throw new RuntimeException(ex.getMessage(), ex); } }
/** * Returns the builder object for creating new output variable value. */ protected void runScript(String mapperScript, Slurper slurper, Builder builder) throws ActivityException, TransformerException { CompilerConfiguration compilerConfig = new CompilerConfiguration(); compilerConfig.setScriptBaseClass(CrossmapScript.class.getName()); Binding binding = new Binding(); binding.setVariable("runtimeContext", getRuntimeContext()); binding.setVariable(slurper.getName(), slurper.getInput()); binding.setVariable(builder.getName(), builder); GroovyShell shell = new GroovyShell(getPackage().getCloudClassLoader(), binding, compilerConfig); Script gScript = shell.parse(mapperScript); // gScript.setProperty("out", getRuntimeContext().get); gScript.run(); }
public Object evaluate(String expression, Map<String, Object> bindings) throws ExecutionException { binding = new Binding(); for (String bindName : bindings.keySet()) { Object value = bindings.get(bindName); DocumentReferenceTranslator docRefTranslator = getDocRefTranslator(value); if (docRefTranslator != null) { try { if (!(docRefTranslator instanceof XmlBeanWrapperTranslator)) { value = new XmlSlurper().parseText(docRefTranslator.realToString(value)); } } catch (Exception ex) { throw new ExecutionException("Cannot parse document content: '" + bindName + "'", ex); } } binding.setVariable(bindName, value); } return runScript(expression); }
@Authenticated @Override public String runGroovyScript(String scriptName) { try { Binding binding = new Binding(); binding.setVariable("persistence", persistence); binding.setVariable("metadata", metadata); binding.setVariable("configuration", configuration); binding.setVariable("dataManager", dataManager); Object result = scripting.runGroovyScript(scriptName, binding); return String.valueOf(result); } catch (Exception e) { log.error("Error runGroovyScript", e); return ExceptionUtils.getStackTrace(e); } }
protected boolean loadFolderQuantity(Binding binding, AppFolder folder) { if (!StringUtils.isBlank(folder.getQuantityScript())) { binding.setVariable("folder", folder); String styleVariable = "style"; binding.setVariable(styleVariable, null); try { Number qty = runScript(folder.getQuantityScript(), binding); folder.setItemStyle((String) binding.getVariable(styleVariable)); folder.setQuantity(qty == null ? null : qty.intValue()); } catch (Exception e) { log.warn("Unable to evaluate AppFolder quantity script for folder: id: {} , name: {}", folder.getId(), folder.getName(), e); return false; } } return true; }
protected String getParam(String[] args, int idx, TimeZone timeZone) { String arg = args[idx].trim(); String unit = args[3].trim(); Matcher matcher = PARAM_PATTERN.matcher(arg); if (!matcher.find()) throw new RuntimeException("Invalid macro argument: " + arg); int num = 0; try { String expr = matcher.group(2); if (!Strings.isNullOrEmpty(expr)) { Scripting scripting = AppBeans.get(Scripting.class); num = scripting.evaluateGroovy(expr, new Binding()); } } catch (NumberFormatException e) { throw new RuntimeException("Invalid macro argument: " + arg, e); } Date date = computeDate(num, unit, timeZone); String paramName = args[0].trim().replace(".", "_") + "_" + count + "_" + idx; params.put(paramName, date); return paramName; }
/** * Returns how many times the supplied item can be added to the given slot * in the given bag by the given container. 0 means the item cannot be added * to the slot at all. * * @param slot * @return */ public int canBeAddedTo(BagType bag, int slot, InventoryContainer container) { if (BagType.EQUIPPED.equals(bag)) { if (!checkEquippedSlot(slot, container)) { return 0; } if (s_equipCondition != null) { Binding binding = new Binding(); binding.setVariable("slot", slot); binding.setVariable("item", this); return s_equipCondition.execute(container.getInventory().getConditionTarget(), binding) ? getStackSize() : 0; } } else if (BagType.QUICKUSE.equals(bag)) { if (!Condition.areResultsOk(canBeAddedToQuickUse(container))) { return 0; } } InventoryCheckResult checkResult = container.getInventory().canAddItem(this); if (checkResult.getError() != null) { Log.log(checkResult.getError(), LogType.INVENTORY); } return checkResult.getAllowedStackSize(); }
@Override protected void run(Object object, Binding parameters) { if (!(object instanceof PositionedThing)) { throw new GdxRuntimeException("DropItem can only be called on positioned things!"); } String itemId = getParameter(XMLUtil.XML_ATTRIBUTE_ID); InventoryItem item = null; if (object instanceof GameCharacter) { Inventory inventory = ((GameCharacter)object).getInventory(); item = inventory.removeItem(itemId); } if (item == null) { item = InventoryItem.getItem(itemId); } Position position = ((PositionedThing)object).position(); new PickableGameObject(item, position.getX(), position.getY(), gameState.getCurrentMap()); }
@Override public Array<ConditionResult> canBeUsedBy(InventoryContainer ic) { Array<ConditionResult> result = new Array<ConditionResult>(); if (useCondition != null) { result.addAll(useCondition.evaluateWithDetails(ic, new Binding())); } if (ic instanceof GameCharacter) { GameCharacter character = (GameCharacter) ic; result.add(new ConditionResult(Strings.getString( Condition.STRING_TABLE, "combatOnly"), !isCombatOnly() || (character.getMap() != null && !character.getMap() .isWorldMap()))); result.add(new ConditionResult(Strings.getString( Condition.STRING_TABLE, "apRequired", Configuration.getAPCostUseItem()), !GameState .isCombatInProgress() || character.stats().getAPAct() >= Configuration .getAPCostUseItem())); } return result; }
@Override protected void run(Object object, Binding parameters) { if (!gameState.getCurrentMap().isWorldMap()) { throw new GdxRuntimeException("SwitchToCombatMap can only be used on world maps."); } PlayerCharacterGroupGameObject playerGroup = GameState.getPlayerCharacterGroup().getGroupGameObject(); try { CharacterGroup encounter = new CharacterGroup(Gdx.files.internal(Configuration.getFolderGroups() + getParameter(XML_ENEMY_GROUP) + ".xml")); encounter.setShouldBeSaved(false); playerGroup.startRandomEncounter(encounter, true); } catch (IOException e) { throw new GdxRuntimeException("Error loading enemy group in SwitchToCombatMap.", e); } }
@Override protected void run(Object object, Binding parameters) { Quest quest = null; if (object instanceof Quest) { quest = (Quest) object; } String questId = getParameter(XML_QUEST); if (questId != null) { quest = Quest.getQuest(questId); } if (quest == null) { throw new GdxRuntimeException("Could not find quest with id "+questId+" for action "+getClass().getName()); } quest.processEvent(getParameter(XML_EVENT)); }
@Override public String getValue(String orginData) { String value; Binding binding = new Binding(); GroovyShell shell = new GroovyShell(binding); binding.setVariable("globalMap", globalMap); Object resObj = null; try { resObj = shell.evaluate(groovyCls + orginData); if(resObj != null) { value = resObj.toString(); } else { value = "groovy not return!"; } } catch(CompilationFailedException e) { value = e.getMessage(); logger.error("Groovy动态数据语法错误!", e); } return value; }
public static void main(String[] args) throws Exception { Binding binding = new Binding(); binding.setVariable("language", "Groovy"); GroovyShell shell = new GroovyShell(binding); GroovyScriptEngine engine = new GroovyScriptEngine(new URL[]{GroovyTest.class.getClassLoader().getResource("/")}); Script script = shell.parse(GroovyTest.class.getClassLoader().getResource("random.groovy").toURI()); // System.out.println(script); // script.invokeMethod("new SuRenRandom()", null); // script.evaluate("new SuRenRandom()"); // engine.run("random.groovy", binding); InputStream stream = GroovyTest.class.getClassLoader().getResource("random.groovy").openStream(); StringBuffer buf = new StringBuffer(); byte[] bf = new byte[1024]; int len = -1; while((len = stream.read(bf)) != -1) { buf.append(new String(bf, 0, len)); } buf.append("\n"); for(int i = 0; i < 30; i++) { System.out.println(shell.evaluate(buf.toString() + "new SuRenRandom().randomPhoneNum()")); System.out.println(shell.evaluate(buf.toString() + "new SuRenRandom().randomEmail()")); System.out.println(shell.evaluate(buf.toString() + "new SuRenRandom().randomZipCode()")); } }
@Override public void run(CommandLine line, ToolRunningContext context) throws Exception { Path file = context.getFileSystem().getPath(line.getOptionValue(FILE)); Writer writer = new OutputStreamWriter(context.getOutputStream()); try { AppLogger logger = new AppLogger() { @Override public void log(String message, Object... args) { context.getOutputStream().println(String.format(message, args)); } @Override public AppLogger tagged(String tag) { return this; } }; try (AppData data = new AppData(context.getComputationManager(), fileSystemProviders, fileExtensions, projectFileExtensions, serviceExtensions, () -> logger)) { if (file.getFileName().toString().endsWith(".groovy")) { try { Binding binding = new Binding(); binding.setProperty("args", line.getArgs()); GroovyScripts.run(file, data, binding, writer); } catch (Throwable t) { Throwable rootCause = StackTraceUtils.sanitizeRootCause(t); rootCause.printStackTrace(context.getErrorStream()); } } else { throw new IllegalArgumentException("Script type not supported"); } } } finally { writer.flush(); } }
private static Map<String, Object> getGroovyAttributeValue(final String groovyScript, final Map<String, Object> resolvedAttributes) { try { final Binding binding = new Binding(); final GroovyShell shell = new GroovyShell(binding); binding.setVariable("attributes", resolvedAttributes); binding.setVariable("logger", LOGGER); final Map<String, Object> res = (Map<String, Object>) shell.evaluate(groovyScript); return res; } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return new HashMap<>(); }
private static Object getGroovyAttributeValue(final Principal principal, final String script) { try { final Binding binding = new Binding(); final GroovyShell shell = new GroovyShell(binding); binding.setVariable("attributes", principal.getAttributes()); binding.setVariable("id", principal.getId()); binding.setVariable("logger", LOGGER); final Object res = shell.evaluate(script); return res; } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return null; }
Binding createBinding() { val binding = new Binding(); binding.setVariable("headers", requestHeaders); binding.setVariable("path", pathVariables); binding.setVariable("params", requestParams); binding.setVariable("body", requestBody); binding.setVariable("constants", constants); return binding; }
static Object executeScript(UrlLepResourceKey scriptResourceKey, ProceedingLep proceedingLep, // can be null LepMethod method, LepManagerService managerService, Supplier<GroovyScriptRunner> resourceExecutorSupplier, Object... overrodeArgValues) throws LepInvocationCauseException { GroovyScriptRunner runner = resourceExecutorSupplier.get(); String scriptName = runner.getResourceKeyMapper().map(scriptResourceKey); Binding binding = buildBinding(scriptResourceKey, managerService, method, proceedingLep, overrodeArgValues); return runner.runScript(scriptResourceKey, method, managerService, scriptName, binding); }
@Override public Object executeLepResource(UrlLepResourceKey resourceKey, LepMethod method, LepManagerService managerService, Supplier<GroovyScriptRunner> resourceExecutorSupplier) throws LepInvocationCauseException { GroovyScriptRunner groovyScriptRunner = resourceExecutorSupplier.get(); ScriptNameLepResourceKeyMapper resourceKeyMapper = groovyScriptRunner.getResourceKeyMapper(); String scriptName = resourceKeyMapper.map(resourceKey); Binding binding = buildBinding(managerService, method); return groovyScriptRunner.runScript(resourceKey, method, managerService, scriptName, binding); }
/** * Load bean definitions from the specified Groovy script. * @param encodedResource the resource descriptor for the Groovy script, * allowing to specify 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 { 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(), encodedResource.getResource().getFilename()); } catch (Throwable ex) { throw new BeanDefinitionParsingException(new Problem("Error evaluating Groovy script: " + ex.getMessage(), new Location(encodedResource.getResource()), null, ex)); } return getRegistry().getBeanDefinitionCount() - countBefore; }
@Override public boolean execute(final Map<String, Object> boundVariables) { if (LOGGER.isDebugEnabled()) { StringBuilder msgBuilder = new StringBuilder(); msgBuilder.append("The script is bound to the following variables:\n"); for (Entry<String, Object> entry : boundVariables.entrySet()) { msgBuilder.append("* ").append(entry.getKey()).append(":").append(entry.getValue()).append("\n"); } LOGGER.debug(msgBuilder.toString()); } Binding binding = new Binding(boundVariables); this.script.setBinding(binding); return (boolean) this.script.run(); }
@PostConstruct public void init() { ImportCustomizer importCustomizer = new ImportCustomizer(); importCustomizer.addStarImports("net.dv8tion.jda.core.entities"); configuration = new CompilerConfiguration(); configuration.addCompilationCustomizers(importCustomizer); sharedData = new Binding(); sharedData.setProperty("ctx", context); sharedData.setProperty("jda", discordService.getJda()); }
@Override public Object getValue(CpsScript script) throws Exception { Binding binding = script.getBinding(); Object gerrit; if (binding.hasVariable(getName())) { gerrit = binding.getVariable(getName()); } else { // Note that if this were a method rather than a constructor, we would need to mark it @NonCPS lest it throw CpsCallableInvocation. gerrit = script.getClass().getClassLoader().loadClass("jenkins.plugins.gerrit.workflow.Gerrit").getConstructor(CpsScript.class).newInstance(script); binding.setVariable(getName(), gerrit); } return gerrit; }
private Binding fromMap(Map<String, Object> parameters) { Map variables = new HashMap(baseVariables); if (parameters != null) { variables.putAll(parameters); } return new Binding(variables); }