/**
   * Constructor. The first time an RJavaClassLoader is created, it is cached as the primary loader.
   *
   * @param path path of the rJava package
   * @param libpath lib sub directory of the rJava package
   */
  public RJavaClassLoader(String path, String libpath) {
    super(new URL[] {});
    // respect rJava.debug level
    String rjd = System.getProperty("rJava.debug");
    if (rjd != null && rjd.length() > 0 && !rjd.equals("0")) verbose = true;
    if (verbose) System.out.println("RJavaClassLoader(\"" + path + "\",\"" + libpath + "\")");
    if (primaryLoader == null) {
      primaryLoader = this;
      if (verbose) System.out.println(" - primary loader");
    } else {
      if (verbose)
        System.out.println(" - NOT primrary (this=" + this + ", primary=" + primaryLoader + ")");
    }
    libMap = new HashMap /*<String,UnixFile>*/();

    classPath = new Vector /*<UnixFile>*/();
    classPath.add(new UnixDirectory(path + "/java"));

    rJavaPath = path;
    rJavaLibPath = libpath;

    /* load the rJava library */
    UnixFile so = new UnixFile(rJavaLibPath + "/rJava.so");
    if (!so.exists()) so = new UnixFile(rJavaLibPath + "/rJava.dll");
    if (so.exists()) libMap.put("rJava", so);

    /* load the jri library */
    UnixFile jri = new UnixFile(path + "/jri/libjri.so");
    String rarch = System.getProperty("r.arch");
    if (rarch != null && rarch.length() > 0) {
      UnixFile af = new UnixFile(path + "/jri" + rarch + "/libjri.so");
      if (af.exists()) jri = af;
      else {
        af = new UnixFile(path + "/jri" + rarch + "/jri.dll");
        if (af.exists()) jri = af;
      }
    }
    if (!jri.exists()) jri = new UnixFile(path + "/jri/libjri.jnilib");
    if (!jri.exists()) jri = new UnixFile(path + "/jri/jri.dll");
    if (jri.exists()) {
      libMap.put("jri", jri);
      if (verbose) System.out.println(" - registered JRI: " + jri);
    }

    /* if we are the primary loader, make us the context loader so
    projects that rely on the context loader pick us */
    if (primaryLoader == this) Thread.currentThread().setContextClassLoader(this);

    if (verbose) {
      System.out.println("RJavaClassLoader initialized.\n\nRegistered libraries:");
      for (Iterator entries = libMap.keySet().iterator(); entries.hasNext(); ) {
        Object key = entries.next();
        System.out.println("  " + key + ": '" + libMap.get(key) + "'");
      }
      System.out.println("\nRegistered class paths:");
      for (Enumeration e = classPath.elements(); e.hasMoreElements(); )
        System.out.println("  '" + e.nextElement() + "'");
      System.out.println("\n-- end of class loader report --");
    }
  }
 /**
  * main method
  *
  * <p>This uses the system properties:
  *
  * <ul>
  *   <li><code>rjava.path</code> : path of the rJava package
  *   <li><code>rjava.lib</code> : lib sub directory of the rJava package
  *   <li><code>main.class</code> : main class to "boot", assumes Main if not specified
  *   <li><code>rjava.class.path</code> : set of paths to populate the initiate the class path
  * </ul>
  *
  * <p>and boots the "main" method of the specified <code>main.class</code>, passing the args down
  * to the booted class
  *
  * <p>This makes sure R and rJava are known by the class loader
  */
 public static void main(String[] args) {
   String rJavaPath = System.getProperty("rjava.path");
   if (rJavaPath == null) {
     System.err.println("ERROR: rjava.path is not set");
     System.exit(2);
   }
   String rJavaLib = System.getProperty("rjava.lib");
   if (rJavaLib == null) { // it is not really used so far, just for rJava.so, so we can guess
     rJavaLib = rJavaPath + File.separator + "libs";
   }
   RJavaClassLoader cl = new RJavaClassLoader(u2w(rJavaPath), u2w(rJavaLib));
   String mainClass = System.getProperty("main.class");
   if (mainClass == null || mainClass.length() < 1) {
     System.err.println("WARNING: main.class not specified, assuming 'Main'");
     mainClass = "Main";
   }
   String classPath = System.getProperty("rjava.class.path");
   if (classPath != null) {
     StringTokenizer st = new StringTokenizer(classPath, File.pathSeparator);
     while (st.hasMoreTokens()) {
       String dirname = u2w(st.nextToken());
       cl.addClassPath(dirname);
     }
   }
   try {
     cl.bootClass(mainClass, "main", args);
   } catch (Exception ex) {
     System.err.println("ERROR: while running main method: " + ex);
     ex.printStackTrace();
   }
 }
示例#3
0
 private void addCreatedBy(Manifest m) {
   Attributes global = m.getMainAttributes();
   if (global.getValue(new Attributes.Name("Created-By")) == null) {
     String javaVendor = System.getProperty("java.vendor");
     String jdkVersion = System.getProperty("java.version");
     global.put(new Attributes.Name("Created-By"), jdkVersion + " (" + javaVendor + ")");
   }
 }
示例#4
0
文件: Installer.java 项目: suever/CTP
  private void updateLinuxServiceInstaller() {
    try {
      File dir = new File(directory, "CTP");
      if (suppressFirstPathElement) dir = dir.getParentFile();
      Properties props = new Properties();
      String ctpHome = dir.getAbsolutePath();
      cp.appendln(Color.black, "...CTP_HOME: " + ctpHome);
      ctpHome = ctpHome.replaceAll("\\\\", "\\\\\\\\");
      props.put("CTP_HOME", ctpHome);
      File javaHome = new File(System.getProperty("java.home"));
      String javaBin = (new File(javaHome, "bin")).getAbsolutePath();
      cp.appendln(Color.black, "...JAVA_BIN: " + javaBin);
      javaBin = javaBin.replaceAll("\\\\", "\\\\\\\\");
      props.put("JAVA_BIN", javaBin);

      File linux = new File(dir, "linux");
      File install = new File(linux, "ctpService-ubuntu.sh");
      cp.appendln(Color.black, "Linux service installer:");
      cp.appendln(Color.black, "...file: " + install.getAbsolutePath());
      String bat = getFileText(install);
      bat = replace(bat, props); // do the substitutions
      bat = bat.replace("\r", "");
      setFileText(install, bat);

      // If this is an ISN installation, put the script in the correct place.
      String osName = System.getProperty("os.name").toLowerCase();
      if (programName.equals("ISN") && !osName.contains("windows")) {
        install = new File(linux, "ctpService-red.sh");
        cp.appendln(Color.black, "ISN service installer:");
        cp.appendln(Color.black, "...file: " + install.getAbsolutePath());
        bat = getFileText(install);
        bat = replace(bat, props); // do the substitutions
        bat = bat.replace("\r", "");
        File initDir = new File("/etc/init.d");
        File initFile = new File(initDir, "ctpService");
        if (initDir.exists()) {
          setOwnership(initDir, "edge", "edge");
          setFileText(initFile, bat);
          initFile.setReadable(true, false); // everybody can read //Java 1.6
          initFile.setWritable(true); // only the owner can write //Java 1.6
          initFile.setExecutable(true, false); // everybody can execute //Java 1.6
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      System.err.println("Unable to update the Linux service ctpService.sh file");
    }
  }
  public boolean avrdude(Collection params) throws RunnerException {
    List commandDownloader = new ArrayList();
    commandDownloader.add("avrdude");

    // Point avrdude at its config file since it's in a non-standard location.
    if (Base.isMacOS()) {
      commandDownloader.add("-C" + "hardware/tools/avr/etc/avrdude.conf");
    } else if (Base.isWindows()) {
      String userdir = System.getProperty("user.dir") + File.separator;
      commandDownloader.add("-C" + userdir + "hardware/tools/avr/etc/avrdude.conf");
    } else {
      // ???: is it better to have Linux users install avrdude themselves, in
      // a way that it can find its own configuration file?
      commandDownloader.add("-C" + "hardware/tools/avrdude.conf");
    }

    if (Preferences.getBoolean("upload.verbose")) {
      commandDownloader.add("-v");
      commandDownloader.add("-v");
      commandDownloader.add("-v");
      commandDownloader.add("-v");
    } else {
      commandDownloader.add("-q");
      commandDownloader.add("-q");
    }
    // XXX: quick hack to chop the "atmega" off of "atmega8" and "atmega168",
    // then shove an "m" at the beginning.  won't work for attiny's, etc.
    commandDownloader.add(
        "-pm" + Preferences.get("boards." + Preferences.get("board") + ".build.mcu").substring(6));
    commandDownloader.addAll(params);

    return executeUploadCommand(commandDownloader);
  }
 public ExtMXSerializer getResXmlSerializer() {
   ExtMXSerializer serial = new ExtMXSerializer();
   serial.setProperty(ExtXmlSerializer.PROPERTY_SERIALIZER_INDENTATION, "    ");
   serial.setProperty(
       ExtXmlSerializer.PROPERTY_SERIALIZER_LINE_SEPARATOR, System.getProperty("line.separator"));
   serial.setProperty(ExtMXSerializer.PROPERTY_DEFAULT_ENCODING, "utf-8");
   serial.setDisabledAttrEscape(true);
   return serial;
 }
示例#7
0
 public static String getSystemName() {
   String name = System.getProperty("os.name");
   // if(name.indexOf("Solaris") >= 0) return "solaris"; -- Deprecated in 1.6.2+
   if (name.indexOf("Linux") >= 0) return "linux";
   if (name.indexOf("Mac") >= 0) return "osx";
   if (name.indexOf("Windows") >= 0) return "windows";
   return "commodore64";
   // Default choice.
   // Most likely as the C64 was the best selling home computer in history.
   // ToDon't: Check the SID version for the zealots.
 }
 public static void main(String[] args) throws Exception {
   int iterations = 0;
   File zFile1 = new File(System.getProperty("test.src", "."), "pkware123456789012345.zip");
   while (iterations < 2500) {
     ZipFile zipFile = new ZipFile(zFile1);
     List entries = Collections.list(zipFile.entries());
     for (Iterator it = entries.iterator(); it.hasNext(); ) {
       ZipEntry zipEntry = (ZipEntry) it.next();
       InputStream in = zipFile.getInputStream(zipEntry);
       in.close();
     }
     iterations++;
   }
 }
 public String getClasspath() {
   final StringBuilder sb = new StringBuilder();
   boolean firstPass = true;
   final Enumeration<File> componentEnum = this.pathComponents.elements();
   while (componentEnum.hasMoreElements()) {
     if (!firstPass) {
       sb.append(System.getProperty("path.separator"));
     } else {
       firstPass = false;
     }
     sb.append(componentEnum.nextElement().getAbsolutePath());
   }
   return sb.toString();
 }
 private File getFrameworkDir() throws AndrolibException {
   File dir =
       new File(
           System.getProperty("user.home")
               + File.separatorChar
               + "apktool"
               + File.separatorChar
               + "framework");
   if (!dir.exists()) {
     if (!dir.mkdirs()) {
       throw new AndrolibException("Can't create directory: " + dir);
     }
   }
   return dir;
 }
示例#11
0
文件: Installer.java 项目: suever/CTP
 private void fixRSNAROOT(Element server) {
   if (programName.equals("ISN")) {
     Element ssl = getFirstNamedChild(server, "SSL");
     if (ssl != null) {
       if (System.getProperty("os.name").contains("Windows")) {
         ssl.setAttribute(
             "keystore", ssl.getAttribute("keystore").replace("RSNA_HOME", "RSNA_ROOT"));
         ssl.setAttribute(
             "truststore", ssl.getAttribute("truststore").replace("RSNA_HOME", "RSNA_ROOT"));
       } else {
         ssl.setAttribute("keystore", "${RSNA_ROOT}/conf/keystore.jks");
         ssl.setAttribute("truststore", "${RSNA_ROOT}/conf/truststore.jks");
       }
     }
   }
 }
  /** adds an entry to the class path */
  public void addClassPath(String cp) {
    UnixFile f = new UnixFile(cp);

    // use the URLClassLoader
    if (useSystem) {
      try {
        addURL(f.toURL());
        if (verbose)
          System.out.println("RJavaClassLoader: added '" + cp + "' to the URL class path loader");
        // return; // we need to add it anyway so it appears in .jclassPath()
      } catch (Exception ufe) {
      }
    }

    UnixFile g = null;
    if (f.isFile() && (f.getName().endsWith(".jar") || f.getName().endsWith(".JAR"))) {
      g = new UnixJarFile(cp);
      if (verbose)
        System.out.println(
            "RJavaClassLoader: adding Java archive file '" + cp + "' to the internal class path");
    } else if (f.isDirectory()) {
      g = new UnixDirectory(cp);
      if (verbose)
        System.out.println(
            "RJavaClassLoader: adding class directory '" + cp + "' to the internal class path");
    } else if (verbose)
      System.err.println(
          f.exists()
              ? ("WARNING: the path '"
                  + cp
                  + "' is neither a directory nor a .jar file, it will NOT be added to the internal class path!")
              : ("WARNING: the path '"
                  + cp
                  + "' does NOT exist, it will NOT be added to the internal class path!"));

    if (g != null && !classPath.contains(g)) {
      // this is the real meat - add it to our internal list
      classPath.add(g);
      // this is just cosmetics - it doesn't really have any meaning
      System.setProperty(
          "java.class.path",
          System.getProperty("java.class.path") + File.pathSeparator + g.getPath());
    }
  }
示例#13
0
文件: Installer.java 项目: suever/CTP
 // If this is a new installation, ask the user for a
 // port for the server; otherwise, return the negative
 // of the configured port. If the user selects an illegal
 // port, return zero.
 private int getPort() {
   // Note: directory points to the parent of the CTP directory.
   File ctp = new File(directory, "CTP");
   if (suppressFirstPathElement) ctp = ctp.getParentFile();
   File config = new File(ctp, "config.xml");
   if (!config.exists()) {
     // No config file - must be a new installation.
     // Figure out whether this is Windows or something else.
     String os = System.getProperty("os.name").toLowerCase();
     int defPort = ((os.contains("windows") && !programName.equals("ISN")) ? 80 : 1080);
     int userPort = 0;
     while (userPort == 0) {
       String port =
           JOptionPane.showInputDialog(
               null,
               "This is a new "
                   + programName
                   + " installation.\n\n"
                   + "Select a port number for the web server.\n\n",
               Integer.toString(defPort));
       try {
         userPort = Integer.parseInt(port.trim());
       } catch (Exception ex) {
         userPort = -1;
       }
       if ((userPort < 80) || (userPort > 32767)) userPort = 0;
     }
     return userPort;
   } else {
     try {
       Document doc = getDocument(config);
       Element root = doc.getDocumentElement();
       Element server = getFirstNamedChild(root, "Server");
       String port = server.getAttribute("port");
       return -Integer.parseInt(port);
     } catch (Exception ex) {
     }
   }
   return 0;
 }
示例#14
0
  protected boolean executeUploadCommand(Collection commandDownloader) throws RunnerException {
    firstErrorFound = false; // haven't found any errors yet
    secondErrorFound = false;
    notFoundError = false;
    int result = 0; // pre-initialized to quiet a bogus warning from jikes

    String userdir = System.getProperty("user.dir") + File.separator;

    try {
      String[] commandArray = new String[commandDownloader.size()];
      commandDownloader.toArray(commandArray);

      String avrBasePath;

      if (Base.isLinux()) {
        avrBasePath = new String(Base.getHardwarePath() + "/tools/");
      } else {
        avrBasePath = new String(Base.getHardwarePath() + "/tools/avr/bin/");
      }

      commandArray[0] = avrBasePath + commandArray[0];

      if (verbose || Preferences.getBoolean("upload.verbose")) {
        for (int i = 0; i < commandArray.length; i++) {
          System.out.print(commandArray[i] + " ");
        }
        System.out.println();
      }
      Process process = Runtime.getRuntime().exec(commandArray);
      new MessageSiphon(process.getInputStream(), this);
      new MessageSiphon(process.getErrorStream(), this);

      // wait for the process to finish.  if interrupted
      // before waitFor returns, continue waiting
      //
      boolean compiling = true;
      while (compiling) {
        try {
          result = process.waitFor();
          compiling = false;
        } catch (InterruptedException intExc) {
        }
      }
      if (exception != null) {
        exception.hideStackTrace();
        throw exception;
      }
      if (result != 0) return false;
    } catch (Exception e) {
      String msg = e.getMessage();
      if ((msg != null)
          && (msg.indexOf("uisp: not found") != -1)
          && (msg.indexOf("avrdude: not found") != -1)) {
        // System.err.println("uisp is missing");
        // JOptionPane.showMessageDialog(editor.base,
        //                              "Could not find the compiler.\n" +
        //                              "uisp is missing from your PATH,\n" +
        //                              "see readme.txt for help.",
        //                              "Compiler error",
        //                              JOptionPane.ERROR_MESSAGE);
        return false;
      } else {
        e.printStackTrace();
        result = -1;
      }
    }
    // System.out.println("result2 is "+result);
    // if the result isn't a known, expected value it means that something
    // is fairly wrong, one possibility is that jikes has crashed.
    //
    if (exception != null) throw exception;

    if ((result != 0) && (result != 1)) {
      exception = new RunnerException(SUPER_BADNESS);
      // editor.error(exception);
      // PdeBase.openURL(BUGS_URL);
      // throw new PdeException(SUPER_BADNESS);
    }

    return (result == 0); // ? true : false;
  }
示例#15
0
文件: Installer.java 项目: suever/CTP
  /**
   * Class constructor; creates a new Installer object, displays a JFrame introducing the program,
   * allows the user to select an install directory, and copies files from the jar into the
   * directory.
   */
  public Installer(String args[]) {
    // Inputs are --install-dir INSTALL_DIR
    for (int k = 0; k < args.length; k = k + 2) {

      switch (args[k]) {
        case "--install-dir":
          directory = new File(args[k + 1]);
          System.out.println(directory);
          break;
        case "--port":
          port = Integer.parseInt(args[k + 1]);
          break;
      }
    }

    cp = new Stream();

    // Find the installer program so we can get to the files.
    installer = getInstallerProgramFile();
    String name = installer.getName();
    programName = (name.substring(0, name.indexOf("-"))).toUpperCase();

    // Get the installation information
    thisJava = System.getProperty("java.version");
    thisJavaBits = System.getProperty("sun.arch.data.model") + " bits";

    // Find the ImageIO Tools and get the version
    String javaHome = System.getProperty("java.home");
    File extDir = new File(javaHome);
    extDir = new File(extDir, "lib");
    extDir = new File(extDir, "ext");
    File clib = getFile(extDir, "clibwrapper_jiio", ".jar");
    File jai = getFile(extDir, "jai_imageio", ".jar");
    imageIOTools = (clib != null) && clib.exists() && (jai != null) && jai.exists();
    if (imageIOTools) {
      Hashtable<String, String> jaiManifest = getManifestAttributes(jai);
      imageIOVersion = jaiManifest.get("Implementation-Version");
    }

    // Get the CTP.jar parameters
    Hashtable<String, String> manifest = getJarManifestAttributes("/CTP/libraries/CTP.jar");
    programDate = manifest.get("Date");
    buildJava = manifest.get("Java-Version");

    // Get the util.jar parameters
    Hashtable<String, String> utilManifest = getJarManifestAttributes("/CTP/libraries/util.jar");
    utilJava = utilManifest.get("Java-Version");

    // Get the MIRC.jar parameters (if the plugin is present)
    Hashtable<String, String> mircManifest = getJarManifestAttributes("/CTP/libraries/MIRC.jar");
    if (mircManifest != null) {
      mircJava = mircManifest.get("Java-Version");
      mircDate = mircManifest.get("Date");
      mircVersion = mircManifest.get("Version");
    }

    // Set up the installation information for display
    if (imageIOVersion.equals("")) {
      imageIOVersion = "<b><font color=\"red\">not installed</font></b>";
    } else if (imageIOVersion.startsWith("1.0")) {
      imageIOVersion = "<b><font color=\"red\">" + imageIOVersion + "</font></b>";
    }
    if (thisJavaBits.startsWith("64")) {
      thisJavaBits = "<b><font color=\"red\">" + thisJavaBits + "</font></b>";
    }
    boolean javaOK = (thisJava.compareTo(buildJava) >= 0);
    javaOK &= (thisJava.compareTo(utilJava) >= 0);
    javaOK &= (thisJava.compareTo(mircJava) >= 0);
    if (!javaOK) {
      thisJava = "<b><font color=\"red\">" + thisJava + "</font></b>";
    }

    if (directory == null) exit();

    // Point to the parent of the directory in which to install the program.
    // so the copy process works correctly for directory trees.
    //
    // If the user has selected a directory named "CTP",
    // then assume that this is the directory in which
    // to install the program.
    //
    // If the directory is not CTP, see if it is called "RSNA" and contains
    // the Launcher program, in which case we can assume that it is an
    // installation that was done with Bill Weadock's all-in-one installer for Windows.
    //
    // If neither of those cases is true, then this is already the parent of the
    // directory in which to install the program
    if (directory.getName().equals("CTP")) {
      directory = directory.getParentFile();
    } else if (directory.getName().equals("RSNA")
        && (new File(directory, "Launcher.jar")).exists()) {
      suppressFirstPathElement = true;
    }

    // Cleanup old releases
    cleanup(directory);

    // Get a port for the server.
    if (port < 0) {
      if (checkServer(-port, false)) {
        System.err.println(
            "CTP appears to be running.\nPlease stop CTP and run the installer again.");
        System.exit(0);
      }
    }

    // Now install the files and report the results.
    int count =
        unpackZipFile(installer, "CTP", directory.getAbsolutePath(), suppressFirstPathElement);
    if (count > 0) {
      // Create the service installer batch files.
      updateWindowsServiceInstaller();
      updateLinuxServiceInstaller();

      // If this was a new installation, set up the config file and set the port
      installConfigFile(port);

      // Make any necessary changes in the config file to reflect schema evolution
      fixConfigSchema();

      System.out.println("Installation complete.");
      System.out.println(programName + " has been installed successfully.");
      System.out.println(count + " files were installed.");
    } else {
      System.err.println("Installation failed.");
      System.err.println(programName + " could not be fully installed.");
    }
    if (!programName.equals("ISN") && startRunner(new File(directory, "CTP"))) System.exit(0);
  }
示例#16
0
 public static String getPath(String path) {
   if (path == null) return null;
   return path.replaceAll("\\\\|/", "\\" + System.getProperty("file.separator"));
 }
示例#17
0
  public static void main(String[] args) throws Exception {
    boolean isInteractive = false;
    classUrl = MynaInstaller.class.getResource("MynaInstaller.class").toString();
    isJar = (classUrl.indexOf("jar") == 0);
    if (!isJar) {
      System.err.println("Installer can only be run from inside a Myna distribution war file");
      System.exit(1);
    }

    Thread.sleep(1000);

    Console console = System.console();
    String response = null;
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();
    options.addOption(
        "c", "context", true, "Webapp context. Must Start with \"/\" Default: " + webctx);
    options.addOption("h", "help", false, "Displays help.");
    options.addOption(
        "w",
        "webroot",
        true,
        "Webroot to use. Will be created if webroot/WEB-INF does not exist. Default: " + webroot);
    options.addOption(
        "l",
        "logfile",
        true,
        "Log file to use. Will be created if it does not exist. Default: ./<context>.log");
    options.addOption(
        "s",
        "servername",
        true,
        "Name of this instance. Will also be the name of the init script. Defaults to either \"myna\" or the value of <context> if defined");
    // options.addOption( "P", "purpose", true, "Purpose of the Server, such as DEV,PROD,TRAIN, etc.
    // Defaults to DEV" );

    options.addOption("p", "port", true, "HTTP port. Set to 0 to disable HTTP. Default: " + port);
    options.addOption(
        "sp", "ssl-port", true, "SSL (HTTPS) port. Set to 0 to disable SSL, Default: 0");

    options.addOption(
        "ks", "keystore", true, "keystore path. Default: <webroot>/WEB-INF/myna/myna_keystore");
    options.addOption("ksp", "ks-pass", true, "keystore password. Default: " + ksPass);
    options.addOption("ksa", "ks-alias", true, "certificate alias. Default: " + ksAlias);

    modeOptions.add("upgrade");
    modeOptions.add("install");
    options.addOption(
        "m",
        "mode",
        true,
        "Mode: one of "
            + modeOptions.toString()
            + ". \n"
            + "\"upgrade\": Upgrades myna installation in webroot and exits. "
            + "\"install\": Unpacks to webroot, and installs startup files");
    options.addOption(
        "u",
        "user",
        true,
        "User to own and run the Myna installation. Only applies to unix installs. Default: nobody");

    HelpFormatter formatter = new HelpFormatter();

    String cmdSyntax = "java -jar myna-X.war -m <mode> [options]";
    try {
      CommandLine line = parser.parse(options, args);
      Option option;
      if (args.length == 0) {
        formatter.printHelp(cmdSyntax, options);
        response = console.readLine("\nContinue with Interactive Install? (y/N)");
        if (response.toLowerCase().equals("y")) {
          isInteractive = true;

        } else System.exit(1);
      }
      // Help
      if (line.hasOption("help")) {
        formatter.printHelp(cmdSyntax, options);
        System.exit(1);
      }
      // mode
      if (line.hasOption("mode")) {
        mode = line.getOptionValue("mode");
        if (!modeOptions.contains(mode)) {
          System.err.println(
              "Invalid Arguments.  Reason: Mode must be in " + modeOptions.toString());
          formatter.printHelp(cmdSyntax, options);
          System.exit(1);
        }
      } else if (isInteractive) {
        option = options.getOption("mode");
        console.printf("\n" + option.getDescription());

        do {
          response = console.readLine("\nEnter " + option.getLongOpt() + "(" + mode + "): ");
          if (!response.isEmpty()) mode = response;
        } while (!modeOptions.contains(mode));
      }
      // webroot
      if (line.hasOption("webroot")) {
        webroot = line.getOptionValue("webroot");
      } else if (isInteractive) {
        option = options.getOption("webroot");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + webroot + "): ");
        if (!response.isEmpty()) webroot = response;
      }
      // port
      if (line.hasOption("port")) {
        port = Integer.parseInt(line.getOptionValue("port"));
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("port");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + port + "): ");
        if (!response.isEmpty()) port = Integer.parseInt(response);
      }
      // context
      if (line.hasOption("context")) {
        webctx = line.getOptionValue("context");

      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("context");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + webctx + "): ");
        if (!response.isEmpty()) webctx = response;
      }
      if (!webctx.startsWith("/")) {
        webctx = "/" + webctx;
      }
      // servername (depends on context)
      if (!webctx.equals("/")) {
        serverName = webctx.substring(1);
      }
      if (line.hasOption("servername")) {
        serverName = line.getOptionValue("servername");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("servername");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + serverName + "): ");
        if (!response.isEmpty()) serverName = response;
      }
      // user
      if (line.hasOption("user")) {
        user = line.getOptionValue("user");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("user");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + user + "): ");
        if (!response.isEmpty()) user = response;
      }
      // logfile
      logFile = "myna.log";
      if (!webctx.equals("/")) {
        logFile = webctx.substring(1) + ".log";
      }
      if (line.hasOption("logfile")) {
        logFile = line.getOptionValue("logfile");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("logfile");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "path(" + logFile + "): ");
        if (!response.isEmpty()) logFile = response;
      }

      // ssl-port
      if (line.hasOption("ssl-port")) {
        sslPort = Integer.parseInt(line.getOptionValue("ssl-port"));
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("ssl-port");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + sslPort + "): ");
        if (!response.isEmpty()) sslPort = Integer.parseInt(response);
      }
      // ks-pass
      if (line.hasOption("ks-pass")) {
        ksPass = line.getOptionValue("ks-pass");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("ks-pass");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + ksPass + "): ");
        if (!response.isEmpty()) ksPass = response;
      }
      // ks-alias
      if (line.hasOption("ks-alias")) {
        ksAlias = line.getOptionValue("ks-alias");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("ks-alias");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + ksAlias + "): ");
        if (!response.isEmpty()) ksAlias = response;
      }
      // keystore
      String appBase = new File(webroot).getCanonicalPath();
      if (keystore == null) {
        keystore = appBase + "/WEB-INF/myna/myna_keystore";
      }
      if (line.hasOption("keystore")) {
        keystore = line.getOptionValue("keystore");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("keystore");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + keystore + "): ");
        if (!response.isEmpty()) keystore = response;
      }

      javaOpts = line.getArgList();
    } catch (ParseException exp) {
      System.err.println("Invalid Arguments.	Reason: " + exp.getMessage());

      formatter.printHelp(cmdSyntax, options);
      System.exit(1);
    }

    if (isInteractive) {
      System.out.println("\nProceeed with the following settings?:\n");
      System.out.println("mode        = " + mode);
      System.out.println("webroot     = " + webroot);
      if (mode.equals("install")) {
        System.out.println("port        = " + port);
        System.out.println("context     = " + webctx);
        System.out.println("servername  = " + serverName);
        System.out.println("user        = "******"logfile     = " + logFile);
        System.out.println("ssl-port    = " + sslPort);
        System.out.println("ks-pass     = "******"ks-alias    = " + ksAlias);
        System.out.println("keystore    = " + keystore);
      }
      response = console.readLine("Continue? (Y/n)");
      if (response.toLowerCase().equals("n")) System.exit(1);
    }
    File wrFile = new File(webroot);
    webroot = wrFile.toString();
    if (mode.equals("install")) {
      adminPassword = console.readLine("\nCreate an Admin password for this installation: ");
    }
    // unpack myna if necessary
    if (!wrFile.exists() || mode.equals("upgrade") || mode.equals("install")) {
      upgrade(wrFile);
    }

    if (mode.equals("install")) {
      File propertiesFile = new File(wrFile.toURI().resolve("WEB-INF/classes/general.properties"));
      FileInputStream propertiesFileIS = new FileInputStream(propertiesFile);
      Properties generalProperties = new Properties();
      generalProperties.load(propertiesFileIS);
      propertiesFileIS.close();
      if (!adminPassword.isEmpty()) {
        org.jasypt.util.password.StrongPasswordEncryptor cryptTool =
            new org.jasypt.util.password.StrongPasswordEncryptor();
        generalProperties.setProperty("admin_password", cryptTool.encryptPassword(adminPassword));
      }
      generalProperties.setProperty("instance_id", serverName);

      generalProperties.store(
          new java.io.FileOutputStream(propertiesFile), "Myna General Properties");

      String javaHome = System.getProperty("java.home");
      webroot = new File(webroot).getCanonicalPath();
      if (serverName.length() == 0) serverName = "myna";
      if (java.lang.System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
        if (!new File(logFile).isAbsolute()) {
          logFile = new File(wrFile.toURI().resolve("WEB-INF/" + logFile)).toString();
        }
        File templateFile =
            new File(
                wrFile.toURI().resolve("WEB-INF/myna/install/windows/update_myna_service.cmd"));

        String initScript =
            FileUtils.readFileToString(templateFile)
                .replaceAll("\\{webctx\\}", webctx)
                .replaceAll("\\{server\\}", Matcher.quoteReplacement(serverName))
                .replaceAll("\\{webroot\\}", Matcher.quoteReplacement(webroot))
                .replaceAll("\\{logfile\\}", Matcher.quoteReplacement(logFile))
                .replaceAll("\\{javahome\\}", Matcher.quoteReplacement(javaHome))
                .replaceAll("\\{port\\}", new Integer(port).toString())
                .replaceAll("\\{sslPort\\}", new Integer(sslPort).toString())
                .replaceAll("\\{keystore\\}", Matcher.quoteReplacement(keystore))
                .replaceAll("\\{ksPass\\}", Matcher.quoteReplacement(ksPass))
                .replaceAll("\\{ksAlias\\}", Matcher.quoteReplacement(ksAlias));

        File scriptFile =
            new File(wrFile.toURI().resolve("WEB-INF/myna/install/update_myna_service.cmd"));

        FileUtils.writeStringToFile(scriptFile, initScript);

        // Runtime.getRuntime().exec("cmd /c start " + scriptFile.toString()).waitFor();

        System.out.println(
            "\nInstalled Service 'Myna App Server " + serverName + "' the following settings:\n");
        System.out.println(
            "\nInit script '" + scriptFile + "' created with the following settings:\n");
        System.out.println("memory=256MB");
        System.out.println("serverName=" + serverName);
        System.out.println("javaHome=" + javaHome);
        System.out.println("context=" + webctx);
        System.out.println("port=" + port);
        System.out.println("myna_home=" + webroot);
        System.out.println("logfile=" + logFile);

        System.out.println("sslPort=" + sslPort);
        System.out.println("keyStore=" + keystore);
        System.out.println("ksPass="******"ksAlias=" + ksAlias);

        System.out.println(
            "\nEdit and and run the command file in " + scriptFile + " to update this service");

      } else {
        String curUser = java.lang.System.getProperty("user.name");
        if (!curUser.equals("root")) {
          System.out.println("Install mode must be run as root.");
          System.exit(1);
        }

        if (!new File(logFile).isAbsolute()) {
          logFile = new File(wrFile.toURI().resolve("WEB-INF/" + logFile)).toString();
        }
        File templateFile =
            new File(wrFile.toURI().resolve("WEB-INF/myna/install/linux/init_script"));
        String initScript =
            FileUtils.readFileToString(templateFile)
                .replaceAll("\\{webctx\\}", webctx)
                .replaceAll("\\{server\\}", serverName)
                .replaceAll("\\{user\\}", user)
                .replaceAll("\\{webroot\\}", webroot)
                .replaceAll("\\{javahome\\}", javaHome)
                .replaceAll("\\{logfile\\}", logFile)
                .replaceAll("\\{port\\}", new Integer(port).toString())
                .replaceAll("\\{sslPort\\}", new Integer(sslPort).toString())
                .replaceAll("\\{keystore\\}", keystore)
                .replaceAll("\\{ksPass\\}", ksPass)
                .replaceAll("\\{ksAlias\\}", ksAlias);

        File scriptFile = new File(wrFile.toURI().resolve("WEB-INF/myna/install/" + serverName));

        FileUtils.writeStringToFile(scriptFile, initScript);

        if (new File("/etc/init.d").exists()) {

          exec("chown  -R " + user + " " + webroot);
          exec("chown root " + scriptFile.toString());
          exec("chmod 700 " + scriptFile.toString());
          exec("cp " + scriptFile.toString() + " /etc/init.d/");

          System.out.println(
              "\nInit script '/etc/init.d/"
                  + serverName
                  + "' created with the following settings:\n");
        } else {
          System.out.println(
              "\nInit script '" + scriptFile + "' created with the following settings:\n");
        }

        System.out.println("user="******"memory=256MB");
        System.out.println("server=" + serverName);
        System.out.println("context=" + webctx);
        System.out.println("port=" + port);
        System.out.println("myna_home=" + webroot);
        System.out.println("logfile=" + logFile);

        System.out.println("sslPort=" + sslPort);
        System.out.println("keyStore=" + keystore);
        System.out.println("ksPass="******"ksAlias=" + ksAlias);

        System.out.println("\nEdit this file to customize startup behavior");
      }
    }
  }
  /** The run method. */
  public void run() {
    instances.add(this);
    try {
      listener.startUnpack();
      String currentOs = System.getProperty("os.name").toLowerCase();
      //
      // Initialisations
      FileOutputStream out = null;
      ArrayList parsables = new ArrayList();
      ArrayList executables = new ArrayList();
      List packs = idata.selectedPacks;
      int npacks = packs.size();
      udata = UninstallData.getInstance();

      // Specific to the web installers
      if (idata.kind.equalsIgnoreCase("web") || idata.kind.equalsIgnoreCase("web-kunststoff")) {
        InputStream kin = getClass().getResourceAsStream("/res/WebInstallers.url");
        BufferedReader kreader = new BufferedReader(new InputStreamReader(kin));
        jarLocation = kreader.readLine();
      }

      // We unpack the selected packs
      for (int i = 0; i < npacks; i++) {
        // We get the pack stream
        int n = idata.allPacks.indexOf(packs.get(i));
        ObjectInputStream objIn = new ObjectInputStream(getPackAsStream(n));

        // We unpack the files
        int nfiles = objIn.readInt();
        listener.changeUnpack(0, nfiles, ((Pack) packs.get(i)).name);
        for (int j = 0; j < nfiles; j++) {
          // We read the header
          PackFile pf = (PackFile) objIn.readObject();
          if (null == pf.os || matchOS(currentOs, pf.os.toLowerCase())) {
            // We translate & build the path
            String path = translatePath(pf.targetPath);
            File pathFile = new File(path);
            String fname = pathFile.getName();
            int z = fname.length();
            File dest = pathFile.getParentFile();
            if (!dest.exists()) dest.mkdirs();

            // We add the path to the log,
            udata.addFile(path);

            listener.progressUnpack(j, path);

            // if this file exists and shouldnot override skip this file
            if (((pf.override == false) && (pathFile.exists()))) {
              objIn.skip(pf.length);
              continue;
            }

            // We copy the file
            out = new FileOutputStream(path);
            byte[] buffer = new byte[5120];
            long bytesCopied = 0;
            while (bytesCopied < pf.length) {
              int maxBytes =
                  (pf.length - bytesCopied < buffer.length
                      ? (int) (pf.length - bytesCopied)
                      : buffer.length);
              int bytesInBuffer = objIn.read(buffer, 0, maxBytes);
              if (bytesInBuffer == -1) throw new IOException("Unexpected end of stream");

              out.write(buffer, 0, bytesInBuffer);

              bytesCopied += bytesInBuffer;
            }
            // Cleanings
            out.close();

            // Empty dirs restoring
            String _n = pathFile.getName();
            if (_n.startsWith("izpack-keepme") && _n.endsWith(".tmp")) pathFile.delete();

          } else objIn.skip(pf.length);
        }

        // Load information about parsable files
        int numParsables = objIn.readInt();
        int k;
        for (k = 0; k < numParsables; k++) {
          ParsableFile pf = (ParsableFile) objIn.readObject();
          pf.path = translatePath(pf.path);
          parsables.add(pf);
        }

        // Load information about executable files
        int numExecutables = objIn.readInt();
        for (k = 0; k < numExecutables; k++) {
          ExecutableFile ef = (ExecutableFile) objIn.readObject();
          ef.path = translatePath(ef.path);
          if (null != ef.argList && !ef.argList.isEmpty()) {
            String arg = null;
            for (int j = 0; j < ef.argList.size(); j++) {
              arg = (String) ef.argList.get(j);
              arg = translatePath(arg);
              ef.argList.set(j, arg);
            }
          }
          executables.add(ef);
          if (ef.executionStage == ExecutableFile.UNINSTALL) {
            udata.addExecutable(ef);
          }
        }
        objIn.close();
      }

      // We use the scripts parser
      ScriptParser parser = new ScriptParser(parsables, vs);
      parser.parseFiles();

      // We use the file executor
      FileExecutor executor = new FileExecutor(executables);
      if (executor.executeFiles(ExecutableFile.POSTINSTALL) != 0)
        javax.swing.JOptionPane.showMessageDialog(
            null,
            "The installation was not completed.",
            "Installation warning",
            javax.swing.JOptionPane.WARNING_MESSAGE);

      // We put the uninstaller
      putUninstaller();

      // The end :-)
      listener.stopUnpack();
    } catch (Exception err) {
      listener.stopUnpack();
      listener.errorUnpack(err.toString());
    }
    instances.remove(instances.indexOf(this));
  }