private String managePermissions(IMessage message, OptionSet optionSet) {
   List<String> nonOptions = optionSet.valuesOf(permNonOptionSpec);
   if (optionSet.has("?") || nonOptions.size() < 2) {
     return null;
   }
   String permName = nonOptions.get(0).toLowerCase();
   String action = nonOptions.get(1).toLowerCase();
   Optional<Permission> permission = permissionService.findPermissionByName(permName);
   List<String> args = nonOptions.subList(2, nonOptions.size());
   if (action.equals("list")) {
     return listPermissions(message, permName, args);
   } else if (action.equals("evict")) {
     permissionService.evict();
     return "OK";
   } else if (!permission.isPresent()) {
     return "Not a valid permission name";
   } else if (action.equals("allow")) {
     return editPermission(Operation.ALLOW, message, permission.get(), args);
   } else if (action.equals("deny")) {
     return editPermission(Operation.DENY, message, permission.get(), args);
   } else if (action.equals("reset")) {
     return editPermission(Operation.RESET, message, permission.get(), args);
   }
   return "Invalid operation! Check details with `.perm -?`";
 }
示例#2
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);
 }
  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);
  }
示例#4
0
文件: MainIT.java 项目: difi/oxalis
  @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));
  }
 private File getPropertiesFile() {
   if (options.has(propertiesFileSpec)) {
     // a file was explicitly configured
     return new File(options.valueOf(propertiesFileSpec));
   } else {
     return null;
   }
 }
示例#6
0
文件: MainIT.java 项目: difi/oxalis
  @Test
  public void senderAndReceiverIsOptional() throws Exception {
    OptionParser optionParser = Main.getOptionParser();

    OptionSet optionSet =
        optionParser.parse("-f", "/tmp/dummy", "-u", "https://ap.unit4.com", "-m", "as2");
    assertFalse(optionSet.has("-r"));
    assertFalse(optionSet.has("-s"));
  }
示例#7
0
 private static long getCreationTimeSeconds() {
   long creationTimeSeconds = 0;
   if (options.has(unixtimeFlag)) {
     creationTimeSeconds = unixtimeFlag.value(options);
   } else if (options.has(dateFlag)) {
     creationTimeSeconds = dateFlag.value(options).getTime() / 1000;
   }
   return creationTimeSeconds;
 }
示例#8
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);
 }
 private static Properties asProperties(OptionSet options, String prefix) {
   Properties properties = new Properties();
   for (Entry<OptionSpec<?>, List<?>> entry : options.asMap().entrySet()) {
     OptionSpec<?> spec = entry.getKey();
     properties.setProperty(
         asPropertyKey(prefix, spec), asPropertyValue(entry.getValue(), options.has(spec)));
   }
   return properties;
 }
  @Test
  public void testInitOptionsWithHelp_optionalArgument() {
    parser.accepts("argName", "Funky description");

    OptionSet options = initOptionsWithHelp(parser, new String[] {"--argName"});
    assertNotNull(options);
    assertEquals(1, options.specs().size());
    assertTrue(options.has("argName"));
  }
 @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);
 }
示例#12
0
  private void unschedule(String[] args) throws Exception {
    String[] ONE_REQUIRED = {OPT_RESOURCEID, OPT_GROUPID};

    OptionParser p = getOptionParser();

    p.accepts(OPT_RESOURCEID, "The id of the resource to unschedule from maintenance")
        .withRequiredArg()
        .ofType(Integer.class);

    p.accepts(OPT_GROUPID, "The id of the group to unschedule from maintenance")
        .withRequiredArg()
        .ofType(Integer.class);

    OptionSet options = getOptions(p, args);

    int criteria = 0;
    for (String opt : ONE_REQUIRED) {
      if (options.has(opt)) {
        criteria++;
      }
    }

    if (criteria == 0) {
      System.err.println("One of " + Arrays.toString(ONE_REQUIRED) + " is required.");
      System.exit(-1);
    } else if (criteria > 1) {
      System.err.println("Only one of " + Arrays.toString(ONE_REQUIRED) + " may be specified");
      System.exit(-1);
    }

    HQApi api = getApi(options);
    MaintenanceApi maintenanceApi = api.getMaintenanceApi();
    StatusResponse response = null;
    Integer id = null;

    if (options.has(OPT_GROUPID)) {
      id = (Integer) getRequired(options, OPT_GROUPID);
      response = maintenanceApi.unschedule(id);
    } else if (options.has(OPT_RESOURCEID)) {
      id = (Integer) getRequired(options, OPT_RESOURCEID);
      ResourceResponse resourceResponse = api.getResourceApi().getResource(id, false, false);
      checkSuccess(resourceResponse);
      response = maintenanceApi.unschedule(resourceResponse.getResource());
    }

    checkSuccess(response);

    if (options.has(OPT_GROUPID)) {
      System.out.println("Maintenance for group " + id + " unscheduled.");
    } else {
      System.out.println("Maintenance for resource " + id + " unscheduled.");
    }
  }
示例#13
0
  private static OptionSet parseOptions(String[] argv) throws IOException {
    OptionSet args = null;
    OptionParser parser = new OptionParser();
    parser.acceptsAll(Arrays.asList("l", CMD_LIST), "list readers");
    parser.acceptsAll(Arrays.asList("p", OPT_PROVIDER), "specify provider").withRequiredArg();
    parser.acceptsAll(Arrays.asList("v", OPT_VERBOSE), "be verbose");
    parser.acceptsAll(Arrays.asList("e", OPT_ERROR), "fail if not 0x9000");
    parser.acceptsAll(Arrays.asList("h", OPT_HELP), "show help");
    parser.acceptsAll(Arrays.asList("r", OPT_READER), "use reader").withRequiredArg();
    parser.acceptsAll(Arrays.asList("a", CMD_APDU), "send APDU").withRequiredArg();
    parser.acceptsAll(Arrays.asList("w", OPT_WEB), "open ATR in web");
    parser.acceptsAll(Arrays.asList("V", OPT_VERSION), "show version information");
    parser.accepts(OPT_DUMP, "save dump to file").withRequiredArg().ofType(File.class);
    parser.accepts(OPT_REPLAY, "replay command from dump").withRequiredArg().ofType(File.class);

    parser.accepts(OPT_SUN, "load SunPCSC");
    parser.accepts(OPT_JNA, "load jnasmartcardio");
    parser.accepts(OPT_CONNECT, "connect to host:port or URL").withRequiredArg();
    parser.accepts(OPT_PINNED, "require certificate").withRequiredArg().ofType(File.class);

    parser.accepts(OPT_PROVIDERS, "list providers");
    parser.accepts(OPT_ALL, "process all readers");
    parser.accepts(OPT_WAIT, "wait for card insertion");
    parser.accepts(OPT_T0, "use T=0");
    parser.accepts(OPT_T1, "use T=1");
    parser.accepts(OPT_TEST_SERVER, "run a test server on port 10000").withRequiredArg();
    parser.accepts(OPT_NO_GET_RESPONSE, "don't use GET RESPONSE with SunPCSC");
    parser.accepts(OPT_LIB, "use specific PC/SC lib with SunPCSC").withRequiredArg();
    parser.accepts(OPT_PROVIDER_TYPE, "provider type if not PC/SC").withRequiredArg();

    // Parse arguments
    try {
      args = parser.parse(argv);
      // Try to fetch all values so that format is checked before usage
      for (String s : parser.recognizedOptions().keySet()) {
        args.valuesOf(s);
      }
    } catch (OptionException e) {
      if (e.getCause() != null) {
        System.err.println(e.getMessage() + ": " + e.getCause().getMessage());
      } else {
        System.err.println(e.getMessage());
      }
      System.err.println();
      help_and_exit(parser, System.err);
    }
    if (args.has(OPT_HELP)) {
      help_and_exit(parser, System.out);
    }
    return args;
  }
示例#14
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;
 }
示例#15
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);
  }
示例#16
0
 private static void send(PaymentSession session) {
   try {
     System.out.println("Payment Request");
     System.out.println("Amount: " + session.getValue().doubleValue() / 100000 + "mDOGE");
     System.out.println("Date: " + session.getDate());
     System.out.println("Memo: " + session.getMemo());
     if (session.pkiVerificationData != null) {
       System.out.println("Pki-Verified Name: " + session.pkiVerificationData.name);
       if (session.pkiVerificationData.orgName != null)
         System.out.println("Pki-Verified Org: " + session.pkiVerificationData.orgName);
       System.out.println(
           "PKI data verified by: " + session.pkiVerificationData.rootAuthorityName);
     }
     final Wallet.SendRequest req = session.getSendRequest();
     if (password != null) {
       if (!wallet.checkPassword(password)) {
         System.err.println("Password is incorrect.");
         return;
       }
       req.aesKey = wallet.getKeyCrypter().deriveKey(password);
     }
     wallet.completeTx(req); // may throw InsufficientMoneyException.
     if (options.has("offline")) {
       wallet.commitTx(req.tx);
       return;
     }
     setup();
     // No refund address specified, no user-specified memo field.
     ListenableFuture<PaymentSession.Ack> future =
         session.sendPayment(ImmutableList.of(req.tx), null, null);
     if (future == null) {
       // No payment_url for submission so, broadcast and wait.
       peers.startAndWait();
       peers.broadcastTransaction(req.tx).get();
     } else {
       PaymentSession.Ack ack = future.get();
       wallet.commitTx(req.tx);
       System.out.println("Memo from server: " + ack.getMemo());
     }
   } catch (PaymentRequestException e) {
     System.err.println("Failed to send payment " + e.getMessage());
     System.exit(1);
   } catch (VerificationException e) {
     System.err.println("Failed to send payment " + e.getMessage());
     System.exit(1);
   } catch (ExecutionException e) {
     System.err.println("Failed to send payment " + e.getMessage());
     System.exit(1);
   } catch (IOException e) {
     System.err.println("Invalid payment " + e.getMessage());
     System.exit(1);
   } catch (InterruptedException e1) {
     // Ignore.
   } catch (InsufficientMoneyException e) {
     System.err.println(
         "Insufficient funds: have " + Utils.bitcoinValueToFriendlyString(wallet.getBalance()));
   } catch (BlockStoreException e) {
     throw new RuntimeException(e);
   }
 }
  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;
  }
示例#18
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));
    }
  }
 @Override
 protected void verifyOptionSet(OptionSet options) throws Exception {
   String appId = options.valueOf(getApplicationIdOption());
   if (!appId.startsWith("jee")) {
     throw new IllegalArgumentException("no jee");
   }
 }
示例#20
0
 private OptionSet parseOptions(OptionParser p, String[] args) throws IOException {
   OptionSet options = null;
   try {
     options = p.parse(args);
     if (options.has("?")
         || !options.has(maxwiOptName)
         || options.nonOptionArguments().size() < 2) {
       System.err.println("Usage:\nSimilarity <input_paths> <output_path> [options]");
       System.err.println("Please specify " + maxwiOptName + " option\n");
       p.printHelpOn(System.err);
       System.exit(0);
     }
   } catch (OptionException e) {
     System.err.println(e.getMessage());
     System.exit(1);
   }
   return options;
 }
示例#21
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"));
  }
示例#22
0
 private static void checkRequiredArgs(
     OptionParser parser, OptionSet options, OptionSpec[] required) throws IOException {
   for (OptionSpec arg : required) {
     if (!options.has(arg)) {
       System.err.println("Missing required argument \"" + arg + "\"");
       parser.printHelpOn(System.err);
       System.exit(1);
     }
   }
 }
  @Test
  public void parsesFilesWithWhitespaceSuccessfully() throws IOException {
    File tempFile = File.createTempFile("this is a test with whitespaces", ".txt");
    tempFile.deleteOnExit();
    System.out.println("Using temp file: " + tempFile.getAbsolutePath());

    // use a dummy configuration
    final CompositeConfiguration dummyConfig = new CompositeConfiguration();
    final GlacierUploaderOptionParser optionParser = new GlacierUploaderOptionParser(dummyConfig);
    final OptionSet options = optionParser.parse("-m", tempFile.getAbsolutePath());
    final List<File> optionsFiles = options.valuesOf(optionParser.MULTIPARTUPLOAD);
    final List<String> nonOptions = options.nonOptionArguments();

    assertEquals(1, optionsFiles.size());
    assertEquals(0, nonOptions.size());

    final ArrayList<File> files = optionParser.mergeNonOptionsFiles(optionsFiles, nonOptions);
    assertEquals(tempFile.getName(), files.get(0).getName());
  }
示例#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());
    }
  }
 static void checkRequiredArgs(
     OptionParser parser, OptionSet options, OptionSpec<?>... optionSepcs) throws IOException {
   for (OptionSpec<?> arg : optionSepcs) {
     if (!options.has(arg)) {
       System.err.println("Missing required argument " + arg);
       // parser.formatHelpWith(new MyFormatter());
       parser.printHelpOn(System.err);
       System.exit(1);
     }
   }
 }
示例#26
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);
  }
  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);
    }
  }
示例#28
0
文件: Runner.java 项目: raiben/made
  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);
  }
示例#29
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");
  }
示例#30
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));
   }
 }