You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@maven.apache.org by GitBox <gi...@apache.org> on 2022/04/19 18:21:25 UTC
[GitHub] [maven-scripting-plugin] bmarwell commented on a diff in pull request #5: [MSCRIPTING-9] - basic java scripting support
bmarwell commented on code in PR #5:
URL: https://github.com/apache/maven-scripting-plugin/pull/5#discussion_r853357835
##########
README.md:
##########
@@ -65,7 +65,7 @@ There are some guidelines which will make applying PRs easier for us:
Optional supplemental description.
```
+ Make sure you have added the necessary tests (JUnit/IT) for your changes.
-+ Run all the tests with `mvn -Prun-its verify` to assure nothing else was accidentally broken.
++ Run all the tests with `mvn -Prun-its verify` to assure nothing else was accidentally broken (you can need to `mvn install` before).
Review Comment:
```suggestion
+ Run all the tests with `mvn -Prun-its verify` to assure nothing else was accidentally broken (you may need to run `mvn install` beforehand).
```
##########
src/main/java/org/apache/maven/plugins/scripting/engine/JavaEngine.java:
##########
@@ -0,0 +1,327 @@
+package org.apache.maven.plugins.scripting.engine;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import javax.script.AbstractScriptEngine;
+import javax.script.Bindings;
+import javax.script.Compilable;
+import javax.script.CompiledScript;
+import javax.script.ScriptContext;
+import javax.script.ScriptEngine;
+import javax.script.ScriptEngineFactory;
+import javax.script.ScriptException;
+import javax.script.SimpleBindings;
+import javax.tools.JavaCompiler;
+import javax.tools.ToolProvider;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.io.Writer;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.stream.Stream;
+
+import static java.util.Objects.requireNonNull;
+import static java.util.stream.Collectors.joining;
+
+/**
+ * The java engine implementation.
+ */
+public class JavaEngine extends AbstractScriptEngine implements Compilable
+{
+ private final ScriptEngineFactory factory;
+
+ public JavaEngine( ScriptEngineFactory factory )
+ {
+ this.factory = factory;
+ }
+
+ @Override
+ public CompiledScript compile( String script ) throws ScriptException
+ {
+ // plexus compiler is great but overkill there so don't bring it just for that
+ final JavaCompiler compiler = requireNonNull(
+ ToolProvider.getSystemJavaCompiler(),
+ "you must run on a JDK to have a compiler" );
+ Path tmpDir = null;
+ try
+ {
+ tmpDir = Files.createTempDirectory( getClass().getSimpleName() );
+
+ final String packageName = getClass().getPackage().getName() + ".generated";
+ final String className = "JavaCompiledScript_" + Math.abs( script.hashCode() );
+ final String source = toSource( packageName, className, script );
+ final Path src = tmpDir.resolve( "sources" );
+ final Path bin = tmpDir.resolve( "bin" );
+ final Path srcDir = src.resolve( packageName.replace( '.', '/' ) );
+ Files.createDirectories( srcDir );
+ Files.createDirectories( bin );
+ final Path java = srcDir.resolve( className + ".java" );
+ try ( Writer writer = Files.newBufferedWriter( java ) )
+ {
+ writer.write( source );
+ }
+
+ // todo: enable to control it from the project but requires a bit too much config effort for this iteration
+ final String classpath = mavenClasspathPrefix() + System.getProperty( getClass().getName() + ".classpath",
+ System.getProperty( "java.class.path", System.getProperty( "surefire.real.class.path" ) ) );
+
+ // todo: use log, not very important for now so using std streams
Review Comment:
```suggestion
// TODO: use a Logger in subsequent releases. Not very important as of now, so using std streams
```
##########
src/main/java/org/apache/maven/plugins/scripting/engine/JavaEngine.java:
##########
@@ -0,0 +1,327 @@
+package org.apache.maven.plugins.scripting.engine;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import javax.script.AbstractScriptEngine;
+import javax.script.Bindings;
+import javax.script.Compilable;
+import javax.script.CompiledScript;
+import javax.script.ScriptContext;
+import javax.script.ScriptEngine;
+import javax.script.ScriptEngineFactory;
+import javax.script.ScriptException;
+import javax.script.SimpleBindings;
+import javax.tools.JavaCompiler;
+import javax.tools.ToolProvider;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.io.Writer;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.stream.Stream;
+
+import static java.util.Objects.requireNonNull;
+import static java.util.stream.Collectors.joining;
+
+/**
+ * The java engine implementation.
+ */
+public class JavaEngine extends AbstractScriptEngine implements Compilable
+{
+ private final ScriptEngineFactory factory;
+
+ public JavaEngine( ScriptEngineFactory factory )
+ {
+ this.factory = factory;
+ }
+
+ @Override
+ public CompiledScript compile( String script ) throws ScriptException
+ {
+ // plexus compiler is great but overkill there so don't bring it just for that
+ final JavaCompiler compiler = requireNonNull(
+ ToolProvider.getSystemJavaCompiler(),
+ "you must run on a JDK to have a compiler" );
+ Path tmpDir = null;
+ try
+ {
+ tmpDir = Files.createTempDirectory( getClass().getSimpleName() );
+
+ final String packageName = getClass().getPackage().getName() + ".generated";
+ final String className = "JavaCompiledScript_" + Math.abs( script.hashCode() );
+ final String source = toSource( packageName, className, script );
+ final Path src = tmpDir.resolve( "sources" );
+ final Path bin = tmpDir.resolve( "bin" );
+ final Path srcDir = src.resolve( packageName.replace( '.', '/' ) );
+ Files.createDirectories( srcDir );
+ Files.createDirectories( bin );
+ final Path java = srcDir.resolve( className + ".java" );
+ try ( Writer writer = Files.newBufferedWriter( java ) )
+ {
+ writer.write( source );
+ }
+
+ // todo: enable to control it from the project but requires a bit too much config effort for this iteration
Review Comment:
```suggestion
// TODO: make it configurable from the project in subsequent releases
```
##########
src/main/java/org/apache/maven/plugins/scripting/engine/JavaEngine.java:
##########
@@ -0,0 +1,327 @@
+package org.apache.maven.plugins.scripting.engine;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import javax.script.AbstractScriptEngine;
+import javax.script.Bindings;
+import javax.script.Compilable;
+import javax.script.CompiledScript;
+import javax.script.ScriptContext;
+import javax.script.ScriptEngine;
+import javax.script.ScriptEngineFactory;
+import javax.script.ScriptException;
+import javax.script.SimpleBindings;
+import javax.tools.JavaCompiler;
+import javax.tools.ToolProvider;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.io.Writer;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.stream.Stream;
+
+import static java.util.Objects.requireNonNull;
+import static java.util.stream.Collectors.joining;
+
+/**
+ * The java engine implementation.
+ */
+public class JavaEngine extends AbstractScriptEngine implements Compilable
+{
+ private final ScriptEngineFactory factory;
+
+ public JavaEngine( ScriptEngineFactory factory )
+ {
+ this.factory = factory;
+ }
+
+ @Override
+ public CompiledScript compile( String script ) throws ScriptException
+ {
+ // plexus compiler is great but overkill there so don't bring it just for that
+ final JavaCompiler compiler = requireNonNull(
+ ToolProvider.getSystemJavaCompiler(),
+ "you must run on a JDK to have a compiler" );
+ Path tmpDir = null;
+ try
+ {
+ tmpDir = Files.createTempDirectory( getClass().getSimpleName() );
+
+ final String packageName = getClass().getPackage().getName() + ".generated";
+ final String className = "JavaCompiledScript_" + Math.abs( script.hashCode() );
+ final String source = toSource( packageName, className, script );
+ final Path src = tmpDir.resolve( "sources" );
+ final Path bin = tmpDir.resolve( "bin" );
+ final Path srcDir = src.resolve( packageName.replace( '.', '/' ) );
+ Files.createDirectories( srcDir );
+ Files.createDirectories( bin );
+ final Path java = srcDir.resolve( className + ".java" );
+ try ( Writer writer = Files.newBufferedWriter( java ) )
+ {
+ writer.write( source );
+ }
+
+ // todo: enable to control it from the project but requires a bit too much config effort for this iteration
+ final String classpath = mavenClasspathPrefix() + System.getProperty( getClass().getName() + ".classpath",
+ System.getProperty( "java.class.path", System.getProperty( "surefire.real.class.path" ) ) );
+
+ // todo: use log, not very important for now so using std streams
+ final int run = compiler.run( null, System.out, System.err, Stream.of(
+ "-classpath", classpath,
+ "-sourcepath", src.toAbsolutePath().toString(),
+ "-d", bin.toAbsolutePath().toString(),
+ java.toAbsolutePath().toString() )
+ .toArray( String[]::new ) );
+ if ( run != 0 )
+ {
+ throw new IllegalArgumentException(
+ "Can't compile the incoming script, here is the generated code: >\n" + source + "\n<\n" );
+ }
+ final URLClassLoader loader = new URLClassLoader(
+ new URL[]{ bin.toUri().toURL() },
+ Thread.currentThread().getContextClassLoader() );
+ final Class<? extends CompiledScript> loadClass =
+ loader.loadClass( packageName + '.' + className ).asSubclass( CompiledScript.class );
+ return loadClass
+ .getConstructor( ScriptEngine.class, URLClassLoader.class )
+ .newInstance( this, loader );
+ }
+ catch ( Exception e )
+ {
+ throw new ScriptException( e );
+ }
+ finally
+ {
+ if ( tmpDir != null )
+ {
+ try
+ {
+ Files.walkFileTree( tmpDir, new SimpleFileVisitor<Path>()
+ {
+ @Override
+ public FileVisitResult visitFile( Path file, BasicFileAttributes attrs )
+ throws IOException
+ {
+ Files.delete( file );
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ public FileVisitResult postVisitDirectory( Path dir, IOException exc )
+ throws IOException
+ {
+ Files.delete( dir );
+ return FileVisitResult.CONTINUE;
+ }
+
+ } );
+ }
+ catch ( IOException e )
+ {
+ // no-op: todo: throw an exception if not already thrown or add a suppressed
+ }
Review Comment:
Please at least log with a minor log level
##########
src/main/java/org/apache/maven/plugins/scripting/engine/JavaEngine.java:
##########
@@ -0,0 +1,327 @@
+package org.apache.maven.plugins.scripting.engine;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import javax.script.AbstractScriptEngine;
+import javax.script.Bindings;
+import javax.script.Compilable;
+import javax.script.CompiledScript;
+import javax.script.ScriptContext;
+import javax.script.ScriptEngine;
+import javax.script.ScriptEngineFactory;
+import javax.script.ScriptException;
+import javax.script.SimpleBindings;
+import javax.tools.JavaCompiler;
+import javax.tools.ToolProvider;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.io.Writer;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.stream.Stream;
+
+import static java.util.Objects.requireNonNull;
+import static java.util.stream.Collectors.joining;
+
+/**
+ * The java engine implementation.
+ */
+public class JavaEngine extends AbstractScriptEngine implements Compilable
+{
+ private final ScriptEngineFactory factory;
+
+ public JavaEngine( ScriptEngineFactory factory )
+ {
+ this.factory = factory;
+ }
+
+ @Override
+ public CompiledScript compile( String script ) throws ScriptException
+ {
+ // plexus compiler is great but overkill there so don't bring it just for that
+ final JavaCompiler compiler = requireNonNull(
+ ToolProvider.getSystemJavaCompiler(),
+ "you must run on a JDK to have a compiler" );
+ Path tmpDir = null;
+ try
+ {
+ tmpDir = Files.createTempDirectory( getClass().getSimpleName() );
+
+ final String packageName = getClass().getPackage().getName() + ".generated";
+ final String className = "JavaCompiledScript_" + Math.abs( script.hashCode() );
+ final String source = toSource( packageName, className, script );
+ final Path src = tmpDir.resolve( "sources" );
+ final Path bin = tmpDir.resolve( "bin" );
+ final Path srcDir = src.resolve( packageName.replace( '.', '/' ) );
+ Files.createDirectories( srcDir );
+ Files.createDirectories( bin );
+ final Path java = srcDir.resolve( className + ".java" );
+ try ( Writer writer = Files.newBufferedWriter( java ) )
+ {
+ writer.write( source );
+ }
+
+ // todo: enable to control it from the project but requires a bit too much config effort for this iteration
+ final String classpath = mavenClasspathPrefix() + System.getProperty( getClass().getName() + ".classpath",
+ System.getProperty( "java.class.path", System.getProperty( "surefire.real.class.path" ) ) );
+
+ // todo: use log, not very important for now so using std streams
+ final int run = compiler.run( null, System.out, System.err, Stream.of(
+ "-classpath", classpath,
+ "-sourcepath", src.toAbsolutePath().toString(),
+ "-d", bin.toAbsolutePath().toString(),
+ java.toAbsolutePath().toString() )
+ .toArray( String[]::new ) );
+ if ( run != 0 )
+ {
+ throw new IllegalArgumentException(
+ "Can't compile the incoming script, here is the generated code: >\n" + source + "\n<\n" );
+ }
+ final URLClassLoader loader = new URLClassLoader(
+ new URL[]{ bin.toUri().toURL() },
+ Thread.currentThread().getContextClassLoader() );
+ final Class<? extends CompiledScript> loadClass =
+ loader.loadClass( packageName + '.' + className ).asSubclass( CompiledScript.class );
+ return loadClass
+ .getConstructor( ScriptEngine.class, URLClassLoader.class )
+ .newInstance( this, loader );
+ }
+ catch ( Exception e )
+ {
+ throw new ScriptException( e );
+ }
+ finally
+ {
+ if ( tmpDir != null )
+ {
+ try
+ {
+ Files.walkFileTree( tmpDir, new SimpleFileVisitor<Path>()
+ {
+ @Override
+ public FileVisitResult visitFile( Path file, BasicFileAttributes attrs )
+ throws IOException
+ {
+ Files.delete( file );
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ public FileVisitResult postVisitDirectory( Path dir, IOException exc )
+ throws IOException
+ {
+ Files.delete( dir );
+ return FileVisitResult.CONTINUE;
+ }
+
+ } );
+ }
+ catch ( IOException e )
+ {
+ // no-op: todo: throw an exception if not already thrown or add a suppressed
+ }
+ }
+ }
+ }
+
+ private String mavenClasspathPrefix()
+ {
+ final String home = System.getProperty( "maven.home" );
+ if ( home == null )
+ {
+ return "";
+ }
+ try ( Stream<Path> files = Files.list( Paths.get( home ).resolve( "lib" ) ) )
+ {
+ return files
+ .filter( it ->
+ {
+ final String name = it.getFileName().toString();
+ return name.startsWith( "maven-" );
+ } )
+ .map( Path::toString )
+ .collect( joining( File.pathSeparator, "", File.pathSeparator ) );
+ }
+ catch ( IOException e )
+ {
+ return "";
+ }
Review Comment:
Please at least log the exception with a minor log level
##########
README.md:
##########
@@ -65,7 +65,7 @@ There are some guidelines which will make applying PRs easier for us:
Optional supplemental description.
```
+ Make sure you have added the necessary tests (JUnit/IT) for your changes.
-+ Run all the tests with `mvn -Prun-its verify` to assure nothing else was accidentally broken.
++ Run all the tests with `mvn -Prun-its verify` to assure nothing else was accidentally broken (you can need to `mvn install` before).
Review Comment:
Hint: It should *never* need an `install`!
##########
src/main/java/org/apache/maven/plugins/scripting/engine/JavaEngine.java:
##########
@@ -0,0 +1,327 @@
+package org.apache.maven.plugins.scripting.engine;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import javax.script.AbstractScriptEngine;
+import javax.script.Bindings;
+import javax.script.Compilable;
+import javax.script.CompiledScript;
+import javax.script.ScriptContext;
+import javax.script.ScriptEngine;
+import javax.script.ScriptEngineFactory;
+import javax.script.ScriptException;
+import javax.script.SimpleBindings;
+import javax.tools.JavaCompiler;
+import javax.tools.ToolProvider;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.io.Writer;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.stream.Stream;
+
+import static java.util.Objects.requireNonNull;
+import static java.util.stream.Collectors.joining;
+
+/**
+ * The java engine implementation.
+ */
+public class JavaEngine extends AbstractScriptEngine implements Compilable
+{
+ private final ScriptEngineFactory factory;
+
+ public JavaEngine( ScriptEngineFactory factory )
+ {
+ this.factory = factory;
+ }
+
+ @Override
+ public CompiledScript compile( String script ) throws ScriptException
+ {
+ // plexus compiler is great but overkill there so don't bring it just for that
+ final JavaCompiler compiler = requireNonNull(
+ ToolProvider.getSystemJavaCompiler(),
+ "you must run on a JDK to have a compiler" );
+ Path tmpDir = null;
+ try
+ {
+ tmpDir = Files.createTempDirectory( getClass().getSimpleName() );
+
+ final String packageName = getClass().getPackage().getName() + ".generated";
+ final String className = "JavaCompiledScript_" + Math.abs( script.hashCode() );
+ final String source = toSource( packageName, className, script );
+ final Path src = tmpDir.resolve( "sources" );
+ final Path bin = tmpDir.resolve( "bin" );
+ final Path srcDir = src.resolve( packageName.replace( '.', '/' ) );
+ Files.createDirectories( srcDir );
+ Files.createDirectories( bin );
+ final Path java = srcDir.resolve( className + ".java" );
+ try ( Writer writer = Files.newBufferedWriter( java ) )
+ {
+ writer.write( source );
+ }
+
+ // todo: enable to control it from the project but requires a bit too much config effort for this iteration
+ final String classpath = mavenClasspathPrefix() + System.getProperty( getClass().getName() + ".classpath",
+ System.getProperty( "java.class.path", System.getProperty( "surefire.real.class.path" ) ) );
+
+ // todo: use log, not very important for now so using std streams
+ final int run = compiler.run( null, System.out, System.err, Stream.of(
+ "-classpath", classpath,
+ "-sourcepath", src.toAbsolutePath().toString(),
+ "-d", bin.toAbsolutePath().toString(),
+ java.toAbsolutePath().toString() )
+ .toArray( String[]::new ) );
+ if ( run != 0 )
+ {
+ throw new IllegalArgumentException(
+ "Can't compile the incoming script, here is the generated code: >\n" + source + "\n<\n" );
+ }
+ final URLClassLoader loader = new URLClassLoader(
+ new URL[]{ bin.toUri().toURL() },
+ Thread.currentThread().getContextClassLoader() );
+ final Class<? extends CompiledScript> loadClass =
+ loader.loadClass( packageName + '.' + className ).asSubclass( CompiledScript.class );
+ return loadClass
+ .getConstructor( ScriptEngine.class, URLClassLoader.class )
+ .newInstance( this, loader );
+ }
+ catch ( Exception e )
+ {
+ throw new ScriptException( e );
+ }
+ finally
+ {
+ if ( tmpDir != null )
+ {
+ try
+ {
+ Files.walkFileTree( tmpDir, new SimpleFileVisitor<Path>()
+ {
+ @Override
+ public FileVisitResult visitFile( Path file, BasicFileAttributes attrs )
+ throws IOException
+ {
+ Files.delete( file );
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ public FileVisitResult postVisitDirectory( Path dir, IOException exc )
+ throws IOException
+ {
+ Files.delete( dir );
+ return FileVisitResult.CONTINUE;
+ }
+
+ } );
+ }
+ catch ( IOException e )
+ {
+ // no-op: todo: throw an exception if not already thrown or add a suppressed
+ }
+ }
+ }
+ }
+
+ private String mavenClasspathPrefix()
+ {
+ final String home = System.getProperty( "maven.home" );
+ if ( home == null )
+ {
+ return "";
+ }
+ try ( Stream<Path> files = Files.list( Paths.get( home ).resolve( "lib" ) ) )
+ {
+ return files
+ .filter( it ->
+ {
+ final String name = it.getFileName().toString();
+ return name.startsWith( "maven-" );
+ } )
+ .map( Path::toString )
+ .collect( joining( File.pathSeparator, "", File.pathSeparator ) );
+ }
+ catch ( IOException e )
+ {
+ return "";
+ }
+ }
+
+ private String toSource( String pck, String name, String script )
+ {
+ final String[] importsAndScript = splitImportsAndScript( script );
+ return "package " + pck + ";\n"
+ + "\n"
+ + "import java.io.*;\n"
+ + "import java.net.*;\n"
+ + "import java.util.*;\n"
+ + "import java.util.stream.*;\n"
+ + "import java.nio.file.*;\n"
+ + "import org.apache.maven.project.MavenProject;\n"
+ + "import org.apache.maven.plugin.logging.Log;\n"
+ + "\n"
+ + "import javax.script.Bindings;\n"
+ + "import javax.script.CompiledScript;\n"
+ + "import javax.script.ScriptContext;\n"
+ + "import javax.script.ScriptEngine;\n"
+ + "import javax.script.ScriptException;\n"
+ + "\n"
+ + importsAndScript[0] + '\n'
+ + "\n"
+ + "public class " + name + " extends CompiledScript implements AutoCloseable {\n"
+ + " private final ScriptEngine $engine;\n"
+ + " private final URLClassLoader $loader;\n"
+ + "\n"
+ + " public " + name + "( ScriptEngine engine, URLClassLoader loader) {\n"
+ + " this.$engine = engine;\n"
+ + " this.$loader = loader;\n"
+ + " }\n"
+ + "\n"
+ + " @Override\n"
+ + " public Object eval( ScriptContext $context) throws ScriptException {\n"
+ + " final Thread $thread = Thread.currentThread();\n"
+ + " final ClassLoader $oldClassLoader = $thread.getContextClassLoader();\n"
+ + " $thread.setContextClassLoader($loader);\n"
+ + " try {\n"
+ + " final Bindings $bindings = $context.getBindings(ScriptContext.GLOBAL_SCOPE);\n"
+ + " final MavenProject $project = MavenProject.class.cast($bindings.get(\"project\"));\n"
+ + " final Log $log = Log.class.cast($bindings.get(\"log\"));\n"
+ + " " + importsAndScript[1] + "\n"
+ + " return null;\n" // assume the script doesn't return anything for now
+ + " } catch ( Exception e) {\n"
+ + " if (RuntimeException.class.isInstance(e)) {\n"
+ + " throw RuntimeException.class.cast(e);\n"
+ + " }\n"
+ + " throw new IllegalStateException(e);\n"
+ + " } finally {\n"
+ + " $thread.setContextClassLoader($oldClassLoader);\n"
+ + " }\n"
+ + " }\n"
+ + "\n"
+ + " @Override\n"
+ + " public ScriptEngine getEngine() {\n"
+ + " return $engine;\n"
+ + " }\n"
+ + "\n"
+ + " @Override\n"
+ + " public void close() throws Exception {\n"
+ + " $loader.close();\n"
+ + " }\n"
+ + "}";
Review Comment:
Does it make sense to extract it to a resource to make it a bit more maintainable?
##########
src/main/java/org/apache/maven/plugins/scripting/engine/JavaEngine.java:
##########
@@ -0,0 +1,327 @@
+package org.apache.maven.plugins.scripting.engine;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import javax.script.AbstractScriptEngine;
+import javax.script.Bindings;
+import javax.script.Compilable;
+import javax.script.CompiledScript;
+import javax.script.ScriptContext;
+import javax.script.ScriptEngine;
+import javax.script.ScriptEngineFactory;
+import javax.script.ScriptException;
+import javax.script.SimpleBindings;
+import javax.tools.JavaCompiler;
+import javax.tools.ToolProvider;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.io.Writer;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.stream.Stream;
+
+import static java.util.Objects.requireNonNull;
+import static java.util.stream.Collectors.joining;
+
+/**
+ * The java engine implementation.
+ */
+public class JavaEngine extends AbstractScriptEngine implements Compilable
+{
+ private final ScriptEngineFactory factory;
+
+ public JavaEngine( ScriptEngineFactory factory )
+ {
+ this.factory = factory;
+ }
+
+ @Override
+ public CompiledScript compile( String script ) throws ScriptException
+ {
+ // plexus compiler is great but overkill there so don't bring it just for that
+ final JavaCompiler compiler = requireNonNull(
+ ToolProvider.getSystemJavaCompiler(),
+ "you must run on a JDK to have a compiler" );
+ Path tmpDir = null;
+ try
+ {
+ tmpDir = Files.createTempDirectory( getClass().getSimpleName() );
+
+ final String packageName = getClass().getPackage().getName() + ".generated";
+ final String className = "JavaCompiledScript_" + Math.abs( script.hashCode() );
+ final String source = toSource( packageName, className, script );
+ final Path src = tmpDir.resolve( "sources" );
+ final Path bin = tmpDir.resolve( "bin" );
+ final Path srcDir = src.resolve( packageName.replace( '.', '/' ) );
+ Files.createDirectories( srcDir );
+ Files.createDirectories( bin );
+ final Path java = srcDir.resolve( className + ".java" );
+ try ( Writer writer = Files.newBufferedWriter( java ) )
+ {
+ writer.write( source );
+ }
+
+ // todo: enable to control it from the project but requires a bit too much config effort for this iteration
+ final String classpath = mavenClasspathPrefix() + System.getProperty( getClass().getName() + ".classpath",
+ System.getProperty( "java.class.path", System.getProperty( "surefire.real.class.path" ) ) );
+
+ // todo: use log, not very important for now so using std streams
+ final int run = compiler.run( null, System.out, System.err, Stream.of(
+ "-classpath", classpath,
+ "-sourcepath", src.toAbsolutePath().toString(),
+ "-d", bin.toAbsolutePath().toString(),
+ java.toAbsolutePath().toString() )
+ .toArray( String[]::new ) );
+ if ( run != 0 )
+ {
+ throw new IllegalArgumentException(
+ "Can't compile the incoming script, here is the generated code: >\n" + source + "\n<\n" );
+ }
+ final URLClassLoader loader = new URLClassLoader(
+ new URL[]{ bin.toUri().toURL() },
+ Thread.currentThread().getContextClassLoader() );
+ final Class<? extends CompiledScript> loadClass =
+ loader.loadClass( packageName + '.' + className ).asSubclass( CompiledScript.class );
+ return loadClass
+ .getConstructor( ScriptEngine.class, URLClassLoader.class )
+ .newInstance( this, loader );
+ }
+ catch ( Exception e )
+ {
+ throw new ScriptException( e );
+ }
+ finally
+ {
+ if ( tmpDir != null )
+ {
+ try
+ {
+ Files.walkFileTree( tmpDir, new SimpleFileVisitor<Path>()
+ {
+ @Override
+ public FileVisitResult visitFile( Path file, BasicFileAttributes attrs )
+ throws IOException
+ {
+ Files.delete( file );
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ public FileVisitResult postVisitDirectory( Path dir, IOException exc )
+ throws IOException
+ {
+ Files.delete( dir );
+ return FileVisitResult.CONTINUE;
+ }
+
+ } );
Review Comment:
Please extract into a static field or method.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org