Ejemplo n.º 1
0
    private static void configureTransportFactory(
        ITransportFactory transportFactory, LoaderOptions opts) {
      Map<String, String> options = new HashMap<>();
      // If the supplied factory supports the same set of options as our SSL impl, set those
      if (transportFactory.supportedOptions().contains(SSLTransportFactory.TRUSTSTORE))
        options.put(SSLTransportFactory.TRUSTSTORE, opts.encOptions.truststore);
      if (transportFactory.supportedOptions().contains(SSLTransportFactory.TRUSTSTORE_PASSWORD))
        options.put(SSLTransportFactory.TRUSTSTORE_PASSWORD, opts.encOptions.truststore_password);
      if (transportFactory.supportedOptions().contains(SSLTransportFactory.PROTOCOL))
        options.put(SSLTransportFactory.PROTOCOL, opts.encOptions.protocol);
      if (transportFactory.supportedOptions().contains(SSLTransportFactory.CIPHER_SUITES))
        options.put(
            SSLTransportFactory.CIPHER_SUITES, Joiner.on(',').join(opts.encOptions.cipher_suites));

      if (transportFactory.supportedOptions().contains(SSLTransportFactory.KEYSTORE)
          && opts.encOptions.require_client_auth)
        options.put(SSLTransportFactory.KEYSTORE, opts.encOptions.keystore);
      if (transportFactory.supportedOptions().contains(SSLTransportFactory.KEYSTORE_PASSWORD)
          && opts.encOptions.require_client_auth)
        options.put(SSLTransportFactory.KEYSTORE_PASSWORD, opts.encOptions.keystore_password);

      // Now check if any of the factory's supported options are set as system properties
      for (String optionKey : transportFactory.supportedOptions())
        if (System.getProperty(optionKey) != null)
          options.put(optionKey, System.getProperty(optionKey));

      transportFactory.setOptions(options);
    }
Ejemplo n.º 2
0
  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");
    }
  }
  @Override
  public int run(String[] args) throws Exception {
    CommandLine cmd = getCommand(args);
    DistCpOptions options = getDistCpOptions(cmd);

    Configuration conf = this.getConf();
    // inject wf configs
    Path confPath = new Path("file:///" + System.getProperty("oozie.action.conf.xml"));

    LOG.info(confPath + " found conf ? " + confPath.getFileSystem(conf).exists(confPath));
    conf.addResource(confPath);

    String falconFeedStorageType = cmd.getOptionValue("falconFeedStorageType").trim();
    Storage.TYPE feedStorageType = Storage.TYPE.valueOf(falconFeedStorageType);

    DistCp distCp =
        (feedStorageType == Storage.TYPE.FILESYSTEM)
            ? new CustomReplicator(conf, options)
            : new DistCp(conf, options);
    LOG.info("Started DistCp");
    distCp.execute();

    if (feedStorageType == Storage.TYPE.FILESYSTEM) {
      executePostProcessing(options); // this only applies for FileSystem Storage.
    }

    LOG.info("Completed DistCp");
    return 0;
  }
Ejemplo n.º 4
0
  /**
   * Initialises the FeatureExtractor from a set of parameters, for example sent as command-line
   * arguments
   *
   * @param args The list of arguments
   */
  public FeatureExtractorSimple(String[] args) {
    workDir = System.getProperty("user.dir");
    new Logger("log.txt");
    parseArguments(args);

    input = workDir + File.separator + resourceManager.getString("input");
    output = workDir + File.separator + resourceManager.getString("output");
    System.out.println("input=" + input + "  output=" + output);
  }
Ejemplo n.º 5
0
 private String getSQLiteDir() {
   File current;
   current = new File(System.getProperty("user.dir"));
   while (!current.getName().equals("Hercules")) {
     current = current.getParentFile();
   }
   return current.getParent()
       + File.separator
       + "TypeChef-SQLiteIfdeftoif"
       + File.separator
       + "optionstructs_ifdeftoif";
 }
Ejemplo n.º 6
0
 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");
       }
     }
   }
 }
Ejemplo n.º 7
0
  /**
   * Runs the initArgs and go methods.
   *
   * @param args Command line arg vector
   */
  public final void run(final String[] args) {
    int exitCode = 1; // pessimistic initial value

    try {
      parseArgs(args);
      executeAction();
      exitCode = 0;
    } catch (Throwable t) {
      if (null == t.getMessage()
          || verbose
          || "true".equals(System.getProperty("rdeck.traceExceptions"))) {
        t.printStackTrace();
      } else {
        error(t);
      }
    }
    exit(exitCode);
  }
Ejemplo n.º 8
0
 // 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;
 }
Ejemplo n.º 9
0
  /**
   * 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);
  }
Ejemplo n.º 10
0
/** Created by muyux on 2016/1/11. */
public class Main {
  static String FILE_SEPARATOR = System.getProperty("file.separator");

  private static String[] getStopWords(String path) {
    try {
      List<String> list = FileUtils.readLines(new File(path), "utf-8");
      System.out.println("==============================================================");
      System.out.println("getStopWords " + list.get(159));
      System.out.println("==============================================================");
      return list.toArray(new String[list.size()]);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
    }
    return null;
  }

  private static void index_h(String prefix, File file, IndexWriter indexWriter)
      throws IOException {
    Document doc = null;

    if (file.isDirectory()) {
      File files[] = file.listFiles();
      for (File file1 : files) {
        index_h(prefix + FILE_SEPARATOR + file.getName(), file1, indexWriter);
      }
    } else {
      String content = FileUtils.readFileToString(file, "utf-8");

      System.out.println("==============================================================");
      System.out.println("index_h " + content);
      System.out.println("==============================================================");

      String filename = prefix + FILE_SEPARATOR + file.getName();
      String path = file.getAbsolutePath();

      doc = new Document();
      doc.add(new Field("content", content, Field.Store.YES, Field.Index.ANALYZED));
      doc.add(new Field("relative_path", filename, Field.Store.YES, Field.Index.NOT_ANALYZED));
      indexWriter.addDocument(doc);
    }
  }

  private static Directory index(Analyzer analyzer, String processingPath) {
    RAMDirectory directory = null;
    IndexWriter indexWriter = null;
    try {
      directory = new RAMDirectory();
      IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_35, analyzer);
      indexWriter = new IndexWriter(directory, iwc);
      File file = new File(processingPath);
      index_h("", file, indexWriter);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (indexWriter != null) {
        try {
          indexWriter.close();
        } catch (CorruptIndexException e1) {
          // TODO Auto-generated catch block
          e1.printStackTrace();
        } catch (IOException e1) {
          // TODO Auto-generated catch block
          e1.printStackTrace();
        }
      }
    }

    return directory;
  }

  private static Map<String, List<String>> generate_result(Directory directory) {
    Map<String, List<String>> result_map = new HashMap<String, List<String>>();

    try {
      IndexReader reader = IndexReader.open(directory);
      TermEnum termEnum = reader.terms();
      while (termEnum.next()) {
        String termEnumString = termEnum.term().toString();
        if (termEnumString.startsWith("content:")) {
          String term = termEnumString.substring(termEnumString.lastIndexOf(":") + 1);
          TermDocs termDocs = reader.termDocs(termEnum.term());
          while (termDocs.next()) {
            Document doc = reader.document(termDocs.doc());
            String relative_path = doc.get("relative_path");

            if (result_map.containsKey(relative_path)) {
              result_map.get(relative_path).add(term + termDocs.freq());
            } else {
              result_map.put(relative_path, new ArrayList<String>());
            }
          }
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
    }

    return result_map;
  }

  public static void main(String[] args) {

    String formatstr = "ws [--in][--out][--dd][--sw][-h]";
    Options opt = new Options();
    // opt.addOption(OptionBuilder.withArgName("in").hasArg().withDescription("search for buildfile
    // towards the root of the filesystem and use it").create("O"));
    opt.addOption(
        OptionBuilder.withLongOpt("in")
            .withDescription("file path of those files need to be processed")
            .withValueSeparator('=')
            .hasArg()
            .create());
    opt.addOption(
        OptionBuilder.withLongOpt("out")
            .withDescription("file path to store result")
            .withValueSeparator('=')
            .hasArg()
            .create());
    opt.addOption(
        OptionBuilder.withLongOpt("dd")
            .withDescription("file path of dictionary")
            .withValueSeparator('=')
            .hasArg()
            .create());
    opt.addOption(
        OptionBuilder.withLongOpt("sw")
            .withDescription("file path of stop words")
            .withValueSeparator('=')
            .hasArg()
            .create());
    opt.addOption("h", "help", false, "print help for the command.");

    if (args.length == 0) {
      HelpFormatter hf = new HelpFormatter();
      hf.printHelp(formatstr, "", opt, "");
      return;
    } else {
      parse_args(args, formatstr, opt);
    }
  }

  private static void parse_args(String[] args, String formatstr, Options opt) {
    HelpFormatter formatter = new HelpFormatter();
    CommandLineParser parser = new PosixParser();
    CommandLine cl = null;

    try {
      cl = parser.parse(opt, args);
    } catch (ParseException e) {
      formatter.printHelp(formatstr, opt); // 如果发生异常,则打印出帮助信息
    }

    if (cl.hasOption("in") && cl.hasOption("out") && cl.hasOption("dd") && cl.hasOption("sw")) {
      String stopWordsPath = cl.getOptionValue("sw");
      String inPath = cl.getOptionValue("in");
      String outPath = cl.getOptionValue("out");
      String dicPath = cl.getOptionValue("dd");
      processOperation(stopWordsPath, inPath, outPath, dicPath);
    } else {
      HelpFormatter hf = new HelpFormatter();
      hf.printHelp(formatstr, "", opt, "");
      return;
    }
  }

  private static void processOperation(
      String stopWordsPath, String inPath, String outPath, String dicPath) {
    Analyzer analyzer = new MyMMSegAnalyzer(new File(dicPath), getStopWords(stopWordsPath));
    Directory directory = index(analyzer, inPath);
    Map<String, List<String>> result_map = generate_result(directory);
    output_result(outPath, result_map);
  }

  private static void output_result(String outPath, Map<String, List<String>> result_map) {
    for (String s : result_map.keySet()) {
      try {
        FileUtils.writeLines(new File(outPath + s), result_map.get(s));
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}
 String userPath() {
   return System.getProperty("user.dir");
 }
Ejemplo n.º 12
0
  /** loads [additional] policies from commandline (either -p or -f) */
  private void loadCLPolicies() {
    // we already checked to make sure we have one of the options avaliable
    File pLoc = null;
    PolicyObject p = null;

    if (genProps.getProperty("p3pLocation", null) != null) {
      pLoc = new File(genProps.getProperty("p3pLocation"));
      if (!pLoc.exists()) {
        System.err.println(
            "no file found at p3p policy location specified by the -p3p option: "
                + genProps.getProperty("p3pLocation"));
        System.err.println("current location is " + System.getProperty("user.dir"));
        System.exit(1);
      }
      try {
        p = (new P3PParser()).parse(pLoc.getAbsolutePath());
        if (p.getContextDomain() == null) {
          p.setContext(
              new Context(
                  new Date(System.currentTimeMillis()),
                  new Date(System.currentTimeMillis()),
                  genProps.getProperty("p3pLocation")));
        }
        pdb.addPolicy(p);
      } catch (Exception e) {
        System.err.println("Error with parsing or database");
        e.printStackTrace();
        // System.exit(5);
      }
    }
    if (genProps.getProperty("p3pDirLocation", null) != null) {
      pLoc = new File(genProps.getProperty("p3pDirLocation"));
      File[] pfiles = pLoc.listFiles();

      // System.err.println("pfiles for p3pDirLocation: "+pfiles);
      for (int i = 0; i < pfiles.length; i++) {

        pLoc = (pfiles[i]);
        if (!pLoc.exists()) {
          System.err.println(
              "no file found at p3p policy location specified by the -p3pDirLocation option, "
                  + genProps.getProperty("p3pDirLocation"));
          System.exit(1);
        }
        try {

          p = (new P3PParser()).parse(pLoc.getAbsolutePath());
          if (p.getContext().getDomain() == null) {
            p.setContext(
                new Context(
                    new Date(System.currentTimeMillis()),
                    new Date(System.currentTimeMillis()),
                    pfiles[i].getAbsolutePath()));
          }
          pdb.addPolicy(p);
        } catch (Exception e) {
          System.err.println("Einar needs to fix this parsing error.");
          e.printStackTrace();
        }
      }
    }
  }
  public static void main(String[] args) {
    String logConfig = System.getProperty("log-config");
    if (logConfig == null) {
      logConfig = "log-config.txt";
    }

    Options options = new Options();
    options.addOption("h", "help", false, "print this message");
    options.addOption("v", "version", false, "output version information and exit");
    options.addOption(OptionBuilder.withDescription("trace mode").withLongOpt("trace").create());
    options.addOption(OptionBuilder.withDescription("debug mode").withLongOpt("debug").create());
    options.addOption(OptionBuilder.withDescription("info mode").withLongOpt("info").create());
    options.addOption(
        OptionBuilder.withArgName("file")
            .hasArg()
            .withDescription(
                "file from which to read the labelled training set in tabular format (reference annotation)")
            .isRequired()
            .withLongOpt("labelled")
            .create("l"));
    options.addOption(
        OptionBuilder.withArgName("file")
            .hasArg()
            .withDescription(
                "file from which to read the translated unlabelled training set in tabular format (one sentence per line, including id)")
            .isRequired()
            .withLongOpt("unlabelled")
            .create("u"));
    options.addOption(
        OptionBuilder.withArgName("file")
            .hasArg()
            .withDescription(
                "file from which to read the translated roles (phrase table: source language \\t target language)")
            .isRequired()
            .withLongOpt("roles")
            .create("r"));
    options.addOption(
        OptionBuilder.withArgName("file")
            .hasArg()
            .withDescription(
                "file in which to write the translated labelled training set in tabular format (aligned with the reference annotation)")
            .isRequired()
            .withLongOpt("output")
            .create("o"));
    options.addOption(
        OptionBuilder.withArgName("int")
            .hasArg()
            .withDescription("example from which to start from")
            .withLongOpt("start")
            .create());

    CommandLineParser parser = new PosixParser();
    CommandLine commandLine = null;

    try {
      commandLine = parser.parse(options, args);

      Properties defaultProps = new Properties();
      try {
        defaultProps.load(new InputStreamReader(new FileInputStream(logConfig), "UTF-8"));
      } catch (Exception e) {
        defaultProps.setProperty("log4j.appender.stdout", "org.apache.log4j.ConsoleAppender");
        defaultProps.setProperty(
            "log4j.appender.stdout.layout.ConversionPattern", "[%t] %-5p (%F:%L) - %m %n");
        defaultProps.setProperty("log4j.appender.stdout.layout", "org.apache.log4j.PatternLayout");
        defaultProps.setProperty("log4j.appender.stdout.Encoding", "UTF-8");
      }

      if (commandLine.hasOption("trace")) {
        defaultProps.setProperty("log4j.rootLogger", "trace,stdout");
      } else if (commandLine.hasOption("debug")) {
        defaultProps.setProperty("log4j.rootLogger", "debug,stdout");
      } else if (commandLine.hasOption("info")) {
        defaultProps.setProperty("log4j.rootLogger", "info,stdout");
      } else {
        if (defaultProps.getProperty("log4j.rootLogger") == null) {
          defaultProps.setProperty("log4j.rootLogger", "info,stdout");
        }
      }
      PropertyConfigurator.configure(defaultProps);

      if (commandLine.hasOption("help") || commandLine.hasOption("version")) {
        throw new ParseException("");
      }

      File labelled = new File(commandLine.getOptionValue("labelled"));
      File unlabelled = new File(commandLine.getOptionValue("unlabelled"));
      File roles = new File(commandLine.getOptionValue("roles"));
      File output = new File(commandLine.getOptionValue("output"));
      try {
        if (commandLine.hasOption("start")) {
          int start = Integer.parseInt(commandLine.getOptionValue("start"));
          new AnnotationMigration(labelled, unlabelled, roles, output, start);
        } else {
          new AnnotationMigration(labelled, unlabelled, roles, output);
        }

      } catch (IOException e) {
        logger.error(e);
      }

    } catch (ParseException exp) {
      if (exp.getMessage().length() > 0) {
        System.err.println("Parsing failed: " + exp.getMessage() + "\n");
      }
      HelpFormatter formatter = new HelpFormatter();
      formatter.printHelp(
          200,
          "java -Dfile.encoding=UTF-8 -cp dist/dirha.jar org.fbk.cit.hlt.dirha.AnnotationMigration",
          "\n",
          options,
          "\n",
          true);
      System.exit(1);
    }
  }
Ejemplo n.º 14
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");
      }
    }
  }