public static Options parseArgs(String cmdArgs[]) {
      CommandLineParser parser = new GnuParser();
      CmdLineOptions options = getCmdLineOptions();
      try {
        CommandLine cmd = parser.parse(options, cmdArgs, false);

        if (cmd.hasOption(HELP_OPTION)) {
          printUsage(options);
          System.exit(0);
        }

        String[] args = cmd.getArgs();
        if (args.length == 0) {
          System.err.println("No sstables to split");
          printUsage(options);
          System.exit(1);
        }
        Options opts = new Options(Arrays.asList(args));
        opts.debug = cmd.hasOption(DEBUG_OPTION);
        opts.verbose = cmd.hasOption(VERBOSE_OPTION);
        opts.snapshot = !cmd.hasOption(NO_SNAPSHOT_OPTION);
        opts.sizeInMB = DEFAULT_SSTABLE_SIZE;

        if (cmd.hasOption(SIZE_OPTION))
          opts.sizeInMB = Integer.valueOf(cmd.getOptionValue(SIZE_OPTION));

        return opts;
      } catch (ParseException e) {
        errorMsg(e.getMessage(), options);
        return null;
      }
    }
Example #2
0
	public static void main(String[] args) throws IOException {
		boolean ret = true;
		String[] leftedArgs = ginit(args);
		if(leftedArgs.length > 1) System.exit(1);
		else if(leftedArgs.length == 0) interactiveFlag = true;
		
		if(builtinTest != null) {
			System.exit(builtinTest(builtinTest));
		}
		if(testScript != null) {
			System.exit(test(testScript));
		}
		CTX konoha = open();
		if(startupScript != null) {
			startup(konoha, startupScript);
		}
		if(leftedArgs.length == 1) {
			ret = load(konoha, leftedArgs[0]);
		}
		if(ret && (interactiveFlag != false)) {    // TODO interactiveFlag to boolean?
			ret = kShell(konoha);
		}
		close(konoha);
		// MODGC_check_malloced_size()
		System.exit(ret ? assertResult : 1);
	}
  public static void main(String args[]) throws IOException {
    LoaderOptions options = LoaderOptions.parseArgs(args);
    try {
      SSTableLoader loader =
          new SSTableLoader(options.directory, new ExternalClient(options), options);
      SSTableLoader.LoaderFuture future = loader.stream(options.ignores);

      if (options.noProgress) {
        future.get();
      } else {
        ProgressIndicator indicator = new ProgressIndicator(future.getPendingFiles());
        indicator.start();
        System.out.println("");
        while (!future.isDone()) {
          if (indicator.printProgress()) {
            // We're done with streaming
            System.out.println("\nWaiting for targets to rebuild indexes ...");
            future.get();
            assert future.isDone();
          } else {
            try {
              Thread.sleep(1000L);
            } catch (Exception e) {
            }
          }
        }
      }

      System.exit(0); // We need that to stop non daemonized threads
    } catch (Exception e) {
      System.err.println(e.getMessage());
      if (options.debug) e.printStackTrace(System.err);
      System.exit(1);
    }
  }
    public static Options parseArgs(String cmdArgs[]) {
      CommandLineParser parser = new GnuParser();
      CmdLineOptions options = getCmdLineOptions();
      try {
        CommandLine cmd = parser.parse(options, cmdArgs, false);

        if (cmd.hasOption(HELP_OPTION)) {
          printUsage(options);
          System.exit(0);
        }

        String[] args = cmd.getArgs();
        if (args.length >= 4 || args.length < 2) {
          String msg = args.length < 2 ? "Missing arguments" : "Too many arguments";
          errorMsg(msg, options);
          System.exit(1);
        }

        String keyspace = args[0];
        String cf = args[1];
        String snapshot = null;
        if (args.length == 3) snapshot = args[2];

        Options opts = new Options(keyspace, cf, snapshot);

        opts.debug = cmd.hasOption(DEBUG_OPTION);
        opts.keepSource = cmd.hasOption(KEEP_SOURCE);

        return opts;
      } catch (ParseException e) {
        errorMsg(e.getMessage(), options);
        return null;
      }
    }
Example #5
0
  public int ParseAuth(BufferedReader bufferedReader, int count, Logger runtimeLogger) {

    try {

      while (true) {

        String line = bufferedReader.readLine();
        count++;

        if ("[/auth]".equalsIgnoreCase(line)) {
          break;
        }

        if (line.startsWith("#") | "".equals(line)) {
          continue;
        }

        String[] words = line.split(":");
        if (words.length == 2) {

          Pattern pattern;
          Matcher matcher;

          String regexUsername = "******";
          pattern = Pattern.compile(regexUsername);
          matcher = pattern.matcher(words[0]);
          if (!matcher.find()) {
            runtimeLogger.error(
                String.format(
                    "Auth config error occurs at line %d: invalid username %s", count, words[0]));
            System.exit(-1);
          }

          String regexPassword = "******";
          pattern = Pattern.compile(regexPassword);
          matcher = pattern.matcher(words[1]);
          if (!matcher.find()) {
            runtimeLogger.error(
                String.format(
                    "Auth config error occurs at line %d: invalid password %s", count, words[0]));
            System.exit(-1);
          }

          username = words[0];
          password = words[1];

        } else {
          runtimeLogger.error(String.format("Auth error occurs at line %d", count));
          System.exit(-1);
        }
      }
      return count;

    } catch (IOException e) {
      runtimeLogger.error(e.getMessage(), e);
      return 0;
    }
  }
    public static LoaderOptions parseArgs(String cmdArgs[]) {
      CommandLineParser parser = new GnuParser();
      CmdLineOptions options = getCmdLineOptions();
      try {
        CommandLine cmd = parser.parse(options, cmdArgs, false);

        if (cmd.hasOption(HELP_OPTION)) {
          printUsage(options);
          System.exit(0);
        }

        String[] args = cmd.getArgs();
        if (args.length == 0) {
          System.err.println("Missing sstable directory argument");
          printUsage(options);
          System.exit(1);
        }

        if (args.length > 1) {
          System.err.println("Too many arguments");
          printUsage(options);
          System.exit(1);
        }

        String dirname = args[0];
        File dir = new File(dirname);

        if (!dir.exists()) errorMsg("Unknown directory: " + dirname, options);

        if (!dir.isDirectory()) errorMsg(dirname + " is not a directory", options);

        LoaderOptions opts = new LoaderOptions(dir);

        opts.debug = cmd.hasOption(DEBUG_OPTION);
        opts.verbose = cmd.hasOption(VERBOSE_OPTION);
        opts.noProgress = cmd.hasOption(NOPROGRESS_OPTION);

        if (cmd.hasOption(IGNORE_NODES_OPTION)) {
          String[] nodes = cmd.getOptionValue(IGNORE_NODES_OPTION).split(",");
          try {
            for (String node : nodes) {
              opts.ignores.add(InetAddress.getByName(node));
            }
          } catch (UnknownHostException e) {
            errorMsg(e.getMessage(), options);
          }
        }

        return opts;
      } catch (ParseException e) {
        errorMsg(e.getMessage(), options);
        return null;
      }
    }
Example #7
0
  public int ParseServer(BufferedReader bufferedReader, int count, Logger runtimeLogger) {

    try {

      while (true) {

        String line = bufferedReader.readLine();
        count++;

        if ("[/server]".equalsIgnoreCase(line)) {
          break;
        }

        if (line.startsWith("#") | "".equals(line)) {
          continue;
        }

        String regexDomain = "(?:(?:\\d{1,3}){1,3}\\d{1,3})|(?:(?:[\\w|-]+){2,})";
        Pattern pattern = Pattern.compile(regexDomain);
        Matcher matcher = pattern.matcher(line);

        if (!matcher.find()) {
          runtimeLogger.error(String.format("Server address %s format is wrong", line));
          System.exit(-1);
        }

        serverAddress = line;
      }
      return count;

    } catch (IOException e) {
      runtimeLogger.error(e.getMessage(), e);
      return 0;
    }
  }
 public static int getBStartAddress() {
   if (b_start_address == -1) {
     System.err.println("B Start Address is not yet set!");
     System.exit(-1);
   }
   return b_start_address;
 }
Example #9
0
  public static void main(String[] args) throws Exception {
    final Configuration conf = new Configuration();
    initalizeConf(conf, args);

    int res = ToolRunner.run(conf, new FrameworkDriver(), args);
    System.exit(res);
  }
Example #10
0
  public static void main(String args[]) {

    Throwable anyError = null;
    ParameterProblem paramError = null;
    ExecutionProblem execError = null;
    int ret = EXIT_OK;
    try {
      final AdminClient adminClient = new AdminClient();
      adminClient.setupDebug(args);
      adminClient.run(args);

    } catch (ParameterProblem e) {
      paramError = e;
      anyError = e;
      ret = EXIT_PARAMETER_PROBLEM;
    } catch (ExecutionProblem e) {
      execError = e;
      anyError = e;
      ret = EXIT_EXECUTION_PROBLEM;
    } catch (Throwable t) {
      anyError = t;
      ret = EXIT_UNKNOWN_PROBLEM;
    }

    if (anyError == null) {
      System.exit(ret);
    } else {
      logger.debug("Got error", anyError);
    }

    if (paramError != null) {
      System.err.println("Parameter Problem:\n\n" + paramError.getMessage());
      System.err.println("See --help");

    } else if (execError != null) {
      System.err.println(execError.getMessage());
    } else {
      System.err.println("An unexpected error was encountered. Please report this!");
      System.err.println(anyError.getMessage());
      System.err.println();
      System.err.println("Stack trace:");
      anyError.printStackTrace(System.err);
    }

    System.exit(ret);
  }
Example #11
0
 /**
  * startLogger initializes and returns a file at logLoc with the results of logging at level
  * logLevel.
  *
  * @param logLoc location of the output log file- a string
  * @param logLevel logging level (is parsed by level.parse())
  * @return Logger object to log to.
  */
 public Logger startLogger(String logLoc, String logLevel) {
   try {
     fh = new FileHandler(logLoc); // sets output log file at logLoc
   } catch (SecurityException e) {
     e.printStackTrace();
     System.err.println("SecurityException establishing logger. Exiting...\n");
     System.exit(1);
   } catch (IOException e) {
     e.printStackTrace();
     System.err.println("IOException establishing logger. Exiting...\n");
     System.exit(1);
   }
   fh.setFormatter(new SimpleFormatter()); // format of log is 'human-readable' simpleformat
   logger.addHandler(fh); // attach formatter to logger
   logger.setLevel(Level.parse(logLevel)); // set log level
   return logger;
 }
Example #12
0
  // TODO add exception for invalid options
  private void loadCLO(String[] args) {
    Options options = new Options();

    String[][] clolist = {
      // {"variable/optionname", "description"},
      {"genConfig", "general configuration file location"},
      {"inWeightsLoc", "input weights configuration file location"},
      {"inDBLoc", "input database file location"},
      {"outWeightsLoc", "output weights configuration file location"},
      {"outDBLoc", "output database file location"},
      {"p3pLocation", "adding to DB: single policy file location"},
      {"p3pDirLocation", "adding to DB: multiple policy directory location"},
      {"newDB", "create new database in place of old one (doesn't check for existence of old one"},
      {"newPolicyLoc", "the policy object to process"},
      {"userResponse", "response to specified policy"},
      {"userIO", "user interface"},
      {"userInit", "initialization via user interface"},
      {"policyDB", "PolicyDatabase backend"},
      {"cbrV", "CBR to use"},
      {"blanketAccept", "automatically accept the user suggestion"},
      {"loglevel", "level of things save to the log- see java logging details"},
      {"policyDB", "PolicyDatabase backend"},
      {"NetworkRType", "Network Resource type"},
      {"NetworkROptions", "Network Resource options"},
      {"confidenceLevel", "Confidence threshold for consulting a networked resource"},
      {"useNet", "use networking options"},
      {"loglocation", "where to save the log file"},
      {"loglevel", "the java logging level to use. See online documentation for enums."}
    };

    for (String[] i : clolist) {
      options.addOption(i[0], true, i[1]);
    }

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
      cmd = parser.parse(options, args);
    } catch (ParseException e) {
      System.err.println("Error parsing commandline arguments.");
      e.printStackTrace();
      System.exit(3);
    }
    /*
    for(String i : args)
    {
    	System.err.println(i);
    }
    */
    for (String[] i : clolist) {
      if (cmd.hasOption(i[0])) {
        System.err.println("found option i: " + i);
        genProps.setProperty(i[0], cmd.getOptionValue(i[0]));
      }
    }
    System.err.println(genProps);
  }
Example #13
0
 /**
  * Primary entry point for compiling from the command line (using the groovyc script).
  *
  * <p>If calling inside a process and you don't want the JVM to exit on an error call
  * commandLineCompile(String[]), which this method simply wraps
  *
  * @param args command line arguments
  * @param lookupUnnamedFiles do a lookup for .groovy files not part of the given list of files to
  *     compile
  */
 public static void commandLineCompileWithErrorHandling(
     String[] args, boolean lookupUnnamedFiles) {
   try {
     commandLineCompile(args, lookupUnnamedFiles);
   } catch (Throwable e) {
     new ErrorReporter(e, displayStackTraceOnError).write(System.err);
     System.exit(1);
   }
 }
Example #14
0
  private void parseCmdLine(String[] args) {
    CommandLineParser parser = new PosixParser();

    Options options = new Options();
    options.addOption("v", "version", false, "Q2's version");
    options.addOption("d", "deploydir", true, "Deployment directory");
    options.addOption("r", "recursive", false, "Deploy subdirectories recursively");
    options.addOption("h", "help", false, "Usage information");
    options.addOption("C", "config", true, "Configuration bundle");
    options.addOption("e", "encrypt", true, "Encrypt configuration bundle");
    options.addOption("i", "cli", false, "Command Line Interface");
    options.addOption("c", "command", true, "Command to execute");

    try {
      CommandLine line = parser.parse(options, args);
      if (line.hasOption("v")) {
        displayVersion();
        System.exit(0);
      }
      if (line.hasOption("h")) {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp("Q2", options);
        System.exit(0);
      }
      if (line.hasOption("c")) {
        cli = new CLI(this, line.getOptionValue("c"), line.hasOption("i"));
      } else if (line.hasOption("i")) cli = new CLI(this, null, true);

      String dir = DEFAULT_DEPLOY_DIR;
      if (line.hasOption("d")) {
        dir = line.getOptionValue("d");
      }
      recursive = line.hasOption("r");
      this.deployDir = new File(dir);
      if (line.hasOption("C")) deployBundle(new File(line.getOptionValue("C")), false);
      if (line.hasOption("e")) deployBundle(new File(line.getOptionValue("e")), true);
    } catch (MissingArgumentException e) {
      System.out.println("ERROR: " + e.getMessage());
      System.exit(1);
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
  public static void main(String args[]) {
    Config.setClientMode(true);
    LoaderOptions options = LoaderOptions.parseArgs(args);
    OutputHandler handler = new OutputHandler.SystemOutput(options.verbose, options.debug);
    SSTableLoader loader =
        new SSTableLoader(
            options.directory,
            new ExternalClient(
                options.hosts,
                options.rpcPort,
                options.user,
                options.passwd,
                options.transportFactory,
                options.storagePort,
                options.sslStoragePort,
                options.serverEncOptions),
            handler);
    DatabaseDescriptor.setStreamThroughputOutboundMegabitsPerSec(options.throttle);
    StreamResultFuture future = null;
    try {
      if (options.noProgress) future = loader.stream(options.ignores);
      else future = loader.stream(options.ignores, new ProgressIndicator());
    } catch (Exception e) {
      System.err.println(e.getMessage());
      if (e.getCause() != null) System.err.println(e.getCause());
      if (options.debug) e.printStackTrace(System.err);
      else System.err.println("Run with --debug to get full stack trace or --help to get help.");
      System.exit(1);
    }

    handler.output(String.format("Streaming session ID: %s", future.planId));

    try {
      future.get();
      System.exit(0); // We need that to stop non daemonized threads
    } catch (Exception e) {
      System.err.println("Streaming to the following hosts failed:");
      System.err.println(loader.getFailedHosts());
      System.err.println(e);
      if (options.debug) e.printStackTrace(System.err);
      System.exit(1);
    }
  }
Example #16
0
 /**
  * writes a property file to disk
  *
  * @param wprops the property file to write
  * @param wloc where to write to
  */
 private void writePropertyFile(Properties wprops, String wloc) {
   if (wprops == null) System.out.println("wrops null in gio/writepropertyfile");
   if (wloc == null) System.out.println("wloc null in gio/writepropertyfile");
   try {
     wprops.store(new FileOutputStream(wloc), null);
   } catch (IOException e) {
     System.err.println("Error writing weights to file.");
     e.printStackTrace();
     System.exit(3);
   }
 }
Example #17
0
  /**
   * converts a string into a valid CBR
   *
   * @param string the string to parse
   * @return the CBR to use
   * @throws Exception
   */
  private CBR parseCBR(String string) throws Exception {

    try {
      return (string == null) ? (null) : (new CBR(this)).parse(string);
    } catch (Exception e) {
      System.err.println("error parsing CBR, exiting.");
      e.printStackTrace();
      System.exit(5);
      return null;
    }
  }
Example #18
0
  public static void main(String[] args) throws Exception {
    TajoConf conf = new TajoConf();

    Writer writer = new PrintWriter(System.out);
    try {
      TajoGetConf admin = new TajoGetConf(conf, writer);
      admin.runCommand(args, false);
    } finally {
      writer.close();
      System.exit(0);
    }
  }
Example #19
0
  // TODO add exception for invalid options
  public Properties loadFromConfig(String fileLoc) {
    Properties configFile = new Properties();

    try {
      File localConfig = new File(fileLoc);
      InputStream is = null;
      if (localConfig.exists()) {
        is = new FileInputStream(localConfig);
      } else {
        System.err.println(
            "No configuration file at " + fileLoc + ". Please place one in the working directory.");
        System.exit(3);
      }
      configFile.load(is);
    } catch (IOException e) {
      e.printStackTrace();
      System.err.println("IOException reading first configuration file. Exiting...\n");
      System.exit(1);
    }

    return configFile;
  }
Example #20
0
	public static void startup(CTX konoha, String startup_script) {
		String[] buf = new String[256];
		String path = System.getenv("KONOHA_SCRIPTPATH");
		String local = "";
		if (path == null) {
			path = System.getenv("KONOHA_HOME");
			local = "/script";
		}	
		if (path == null) {
			path = System.getenv("HOME");
			local = "/.konoha/script";
		}
		//TODO snprintf(buf, sizeof(buf), "%s%s%s.k", path, local, startup_script);
		if (true /*TODO load(konoha, (const char*)buf)*/ ) {
			System.exit(1);
		}
	}
Example #21
0
  /**
   * returns the policy object from the policyObject option
   *
   * @return the policy object to be processed
   */
  public void loadPO() {

    if (genProps.getProperty("newPolicyLoc", null) == null)
      System.err.println("newPolLoc == null in gio:loadPO");
    File pLoc = new File(genProps.getProperty("newPolicyLoc", null));
    if (!pLoc.exists()) {
      System.err.println("no file found at p3p policy location specified by the new policy option");
      System.exit(1);
    }

    po = (new P3PParser()).parse(pLoc.getAbsolutePath());
    // TODO make sure that the context is parsed if avaliable
    if (po.getContext().getDomain() == null) {
      po.setContext(
          new Context(
              new Date(System.currentTimeMillis()),
              new Date(System.currentTimeMillis()),
              genProps.getProperty("newPolicyLoc")));
    }
  }
  private double computeStats(final int start, final int end, final String title) {
    double sum = 0.0;
    double min = Double.MAX_VALUE;
    double max = Double.MIN_VALUE;

    for (int i = start; i < end; i++) {
      final double ts = timestamps[i] / 1000.0;
      if (ts < 0) {
        System.exit(1);
      }
      sum += ts;
      if (ts < min) {
        min = ts;
      }
      if (ts > max) {
        max = ts;
      }
    }
    System.out.println("Mean latency for " + title + ": " + sum / (end - start));
    return sum / (end - start);
  }
  private static boolean sendCacheRequest(Cache cache, String matrix, int i, int j, int size) {
    // different matrices are located in different places in the memory, this
    // is modelled by using a matrix-specific base address.
    int base = 0;
    if (matrix.compareTo("A") == 0) base = 0;
    else if (matrix.compareTo("B") == 0) base = getBStartAddress();
    else if (matrix.compareTo("Cread") == 0) base = 8 * size * size + 128;
    else if (matrix.compareTo("Cwrite") == 0) base = 8 * size * size + 128;
    else {
      System.err.println("Matrix " + matrix + "not recognized, please use A, B or C");
      System.exit(-1);
    }

    // Address is calculated (multiply by 4 assumes int equals 4B).
    int address = base + 4 * ((i * size) + j);

    boolean hit = cache.request(address);

    // Print out the address  (comment out the following line if needed)
    System.out.println(matrix + ": " + address + (hit ? "" : " *"));

    return hit;
  }
  /**
   * Given arguments specifying an SSTable, and optionally an output file, export the contents of
   * the SSTable to JSON.
   *
   * @param args command lines arguments
   * @throws ConfigurationException on configuration failure (wrong params given)
   */
  public static void main(String[] args) throws ConfigurationException {
    CommandLineParser parser = new PosixParser();
    try {
      cmd = parser.parse(options, args);
    } catch (ParseException e1) {
      System.err.println(e1.getMessage());
      printUsage();
      System.exit(1);
    }

    if (cmd.getArgs().length != 1) {
      System.err.println("You must supply exactly one sstable");
      printUsage();
      System.exit(1);
    }

    String[] keys = cmd.getOptionValues(KEY_OPTION);
    HashSet<String> excludes =
        new HashSet<>(
            Arrays.asList(
                cmd.getOptionValues(EXCLUDE_KEY_OPTION) == null
                    ? new String[0]
                    : cmd.getOptionValues(EXCLUDE_KEY_OPTION)));
    String ssTableFileName = new File(cmd.getArgs()[0]).getAbsolutePath();

    if (Descriptor.isLegacyFile(new File(ssTableFileName))) {
      System.err.println("Unsupported legacy sstable");
      System.exit(1);
    }
    if (!new File(ssTableFileName).exists()) {
      System.err.println("Cannot find file " + ssTableFileName);
      System.exit(1);
    }
    Descriptor desc = Descriptor.fromFilename(ssTableFileName);
    try {
      CFMetaData metadata = metadataFromSSTable(desc);
      if (cmd.hasOption(ENUMERATE_KEYS_OPTION)) {
        JsonTransformer.keysToJson(
            null,
            iterToStream(new KeyIterator(desc, metadata)),
            cmd.hasOption(RAW_TIMESTAMPS),
            metadata,
            System.out);
      } else {
        SSTableReader sstable = SSTableReader.openNoValidation(desc, metadata);
        IPartitioner partitioner = sstable.getPartitioner();
        final ISSTableScanner currentScanner;
        if ((keys != null) && (keys.length > 0)) {
          List<AbstractBounds<PartitionPosition>> bounds =
              Arrays.stream(keys)
                  .filter(key -> !excludes.contains(key))
                  .map(metadata.getKeyValidator()::fromString)
                  .map(partitioner::decorateKey)
                  .sorted()
                  .map(DecoratedKey::getToken)
                  .map(token -> new Bounds<>(token.minKeyBound(), token.maxKeyBound()))
                  .collect(Collectors.toList());
          currentScanner = sstable.getScanner(bounds.iterator());
        } else {
          currentScanner = sstable.getScanner();
        }
        Stream<UnfilteredRowIterator> partitions =
            iterToStream(currentScanner)
                .filter(
                    i ->
                        excludes.isEmpty()
                            || !excludes.contains(
                                metadata.getKeyValidator().getString(i.partitionKey().getKey())));
        if (cmd.hasOption(DEBUG_OUTPUT_OPTION)) {
          AtomicLong position = new AtomicLong();
          partitions.forEach(
              partition -> {
                position.set(currentScanner.getCurrentPosition());

                if (!partition.partitionLevelDeletion().isLive()) {
                  System.out.println(
                      "["
                          + metadata.getKeyValidator().getString(partition.partitionKey().getKey())
                          + "]@"
                          + position.get()
                          + " "
                          + partition.partitionLevelDeletion());
                }
                if (!partition.staticRow().isEmpty()) {
                  System.out.println(
                      "["
                          + metadata.getKeyValidator().getString(partition.partitionKey().getKey())
                          + "]@"
                          + position.get()
                          + " "
                          + partition.staticRow().toString(metadata, true));
                }
                partition.forEachRemaining(
                    row -> {
                      System.out.println(
                          "["
                              + metadata
                                  .getKeyValidator()
                                  .getString(partition.partitionKey().getKey())
                              + "]@"
                              + position.get()
                              + " "
                              + row.toString(metadata, false, true));
                      position.set(currentScanner.getCurrentPosition());
                    });
              });
        } else {
          JsonTransformer.toJson(
              currentScanner, partitions, cmd.hasOption(RAW_TIMESTAMPS), metadata, System.out);
        }
      }
    } catch (IOException e) {
      // throwing exception outside main with broken pipe causes windows cmd to hang
      e.printStackTrace(System.err);
    }

    System.exit(0);
  }
Example #25
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);
  }
Example #26
0
 private static void exit() {
   System.exit(0);
 }
Example #27
0
  /*
   *main function
   */
  public static void main(String args[]) {
    String title1 = " ";
    String publisher_name1 = " ";
    String published_date1 = "";
    String content1 = "";
    int n = 0;
    String str = "";

    // try block starts here
    try {
      Options option = new Options();
      option.addOption("hp", false, "help");
      option.addOption("hlp", false, "help");
      CommandLineParser parser = new DefaultParser();
      CommandLine cmd = parser.parse(option, args);
      // str=cmd.getArgs()[0];

      /*prints the help message here*/
      if ((cmd.hasOption("hp")) || (cmd.hasOption("hlp"))) {
        System.out.println(
            "this program gets an argument through commandline 'n' number of books. then reads n books from standard input"
                + "and prints them on standard output");

        if (args.length <= 1) {

          // exit the program
          System.exit(0);
        }
      } // close outer if block
      else {
        if (args.length < 1) {

          // if user not gives option  and value of n then prints this message.
          System.out.println(
              "this program gets an argument through commandline 'n' number of books. then reads n books from standard input"
                  + "and prints them on standard output");
          System.exit(0);
        }
      } // close the  outer else block

      str = cmd.getArgs()[0];
      n = Integer.parseInt(str);

    } catch (Exception e) {
      // System.exit(0);
      // if any erroy occurs it catches here
      System.out.println(e);
    }

    int num = 0;
    Scanner sc1 = new Scanner(System.in); /*create an instance of scanner object*/
    Scanner sc = new Scanner(System.in);

    CmdBook b[] = new CmdBook[n]; /* create arraylist of objects of class Book*/
    for (int i = 0; i < n; i++) {

      // initialise the array of objects
      b[i] = new CmdBook();
    }
    for (int i = 0; i < n; i++) {

      /* take input from  standard input*/
      System.out.println("enter the title of the book:");
      title1 = sc.next();

      System.out.println("enter the name of publisher");
      publisher_name1 = sc.next();

      System.out.println("enter published date");
      published_date1 = sc.next();

      System.out.println("how many authors are");
      num = sc1.nextInt();

      ArrayList<String> author_name1 =
          new ArrayList<String>(); /*create an ArrayList author_name1 */

      for (int j = 0; j < num; j++) {

        /*take input */
        System.out.println("enter authorname" + (j + 1));
        author_name1.add(sc.next());
      }

      System.out.println("enter contents of book:");
      content1 = sc.next();

      /* call the method bookdetail with auguments which contains from
       *  standard input
       */

      b[i].bookdetail(title1, publisher_name1, published_date1, content1, author_name1);
    }
    for (int i = 0; i < n; i++) {

      /*call the methode printbook withe no aurgument*/
      b[i].printbook();
    }
  } /*end of main function here*/
Example #28
0
 /**
  * Calls the exit method
  *
  * @param code return code to exit with
  */
 public void exit(final int code) {
   System.exit(code);
 }
  // This function generates the access pattern for a straightforward matrix multiplication.
  private static void matrixTiledMultiply(Cache cache, int size) {
    // Set tilesize
    int tilesize = 2;
    if (size % tilesize != 0) {
      System.out.println("tilesize must be N*size!");
      System.exit(-1);
    }

    // Statistics
    int requests = 0;
    int hits = 0;

    // Define matrices for A*B=C
    int A[][] = new int[size][size];
    int B[][] = new int[size][size];
    int C[][] = new int[size][size];

    setBStartAddress(size, -1);

    // Initialize matrix
    for (int i = 0; i < size; i++) {
      for (int j = 0; j < size; j++) {
        A[i][j] = i;
        B[i][j] = j;
        C[i][j] = 0;
      }
    }

    // Print matrix (for verification)
    // System.out.println("////////////////////////////////////////////////////////////////////////////////");
    // System.out.println("/////////////////////////////// Input Matrix
    // ///////////////////////////////////");
    // System.out.println("////////////////////////////////////////////////////////////////////////////////");
    // A
    // System.out.println("A=\t");
    // for (int i=0;i<size;i++)
    // {
    //	System.out.print("\t");
    //	for (int j=0;j<size;j++)
    //	{
    //		System.out.print(A[ i ][ j ]);
    //		System.out.print("\t");
    //	}
    //	System.out.println();
    // }
    // B
    // System.out.println("B=\t");
    // for (int i=0;i<size;i++)
    // {
    //	System.out.print("\t");
    //	for (int j=0;j<size;j++)
    //	{
    //		System.out.print(B[ i ][ j ]);
    //		System.out.print("\t");
    //	}
    //	System.out.println();
    // }

    // Now do A*B=C
    for (int i0 = 0; i0 < size; i0 += tilesize) {
      for (int j0 = 0; j0 < size; j0 += tilesize) {
        for (int k0 = 0; k0 < size; k0 += tilesize) {
          for (int i = i0; i < (i0 + tilesize); i++) {
            for (int j = j0; j < (j0 + tilesize); j++) {
              for (int k = k0; k < (k0 + tilesize); k++) {
                C[i][j] = C[i][j] + A[i][k] * B[k][j];

                // Read C[i][j]
                requests++;
                if (sendCacheRequest(cache, "Cread", i, j, size)) {
                  hits++;
                }

                // Read A[j][k]
                requests++;
                if (sendCacheRequest(cache, "A", i, k, size)) {
                  hits++;
                }

                // Read B[k][j]
                requests++;
                if (sendCacheRequest(cache, "B", k, j, size)) {
                  hits++;
                }

                // Write C[i][j]
                requests++;
                if (sendCacheRequest(cache, "Cwrite", i, j, size)) {
                  hits++;
                }
              }
            }
          }
        }
      }
    }

    // Print matrix (for verification)
    // System.out.println("////////////////////////////////////////////////////////////////////////////////");
    // System.out.println("/////////////////////////////// Output Matrix
    // //////////////////////////////////");
    // System.out.println("////////////////////////////////////////////////////////////////////////////////");
    // C
    // System.out.println("C=\t");
    // for (int i=0;i<size;i++)
    // {
    //	System.out.print("\t");
    //	for (int j=0;j<size;j++)
    //	{
    //		System.out.print(C[ i ][ j ]);
    //		System.out.print("\t");
    //	}
    //	System.out.println();
    // }

    // Force a cache dump (optional)
    // cache.request(-1);

    // Report the results of the simulation.
    System.out.println(
        "////////////////////////////////////////////////////////////////////////////////");
    System.out.println(
        "//////////////////////////////// Statistics ////////////////////////////////////");
    System.out.println(
        "////////////////////////////////////////////////////////////////////////////////");
    System.out.println("Total Requests: " + requests);
    System.out.println("    Cache Hits: " + hits);
    System.out.println("      Hit Rate: " + ((double) hits) / requests);
    System.out.println();
    System.out.println(
        "////////////////////////////////////////////////////////////////////////////////");
  }
  public static void main(String[] args) {

    Option cacheOpt =
        OptionBuilder.withArgName("cache")
            .hasArgs()
            .withDescription(
                "Type of cache. One of DirectMapped, FullyAssociative, NWaySetAssociative")
            .isRequired()
            .create("cache");
    Option blocksOpt =
        OptionBuilder.withArgName("blocks")
            .hasArg()
            .isRequired()
            .withDescription("The number of blocks in the cache")
            .create("blocks");
    Option linesizeOpt =
        OptionBuilder.withArgName("linesize")
            .hasArg()
            .isRequired()
            .withDescription("")
            .create("linesize");
    Option assocOpt =
        OptionBuilder.withArgName("ways")
            .hasArg()
            .withDescription(
                "Number of ways of the cache. Ignored for a direct mapped cache and a fully associative cache.")
            .create("ways");
    Option patternOpt =
        OptionBuilder.withArgName("pattern")
            .hasArg()
            .isRequired()
            .withDescription(
                "Address pattern to simulate. Can by one of rowMajor, columnMajor, matrixMultiply or matrixTiledMultiply")
            .create("pattern");
    Option bAddressOpt =
        OptionBuilder.withArgName("Bstartaddress")
            .hasArg()
            .withDescription(
                "Start address of array B. If not set, a default, sensible value is used. Only works for rowMajor and columnMajor.")
            .create("Bstartaddress");

    Options options = new Options();
    options.addOption(cacheOpt);
    options.addOption(blocksOpt);
    options.addOption(linesizeOpt);
    options.addOption(assocOpt);
    options.addOption(patternOpt);
    options.addOption(bAddressOpt);

    HelpFormatter formatter = new HelpFormatter();

    CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    try {
      line = parser.parse(options, args);
    } catch (ParseException exp) {
      System.err.println("Parsing of the command line has failed. Here's why: ");
      System.err.println(exp.getMessage());
      formatter.printHelp("CacheSim", options);
      System.exit(-1);
    }

    // The cache should be one of the specified types.
    Cache cache = null;
    try {
      int blocks = Integer.parseInt(line.getOptionValue("blocks"));
      int linesize = Integer.parseInt(line.getOptionValue("linesize"));
      if (!isPowerOf2(blocks) || !isPowerOf2(linesize)) {
        throw new OptionError("Whoops. blocks and linesize must be powers of 2.");
      }
      String ctype = line.getOptionValue("cache");
      if (ctype.equals("DirectMapped")) {
        cache = new DirectMappedCache(blocks, linesize);
      } else if (ctype.equals("FullyAssociative")) {
        cache = new FullyAssociativeCache(blocks, linesize);
      } else if (ctype.equals("NWaySetAssociative")) {
        int assoc = Integer.parseInt(line.getOptionValue("ways"));
        if (blocks % assoc != 0) {
          throw new OptionError(
              "Whoops. blocks should be a multiple of the associativity in a n-way set associative cache");
        }
        cache = new NWayAssociativeCache(blocks / assoc, linesize, assoc);
      } else {
        throw new OptionError("Unknown cache type.");
      }

      String pattern = line.getOptionValue("pattern");

      boolean b_start_address_set = line.hasOption("Bstartaddress");
      int b_start_address = 0;
      if (b_start_address_set) {
        b_start_address = Integer.parseInt(line.getOptionValue("Bstartaddress"));

        if (!pattern.equals("rowMajor") && !pattern.equals("columnMajor")) {
          throw new OptionError(
              "the option Bstartaddress is only supported for the patterns rowMajor and columnMajor");
        }
      }

      if (pattern.equals("rowMajor")) {
        rowMajor(cache, 8, b_start_address_set, b_start_address);
      } else if (pattern.equals("columnMajor")) {
        columnMajor(cache, 8, b_start_address_set, b_start_address);
      } else if (pattern.equals("matrixMultiply")) {
        matrixMultiply(cache, 8);
      } else if (pattern.equals("matrixTiledMultiply")) {
        matrixTiledMultiply(cache, 8);
      } else {
        throw new OptionError("Unknown pattern type.");
      }
    } catch (OptionError exp) {
      System.err.println(exp.getMessage());
      exp.printStackTrace();
      formatter.printHelp("CacheSim", options);
      System.exit(-1);
    }
  }