下面列出了org.springframework.beans.factory.parsing.Location#groovy.lang.GroovyShell 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
}
/**
* 生成自定义变量
*
* @param customValueMap 自定义值
* @param placeholder 占位符
* @param innerVariableMap 内部变量映射
* @return {@link String}
*/
private String generateCustomVariable(Map<String, CustomValue> customValueMap, Map<String, Object> innerVariableMap,
String placeholder) {
Optional<CustomValue> valueOptional = customValueMap.entrySet().stream()
.filter(entry -> placeholder.equalsIgnoreCase(entry.getKey())).map(Entry::getValue).findAny();
// 找不到自定义方法,返回原占位符
if (!valueOptional.isPresent()) {
return placeholder;
}
CustomValue value = valueOptional.get();
switch (value.getType()) {
case STRING:
return value.getValue();
case GROOVY:
try {
return new GroovyShell(new Binding(innerVariableMap)).evaluate(value.getValue()).toString();
} catch (Exception e) {
LOGGER.error(String.format("自定义变量%s的groovy脚本执行异常,请检查语法是否正确且有正确返回值:%s", placeholder, value.getValue()), e);
return value.getValue();
}
default:
return "";
}
}
public void testPlatformLineWriter() throws IOException, ClassNotFoundException {
String LS = System.lineSeparator();
Binding binding = new Binding();
binding.setVariable("first", "Tom");
binding.setVariable("last", "Adams");
StringWriter stringWriter = new StringWriter();
Writer platformWriter = new PlatformLineWriter(stringWriter);
GroovyShell shell = new GroovyShell(binding);
platformWriter.write(shell.evaluate("\"$first\\n$last\\n\"").toString());
platformWriter.flush();
assertEquals("Tom" + LS + "Adams" + LS, stringWriter.toString());
stringWriter = new StringWriter();
platformWriter = new PlatformLineWriter(stringWriter);
platformWriter.write(shell.evaluate("\"$first\\r\\n$last\\r\\n\"").toString());
platformWriter.flush();
assertEquals("Tom" + LS + "Adams" + LS, stringWriter.toString());
}
@Override
public void open() {
CompilerConfiguration conf = new CompilerConfiguration();
conf.setDebug(true);
shell = new GroovyShell(conf);
String classes = getProperty("GROOVY_CLASSES");
if (classes == null || classes.length() == 0) {
try {
File jar = new File(
GroovyInterpreter.class.getProtectionDomain().getCodeSource().getLocation().toURI()
.getPath());
classes = new File(jar.getParentFile(), "classes").toString();
} catch (Exception e) {
log.error(e.getMessage());
}
}
log.info("groovy classes classpath: " + classes);
if (classes != null && classes.length() > 0) {
File fClasses = new File(classes);
if (!fClasses.exists()) {
fClasses.mkdirs();
}
shell.getClassLoader().addClasspath(classes);
}
}
@Override
public void validateTripleSet(LintProblemSet problems, String file, List<Triple> tripeSet) {
if (this.getParameters().getRules() == null) {
return;
}
// execute sparql & custom validation
Graph g = Factory.createGraphMem();
tripeSet.forEach(g::add);
Model m = ModelFactory.createModelForGraph(g);
this.getParameters().getRules().stream()
.filter(r -> file.matches(r.getTarget()))
.forEach(r -> {
Query query = QueryFactory.create(r.getQuery());
QueryExecution qe = QueryExecutionFactory.create(query, m);
Binding binding = new Binding();
binding.setVariable("rs", qe.execSelect());
binding.setVariable("log", new ProblemLogger(this, problems, file, r.getName()));
GroovyShell shell = new GroovyShell(binding, new CompilerConfiguration());
shell.evaluate(r.getValid());
});
}
@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 void setupContextClassLoader(GroovyShell shell) {
final Thread current = Thread.currentThread();
class DoSetContext implements PrivilegedAction<Object> {
ClassLoader classLoader;
public DoSetContext(ClassLoader loader) {
classLoader = loader;
}
public Object run() {
current.setContextClassLoader(classLoader);
return null;
}
}
AccessController.doPrivileged(new DoSetContext(shell.getClassLoader()));
}
@Setup
public void setup()
throws IllegalAccessException, InstantiationException {
_concatScriptText = "firstName + ' ' + lastName";
_concatBinding = new Binding();
_concatScript = new GroovyShell(_concatBinding).parse(_concatScriptText);
_concatCodeSource = new GroovyCodeSource(_concatScriptText, Math.abs(_concatScriptText.hashCode()) + ".groovy",
GroovyShell.DEFAULT_CODE_BASE);
_concatGCLScript = (Script) _groovyClassLoader.parseClass(_concatCodeSource).newInstance();
_maxScriptText = "longList.max{ it.toBigDecimal() }";
_maxBinding = new Binding();
_maxScript = new GroovyShell(_maxBinding).parse(_maxScriptText);
_maxCodeSource = new GroovyCodeSource(_maxScriptText, Math.abs(_maxScriptText.hashCode()) + ".groovy",
GroovyShell.DEFAULT_CODE_BASE);
_maxGCLScript = (Script) _groovyClassLoader.parseClass(_maxCodeSource).newInstance();
}
/**
* 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 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);
}
}
@SuppressWarnings("unchecked")
private static void setupContextClassLoader(GroovyShell shell) {
final Thread current = Thread.currentThread();
@SuppressWarnings("rawtypes")
class DoSetContext implements PrivilegedAction {
ClassLoader classLoader;
public DoSetContext(ClassLoader loader) {
classLoader = loader;
}
public Object run() {
current.setContextClassLoader(classLoader);
return null;
}
}
AccessController.doPrivileged(new DoSetContext(shell.getClassLoader()));
}
@Test
public void testGroovyShell() throws Exception {
GroovyShell groovyShell = new GroovyShell();
final String s = "x > 2 && y > 1";
Script script = groovyShell.parse(s);
Binding binding = new Binding();
binding.setProperty("x",5);
binding.setProperty("y",3);
script.setBinding(binding);
Object result = script.run();
Assert.assertEquals(true, result);
log.debug("evaluating [{}] with (x,y)=({},{}) => {}\n", s,
script.getBinding().getProperty("x"), script.getBinding().getProperty("y"), result);
binding.setProperty("y",0);
result = script.run();
Assert.assertEquals(false, result);
log.debug("evaluating [{}] with (x,y)=({},{}) => {}\n", s,
binding.getProperty("x"), binding.getProperty("y"), result);
}
private void testPutGetScript(String script) throws IOException, URISyntaxException {
setupLogging();
DistributedFileSystem fileSystem = miniDFSCluster.getFileSystem();
Path dir = new Path("/user/guest/example");
fileSystem.delete(dir, true);
fileSystem.mkdirs(dir, new FsPermission("777"));
fileSystem.setOwner(dir, "guest", "users");
Binding binding = new Binding();
binding.setProperty("gateway", driver.getClusterUrl());
URL readme = driver.getResourceUrl("README");
File file = new File(readme.toURI());
binding.setProperty("file", file.getAbsolutePath());
GroovyShell shell = new GroovyShell(binding);
shell.evaluate(driver.getResourceUrl(script).toURI());
String status = (String) binding.getProperty("status");
assertNotNull(status);
String fetchedFile = (String) binding.getProperty("fetchedFile");
assertNotNull(fetchedFile);
assertThat(fetchedFile, containsString("README"));
}
/**
* Creates a new ChatAction from ConfigurableFactoryContext.
*
* @param ctx
* ConfigurableFactoryContext
* @return
* ChatAction instance
*/
protected ChatAction getRejectedAction(final ConfigurableFactoryContext ctx) {
String value = ctx.getString("rejectedAction", null);
if (value == null) {
return null;
}
Binding groovyBinding = new Binding();
final GroovyShell interp = new GroovyShell(groovyBinding);
try {
String code = "import games.stendhal.server.entity.npc.action.*;\r\n"
+ value;
return (ChatAction) interp.evaluate(code);
} catch (CompilationFailedException e) {
throw new IllegalArgumentException(e);
}
}
private void configureCompiler() {
if (scriptBaseClass != null) {
configuration.setScriptBaseClass(scriptBaseClass);
}
if (configscript != null) {
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);
File confSrc = new File(configscript);
try {
shell.evaluate(confSrc);
} catch (IOException e) {
throw new BuildException("Unable to configure compiler using configuration file: " + confSrc, e);
}
}
}
@Override
public Component getComponent(int width, int height) throws IOException {
final JPanel base = new JPanel();
base.setOpaque(false);
base.setPreferredSize(new Dimension(width, height));
base.setLayout(new BoxLayout(base, BoxLayout.Y_AXIS));
final Binding sharedData = new Binding();
final GroovyShell shell = new GroovyShell(sharedData);
sharedData.setProperty("slidePanel", base);
final Script script = shell.parse(new InputStreamReader(GroovySlide.class.getResourceAsStream("../test.groovy")));
script.run();
// final RSyntaxTextArea textArea = new RSyntaxTextArea(20, 60);
// textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_GROOVY);
// textArea.setCodeFoldingEnabled(true);
// final RTextScrollPane sp = new RTextScrollPane(textArea);
// base.add(sp);
return base;
}
@PostConstruct
public void init(){
GroovyClassLoader groovyClassLoader = new GroovyClassLoader(this.getClass().getClassLoader());
CompilerConfiguration compilerConfiguration = new CompilerConfiguration();
compilerConfiguration.setSourceEncoding("utf-8");
compilerConfiguration.setScriptBaseClass(TestScript.class.getName());
groovyShell = new GroovyShell(groovyClassLoader, groovyBinding, compilerConfiguration);
}
public static void main(String[] args) {
Binding groovyBinding = new Binding();
groovyBinding.setVariable("testService", new TestService());
GroovyShell groovyShell = new GroovyShell(groovyBinding);
String scriptContent = "import pers.doublebin.example.groovy.script.service.TestService\n" +
"def query = new TestService().testQuery(1L);\n" +
"query";
/*String scriptContent = "def query = testService.testQuery(2L);\n" +
"query";*/
Script script = groovyShell.parse(scriptContent);
System.out.println(script.run());
}
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()"));
}
}
public static GroovyCodeSource load(Path path) {
Objects.requireNonNull(path);
try (Reader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
return new GroovyCodeSource(reader, "script", GroovyShell.DEFAULT_CODE_BASE);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Test
public void testPrint() {
ASTTransformationCustomizer astCustomizer = new ASTTransformationCustomizer(new FakeTransformer());
ImportCustomizer imports = new ImportCustomizer();
CompilerConfiguration config = new CompilerConfiguration();
config.addCompilationCustomizers(astCustomizer, imports);
Binding binding = new Binding();
assertNull(new GroovyShell(binding, config).evaluate("print('hello')"));
}
public GroovyShell createGroovyShell(Exchange exchange) {
ImportCustomizer importCustomizer = new ImportCustomizer();
importCustomizer.addStaticStars("org.wildfly.camel.test.groovy.subA.CustomUtils");
CompilerConfiguration configuration = new CompilerConfiguration();
configuration.addCompilationCustomizers(importCustomizer);
ClassLoader classLoader = exchange.getContext().getApplicationContextClassLoader();
return new GroovyShell(classLoader, configuration);
}
@Test
public void testGroovyWithCustomObjects() throws IOException {
Binding binding = new Binding();
binding.setVariable("device", new Device("device-"+System.currentTimeMillis()));
for (Map.Entry<String, Object> entry : INPUT_STREAMLINE_EVENT.entrySet()) {
binding.setVariable(entry.getKey(), entry.getValue());
}
binding.setVariable("__outputSchema", OUTPUT_SCHEMA_FIELDS);
GroovyShell groovyShell = new GroovyShell(binding);
Object result = groovyShell.evaluate(getBulkScriptText());
}
@Before
public void setUp() {
network = createNetwork();
LoadFlowActionSimulatorObserver observer = createObserver();
GroovyCodeSource src = new GroovyCodeSource(new InputStreamReader(getClass().getResourceAsStream(getDslFile())), "test", GroovyShell.DEFAULT_CODE_BASE);
actionDb = new ActionDslLoader(src).load(network);
engine = new LoadFlowActionSimulator(network, computationManager, new LoadFlowActionSimulatorConfig("LoadFlowMock", 3, false, false),
applyIfWorks(), new LoadFlowParameters(), observer);
}
public static void processConfigScripts(List<String> scripts, CompilerConfiguration conf) throws IOException {
if (scripts.isEmpty()) return;
GroovyShell shell = createConfigScriptsShell(conf);
for (String script : scripts) {
shell.evaluate(new File(script));
}
}
@Override
public List<Curve> get(Network network) {
List<Curve> curves = new ArrayList<>();
Binding binding = new Binding();
binding.setVariable("network", network);
ExpressionDslLoader.prepareClosures(binding);
extensions.forEach(e -> e.load(binding, curves::add));
GroovyShell shell = new GroovyShell(binding, new CompilerConfiguration());
shell.evaluate(codeSource);
return curves;
}
public Map<String,Object> filter(Map<String,Object> input) {
Binding binding = new Binding();
binding.setVariable("input", input);
GroovyShell shell = new GroovyShell(binding);
String filterScript = "def field = input.get('field')\n"
+ "if (input.field == 'buyer') { return ['losDataBusinessName':'losESDataBusiness3', 'esIndex':'potential_goods_recommend1']}\n"
+ "if (input.field == 'seller') { return ['losDataBusinessName':'losESDataBusiness4', 'esIndex':'potential_goods_recommend2']}\n";
Script script = shell.parse(filterScript);
Object ret = script.run();
System.out.println(ret);
return (Map<String, Object>) ret;
}
private GroovyShell getOrCreateShell(Optional<String> baseScript) {
if (baseScript.isPresent()) {
return shellsCache.computeIfAbsent(baseScript.get(), baseScriptTextKey -> createGroovyShell(contextClassLoader, baseScriptTextKey));
} else {
return groovyShell;
}
}
public void testClassPropsGroovy() {
Object testObject = new GroovyShell().evaluate("class Test {def meth1(a,b){}}\nreturn new Test()");
Inspector insp = new Inspector(testObject);
String[] classProps = insp.getClassProps();
assertEquals("package n/a", classProps[Inspector.CLASS_PACKAGE_IDX]);
assertEquals("public class Test", classProps[Inspector.CLASS_CLASS_IDX]);
assertEquals("implements GroovyObject ", classProps[Inspector.CLASS_INTERFACE_IDX]);
assertEquals("extends Object", classProps[Inspector.CLASS_SUPERCLASS_IDX]);
assertEquals("is Primitive: false, is Array: false, is Groovy: true", classProps[Inspector.CLASS_OTHER_IDX]);
}
public static void main(String[] args) {
final GroovyShell shell = new GroovyShell(new Binding());
final Groovy groovy = new Groovy();
for (int i = 1; i < args.length; i++) {
final Commandline.Argument argument = groovy.createArg();
argument.setValue(args[i]);
}
final AntBuilder builder = new AntBuilder();
groovy.setProject(builder.getProject());
groovy.parseAndRunScript(shell, null, null, null, new File(args[0]), builder);
}