Author: rmannibucau
Date: Mon Apr 24 22:41:56 2017
New Revision: 1792555

URL: http://svn.apache.org/viewvc?rev=1792555&view=rev
Log:
MEECROWAVE-27 basic bundle command

Added:
    
openwebbeans/meecrowave/trunk/meecrowave-maven-plugin/src/main/java/org/apache/meecrowave/maven/MeecrowaveBundleMojo.java
      - copied, changed from r1792043, 
openwebbeans/meecrowave/trunk/meecrowave-maven-plugin/src/main/java/org/apache/meecrowave/maven/MeecrowaveRunMojo.java
    
openwebbeans/meecrowave/trunk/meecrowave-maven-plugin/src/main/resources/bin/
    
openwebbeans/meecrowave/trunk/meecrowave-maven-plugin/src/main/resources/bin/meecrowave.sh
Modified:
    openwebbeans/meecrowave/trunk/meecrowave-core/pom.xml
    
openwebbeans/meecrowave/trunk/meecrowave-core/src/main/java/org/apache/meecrowave/openwebbeans/OWBTomcatWebScannerService.java
    openwebbeans/meecrowave/trunk/meecrowave-maven-plugin/pom.xml

Modified: openwebbeans/meecrowave/trunk/meecrowave-core/pom.xml
URL: 
http://svn.apache.org/viewvc/openwebbeans/meecrowave/trunk/meecrowave-core/pom.xml?rev=1792555&r1=1792554&r2=1792555&view=diff
==============================================================================
--- openwebbeans/meecrowave/trunk/meecrowave-core/pom.xml (original)
+++ openwebbeans/meecrowave/trunk/meecrowave-core/pom.xml Mon Apr 24 22:41:56 
2017
@@ -69,7 +69,6 @@
       <artifactId>tomcat-jaspic-api</artifactId>
       <version>${tomcat.version}</version>
     </dependency>
-
     <dependency>
       <groupId>commons-cli</groupId>
       <artifactId>commons-cli</artifactId>

Modified: 
openwebbeans/meecrowave/trunk/meecrowave-core/src/main/java/org/apache/meecrowave/openwebbeans/OWBTomcatWebScannerService.java
URL: 
http://svn.apache.org/viewvc/openwebbeans/meecrowave/trunk/meecrowave-core/src/main/java/org/apache/meecrowave/openwebbeans/OWBTomcatWebScannerService.java?rev=1792555&r1=1792554&r2=1792555&view=diff
==============================================================================
--- 
openwebbeans/meecrowave/trunk/meecrowave-core/src/main/java/org/apache/meecrowave/openwebbeans/OWBTomcatWebScannerService.java
 (original)
+++ 
openwebbeans/meecrowave/trunk/meecrowave-core/src/main/java/org/apache/meecrowave/openwebbeans/OWBTomcatWebScannerService.java
 Mon Apr 24 22:41:56 2017
@@ -74,6 +74,8 @@ public class OWBTomcatWebScannerService
             final String m2 = new File(System.getProperty("user.home", "."), 
".m2/repository").getAbsolutePath();
             final String base = ofNullable(docBase).orElse("$$$");
             final String sharedBase = ofNullable(shared).orElse("$$$");
+            final String runnerBase = 
ofNullable(System.getProperty("meecrowave.base")).orElse("$$$");
+            final String runnerHome = 
ofNullable(System.getProperty("meecrowave.home")).orElse("$$$");
             urls.stream().map(u -> {
                 String shownValue = u
                         // protocol
@@ -93,6 +95,10 @@ public class OWBTomcatWebScannerService
                     shownValue = "${app}" + shownValue.replace(base, "");
                 } else if (shownValue.startsWith(sharedBase)) {
                     shownValue = "${shared}" + shownValue.replace(sharedBase, 
"");
+                } else if (shownValue.startsWith(runnerBase)) {
+                    shownValue = "${base}" + shownValue.replace(runnerBase, 
"");
+                } else if (shownValue.startsWith(runnerHome)) {
+                    shownValue = "${home}" + shownValue.replace(runnerHome, 
"");
                 }
 
                 return shownValue;

Modified: openwebbeans/meecrowave/trunk/meecrowave-maven-plugin/pom.xml
URL: 
http://svn.apache.org/viewvc/openwebbeans/meecrowave/trunk/meecrowave-maven-plugin/pom.xml?rev=1792555&r1=1792554&r2=1792555&view=diff
==============================================================================
--- openwebbeans/meecrowave/trunk/meecrowave-maven-plugin/pom.xml (original)
+++ openwebbeans/meecrowave/trunk/meecrowave-maven-plugin/pom.xml Mon Apr 24 
22:41:56 2017
@@ -67,6 +67,11 @@
       <artifactId>meecrowave-core</artifactId>
       <version>${project.version}</version>
     </dependency>
+    <dependency>
+      <groupId>org.apache.commons</groupId>
+      <artifactId>commons-compress</artifactId>
+      <version>1.11</version>
+    </dependency>
 
     <dependency>
       <groupId>org.apache.maven.plugin-testing</groupId>

Copied: 
openwebbeans/meecrowave/trunk/meecrowave-maven-plugin/src/main/java/org/apache/meecrowave/maven/MeecrowaveBundleMojo.java
 (from r1792043, 
openwebbeans/meecrowave/trunk/meecrowave-maven-plugin/src/main/java/org/apache/meecrowave/maven/MeecrowaveRunMojo.java)
URL: 
http://svn.apache.org/viewvc/openwebbeans/meecrowave/trunk/meecrowave-maven-plugin/src/main/java/org/apache/meecrowave/maven/MeecrowaveBundleMojo.java?p2=openwebbeans/meecrowave/trunk/meecrowave-maven-plugin/src/main/java/org/apache/meecrowave/maven/MeecrowaveBundleMojo.java&p1=openwebbeans/meecrowave/trunk/meecrowave-maven-plugin/src/main/java/org/apache/meecrowave/maven/MeecrowaveRunMojo.java&r1=1792043&r2=1792555&rev=1792555&view=diff
==============================================================================
--- 
openwebbeans/meecrowave/trunk/meecrowave-maven-plugin/src/main/java/org/apache/meecrowave/maven/MeecrowaveRunMojo.java
 (original)
+++ 
openwebbeans/meecrowave/trunk/meecrowave-maven-plugin/src/main/java/org/apache/meecrowave/maven/MeecrowaveBundleMojo.java
 Mon Apr 24 22:41:56 2017
@@ -18,388 +18,290 @@
  */
 package org.apache.meecrowave.maven;
 
-import org.apache.logging.log4j.LogManager;
+import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
+import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
+import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
+import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
+import org.apache.commons.lang3.text.StrSubstitutor;
 import org.apache.maven.artifact.Artifact;
 import org.apache.maven.plugin.AbstractMojo;
 import org.apache.maven.plugin.MojoExecutionException;
 import org.apache.maven.plugin.MojoFailureException;
+import org.apache.maven.plugins.annotations.Component;
 import org.apache.maven.plugins.annotations.Mojo;
 import org.apache.maven.plugins.annotations.Parameter;
 import org.apache.maven.project.MavenProject;
-import org.apache.meecrowave.Meecrowave;
+import org.apache.maven.project.MavenProjectHelper;
 
-import javax.script.ScriptEngine;
-import javax.script.ScriptEngineManager;
-import javax.script.ScriptException;
-import javax.script.SimpleBindings;
+import java.io.BufferedReader;
 import java.io.File;
+import java.io.FileOutputStream;
 import java.io.IOException;
-import java.io.StringReader;
-import java.lang.reflect.Field;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.util.ArrayList;
+import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.StandardOpenOption;
+import java.nio.file.attribute.BasicFileAttributes;
 import java.util.Collection;
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Scanner;
-
-import static java.util.Collections.singletonList;
-import static java.util.Collections.singletonMap;
-import static java.util.Optional.ofNullable;
-import static java.util.stream.Collectors.toList;
-import static 
org.apache.maven.plugins.annotations.ResolutionScope.RUNTIME_PLUS_SYSTEM;
-
-@Mojo(name = "run", requiresDependencyResolution = RUNTIME_PLUS_SYSTEM)
-public class MeecrowaveRunMojo extends AbstractMojo {
-    @Parameter(property = "meecrowave.http", defaultValue = "8080")
-    private int httpPort;
-
-    @Parameter(property = "meecrowave.https", defaultValue = "8443")
-    private int httpsPort;
-
-    @Parameter(property = "meecrowave.stop", defaultValue = "8005")
-    private int stopPort;
-
-    @Parameter(property = "meecrowave.host", defaultValue = "localhost")
-    private String host;
-
-    @Parameter(property = "meecrowave.dir")
-    protected String dir;
-
-    @Parameter(property = "meecrowave.serverXml")
-    private File serverXml;
-
-    @Parameter(property = "meecrowave.keepServerXmlAsThis")
-    private boolean keepServerXmlAsThis;
-
-    @Parameter(property = "meecrowave.jaxrsLogProviders", defaultValue = 
"false")
-    private boolean jaxrsLogProviders;
-
-    @Parameter(property = "meecrowave.jaxrsLogProviders", defaultValue = 
"true")
-    private boolean tomcatWrapLoader;
-
-    @Parameter(property = "meecrowave.useTomcatDefaults", defaultValue = 
"true")
-    private boolean useTomcatDefaults;
-
-    @Parameter
-    private Map<String, String> properties;
-
-    @Parameter
-    private Map<String, String> cxfServletParams;
-
-    @Parameter(property = "meecrowave.tomcatNoJmx", defaultValue = "true")
-    private boolean tomcatNoJmx;
-
-    @Parameter(property = "meecrowave.quickSession", defaultValue = "true")
-    private boolean quickSession;
-
-    @Parameter(property = "meecrowave.tomcatScanning", defaultValue = "true")
-    private boolean tomcatScanning;
-
-    @Parameter(property = "meecrowave.tomcatAutoSetup", defaultValue = "true")
-    private boolean tomcatAutoSetup;
-
-    @Parameter(property = "meecrowave.java9SkipWorkarounds")
-    private boolean java9SkipWorkarounds;
-
-    @Parameter(property = "meecrowave.skipHttp")
-    private boolean skipHttp;
-
-    @Parameter(property = "meecrowave.ssl")
-    private boolean ssl;
-
-    @Parameter(property = "meecrowave.keystoreFile")
-    private String keystoreFile;
-
-    @Parameter(property = "meecrowave.keystorePass")
-    private String keystorePass;
-
-    @Parameter(property = "meecrowave.keystoreType", defaultValue = "JKS")
-    private String keystoreType;
-
-    @Parameter(property = "meecrowave.clientAuth")
-    private String clientAuth;
-
-    @Parameter(property = "meecrowave.keyAlias")
-    private String keyAlias;
+import java.util.HashMap;
+import java.util.stream.Stream;
+import java.util.zip.GZIPOutputStream;
 
-    @Parameter(property = "meecrowave.sslProtocol")
-    private String sslProtocol;
-
-    @Parameter(property = "meecrowave.webXml")
-    private String webXml;
-
-    @Parameter(property = "meecrowave.tomcatAccessLogPattern")
-    private String tomcatAccessLogPattern;
-
-    @Parameter
-    private Meecrowave.LoginConfigBuilder loginConfig;
-
-    @Parameter
-    private Collection<Meecrowave.SecurityConstaintBuilder> 
securityConstraints = new LinkedList<>();
-
-    @Parameter
-    private Map<String, String> users;
-
-    @Parameter
-    private Map<String, String> roles;
+import static java.util.Locale.ENGLISH;
+import static java.util.stream.Collectors.joining;
+import static 
org.apache.maven.plugins.annotations.ResolutionScope.RUNTIME_PLUS_SYSTEM;
 
-    @Parameter(property = "meecrowave.http2")
-    private boolean http2;
+@Mojo(name = "bundle", requiresDependencyResolution = RUNTIME_PLUS_SYSTEM)
+public class MeecrowaveBundleMojo extends AbstractMojo {
+    private static final String DELETE_TEXT = "Just there to not loose the 
folder cause it is empty, you can safely delete.";
 
-    @Parameter(property = "meecrowave.tempDir")
-    private String tempDir;
+    @Parameter(property = "meecrowave.main", defaultValue = 
"org.apache.meecrowave.runner.Cli")
+    private String main;
 
-    @Parameter(property = "meecrowave.webResourceCached", defaultValue = 
"true")
-    private boolean webResourceCached;
+    @Parameter(property = "meecrowave.scopes", defaultValue = 
"compile,runtime")
+    private Collection<String> scopes;
 
-    @Parameter(property = "meecrowave.conf")
+    @Parameter(property = "meecrowave.conf", defaultValue = 
"src/main/meecrowave/conf")
     private String conf;
 
-    @Parameter(property = "meecrowave.deleteBaseOnStartup", defaultValue = 
"true")
-    private boolean deleteBaseOnStartup;
+    @Parameter(property = "meecrowave.libs")
+    private Collection<String> libs;
 
-    @Parameter(property = "meecrowave.jaxrsMapping", defaultValue = "/*")
-    private String jaxrsMapping;
-
-    @Parameter(property = "meecrowave.cdiConversation", defaultValue = "true")
-    private boolean cdiConversation;
-
-    @Parameter(property = "meecrowave.skip")
+    @Parameter(property = "meecrowave.skip", defaultValue = "false")
     private boolean skip;
 
-    @Parameter(property = "meecrowave.jaxrs-beanvalidation", defaultValue = 
"true")
-    private boolean jaxrsAutoActivateBeanValidation;
+    @Parameter(property = "meecrowave.formats", defaultValue = "zip")
+    private Collection<String> formats;
 
-    @Parameter(property = "meecrowave.jaxrs-default-providers")
-    private String jaxrsDefaultProviders;
+    @Parameter(property = "meecrowave.classifier")
+    private String classifier;
 
-    @Parameter(property = "meecrowave.jaxrs-provider-setup", defaultValue = 
"true")
-    private boolean jaxrsProviderSetup;
+    @Parameter(property = "meecrowave.attach", defaultValue = "true")
+    private boolean attach;
 
-    @Parameter(property = "meecrowave.logging-global-setup", defaultValue = 
"true")
-    private boolean loggingGlobalSetup;
+    @Parameter(property = "meecrowave.no-root", defaultValue = "false")
+    private boolean skipArchiveRootFolder;
 
-    @Parameter(property = 
"meecrowave.servlet-container-initializer-injections", defaultValue = "true")
-    private boolean injectServletContainerInitializer;
+    @Parameter(property = "meecrowave.keep-exploded-folder", defaultValue = 
"false")
+    private boolean keepExplodedFolder;
 
-    @Parameter(property = "meecrowave.shutdown-hook", defaultValue = "true")
-    private boolean useShutdownHook;
+    @Parameter(property = "meecrowave.root-name")
+    private String rootName;
 
-    @Parameter
-    private List<String> jsCustomizers;
+    @Parameter(defaultValue = "${project.build.directory}", readonly = true)
+    private File buildDirectory;
 
-    @Parameter
-    private List<String> applicationScopes;
+    @Parameter(defaultValue = "${project.artifactId}", readonly = true)
+    private String artifactId;
 
-    @Parameter(defaultValue = "${project.build.outputDirectory}")
-    private List<File> modules;
+    @Parameter(defaultValue = 
"${project.build.directory}/${project.build.finalName}.${project.packaging}", 
readonly = true)
+    private File app;
 
-    @Parameter(defaultValue = "${project}", readonly = true, required = true)
+    @Parameter(defaultValue = "${project}", readonly = true)
     private MavenProject project;
 
-    @Parameter(property = "meecrowave.tomcatFilter")
-    private String tomcatFilter;
-
-    @Parameter(property = "meecrowave.context", defaultValue = "")
-    private String context;
-
-    // we don't need to resolve from maven coordinates cause can be added to 
the plugin deps, just here to reproduce manual deployments
-    @Parameter(property = "meecrowave.shared-libraries")
-    private String sharedLibraries;
-
-    @Parameter(property = "meecrowave.log4j2-jul-bridge", defaultValue = 
"true")
-    private boolean useLog4j2JulLogManager;
-
-    @Parameter(property = "meecrowave.jsonp-buffer-strategy", defaultValue = 
"QUEUE")
-    private String jsonpBufferStrategy;
-
-    @Parameter(property = "meecrowave.jsonp-max-string-length", defaultValue = 
"10485760")
-    private int jsonpMaxStringLen;
-
-    @Parameter(property = "meecrowave.jsonp-max-read-buffer-size", 
defaultValue = "65536")
-    private int jsonpMaxReadBufferLen;
-
-    @Parameter(property = "meecrowave.jsonp-max-write-buffer-size", 
defaultValue = "65536")
-    private int jsonpMaxWriteBufferLen;
-
-    @Parameter(property = "meecrowave.jsonp-comments", defaultValue = "false")
-    private boolean jsonpSupportsComment;
-
-    @Parameter(property = "meecrowave.jsonp-prettify", defaultValue = "false")
-    private boolean jsonpPrettify;
-
-    @Parameter(property = "meecrowave.jsonb-encoding", defaultValue = "UTF-8")
-    private String jsonbEncoding;
-
-    @Parameter(property = "meecrowave.jsonb-nulls", defaultValue = "false")
-    private boolean jsonbNulls = false;
-
-    @Parameter(property = "meecrowave.jsonb-ijson", defaultValue = "false")
-    private boolean jsonbIJson;
-
-    @Parameter(property = "meecrowave.jsonb-prettify", defaultValue = "false")
-    private boolean jsonbPrettify;
-
-    @Parameter(property = "meecrowave.jsonb-binary-strategy")
-    private String jsonbBinaryStrategy;
-
-    @Parameter(property = "meecrowave.jsonb-naming-strategy")
-    private String jsonbNamingStrategy;
-
-    @Parameter(property = "meecrowave.jsonb-order-strategy")
-    private String jsonbOrderStrategy;
+    @Component
+    private MavenProjectHelper projectHelper;
 
-    @Parameter(property = "meecrowave.scanning-exclude")
-    private String scanningIncludes;
+    @Override
+    public void execute() throws MojoExecutionException, MojoFailureException {
+        if (skip) {
+            getLog().warn(getClass().getSimpleName() + " skipped");
+            return;
+        }
 
-    @Parameter(property = "meecrowave.scanning-include")
-    private String scanningExcludes;
+        final File distroFolder = new File(buildDirectory, rootName == null ? 
artifactId + "-distribution" : rootName);
+        if (distroFolder.exists()) {
+            delete(distroFolder);
+        }
 
-    @Parameter(property = "meecrowave.scanning-package-include")
-    private String scanningPackageIncludes;
+        Stream.of("bin", "conf", "logs", "lib").forEach(i -> new 
File(distroFolder, i).mkdirs());
 
-    @Parameter(property = "meecrowave.scanning-package-exclude")
-    private String scanningPackageExcludes;
+        // TODO: add .bat support
+        try (final BufferedReader reader = new BufferedReader(new 
InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("bin/meecrowave.sh"))))
 {
+            write(new File(distroFolder, "bin/meecrowave.sh"), 
StrSubstitutor.replace(reader.lines().collect(joining("\n")), new 
HashMap<String, String>() {{
+                put("main", main);
+            }}));
+        } catch (final IOException e) {
+            throw new MojoExecutionException(e.getMessage(), e);
+        }
+        write(new File(distroFolder, "conf/log4j2.xml"), "<?xml 
version=\"1.0\" encoding=\"UTF-8\"?>\n" +
+                "<Configuration status=\"INFO\">\n" +
+                "  <Properties>\n" +
+                "    <Property name=\"name\">" + artifactId + "</Property>\n" +
+                "  </Properties>\n" +
+                "  <Appenders>\n" +
+                "    <Console name=\"Console\" target=\"SYSTEM_OUT\">\n" +
+                "      <PatternLayout 
pattern=\"[%d{HH:mm:ss.SSS}][%highlight{%-5level}][%15.15t][%30.30logger] 
%msg%n\"/>\n" +
+                "    </Console>" +
+                "    <RollingFile name=\"DailyLogFile\" 
fileName=\"logs/meecrowave.log\"\n" +
+                "                 
filePattern=\"logs/${name}-%d{yyyy-MM-dd}-%i.log.gz\">\n" +
+                "      <PatternLayout 
pattern=\"[%d{HH:mm:ss.SSS}][%-5level][%15.15t][%30.30logger] %msg%n\"/>\n" +
+                "      <Policies>\n" +
+                "        <TimeBasedTriggeringPolicy />\n" +
+                "        <SizeBasedTriggeringPolicy size=\"50 MB\"/>\n" +
+                "      </Policies>\n" +
+                "    </RollingFile>\n" +
+                "  </Appenders>\n" +
+                "  <Loggers>\n" +
+                "    <Root level=\"INFO\">\n" +
+                "      <!--<AppenderRef ref=\"Console\"/>-->\n" +
+                "      <AppenderRef ref=\"DailyLogFile\"/>\n" +
+                "    </Root>\n" +
+                "  </Loggers>\n" +
+                "</Configuration>\n\n");
+        write(new File(distroFolder, "logs/you_can_safely_delete.txt"), 
DELETE_TEXT);
+        project.getArtifacts().stream()
+                .filter(this::isIncluded)
+                .map(Artifact::getFile)
+                .forEach(f -> {
+                    try {
+                        Files.copy(f.toPath(), new File(distroFolder, "lib/" + 
f.getName()).toPath(), StandardCopyOption.REPLACE_EXISTING);
+                    } catch (final IOException e) {
+                        throw new IllegalStateException(e);
+                    }
+                });
+        if (app.exists()) {
+            try {
+                Files.copy(app.toPath(), new File(distroFolder, "lib/" + 
app.getName()).toPath(), StandardCopyOption.REPLACE_EXISTING);
+            } catch (final IOException e) {
+                throw new IllegalStateException(e);
+            }
+        }
 
-    @Parameter(property = "meecrowave.force-log4j2-shutdown", defaultValue = 
"true")
-    private boolean forceLog4j2Shutdown;
+        final Path prefix = skipArchiveRootFolder ? distroFolder.toPath() : 
distroFolder.getParentFile().toPath();
+        for (final String format : formats) {
+            getLog().info(format + "-ing Custom Meecrowave Distribution");
+
+            final File output = new File(buildDirectory, artifactId + 
"-meecrowave-distribution." + format);
+
+            switch (format.toLowerCase(ENGLISH)) {
+                case "tar.gz":
+                    try (final TarArchiveOutputStream tarGz =
+                                 new TarArchiveOutputStream(new 
GZIPOutputStream(new FileOutputStream(output)))) {
+                        
tarGz.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
+                        for (final String entry : distroFolder.list()) {
+                            tarGz(tarGz, new File(distroFolder, entry), 
prefix);
+                        }
+                    } catch (final IOException e) {
+                        throw new MojoExecutionException(e.getMessage(), e);
+                    }
+                    break;
+                case "zip":
+                    try (final ZipArchiveOutputStream zos =
+                                 new ZipArchiveOutputStream(new 
FileOutputStream(output))) {
+                        for (final String entry : distroFolder.list()) {
+                            zip(zos, new File(distroFolder, entry), prefix);
+                        }
+                    } catch (final IOException e) {
+                        throw new MojoExecutionException(e.getMessage(), e);
+                    }
+                    break;
+                default:
+                    throw new IllegalArgumentException(format + " is not 
supported");
+            }
 
-    @Parameter(property = "meecrowave.webapp", defaultValue = 
"${project.basedir}/src/main/webapp")
-    private File webapp;
+            attach(format, output);
+        }
 
-    @Parameter(property = "meecrowave.force-classpath-deployment", 
defaultValue = "true")
-    private boolean useClasspathDeployment;
+        if (!keepExplodedFolder) {
+            delete(distroFolder);
+        }
+    }
 
-    @Parameter
-    private String jsContextCustomizer;
+    private boolean isIncluded(final Artifact a) {
+        return !((scopes == null && 
!(Artifact.SCOPE_COMPILE.equals(a.getScope()) || 
Artifact.SCOPE_RUNTIME.equals(a.getScope())))
+                || (scopes != null && !scopes.contains(a.getScope())));
+    }
 
-    @Override
-    public void execute() throws MojoExecutionException, MojoFailureException {
-        if (skip) {
-            getLog().warn("Mojo skipped");
-            return;
+    private void write(final File file, final String content) {
+        try {
+            Files.write(file.toPath(), 
content.getBytes(StandardCharsets.UTF_8), StandardOpenOption.WRITE, 
StandardOpenOption.CREATE);
+        } catch (final IOException e) {
+            throw new IllegalStateException(e);
         }
+    }
 
-        final Thread thread = Thread.currentThread();
-        final ClassLoader loader = thread.getContextClassLoader();
-        final ClassLoader appLoader = createClassLoader(loader);
-        thread.setContextClassLoader(appLoader);
+    private void delete(final File distroFolder) { // not critical
+        final Path rootPath = distroFolder.toPath();
         try {
-            final Meecrowave.Builder builder = getConfig();
-            try (final Meecrowave meecrowave = new Meecrowave(builder) {
+            Files.walkFileTree(rootPath, new SimpleFileVisitor<Path>() {
                 @Override
-                protected void beforeStart() {
-                    scriptCustomization(jsCustomizers, "js", 
singletonMap("meecrowaveBase", base.getAbsolutePath()));
+                public FileVisitResult visitFile(final Path file, final 
BasicFileAttributes attrs) throws IOException {
+                    Files.delete(file);
+                    return FileVisitResult.CONTINUE;
                 }
-            }) {
-                meecrowave.start();
-                final String fixedContext = ofNullable(context).orElse("");
-                final Meecrowave.DeploymentMeta deploymentMeta = new 
Meecrowave.DeploymentMeta(
-                        fixedContext,
-                        webapp != null && webapp.isDirectory() ? webapp : null,
-                        jsContextCustomizer == null ?
-                                null : ctx -> scriptCustomization(
-                                singletonList(jsContextCustomizer), "js", 
singletonMap("context", ctx)));
-                if (useClasspathDeployment) {
-                    meecrowave.deployClasspath(deploymentMeta);
-                } else {
-                    meecrowave.deployWebapp(deploymentMeta);
-                }
-                new Scanner(System.in).next();
-            }
-        } finally {
-            if (forceLog4j2Shutdown) {
-                LogManager.shutdown();
-            }
-            if (appLoader != loader) {
-                try {
-                    URLClassLoader.class.cast(appLoader).close();
-                } catch (final IOException e) {
-                    getLog().warn(e.getMessage(), e);
+
+                @Override
+                public FileVisitResult postVisitDirectory(final Path dir, 
final IOException exc) throws IOException {
+                    Files.delete(dir);
+                    return FileVisitResult.CONTINUE;
                 }
-            }
-            thread.setContextClassLoader(loader);
+
+            });
+        } catch (final IOException e) {
+            getLog().warn(e);
         }
     }
 
-    private void scriptCustomization(final List<String> customizers, final 
String ext, final Map<String, Object> customBindings) {
-        if (customizers == null || customizers.isEmpty()) {
-            return;
-        }
-        final ScriptEngine engine = new 
ScriptEngineManager().getEngineByExtension(ext);
-        if (engine == null) {
-            throw new IllegalStateException("No engine for " + ext + ". Maybe 
add the JSR223 implementation as plugin dependency.");
-        }
-        for (final String js : customizers) {
-            try {
-                final SimpleBindings bindings = new SimpleBindings();
-                bindings.put("project", project);
-                engine.eval(new StringReader(js), bindings);
-                bindings.putAll(customBindings);
-            } catch (final ScriptException e) {
-                throw new IllegalStateException(e.getMessage(), e);
+    private void attach(final String ext, final File output) {
+        if (attach) {
+            getLog().info("Attaching Custom TomEE Distribution (" + ext + ")");
+            if (classifier != null) {
+                projectHelper.attachArtifact(project, ext, classifier, output);
+            } else {
+                projectHelper.attachArtifact(project, ext, output);
             }
         }
     }
 
-    private ClassLoader createClassLoader(final ClassLoader parent) {
-        final List<URL> urls = new ArrayList<>();
-        urls.addAll(project.getArtifacts().stream()
-                .filter(a -> !((applicationScopes == null && 
!(Artifact.SCOPE_COMPILE.equals(a.getScope()) || 
Artifact.SCOPE_RUNTIME.equals(a.getScope())))
-                        || (applicationScopes != null && 
!applicationScopes.contains(a.getScope()))))
-                .map(f -> {
-                    try {
-                        return f.getFile().toURI().toURL();
-                    } catch (final MalformedURLException e) {
-                        throw new IllegalArgumentException(e);
-                    }
-                })
-                .collect(toList()));
-        
urls.addAll(ofNullable(modules).orElse(Collections.emptyList()).stream().map(f 
-> {
-            try {
-                return f.toURI().toURL();
-            } catch (final MalformedURLException e) {
-                throw new IllegalArgumentException(e);
-            }
-        }).collect(toList()));
-        return urls.isEmpty() ? parent : new URLClassLoader(urls.toArray(new 
URL[urls.size()]), parent) {
-            @Override
-            public boolean equals(final Object obj) {
-                return super.equals(obj) || parent.equals(obj);
+    private void zip(final ZipArchiveOutputStream zip, final File f, final 
Path prefix) throws IOException {
+        final String path = 
prefix.relativize(f.toPath()).toString().replace(File.separator, "/");
+        final ZipArchiveEntry archiveEntry = new ZipArchiveEntry(f, path);
+        if (isSh(path)) {
+            archiveEntry.setUnixMode(0755);
+        }
+        zip.putArchiveEntry(archiveEntry);
+        if (f.isDirectory()) {
+            zip.closeArchiveEntry();
+            final File[] files = f.listFiles();
+            if (files != null) {
+                for (final File child : files) {
+                    zip(zip, child, prefix);
+                }
             }
-        };
+        } else {
+            Files.copy(f.toPath(), zip);
+            zip.closeArchiveEntry();
+        }
     }
 
-    private Meecrowave.Builder getConfig() {
-        final Meecrowave.Builder config = new Meecrowave.Builder();
-        for (final Field field : MeecrowaveRunMojo.class.getDeclaredFields()) {
-            if ("properties".equals(field.getName())) {
-                continue;
-            }
-            try {
-                final Field configField = 
Meecrowave.Builder.class.getDeclaredField(field.getName());
-                field.setAccessible(true);
-                configField.setAccessible(true);
-
-                final Object value = field.get(this);
-                if (value != null) {
-                    configField.set(config, value);
-                    getLog().debug("using " + field.getName() + " = " + value);
+    private void tarGz(final TarArchiveOutputStream tarGz, final File f, final 
Path prefix) throws IOException {
+        final String path = 
prefix.relativize(f.toPath()).toString().replace(File.separator, "/");
+        final TarArchiveEntry archiveEntry = new TarArchiveEntry(f, path);
+        if (isSh(path)) {
+            archiveEntry.setMode(0755);
+        }
+        tarGz.putArchiveEntry(archiveEntry);
+        if (f.isDirectory()) {
+            tarGz.closeArchiveEntry();
+            final File[] files = f.listFiles();
+            if (files != null) {
+                for (final File child : files) {
+                    tarGz(tarGz, child, prefix);
                 }
-            } catch (final NoSuchFieldException nsfe) {
-                // ignored
-            } catch (final Exception e) {
-                getLog().warn("can't initialize attribute " + field.getName());
             }
+        } else {
+            Files.copy(f.toPath(), tarGz);
+            tarGz.closeArchiveEntry();
         }
-        if (properties != null) {
-            config.getProperties().putAll(properties);
-        }
-        return config;
+    }
+
+    private boolean isSh(final String path) {
+        return path.endsWith(".sh");
     }
 }

Added: 
openwebbeans/meecrowave/trunk/meecrowave-maven-plugin/src/main/resources/bin/meecrowave.sh
URL: 
http://svn.apache.org/viewvc/openwebbeans/meecrowave/trunk/meecrowave-maven-plugin/src/main/resources/bin/meecrowave.sh?rev=1792555&view=auto
==============================================================================
--- 
openwebbeans/meecrowave/trunk/meecrowave-maven-plugin/src/main/resources/bin/meecrowave.sh
 (added)
+++ 
openwebbeans/meecrowave/trunk/meecrowave-maven-plugin/src/main/resources/bin/meecrowave.sh
 Mon Apr 24 22:41:56 2017
@@ -0,0 +1,491 @@
+#!/bin/sh
+
+# 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.
+
+#
+# forked from Meecrowave
+#
+
+# OS specific support.  $var _must_ be set to either true or false.
+cygwin=false
+darwin=false
+os400=false
+hpux=false
+case "`uname`" in
+CYGWIN*) cygwin=true;;
+Darwin*) darwin=true;;
+OS400*) os400=true;;
+HP-UX*) hpux=true;;
+esac
+
+# resolve links - $0 may be a softlink
+PRG="$0"
+
+while [ -h "$PRG" ]; do
+  ls=`ls -ld "$PRG"`
+  link=`expr "$ls" : '.*-> \(.*\)$'`
+  if expr "$link" : '/.*' > /dev/null; then
+    PRG="$link"
+  else
+    PRG=`dirname "$PRG"`/"$link"
+  fi
+done
+
+# Get standard environment variables
+PRGDIR=`dirname "$PRG"`
+
+# Only set MEECROWAVE_HOME if not already set
+[ -z "$MEECROWAVE_HOME" ] && MEECROWAVE_HOME=`cd "$PRGDIR/.." >/dev/null; pwd`
+
+# Copy MEECROWAVE_BASE from MEECROWAVE_HOME if not already set
+[ -z "$MEECROWAVE_BASE" ] && MEECROWAVE_BASE="$MEECROWAVE_HOME"
+
+# Ensure that any user defined CLASSPATH variables are not used on startup,
+# but allow them to be specified in setenv.sh, in rare case when it is needed.
+CLASSPATH=
+
+if [ -r "$MEECROWAVE_BASE/bin/setenv.sh" ]; then
+  . "$MEECROWAVE_BASE/bin/setenv.sh"
+elif [ -r "$MEECROWAVE_HOME/bin/setenv.sh" ]; then
+  . "$MEECROWAVE_HOME/bin/setenv.sh"
+fi
+
+# For Cygwin, ensure paths are in UNIX format before anything is touched
+if $cygwin; then
+  [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
+  [ -n "$JRE_HOME" ] && JRE_HOME=`cygpath --unix "$JRE_HOME"`
+  [ -n "$MEECROWAVE_HOME" ] && MEECROWAVE_HOME=`cygpath --unix 
"$MEECROWAVE_HOME"`
+  [ -n "$MEECROWAVE_BASE" ] && MEECROWAVE_BASE=`cygpath --unix 
"$MEECROWAVE_BASE"`
+  [ -n "$CLASSPATH" ] && CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
+fi
+
+# Ensure that neither MEECROWAVE_HOME nor MEECROWAVE_BASE contains a colon
+# as this is used as the separator in the classpath and Java provides no
+# mechanism for escaping if the same character appears in the path.
+case $MEECROWAVE_HOME in
+  *:*) echo "Using MEECROWAVE_HOME:   $MEECROWAVE_HOME";
+       echo "Unable to start as MEECROWAVE_HOME contains a colon (:) 
character";
+       exit 1;
+esac
+case $MEECROWAVE_BASE in
+  *:*) echo "Using MEECROWAVE_BASE:   $MEECROWAVE_BASE";
+       echo "Unable to start as MEECROWAVE_BASE contains a colon (:) 
character";
+       exit 1;
+esac
+
+# For OS400
+if $os400; then
+  # Set job priority to standard for interactive (interactive - 6) by using
+  # the interactive priority - 6, the helper threads that respond to requests
+  # will be running at the same priority as interactive jobs.
+  COMMAND='chgjob job('$JOBNAME') runpty(6)'
+  system $COMMAND
+
+  # Enable multi threading
+  export QIBM_MULTI_THREADED=Y
+fi
+
+# Get standard Java environment variables
+# Make sure prerequisite environment variables are set
+if [ -z "$JAVA_HOME" -a -z "$JRE_HOME" ]; then
+  if $darwin; then
+    # Bugzilla 54390
+    if [ -x '/usr/libexec/java_home' ] ; then
+      export JAVA_HOME=`/usr/libexec/java_home`
+    # Bugzilla 37284 (reviewed).
+    elif [ -d 
"/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home" ]; then
+      export 
JAVA_HOME="/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home"
+    fi
+  else
+    JAVA_PATH=`which java 2>/dev/null`
+    if [ "x$JAVA_PATH" != "x" ]; then
+      JAVA_PATH=`dirname $JAVA_PATH 2>/dev/null`
+      JRE_HOME=`dirname $JAVA_PATH 2>/dev/null`
+    fi
+    if [ "x$JRE_HOME" = "x" ]; then
+      # XXX: Should we try other locations?
+      if [ -x /usr/bin/java ]; then
+        JRE_HOME=/usr
+      fi
+    fi
+  fi
+  if [ -z "$JAVA_HOME" -a -z "$JRE_HOME" ]; then
+    echo "Neither the JAVA_HOME nor the JRE_HOME environment variable is 
defined"
+    echo "At least one of these environment variable is needed to run this 
program"
+    exit 1
+  fi
+fi
+if [ -z "$JAVA_HOME" -a "$1" = "debug" ]; then
+  echo "JAVA_HOME should point to a JDK in order to run in debug mode."
+  exit 1
+fi
+if [ -z "$JRE_HOME" ]; then
+  JRE_HOME="$JAVA_HOME"
+fi
+
+# If we're running under jdb, we need a full jdk.
+if [ "$1" = "debug" ] ; then
+  if [ "$os400" = "true" ]; then
+    if [ ! -x "$JAVA_HOME"/bin/java -o ! -x "$JAVA_HOME"/bin/javac ]; then
+      echo "The JAVA_HOME environment variable is not defined correctly"
+      echo "This environment variable is needed to run this program"
+      echo "NB: JAVA_HOME should point to a JDK not a JRE"
+      exit 1
+    fi
+  else
+    if [ ! -x "$JAVA_HOME"/bin/java -o ! -x "$JAVA_HOME"/bin/jdb -o ! -x 
"$JAVA_HOME"/bin/javac ]; then
+      echo "The JAVA_HOME environment variable is not defined correctly"
+      echo "This environment variable is needed to run this program"
+      echo "NB: JAVA_HOME should point to a JDK not a JRE"
+      exit 1
+    fi
+  fi
+fi
+
+# Set standard commands for invoking Java, if not already set.
+if [ -z "$_RUNJAVA" ]; then
+  _RUNJAVA="$JRE_HOME"/bin/java
+fi
+if [ "$os400" != "true" ]; then
+  if [ -z "$_RUNJDB" ]; then
+    _RUNJDB="$JAVA_HOME"/bin/jdb
+  fi
+fi
+
+# Add on extra jar files to CLASSPATH
+if [ ! -z "$CLASSPATH" ] ; then
+  CLASSPATH="$CLASSPATH":
+fi
+for i in "$MEECROWAVE_HOME/lib/"*.jar ; do
+  if [ -z "$CLASSPATH" ] ; then
+    CLASSPATH="$i"
+  else
+    CLASSPATH="$i:$CLASSPATH"
+  fi
+done
+
+if [ -z "$MEECROWAVE_OUT" ] ; then
+  MEECROWAVE_OUT="$MEECROWAVE_BASE"/logs/meecrowave.out
+fi
+
+if [ -z "$MEECROWAVE_TMPDIR" ] ; then
+  # Define the java.io.tmpdir to use for MEECROWAVE
+  MEECROWAVE_TMPDIR="$MEECROWAVE_BASE"/temp
+fi
+
+# Bugzilla 37848: When no TTY is available, don't output to console
+have_tty=0
+if [ "`tty`" != "not a tty" ]; then
+    have_tty=1
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin; then
+  JAVA_HOME=`cygpath --absolute --windows "$JAVA_HOME"`
+  JRE_HOME=`cygpath --absolute --windows "$JRE_HOME"`
+  MEECROWAVE_HOME=`cygpath --absolute --windows "$MEECROWAVE_HOME"`
+  MEECROWAVE_BASE=`cygpath --absolute --windows "$MEECROWAVE_BASE"`
+  MEECROWAVE_TMPDIR=`cygpath --absolute --windows "$MEECROWAVE_TMPDIR"`
+  CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
+fi
+
+if [ -z "$JSSE_OPTS" ] ; then
+  JSSE_OPTS="-Djdk.tls.ephemeralDHKeySize=2048"
+fi
+JAVA_OPTS="$JAVA_OPTS $JSSE_OPTS"
+
+# Register custom URL handlers
+# Do this here so custom URL handles (specifically 'war:...') can be used in 
the security policy
+JAVA_OPTS="$JAVA_OPTS 
-Djava.protocol.handler.pkgs=org.apache.MEECROWAVE.webresources"
+
+# Set juli LogManager config file if it is present and an override has not 
been issued
+if [ -z "$LOGGING_CONFIG" ]; then
+  if [ -r "$MEECROWAVE_BASE"/conf/logging.properties ]; then
+    
LOGGING_CONFIG="-Djava.util.logging.config.file=$MEECROWAVE_BASE/conf/logging.properties"
+  else
+    # Bugzilla 45585
+    LOGGING_CONFIG="-Dmeecrowave.script.nologgingconfig"
+  fi
+fi
+
+if [ -z "$LOGGING_MANAGER" ]; then
+  
LOGGING_MANAGER="-Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager"
+fi
+
+# Set UMASK unless it has been overridden
+if [ -z "$UMASK" ]; then
+    UMASK="0027"
+fi
+umask $UMASK
+
+# Uncomment the following line to make the umask available when using the
+# org.apache.MEECROWAVE.security.SecurityListener
+#JAVA_OPTS="$JAVA_OPTS 
-Dorg.apache.MEECROWAVE.security.SecurityListener.UMASK=`umask`"
+
+if [ -z "$USE_NOHUP" ]; then
+    if $hpux; then
+        USE_NOHUP="true"
+    else
+        USE_NOHUP="false"
+    fi
+fi
+unset _NOHUP
+if [ "$USE_NOHUP" = "true" ]; then
+    _NOHUP=nohup
+fi
+
+if [ -z "$MEECROWAVE_PID" ]; then
+  MEECROWAVE_PID="$MEECROWAVE_BASE"/conf/meecrowave.pid
+fi
+# ----- Execute The Requested Command -----------------------------------------
+
+# Bugzilla 37848: only output this if we have a TTY
+if [ $have_tty -eq 1 ]; then
+  echo "Using MEECROWAVE_BASE:   $MEECROWAVE_BASE"
+  echo "Using MEECROWAVE_HOME:   $MEECROWAVE_HOME"
+  echo "Using MEECROWAVE_TMPDIR: $MEECROWAVE_TMPDIR"
+  echo "Using JRE_HOME:        $JRE_HOME"
+  echo "Using CLASSPATH:       $CLASSPATH"
+  if [ ! -z "$MEECROWAVE_PID" ]; then
+    echo "Using MEECROWAVE_PID:    $MEECROWAVE_PID"
+  fi
+fi
+
+if [ "$1" = "jpda" ] ; then
+  if [ -z "$JPDA_TRANSPORT" ]; then
+    JPDA_TRANSPORT="dt_socket"
+  fi
+  if [ -z "$JPDA_ADDRESS" ]; then
+    JPDA_ADDRESS="localhost:8000"
+  fi
+  if [ -z "$JPDA_SUSPEND" ]; then
+    JPDA_SUSPEND="n"
+  fi
+  if [ -z "$JPDA_OPTS" ]; then
+    
JPDA_OPTS="-agentlib:jdwp=transport=$JPDA_TRANSPORT,address=$JPDA_ADDRESS,server=y,suspend=$JPDA_SUSPEND"
+  fi
+  MEECROWAVE_OPTS="$JPDA_OPTS $MEECROWAVE_OPTS"
+  shift
+fi
+
+if [ -f "$MEECROWAVE_BASE"/conf/log4j2.xml ]; then
+  MEECROWAVE_OPTS="$MEECROWAVE_OPTS 
-Dlog4j.configurationFile="$MEECROWAVE_BASE"/conf/log4j2.xml"
+fi
+
+if [ "$1" = "run" ]; then
+
+  shift
+  eval exec "\"$_RUNJAVA\"" "\"$LOGGING_CONFIG\"" $LOGGING_MANAGER $JAVA_OPTS 
$MEECROWAVE_OPTS \
+    -classpath "\"$CLASSPATH\"" \
+    -Dmeecrowave.base="\"$MEECROWAVE_BASE\"" \
+    -Dmeecrowave.home="\"$MEECROWAVE_HOME\"" \
+    -Dmeecrowave.home="\"$MEECROWAVE_HOME\"" \
+    -Djava.io.tmpdir="\"$MEECROWAVE_TMPDIR\"" \
+    ${main} "$@" start
+
+elif [ "$1" = "start" ] ; then
+
+  if [ ! -z "$MEECROWAVE_PID" ]; then
+    if [ -f "$MEECROWAVE_PID" ]; then
+      if [ -s "$MEECROWAVE_PID" ]; then
+        echo "Existing PID file found during start."
+        if [ -r "$MEECROWAVE_PID" ]; then
+          PID=`cat "$MEECROWAVE_PID"`
+          ps -p $PID >/dev/null 2>&1
+          if [ $? -eq 0 ] ; then
+            echo "Meecrowave appears to still be running with PID $PID. Start 
aborted."
+            echo "If the following process is not a Meecrowave process, remove 
the PID file and try again:"
+            ps -f -p $PID
+            exit 1
+          else
+            echo "Removing/clearing stale PID file."
+            rm -f "$MEECROWAVE_PID" >/dev/null 2>&1
+            if [ $? != 0 ]; then
+              if [ -w "$MEECROWAVE_PID" ]; then
+                cat /dev/null > "$MEECROWAVE_PID"
+              else
+                echo "Unable to remove or clear stale PID file. Start aborted."
+                exit 1
+              fi
+            fi
+          fi
+        else
+          echo "Unable to read PID file. Start aborted."
+          exit 1
+        fi
+      else
+        rm -f "$MEECROWAVE_PID" >/dev/null 2>&1
+        if [ $? != 0 ]; then
+          if [ ! -w "$MEECROWAVE_PID" ]; then
+            echo "Unable to remove or write to empty PID file. Start aborted."
+            exit 1
+          fi
+        fi
+      fi
+    fi
+  fi
+
+  shift
+  touch "$MEECROWAVE_OUT"
+  eval $_NOHUP "\"$_RUNJAVA\"" "\"$LOGGING_CONFIG\"" $LOGGING_MANAGER 
$JAVA_OPTS $MEECROWAVE_OPTS \
+    -classpath "\"$CLASSPATH\"" \
+    -Dmeecrowave.base="\"$MEECROWAVE_BASE\"" \
+    -Dmeecrowave.home="\"$MEECROWAVE_HOME\"" \
+    -Djava.io.tmpdir="\"$MEECROWAVE_TMPDIR\"" \
+    ${main} "$@" start \
+    >> "$MEECROWAVE_OUT" 2>&1 "&"
+
+  if [ ! -z "$MEECROWAVE_PID" ]; then
+    echo $! > "$MEECROWAVE_PID"
+  fi
+
+  echo "Meecrowave started."
+
+elif [ "$1" = "stop" ] ; then
+
+  shift
+
+  SLEEP=5
+  if [ ! -z "$1" ]; then
+    echo $1 | grep "[^0-9]" >/dev/null 2>&1
+    if [ $? -gt 0 ]; then
+      SLEEP=$1
+      shift
+    fi
+  fi
+
+  FORCE=0
+  if [ "$1" = "-force" ]; then
+    shift
+    FORCE=1
+  fi
+
+  if [ ! -z "$MEECROWAVE_PID" ]; then
+    if [ -f "$MEECROWAVE_PID" ]; then
+      if [ -s "$MEECROWAVE_PID" ]; then
+        kill -9 `cat "$MEECROWAVE_PID"` >/dev/null 2>&1
+        if [ $? -gt 0 ]; then
+          echo "PID file found but no matching process was found. Stop 
aborted."
+          exit 1
+        fi
+      else
+        echo "PID file is empty and has been ignored."
+      fi
+    else
+      echo "\$MEECROWAVE_PID was set but the specified file does not exist. Is 
Meecrowave running? Stop aborted."
+      exit 1
+    fi
+  fi
+
+  #eval "\"$_RUNJAVA\"" $JAVA_OPTS \
+  #  -classpath "\"$CLASSPATH\"" \
+  #  -Dmeecrowave.base="\"$MEECROWAVE_BASE\"" \
+  #  -Dmeecrowave.home="\"$MEECROWAVE_HOME\"" \
+  #  -Djava.io.tmpdir="\"$MEECROWAVE_TMPDIR\"" \
+  #  ${main} "$@" stop
+
+  # stop failed. Shutdown port disabled? Try a normal kill.
+  #if [ $? != 0 ]; then
+  #  if [ ! -z "$MEECROWAVE_PID" ]; then
+  #    echo "The stop command failed. Attempting to signal the process to stop 
through OS signal."
+  #    kill -15 `cat "$MEECROWAVE_PID"` >/dev/null 2>&1
+  #  fi
+  #fi
+
+  if [ ! -z "$MEECROWAVE_PID" ]; then
+    if [ -f "$MEECROWAVE_PID" ]; then
+      while [ $SLEEP -ge 0 ]; do
+        kill -9 `cat "$MEECROWAVE_PID"` >/dev/null 2>&1
+        if [ $? -gt 0 ]; then
+          rm -f "$MEECROWAVE_PID" >/dev/null 2>&1
+          if [ $? != 0 ]; then
+            if [ -w "$MEECROWAVE_PID" ]; then
+              cat /dev/null > "$MEECROWAVE_PID"
+              # If Meecrowave has stopped don't try and force a stop with an 
empty PID file
+              FORCE=0
+            else
+              echo "The PID file could not be removed or cleared."
+            fi
+          fi
+          echo "Meecrowave stopped."
+          break
+        fi
+        if [ $SLEEP -gt 0 ]; then
+          sleep 1
+        fi
+        if [ $SLEEP -eq 0 ]; then
+          echo "Meecrowave did not stop in time."
+          if [ $FORCE -eq 0 ]; then
+            echo "PID file was not removed."
+          fi
+          echo "To aid diagnostics a thread dump has been written to standard 
out."
+          kill -3 `cat "$MEECROWAVE_PID"`
+        fi
+        SLEEP=`expr $SLEEP - 1 `
+      done
+    fi
+  fi
+
+  KILL_SLEEP_INTERVAL=5
+  if [ $FORCE -eq 1 ]; then
+    if [ -z "$MEECROWAVE_PID" ]; then
+      echo "Kill failed: \$MEECROWAVE_PID not set"
+    else
+      if [ -f "$MEECROWAVE_PID" ]; then
+        PID=`cat "$MEECROWAVE_PID"`
+        echo "Killing Meecrowave with the PID: $PID"
+        kill -9 $PID
+        while [ $KILL_SLEEP_INTERVAL -ge 0 ]; do
+            kill -0 `cat "$MEECROWAVE_PID"` >/dev/null 2>&1
+            if [ $? -gt 0 ]; then
+                rm -f "$MEECROWAVE_PID" >/dev/null 2>&1
+                if [ $? != 0 ]; then
+                    if [ -w "$MEECROWAVE_PID" ]; then
+                        cat /dev/null > "$MEECROWAVE_PID"
+                    else
+                        echo "The PID file could not be removed."
+                    fi
+                fi
+                echo "The Meecrowave process has been killed."
+                break
+            fi
+            if [ $KILL_SLEEP_INTERVAL -gt 0 ]; then
+                sleep 1
+            fi
+            KILL_SLEEP_INTERVAL=`expr $KILL_SLEEP_INTERVAL - 1 `
+        done
+        if [ $KILL_SLEEP_INTERVAL -lt 0 ]; then
+            echo "Meecrowave has not been killed completely yet. The process 
might be waiting on some system call or might be UNINTERRUPTIBLE."
+        fi
+      fi
+    fi
+  fi
+
+else
+
+  echo "Usage: MEECROWAVE.sh ( commands ... )"
+  echo "commands:"
+  echo "  jpda start        Start MEECROWAVE under JPDA debugger"
+  echo "  run               Start MEECROWAVE in the current window"
+  echo "  start             Start MEECROWAVE in a separate window"
+  echo "  stop              Stop MEECROWAVE, waiting up to 5 seconds for the 
process to end"
+  echo "  stop n            Stop MEECROWAVE, waiting up to n seconds for the 
process to end"
+  echo "  stop -force       Stop MEECROWAVE, wait up to 5 seconds and then use 
kill -KILL if still running"
+  echo "  stop n -force     Stop MEECROWAVE, wait up to n seconds and then use 
kill -KILL if still running"
+  echo "Note: Waiting for the process to end and use of the -force option 
require that \$MEECROWAVE_PID is defined"
+  exit 1
+
+fi


Reply via email to