Skip to content

Instantly share code, notes, and snippets.

@Youka
Last active June 6, 2017 01:05
Show Gist options
  • Select an option

  • Save Youka/fe32b38d841a3f6d4b860e1b1cf1fc08 to your computer and use it in GitHub Desktop.

Select an option

Save Youka/fe32b38d841a3f6d4b860e1b1cf1fc08 to your computer and use it in GitHub Desktop.
Groovy in Java test
/*
* The MIT License
*
* Copyright 2017 Youka.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package de.eis.test.groovy;
import groovy.lang.Binding;
import groovy.lang.GroovyRuntimeException;
import groovy.lang.GroovyShell;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.codehaus.groovy.control.CompilationFailedException;
/**
* Application entry class.
*
* @author Youka
*/
public class Main {
// Application entry point
public static void main(String[] args){
// Groovy script
final String script_name = "MyScript.groovy",
script_text = "println(\"${test}\")\n"
//+ "println(new de.eis.test.groovy.Main())\n"
+ "return 5;";
// Groovy environment
final ClassLoader cl = new RestrictedClassLoader(new String[]{"de.eis."});
// Groovy<-Java bindings
final Binding bind = new Binding();
final ByteArrayOutputStream log = new ByteArrayOutputStream();
final PrintStream logPrinter = new PrintStream(log);
bind.setProperty("out", logPrinter);
bind.setProperty("err", logPrinter);
bind.setProperty("test", cl);
// Groovy shell
final GroovyShell shell = new GroovyShell(cl, bind);
// Run code in groovy shell
try{
System.out.println("Result: " + shell.evaluate(script_text, script_name));
System.out.println("Log:\n" + log.toString());
}catch(final CompilationFailedException e){
System.err.println(e.getMessage());
}catch(final GroovyRuntimeException e){
for(final StackTraceElement trace : e.getStackTrace())
if(trace.getFileName().equals(script_name) && trace.getMethodName().equals("run")){
System.err.println(trace.toString() + ": " + e.getLocalizedMessage());
break;
}
}
}
public static final class RestrictedClassLoader extends ClassLoader{
// Restrictions for classes selection
private final String[] restrictions;
public RestrictedClassLoader(final String[] restrictions) {
// No parent classloader
super(null);
// Save restrictions
this.restrictions = restrictions;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
// Check by restrictions
if(restrictions != null)
for(final String restriction : this.restrictions)
if(name.startsWith(restriction))
throw new ClassNotFoundException("Tried to access a restricted class ('" + restriction + "')!");
// Find by system classloader
return ClassLoader.getSystemClassLoader().loadClass(name);
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>de.eis.test</groupId>
<artifactId>GroovyTest</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<name>GroovyTest</name>
<description>Execute Groovy scripts by given source.</description>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<showDeprecation>true</showDeprecation>
<debug>false</debug>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<goals>
<goal>single</goal>
</goals>
<phase>package</phase>
<id>single</id>
</execution>
</executions>
<configuration>
<archive>
<manifest>
<mainClass>de.eis.test.groovy.Main</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all-minimal</artifactId>
<version>1.5.8</version>
</dependency>
</dependencies>
</project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment