Esempio n. 1
0
 private static void deleteKey() {
   String pubkey = (String) options.valueOf("pubkey");
   String addr = (String) options.valueOf("addr");
   if (pubkey == null && addr == null) {
     System.err.println("One of --pubkey or --addr must be specified.");
     return;
   }
   ECKey key = null;
   if (pubkey != null) {
     key = wallet.findKeyFromPubKey(Hex.decode(pubkey));
   } else {
     try {
       Address address = new Address(wallet.getParams(), addr);
       key = wallet.findKeyFromPubHash(address.getHash160());
     } catch (AddressFormatException e) {
       System.err.println(
           addr + " does not parse as a Bitcoin address of the right network parameters.");
       return;
     }
   }
   if (key == null) {
     System.err.println("Wallet does not seem to contain that key.");
     return;
   }
   wallet.removeKey(key);
 }
Esempio n. 2
0
 private static void addKey() {
   ECKey key;
   long creationTimeSeconds = getCreationTimeSeconds();
   if (options.has("privkey")) {
     String data = (String) options.valueOf("privkey");
     if (data.startsWith("5J") || data.startsWith("5H") || data.startsWith("5K")) {
       DumpedPrivateKey dpk;
       try {
         dpk = new DumpedPrivateKey(params, data);
       } catch (AddressFormatException e) {
         System.err.println("Could not parse dumped private key " + data);
         return;
       }
       key = dpk.getKey();
     } else {
       byte[] decode = Utils.parseAsHexOrBase58(data);
       if (decode == null) {
         System.err.println("Could not understand --privkey as either hex or base58: " + data);
         return;
       }
       key = new ECKey(new BigInteger(1, decode));
     }
     if (options.has("pubkey")) {
       // Give the user a hint.
       System.out.println("You don't have to specify --pubkey when a private key is supplied.");
     }
     key.setCreationTimeSeconds(creationTimeSeconds);
   } else if (options.has("pubkey")) {
     byte[] pubkey = Utils.parseAsHexOrBase58((String) options.valueOf("pubkey"));
     key = new ECKey(null, pubkey);
     key.setCreationTimeSeconds(creationTimeSeconds);
   } else {
     // Freshly generated key.
     key = new ECKey();
     if (creationTimeSeconds > 0) key.setCreationTimeSeconds(creationTimeSeconds);
   }
   if (wallet.findKeyFromPubKey(key.getPubKey()) != null) {
     System.err.println("That key already exists in this wallet.");
     return;
   }
   try {
     if (wallet.isEncrypted()) {
       if (password == null || !wallet.checkPassword(password)) {
         System.err.println("The password is incorrect.");
         return;
       }
       key = key.encrypt(wallet.getKeyCrypter(), wallet.getKeyCrypter().deriveKey(password));
     }
     wallet.addKey(key);
   } catch (KeyCrypterException kce) {
     System.err.println(
         "There was an encryption related error when adding the key. The error was '"
             + kce.getMessage()
             + "'.");
   }
   System.out.println(key.toAddress(params) + " " + key);
 }
 @Override
 protected void runApplication(OptionSet options) throws Exception {
   String appVersion = options.valueOf(applicationVersionOption);
   String appName = options.valueOf(applicationNameOption);
   Assert.hasText(appVersion, "Application version must be defined");
   YarnSubmitApplication app = new YarnSubmitApplication();
   if (StringUtils.hasText(appName)) {
     app.applicationName(appName);
   }
   app.applicationVersion(appVersion);
   handleApplicationRun(app);
 }
Esempio n. 4
0
  /**
   * {@inheritDoc}
   *
   * <p>All necessary setup for the module. Populate the "processing" table in seqware_meta_db.
   * Create a temporary directory.
   */
  @Override
  public ReturnValue init() {

    ReturnValue ret = new ReturnValue();
    ret.setExitStatus(ReturnValue.SUCCESS);
    // fill in the [xxx] fields in the processing table
    ret.setAlgorithm("TrimAllReads");
    ret.setDescription("Trim all reads to a specific length.");
    ret.setVersion("0.7.0");

    try {
      OptionParser parser = getOptionParser();
      // The parameters object is actually an ArrayList of Strings created
      // by splitting the command line options by space. JOpt expects a String[]
      options = parser.parse(this.getParameters().toArray(new String[0]));
      // create a temp directory in current working directory
      // tempDir = FileTools.createTempDirectory(new File("."));
      // you can write to "stdout" or "stderr" which will be persisted back to the DB
      ret.setStdout(ret.getStdout() + "Output: " + (String) options.valueOf("outfastq") + "\n");
    } catch (OptionException e) {
      e.printStackTrace();
      ret.setStderr(e.getMessage());
      ret.setExitStatus(ReturnValue.INVALIDPARAMETERS);
    } // catch (IOException e) {
    //  e.printStackTrace();
    //  ret.setStderr(e.getMessage());
    //  ret.setExitStatus(ReturnValue.DIRECTORYNOTWRITABLE);
    // }

    return (ret);
  }
  public static void main(String[] args) throws Exception {

    OptionParser parser = new OptionParser();
    parser
        .accepts("client-zone-id", "client zone id for zone routing")
        .withRequiredArg()
        .describedAs("zone-id")
        .ofType(Integer.class);
    OptionSet options = parser.parse(args);

    List<String> nonOptions = options.nonOptionArguments();
    if (nonOptions.size() < 2 || nonOptions.size() > 3) {
      System.err.println(
          "Usage: java VoldemortClientShell store_name bootstrap_url [command_file] [options]");
      parser.printHelpOn(System.err);
      System.exit(-1);
    }

    String storeName = nonOptions.get(0);
    String bootstrapUrl = nonOptions.get(1);

    String commandsFileName = "";
    BufferedReader fileReader = null;
    BufferedReader inputReader = null;
    try {
      if (nonOptions.size() == 3) {
        commandsFileName = nonOptions.get(2);
        fileReader = new BufferedReader(new FileReader(commandsFileName));
      }

      inputReader = new BufferedReader(new InputStreamReader(System.in));
    } catch (IOException e) {
      Utils.croak("Failure to open input stream: " + e.getMessage());
    }

    ClientConfig clientConfig =
        new ClientConfig()
            .setBootstrapUrls(bootstrapUrl)
            .setRequestFormatType(RequestFormatType.VOLDEMORT_V3);

    if (options.has("client-zone-id")) {
      clientConfig.setClientZoneId((Integer) options.valueOf("client-zone-id"));
    }

    StoreClientFactory factory = new SocketStoreClientFactory(clientConfig);

    try {
      client = (DefaultStoreClient<Object, Object>) factory.getStoreClient(storeName);
    } catch (Exception e) {
      Utils.croak("Could not connect to server: " + e.getMessage());
    }

    System.out.println("Established connection to " + storeName + " via " + bootstrapUrl);
    System.out.print(PROMPT);
    if (fileReader != null) {
      processCommands(factory, fileReader, true);
      fileReader.close();
    }
    processCommands(factory, inputReader, false);
  }
Esempio n. 6
0
  @Test
  public void testGetOptionParser() throws Exception {
    OptionParser optionParser = Main.getOptionParser();

    String tmpDir = systemTempDir().toString();

    OptionSet optionSet =
        optionParser.parse(
            "-f",
            "/tmp/dummy",
            "-s",
            "9908:976098897",
            "-r",
            "9908:810017902",
            "-u",
            "https://ap.unit4.com",
            "-m",
            "as2",
            "-e",
            tmpDir);
    assertTrue(optionSet.has("u"));
    assertTrue(optionSet.has("f"));
    assertTrue(optionSet.has("e"));
    Object e = optionSet.valueOf("e");
    assertNotNull(e);
    assertTrue(e instanceof File);
    File f = (File) e;
    assertEquals(f, new File(tmpDir));
  }
  @Test
  public void allowsDifferentFormsOfPairingArgumentWithOption() {
    OptionParser parser = new OptionParser();
    parser.accepts("count").withRequiredArg();
    parser.accepts("level").withOptionalArg();

    OptionSet options = parser.parse("--count", "4", "--level=3");

    assertTrue(options.has("count"));
    assertTrue(options.hasArgument("count"));
    assertEquals("4", options.valueOf("count"));

    assertTrue(options.has("level"));
    assertTrue(options.hasArgument("level"));
    assertEquals("3", options.valueOf("level"));
  }
  protected void main(OptionParser parser, OptionSet options) {
    int flags = 0;
    if (options.has("o2")) flags |= QBImporter.TEXTUREPLANES;
    if (options.has("s")) flags |= QBImporter.SQUARETEXTURE;
    if (options.has("t")) flags |= QBImporter.MERGETEXTURES;
    if (options.has("r")) flags |= QBImporter.SCALEMC;

    File[] input = options.valuesOf("input").toArray(new File[0]);
    File[] outDir = new File[input.length];
    if (options.has("out")) {
      File output = (File) options.valueOf("out");
      if (output.isFile()) throw new RuntimeException("Output Path is not a directory");
      if (!output.exists()) output.mkdirs();

      for (int i = 0; i < input.length; i++) outDir[i] = output;
    } else {
      for (int i = 0; i < input.length; i++)
        outDir[i] = input[i].isDirectory() ? input[i] : input[i].getParentFile();
    }

    for (int i = 0; i < input.length; i++) {
      File file = input[i];
      if (file.isDirectory()) {
        for (File file2 : file.listFiles())
          if (file2.getName().endsWith(".qb")) convert(file2, outDir[i], flags);
      } else convert(file, outDir[i], flags);
    }
  }
 @Override
 protected void verifyOptionSet(OptionSet options) throws Exception {
   String appId = options.valueOf(getApplicationIdOption());
   if (!appId.startsWith("jee")) {
     throw new IllegalArgumentException("no jee");
   }
 }
  private static List<String> loadAddresses(
      OptionSet options, OptionSpec<String> spec, AddressLevel addressLevel) {
    String addresses = options.valueOf(spec);
    if (addresses == null) {
      return null;
    }

    List<String> result = new LinkedList<String>();
    for (String addressString : addresses.split(",")) {

      if (addressString != null) {
        SimulatorAddress address;
        try {
          address = SimulatorAddress.fromString(addressString);
        } catch (Exception e) {
          throw new CommandLineExitException(
              "Worker address [" + addressString + "] is not a valid simulator address", e);
        }

        if (!address.getAddressLevel().equals(addressLevel)) {
          throw new CommandLineExitException(
              "address ["
                  + addressString
                  + "] is not a valid "
                  + addressLevel
                  + " address, it's a "
                  + address.getAddressLevel()
                  + " address");
        }
      }
      result.add(addressString);
    }

    return result;
  }
Esempio n. 11
0
 public static File getFile(OptionSpec<String> spec, OptionSet options, String desc) {
   File file = newFile(options.valueOf(spec));
   if (!file.exists()) {
     throw new CommandLineExitException(format("%s [%s] does not exist%n", desc, file));
   }
   return file;
 }
Esempio n. 12
0
 private File getPropertiesFile() {
   if (options.has(propertiesFileSpec)) {
     // a file was explicitly configured
     return new File(options.valueOf(propertiesFileSpec));
   } else {
     return null;
   }
 }
Esempio n. 13
0
  public final void parseAndExecute(final String[] cmds) throws IOException {
    opts = parser.parse(cmds);
    if (opts.has(HELP)) {
      parser.printHelpOn(System.out);
      return;
    }

    Indexing.STORE = opts.has(STORE);
    Indexing.COMMIT = (Integer) opts.valueOf(COMMIT);

    // FORMAT
    if (opts.has(FORMAT)) {
      format = (Format) opts.valueOf(FORMAT);
    } else printError(FORMAT);

    // DUMPS_DIR
    if (opts.has(DUMPS_DIR)) {
      dumpsDir = (File) opts.valueOf(DUMPS_DIR);
    } else printError(DUMPS_DIR);

    // INDEX_DIR
    if (opts.has(INDEX_DIR)) {
      indexDir = (File) opts.valueOf(INDEX_DIR);
    } else printError(INDEX_DIR);

    logger.info(
        "Creating index at {} from the files at {}",
        indexDir.getAbsolutePath(),
        dumpsDir.getAbsolutePath());
    final Indexing indexing;
    switch (format) {
      case SINDICE_DE:
        indexing = new SindiceDEIndexing(dumpsDir, FSDirectory.open(indexDir));
        break;
      case SINDICE_ED:
        indexing = new SindiceEDIndexing(dumpsDir, FSDirectory.open(indexDir));
        break;
      default:
        throw new IllegalArgumentException("No such dataset format: " + format);
    }
    indexing.indexIt();
    indexing.close();
    logger.info("Finished indexing");
  }
Esempio n. 14
0
  public static void main(String[] args) throws Exception {
    SaraTouchClient client = new SaraTouchClient();

    OptionParser parser = new OptionParser("ch:p:t");
    OptionSet options = null;

    try {
      options = parser.parse(args);
    } catch (Exception e) {
      System.out.println("Could not parse command-line options:\n" + e);
      System.out.println();
      System.out.println("-h <host>   Server host");
      System.out.println("-p <port>   Server port");
      System.out.println("-t          Send TUIO events instead of mouse events");
      System.out.println("-c          Connect after starting up");
      System.out.println();
      System.exit(-1);
    }

    if (options.has("h")) {
      Object o = options.valueOf("h");
      if (o != null) {
        String s = (String) o;
        client.setHost(s);
      }
    }

    if (options.has("p")) {
      Object o = options.valueOf("p");
      if (o != null) {
        int i = Integer.parseInt((String) o);
        client.setPort(i);
      }
    }

    if (options.has("t")) client.setModeToTUIO();

    if (options.has("c")) client.connect();

    client.setSize(600, 500);
    client.setVisible(true);
  }
Esempio n. 15
0
  /**
   * {@inheritDoc}
   *
   * <p>Run core of module. Based on script sw_module_TrimAllReads.pl
   */
  @Override
  public ReturnValue do_run() {

    ReturnValue ret = new ReturnValue();
    ret.setExitStatus(ReturnValue.SUCCESS);
    ret.setRunStartTstmp(new Date());

    StringBuffer cmd = new StringBuffer();
    cmd.append(
        options.valueOf("perl")
            + " "
            + options.valueOf("script")
            + " "
            + options.valueOf("infastq"));
    cmd.append(" " + options.valueOf("outfastq") + " " + options.valueOf("readsize"));

    RunTools.runCommand(new String[] {"bash", "-c", cmd.toString()});

    // record the file output
    String outputF = (String) options.valueOf("outfastq");
    FileMetadata fm1 = new FileMetadata();
    fm1.setMetaType("chemical/seq-na-fastq");
    fm1.setFilePath(outputF);
    fm1.setType("TrimAllReads-fastq");
    fm1.setDescription("Trimmed reads in fastq format.");
    ret.getFiles().add(fm1);

    ret.setRunStopTstmp(new Date());
    return (ret);
  }
Esempio n. 16
0
 private static void addAddr() {
   String addr = (String) options.valueOf("addr");
   if (addr == null) {
     System.err.println("You must specify an --addr to watch.");
     return;
   }
   try {
     Address address = new Address(params, addr);
     // If no creation time is specified, assume genesis (zero).
     wallet.addWatchedAddress(address, getCreationTimeSeconds());
   } catch (AddressFormatException e) {
     System.err.println("Could not parse given address, or wrong network: " + addr);
   }
 }
  /**
   * @param args
   * @throws Exception
   */
  public static void main(String[] args) throws Exception {
    PropertyConfigurator.configure("conf/log4j.properties");
    // args = new String[] { "-c", "127.0.0.1", "-k", "localhost:9092" };
    OptionParser parser = new OptionParser();
    parser.accepts("c", "cassandra server address").withRequiredArg().ofType(String.class);
    parser.accepts("k", "kafka server address").withRequiredArg().ofType(String.class);
    parser.accepts("r", "consume topics from the beginning");
    parser
        .accepts("g", "server address of ganglia gmond. e.g 10.11.1.212:8649")
        .withRequiredArg()
        .ofType(String.class);
    OptionSet set = parser.parse(args);
    if (!set.hasOptions()) {
      parser.printHelpOn(new PrintStream(System.out));
      System.exit(1);
    }

    String[] fields = set.valueOf("g").toString().split(":");
    MetricBasedPerfProfile.reportForGanglia(fields[0], Short.parseShort(fields[1].trim()));
    TimeSeriesProducer producer = new TimeSeriesProducer();
    producer.init(set.valueOf("k").toString(), set.valueOf("c").toString().trim(), set.has("r"));
    producer.start();
  }
Esempio n. 18
0
  public static void main(String[] args) {
    OptionParser p = new OptionParser("fc:q::");
    p.accepts("ftp");
    p.accepts("user").requiredIf("ftp").withRequiredArg();
    p.accepts("pass").requiredIf("ftp").withRequiredArg();

    OptionSet opt = p.parse(args);
    if (opt.has("f")) {
      System.out.println("-f exist");
      System.out.println("-f with : " + opt.valueOf("f"));
    }
    if (opt.has("c")) {
      System.out.println("-c exist with:" + opt.valueOf("c"));
    }

    if (opt.has("ftp")) {
      // we know username and password
      // existe if -ftp is set
      String user = (String) opt.valueOf("user");
      String pwd = (String) opt.valueOf("pass");
      System.out.println("user:"******" pass:" + pwd);
    }
  }
Esempio n. 19
0
  @SuppressWarnings("unchecked")
  public static void main(String[] args) throws Exception {
    OptionParser parser = new OptionParser();

    parser.accepts("native", "use native admin client");
    parser.accepts("f", "execute fetch operation");
    parser.accepts("fu", "fetch and update").withRequiredArg().ofType(Integer.class);
    parser
        .accepts("n", "node id")
        .withRequiredArg()
        .ofType(Integer.class)
        .withValuesSeparatedBy(',');
    parser
        .accepts("p", "partition id")
        .withRequiredArg()
        .ofType(Integer.class)
        .withValuesSeparatedBy(',');
    OptionSet options = parser.parse(args);

    List<String> nonOptions = (List<String>) options.nonOptionArguments();

    if (args.length < 2) {
      System.out.println(usageStr);
      return;
    }

    String bootstrapUrl = nonOptions.get(0);
    String storeName = nonOptions.get(1);

    if (!options.has("p") && !options.has("n")) {
      printUsage(
          System.err,
          parser,
          "One or more node and/or one or more partition has" + " to be specified");
    }

    AdminTest adminTest;

    adminTest = new AdminTest(bootstrapUrl, storeName);

    SetMultimap<Integer, Integer> nodePartitions =
        adminTest.getNodePartitions(
            options.has("n") ? options.valuesOf("n") : null,
            options.has("p") ? options.valuesOf("p") : null);

    if (options.has("f")) adminTest.testFetch(nodePartitions);
    if (options.has("fu"))
      adminTest.testFetchAndUpdate(nodePartitions, (Integer) options.valueOf("fu"));
  }
 public static void main(final String[] args) throws IOException {
   final MappingTestServerOptionParser parser = new MappingTestServerOptionParser();
   try {
     final OptionSet options = parser.parse(args);
     if (options.has("help")) {
       parser.printHelpOn(System.out);
     } else {
       final String host = options.valueOf(parser.hostOption);
       final Integer port = options.valueOf(parser.portOption);
       final MappingTestServer server =
           new MappingTestServer(
               options.valueOf(parser.schemaOption),
               options.valueOf(parser.mappingOption),
               port,
               host);
       Runtime.getRuntime().addShutdownHook(new Thread(server::stopServer));
       log.info("Starting server on {}:{}...", host, port);
       server.runServer();
     }
   } catch (final OptionException e) {
     System.err.println(e.getLocalizedMessage());
     parser.printHelpOn(System.err);
   }
 }
Esempio n. 21
0
  public static void parseArgs(String args[]) throws java.io.IOException {

    parser.acceptsAll(asList("h", "?"), "show help then exit");
    OptionSpec<String> CMD = parser.accepts("c", "command").withRequiredArg().ofType(String.class);
    OptionSpec<String> LOGIN =
        parser.accepts("u", "LoginId").withRequiredArg().ofType(String.class);
    OptionSpec<String> PASSWORD =
        parser.accepts("p", "password").withRequiredArg().ofType(String.class);
    OptionSpec<String> ISSUER =
        parser.accepts("i", "IssuerDN").withRequiredArg().ofType(String.class);
    OptionSpec<String> SUBJECT =
        parser.accepts("s", "SubjectDN").withRequiredArg().ofType(String.class);
    OptionSpec<String> CONTEXT =
        parser
            .accepts("C", "context:UNITTEST,DEVELOPMENT,SDK,PRODUCTION")
            .withRequiredArg()
            .ofType(String.class);

    OptionSet options = parser.parse(args);

    // check for help
    if (options.has("?")) {
      parser.printHelpOn(System.out);
      System.exit(0);
    }
    if (options.has(CMD)) {
      cmd = options.valueOf(CMD);
    } else {
      System.out.println("a -c cmd argument is required");
      parser.printHelpOn(System.out);
      System.exit(0);
    }
    if (options.has(LOGIN)) {
      loginName = options.valueOf(LOGIN);
    }
    if (options.has(PASSWORD)) {
      password = options.valueOf(PASSWORD);
    }
    if (options.has(ISSUER)) {
      issuer = options.valueOf(ISSUER);
    }
    if (options.has(SUBJECT)) {
      subject = options.valueOf(SUBJECT);
    }
    if (options.has(CONTEXT)) {
      context = options.valueOf(CONTEXT);
      if (!context.equals("UNITTEST")
          && !context.equals("SDK")
          && !context.equals("DEVELOPMENT")
          && !context.equals("PRODUCTION")) {
        System.out.println("unrecognized CONTEXT value: " + context);
        System.exit(-1);
      }
    }
  }
Esempio n. 22
0
  @Test
  public void supportsOptionSynonyms() {
    OptionParser parser = new OptionParser();
    List<String> synonyms = asList("message", "blurb", "greeting");
    parser.acceptsAll(synonyms).withRequiredArg();
    String expectedMessage = "Hello";

    OptionSet options = parser.parse("--message", expectedMessage);

    for (String each : synonyms) {
      assertTrue(each, options.has(each));
      assertTrue(each, options.hasArgument(each));
      assertEquals(each, expectedMessage, options.valueOf(each));
      assertEquals(each, asList(expectedMessage), options.valuesOf(each));
    }
  }
 /**
  * Process the options found in the commandline arguments and checks that all required options are
  * present.
  *
  * @param opts
  * @param cfg
  * @throws Exception
  */
 private static void processOptions(OptionSet opts, ConfigurationOptions cfg) throws Exception {
   if (opts.has("N")) {
     cfg.numNodes = Integer.parseInt(opts.valueOf("N").toString());
   } else throw new Exception("Argument --num-nodes is required");
   if (opts.has("C")) {
     cfg.numVehicles = Integer.parseInt(opts.valueOf("C").toString());
   } else throw new Exception("Argument --num-vehicles is required");
   if (opts.has("D")) {
     cfg.degreeProb = Integer.parseInt(opts.valueOf("D").toString()) / (double) cfg.numNodes;
   } else throw new Exception("Argument --node-degree is required");
   if (opts.has("node-capacity")) {
     cfg.capacity = Integer.parseInt(opts.valueOf("node-capacity").toString());
   } // this argument is optional
   if (opts.has("o")) {
     cfg.outputFile = new File(opts.valueOf("o").toString());
   } else throw new Exception("Argument --output-file is required");
   if (opts.has("d")) {
     String s = opts.valueOf("d").toString();
     String[] ss = s.split(":");
     if (ss.length != 2) throw new Exception("Argument to node-delay must have the form min:max");
     cfg.nodeDelay[0] = Integer.parseInt(ss[0]);
     cfg.nodeDelay[1] = Integer.parseInt(ss[1]);
   } else throw new Exception("Argument --node-delay is required");
   if (opts.has("S")) {
     String[] ss = opts.valueOf("S").toString().split(",");
     for (String s : ss) {
       cfg.strategies.add(s);
     }
   } else throw new Exception("Argument --vehicle-strategies is required");
   if (opts.has("one-way-prob")) {
     cfg.oneWay = Double.parseDouble(opts.valueOf("one-way-prob").toString());
   }
   cfg.bottleneck = opts.has("congested");
   if (opts.has("graph")) {
     cfg.graphFile = new File(opts.valueOf("graph").toString());
   }
 }
Esempio n. 24
0
  public static void main(String[] args) throws IOException, TException {
    OptionParser parser = new OptionParser();
    parser.accepts("c", "configuration file").withRequiredArg().ofType(String.class);
    parser.accepts("help", "print help statement");
    OptionSet options = parser.parse(args);

    if (options.has("help")) {
      parser.printHelpOn(System.out);
      System.exit(-1);
    }

    // Logger configuration: log to the console
    BasicConfigurator.configure();
    LOG.setLevel(Level.DEBUG);
    LOG.debug("debug logging on");

    Configuration conf = new PropertiesConfiguration();

    if (options.has("c")) {
      String configFile = (String) options.valueOf("c");
      try {
        conf = new PropertiesConfiguration(configFile);
      } catch (ConfigurationException e) {
      }
    }
    // Start backend server
    BackendService.Processor<BackendService.Iface> processor =
        new BackendService.Processor<BackendService.Iface>(new ProtoBackend());

    int listenPort = conf.getInt("listen_port", DEFAULT_LISTEN_PORT);
    NM_PORT = conf.getInt("node_monitor_port", NodeMonitorThrift.DEFAULT_NM_THRIFT_PORT);
    TServers.launchThreadedThriftServer(listenPort, THRIFT_WORKER_THREADS, processor);

    // Register server
    client = TClients.createBlockingNmClient(NM_HOST, NM_PORT);

    try {
      client.registerBackend(APP_ID, "localhost:" + listenPort);
      LOG.debug("Client successfullly registered");
    } catch (TTransportException e) {
      LOG.debug("Error while registering backend: " + e.getMessage());
    }
  }
Esempio n. 25
0
  public void run() {
    Reflections.log = null;

    printVersion();

    OptionParser parser = buildOptionParser();

    OptionSet options = parser.parse(arguments);
    if (options.has(ARGUMENT_EXPERIMENT)) {
      runExperiment(options.valueOf(ARGUMENT_EXPERIMENT).toString());
      System.exit(0);
    }
    if (options.has(ARGUMENT_EXPERIMENT_LIST)) {
      printExperimentList();
      System.exit(0);
    }
    if (options.has(ARGUMENT_HELP)) {
      printHelp(parser);
      System.exit(0);
    }
    printHelp(parser);
  }
Esempio n. 26
0
 // Sets up all objects needed for network communication but does not bring up the peers.
 private static void setup() throws BlockStoreException {
   if (store != null) return; // Already done.
   // Will create a fresh chain if one doesn't exist or there is an issue with this one.
   if (!chainFileName.exists() && wallet.getTransactions(true).size() > 0) {
     // No chain, so reset the wallet as we will be downloading from scratch.
     System.out.println("Chain file is missing so clearing transactions from the wallet.");
     reset();
   }
   if (mode == ValidationMode.SPV) {
     store = new SPVBlockStore(params, chainFileName);
     chain = new BlockChain(params, wallet, store);
   } else if (mode == ValidationMode.FULL) {
     FullPrunedBlockStore s =
         new H2FullPrunedBlockStore(params, chainFileName.getAbsolutePath(), 5000);
     store = s;
     chain = new FullPrunedBlockChain(params, wallet, s);
   }
   // This will ensure the wallet is saved when it changes.
   wallet.autosaveToFile(walletFile, 200, TimeUnit.MILLISECONDS, null);
   peers = new PeerGroup(params, chain);
   peers.setUserAgent("WalletTool", "1.0");
   peers.addWallet(wallet);
   if (options.has("peers")) {
     String peersFlag = (String) options.valueOf("peers");
     String[] peerAddrs = peersFlag.split(",");
     for (String peer : peerAddrs) {
       try {
         peers.addAddress(new PeerAddress(InetAddress.getByName(peer), params.getPort()));
       } catch (UnknownHostException e) {
         System.err.println(
             "Could not understand peer domain name/IP address: " + peer + ": " + e.getMessage());
         System.exit(1);
       }
     }
   } else {
     peers.addPeerDiscovery(new DnsDiscovery(params));
   }
 }
Esempio n. 27
0
  void run() {
    try {
      cloudInfo.props.init(getPropertiesFile());

      cloudInfo.locationId = options.valueOf(locationSpec);
      cloudInfo.verbose = options.has(verboseSpec);

      if (options.has(showLocationsSpec)) {
        cloudInfo.init();
        cloudInfo.showLocations();
      } else if (options.has(showHardwareSpec)) {
        cloudInfo.init();
        cloudInfo.showHardware();
      } else if (options.has(showImagesSpec)) {
        cloudInfo.init();
        cloudInfo.showImages();
      } else {
        CliUtils.printHelpAndExit(parser);
      }
    } finally {
      cloudInfo.shutdown();
    }
  }
Esempio n. 28
0
  /**
   * {@inheritDoc}
   *
   * <p>Verify anything needed to run the module is ready (e.g. input files exist, etc).
   */
  @Override
  public ReturnValue do_verify_input() {

    ReturnValue ret = new ReturnValue();
    ret.setExitStatus(ReturnValue.SUCCESS);

    // Does input file ('infastq') exist & is it readable?
    if (FileTools.fileExistsAndReadable(new File((String) options.valueOf("infastq")))
            .getExitStatus()
        != ReturnValue.SUCCESS) {
      ret.setExitStatus(ReturnValue.FILENOTREADABLE);
      ret.setStderr("Input file " + (String) options.valueOf("infastq") + " is not readable");
    }

    // Is output file path writable (for 'outfastq')?
    File output1 = new File((String) options.valueOf("outfastq"));
    if (FileTools.dirPathExistsAndWritable(output1.getParentFile()).getExitStatus()
        != ReturnValue.SUCCESS) {
      ret.setExitStatus(ReturnValue.DIRECTORYNOTWRITABLE);
      ret.setStderr("Can't write to output directory");
    }

    // Is 'perl' executable?
    if (FileTools.fileExistsAndExecutable(new File((String) options.valueOf("perl")))
            .getExitStatus()
        != ReturnValue.SUCCESS) {
      ret.setExitStatus(ReturnValue.FILENOTEXECUTABLE);
      ret.setStderr("Not executable: " + (String) options.valueOf("perl"));
    }

    // Does 'script' (sw_module_TrimAllReads.pl) exist?
    if (FileTools.fileExistsAndReadable(new File((String) options.valueOf("script")))
            .getExitStatus()
        != ReturnValue.SUCCESS) {
      ret.setExitStatus(ReturnValue.FILENOTREADABLE);
      ret.setStderr("Could not find script at " + (String) options.valueOf("script"));
    }

    return (ret);
  }
Esempio n. 29
0
  public static void main(String[] args) {
    // TODO main
    OptionParser parser = new OptionParser();
    parser.acceptsAll(Arrays.asList("h", "help"), "Show this help dialog.");
    OptionSpec<String> serverOption =
        parser
            .acceptsAll(Arrays.asList("s", "server"), "Server to join.")
            .withRequiredArg()
            .describedAs("server-address[:port]");
    OptionSpec<String> proxyOption =
        parser
            .acceptsAll(
                Arrays.asList("P", "proxy"),
                "SOCKS proxy to use. Ignored in presence of 'socks-proxy-list'.")
            .withRequiredArg()
            .describedAs("proxy-address");
    OptionSpec<String> ownerOption =
        parser
            .acceptsAll(
                Arrays.asList("o", "owner"), "Owner of the bot (username of in-game control).")
            .withRequiredArg()
            .describedAs("username");
    OptionSpec<?> offlineOption =
        parser.acceptsAll(
            Arrays.asList("O", "offline"),
            "Offline-mode. Ignores 'password' and 'account-list' (will "
                + "generate random usernames if 'username' is not supplied).");
    OptionSpec<?> autoRejoinOption =
        parser.acceptsAll(Arrays.asList("a", "auto-rejoin"), "Auto-rejoin a server on disconnect.");
    OptionSpec<Integer> loginDelayOption =
        parser
            .acceptsAll(
                Arrays.asList("d", "login-delay"),
                "Delay between bot joins, in milliseconds. 5000 is "
                    + "recommended if not using socks proxies.")
            .withRequiredArg()
            .describedAs("delay")
            .ofType(Integer.class);
    OptionSpec<Integer> botAmountOption =
        parser
            .acceptsAll(
                Arrays.asList("b", "bot-amount"),
                "Amount of bots to join. Must be <= amount of accounts.")
            .withRequiredArg()
            .describedAs("amount")
            .ofType(Integer.class);

    OptionSpec<String> accountListOption =
        parser
            .accepts(
                "account-list",
                "File containing a list of accounts, in username/email:password format.")
            .withRequiredArg()
            .describedAs("file");
    OptionSpec<String> socksProxyListOption =
        parser
            .accepts(
                "socks-proxy-list",
                "File containing a list of SOCKS proxies, in address:port format.")
            .withRequiredArg()
            .describedAs("file");
    OptionSpec<String> httpProxyListOption =
        parser
            .accepts(
                "http-proxy-list",
                "File containing a list of HTTP proxies, in address:port format.")
            .withRequiredArg()
            .describedAs("file");

    OptionSet options;
    try {
      options = parser.parse(args);
    } catch (OptionException exception) {
      try {
        parser.printHelpOn(System.out);
      } catch (Exception exception1) {
        exception1.printStackTrace();
      }
      return;
    }

    if (options.has("help")) {
      printHelp(parser);
      return;
    }

    final boolean offline = options.has(offlineOption);
    final boolean autoRejoin = options.has(autoRejoinOption);

    final List<String> accounts;
    if (options.has(accountListOption)) {
      accounts = loadAccounts(options.valueOf(accountListOption));
    } else if (!offline) {
      System.out.println("Option 'accounts' must be supplied in " + "absence of option 'offline'.");
      printHelp(parser);
      return;
    } else accounts = null;

    final String server;
    if (!options.has(serverOption)) {
      System.out.println("Option 'server' required.");
      printHelp(parser);
      return;
    } else server = options.valueOf(serverOption);

    final String owner;
    if (!options.has(ownerOption)) {
      System.out.println("Option 'owner' required.");
      printHelp(parser);
      return;
    } else owner = options.valueOf(ownerOption);

    final List<String> socksProxies;
    if (options.has(socksProxyListOption))
      socksProxies = loadProxies(options.valueOf(socksProxyListOption));
    else socksProxies = null;
    final boolean useProxy = socksProxies != null;

    final List<String> httpProxies;
    if (options.has(httpProxyListOption))
      httpProxies = loadLoginProxies(options.valueOf(httpProxyListOption));
    else if (!offline && accounts != null) {
      System.out.println(
          "Option 'http-proxy-list' required if " + "option 'account-list' is supplied.");
      printHelp(parser);
      return;
    } else httpProxies = null;

    final int loginDelay;
    if (options.has(loginDelayOption)) loginDelay = options.valueOf(loginDelayOption);
    else loginDelay = 0;

    final int botAmount;
    if (!options.has(botAmountOption)) {
      System.out.println("Option 'bot-amount' required.");
      printHelp(parser);
      return;
    } else botAmount = options.valueOf(botAmountOption);

    initGui();
    while (!sessions.get()) {
      synchronized (sessions) {
        try {
          sessions.wait(5000);
        } catch (InterruptedException exception) {
        }
      }
    }

    final Queue<Runnable> lockQueue = new ArrayDeque<Runnable>();

    ExecutorService service = Executors.newFixedThreadPool(botAmount + (loginDelay > 0 ? 1 : 0));
    final Object firstWait = new Object();
    if (loginDelay > 0) {
      service.execute(
          new Runnable() {
            @Override
            public void run() {
              synchronized (firstWait) {
                try {
                  firstWait.wait();
                } catch (InterruptedException exception) {
                }
              }
              while (true) {
                if (die) return;
                while (slotsTaken.get() >= 2) {
                  synchronized (slotsTaken) {
                    try {
                      slotsTaken.wait(500);
                    } catch (InterruptedException exception) {
                    }
                  }
                }
                synchronized (lockQueue) {
                  if (lockQueue.size() > 0) {
                    Runnable thread = lockQueue.poll();
                    synchronized (thread) {
                      thread.notifyAll();
                    }
                    lockQueue.offer(thread);
                  } else continue;
                }
                try {
                  Thread.sleep(loginDelay);
                } catch (InterruptedException exception) {
                }
                while (!sessions.get()) {
                  synchronized (sessions) {
                    try {
                      sessions.wait(5000);
                    } catch (InterruptedException exception) {
                    }
                  }
                }
              }
            }
          });
    }
    final List<String> accountsInUse = new ArrayList<String>();
    for (int i = 0; i < botAmount; i++) {
      final int botNumber = i;
      Runnable runnable =
          new Runnable() {
            @Override
            public void run() {
              if (loginDelay > 0)
                synchronized (lockQueue) {
                  lockQueue.add(this);
                }
              Random random = new Random();

              if (!offline) {
                boolean authenticated = false;
                user:
                while (true) {
                  if (authenticated) {
                    authenticated = false;
                    sessionCount.decrementAndGet();
                  }
                  Session session = null;
                  String loginProxy;
                  String account = accounts.get(random.nextInt(accounts.size()));
                  synchronized (accountsInUse) {
                    if (accountsInUse.size() == accounts.size()) System.exit(0);
                    while (accountsInUse.contains(account))
                      account = accounts.get(random.nextInt(accounts.size()));
                    accountsInUse.add(account);
                  }
                  String[] accountParts = account.split(":");
                  while (true) {
                    while (!sessions.get()) {
                      synchronized (sessions) {
                        try {
                          sessions.wait(5000);
                        } catch (InterruptedException exception) {
                        }
                      }
                    }
                    loginProxy = httpProxies.get(random.nextInt(httpProxies.size()));
                    try {
                      session = Util.retrieveSession(accountParts[0], accountParts[1], loginProxy);
                      // addAccount(session);
                      sessionCount.incrementAndGet();
                      authenticated = true;
                      break;
                    } catch (AuthenticationException exception) {
                      System.err.println("[Bot" + botNumber + "] " + exception);
                      if (!exception.getMessage().startsWith("Exception"))
                        // && !exception.getMessage().equals(
                        // "Too many failed logins"))
                        continue user;
                    }
                  }
                  System.out.println(
                      "["
                          + session.getUsername()
                          + "] Password: "******", Session ID: "
                          + session.getSessionId());
                  while (!joins.get()) {
                    synchronized (joins) {
                      try {
                        joins.wait(5000);
                      } catch (InterruptedException exception) {
                      }
                    }
                  }
                  if (loginDelay > 0) {
                    synchronized (this) {
                      try {
                        synchronized (firstWait) {
                          firstWait.notifyAll();
                        }
                        wait();
                      } catch (InterruptedException exception) {
                      }
                    }
                  }

                  while (true) {
                    String proxy =
                        useProxy ? socksProxies.get(random.nextInt(socksProxies.size())) : null;
                    try {
                      new DarkBotMCSpambot(
                          DARK_BOT,
                          server,
                          session.getUsername(),
                          session.getPassword(),
                          session.getSessionId(),
                          null,
                          proxy,
                          owner);
                      if (die) break user;
                      else if (!autoRejoin) break;
                    } catch (Exception exception) {
                      exception.printStackTrace();
                      System.out.println(
                          "["
                              + session.getUsername()
                              + "] Error connecting: "
                              + exception.getCause().toString());
                    }
                  }
                  System.out.println("[" + session.getUsername() + "] Account failed");
                }
              } else {
                while (true) {
                  String proxy =
                      useProxy ? socksProxies.get(random.nextInt(socksProxies.size())) : null;
                  try {
                    String username = "";
                    if (accounts != null) {
                      username = accounts.get(random.nextInt(accounts.size())).split(":")[0];
                      synchronized (accountsInUse) {
                        while (accountsInUse.contains(username))
                          username = accounts.get(random.nextInt(accounts.size()));
                        accountsInUse.add(username);
                      }
                    } else
                      for (int i = 0; i < 10 + random.nextInt(6); i++)
                        username += alphas[random.nextInt(alphas.length)];
                    if (loginDelay > 0) {
                      synchronized (this) {
                        try {
                          synchronized (firstWait) {
                            firstWait.notifyAll();
                          }
                          wait();
                        } catch (InterruptedException exception) {
                        }
                      }
                    }
                    new DarkBotMCSpambot(DARK_BOT, server, username, "", "", null, proxy, owner);
                    if (die || !autoRejoin) break;
                    else continue;
                  } catch (Exception exception) {
                    System.out.println(
                        "[Bot" + botNumber + "] Error connecting: " + exception.toString());
                  }
                }
              }
            }
          };
      service.execute(runnable);
    }
    service.shutdown();
    while (!service.isTerminated()) {
      try {
        service.awaitTermination(9000, TimeUnit.DAYS);
      } catch (InterruptedException exception) {
        exception.printStackTrace();
      }
    }
    System.exit(0);
  }
Esempio n. 30
0
  private static void work(CardTerminal reader, OptionSet args) throws CardException {
    if (!reader.isCardPresent()) {
      System.out.println("No card in " + reader.getName());
      return;
    }

    FileOutputStream o = null;
    if (args.has(OPT_DUMP)) {
      try {
        o = new FileOutputStream((File) args.valueOf(OPT_DUMP));
      } catch (FileNotFoundException e) {
        System.err.println("Can not dump to " + args.valueOf(OPT_DUMP));
      }
    }
    reader = LoggingCardTerminal.getInstance(reader, o);
    // This allows to override the protocol for RemoteTerminal as well.
    final String protocol;
    if (args.has(OPT_T0)) {
      protocol = "T=0";
    } else if (args.has(OPT_T1)) {
      protocol = "T=1";
    } else {
      protocol = "*";
    }
    if (args.has(CMD_APDU)) {

      Card c = null;
      try {
        c = reader.connect(protocol);

        if (args.has(CMD_APDU)) {
          for (Object s : args.valuesOf(CMD_APDU)) {
            CommandAPDU a = new CommandAPDU(HexUtils.stringToBin((String) s));
            ResponseAPDU r = c.getBasicChannel().transmit(a);
            if (args.has(OPT_ERROR) && r.getSW() != 0x9000) {
              System.out.println(
                  "Card returned " + String.format("%04X", r.getSW()) + ", exiting!");
              return;
            }
          }
        }
      } catch (CardException e) {
        if (TerminalManager.getExceptionMessage(e) != null) {
          System.out.println("PC/SC failure: " + TerminalManager.getExceptionMessage(e));
        } else {
          throw e;
        }
      } finally {
        if (c != null) {
          c.disconnect(true);
        }
      }
    } else if (args.has(OPT_CONNECT)) {
      String remote = (String) args.valueOf(OPT_CONNECT);
      JSONMessagePipe transport = null;

      try {
        if (remote.startsWith("http://") || remote.startsWith("https://")) {
          if (args.has(OPT_PINNED)) {
            transport =
                HTTPTransport.open(
                    new URL(remote), certFromPEM(((File) args.valueOf(OPT_PINNED)).getPath()));
          } else {
            transport = HTTPTransport.open(new URL(remote), null);
          }
        } else {
          transport = SocketTransport.connect(string2socket(remote), null);
        }

        // Connect the transport and the terminal
        CmdlineRemoteTerminal c = new CmdlineRemoteTerminal(transport, reader);
        c.forceProtocol(protocol);
        // Run
        c.run();
      } catch (IOException e) {
        System.err.println("Communication error: " + e.getMessage());
      } finally {
        if (transport != null) transport.close();
      }
    }
  }