You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maven.apache.org by bm...@apache.org on 2024/03/02 22:43:09 UTC

(maven-scripting-plugin) 01/07: [MSCRIPTING-9] - basic java scripting support

This is an automated email from the ASF dual-hosted git repository.

bmarwell pushed a commit to branch support-java-scripting
in repository https://gitbox.apache.org/repos/asf/maven-scripting-plugin.git

commit c85c032b24753a4ffd3cd988a2a84db183a58d57
Author: Romain Manni-Bucau <rm...@gmail.com>
AuthorDate: Tue Apr 19 20:07:11 2022 +0200

    [MSCRIPTING-9] - basic java scripting support
---
 README.md                                          |   2 +-
 src/it/projects/java-script/pom.xml                |  48 +++
 src/it/projects/java-script/verify.bsh             |  26 ++
 .../maven/plugins/scripting/engine/JavaEngine.java | 327 +++++++++++++++++++++
 .../scripting/engine/JavaEngineFactory.java        | 127 ++++++++
 .../services/javax.script.ScriptEngineFactory      |  19 ++
 .../plugins/scripting/engine/JavaEngineTest.java   |  38 +++
 7 files changed, 586 insertions(+), 1 deletion(-)

diff --git a/README.md b/README.md
index ee94865..d714bd4 100644
--- a/README.md
+++ b/README.md
@@ -66,7 +66,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).
 + Submit a pull request to the repository in the Apache organization.
 + Update your JIRA ticket and include a link to the pull request in the ticket.
 
diff --git a/src/it/projects/java-script/pom.xml b/src/it/projects/java-script/pom.xml
new file mode 100644
index 0000000..ae202ee
--- /dev/null
+++ b/src/it/projects/java-script/pom.xml
@@ -0,0 +1,48 @@
+<?xml version='1.0' encoding='UTF-8'?>
+
+<!--
+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.
+-->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+
+  <groupId>org.apache.maven.plugins.scripting.its</groupId>
+  <artifactId>java-script</artifactId>
+  <version>1.0.0-SNAPSHOT</version>
+  <packaging>pom</packaging>
+  
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-scripting-plugin</artifactId>
+        <version>@project.version@</version>
+        <configuration>
+          <engineName>Maven-Scripting-Java-Engine</engineName>
+          <script>
+          <![CDATA[
+            // will print "87java-script" in the logs
+            $log.info(IntStream.rangeClosed(1, 10).sum() + ' ' + $project.getArtifactId());
+          ]]>
+          </script>
+        </configuration>
+      </plugin>
+    </plugins>
+  </build>
+</project>
diff --git a/src/it/projects/java-script/verify.bsh b/src/it/projects/java-script/verify.bsh
new file mode 100644
index 0000000..0124f7a
--- /dev/null
+++ b/src/it/projects/java-script/verify.bsh
@@ -0,0 +1,26 @@
+import java.io.*;
+import java.nio.file.*;
+
+/*
+ * 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.
+ */
+
+File file = new File( basedir, "build.log" );
+if ( ! new String( Files.readAllBytes( file.toPath() ) ).contains( "87java-script" ) ) {
+    throw new IllegalArgumentException( "invalid output" );
+}
diff --git a/src/main/java/org/apache/maven/plugins/scripting/engine/JavaEngine.java b/src/main/java/org/apache/maven/plugins/scripting/engine/JavaEngine.java
new file mode 100644
index 0000000..e0021e4
--- /dev/null
+++ b/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"
+                + "}";
+    }
+
+    private String[] splitImportsAndScript( String script )
+    {
+        final StringBuilder imports = new StringBuilder();
+        final StringBuilder content = new StringBuilder();
+        boolean useImport = true;
+        boolean inComment = false;
+        try ( BufferedReader reader = new BufferedReader( new StringReader( script ) ) )
+        {
+            String line;
+            while ( ( line = reader.readLine() ) != null )
+            {
+                if ( useImport )
+                {
+                    String trimmed = line.trim();
+                    if ( trimmed.isEmpty() )
+                    {
+                        continue;
+                    }
+                    if ( trimmed.startsWith( "/*" ) )
+                    {
+                        inComment = true;
+                        continue;
+                    }
+                    if ( trimmed.endsWith( "*/" ) && inComment )
+                    {
+                        inComment = false;
+                        continue;
+                    }
+                    if ( inComment )
+                    {
+                        continue;
+                    }
+                    if ( trimmed.startsWith( "import " ) && trimmed.endsWith( ";" ) )
+                    {
+                        imports.append( line ).append( '\n' );
+                        continue;
+                    }
+                    useImport = false;
+                }
+                content.append( line ).append( '\n' );
+            }
+        }
+        catch ( IOException ioe )
+        {
+            throw new IllegalStateException( ioe );
+        }
+        return new String[]
+        {
+                imports.toString().trim(),
+                content.toString().trim()
+        };
+    }
+
+    @Override
+    public Object eval( String script, ScriptContext context ) throws ScriptException
+    {
+        return compile( script ).eval( context );
+    }
+
+    @Override
+    public Object eval( Reader reader, ScriptContext context ) throws ScriptException
+    {
+        return eval( load( reader ), context );
+    }
+
+    @Override
+    public CompiledScript compile( Reader script ) throws ScriptException
+    {
+        return compile( load( script ) );
+    }
+
+    @Override
+    public Bindings createBindings()
+    {
+        return new SimpleBindings();
+    }
+
+    @Override
+    public ScriptEngineFactory getFactory()
+    {
+        return factory;
+    }
+
+    private String load( Reader reader )
+    {
+        return new BufferedReader( reader ).lines().collect( joining( "\n" ) );
+    }
+}
diff --git a/src/main/java/org/apache/maven/plugins/scripting/engine/JavaEngineFactory.java b/src/main/java/org/apache/maven/plugins/scripting/engine/JavaEngineFactory.java
new file mode 100644
index 0000000..7e2a3f7
--- /dev/null
+++ b/src/main/java/org/apache/maven/plugins/scripting/engine/JavaEngineFactory.java
@@ -0,0 +1,127 @@
+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.ScriptEngine;
+import javax.script.ScriptEngineFactory;
+import java.util.List;
+import java.util.stream.Stream;
+
+import static java.util.Collections.singletonList;
+import static java.util.stream.Collectors.joining;
+import static java.util.stream.Collectors.toList;
+
+/**
+ * A java engine factory to be able to script in plain java in the build.
+ */
+public class JavaEngineFactory implements ScriptEngineFactory
+{
+    @Override
+    public String getEngineName()
+    {
+        return "Maven-Scripting-Java-Engine";
+    }
+
+    @Override
+    public String getEngineVersion()
+    {
+        return "1.0";
+    }
+
+    @Override
+    public List<String> getExtensions()
+    {
+        return singletonList( "java" );
+    }
+
+    @Override
+    public List<String> getMimeTypes()
+    {
+        return singletonList( "application/java" );
+    }
+
+    @Override
+    public List<String> getNames()
+    {
+        return Stream.concat(
+                        Stream.concat( getMimeTypes().stream(), getExtensions().stream() ),
+                        Stream.of( getEngineName(), getLanguageName() ) )
+                .distinct()
+                .collect( toList() );
+    }
+
+    @Override
+    public String getLanguageName()
+    {
+        return "java";
+    }
+
+    @Override
+    public String getLanguageVersion()
+    {
+        return System.getProperty( "java.version", "8" );
+    }
+
+    @Override
+    public Object getParameter( String key )
+    {
+        if ( key.equals( "javax.script.engine_version" ) )
+        {
+            return getEngineVersion();
+        }
+        if ( key.equals( "javax.script.engine" ) )
+        {
+            return getEngineName();
+        }
+        if ( key.equals( "javax.script.language" ) )
+        {
+            return getLanguageName();
+        }
+        if ( key.equals( "javax.script.language_version" ) )
+        {
+            return getLanguageVersion();
+        }
+        return null;
+    }
+
+    @Override
+    public String getMethodCallSyntax( String obj, String m, String... args )
+    {
+        return obj + "." + m + '(' + ( args == null ? "" : String.join( ", ", args ) ) + ')';
+    }
+
+    @Override
+    public String getOutputStatement( String toDisplay )
+    {
+        return "System.out.println(" + toDisplay + ")";
+    }
+
+    @Override
+    public String getProgram( String... statements )
+    {
+        return Stream.of( statements ).collect( joining( ";", "", ";"  ) );
+    }
+
+    @Override
+    public ScriptEngine getScriptEngine()
+    {
+        return new JavaEngine( this );
+    }
+}
diff --git a/src/main/resources/META-INF/services/javax.script.ScriptEngineFactory b/src/main/resources/META-INF/services/javax.script.ScriptEngineFactory
new file mode 100644
index 0000000..d4209f2
--- /dev/null
+++ b/src/main/resources/META-INF/services/javax.script.ScriptEngineFactory
@@ -0,0 +1,19 @@
+#
+#  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.
+#
+org.apache.maven.plugins.scripting.engine.JavaEngineFactory
diff --git a/src/test/java/org/apache/maven/plugins/scripting/engine/JavaEngineTest.java b/src/test/java/org/apache/maven/plugins/scripting/engine/JavaEngineTest.java
new file mode 100644
index 0000000..026d3de
--- /dev/null
+++ b/src/test/java/org/apache/maven/plugins/scripting/engine/JavaEngineTest.java
@@ -0,0 +1,38 @@
+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 org.junit.Test;
+
+import javax.script.ScriptEngineManager;
+import javax.script.ScriptException;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+public class JavaEngineTest {
+    @Test
+    public void run() throws ScriptException {
+        assertNull(System.getProperty("JavaEngineTest.run"));
+        new ScriptEngineManager().getEngineByExtension("java").eval("System.setProperty(\"JavaEngineTest.run\",\"yes\");");
+        assertEquals("yes", System.getProperty("JavaEngineTest.run"));
+        System.clearProperty("JavaEngineTest.run");
+    }
+}