BAEL-2899: adding some more case scenarios

This commit is contained in:
Gian Mario Contessa 2019-05-26 01:09:20 +01:00
parent 7c3082a093
commit 653717e25e
6 changed files with 228 additions and 30 deletions

View File

@ -0,0 +1,148 @@
<?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>
<artifactId>java-groovy-joint</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>java-groovy-joint</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<commons-lang3.version>3.9</commons-lang3.version>
<java.version>1.8</java.version>
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
<logback.version>1.2.3</logback.version>
<groovy.version>2.5.7</groovy.version>
</properties>
<pluginRepositories>
<pluginRepository>
<id>bintray</id>
<name>Groovy Bintray</name>
<url>https://dl.bintray.com/groovy/maven</url>
<releases>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>${groovy.version}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<!-- Build an executable JAR -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.1.2</version>
<configuration>
<archive>
<manifest>
<mainClass>com.baeldung.App</mainClass>
<addClasspath>true</addClasspath>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>1.7.0</version>
<executions>
<execution>
<goals>
<goal>execute</goal>
<goal>addSources</goal>
<goal>addTestSources</goal>
<goal>generateStubs</goal>
<goal>compile</goal>
<goal>generateTestStubs</goal>
<goal>compileTests</goal>
<goal>removeStubs</goal>
<goal>removeTestStubs</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<!-- any version of Groovy \>= 1.5.0 should work here -->
<version>2.5.6</version>
<scope>runtime</scope>
<type>pom</type>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<!-- Maven Assembly Plugin: needed to run the jar through command line -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<!-- get all project dependencies -->
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<!-- MainClass in mainfest make a executable jar -->
<archive>
<manifest>
<mainClass>com.baeldung.App</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<!-- bind to the packaging phase -->
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -27,6 +27,7 @@
<name>Groovy Bintray</name> <name>Groovy Bintray</name>
<url>https://dl.bintray.com/groovy/maven</url> <url>https://dl.bintray.com/groovy/maven</url>
<releases> <releases>
<!-- avoid automatic updates -->
<updatePolicy>never</updatePolicy> <updatePolicy>never</updatePolicy>
</releases> </releases>
<snapshots> <snapshots>

View File

@ -1,19 +0,0 @@
package com.baeldung
import org.slf4j.LoggerFactory
abstract class CalcScript extends Script {
def log = LoggerFactory.getLogger(this.getClass())
def calcSum(x, y) {
log.info "Executing $x + $y"
x + y
}
def calcSum2(x, y) {
log.info "Executing $x + $y"
// DANGER! This won't throw a compilation issue and fail only at runtime!!!
calcSum3()
log.info("Logging an undefined variable: $z")
}
}

View File

@ -10,6 +10,12 @@ class CalcMath {
x + y x + y
} }
/**
* example of method that in java would throw error at compile time
* @param x
* @param y
* @return
*/
def calcSum2(x, y) { def calcSum2(x, y) {
log.info "Executing $x + $y" log.info "Executing $x + $y"
// DANGER! This won't throw a compilation issue and fail only at runtime!!! // DANGER! This won't throw a compilation issue and fail only at runtime!!!

View File

@ -0,0 +1,10 @@
package com.baeldung
def calcSum(x, y) {
x + y
}
def calcSum2(x, y) {
// DANGER! This won't throw a compilation issue and fail only at runtime!!!
calcSum3()
}

View File

@ -1,12 +1,20 @@
package com.baeldung; package com.baeldung;
import groovy.lang.Binding; import groovy.lang.*;
import groovy.lang.GroovyClassLoader; import groovy.util.GroovyScriptEngine;
import groovy.lang.GroovyShell; import groovy.util.ResourceException;
import groovy.util.ScriptException;
import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.jsr223.GroovyScriptEngineFactory;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.script.Compilable;
import javax.script.ScriptEngine;
import java.io.File;
import java.io.IOException;
import java.net.URL;
/** /**
* Hello world! * Hello world!
* *
@ -15,40 +23,84 @@ public class App {
private final static Logger LOG = LoggerFactory.getLogger(App.class); private final static Logger LOG = LoggerFactory.getLogger(App.class);
private final GroovyClassLoader loader; private final GroovyClassLoader loader;
private final GroovyShell shell; private final GroovyShell shell;
private final GroovyScriptEngine engine;
private App() { private App() throws IOException {
loader = new GroovyClassLoader(this.getClass().getClassLoader()); loader = new GroovyClassLoader(this.getClass().getClassLoader());
CompilerConfiguration config = new CompilerConfiguration(); CompilerConfiguration config = new CompilerConfiguration();
config.setScriptBaseClass("com.baeldung.CalcScript"); config.setScriptBaseClass("com.baeldung.CalcScript");
shell = new GroovyShell(loader, new Binding(), config); shell = new GroovyShell(loader, new Binding(), config);
engine = new GroovyScriptEngine(new URL[] { new File("src/main/groovy/com/baeldung/").toURI().toURL() }, this.getClass().getClassLoader());
} }
private void runScript(int x, int y) { private void runCompiledClasses(int x, int y) {
Object script = shell.parse(String.format("calcSum(%d,%d)", x, y)); Object result1 = new CalcScript().calcSum(x, y);
LOG.info("Result of calcSum() method is {}", result1);
Object result2 = new CalcMath().calcSum(x, y);
LOG.info("Result of calcSum() method is {}", result2);
}
private void runShellScript(int x, int y) {
Script script = shell.parse(String.format("calcSum(%d,%d)", x, y));
assert script instanceof CalcScript; assert script instanceof CalcScript;
Object result = ((CalcScript) script).run(); Object result = script.run();
LOG.info("Result of run() method is {}", result); LOG.info("Result of run() method is {}", result);
Object script2 = shell.parse("CalcScript"); Object script2 = shell.parse("CalcScript");
assert script2 instanceof CalcScript;
Object result2 = ((CalcScript) script2).calcSum(x + 7, y + 7); Object result2 = ((CalcScript) script2).calcSum(x + 7, y + 7);
LOG.info("Result of calcSum() method is {}", result2); LOG.info("Result of calcSum() method is {}", result2);
Script script3 = shell.parse("");
assert script3 instanceof CalcScript;
Object result3 = script3.invokeMethod("calcSum", new Object[] { x + 14, y + 14 });
LOG.info("Result of run() method is {}", result3);
} }
private void runClass(int x, int y) throws ClassNotFoundException, IllegalAccessException, InstantiationException { private void runClassWithLoader(int x, int y) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
Class calcClass = loader.loadClass("com.baeldung.CalcMath"); Class calcClass = loader.loadClass("com.baeldung.CalcMath");
Object calc = calcClass.newInstance(); Object calc = calcClass.newInstance();
assert calc instanceof CalcMath; assert calc instanceof CalcMath;
Object result = ((CalcMath) calc).calcSum(x, y); Object result = ((CalcMath) calc).calcSum(x, y);
LOG.info("Result is {}", result); LOG.info("Result is {}", result);
Object result2 = ((GroovyObject) calc).invokeMethod("calcSum", new Object[] { x + 14, y + 14 });
LOG.info("Result is {}", result2);
} }
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { private void runClassWithEngine(int x, int y) throws ClassNotFoundException, IllegalAccessException, InstantiationException, ResourceException, ScriptException {
Class<GroovyObject> calcClass = engine.loadScriptByName("CalcMath.groovy");
GroovyObject calc = calcClass.newInstance();
Object result = calc.invokeMethod("calcSum", new Object[] { x, y });
//WARNING the following will throw a ClassCastException
//((CalcMath)calc).calcSum(1,2);
LOG.info("Result is {}", result);
}
private void runClassWithEngineFactory(int x, int y) throws ClassNotFoundException, IllegalAccessException, InstantiationException, ResourceException, ScriptException, javax.script.ScriptException {
ScriptEngine engine = new GroovyScriptEngineFactory().getScriptEngine();
Class calcClass = (Class) ((Compilable) engine).compile("com.baeldung.CalcMath").eval();
Object calc = calcClass.newInstance();
Object result = ((CalcMath) calc).calcSum(1, 20);
LOG.info("Result is {}", result);
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, ResourceException, ScriptException, IOException, javax.script.ScriptException {
App app = new App(); App app = new App();
LOG.info("Running an already compiled groovy class instance...");
app.runCompiledClasses(5, 10);
LOG.info("Running a groovy script..."); LOG.info("Running a groovy script...");
app.runScript(5, 10); app.runShellScript(5, 10);
LOG.info("Running a groovy class..."); LOG.info("Running a groovy class...");
app.runClass(1, 3); app.runClassWithLoader(1, 3);
LOG.info("Running a groovy class using the engine...");
app.runClassWithEngine(10, 30);
LOG.info("Running a groovy class using the engine factory...");
app.runClassWithEngineFactory(10, 30);
} }
} }