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:08:42 UTC

[GitHub] [maven-scripting-plugin] rmannibucau opened a new pull request, #5: [MSCRIPTING-9] - basic java scripting support

rmannibucau opened a new pull request, #5:
URL: https://github.com/apache/maven-scripting-plugin/pull/5

   Following this checklist to help us incorporate your 
   contribution quickly and easily:
   
    - [X] Make sure there is a [JIRA issue](https://issues.apache.org/jira/browse/MSCRIPTING) filed 
          for the change (usually before you start working on it).  Trivial changes like typos do not 
          require a JIRA issue.  Your pull request should address just this issue, without 
          pulling in other changes.
    - [X] Each commit in the pull request should have a meaningful subject line and body.
    - [X] Format the pull request title like `[MSCRIPTING-XXX] - Fixes bug in ApproximateQuantiles`,
          where you replace `MSCRIPTING-XXX` with the appropriate JIRA issue. Best practice
          is to use the JIRA issue title in the pull request title and in the first line of the 
          commit message.
    - [X] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
    - [X] Run `mvn clean verify` to make sure basic checks pass. A more thorough check will 
          be performed on your pull request automatically.
    - [X] You have run the integration tests successfully (`mvn -Prun-its clean verify`).
   
   If your pull request is about ~20 lines of code you don't need to sign an
   [Individual Contributor License Agreement](https://www.apache.org/licenses/icla.pdf) if you are unsure
   please ask on the developers list.
   
   To make clear that you license your contribution under 
   the [Apache License Version 2.0, January 2004](http://www.apache.org/licenses/LICENSE-2.0)
   you have to acknowledge this by using the following check-box.
   
    - [ ] I hereby declare this contribution to be licenced under the [Apache License Version 2.0, January 2004](http://www.apache.org/licenses/LICENSE-2.0)
   
    - [ ] In any other case, please file an [Apache Individual Contributor License Agreement](https://www.apache.org/licenses/icla.pdf).
   
   description: the goal is to be able to script - as with any jsr223 impl - in plain java
   
   


-- 
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


[GitHub] [maven-scripting-plugin] rmannibucau commented on pull request #5: [MSCRIPTING-9] - basic java scripting support

Posted by GitBox <gi...@apache.org>.
rmannibucau commented on PR #5:
URL: https://github.com/apache/maven-scripting-plugin/pull/5#issuecomment-1344282710

   Anything pending on this one? (just trying to see if we should try to move it forward or not)


-- 
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


Re: [PR] [MSCRIPTING-9] - basic java scripting support [maven-scripting-plugin]

Posted by "bmarwell (via GitHub)" <gi...@apache.org>.
bmarwell commented on PR #5:
URL: https://github.com/apache/maven-scripting-plugin/pull/5#issuecomment-1974930702

   Rebased and superseded by https://github.com/apache/maven-scripting-plugin/pull/25


-- 
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


[GitHub] [maven-scripting-plugin] rmannibucau commented on a diff in pull request #5: [MSCRIPTING-9] - basic java scripting support

Posted by GitBox <gi...@apache.org>.
rmannibucau commented on code in PR #5:
URL: https://github.com/apache/maven-scripting-plugin/pull/5#discussion_r853389952


##########
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:
   don't think so, would require to use some templating or replace so since it is not that big and will likely not be x10 I think it is a good compromise



-- 
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


Re: [PR] [MSCRIPTING-9] - basic java scripting support [maven-scripting-plugin]

Posted by "bmarwell (via GitHub)" <gi...@apache.org>.
bmarwell closed pull request #5: [MSCRIPTING-9] - basic java scripting support
URL: https://github.com/apache/maven-scripting-plugin/pull/5


-- 
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


[GitHub] [maven-scripting-plugin] rmannibucau commented on a diff in pull request #5: [MSCRIPTING-9] - basic java scripting support

Posted by GitBox <gi...@apache.org>.
rmannibucau commented on code in PR #5:
URL: https://github.com/apache/maven-scripting-plugin/pull/5#discussion_r853389337


##########
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:
   done



##########
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:
   done



-- 
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


[GitHub] [maven-scripting-plugin] slachiewicz commented on pull request #5: [MSCRIPTING-9] - basic java scripting support

Posted by GitBox <gi...@apache.org>.
slachiewicz commented on PR #5:
URL: https://github.com/apache/maven-scripting-plugin/pull/5#issuecomment-1346623345

   would be good to add documentation to jsr223-script-engines.md.vm


-- 
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


[GitHub] [maven-scripting-plugin] rmannibucau commented on a diff in pull request #5: [MSCRIPTING-9] - basic java scripting support

Posted by GitBox <gi...@apache.org>.
rmannibucau commented on code in PR #5:
URL: https://github.com/apache/maven-scripting-plugin/pull/5#discussion_r853390470


##########
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:
   @bmarwell well I will not enter into the debate but this is not my change but the way the project was setup, invoker+mrm config does not seem to work reliably without an install so added the comment.



-- 
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


[GitHub] [maven-scripting-plugin] bmarwell commented on a diff in pull request #5: [MSCRIPTING-9] - basic java scripting support

Posted by GitBox <gi...@apache.org>.
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


[GitHub] [maven-scripting-plugin] bmarwell commented on pull request #5: [MSCRIPTING-9] - basic java scripting support

Posted by GitBox <gi...@apache.org>.
bmarwell commented on PR #5:
URL: https://github.com/apache/maven-scripting-plugin/pull/5#issuecomment-1346793735

   We should get rid of Travis-CI. In fact, we HAVE to.


-- 
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


[GitHub] [maven-scripting-plugin] rmannibucau commented on pull request #5: [MSCRIPTING-9] - basic java scripting support

Posted by GitBox <gi...@apache.org>.
rmannibucau commented on PR #5:
URL: https://github.com/apache/maven-scripting-plugin/pull/5#issuecomment-1102980200

   Fixed all review comments (cc @bmarwell )


-- 
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


[GitHub] [maven-scripting-plugin] bmarwell commented on a diff in pull request #5: [MSCRIPTING-9] - basic java scripting support

Posted by GitBox <gi...@apache.org>.
bmarwell commented on code in PR #5:
URL: https://github.com/apache/maven-scripting-plugin/pull/5#discussion_r853402558


##########
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 may need to run `mvn install` beforehand).

Review Comment:
   Review hint: This was not introduced by @rmannibucau’s change, mrm+invoker was already broken before.



-- 
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