Example usage for java.lang IllegalArgumentException IllegalArgumentException

List of usage examples for java.lang IllegalArgumentException IllegalArgumentException

Introduction

In this page you can find the example usage for java.lang IllegalArgumentException IllegalArgumentException.

Prototype

public IllegalArgumentException(Throwable cause) 

Source Link

Document

Constructs a new exception with the specified cause and a detail message of (cause==null ?

Usage

From source file:com.p2p.peercds.cli.TorrentMain.java

/**
 * Torrent reader and creator./*from ww  w .  j av  a  2  s  .  c  om*/
 *
 * <p>
 * You can use the {@code main()} function of this class to read or create
 * torrent files. See usage for details.
 * </p>
 *
 */
public static void main(String[] args) {
    BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%-5p: %m%n")));

    CmdLineParser parser = new CmdLineParser();
    CmdLineParser.Option help = parser.addBooleanOption('h', "help");
    CmdLineParser.Option filename = parser.addStringOption('t', "torrent");
    CmdLineParser.Option create = parser.addBooleanOption('c', "create");
    CmdLineParser.Option announce = parser.addStringOption('a', "announce");

    try {
        parser.parse(args);
    } catch (CmdLineParser.OptionException oe) {
        System.err.println(oe.getMessage());
        usage(System.err);
        System.exit(1);
    }

    // Display help and exit if requested
    if (Boolean.TRUE.equals((Boolean) parser.getOptionValue(help))) {
        usage(System.out);
        System.exit(0);
    }

    String filenameValue = (String) parser.getOptionValue(filename);
    if (filenameValue == null) {
        usage(System.err, "Torrent file must be provided!");
        System.exit(1);
    }

    Boolean createFlag = (Boolean) parser.getOptionValue(create);

    //For repeated announce urls
    @SuppressWarnings("unchecked")
    Vector<String> announceURLs = (Vector<String>) parser.getOptionValues(announce);

    String[] otherArgs = parser.getRemainingArgs();

    if (Boolean.TRUE.equals(createFlag) && (otherArgs.length != 1 || announceURLs.isEmpty())) {
        usage(System.err,
                "Announce URL and a file or directory must be " + "provided to create a torrent file!");
        System.exit(1);
    }

    OutputStream fos = null;
    try {
        if (Boolean.TRUE.equals(createFlag)) {
            if (filenameValue != null) {
                fos = new FileOutputStream(filenameValue);
            } else {
                fos = System.out;
            }

            //Process the announce URLs into URIs
            List<URI> announceURIs = new ArrayList<URI>();
            for (String url : announceURLs) {
                announceURIs.add(new URI(url));
            }

            //Create the announce-list as a list of lists of URIs
            //Assume all the URI's are first tier trackers
            List<List<URI>> announceList = new ArrayList<List<URI>>();
            announceList.add(announceURIs);

            File source = new File(otherArgs[0]);
            if (!source.exists() || !source.canRead()) {
                throw new IllegalArgumentException(
                        "Cannot access source file or directory " + source.getName());
            }

            String creator = String.format("%s (ttorrent)", System.getProperty("user.name"));

            Torrent torrent = null;
            if (source.isDirectory()) {
                File[] files = source.listFiles(Constants.hiddenFilesFilter);
                Arrays.sort(files);
                torrent = Torrent.create(source, Arrays.asList(files), announceList, creator);
            } else {
                torrent = Torrent.create(source, announceList, creator);

            }

            torrent.save(fos);
        } else {
            Torrent.load(new File(filenameValue), true);
        }
    } catch (Exception e) {
        logger.error("{}", e.getMessage(), e);
        System.exit(2);
    } finally {
        if (fos != System.out) {
            IOUtils.closeQuietly(fos);
        }
    }
}

From source file:com.mh2c.LogGenerator.java

public static void main(String[] args) throws Exception {
    if (args.length != 3) {
        throw new IllegalArgumentException(
                "Expected arguments: Kinesis stream name, " + "records per second, number of records");
    }//www.  j  a  v a 2 s.  c o m

    new LogGenerator().generate(args[0], Integer.parseInt(args[1]), Integer.parseInt(args[2]));
}

From source file:com.google.oacurl.Login.java

public static void main(String[] args) throws Exception {
    LoginOptions options = new LoginOptions();
    try {//  w ww.j  a  v  a  2s .c o  m
        options.parse(args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.exit(-1);
    }

    if (options.isHelp()) {
        new HelpFormatter().printHelp(" ", options.getOptions());
        System.exit(0);
    }

    if (options.isInsecure()) {
        SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());
    }

    LoggingConfig.init(options.isVerbose());
    if (options.isWirelogVerbose()) {
        LoggingConfig.enableWireLog();
    }

    ServiceProviderDao serviceProviderDao = new ServiceProviderDao();
    ConsumerDao consumerDao = new ConsumerDao(options);
    AccessorDao accessorDao = new AccessorDao();

    String serviceProviderFileName = options.getServiceProviderFileName();
    if (serviceProviderFileName == null) {
        if (options.isBuzz()) {
            // Buzz has its own provider because it has a custom authorization URL
            serviceProviderFileName = "BUZZ";
        } else if (options.getVersion() == OAuthVersion.V2) {
            serviceProviderFileName = "GOOGLE_V2";
        } else {
            serviceProviderFileName = "GOOGLE";
        }
    }

    // We have a wee library of service provider properties files bundled into
    // the resources, so we set up the PropertiesProvider to search for them
    // if the file cannot be found.
    OAuthServiceProvider serviceProvider = serviceProviderDao.loadServiceProvider(
            new PropertiesProvider(serviceProviderFileName, ServiceProviderDao.class, "services/").get());
    OAuthConsumer consumer = consumerDao
            .loadConsumer(new PropertiesProvider(options.getConsumerFileName()).get(), serviceProvider);
    OAuthAccessor accessor = accessorDao.newAccessor(consumer);

    OAuthClient client = new OAuthClient(new HttpClient4());

    LoginCallbackServer callbackServer = null;

    boolean launchedBrowser = false;

    try {
        if (!options.isNoServer()) {
            callbackServer = new LoginCallbackServer(options);
            callbackServer.start();
        }

        String callbackUrl;
        if (options.getCallback() != null) {
            callbackUrl = options.getCallback();
        } else if (callbackServer != null) {
            callbackUrl = callbackServer.getCallbackUrl();
        } else {
            callbackUrl = null;
        }

        OAuthEngine engine;
        switch (options.getVersion()) {
        case V1:
            engine = new V1OAuthEngine();
            break;
        case V2:
            engine = new V2OAuthEngine();
            break;
        case WRAP:
            engine = new WrapOAuthEngine();
            break;
        default:
            throw new IllegalArgumentException("Unknown version: " + options.getVersion());
        }

        do {
            String authorizationUrl = engine.getAuthorizationUrl(client, accessor, options, callbackUrl);

            if (!options.isNoServer()) {
                callbackServer.setAuthorizationUrl(authorizationUrl);
            }

            if (!launchedBrowser) {
                String url = options.isDemo() ? callbackServer.getDemoUrl() : authorizationUrl;

                if (options.isNoBrowser()) {
                    System.out.println(url);
                    System.out.flush();
                } else {
                    launchBrowser(options, url);
                }

                launchedBrowser = true;
            }

            accessor.accessToken = null;

            logger.log(Level.INFO, "Waiting for verification token...");
            String verifier;
            if (options.isNoServer()) {
                System.out.print("Verification token: ");
                BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
                verifier = "";
                while (verifier.isEmpty()) {
                    String line = reader.readLine();
                    if (line == null) {
                        System.exit(-1);
                    }
                    verifier = line.trim();
                }
            } else {
                verifier = callbackServer.waitForVerifier(accessor, -1);
                if (verifier == null) {
                    System.err.println("Wait for verifier interrupted");
                    System.exit(-1);
                }
            }
            logger.log(Level.INFO, "Verification token received: " + verifier);

            boolean success = engine.getAccessToken(accessor, client, callbackUrl, verifier);

            if (success) {
                if (callbackServer != null) {
                    callbackServer.setTokenStatus(TokenStatus.VALID);
                }

                Properties loginProperties = new Properties();
                accessorDao.saveAccessor(accessor, loginProperties);
                consumerDao.saveConsumer(consumer, loginProperties);
                loginProperties.put("oauthVersion", options.getVersion().toString());
                new PropertiesProvider(options.getLoginFileName()).overwrite(loginProperties);
            } else {
                if (callbackServer != null) {
                    callbackServer.setTokenStatus(TokenStatus.INVALID);
                }
            }
        } while (options.isDemo());
    } catch (OAuthProblemException e) {
        OAuthUtil.printOAuthProblemException(e);
    } finally {
        if (callbackServer != null) {
            callbackServer.stop();
        }
    }
}

From source file:eu.itesla_project.online.mpi.Master.java

public static void main(String[] args) throws Exception {
    try {/*from   w  w w .  j a v a 2  s  . c o  m*/
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(OPTIONS, args);

        String mode = line.getOptionValue("m");
        Path tmpDir = Paths.get(line.getOptionValue("t"));
        Class<?> statisticsFactoryClass = Class.forName(line.getOptionValue("f"));
        Path statisticsDbDir = Paths.get(line.getOptionValue("s"));
        String statisticsDbName = line.getOptionValue("d");
        int coresPerRank = Integer.parseInt(line.getOptionValue("n"));
        Path stdOutArchive = line.hasOption("o") ? Paths.get(line.getOptionValue("o")) : null;

        MpiExecutorContext mpiExecutorContext = new MultiStateNetworkAwareMpiExecutorContext();
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        ExecutorService executorService = MultiStateNetworkAwareExecutors.newCachedThreadPool();
        try {
            MpiStatisticsFactory statisticsFactory = statisticsFactoryClass
                    .asSubclass(MpiStatisticsFactory.class).newInstance();
            MpiStatistics statistics = statisticsFactory.create(statisticsDbDir, statisticsDbName);
            try (ComputationManager computationManager = new MpiComputationManager(tmpDir, statistics,
                    mpiExecutorContext, coresPerRank, false, stdOutArchive)) {
                OnlineConfig config = OnlineConfig.load();
                try (LocalOnlineApplication application = new LocalOnlineApplication(config, computationManager,
                        scheduledExecutorService, executorService, true)) {
                    switch (mode) {
                    case "ui":
                        System.out.println("LocalOnlineApplication created");
                        System.out.println("Waiting till shutdown");
                        // indefinitely wait for JMX commands
                        //TimeUnit.DAYS.sleep(Integer.MAX_VALUE);
                        synchronized (application) {
                            try {
                                application.wait();
                            } catch (InterruptedException ex) {
                            }

                        }
                        break;
                    default:
                        throw new IllegalArgumentException("Invalid mode " + mode);
                    }
                }
            }
        } finally {
            mpiExecutorContext.shutdown();
            executorService.shutdown();
            scheduledExecutorService.shutdown();
            executorService.awaitTermination(15, TimeUnit.MINUTES);
            scheduledExecutorService.awaitTermination(15, TimeUnit.MINUTES);
        }
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("master", OPTIONS, true);
        System.exit(-1);
    } catch (Throwable t) {
        LOGGER.error(t.toString(), t);
        System.exit(-1);
    }
}

From source file:com.google.oacurl.Fetch.java

public static void main(String[] args) throws Exception {
    FetchOptions options = new FetchOptions();
    CommandLine line = options.parse(args);
    args = line.getArgs();//from  w w  w .  j av  a 2 s .c o  m

    if (options.isHelp()) {
        new HelpFormatter().printHelp("url", options.getOptions());
        System.exit(0);
    }

    if (args.length != 1) {
        new HelpFormatter().printHelp("url", options.getOptions());
        System.exit(-1);
    }

    if (options.isInsecure()) {
        SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());
    }

    LoggingConfig.init(options.isVerbose());
    if (options.isVerbose()) {
        LoggingConfig.enableWireLog();
    }

    String url = args[0];

    ServiceProviderDao serviceProviderDao = new ServiceProviderDao();
    ConsumerDao consumerDao = new ConsumerDao();
    AccessorDao accessorDao = new AccessorDao();

    Properties loginProperties = null;
    try {
        loginProperties = new PropertiesProvider(options.getLoginFileName()).get();
    } catch (FileNotFoundException e) {
        System.err.println(".oacurl.properties file not found in homedir");
        System.err.println("Make sure you've run oacurl-login first!");
        System.exit(-1);
    }

    OAuthServiceProvider serviceProvider = serviceProviderDao.nullServiceProvider();
    OAuthConsumer consumer = consumerDao.loadConsumer(loginProperties, serviceProvider);
    OAuthAccessor accessor = accessorDao.loadAccessor(loginProperties, consumer);

    OAuthClient client = new OAuthClient(new HttpClient4(SingleClient.HTTP_CLIENT_POOL));

    OAuthVersion version = (loginProperties.containsKey("oauthVersion"))
            ? OAuthVersion.valueOf(loginProperties.getProperty("oauthVersion"))
            : OAuthVersion.V1;

    OAuthEngine engine;
    switch (version) {
    case V1:
        engine = new V1OAuthEngine();
        break;
    case V2:
        engine = new V2OAuthEngine();
        break;
    case WRAP:
        engine = new WrapOAuthEngine();
        break;
    default:
        throw new IllegalArgumentException("Unknown version: " + version);
    }

    try {
        OAuthMessage request;

        List<Entry<String, String>> related = options.getRelated();

        Method method = options.getMethod();
        if (method == Method.POST || method == Method.PUT) {
            InputStream bodyStream;
            if (related != null) {
                bodyStream = new MultipartRelatedInputStream(related);
            } else if (options.getFile() != null) {
                bodyStream = new FileInputStream(options.getFile());
            } else {
                bodyStream = System.in;
            }
            request = newRequestMessage(accessor, method, url, bodyStream, engine);
            request.getHeaders().add(new OAuth.Parameter("Content-Type", options.getContentType()));
        } else {
            request = newRequestMessage(accessor, method, url, null, engine);
        }

        List<Parameter> headers = options.getHeaders();
        addHeadersToRequest(request, headers);

        HttpResponseMessage httpResponse;
        if (version == OAuthVersion.V1) {
            OAuthResponseMessage response;
            response = client.access(request, ParameterStyle.AUTHORIZATION_HEADER);
            httpResponse = response.getHttpResponse();
        } else {
            HttpMessage httpRequest = new HttpMessage(request.method, new URL(request.URL),
                    request.getBodyAsStream());
            httpRequest.headers.addAll(request.getHeaders());
            httpResponse = client.getHttpClient().execute(httpRequest, client.getHttpParameters());
            httpResponse = HttpMessageDecoder.decode(httpResponse);
        }

        System.err.flush();

        if (options.isInclude()) {
            Map<String, Object> dump = new HashMap<String, Object>();
            httpResponse.dump(dump);
            System.out.print(dump.get(HttpMessage.RESPONSE));
        }

        // Dump the bytes in the response's encoding.
        InputStream bodyStream = httpResponse.getBody();
        byte[] buf = new byte[1024];
        int count;
        while ((count = bodyStream.read(buf)) > -1) {
            System.out.write(buf, 0, count);
        }
    } catch (OAuthProblemException e) {
        OAuthUtil.printOAuthProblemException(e);
    }
}

From source file:edu.msu.cme.rdp.multicompare.Reprocess.java

/**
 * This class reprocesses the classification results (allrank output) and print out hierarchy output file, based on the confidence cutoff;
 * and print out only the detail classification results with assignment at certain rank with confidence above the cutoff or/and matching a given taxon.
 * @param args//  w  w w  .j a  v  a 2 s.c o m
 * @throws Exception 
 */
public static void main(String[] args) throws Exception {

    PrintWriter assign_out = new PrintWriter(new NullWriter());
    float conf = 0.8f;
    PrintStream heir_out = null;
    String hier_out_filename = null;
    ClassificationResultFormatter.FORMAT format = ClassificationResultFormatter.FORMAT.allRank;
    String rank = null;
    String taxonFilterFile = null;
    String train_propfile = null;
    String gene = null;
    List<MCSample> samples = new ArrayList();

    try {
        CommandLine line = new PosixParser().parse(options, args);
        if (line.hasOption(CmdOptions.HIER_OUTFILE_SHORT_OPT)) {
            hier_out_filename = line.getOptionValue(CmdOptions.HIER_OUTFILE_SHORT_OPT);
            heir_out = new PrintStream(hier_out_filename);
        } else {
            throw new Exception(
                    "It make sense to provide output filename for " + CmdOptions.HIER_OUTFILE_LONG_OPT);
        }
        if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) {
            assign_out = new PrintWriter(line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT));
        }

        if (line.hasOption(CmdOptions.RANK_SHORT_OPT)) {
            rank = line.getOptionValue(CmdOptions.RANK_SHORT_OPT);
        }
        if (line.hasOption(CmdOptions.TAXON_SHORT_OPT)) {
            taxonFilterFile = line.getOptionValue(CmdOptions.TAXON_SHORT_OPT);
        }

        if (line.hasOption(CmdOptions.BOOTSTRAP_SHORT_OPT)) {
            conf = Float.parseFloat(line.getOptionValue(CmdOptions.BOOTSTRAP_SHORT_OPT));
            if (conf < 0 || conf > 1) {
                throw new IllegalArgumentException("Confidence must be in the range [0,1]");
            }
        }
        if (line.hasOption(CmdOptions.FORMAT_SHORT_OPT)) {
            String f = line.getOptionValue(CmdOptions.FORMAT_SHORT_OPT);
            if (f.equalsIgnoreCase("allrank")) {
                format = ClassificationResultFormatter.FORMAT.allRank;
            } else if (f.equalsIgnoreCase("fixrank")) {
                format = ClassificationResultFormatter.FORMAT.fixRank;
            } else if (f.equalsIgnoreCase("db")) {
                format = ClassificationResultFormatter.FORMAT.dbformat;
            } else if (f.equalsIgnoreCase("filterbyconf")) {
                format = ClassificationResultFormatter.FORMAT.filterbyconf;
            } else {
                throw new IllegalArgumentException(
                        "Not valid output format, only allrank, fixrank, filterbyconf and db allowed");
            }
        }
        if (line.hasOption(CmdOptions.TRAINPROPFILE_SHORT_OPT)) {
            if (gene != null) {
                throw new IllegalArgumentException(
                        "Already specified the gene from the default location. Can not specify train_propfile");
            } else {
                train_propfile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT);
            }
        }
        if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) {
            if (train_propfile != null) {
                throw new IllegalArgumentException(
                        "Already specified train_propfile. Can not specify gene any more");
            }
            gene = line.getOptionValue(CmdOptions.GENE_SHORT_OPT).toLowerCase();

            if (!gene.equals(ClassifierFactory.RRNA_16S_GENE) && !gene.equals(ClassifierFactory.FUNGALLSU_GENE)
                    && !gene.equals(ClassifierFactory.FUNGALITS_warcup_GENE)
                    && !gene.equals(ClassifierFactory.FUNGALITS_unite_GENE)) {
                throw new IllegalArgumentException(gene + " is NOT valid, only allows "
                        + ClassifierFactory.RRNA_16S_GENE + ", " + ClassifierFactory.FUNGALLSU_GENE + ", "
                        + ClassifierFactory.FUNGALITS_warcup_GENE + " and "
                        + ClassifierFactory.FUNGALITS_unite_GENE);
            }
        }
        args = line.getArgs();
        if (args.length < 1) {
            throw new Exception("Incorrect number of command line arguments");
        }

        for (String arg : args) {
            String[] inFileNames = arg.split(",");
            String inputFile = inFileNames[0];
            File idmappingFile = null;

            if (inFileNames.length == 2) {
                idmappingFile = new File(inFileNames[1]);
                if (!idmappingFile.exists()) {
                    System.err.println("Failed to find input file \"" + inFileNames[1] + "\"");
                    return;
                }
            }

            MCSample nextSample = new MCSampleResult(inputFile, idmappingFile);
            samples.add(nextSample);

        }
    } catch (Exception e) {
        System.out.println("Command Error: " + e.getMessage());
        new HelpFormatter().printHelp(120,
                "Reprocess [options] <Classification_allrank_result>[,idmappingfile] ...", "", options, "");
        return;
    }

    if (train_propfile == null && gene == null) {
        gene = ClassifierFactory.RRNA_16S_GENE;
    }

    HashSet<String> taxonFilter = null;
    if (taxonFilterFile != null) {
        taxonFilter = readTaxonFilterFile(taxonFilterFile);
    }

    MultiClassifier multiClassifier = new MultiClassifier(train_propfile, gene);
    DefaultPrintVisitor printVisitor = new DefaultPrintVisitor(heir_out, samples);
    MultiClassifierResult result = multiClassifier.multiClassificationParser(samples, conf, assign_out, format,
            rank, taxonFilter);

    result.getRoot().topDownVisit(printVisitor);

    assign_out.close();
    heir_out.close();
    if (multiClassifier.hasCopyNumber()) {
        // print copy number corrected counts
        File cn_corrected_s = new File(new File(hier_out_filename).getParentFile(),
                "cncorrected_" + hier_out_filename);
        PrintStream cn_corrected_hier_out = new PrintStream(cn_corrected_s);
        printVisitor = new DefaultPrintVisitor(cn_corrected_hier_out, samples, true);
        result.getRoot().topDownVisit(printVisitor);
        cn_corrected_hier_out.close();
    }

}

From source file:com.tamingtext.classifier.bayes.ExtractTrainingData.java

public static void main(String[] args) {

    log.info("Command-line arguments: " + Arrays.toString(args));

    DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
    ArgumentBuilder abuilder = new ArgumentBuilder();
    GroupBuilder gbuilder = new GroupBuilder();

    Option inputOpt = obuilder.withLongName("dir").withRequired(true)
            .withArgument(abuilder.withName("dir").withMinimum(1).withMaximum(1).create())
            .withDescription("Lucene index directory containing input data").withShortName("d").create();

    Option categoryOpt = obuilder.withLongName("categories").withRequired(true)
            .withArgument(abuilder.withName("file").withMinimum(1).withMaximum(1).create())
            .withDescription("File containing a list of categories").withShortName("c").create();

    Option outputOpt = obuilder.withLongName("output").withRequired(false)
            .withArgument(abuilder.withName("output").withMinimum(1).withMaximum(1).create())
            .withDescription("Output directory").withShortName("o").create();

    Option categoryFieldsOpt = obuilder.withLongName("category-fields").withRequired(true)
            .withArgument(abuilder.withName("fields").withMinimum(1).withMaximum(1).create())
            .withDescription("Fields to match categories against (comma-delimited)").withShortName("cf")
            .create();/*from  w w w.j a v a 2s . co  m*/

    Option textFieldsOpt = obuilder.withLongName("text-fields").withRequired(true)
            .withArgument(abuilder.withName("fields").withMinimum(1).withMaximum(1).create())
            .withDescription("Fields from which to extract training text (comma-delimited)").withShortName("tf")
            .create();

    Option useTermVectorsOpt = obuilder.withLongName("use-term-vectors").withDescription(
            "Extract term vectors containing preprocessed data " + "instead of unprocessed, stored text values")
            .withShortName("tv").create();

    Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h")
            .create();

    Group group = gbuilder.withName("Options").withOption(inputOpt).withOption(categoryOpt)
            .withOption(outputOpt).withOption(categoryFieldsOpt).withOption(textFieldsOpt)
            .withOption(useTermVectorsOpt).create();

    try {
        Parser parser = new Parser();
        parser.setGroup(group);
        CommandLine cmdLine = parser.parse(args);

        if (cmdLine.hasOption(helpOpt)) {
            CommandLineUtil.printHelp(group);
            return;
        }

        File inputDir = new File(cmdLine.getValue(inputOpt).toString());

        if (!inputDir.isDirectory()) {
            throw new IllegalArgumentException(inputDir + " does not exist or is not a directory");
        }

        File categoryFile = new File(cmdLine.getValue(categoryOpt).toString());

        if (!categoryFile.isFile()) {
            throw new IllegalArgumentException(categoryFile + " does not exist or is not a directory");
        }

        File outputDir = new File(cmdLine.getValue(outputOpt).toString());

        outputDir.mkdirs();

        if (!outputDir.isDirectory()) {
            throw new IllegalArgumentException(outputDir + " is not a directory or could not be created");
        }

        Collection<String> categoryFields = stringToList(cmdLine.getValue(categoryFieldsOpt).toString());

        if (categoryFields.size() < 1) {
            throw new IllegalArgumentException("At least one category field must be spcified.");
        }

        Collection<String> textFields = stringToList(cmdLine.getValue(textFieldsOpt).toString());

        if (categoryFields.size() < 1) {
            throw new IllegalArgumentException("At least one text field must be spcified.");
        }

        boolean useTermVectors = cmdLine.hasOption(useTermVectorsOpt);

        extractTraininingData(inputDir, categoryFile, categoryFields, textFields, outputDir, useTermVectors);

    } catch (OptionException e) {
        log.error("Exception", e);
        CommandLineUtil.printHelp(group);
    } catch (IOException e) {
        log.error("IOException", e);
    } finally {
        closeWriters();
    }
}

From source file:com.turn.ttorrent.cli.TorrentMain.java

/**
 * Torrent reader and creator.//from  w w  w .  j  ava  2s  . c o  m
 *
 * <p>
 * You can use the {@code main()} function of this class to read or create
 * torrent files. See usage for details.
 * </p>
 *
 */
public static void main(String[] args) {
    BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%-5p: %m%n")));

    CmdLineParser parser = new CmdLineParser();
    CmdLineParser.Option help = parser.addBooleanOption('h', "help");
    CmdLineParser.Option filename = parser.addStringOption('t', "torrent");
    CmdLineParser.Option create = parser.addBooleanOption('c', "create");
    CmdLineParser.Option pieceLength = parser.addIntegerOption('l', "length");
    CmdLineParser.Option announce = parser.addStringOption('a', "announce");

    try {
        parser.parse(args);
    } catch (CmdLineParser.OptionException oe) {
        System.err.println(oe.getMessage());
        usage(System.err);
        System.exit(1);
    }

    // Display help and exit if requested
    if (Boolean.TRUE.equals((Boolean) parser.getOptionValue(help))) {
        usage(System.out);
        System.exit(0);
    }

    String filenameValue = (String) parser.getOptionValue(filename);
    if (filenameValue == null) {
        usage(System.err, "Torrent file must be provided!");
        System.exit(1);
    }

    Integer pieceLengthVal = (Integer) parser.getOptionValue(pieceLength);
    if (pieceLengthVal == null) {
        pieceLengthVal = Torrent.DEFAULT_PIECE_LENGTH;
    } else {
        pieceLengthVal = pieceLengthVal * 1024;
    }
    logger.info("Using piece length of {} bytes.", pieceLengthVal);

    Boolean createFlag = (Boolean) parser.getOptionValue(create);

    //For repeated announce urls
    @SuppressWarnings("unchecked")
    Vector<String> announceURLs = (Vector<String>) parser.getOptionValues(announce);

    String[] otherArgs = parser.getRemainingArgs();

    if (Boolean.TRUE.equals(createFlag) && (otherArgs.length != 1 || announceURLs.isEmpty())) {
        usage(System.err,
                "Announce URL and a file or directory must be " + "provided to create a torrent file!");
        System.exit(1);
    }

    OutputStream fos = null;
    try {
        if (Boolean.TRUE.equals(createFlag)) {
            if (filenameValue != null) {
                fos = new FileOutputStream(filenameValue);
            } else {
                fos = System.out;
            }

            //Process the announce URLs into URIs
            List<URI> announceURIs = new ArrayList<URI>();
            for (String url : announceURLs) {
                announceURIs.add(new URI(url));
            }

            //Create the announce-list as a list of lists of URIs
            //Assume all the URI's are first tier trackers
            List<List<URI>> announceList = new ArrayList<List<URI>>();
            announceList.add(announceURIs);

            File source = new File(otherArgs[0]);
            if (!source.exists() || !source.canRead()) {
                throw new IllegalArgumentException(
                        "Cannot access source file or directory " + source.getName());
            }

            String creator = String.format("%s (ttorrent)", System.getProperty("user.name"));

            Torrent torrent = null;
            if (source.isDirectory()) {
                List<File> files = new ArrayList<File>(
                        FileUtils.listFiles(source, TrueFileFilter.TRUE, TrueFileFilter.TRUE));
                Collections.sort(files);
                torrent = Torrent.create(source, files, pieceLengthVal, announceList, creator);
            } else {
                torrent = Torrent.create(source, pieceLengthVal, announceList, creator);
            }

            torrent.save(fos);
        } else {
            Torrent.load(new File(filenameValue), true);
        }
    } catch (Exception e) {
        logger.error("{}", e.getMessage(), e);
        System.exit(2);
    } finally {
        if (fos != System.out) {
            IOUtils.closeQuietly(fos);
        }
    }
}

From source file:dk.alexandra.fresco.demo.AESDemo.java

/**
 * The main method sets up application specific command line parameters,
 * parses command line arguments. Based on the command line arguments it
 * configures the SCE, instantiates the TestAESDemo and runs the TestAESDemo on the
 * SCE./*from  ww w .ja  v a2  s. c  om*/
 * 
 */
public static void main(String[] args) {
    CmdLineUtil util = new CmdLineUtil();
    SCEConfiguration sceConf = null;
    boolean[] input = null;
    try {

        util.addOption(Option.builder("in")
                .desc("The input to use for encryption. " + "A " + INPUT_LENGTH
                        + " char hex string. Required for player 1 and 2. "
                        + "For player 1 this is interpreted as the AES key. "
                        + "For player 2 this is interpreted as the plaintext block to encrypt.")
                .longOpt("input").hasArg().build());

        CommandLine cmd = util.parse(args);
        sceConf = util.getSCEConfiguration();

        // Get and validate the AES specific input.
        if (sceConf.getMyId() == 1 || sceConf.getMyId() == 2) {
            if (!cmd.hasOption("in")) {
                throw new ParseException("Player 1 and 2 must submit input");
            } else {
                if (cmd.getOptionValue("in").length() != INPUT_LENGTH) {
                    throw new IllegalArgumentException(
                            "bad input hex string: must be hex string of length " + INPUT_LENGTH);
                }
                input = ByteArithmetic.toBoolean(cmd.getOptionValue("in"));
            }
        } else {
            if (cmd.hasOption("in")) {
                throw new ParseException("Only player 1 and 2 should submit input");
            }
        }

    } catch (ParseException | IllegalArgumentException e) {
        System.out.println("Error: " + e);
        System.out.println();
        util.displayHelp();
        System.exit(-1);
    }

    // Do the secure computation using config from property files.
    AESDemo aes = new AESDemo(sceConf.getMyId(), input);
    SCE sce = SCEFactory.getSCEFromConfiguration(sceConf, util.getProtocolSuiteConfiguration());

    try {
        sce.runApplication(aes);
    } catch (MPCException e) {
        System.out.println("Error while doing MPC: " + e.getMessage());
        System.exit(-1);
    }

    // Print result.
    boolean[] res = new boolean[BLOCK_SIZE];
    for (int i = 0; i < BLOCK_SIZE; i++) {
        res[i] = aes.result[i].getValue();
    }
    System.out.println("The resulting ciphertext is: " + ByteArithmetic.toHex(res));

}

From source file:edu.msu.cme.rdp.classifier.train.validation.crossvalidate.CrossValidateMain.java

/**
 * This is the main method for cross validation test. 
 * @param args//from  w  ww  . jav  a2s  .  c om
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    String tax_file = null;
    String source_file = null;
    String out_file = null;
    Integer partialLength = null; // default is full length
    float fraction = 0.1f;
    String rdmSelectedRank = null;
    int min_bootstrap_words = NBClassifier.MIN_BOOTSTRSP_WORDS;
    try {
        CommandLine line = new PosixParser().parse(options, args);
        if (line.hasOption(TRAIN_TAXONFILE_SHORT_OPT)) {
            tax_file = line.getOptionValue(TRAIN_TAXONFILE_SHORT_OPT);
        } else {
            throw new ParseException("Taxonomy file must be specified");
        }
        if (line.hasOption(TRAIN_SEQFILE_SHORT_OPT)) {
            source_file = line.getOptionValue(TRAIN_SEQFILE_SHORT_OPT);
        } else {
            throw new ParseException("Source training fasta file must be specified");
        }
        if (line.hasOption(OUTFILE_SHORT_OPT)) {
            out_file = line.getOptionValue(OUTFILE_SHORT_OPT);
        } else {
            throw new ParseException("Output file must be specified");
        }

        if (line.hasOption(LENGTH_SHORT_OPT)) {
            ;
            partialLength = new Integer(line.getOptionValue(LENGTH_SHORT_OPT));
        }
        if (line.hasOption("fraction")) {
            fraction = Float.parseFloat(line.getOptionValue("fraction"));
        }
        if (line.hasOption("rdmRank")) {
            rdmSelectedRank = line.getOptionValue("rdmRank");
        }
        if (line.hasOption(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT)) {
            min_bootstrap_words = Integer
                    .parseInt(line.getOptionValue(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT));
            if (min_bootstrap_words < NBClassifier.MIN_BOOTSTRSP_WORDS) {
                throw new IllegalArgumentException(
                        min_bootstrap_words + " must be at least " + NBClassifier.MIN_BOOTSTRSP_WORDS);
            }
        }

    } catch (ParseException ex) {
        new HelpFormatter().printHelp(120, "CrossValidateMain", "", options, "", true);
        return;
    }

    boolean useSeed = true; // use seed for random number generator

    CrossValidate theObj = new CrossValidate();
    theObj.runTest(new File(tax_file), new File(source_file), new File(out_file), rdmSelectedRank, fraction,
            partialLength, useSeed, min_bootstrap_words);

}