Example usage for java.util Arrays asList

List of usage examples for java.util Arrays asList

Introduction

In this page you can find the example usage for java.util Arrays asList.

Prototype

@SafeVarargs
@SuppressWarnings("varargs")
public static <T> List<T> asList(T... a) 

Source Link

Document

Returns a fixed-size list backed by the specified array.

Usage

From source file:com.revo.deployr.client.example.data.io.auth.stateful.exec.EncodedDataInBinaryFileOut.java

public static void main(String args[]) throws Exception {

    RClient rClient = null;/*www  . j a  v  a2  s  . c om*/
    RProject rProject = null;

    try {

        /*
         * Determine DeployR server endpoint.
         */
        String endpoint = System.getProperty("endpoint");
        log.info("[ CONFIGURATION  ] Using endpoint=" + endpoint);

        /*
         * Establish RClient connection to DeployR server.
         *
         * An RClient connection is the mandatory starting
         * point for any application using the client library.
         */
        rClient = RClientFactory.createClient(endpoint);

        log.info("[   CONNECTION   ] Established anonymous " + "connection [ RClient ].");

        /*
         * Build a basic authentication token.
         */
        RAuthentication rAuth = new RBasicAuthentication(System.getProperty("username"),
                System.getProperty("password"));

        /*
         * Establish an authenticated handle with the DeployR
         * server, rUser. Following this call the rClient 
         * connection is operating as an authenticated connection
         * and all calls on rClient inherit the access permissions
         * of the authenticated user, rUser.
         */
        RUser rUser = rClient.login(rAuth);
        log.info("[ AUTHENTICATION ] Upgraded to authenticated " + "connection [ RUser ].");

        /*
         * Create a temporary project (R session).
         *
         * Optionally:
         * ProjectCreationOptions options =
         * new ProjectCreationOptions();
         *
         * Populate options as needed, then:
         *
         * rProject = rUser.createProject(options);
         */
        rProject = rUser.createProject();

        log.info("[  GO STATEFUL   ] Created stateful temporary " + "R session [ RProject ].");

        /*
         * Create a ProjectExecutionOptions instance
         * to specify data inputs and output to the
         * execution of the repository-managed R script.
         *
         * This options object can be used to pass standard
         * execution model parameters on execution calls. All
         * fields are optional.
         *
         * See the Standard Execution Model chapter in the
         * Client Library Tutorial on the DeployR website for
         * further details.
         */
        ProjectExecutionOptions options = new ProjectExecutionOptions();

        /* 
         * Simulate application generated data. This data
         * is first encoded using the RDataFactory before
         * being passed as an input on the execution.
         *
         * This encoded R input is automatically converted
         * into a workspace object before script execution.
         */
        RData generatedData = simulateGeneratedData();
        if (generatedData != null) {
            List<RData> rinputs = Arrays.asList(generatedData);
            options.rinputs = rinputs;
        }

        log.info("[   DATA INPUT   ] DeployR-encoded R input set on execution, "
                + "[ ProjectExecutionOptions.rinputs ].");

        /*
         * Execute a public analytics Web service as an authenticated
         * user based on a repository-managed R script:
         * /testuser/example-data-io/dataIO.R
         */
        RProjectExecution exec = rProject.executeScript("dataIO.R", "example-data-io", "testuser", null,
                options);

        log.info("[   EXECUTION    ] Stateful R script " + "execution completed [ RProjectExecution ].");

        /*
         * Retrieve the working directory file (artifact) called
         * hip.rData that was generated by the execution.
         *
         * Outputs generated by an execution can be used in any
         * number of ways by client applications, including:
         *
         * 1. Use output data to perform further calculations.
         * 2. Display output data to an end-user.
         * 3. Write output data to a database.
         * 4. Pass output data along to another Web service.
         * 5. etc.
         */
        List<RProjectFile> wdFiles = exec.about().artifacts;

        for (RProjectFile wdFile : wdFiles) {
            if (wdFile.about().filename.equals("hip.rData")) {
                log.info("[  DATA OUTPUT   ] Retrieved working directory " + "file output "
                        + wdFile.about().filename + " [ RProjectFile ].");
                InputStream fis = null;
                try {
                    fis = wdFile.download();
                } catch (Exception ex) {
                    log.warn("Working directory binary file download " + ex);
                } finally {
                    IOUtils.closeQuietly(fis);
                }
            }
        }

    } catch (Exception ex) {
        log.warn("Unexpected runtime exception=" + ex);
    } finally {
        try {
            if (rProject != null) {
                /*
                 * Close rProject before application exits.
                 */
                rProject.close();
            }
        } catch (Exception fex) {
        }
        try {
            if (rClient != null) {
                /*
                 * Release rClient connection before application exits.
                 */
                rClient.release();
            }
        } catch (Exception fex) {
        }
    }

}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.standalone.ArchiveCopyStandalone.java

/**
 * Copy archives to the public location, making the necessary database and filesystem changes.
 * <p/>/*ww  w . jav a 2  s .  co  m*/
 * Right now the only archive type that is supported is "bcr", meaning here all available protected 'bio' archives.
 *
 * @param args the archive type to copy to the public location
 */
public static void main(final String[] args) {

    if (args.length == 0 || !hasValidArgs(args)) {

        System.out.println(USAGE);
        System.exit(-1);

    } else {
        final long startTime = System.currentTimeMillis();
        final ApplicationContext appContext = new ClassPathXmlApplicationContext(APP_CONTEXT_FILE_NAME);
        final ArchiveCopyStandalone archiveCopyStandalone = (ArchiveCopyStandalone) appContext
                .getBean("archiveCopyStandalone");
        archiveCopyStandalone.getLogger()
                .addDestination(new Log4JLoggerDestination(archiveCopyStandalone.getClass().toString()));

        try {
            final List<String> argList = Arrays.asList(args);
            long noOfFilesCopied = 0;
            if (argList.contains(DRY_RUN_ARG)) {

                archiveCopyStandalone.getLogger().log(Level.INFO,
                        "This is a DRY RUN, no actual file system and Database change will be made.");
                archiveCopyStandalone.setDryRun(true);
            }

            if (argList.contains(BCR_ARG)) {
                noOfFilesCopied = archiveCopyStandalone.copyBCRArchivesFromProtectedToPublic();
            }

            if (argList.contains(MAF_ARG)) {
                noOfFilesCopied = archiveCopyStandalone.copyMafArchivesFromProtectedToPublic();
            }
            archiveCopyStandalone.getLogger().log(Level.INFO,
                    "Total archives copied : " + noOfFilesCopied + ". Total execution time: "
                            + ((System.currentTimeMillis() - startTime) / 1000) + " secs.");
        } catch (Exception e) {
            archiveCopyStandalone.getLogger().log(Level.ERROR, e.getMessage());
            e.printStackTrace();
        }
    }
}

From source file:com.linkedin.pinot.integration.tests.HybridClusterIntegrationTestCommandLineRunner.java

public static void main(String[] args) throws Exception {
    int numArgs = args.length;
    if (!((numArgs == 5) || (numArgs == 6 && args[0].equals("--llc")))) {
        printUsage();//from  ww w.ja v  a2s  .com
    }

    CustomHybridClusterIntegrationTest._enabled = true;

    int argIdx = 0;
    if (args[0].equals("--llc")) {
        CustomHybridClusterIntegrationTest._useLlc = true;
        argIdx++;
    }

    CustomHybridClusterIntegrationTest._tableName = args[argIdx++];
    File schemaFile = new File(args[argIdx++]);
    Preconditions.checkState(schemaFile.isFile());
    CustomHybridClusterIntegrationTest._schemaFile = schemaFile;
    File dataDir = new File(args[argIdx++]);
    Preconditions.checkState(dataDir.isDirectory());
    CustomHybridClusterIntegrationTest._dataDir = dataDir;
    CustomHybridClusterIntegrationTest._invertedIndexColumns = Arrays.asList(args[argIdx++].split(","));
    CustomHybridClusterIntegrationTest._sortedColumn = args[argIdx];

    TestListenerAdapter testListenerAdapter = new TestListenerAdapter();
    TestNG testNG = new TestNG();
    testNG.setTestClasses(new Class[] { CustomHybridClusterIntegrationTest.class });
    testNG.addListener(testListenerAdapter);
    testNG.run();

    System.out.println(testListenerAdapter.toString());
    boolean success = true;
    List<ITestResult> skippedTests = testListenerAdapter.getSkippedTests();
    if (!skippedTests.isEmpty()) {
        System.out.println("Skipped tests: " + skippedTests);
        for (ITestResult skippedTest : skippedTests) {
            System.out.println(skippedTest.getName() + ": " + skippedTest.getThrowable());
        }
        success = false;
    }
    List<ITestResult> failedTests = testListenerAdapter.getFailedTests();
    if (!failedTests.isEmpty()) {
        System.err.println("Failed tests: " + failedTests);
        for (ITestResult failedTest : failedTests) {
            System.out.println(failedTest.getName() + ": " + failedTest.getThrowable());
        }
        success = false;
    }
    if (success) {
        System.exit(0);
    } else {
        System.exit(1);
    }
}

From source file:com.gordcorp.jira2db.App.java

public static void main(String[] args) throws Exception {
    File log4jFile = new File("log4j.xml");
    if (log4jFile.exists()) {
        DOMConfigurator.configure("log4j.xml");
    }//ww  w  . j av  a 2  s . c o  m

    Option help = new Option("h", "help", false, "print this message");

    @SuppressWarnings("static-access")
    Option project = OptionBuilder.withLongOpt("project").withDescription("Only sync Jira project PROJECT")
            .hasArg().withArgName("PROJECT").create();

    @SuppressWarnings("static-access")
    Option property = OptionBuilder.withArgName("property=value").hasArgs(2).withValueSeparator()
            .withDescription("use value for given property").create("D");

    @SuppressWarnings("static-access")
    Option testJira = OptionBuilder.withLongOpt("test-jira")
            .withDescription("Test the connection to Jira and print the results").create();

    @SuppressWarnings("static-access")
    Option forever = OptionBuilder.withLongOpt("forever")
            .withDescription("Will continue polling Jira and syncing forever").create();

    Options options = new Options();
    options.addOption(help);
    options.addOption(project);
    options.addOption(property);
    options.addOption(testJira);
    options.addOption(forever);

    CommandLineParser parser = new GnuParser();
    try {

        CommandLine line = parser.parse(options, args);

        if (line.hasOption(help.getOpt())) {
            printHelp(options);
            return;
        }

        // Overwrite the properties file with command line arguments
        if (line.hasOption("D")) {
            String[] values = line.getOptionValues("D");
            for (int i = 0; i < values.length; i = i + 2) {
                String key = values[i];
                // If user does not provide a value for this property, use
                // an empty string
                String value = "";
                if (i + 1 < values.length) {
                    value = values[i + 1];
                }

                log.info("Setting key=" + key + " value=" + value);
                PropertiesWrapper.set(key, value);
            }

        }

        if (line.hasOption("test-jira")) {
            testJira();
        } else {
            JiraSynchroniser jira = new JiraSynchroniser();

            if (line.hasOption("project")) {

                jira.setProjects(Arrays.asList(new String[] { line.getOptionValue("project") }));
            }

            if (line.hasOption("forever")) {
                jira.syncForever();
            } else {
                jira.syncAll();
            }
        }
    } catch (ParseException exp) {

        log.error("Parsing failed: " + exp.getMessage());
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}

From source file:com.datastax.dse.demos.solr.Wikipedia.java

public static void main(String[] args) {

    if (args.length == 0)
        usage();//from   w ww. j  av a 2  s  .co  m

    System.out.println("args: " + Arrays.asList(args));

    // parse args
    for (int i = 0; i < args.length; i = i + 2) {

        if (args[i].startsWith("--")) {
            try {
                String arg = args[i].substring(2);
                String value = args[i + 1];

                if (arg.equalsIgnoreCase("wikifile"))
                    wikifile = value;
                if (arg.equalsIgnoreCase("limit"))
                    limit = Integer.parseInt(value);
                if (arg.equalsIgnoreCase("host"))
                    host = value;
                if (arg.equalsIgnoreCase("scheme"))
                    scheme = value;
                if (arg.equalsIgnoreCase("user"))
                    user = value;
                if (arg.equalsIgnoreCase("password"))
                    password = value;
            } catch (Throwable t) {
                usage();
            }
        }
    }
    url = String.format(urlTemplate, scheme, host);
    // Initialize Solr with our custom HTTP Client helpers - which handle
    // SSL & Kerberos. We must have dse.yaml on the classpath for this
    try {
        if (DseConfig.isSslEnabled()) {
            SolrHttpClientInitializer
                    .initEncryption(new EncryptionOptions().withSSLContext(DseConfig.getSSLContext())
                            .withHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER));
        }

        if (DseConfig.isKerberosEnabled()) {
            // Obtain kerberos credentials from local ticket cache
            AuthenticationOptions options = new AuthenticationOptions();
            if (DseConfig.isSslEnabled()) {
                options.withSSLContext(DseConfig.getSSLContext())
                        .withHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            }

            SolrHttpClientInitializer.initAuthentication(options);
        }
    } catch (Exception e) {
        System.out.println("Fatal error when initializing Solr clients, exiting");
        e.printStackTrace();
        System.exit(1);
    }

    System.out.println("Start indexing wikipedia...");
    long startTime = System.currentTimeMillis();

    indexWikipedia();

    long endTime = System.currentTimeMillis();

    System.out.println("Finished");

    System.exit(0);

}

From source file:com.revo.deployr.client.example.data.io.auth.stateful.exec.ExternalDataInDataFileOut.java

public static void main(String args[]) throws Exception {

    RClient rClient = null;//from  www  .  j a v a2 s.  com
    RProject rProject = null;

    try {

        /*
         * Determine DeployR server endpoint.
         */
        String endpoint = System.getProperty("endpoint");
        log.info("[ CONFIGURATION  ] Using endpoint=" + endpoint);

        /*
         * Establish RClient connection to DeployR server.
         *
         * An RClient connection is the mandatory starting
         * point for any application using the client library.
         */
        rClient = RClientFactory.createClient(endpoint);

        log.info("[   CONNECTION   ] Established anonymous " + "connection [ RClient ].");

        /*
         * Build a basic authentication token.
         */
        RAuthentication rAuth = new RBasicAuthentication(System.getProperty("username"),
                System.getProperty("password"));

        /*
         * Establish an authenticated handle with the DeployR
         * server, rUser. Following this call the rClient 
         * connection is operating as an authenticated connection
         * and all calls on rClient inherit the access permissions
         * of the authenticated user, rUser.
         */
        RUser rUser = rClient.login(rAuth);
        log.info("[ AUTHENTICATION ] Upgraded to authenticated " + "connection [ RUser ].");

        /*
         * Create a temporary project (R session).
         *
         * Optionally:
         * ProjectCreationOptions options =
         * new ProjectCreationOptions();
         *
         * Populate options as needed, then:
         *
         * rProject = rUser.createProject(options);
         */
        rProject = rUser.createProject();

        log.info("[  GO STATEFUL   ] Created stateful temporary " + "R session [ RProject ].");

        /*
         * Create a ProjectExecutionOptions instance
         * to specify data inputs and output to the
         * execution of the repository-managed R script.
         *
         * This options object can be used to pass standard
         * execution model parameters on execution calls. All
         * fields are optional.
         *
         * See the Standard Execution Model chapter in the
         * Client Library Tutorial on the DeployR website for
         * further details.
         */
        ProjectExecutionOptions options = new ProjectExecutionOptions();

        /* 
         * Load an R object literal "hipStarUrl" into the
         * workspace prior to script execution.
         *
         * The R script checks for the existence of "hipStarUrl"
         * in the workspace and if present uses the URL path
         * to load the Hipparcos star dataset from the DAT file
         * at that location.
         */
        RData hipStarUrl = RDataFactory.createString("hipStarUrl", HIP_DAT_URL);
        List<RData> rinputs = Arrays.asList(hipStarUrl);
        options.rinputs = rinputs;

        log.info("[   DATA INPUT   ] External data source input "
                + "set on execution, [ ProjectExecutionOptions.rinputs ].");

        /*
         * Execute a public analytics Web service as an authenticated
         * user based on a repository-managed R script:
         * /testuser/example-data-io/dataIO.R
         */
        RProjectExecution exec = rProject.executeScript("dataIO.R", "example-data-io", "testuser", null,
                options);

        log.info("[   EXECUTION    ] Stateful R script " + "execution completed [ RProjectExecution ].");

        /*
         * Retrieve the working directory file (artifact) called
         * hip.csv that was generated by the execution.
         *
         * Outputs generated by an execution can be used in any
         * number of ways by client applications, including:
         *
         * 1. Use output data to perform further calculations.
         * 2. Display output data to an end-user.
         * 3. Write output data to a database.
         * 4. Pass output data along to another Web service.
         * 5. etc.
         */
        List<RProjectFile> wdFiles = exec.about().artifacts;

        for (RProjectFile wdFile : wdFiles) {
            if (wdFile.about().filename.equals("hip.csv")) {
                log.info("[  DATA OUTPUT   ] Retrieved working directory " + "file output "
                        + wdFile.about().filename + " [ RProjectFile ].");
                InputStream fis = null;
                try {
                    fis = wdFile.download();
                } catch (Exception ex) {
                    log.warn("Working directory data file download " + ex);
                } finally {
                    IOUtils.closeQuietly(fis);
                }
            }
        }

    } catch (Exception ex) {
        log.warn("Unexpected runtime exception=" + ex);
    } finally {
        try {
            if (rProject != null) {
                /*
                 * Close rProject before application exits.
                 */
                rProject.close();
            }
        } catch (Exception fex) {
        }
        try {
            if (rClient != null) {
                /*
                 * Release rClient connection before application exits.
                 */
                rClient.release();
            }
        } catch (Exception fex) {
        }
    }

}

From source file:SparkStreaming.java

public static void main(String[] args) throws Exception {
    JSONObject jo = new JSONObject();
    SparkConf sparkConf = new SparkConf().setAppName("mytestapp").setMaster("local[2]");
    JavaStreamingContext jssc = new JavaStreamingContext(sparkConf, new Duration(2000));

    int numThreads = Integer.parseInt("2");
    Map<String, Integer> topicMap = new HashMap<>();
    String[] topics = "testdemo".split(",");
    for (String topic : topics) {
        topicMap.put(topic, numThreads);
    }/*  ww  w. j  av a 2s  . c o m*/

    JavaPairReceiverInputDStream<String, String> messages = KafkaUtils.createStream(jssc, "localhost:2181",
            "testdemo", topicMap);

    JavaDStream<String> lines = messages.map(new Function<Tuple2<String, String>, String>() {
        @Override
        public String call(Tuple2<String, String> tuple2) {
            return tuple2._2();
        }
    });

    JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
        @Override
        public Iterable<String> call(String x) throws IOException {
            String temperature = x.substring(x.indexOf(":") + 1);
            /*  System.out.println("Temperature from spark++++++++++ "+temperature);
              URL url = new URL("http://localhost:8080/apachetest/Test?var1="+temperature);
              URLConnection conn = url.openConnection();
               conn.setDoOutput(true);*/
            final ThermometerDemo2 demo = new ThermometerDemo2("Thermometer Demo 2", temperature);
            demo.pack();
            demo.setVisible(true);
            return Arrays.asList(x.split(" "));
        }
    });

    JavaPairDStream<String, Integer> wordCounts = words.mapToPair(new PairFunction<String, String, Integer>() {
        @Override
        public Tuple2<String, Integer> call(String s) {
            return new Tuple2<>(s, 1);
        }
    }).reduceByKey(new Function2<Integer, Integer, Integer>() {
        @Override
        public Integer call(Integer i1, Integer i2) {
            return i1 + i2;
        }
    });

    wordCounts.print();
    jssc.start();
    jssc.awaitTermination();
}

From source file:NaturalOrderComparator.java

public static void main(String[] args) {
    String[] strings = new String[] { "1-2", "1-02", "1-20", "10-20", "fred", "jane", "pic01", "pic2", "pic02",
            "pic02a", "pic3", "pic4", "pic 4 else", "pic 5", "pic05", "pic 5", "pic 5 something", "pic 6",
            "pic   7", "pic100", "pic100a", "pic120", "pic121", "pic02000", "tom", "x2-g8", "x2-y7", "x2-y08",
            "x8-y8" };

    List orig = Arrays.asList(strings);

    System.out.println("Original: " + orig);

    List scrambled = Arrays.asList(strings);
    Collections.shuffle(scrambled);

    System.out.println("Scrambled: " + scrambled);

    Collections.sort(scrambled, new NaturalOrderComparator());

    System.out.println("Sorted: " + scrambled);
}

From source file:com.github.vatbub.awsvpnlauncher.Main.java

public static void main(String[] args) {
    Common.getInstance().setAppName("awsVpnLauncher");
    FOKLogger.enableLoggingOfUncaughtExceptions();
    prefs = new Preferences(Main.class.getName());

    // enable the shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        if (session != null) {
            if (session.isConnected()) {
                session.disconnect();/* w w  w . j a  v a  2  s.co  m*/
            }
        }
    }));

    UpdateChecker.completeUpdate(args, (oldVersion, oldFile) -> {
        if (oldVersion != null) {
            FOKLogger.info(Main.class.getName(), "Successfully upgraded " + Common.getInstance().getAppName()
                    + " from v" + oldVersion.toString() + " to v" + Common.getInstance().getAppVersion());
        }
    });
    List<String> argsAsList = new ArrayList<>(Arrays.asList(args));

    for (String arg : args) {
        if (arg.toLowerCase().matches("mockappversion=.*")) {
            // Set the mock version
            String version = arg.substring(arg.toLowerCase().indexOf('=') + 1);
            Common.getInstance().setMockAppVersion(version);
            argsAsList.remove(arg);
        } else if (arg.toLowerCase().matches("mockbuildnumber=.*")) {
            // Set the mock build number
            String buildnumber = arg.substring(arg.toLowerCase().indexOf('=') + 1);
            Common.getInstance().setMockBuildNumber(buildnumber);
            argsAsList.remove(arg);
        } else if (arg.toLowerCase().matches("mockpackaging=.*")) {
            // Set the mock packaging
            String packaging = arg.substring(arg.toLowerCase().indexOf('=') + 1);
            Common.getInstance().setMockPackaging(packaging);
            argsAsList.remove(arg);
        }
    }

    args = argsAsList.toArray(new String[0]);

    try {
        mvnRepoConfig = new Config(
                new URL("https://www.dropbox.com/s/vnhs4nax2lczccf/mavenRepoConfig.properties?dl=1"),
                Main.class.getResource("mvnRepoFallbackConfig.properties"), true, "mvnRepoCachedConfig", true);
        projectConfig = new Config(
                new URL("https://www.dropbox.com/s/d36hwrrufoxfmm7/projectConfig.properties?dl=1"),
                Main.class.getResource("projectFallbackConfig.properties"), true, "projectCachedConfig", true);
    } catch (IOException e) {
        FOKLogger.log(Main.class.getName(), Level.SEVERE, "Could not load the remote config", e);
    }

    try {
        installUpdates(args);
    } catch (Exception e) {
        FOKLogger.log(Main.class.getName(), Level.SEVERE, "Could not install updates", e);
    }

    if (args.length == 0) {
        // not enough arguments
        printHelpMessage();
        throw new NotEnoughArgumentsException();
    }

    switch (args[0].toLowerCase()) {
    case "setup":
        setup();
        break;
    case "launch":
        initAWSConnection();
        launch();
        break;
    case "terminate":
        initAWSConnection();
        terminate();
        break;
    case "config":
        // require a second arg
        if (args.length == 2) {
            // not enough arguments
            printHelpMessage();
            throw new NotEnoughArgumentsException();
        }

        config(Property.valueOf(args[1]), args[2]);
        break;
    case "getconfig":
        // require a second arg
        if (args.length == 1) {
            // not enough arguments
            printHelpMessage();
            throw new NotEnoughArgumentsException();
        }

        getConfig(Property.valueOf(args[1]));
        break;
    case "printconfig":
        printConfig();
        break;
    case "deleteconfig":
        // require a second arg
        if (args.length == 1) {
            // not enough arguments
            printHelpMessage();
            throw new NotEnoughArgumentsException();
        }

        deleteConfig(Property.valueOf(args[1]));
        break;
    case "ssh":
        String sshInstanceId;
        if (args.length == 2) {
            // a instanceID is specified
            sshInstanceId = args[1];
        } else {
            String instanceIdsPrefValue = prefs.getPreference("instanceIDs", "");
            if (instanceIdsPrefValue.equals("")) {
                throw new NotEnoughArgumentsException(
                        "No instanceId was specified to connect to and no instanceId was saved in the preference file. Please either start another instance using the launch command or specify the instance id of the instance to connect to as a additional parameter.");
            }

            List<String> instanceIds = Arrays.asList(instanceIdsPrefValue.split(";"));
            if (instanceIds.size() == 1) {
                // exactly one instance found
                sshInstanceId = instanceIds.get(0);
            } else {
                FOKLogger.severe(Main.class.getName(), "Multiple instance ids found:");

                for (String instanceId : instanceIds) {
                    FOKLogger.severe(Main.class.getName(), instanceId);
                }
                throw new NotEnoughArgumentsException(
                        "Multiple instance ids were found in the preference file. Please specify the instance id of the instance to connect to as a additional parameter.");
            }
        }

        initAWSConnection();
        ssh(sshInstanceId);
        break;
    default:
        printHelpMessage();
    }
}

From source file:edu.cwru.jpdg.JPDG.java

public static void main(String[] argv) throws pDG_Builder.Error {
    final Option helpOpt = new Option("h", "help", false, "print this message");
    final Option outputOpt = new Option("o", "output", true, "output file location");
    final Option baseOpt = new Option("b", "base-dir", true, "base directory to analyze");
    final Option excludeOpt = new Option("e", "exclude", true, "exclude these directories");
    final Option classOpt = new Option("c", "classpath", true, "classpath for soot");
    final Option labelOpt = new Option("l", "label-type", true,
            "label type, valid choices are: expr-tree, inst");
    final org.apache.commons.cli.Options options = new org.apache.commons.cli.Options();

    options.addOption(helpOpt);/*from w  ww . j av a  2  s. com*/
    options.addOption(outputOpt);
    options.addOption(baseOpt);
    options.addOption(classOpt);
    options.addOption(labelOpt);
    options.addOption(excludeOpt);

    String cp = null;
    String base_dir = null;
    String label_type = "expr-tree";
    String output_file = null;
    List<String> excluded = new ArrayList<String>();

    try {
        GnuParser parser = new GnuParser();
        CommandLine line = parser.parse(options, argv);

        if (line.hasOption(helpOpt.getLongOpt())) {
            Usage(options);
        }

        cp = line.getOptionValue(classOpt.getLongOpt());
        base_dir = line.getOptionValue(baseOpt.getLongOpt());
        label_type = line.getOptionValue(labelOpt.getLongOpt());
        output_file = line.getOptionValue(outputOpt.getLongOpt());
        String[] ex = line.getOptionValues(excludeOpt.getLongOpt());
        if (ex != null) {
            excluded = Arrays.asList(ex);
        }
    } catch (final MissingOptionException e) {
        System.err.println(e.getMessage());
        Usage(options);
    } catch (final UnrecognizedOptionException e) {
        System.err.println(e.getMessage());
        Usage(options);
    } catch (final ParseException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }

    List<String> dirs = new ArrayList<String>();
    dirs.add(base_dir);

    soot.Scene S = runSoot(cp, dirs, excluded);
    writeGraph(build_PDG(S, excluded, label_type), output_file);
}