Esempio n. 1
0
 /**
  * This does the work of main, but it never calls System.exit, so it is appropriate to be called
  * progrmmatically. Termination of the program with a message to the user is indicated by throwing
  * Daikon.TerminationMessage.
  *
  * @see #main(String[])
  * @see daikon.Daikon.TerminationMessage
  */
 public static void mainHelper(final String[] args)
     throws FileNotFoundException, IOException, ClassNotFoundException {
   daikon.LogHelper.setupLogs(daikon.LogHelper.INFO);
   LongOpt[] longopts =
       new LongOpt[] {
         new LongOpt(Daikon.suppress_redundant_SWITCH, LongOpt.NO_ARGUMENT, null, 0),
         new LongOpt(Daikon.config_option_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0),
         new LongOpt(Daikon.debugAll_SWITCH, LongOpt.NO_ARGUMENT, null, 0),
         new LongOpt(Daikon.debug_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0),
       };
   Getopt g = new Getopt("daikon.ExtractConsequent", args, "h", longopts);
   int c;
   while ((c = g.getopt()) != -1) {
     switch (c) {
       case 0:
         // got a long option
         String option_name = longopts[g.getLongind()].getName();
         if (Daikon.help_SWITCH.equals(option_name)) {
           System.out.println(usage);
           throw new Daikon.TerminationMessage();
         } else if (Daikon.suppress_redundant_SWITCH.equals(option_name)) {
           Daikon.suppress_redundant_invariants_with_simplify = true;
         } else if (Daikon.config_option_SWITCH.equals(option_name)) {
           String item = Daikon.getOptarg(g);
           daikon.config.Configuration.getInstance().apply(item);
           break;
         } else if (Daikon.debugAll_SWITCH.equals(option_name)) {
           Global.debugAll = true;
         } else if (Daikon.debug_SWITCH.equals(option_name)) {
           LogHelper.setLevel(Daikon.getOptarg(g), LogHelper.FINE);
         } else {
           throw new RuntimeException("Unknown long option received: " + option_name);
         }
         break;
       case 'h':
         System.out.println(usage);
         throw new Daikon.TerminationMessage();
       case '?':
         break; // getopt() already printed an error
       default:
         System.out.println("getopt() returned " + c);
         break;
     }
   }
   // The index of the first non-option argument -- the name of the file
   int fileIndex = g.getOptind();
   if (args.length - fileIndex != 1) {
     throw new Daikon.TerminationMessage("Wrong number of arguments." + Daikon.lineSep + usage);
   }
   String filename = args[fileIndex];
   PptMap ppts =
       FileIO.read_serialized_pptmap(
           new File(filename), true // use saved config
           );
   extract_consequent(ppts);
 }
Esempio n. 2
0
 /** @see de.ailis.wlandsuite.cli.CLIProg#processOption(int, gnu.getopt.Getopt) */
 @Override
 protected void processOption(int opt, Getopt getopt) {
   switch (opt) {
     case 'W':
       this.width = Integer.parseInt(getopt.getOptarg());
       break;
   }
 }
Esempio n. 3
0
 public static void main(final String[] argv) {
   final Getopt g = new Getopt("DomainCommand", argv, "n:m:t:P:");
   String[] allocName = null;
   int c;
   while ((c = g.getopt()) != -1) {
     switch (c) {
       case 110:
         {
           allocName = g.getOptarg().split(",", 2);
         }
       case 109:
       case 116:
         {
           continue;
         }
     }
   }
   final String worldName = System.getProperty("atavism.worldname");
   final String hostName = determineHostName();
   final Properties properties = InitLogAndPid.initLogAndPid(argv, worldName, hostName);
   final MessageAgent agent = new MessageAgent();
   final String domainHost =
       properties.getProperty(
           "atavism.msgsvr_hostname", System.getProperty("atavism.msgsvr_hostname"));
   final String portString =
       properties.getProperty("atavism.msgsvr_port", System.getProperty("atavism.msgsvr_port"));
   int domainPort = 20374;
   if (portString != null) {
     domainPort = Integer.parseInt(portString);
   }
   try {
     agent.connectToDomain(domainHost, domainPort);
     if (allocName != null) {
       final String agentName = agent.getDomainClient().allocName(allocName[0], allocName[1]);
       System.out.println(agentName);
     }
   } catch (Exception ex) {
     System.err.println("DomainCommand: " + ex);
     throw new RuntimeException("failed", ex);
   }
 }
Esempio n. 4
0
  public static void main(String[] args) {
    LoggingUtils.setupNullLogging();

    if (args.length == 0) {
      help();
      System.exit(0);
    }

    IMachine machine = ToolUtils.createMachine();

    Type typer = new Type(machine, System.out);

    Getopt getopt;
    getopt = new Getopt(PROGNAME, args, "?r");

    int opt;
    while ((opt = getopt.getopt()) != -1) {
      switch (opt) {
        case '?':
          help();
          break;
        case 'r':
          typer.setEmitRaw(true);
          break;
      }
    }

    try {
      // leftover files are FIAD
      int idx = getopt.getOptind();
      while (idx < args.length) {
        String name = args[idx++];
        typer.type(name);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Esempio n. 5
0
  public static void main(String[] args) {
    boolean nio = false, server = false, client = false, multicast = false;

    Getopt g = new Getopt("MultiChat", args, "a:dhmnp:sc");
    int c;

    while ((c = g.getopt()) != -1) {
      switch (c) {
        case 'a':
          // set the ip address
          HOST = g.getOptarg();
          break;
        case 'd':
          // Mode debug (log dans la console)
          MyLogger.setConsoleMsg(true);
          break;
        case 'h':
          System.out.println(msgHelp);
          try {
            Thread.sleep(5000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          System.exit(0);
        case 'm':
          // mode multicast
          multicast = true;
          break;
        case 'n':
          // mode client
          nio = true;
          break;
        case 'p':
          // Option -p pour spécifier port
          PORT = Integer.parseInt(g.getOptarg());
          break;
        case 's':
          server = true;
          break;
        case 'c':
          // option -c pour lancer client:
          client = true;
          break;
        case '?':
          break;
        default:
          System.out.print("getopt() returned " + c + "\n");
      }
    }

    if (MyLogger.isConsoleMsg()) {
      MyLogger.init(false);
    } else {
      MyLogger.init(true);
    }

    if (client) {
      if (multicast) {
        MainClient.setISMULTICAST(true);
      } else {
        MainClient.setISMULTICAST(false);
      }
      MainClient.setHOST(HOST);
      MainClient.setPORT(PORT);
      Application.launch(MainClient.class, args);
    } else if (server) {
      MainServer.setHOST(HOST);
      MainServer.setPORT(PORT);
      if (!nio) {
        // option -s pour lancer serveur (par défaut sans NIO):
        MainServer.main();
      } else {
        // -s -n pour lancer un serveur NIO:
        MainServer.mainNIO();
      }
    }
  }
Esempio n. 6
0
  private void processArguments(AgentMain agent, String[] args) {
    PrintWriter out = agent.getOut();

    String sopts = "deop::sv";
    LongOpt[] lopts = {
      new LongOpt("disable", LongOpt.NO_ARGUMENT, null, 'd'),
      new LongOpt("enable", LongOpt.NO_ARGUMENT, null, 'e'),
      new LongOpt("os", LongOpt.NO_ARGUMENT, null, 'o'),
      new LongOpt("ps", LongOpt.OPTIONAL_ARGUMENT, null, 'p'),
      new LongOpt("shutdown", LongOpt.NO_ARGUMENT, null, 's'),
      new LongOpt("version", LongOpt.NO_ARGUMENT, null, 'v')
    };

    Getopt getopt = new Getopt("native", args, sopts, lopts);
    int code;

    while ((code = getopt.getopt()) != -1) {
      switch (code) {
        case ':':
        case '?':
        case 1:
          {
            out.println(MSG.getMsg(AgentI18NResourceKeys.HELP_SYNTAX_LABEL, getSyntax()));
            break;
          }

        case 'd':
          {
            SystemInfoFactory.disableNativeSystemInfo();
            out.println(MSG.getMsg(AgentI18NResourceKeys.NATIVE_DISABLE_DONE));
            break;
          }

        case 'e':
          {
            SystemInfoFactory.enableNativeSystemInfo();
            out.println(MSG.getMsg(AgentI18NResourceKeys.NATIVE_ENABLE_DONE));
            break;
          }

        case 'o':
          {
            SystemInfo sysInfo = SystemInfoFactory.createSystemInfo();

            // careful - I chose to only output things that I know the non-native Java sysinfo can
            // support
            out.println(
                MSG.getMsg(
                    AgentI18NResourceKeys.NATIVE_OS_OUTPUT,
                    sysInfo.getOperatingSystemName(),
                    sysInfo.getOperatingSystemVersion(),
                    sysInfo.getHostname()));

            break;
          }

        case 'p':
          {
            SystemInfo sysInfo = SystemInfoFactory.createSystemInfo();
            String verboseOpt = getopt.getOptarg();
            boolean verbose =
                (verboseOpt != null)
                    && verboseOpt.equals(MSG.getMsg(AgentI18NResourceKeys.NATIVE_VERBOSE));

            try {
              List<ProcessInfo> processes = sysInfo.getAllProcesses();
              if (verbose) {
                out.println(MSG.getMsg(AgentI18NResourceKeys.NATIVE_PS_OUTPUT_VERBOSE_HEADER));
              } else {
                out.println(MSG.getMsg(AgentI18NResourceKeys.NATIVE_PS_OUTPUT_SHORT_HEADER));
              }

              for (ProcessInfo p : processes) {
                if (verbose) {
                  out.println(
                      MSG.getMsg(
                          AgentI18NResourceKeys.NATIVE_PS_OUTPUT_VERBOSE,
                          p.getPid(),
                          p.getParentPid(),
                          p.getBaseName(),
                          Arrays.toString(p.getCommandLine())));
                } else {
                  out.println(
                      MSG.getMsg(
                          AgentI18NResourceKeys.NATIVE_PS_OUTPUT_SHORT, p.getPid(), p.getName()));
                }
              }
            } catch (Exception e) {
              out.println(MSG.getMsg(AgentI18NResourceKeys.NATIVE_NOT_SUPPORTED));
            }

            break;
          }

        case 's':
          {
            if (!agent.isStarted()) {
              SystemInfoFactory.shutdown();
              SystemInfoFactory.disableNativeSystemInfo();
              out.println(MSG.getMsg(AgentI18NResourceKeys.NATIVE_SHUTDOWN_DONE));
            } else {
              out.println(MSG.getMsg(AgentI18NResourceKeys.NATIVE_SHUTDOWN_FAILED_AGENT_STARTED));
            }

            break;
          }

        case 'v':
          {
            out.println(SystemInfoFactory.getNativeSystemInfoVersion());
            break;
          }
      }
    }

    if ((getopt.getOptind() + 1) < args.length) {
      out.println(MSG.getMsg(AgentI18NResourceKeys.HELP_SYNTAX_LABEL, getSyntax()));
    }

    return;
  }
Esempio n. 7
0
  /**
   * Command line application entry point which parses CLI arguments and passes them into the
   * importer. Return codes are:
   *
   * <ul>
   *   <li>0 on success
   *   <li>1 on argument parsing failure
   *   <li>2 on exception during import
   * </ul>
   *
   * @param args Command line arguments.
   */
  public static void main(String[] args) throws Throwable {
    LongOpt[] longOptions =
        new LongOpt[] {
          new LongOpt("error-on", LongOpt.REQUIRED_ARGUMENT, null, 'e'),
          new LongOpt("feedback", LongOpt.REQUIRED_ARGUMENT, null, 'f'),
          new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'h'),
          new LongOpt("no-recurse", LongOpt.OPTIONAL_ARGUMENT, null, 'r')
        };

    // First find our configuration file, if it has been provided.
    Getopt g = new Getopt(APP_NAME, args, "s:u:w:p:k:c:x", longOptions);
    int a;
    InputStream configFile = new ByteArrayInputStream(new byte[0]);
    while ((a = g.getopt()) != -1) {
      switch (a) {
        case 'c':
          {
            configFile = new FileInputStream(g.getOptarg());
            break;
          }
      }
    }
    // Second check for the configuration file on the CLASSPATH if we
    // haven't been given a configuration file on the command line.
    if (configFile instanceof ByteArrayInputStream) {
      InputStream fromClasspath =
          TestEngine.class.getClassLoader().getResourceAsStream("test_engine.ini");
      configFile = fromClasspath == null ? configFile : fromClasspath;
    }

    // Now parse our options.
    g = new Getopt(APP_NAME, args, "s:u:w:p:c:k:x", longOptions);
    TestEngineConfig config = new TestEngineConfig(configFile);
    while ((a = g.getopt()) != -1) {
      switch (a) {
        case 's':
          {
            config.setHostname(g.getOptarg());
            break;
          }
        case 'u':
          {
            config.setUsername(g.getOptarg());
            break;
          }
        case 'w':
          {
            config.setPassword(g.getOptarg());
            break;
          }
        case 'k':
          {
            config.setSessionKey(g.getOptarg());
            break;
          }
        case 'p':
          {
            config.setPort(Integer.parseInt(g.getOptarg()));
            break;
          }
        case 'x':
          {
            config.setPopulate(!config.getPopulate());
            break;
          }
        case 'r':
          {
            config.setRecurse(!config.getRecurse());
            break;
          }
        case 'e':
          {
            config.setErrorOn(g.getOptarg());
          }
        case 'f':
          {
            config.setFeedbackUrl(g.getOptarg());
            break;
          }
        case 'c':
          {
            // Ignore, we've dealt with this already.
            break;
          }
        default:
          {
            usage();
          }
      }
    }

    // Ensure that we have all of our required login arguments
    if (!config.validateLogin()) {
      usage();
    }

    // Ensure that we have a valid target path.
    String path = config.getTarget();
    if (args.length - g.getOptind() == 1) {
      path = args[g.getOptind()];
    } else if (path == null) {
      usage();
    }

    TestEngine engine = new TestEngine(config);
    engine.run(path);
    engine.exit();
  }
  // Usage: mvm [-q] -p <pid|agent> -f <script-file> -s <script>
  public static void main(String[] args) {
    Getopt g = new Getopt("CommandMain", args, "p:f:s:q");
    List<String> scripts = new LinkedList<String>();
    List<String> scriptNames = new LinkedList<String>();
    List<String> processes = new LinkedList<String>();
    boolean quiet = false;

    int c;
    while ((c = g.getopt()) != -1) {
      String script;
      switch (c) {
          // process
        case 'p':
          processes.add(g.getOptarg());
          break;
          // script-file
        case 'f':
          String fileName = g.getOptarg();
          scriptNames.add(fileName);
          script = readFile(fileName);
          if (script == null) System.exit(1);
          scripts.add(script);
          break;
          // script
        case 's':
          script = g.getOptarg();
          scripts.add(script);
          scriptNames.add(script);
          break;
          // quiet
        case 'q':
          quiet = true;
          break;
      }
    }

    if (processes.size() == 0 || scripts.size() == 0) {
      System.err.println("Usage: mvm -p <pid|agent-name> -s <script> -f <script-file>");
      System.exit(1);
    }

    String argvString = "argv = [\"<string>\"";
    int arg = 0;
    for (int ii = g.getOptind(); ii < args.length; ii++) {
      argvString += ",\"" + args[ii] + "\"";
      arg++;
    }
    argvString += "]\n";

    boolean ok = true;
    for (String process : processes) {
      int ss = 0;
      for (String script : scripts) {
        if (!quiet) System.out.println("Process " + process + ": " + scriptNames.get(ss));
        ss++;
        ok = ok && execScript(process, argvString + script);
      }
    }
    if (ok) System.exit(0);
    else System.exit(1);
  }
Esempio n. 9
0
  /**
   * This does the work of main, but it never calls System.exit, so it is appropriate to be called
   * progrmmatically. Termination of the program with a message to the user is indicated by throwing
   * Daikon.TerminationMessage.
   *
   * @see #main(String[])
   * @see daikon.Daikon.TerminationMessage
   */
  public static void mainHelper(final String[] args)
      throws FileNotFoundException, StreamCorruptedException, OptionalDataException, IOException,
          ClassNotFoundException {
    daikon.LogHelper.setupLogs(daikon.LogHelper.INFO);

    LongOpt[] longopts =
        new LongOpt[] {
          new LongOpt(Daikon.config_option_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0),
          new LongOpt(output_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0),
          new LongOpt(dir_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0),
          new LongOpt(conf_SWITCH, LongOpt.NO_ARGUMENT, null, 0),
          new LongOpt(filter_SWITCH, LongOpt.NO_ARGUMENT, null, 0),
          new LongOpt(Daikon.debugAll_SWITCH, LongOpt.NO_ARGUMENT, null, 0),
          new LongOpt(Daikon.debug_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0),
          new LongOpt(Daikon.ppt_regexp_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0),
          new LongOpt(Daikon.track_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0),
        };
    Getopt g = new Getopt("daikon.tools.InvariantChecker", args, "h", longopts);
    int c;
    while ((c = g.getopt()) != -1) {
      switch (c) {
        case 0:
          // got a long option
          String option_name = longopts[g.getLongind()].getName();
          if (Daikon.help_SWITCH.equals(option_name)) {
            System.out.println(usage);
            throw new Daikon.TerminationMessage();
          } else if (conf_SWITCH.equals(option_name)) {
            doConf = true;
          } else if (filter_SWITCH.equals(option_name)) {
            doFilter = true;
          } else if (dir_SWITCH.equals(option_name)) {
            dir_file = new File(g.getOptarg());
            if (!dir_file.exists() || !dir_file.isDirectory())
              throw new Daikon.TerminationMessage("Error reading the directory " + dir_file);

          } else if (output_SWITCH.equals(option_name)) {
            output_file = new File(g.getOptarg());
            output_stream = new PrintStream(new FileOutputStream(output_file));
          } else if (Daikon.config_option_SWITCH.equals(option_name)) {
            String item = g.getOptarg();
            daikon.config.Configuration.getInstance().apply(item);
            break;
          } else if (Daikon.debugAll_SWITCH.equals(option_name)) {
            Global.debugAll = true;
          } else if (Daikon.debug_SWITCH.equals(option_name)) {
            LogHelper.setLevel(g.getOptarg(), LogHelper.FINE);
          } else if (Daikon.track_SWITCH.equals(option_name)) {
            LogHelper.setLevel("daikon.Debug", LogHelper.FINE);
            String error = Debug.add_track(g.getOptarg());
            if (error != null) {
              throw new Daikon.TerminationMessage(
                  "Error parsing track argument '" + g.getOptarg() + "' - " + error);
            }
          } else {
            throw new RuntimeException("Unknown long option received: " + option_name);
          }
          break;
        case 'h':
          System.out.println(usage);
          throw new Daikon.TerminationMessage();
        case '?':
          break; // getopt() already printed an error
        default:
          System.out.println("getopt() returned " + c);
          break;
      }
    }

    // Loop through each filename specified
    for (int i = g.getOptind(); i < args.length; i++) {

      // Get the file and make sure it exists
      File file = new File(args[i]);
      if (!file.exists()) {
        throw new Error("File " + file + " not found.");
      }

      // These aren't "endsWith()" because there might be a suffix on the end
      // (eg, a date).
      String filename = file.toString();
      if (filename.indexOf(".inv") != -1) {
        if (inv_file != null) {
          throw new Daikon.TerminationMessage("multiple inv files specified", usage);
        }
        inv_file = file;
      } else if (filename.indexOf(".dtrace") != -1) {
        dtrace_files.add(filename);
      } else {
        throw new Error("Unrecognized argument: " + file);
      }
    }
    if (dir_file == null) {
      checkInvariants();
      return;
    }

    // Yoav additions:
    File[] filesInDir = dir_file.listFiles();
    if (filesInDir == null || filesInDir.length == 0)
      throw new Daikon.TerminationMessage("The directory " + dir_file + " is empty", usage);
    ArrayList<File> invariants = new ArrayList<File>();
    for (File f : filesInDir) if (f.toString().indexOf(".inv") != -1) invariants.add(f);
    if (invariants.size() == 0)
      throw new Daikon.TerminationMessage(
          "Did not find any invariant files in the directory " + dir_file, usage);
    ArrayList<File> dtraces = new ArrayList<File>();
    for (File f : filesInDir) if (f.toString().indexOf(".dtrace") != -1) dtraces.add(f);
    if (dtraces.size() == 0)
      throw new Daikon.TerminationMessage(
          "Did not find any dtrace files in the directory " + dir_file, usage);

    System.out.println(
        "Collecting data for invariants files " + invariants + " and dtrace files " + dtraces);

    dtrace_files.clear();
    for (File dtrace : dtraces) {
      dtrace_files.add(dtrace.toString());
    }

    String commaLine = "";
    for (File inFile : invariants) {
      String name = inFile.getName().replace(".inv", "").replace(".gz", "");
      commaLine += "," + name;
    }
    outputComma.add(commaLine);

    commaLine = "";
    for (File inFile : invariants) {
      inv_file = inFile;
      failedInvariants.clear();
      testedInvariants.clear();
      error_cnt = 0;

      output_stream =
          new PrintStream(
              new FileOutputStream(
                  inFile.toString().replace(".inv", "").replace(".gz", "")
                      + ".false-positives.txt"));
      checkInvariants();
      output_stream.close();

      int failedCount = failedInvariants.size();
      int testedCount = testedInvariants.size();
      String percent = toPercentage(failedCount, testedCount);
      commaLine += "," + percent;
    }
    outputComma.add(commaLine);

    System.out.println();
    for (String output : outputComma) System.out.println(output);
  }
Esempio n. 10
0
  private WhatToDo[] processArguments(String[] args) throws Exception {
    String sopts = "-:HD:h:p:d:blrt";
    LongOpt[] lopts = {
      new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'H'),
      new LongOpt("host", LongOpt.REQUIRED_ARGUMENT, null, 'h'),
      new LongOpt("port", LongOpt.REQUIRED_ARGUMENT, null, 'p'),
      new LongOpt("dbpassword", LongOpt.REQUIRED_ARGUMENT, null, 'd'),
      new LongOpt("setupdb", LongOpt.NO_ARGUMENT, null, 'b'),
      new LongOpt("listservers", LongOpt.NO_ARGUMENT, null, 'l'),
      new LongOpt("reconfig", LongOpt.NO_ARGUMENT, null, 'r'),
      new LongOpt("test", LongOpt.NO_ARGUMENT, null, 't')
    };

    boolean test = false;
    boolean listservers = false;
    boolean setupdb = false;
    boolean reconfig = false;
    String dbpassword = null;

    Getopt getopt = new Getopt("installer", args, sopts, lopts);
    int code;

    while ((code = getopt.getopt()) != -1) {
      switch (code) {
        case ':':
        case '?':
          {
            // for now both of these should exit
            displayUsage();
            throw new IllegalArgumentException();
          }

        case 1:
          {
            // this will catch non-option arguments (which we don't currently support)
            throw new IllegalArgumentException("Unknown option: " + getopt.getOptarg());
          }

        case 'H':
          {
            return new WhatToDo[] {WhatToDo.DISPLAY_USAGE};
          }

        case 'D':
          {
            // set a system property
            String sysprop = getopt.getOptarg();
            int i = sysprop.indexOf("=");
            String name;
            String value;

            if (i == -1) {
              name = sysprop;
              value = "true";
            } else {
              name = sysprop.substring(0, i);
              value = sysprop.substring(i + 1, sysprop.length());
            }

            System.setProperty(name, value);
            LOG.info("System property set: " + name + "=" + value);

            break;
          }

        case 'h':
          {
            String hostString = getopt.getOptarg();
            if (hostString == null) {
              throw new IllegalArgumentException("Missing host value");
            }
            this.installerConfig.setManagementHost(hostString);
            break;
          }

        case 'p':
          {
            String portString = getopt.getOptarg();
            if (portString == null) {
              throw new IllegalArgumentException("Missing port value");
            }
            this.installerConfig.setManagementPort(Integer.parseInt(portString));
            break;
          }

        case 'd':
          {
            dbpassword = getopt.getOptarg();
            if (dbpassword == null) {
              throw new IllegalArgumentException("Missing password");
            }
            break;
          }

        case 'b':
          {
            setupdb = true;
            break; // don't return, in case we need to allow more args
          }

        case 'l':
          {
            listservers = true;
            break; // don't return, we need to allow more args to be processed, like -p or -h
          }

        case 'r':
          {
            reconfig = true;
            break; // don't return, we need to allow more args to be processed, like -p or -h
          }

        case 't':
          {
            test = true;
            break; // don't return, we need to allow more args to be processed, like -p or -h
          }
      }
    }

    // if a password was asked to be obfuscated, that's all we are to do
    if (dbpassword != null) {
      String pw = new InstallerServiceImpl(installerConfig).obfuscatePassword(dbpassword);
      LOG.info("*** Encoded Password: " + pw);
      return new WhatToDo[] {WhatToDo.DO_NOTHING};
    }

    if (reconfig) {
      return new WhatToDo[] {WhatToDo.RECONFIGURE};
    }

    if (test || setupdb || listservers) {
      ArrayList<WhatToDo> whatToDo = new ArrayList<WhatToDo>();
      if (test) {
        whatToDo.add(WhatToDo.TEST);
      }
      if (setupdb) {
        whatToDo.add(WhatToDo.SETUPDB);
      }
      if (listservers) {
        whatToDo.add(WhatToDo.LIST_SERVERS);
      }
      return whatToDo.toArray(new WhatToDo[whatToDo.size()]);
    }

    return new WhatToDo[] {WhatToDo.INSTALL};
  }
Esempio n. 11
0
  public static void main(String args[]) {

    System.out.println("== MedSavant Server Engine ==\n");

    try {

      /** Override with commands from the command line */
      Getopt g = new Getopt("MedSavantServerEngine", args, "c:l:h:p:u:e:");
      //
      int c;

      String user = "******";
      String password = null;
      String host = "localhost";
      int port = 5029;

      // print usage
      if (args.length > 0 && args[0].equals("--help")) {
        System.out.println(
            "java -jar -Djava.rmi.server.hostname=<hostname> MedSavantServerEngine.jar { [-c CONFIG_FILE] } or { [-l RMI_PORT] [-h DATABASE_HOST] [-p DATABASE_PORT] [-u DATABASE_ROOT_USER] [-e ADMIN_EMAIL] }");
        System.out.println(
            "\n\tCONFIG_FILE should be a file containing any number of these keys:\n"
                + "\t\tdb-user - the database user\n"
                + "\t\tdb-password - the database password\n"
                + "\t\tdb-host - the database host\n"
                + "\t\tdb-port - the database port\n"
                + "\t\tlisten-on-port - the port on which clients will connect\n"
                + "\t\temail - the email address to send important notifications\n"
                + "\t\ttmp-dir - the directory to use for temporary files\n"
                + "\t\tms-dir - the directory to use to store permanent files\n");
        return;
      }

      while ((c = g.getopt()) != -1) {
        switch (c) {
          case 'c':
            String configFileName = g.getOptarg();
            System.out.println(
                "Loading configuration from "
                    + (new File(configFileName)).getAbsolutePath()
                    + " ...");

            Properties prop = new Properties();
            try {
              prop.load(new FileInputStream(configFileName));
              if (prop.containsKey("db-user")) {
                user = prop.getProperty("db-user");
              }
              if (prop.containsKey("db-password")) {
                password = prop.getProperty("db-password");
              }
              if (prop.containsKey("db-host")) {
                host = prop.getProperty("db-host");
              }
              if (prop.containsKey("db-port")) {
                port = Integer.parseInt(prop.getProperty("db-port"));
              }
              if (prop.containsKey("listen-on-port")) {
                int listenOnPort = Integer.parseInt(prop.getProperty("listen-on-port"));
                MedSavantServerUnicastRemoteObject.setListenPort(listenOnPort);
                // MedSavantServerUnicastRemoteObject.setExportPort(listenOnPort + 1);
              }
              if (prop.containsKey("email")) {
                EmailLogger.setMailRecipient(prop.getProperty("email"));
              }
              if (prop.containsKey("tmp-dir")) {
                DirectorySettings.setTmpDirectory(prop.getProperty("tmp-dir"));
              }
              if (prop.containsKey("ms-dir")) {
                DirectorySettings.setMedSavantDirectory(prop.getProperty("ms-dir"));
              }

            } catch (Exception e) {
              System.out.println("ERROR: Could not load properties file " + configFileName);
            }
            break;
          case 'h':
            System.out.println("Host " + g.getOptarg());
            host = g.getOptarg();
            break;
          case 'p':
            port = Integer.parseInt(g.getOptarg());
            break;
          case 'l':
            int listenOnPort = Integer.parseInt(g.getOptarg());
            MedSavantServerUnicastRemoteObject.setListenPort(listenOnPort);
            // MedSavantServerUnicastRemoteObject.setExportPort(listenOnPort + 1);
            break;
          case 'u':
            user = g.getOptarg();
            break;
          case 'e':
            EmailLogger.setMailRecipient(g.getOptarg());
            break;
          case '?':
            break; // getopt() already printed an error
          default:
            System.out.print("getopt() returned " + c + "\n");
        }
      }

      new MedSavantServerEngine(host, port, user, password);
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
Esempio n. 12
0
  @Override
  public String execute(String uuid, String... params) throws RemoteException {
    try {
      LongOpt[] longopts = new LongOpt[4];
      longopts[0] = new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'h');
      longopts[1] = new LongOpt("project", LongOpt.REQUIRED_ARGUMENT, null, 'p');
      longopts[2] = new LongOpt("file", LongOpt.REQUIRED_ARGUMENT, null, 'f');
      longopts[3] = new LongOpt("dest", LongOpt.REQUIRED_ARGUMENT, null, 'd');

      Getopt g = new Getopt("put", params, "", longopts);
      g.setOpterr(false);

      String project = null;
      String path = null;
      String[] parents = null;
      String dest = null;
      int c;
      while ((c = g.getopt()) != -1) {
        switch (c) {
          case 'p':
            project = g.getOptarg();
            break;
          case 'f':
            path = g.getOptarg();
            break;
          case 'd':
            dest = g.getOptarg();
            if (!".".equals(dest)) {
              parents = CLIUtils.convertAbsolutePathToArray(dest, false, false);
            }
            break;
          case 'h':
            return usage(uuid);
          default:
            return CLIResultCodes.INTERNAL_SERVER_ERROR
                + "::Could not execute the command \n "
                + usage(uuid);
        }
      }

      if (uuid == null) {
        return CLIResultCodes.USER_NOT_AUTHORIZED + "::--uuid parameter is required!";
      }

      if (project == null) {
        return CLIResultCodes.USER_ERROR + "::--project parameter is required!";
      }

      if (path == null) {
        return CLIResultCodes.USER_ERROR + "::--file parameter is required!";
      }

      if (dest == null) {
        return CLIResultCodes.USER_ERROR + "::--dest parameter is required!";
      }

      if (!fileService.exists(uuid, project, null, null)) {
        return CLIResultCodes.PROJECT_NOT_FOUND
            + "::Could not find project ["
            + project
            + "] for the current user";
      }

      File src = new File(path);

      if (!src.exists()) {
        return CLIResultCodes.FILE_DOES_NOT_EXIST
            + "::File ["
            + src.getName()
            + "] does not exist!";
      }

      String fileName = src.getName();
      if (src.isDirectory()) {
        fileService.create(uuid, project, parents, fileName, true);
        String childrenPath = fileName;
        if (parents != null) {
          childrenPath = dest + "/" + fileName;
        }
        createDir(uuid, project, childrenPath, src.listFiles());
        return CLIResultCodes.OK
            + "::Put the directory ["
            + src.getName()
            + "] to the destination ["
            + dest
            + "]";
      } else {
        fileService.upload(uuid, project, parents, fileName, src, true);
        return CLIResultCodes.OK
            + "::Put the file ["
            + src.getName()
            + "] to the destination ["
            + dest
            + "]";
      }
    } catch (UserNotAuthorizedException e) {
      CLIUtils.handleException(e, logger);
      return CLIResultCodes.USER_NOT_AUTHORIZED + "::User not authorized!";
    } catch (Exception e) {
      CLIUtils.handleException(e, logger);
      return CLIResultCodes.OK + "::Could not execute the command \n " + usage(uuid);
    }
  }
  public static void main(String args[]) {
    String worldName = System.getProperty("multiverse.worldname");
    Properties properties = InitLogAndPid.initLogAndPid(args, worldName, null);

    System.err.println("Multiverse server version " + ServerVersion.getVersionString());

    List<String> agentNames = new LinkedList<String>();

    LongOpt[] longopts = new LongOpt[2];
    longopts[0] = new LongOpt("pid", LongOpt.REQUIRED_ARGUMENT, null, 2);
    longopts[1] = new LongOpt("port", LongOpt.REQUIRED_ARGUMENT, null, 3);
    Getopt opt = new Getopt("DomainServer", args, "a:m:t:p:P:", longopts);
    int c;
    int port = DEFAULT_PORT;

    String portStr = properties.getProperty("multiverse.msgsvr_port");
    if (portStr != null) port = Integer.parseInt(portStr);

    PluginStartGroup pluginStartGroup = new PluginStartGroup();

    while ((c = opt.getopt()) != -1) {
      switch (c) {
        case 'a':
          agentNames.add(opt.getOptarg());
          break;
        case 't':
        case 'm':
          // ignore RuntimeMarshalling flags
          opt.getOptarg();
          break;
        case 'p':
          String pluginSpec = opt.getOptarg();
          String[] pluginDef = pluginSpec.split(",", 2);
          if (pluginDef.length != 2) {
            System.err.println("Invalid plugin spec format: " + pluginSpec);
            Log.error("Invalid plugin spec format: " + pluginSpec);
            System.exit(1);
          }
          int expected = Integer.parseInt(pluginDef[1]);
          pluginStartGroup.add(pluginDef[0], expected);
          break;
        case '?':
          System.exit(1);
          break;
        case 'P':
          break;
        case 2:
          // ignore --pid
          opt.getOptarg();
          break;
          // port
        case 3:
          String arg = opt.getOptarg();
          port = Integer.parseInt(arg);
          break;
        default:
          break;
      }
    }

    String svrName = System.getProperty("multiverse.loggername");
    String runDir = System.getProperty("multiverse.rundir");

    // Windows non-Cygwin only - save process ID for status script
    if (System.getProperty("os.name").contains("Windows") && svrName != null && runDir != null) {
      saveProcessID(svrName, runDir);
    }

    // parse command-line options

    domainServer = new DomainServer(port);
    domainServer.setAgentNames(agentNames);
    domainServer.setWorldName(worldName);
    domainServer.start();

    pluginStartGroup.prepareDependencies(properties, worldName);
    domainServer.addPluginStartGroup(pluginStartGroup);
    pluginStartGroup.pluginAvailable("Domain", "Domain");

    String timeoutStr = properties.getProperty("multiverse.startup_timeout");
    int timeout = 120;
    if (timeoutStr != null) {
      timeout = Integer.parseInt(timeoutStr);
    }

    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    ScheduledFuture<?> timeoutHandler =
        scheduler.schedule(new TimeoutRunnable(timeout), timeout, TimeUnit.SECONDS);

    javax.crypto.SecretKey domainKey = SecureTokenUtil.generateDomainKey();
    // XXX Use a random keyID for now. Ideally, this would be semi-unique.
    long keyId = new Random().nextLong();
    encodedDomainKey = Base64.encodeBytes(SecureTokenUtil.encodeDomainKey(keyId, domainKey));
    Log.debug("generated domain key: " + encodedDomainKey);

    try {
      pluginStartGroup.awaitDependency("Domain");
      timeoutHandler.cancel(false);
      String availableMessage = properties.getProperty("multiverse.world_available_message");
      String availableFile = properties.getProperty("multiverse.world_available_file");
      if (availableFile != null) touchFile(FileUtil.expandFileName(availableFile));
      if (availableMessage != null) System.err.println("\n" + availableMessage);
      while (true) {
        Thread.sleep(10000000);
      }
    } catch (Exception ex) {
      Log.exception("DomainServer.main", ex);
    }
  }
  // The private constructor
  private PM_Configuration(String[] args) {

    File fileEinstellungen = null;
    File directoryHomeBilder = null;

    // --------------------------------
    // �bernehmen Start-Parameter
    // --------------------------------
    int c;
    Getopt g = new Getopt("photo-manager", args, "e:b:i:n::d::");
    String arg;
    while ((c = g.getopt()) != -1) {
      switch (c) {
        case 'e':
          arg = g.getOptarg();
          fileEinstellungen = (arg == null) ? null : new File(arg);
          break;
        case 'b':
          arg = g.getOptarg();
          directoryHomeBilder = (arg == null) ? null : new File(arg);
          break;
        case 'n': // batch
          batch = true;
          break;
          // case 'd': // daemon und batch
          // demon = true;
          // batch = true;
          // break;
        case 'i':
          arg = g.getOptarg();
          if (arg != null) {
            importFiles.add(new File(arg));
          }
          break;
      }
    }

    // Jetzt noch die ohne Options.Das sind dann Import-Files
    for (int i = g.getOptind(); i < args.length; i++) {
      importFiles.add(new File(args[i]));
    }

    // --------------------------------------------------------------
    // Reihenfolge:
    // 1. a. -e Parameter auswerten
    // b. nigefu: .photo-manager/pm_einstellungen.xml suchen
    // c. nigefu: Locale prompten und .photo-manager/pm_einstellungen.xml
    // neu anlegen
    // 2. a. -b Parameter auswerten
    // b. nigefu: Eintrag in .photo-manager/pm_einstellungen.xml suchen
    // c. nigefu: prompten (ERROR wenn batch)
    // 3. Wenn in .photo-manager/pm_einstellungen.xml
    // Bilder-Dir nicht eingetragen, dann dort eintragen.
    // (wenn vorhanden, nicht �berschreiben)
    // ------------------------------------------------------------------

    // --------------------------------------------------------------------
    // (1) pm_einstellungen.xml und locale ermitteln
    // --------------------------------------------------------------------
    if (fileEinstellungen != null && fileEinstellungen.isFile()) {
      // (1.a.) -e Parameter vorhanden:
      // open und lesen locale
      xmlFile = fileEinstellungen;
      openDocument(OPEN_READ_ONLY);
      locale = getLocale();
      if (locale == null) {
        locale = (new PM_WindowDialogGetLocale().getLocale());
        setLocale(locale);
        writeDocument();
      }
    } else {
      // (1.b.) -e nicht angegeben
      fileEinstellungen = new File(PM_Utils.getConfigDir() + File.separator + FILE_EINSTELLUNGEN);
      if (fileEinstellungen.isFile()) {
        // (1.b) in .photo-manager/pm_einstellungen.xml Datei gefunden
        xmlFile = fileEinstellungen;
        openDocument(OPEN_READ_ONLY);
        locale = getLocale();

        if (locale == null) {
          locale = (new PM_WindowDialogGetLocale().getLocale());
          setLocale(locale);
          writeDocument();
        }
      } else {
        // pm_einstellungen.xml nigefu:
        // locale prompten und pm_einstellungen neu anlegen
        locale = (new PM_WindowDialogGetLocale().getLocale());
        xmlFile = fileEinstellungen;
        rootTagName = rootTag;
        openDocument(OPEN_CREATE);
        setLocale(locale);
        writeDocument();
      }
    }

    // ---------------------------------------------------------------
    // (2) Bilder Dir ermitteln
    // ---------------------------------------------------------------

    if (directoryHomeBilder != null && directoryHomeBilder.isDirectory()) {
      // --- es wurde -b <top level directory> angegeben
      homeBilder = directoryHomeBilder;
      setHomeBilder(homeBilder.getPath());
      writeDocument();
    } else {
      // jetzt muss homeBilder aus der xml-Datei gelesen werden.
      // Wenn nigefu., dann prompten und eingtragen
      homeBilder = getHomeFile();
      if (homeBilder == null || homeBilder.isDirectory() == false) {
        if (batch) {
          System.out.println("ERROR: batch kein TLPD gefunden");
          System.out.println("abnormal end");
          System.exit(0);
        }
        PM_MSG.setResourceBundle(locale);
        PM_WindowGetTLPD sp = new PM_WindowGetTLPD();
        homeBilder = sp.getResult();
        if (homeBilder == null) {
          setLocale(locale);
          writeDocument();
          System.out.println("abnormal end (no TLPD)");
          System.exit(0);
        }
        setLocale(locale);
        setHomeBilder(homeBilder.getPath());
        writeDocument();
      }
    }

    // -----------------------------------------------------
    // Jetzt gibt es:
    // ein korrektes xmlFile mit einem homeBilder Eintrag
    // homeBilder ist korrekt versorgt
    // --------------------------------------------------------

    // System.out.println("Locale = "+ locale);
    PM_MSG.setResourceBundle(locale);

    setAllPrinter();
    setPrinterFormat();
    setDateFromTo();
    setPrefetch();
    setSlideshow();
    setBackup();
    setSequences();
    setMpeg();

    // homeLuceneDB in -e nicht eingetragn
    if (homeLuceneDB == null) {
      homeLuceneDB =
          new File(
              homeBilder.getPath()
                  + File.separator
                  + DIR_METADATEN_ROOT
                  + File.separator
                  + DIR_LUCENE_DB);
      homeLuceneDB.mkdirs();
    }

    // Temp-Dir nicht vorhanden
    if (homeTemp == null) {
      homeTemp = new File(homeBilder.getPath() + File.separator + DIR_PM_TEMP); // "pm_temp");
      homeTemp.mkdirs();
    }

    // Externe-Programme nicht vorhanden
    if (homeExtProgramme == null) {
      homeExtProgramme =
          new File(PM_Utils.getConfigDir() + File.separator + FILE_EXTERNE_PROGRAMME);
    }

    // InitValues nicht vorhanden
    if (homeInitValues == null) {
      homeInitValues = new File(PM_Utils.getConfigDir() + File.separator + FILE_INIT_VALUES);
    }
  }
Esempio n. 15
0
  public void runCommand(String cmd) throws InterruptedException, IOException {
    long timeout = PING_TIMEOUT;
    int count = PING_COUNT;
    boolean countPing = false;
    boolean reportTimes = true;
    String hostListFile = null;
    int localPort = 0;
    int remotePort = 0;
    boolean error = false;
    String[] argv = DataHelper.split(cmd, " ");
    Getopt g = new Getopt("ping", argv, "t:m:n:chl:f:p:");
    int c;
    while ((c = g.getopt()) != -1) {
      switch (c) {
        case 't': // timeout
          timeout = Long.parseLong(g.getOptarg());
          // convenience, convert msec to sec
          if (timeout < 100) timeout *= 1000;
          break;

        case 'm': // max simultaneous pings
          MAX_SIMUL_PINGS = Integer.parseInt(g.getOptarg());
          break;

        case 'n': // number of pings
          count = Integer.parseInt(g.getOptarg());
          break;

        case 'c': // "count" ping
          countPing = true;
          count = CPING_COUNT;
          break;

        case 'h': // ping all hosts
          if (hostListFile != null) error = true;
          else hostListFile = "hosts.txt";
          break;

        case 'l': // ping a list of hosts
          if (hostListFile != null) error = true;
          else hostListFile = g.getOptarg();
          break;

        case 'f': // local port
          localPort = Integer.parseInt(g.getOptarg());
          break;

        case 'p': // remote port
          remotePort = Integer.parseInt(g.getOptarg());
          break;

        case '?':
        case ':':
        default:
          error = true;
      }
    }

    int remaining = argv.length - g.getOptind();

    if (error
        || remaining > 1
        || (remaining <= 0 && hostListFile == null)
        || (remaining > 0 && hostListFile != null)) {
      System.out.println(usage());
      return;
    }

    if (hostListFile != null) {
      BufferedReader br =
          new BufferedReader(new InputStreamReader(new FileInputStream(hostListFile), "UTF-8"));
      String line;
      List<PingHandler> pingHandlers = new ArrayList<PingHandler>();
      int i = 0;
      while ((line = br.readLine()) != null) {
        if (line.startsWith("#")) continue; // comments
        if (line.startsWith(";")) continue;
        if (line.startsWith("!")) continue;
        if (line.indexOf('=') != -1) { // maybe file is hosts.txt?
          line = line.substring(0, line.indexOf('='));
        }
        PingHandler ph =
            new PingHandler(line, count, localPort, remotePort, timeout, countPing, reportTimes);
        ph.start();
        pingHandlers.add(ph);
        if (++i > 1) reportTimes = false;
      }
      br.close();
      for (Thread t : pingHandlers) t.join();
      return;
    }

    String host = argv[g.getOptind()];
    Thread t = new PingHandler(host, count, localPort, remotePort, timeout, countPing, reportTimes);
    t.start();
    t.join();
  }
Esempio n. 16
0
  /** @param args */
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    int i;
    boolean isDaemon = false, isHelp = false;
    String configFilePath = "configure.conf";

    // get input argument
    Getopt getopt = new Getopt(null, args, "f:dh");
    while ((i = getopt.getopt()) != -1) {
      switch (i) {
        case 'f':
          configFilePath = getopt.getOptarg();
          break;
        case 'd':
          isDaemon = true;
          break;
        case 'h':
        default:
          isHelp = true;
          break;
      }
    }

    if (configFilePath.isEmpty() || configFilePath.compareTo(" ") == 0 || isHelp) {
      System.out.println("\nUsage: " + args[0] + " -f conf_file -d -h");
      System.out.println("  -f conf_file   config file path");
      System.out.println("  -d             run daemon");
      System.out.println("  -h             help\n");
      // return GlobalMessage.ISS_SUCCESS;
    }

    // load config file
    int ret = GlobalMessage.ISS_SUCCESS;
    if ((ret = PublicParam.loadManager(configFilePath)) != GlobalMessage.ISS_SUCCESS) {
      System.out.println("load index manager failed:" + configFilePath);
      return;
    }

    ManagerService managerService = new ManagerService();
    managerService.init();
    managerService.start();
    while (true) {
      try {
        sleep(ManagerParam.HEART_INTERVAL);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      // System.out.println(manager.getMetaManager().getLayoutManager().getServerList().size());
      // System.out.println(manager.getMetaManager().getLayoutManager().getCoreList().size());

      // Calendar.getInstance();
    }
    // load config file
    /*int ret = TFS_SUCCESS;
     if ((ret = SysParam::instance().load(conf_file_path.c_str())) != TFS_SUCCESS)
     {
       fprintf(stderr, "SysParam::load failed:%s", conf_file_path.c_str());
       return ret;
     }
     TBSYS_LOGGER.setLogLevel(CONFIG.get_string_value(CONFIG_PUBLIC, CONF_LOG_LEVEL, "debug"));
    TBSYS_LOGGER.setMaxFileSize(CONFIG.get_int_value(CONFIG_PUBLIC, CONF_LOG_SIZE, 0x40000000));
    TBSYS_LOGGER.setMaxFileIndex(CONFIG.get_int_value(CONFIG_PUBLIC, CONF_LOG_NUM, 0x0A));
     const char *ip = CONFIG.get_string_value(CONFIG_NAMESERVER, CONF_IP_ADDR);
     const char *dev_name = CONFIG.get_string_value(CONFIG_NAMESERVER, CONF_DEV_NAME);
     uint64_t local_ip = Func::get_local_addr(dev_name);
     if (Func::get_addr(ip) != local_ip && in_ip_list(local_ip) == 0)
     {
       TBSYS_LOG(ERROR, "ip '%s' is not local ip, local ip: %s", ip, tbsys::CNetUtil::addrToString(local_ip).c_str());
       return EXIT_GENERAL_ERROR;
     }

     const char *work_dir = CONFIG.get_string_value(CONFIG_NAMESERVER, CONF_WORK_DIR);
     if (work_dir == NULL)
     {
       TBSYS_LOG(ERROR, "directory not found");
       return EXIT_CONFIG_ERROR;
     }
     if (!DirectoryOp::create_full_path(work_dir))
     {
       TBSYS_LOG(ERROR, "create directory(%s) failed", work_dir);
       return ret;
     }

     char *pid_file_path = CONFIG.get_string_value(CONFIG_NAMESERVER, CONF_LOCK_FILE);
     int32_t pid = 0;
     if ((pid = tbsys::CProcess::existPid(pid_file_path)))
     {
       fprintf(stderr, "Program has been running: pid(%d)", pid);
       return EXIT_SYSTEM_ERROR;
     }

     const char *log_file_path = CONFIG.get_string_value(CONFIG_NAMESERVER, CONF_LOG_FILE);
     if (access(log_file_path, R_OK) == 0)
     {
       char dest_log_file_path[256];
       sprintf(dest_log_file_path, "%s.%s", log_file_path, Func::time_to_str(time(NULL), 1).c_str());
       rename(log_file_path, dest_log_file_path);
     }

     // start daemon process
     pid = 0;
     if (is_daemon)
     {
       pid = tbsys::CProcess::startDaemon(pid_file_path, log_file_path);
     }

     // start service
     if (pid == 0)
     {
       signal(SIGPIPE, SIG_IGN);
       signal(SIGHUP, SIG_IGN);
       signal(SIGINT, SIG_IGN);
       signal(SIGTERM, SIG_IGN);
       signal(SIGUSR1, SIG_IGN);
       signal(40, SIG_IGN);

       try
       {
         ARG_NEW(g_tfs_ns_service_, Service);
         ret = g_tfs_ns_service_->start();
       }
       catch (std::exception& ex)
       {
         TBSYS_LOG(WARN, "Catch execption (%s), must be exit...", ex.what());
         g_tfs_ns_service_->stop();
       }
       catch (...)
       {
         TBSYS_LOG(WARN, "Catch unknow execption, must be exit...");
         g_tfs_ns_service_->stop();
       }
       tbsys::gDelete(g_tfs_ns_service_);
     }
     return ret;*/
  }
Esempio n. 17
0
  /**
   * @param args
   * @throws Exception
   */
  public static void main(String[] args) throws Exception {
    /* Parse command line arguments */
    Getopt g = new Getopt("gateExtractor", args, "i:r:te");
    g.setOpterr(false);

    String inputPath = "";
    String outputPath = "";

    boolean train = false;
    boolean eval = false;
    boolean run = false;

    int c;
    String arg;
    while ((c = g.getopt()) != -1) {
      switch (c) {
        case 'i':
          arg = g.getOptarg();
          if (arg == null || arg.isEmpty()) {
            usage("Please provide an input path");
          }
          inputPath = arg;
          break;
        case 'r':
          run = true;
          arg = g.getOptarg();
          if (arg == null || arg.isEmpty()) {
            usage("Please provide an output path");
          }
          outputPath = arg;
          break;
        case 't':
          train = true;
          break;
        case 'e':
          eval = true;
          break;
        case '?':
        default:
          usage(null);
      }
    }

    if (args.length == 0 || (!run && !train && !eval)) {
      usage("Nothing to do.");
    }

    if (inputPath == null || inputPath.isEmpty()) {
      usage("Please provide an input path");
    }

    if (run && (outputPath == null || outputPath.isEmpty())) {
      usage("Please provide an output directory!");
    }

    if (train && eval) {
      usage("Only one mode allowed at a time");
    }

    if (train && run) {
      usage("Only one mode allowed at a time");
    }

    if (eval && run) {
      usage("Only one mode allowed at a time");
    }

    /* Initialize GATE */
    String location =
        new File(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath())
            .getParent();
    String resourcesFolder = location + "/resources";
    Gate.setGateHome(new File(resourcesFolder));

    /* Create ml-config.xml with threads */

    createConfig(resourcesFolder + File.separator);
    Gate.init();

    /* Load Corpus */
    log.info("Loading Corpus ... ");
    Corpus corpus = Factory.newCorpus("Training Corpus");
    File directory = new File(inputPath);
    URL url = directory.toURI().toURL();
    corpus.populate(url, null, null, true);
    log.info("Done loading Corpus!");

    Pipeline pipeline = null;

    /* Do Tagging */
    pipeline = new Tagger();
    pipeline.run(corpus, resourcesFolder);

    /* Train */
    if (train) {
      pipeline = new Trainer();
      pipeline.run(corpus, resourcesFolder);
    }

    /* Apply learned rules */
    if (run) {
      pipeline = new Extractor();
      pipeline.run(corpus, resourcesFolder);

      ExecutorService executorService = Executors.newFixedThreadPool(20);
      for (int i = 0; i < corpus.size(); i++) {
        executorService.execute(new OutputGenerator(outputPath, corpus.get(i)));
      }
      executorService.shutdown();
      executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
    }

    /* Evaluate results */
    if (eval) {
      pipeline = new Evaluator();
      pipeline.run(corpus, resourcesFolder);
    }

    /* Clean up */
    Factory.deleteResource(corpus);
    outputFile_mlConfigThreads.delete();
  }
Esempio n. 18
0
  public static void main(String[] args) {
    if (OSTools.isWindows()) {
      try {
        LibraryLoader.LoadLibrary(LibraryLoader.LIB_WINDOW_PATH_NAME);
      } catch (FileNotFoundException ex) {
        System.err.println(ex.getMessage());
        System.exit(2);
      }
    }

    Params params = new Params();

    BasicConfigurator.configure();
    Logger.getRootLogger().setLevel(Level.INFO);

    RdpClient.logger = Logger.getLogger(RdpClient.class);

    // Init Ulteo Logger instance
    String log_dir = ".";
    if (!org.ulteo.Logger.initInstance(
        true,
        log_dir + System.getProperty("file.separator") + org.ulteo.Logger.getDate() + ".log",
        true)) System.err.println("Unable to iniatialize logger instance");

    LongOpt[] alo = new LongOpt[4];
    alo[0] = new LongOpt("persistent-cache-location", LongOpt.REQUIRED_ARGUMENT, null, 0);
    alo[1] = new LongOpt("persistent-cache-maxsize", LongOpt.REQUIRED_ARGUMENT, null, 1);
    alo[2] = new LongOpt("disable-all-cache", LongOpt.NO_ARGUMENT, null, 2);
    alo[3] = new LongOpt("ovd_mode", LongOpt.OPTIONAL_ARGUMENT, null, 3);
    Getopt opt = new Getopt(RdpClient.productName, args, "u:p:g:Ams:o:zP", alo);

    int c;
    while ((c = opt.getopt()) != -1) {
      switch (c) {
        case 0: // --persistent-cache-location
          params.persistentCachePath = opt.getOptarg();
          break;
        case 1: // --persistent-cache-maxsize
          params.persistentCacheMaxSize = Integer.parseInt(opt.getOptarg());
          break;
        case 2: // --disable-all-cache
          params.volatileCache = false;
          break;
        case 3: // --ovd_mode
          params.ovd_environnement = true;
          String mode = opt.getOptarg();
          if ((mode != null)
              && (opt.getOptarg()
                  .equalsIgnoreCase(SessionManagerCommunication.SESSION_MODE_REMOTEAPPS)))
            params.ovd_mode = Properties.MODE_REMOTEAPPS;
          break;
        case 'u':
          params.username = new String(opt.getOptarg());
          break;
        case 'p':
          params.password = new String(opt.getOptarg());
          break;
        case 'g':
          String geometry = opt.getOptarg();
          int index = geometry.indexOf('x');
          if (index == -1) {
            RdpClient.logger.warn(
                "Bad geometry, keep default geometry: "
                    + RdpConnection.DEFAULT_WIDTH
                    + "x"
                    + RdpConnection.DEFAULT_HEIGHT);
            break;
          }
          params.width = Integer.parseInt(geometry.substring(0, index)) & ~3;
          params.height = Integer.parseInt(geometry.substring(index + 1, geometry.length()));
          break;
        case 'A':
          params.seamless = true;
          break;
        case 'm':
          params.multimedia = true;
          break;
        case 's':
          params.shell = new String(opt.getOptarg());
          break;
        case 'o':
          params.bpp = Integer.parseInt(opt.getOptarg());
          break;
        case 'z':
          params.packetCompression = true;
          break;
        case 'P':
          params.persistentCache = true;
        default:
          break;
      }
    }

    if (params.username == null || params.password == null) usage();

    if (opt.getOptind() < args.length) {
      String tmp = new String(args[args.length - 1]);
      int separatorPosition = tmp.indexOf(":");
      if (separatorPosition == -1) {
        params.server = tmp;
      } else {
        params.server = tmp.substring(0, separatorPosition);
        tmp = tmp.substring(separatorPosition + 1);
        try {
          int port = Integer.parseInt(tmp);
          if (port < 1 || port > 65535) {
            org.ulteo.Logger.error("Bad port range('" + port + "'): must be between 1 and 65535");
            usage();
          }
          params.port = port;
        } catch (NumberFormatException nfe) {
          org.ulteo.Logger.error(
              "Failed to parse the port number('" + tmp + "'): " + nfe.getMessage());
          usage();
        }
      }
    } else usage();

    try {
      RdpClient client = new RdpClient(params);

      client.connect();
    } catch (RdesktopException ex) {
      RdpClient.logger.fatal(ex.getMessage());
    }
  }
Esempio n. 19
0
  public static void main(final String[] args) throws Exception {
    if (args.length == 0) {
      displayUsage();
      System.exit(0);
    }

    String sopts = "-:hD:s:n:a:u:p:Se:H:";
    LongOpt[] lopts = {
      new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'h'),
      new LongOpt("server", LongOpt.REQUIRED_ARGUMENT, null, 's'),
      new LongOpt("adapter", LongOpt.REQUIRED_ARGUMENT, null, 'a'),
      new LongOpt("serverName", LongOpt.REQUIRED_ARGUMENT, null, 'n'),
      new LongOpt("shutdown", LongOpt.NO_ARGUMENT, null, 'S'),
      new LongOpt("exit", LongOpt.REQUIRED_ARGUMENT, null, 'e'),
      new LongOpt("halt", LongOpt.REQUIRED_ARGUMENT, null, 'H'),
      new LongOpt("user", LongOpt.REQUIRED_ARGUMENT, null, 'u'),
      new LongOpt("password", LongOpt.REQUIRED_ARGUMENT, null, 'p'),
    };

    Getopt getopt = new Getopt(PROGRAM_NAME, args, sopts, lopts);
    int code;
    String arg;

    String serverURL = null;
    String adapterName = "jmx/rmi/RMIAdaptor";
    String username = null;
    String password = null;
    ObjectName serverJMXName = ObjectNameFactory.create("jboss.system:type=JVMShutdown");
    boolean exit = false;
    boolean halt = false;
    int exitcode = -1;

    while ((code = getopt.getopt()) != -1) {
      switch (code) {
        case ':':
        case '?':
          // for now both of these should exit with error status
          System.exit(1);
          break;

        case 1:
          // this will catch non-option arguments
          // (which we don't currently care about)
          System.err.println(PROGRAM_NAME + ": unused non-option argument: " + getopt.getOptarg());
          break;
        case 'h':
          displayUsage();
          System.exit(0);
          break;
        case 'D':
          {
            // set a system property
            arg = getopt.getOptarg();
            String name, value;
            int i = arg.indexOf("=");
            if (i == -1) {
              name = arg;
              value = "true";
            } else {
              name = arg.substring(0, i);
              value = arg.substring(i + 1, arg.length());
            }
            System.setProperty(name, value);
            break;
          }
        case 's':
          serverURL = getopt.getOptarg();
          break;
        case 'n':
          serverJMXName = new ObjectName(getopt.getOptarg());
          break;
        case 'S':
          // nothing...
          break;
        case 'a':
          adapterName = getopt.getOptarg();
          break;
        case 'u':
          username = getopt.getOptarg();
          SecurityAssociation.setPrincipal(new SimplePrincipal(username));
          break;
        case 'p':
          password = getopt.getOptarg();
          SecurityAssociation.setCredential(password);
          break;
        case 'e':
          exitcode = Integer.parseInt(getopt.getOptarg());
          exit = true;
          break;
        case 'H':
          exitcode = Integer.parseInt(getopt.getOptarg());
          halt = true;
          break;
      }
    }

    InitialContext ctx;

    // If there was a username specified, but no password prompt for it
    if (username != null && password == null) {
      System.out.print("Enter password for " + username + ": ");
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      password = br.readLine();
      SecurityAssociation.setCredential(password);
    }

    if (serverURL == null) {
      ctx = new InitialContext();
    } else {
      Hashtable env = new Hashtable();
      env.put(Context.PROVIDER_URL, serverURL);
      env.put(NamingContext.JNP_DISABLE_DISCOVERY, "true");
      // This is a hack
      if (serverURL.startsWith("http:") || serverURL.startsWith("https:"))
        env.put(Context.INITIAL_CONTEXT_FACTORY, HttpNamingContextFactory.class.getName());
      ctx = new InitialContext(env);
    }

    Object obj = ctx.lookup(adapterName);
    if (!(obj instanceof MBeanServerConnection)) {
      throw new RuntimeException(
          "Object not of type: MBeanServerConnection, but: "
              + (obj == null ? "not found" : obj.getClass().getName()));
    }

    MBeanServerConnection adaptor = (MBeanServerConnection) obj;
    ServerProxyHandler handler = new ServerProxyHandler(adaptor, serverJMXName);
    Class<?>[] ifaces = {JVMShutdownMBean.class};
    ClassLoader tcl = Thread.currentThread().getContextClassLoader();
    JVMShutdownMBean server = (JVMShutdownMBean) Proxy.newProxyInstance(tcl, ifaces, handler);

    if (exit) {
      server.exit(exitcode);
    } else if (halt) {
      server.halt(exitcode);
    } else {
      server.shutdown();
    }
    System.out.println("Shutdown message has been posted to the server.");
    System.out.println("Server shutdown may take a while - check logfiles for completion");
  }