Java 类groovy.lang.Binding 实例源码

项目:Reer    文件:ApiGroovyCompiler.java   
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);
    }
}
项目:powsybl-core    文件:GroovyScriptPostProcessor.java   
@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);
        }
    }
}
项目:cas-5.1.0    文件:ReturnMappedAttributeReleasePolicy.java   
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;
}
项目:xm-commons    文件:LepScriptUtils.java   
/**
 * 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);

}
项目:jenkins-client-plugin    文件:OpenShiftGlobalVariable.java   
@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;

}
项目:xsp-groovy-shell    文件:GroovyShellCommand.java   
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;
}
项目:beaker-notebook-archive    文件:GroovyEvaluatorTest.java   
@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);
}
项目:xm-lep    文件:GroovyLepExecutor.java   
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;
}
项目:xmontiarc    文件:GroovyInterpreter.java   
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;
    }
项目:scipio-erp    文件:GroovyUtil.java   
/** 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);
}
项目:yajsw    文件:GroovyScript.java   
/**
 * 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);
}
项目:fabulae    文件:HasSkill.java   
@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;
}
项目:intellij-ce-playground    文件:DependentGroovycRunner.java   
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();
  }
}
项目:fabulae    文件:HasItemEquipped.java   
@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;
}
项目:eldemo    文件:RunPerform.java   
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);
}
项目:mdw    文件:TestCaseScript.java   
/**
 * 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;
            }
        }
    };
}
项目:mdw    文件:StandaloneTestCaseRun.java   
/**
 * 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);
    }
}
项目:mdw    文件:CrossmapActivity.java   
/**
 * 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();
}
项目:mdw    文件:GroovyExecutor.java   
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);
}
项目:cuba    文件:ScriptingManager.java   
@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);
    }
}
项目:cuba    文件:FoldersServiceBean.java   
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;
}
项目:cuba    文件:TimeBetweenQueryMacroHandler.java   
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;
}
项目:fabulae    文件:InventoryItem.java   
/**
 * 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();
}
项目:fabulae    文件:DropItem.java   
@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());
}
项目:fabulae    文件:UsableItem.java   
@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;
}
项目:fabulae    文件:SwitchToCombatMap.java   
@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);
    }
}
项目:fabulae    文件:FireQuestEvent.java   
@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));
}
项目:phoenix.webui.framework    文件:GroovyDynamicData.java   
@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;
}
项目:phoenix.webui.framework    文件:GroovyTest.java   
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()"));
        }
    }
项目:powsybl-core    文件:RunScriptTool.java   
@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();
    }
}
项目:cas-5.1.0    文件:RegisteredServiceScriptedAttributeFilter.java   
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<>();
}
项目:cas-5.1.0    文件:GroovyRegisteredServiceUsernameProvider.java   
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;
}
项目:httpstub    文件:RequestContext.java   
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;
}
项目:xm-ms-entity    文件:LepScriptUtils.java   
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);
}
项目:xm-lep    文件:GroovyLepExecutor.java   
@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);
}
项目:lams    文件:GroovyBeanDefinitionReader.java   
/**
 * 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;
}
项目:keti    文件:GroovyConditionScript.java   
@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();
}
项目:JuniperBotJ    文件:GroovyService.java   
@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());
}
项目:gerrit-plugin    文件:GerritDSL.java   
@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;
}
项目:jira-groovioli    文件:ScriptManagerImpl.java   
private Binding fromMap(Map<String, Object> parameters) {
    Map variables = new HashMap(baseVariables);

    if (parameters != null) {
        variables.putAll(parameters);
    }
    return new Binding(variables);
}