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:dk.alexandra.fresco.framework.configuration.ConfigurationGenerator.java

public static void main(String args[]) {
    if (args.length == 0) {
        usage();//from w  w w  .j a  va 2 s  .c om
    }

    if (args.length % 2 != 0) {
        System.out.println("Incorrect number of arguments: " + Arrays.asList(args) + ".");
        System.out.println();
        usage();
    }

    List<Pair<String, Integer>> hosts = new LinkedList<Pair<String, Integer>>();
    int inx = 0;
    try {

        for (; inx < args.length; inx = inx + 2) {
            hosts.add(new Pair<String, Integer>(args[inx], new Integer(args[inx + 1])));
        }
    } catch (NumberFormatException ex) {
        System.out.println("Invalid argument for port: \"" + args[inx + 1] + "\".");
        System.exit(1);
    }

    inx = 1;
    try {
        for (; inx < hosts.size() + 1; inx++) {
            String filename = "party-" + inx + ".ini";
            OutputStream out = new FileOutputStream(filename);
            new ConfigurationGenerator().generate(inx, out, hosts);
            out.close();
            System.out.println("Created configuration file: " + filename + ".");
        }
    } catch (Exception ex) {
        System.out.println("Could not write to file: party-" + inx + ".ini.");
        System.exit(1);
    }

}

From source file:com.commonsware.android.gcm.cmd.GCM.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    Option helpOpt = new Option("h", "help", false, "print this message");
    Option apiKeyOpt = OptionBuilder.withArgName("key").hasArg().isRequired().withDescription("GCM API key")
            .withLongOpt("apiKey").create('a');
    Option deviceOpt = OptionBuilder.withArgName("regId").hasArg().isRequired()
            .withDescription("device to send to").withLongOpt("device").create('d');
    Option dataOpt = OptionBuilder.withArgName("key=value").hasArgs(2).withDescription("datum to send")
            .withValueSeparator().withLongOpt("data").create('D');

    Options options = new Options();

    options.addOption(apiKeyOpt);//from  w w w . ja v  a  2s.  c  o  m
    options.addOption(deviceOpt);
    options.addOption(dataOpt);
    options.addOption(helpOpt);

    CommandLineParser parser = new PosixParser();

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

        if (line.hasOption('h') || !line.hasOption('a') || !line.hasOption('d')) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("gcm", options, true);
        } else {
            sendMessage(line.getOptionValue('a'), Arrays.asList(line.getOptionValues('d')),
                    line.getOptionProperties("data"));
        }
    } catch (org.apache.commons.cli.MissingOptionException moe) {
        System.err.println("Invalid command syntax");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("gcm", options, true);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.servioticy.dispatcher.DispatcherTopology.java

/**
 * @param args//  ww w. j a v a  2 s.  c o m
 * @throws InvalidTopologyException
 * @throws AlreadyAliveException
 * @throws InterruptedException
 */
public static void main(String[] args)
        throws AlreadyAliveException, InvalidTopologyException, InterruptedException, ParseException {

    Options options = new Options();

    options.addOption(
            OptionBuilder.withArgName("file").hasArg().withDescription("Config file path.").create("f"));
    options.addOption(OptionBuilder.withArgName("topology").hasArg()
            .withDescription("Name of the topology in storm. If no name is given it will run in local mode.")
            .create("t"));
    options.addOption(OptionBuilder.withDescription("Enable debugging").create("d"));

    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);

    String path = null;
    if (cmd.hasOption("f")) {
        path = cmd.getOptionValue("f");
    }

    DispatcherContext dc = new DispatcherContext();
    dc.loadConf(path);

    TopologyBuilder builder = new TopologyBuilder();

    // TODO Auto-assign workers to the spout in function of the number of Kestrel IPs
    builder.setSpout("updates", new KestrelThriftSpout(Arrays.asList(dc.updatesAddresses), dc.updatesPort,
            dc.updatesQueue, new UpdateDescriptorScheme()));
    builder.setSpout("actions", new KestrelThriftSpout(Arrays.asList(dc.actionsAddresses), dc.actionsPort,
            dc.actionsQueue, new ActuationScheme()));

    builder.setBolt("prepare", new PrepareBolt(dc)).shuffleGrouping("updates");

    builder.setBolt("actuationdispatcher", new ActuationDispatcherBolt(dc)).shuffleGrouping("actions");

    builder.setBolt("subretriever", new SubscriptionRetrieveBolt(dc)).shuffleGrouping("prepare",
            "subscription");

    builder.setBolt("externaldispatcher", new ExternalDispatcherBolt(dc)).fieldsGrouping("subretriever",
            "externalSub", new Fields("subid"));
    builder.setBolt("internaldispatcher", new InternalDispatcherBolt(dc)).fieldsGrouping("subretriever",
            "internalSub", new Fields("subid"));

    builder.setBolt("streamdispatcher", new StreamDispatcherBolt(dc))
            .shuffleGrouping("subretriever", "streamSub").shuffleGrouping("prepare", "stream");
    builder.setBolt("streamprocessor", new StreamProcessorBolt(dc)).shuffleGrouping("streamdispatcher",
            "default");

    if (dc.benchmark) {
        builder.setBolt("benchmark", new BenchmarkBolt(dc)).shuffleGrouping("streamdispatcher", "benchmark")
                .shuffleGrouping("subretriever", "benchmark").shuffleGrouping("streamprocessor", "benchmark")
                .shuffleGrouping("prepare", "benchmark");
    }

    Config conf = new Config();
    conf.setDebug(cmd.hasOption("d"));
    if (cmd.hasOption("t")) {
        StormSubmitter.submitTopology(cmd.getOptionValue("t"), conf, builder.createTopology());
    } else {
        conf.setMaxTaskParallelism(4);
        LocalCluster cluster = new LocalCluster();
        cluster.submitTopology("dispatcher", conf, builder.createTopology());

    }

}

From source file:de.dakror.jagui.parser.NGuiParser.java

public static void main(String[] args) {
    try {//from   w  w  w .ja v a  2  s  .c om
        DIR.mkdirs();
        if (!new File(DIR, "convert.exe").exists())
            Helper.copyInputStream(NGuiParser.class.getResourceAsStream("/res/convert.exe"),
                    new FileOutputStream(new File(DIR, "convert.exe")));

        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

        JFileChooser jfc = new JFileChooser(
                new File(NGuiParser.class.getProtectionDomain().getCodeSource().getLocation().toURI()));
        jfc.setMultiSelectionEnabled(false);
        jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jfc.setFileFilter(new FileNameExtensionFilter("Unity ngui Gui-Skin (*.guiskin)", "guiskin"));

        if (jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            p("Collecting GUIDs, Converting Resources");
            HashMap<String, File> guids = collectGUIDs(jfc.getCurrentDirectory());

            p("Parsing Guiskin file");
            String s = Helper.getFileContent(jfc.getSelectedFile());
            String[] lines = s.split("\n");
            ArrayList<String> l = new ArrayList<>(Arrays.asList(lines));
            String string = "";
            for (int i = 0; i < l.size(); i++)
                if (!l.get(i).startsWith("%") && !l.get(i).startsWith("---"))
                    string += l.get(i) + "\n";

            Yaml yaml = new Yaml();
            for (Iterator<Object> iter = yaml.loadAll(string).iterator(); iter.hasNext();) {
                JSONObject o = new JSONObject((Map<?, ?>) iter.next());
                p("Cconverting Guiskin");
                replaceGuidDeep(o, guids, jfc.getSelectedFile());
                p("Writing converted file");
                Helper.setFileContent(new File(jfc.getSelectedFile().getParentFile(),
                        jfc.getSelectedFile().getName() + ".json"), o.toString(4));
                p("DONE");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.adobe.aem.demomachine.Updates.java

public static void main(String[] args) {

    String rootFolder = null;/* w  w w. ja v  a 2 s  . c o  m*/

    // Command line options for this tool
    Options options = new Options();
    options.addOption("f", true, "Demo Machine root folder");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("f")) {
            rootFolder = cmd.getOptionValue("f");
        }

    } catch (Exception e) {
        System.exit(-1);
    }

    Properties md5properties = new Properties();

    try {
        URL url = new URL(
                "https://raw.githubusercontent.com/Adobe-Marketing-Cloud/aem-demo-machine/master/conf/checksums.properties");
        InputStream in = url.openStream();
        Reader reader = new InputStreamReader(in, "UTF-8");
        md5properties.load(reader);
        reader.close();
    } catch (Exception e) {
        System.out.println("Error: Cannot connect to GitHub.com to check for updates");
        System.exit(-1);
    }

    System.out.println(AemDemoConstants.HR);

    int nbUpdateAvailable = 0;

    List<String[]> listPaths = Arrays.asList(AemDemoConstants.demoPaths);
    for (String[] path : listPaths) {
        if (path.length == 5) {
            logger.debug(path[1]);
            File pathFolder = new File(rootFolder + (path[1].length() > 0 ? (File.separator + path[1]) : ""));
            if (pathFolder.exists()) {
                String newMd5 = AemDemoUtils.calcMD5HashForDir(pathFolder, Boolean.parseBoolean(path[3]),
                        false);
                logger.debug("MD5 is: " + newMd5);
                String oldMd5 = md5properties.getProperty("demo.md5." + path[0]);
                if (oldMd5 == null || oldMd5.length() == 0) {
                    logger.error("Cannot find MD5 for " + path[0]);
                    System.out.println(path[2] + " : Cannot find M5 checksum");
                    continue;
                }
                if (newMd5.equals(oldMd5)) {
                    continue;
                } else {
                    System.out.println(path[2] + " : New update available"
                            + (path[0].equals("0") ? " (use 'git pull' to get the latest changes)" : ""));
                    nbUpdateAvailable++;
                }
            } else {
                System.out.println(path[2] + " : Not installed");
            }
        }
    }

    if (nbUpdateAvailable == 0) {
        System.out.println("Your AEM Demo Machine is up to date!");
    }

    System.out.println(AemDemoConstants.HR);

}

From source file:org.n52.iceland.statistics.api.utils.KibanaExporter.java

public static void main(String args[]) throws Exception {
    if (args.length != 2) {
        System.out.printf("Usage: java KibanaExporter.jar %s %s\n", "localhost:9300", "my-cluster-name");
        System.exit(0);/*from   ww w.  j a va 2  s .co m*/
    }
    if (!args[0].contains(":")) {
        throw new IllegalArgumentException(
                String.format("%s not a valid format. Expected <hostname>:<port>.", args[0]));
    }

    // set ES address
    String split[] = args[0].split(":");
    InetSocketTransportAddress address = new InetSocketTransportAddress(InetAddress.getByName(split[0]),
            Integer.parseInt(split[1], 10));

    // set cluster name
    Builder tcSettings = Settings.settingsBuilder();
    tcSettings.put("cluster.name", args[1]);
    System.out.println("Connection to " + args[1]);

    client = TransportClient.builder().settings(tcSettings).build();
    client.addTransportAddress(address);

    // search index pattern for needle
    searchIndexPattern();

    KibanaConfigHolderDto holder = new KibanaConfigHolderDto();
    System.out.println("Reading .kibana index");

    SearchResponse resp = client.prepareSearch(".kibana").setSize(1000).get();
    Arrays.asList(resp.getHits().getHits()).stream().map(KibanaExporter::parseSearchHit).forEach(holder::add);
    System.out.println("Reading finished");

    ObjectMapper mapper = new ObjectMapper();
    // we love pretty things
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    File f = new File("kibana_config.json");

    try (FileOutputStream out = new FileOutputStream(f, false)) {
        mapper.writeValue(out, holder);
    }

    System.out.println("File outputted to: " + f.getAbsolutePath());

    client.close();

}

From source file:com.cloud.utils.crypt.EncryptionSecretKeyChanger.java

public static void main(String[] args) {
    List<String> argsList = Arrays.asList(args);
    Iterator<String> iter = argsList.iterator();
    String oldMSKey = null;/*w  w w .  j a va 2 s .c om*/
    String oldDBKey = null;
    String newMSKey = null;
    String newDBKey = null;

    //Parse command-line args
    while (iter.hasNext()) {
        String arg = iter.next();
        // Old MS Key
        if (arg.equals("-m")) {
            oldMSKey = iter.next();
        }
        // Old DB Key
        if (arg.equals("-d")) {
            oldDBKey = iter.next();
        }
        // New MS Key
        if (arg.equals("-n")) {
            newMSKey = iter.next();
        }
        // New DB Key
        if (arg.equals("-e")) {
            newDBKey = iter.next();
        }
    }

    if (oldMSKey == null || oldDBKey == null) {
        System.out.println("Existing MS secret key or DB secret key is not provided");
        usage();
        return;
    }

    if (newMSKey == null && newDBKey == null) {
        System.out.println("New MS secret key and DB secret are both not provided");
        usage();
        return;
    }

    final File dbPropsFile = PropertiesUtil.findConfigFile("db.properties");
    final Properties dbProps;
    EncryptionSecretKeyChanger keyChanger = new EncryptionSecretKeyChanger();
    StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
    keyChanger.initEncryptor(encryptor, oldMSKey);
    dbProps = new EncryptableProperties(encryptor);
    PropertiesConfiguration backupDBProps = null;

    System.out.println("Parsing db.properties file");
    try {
        dbProps.load(new FileInputStream(dbPropsFile));
        backupDBProps = new PropertiesConfiguration(dbPropsFile);
    } catch (FileNotFoundException e) {
        System.out.println("db.properties file not found while reading DB secret key" + e.getMessage());
    } catch (IOException e) {
        System.out.println("Error while reading DB secret key from db.properties" + e.getMessage());
    } catch (ConfigurationException e) {
        e.printStackTrace();
    }

    String dbSecretKey = null;
    try {
        dbSecretKey = dbProps.getProperty("db.cloud.encrypt.secret");
    } catch (EncryptionOperationNotPossibleException e) {
        System.out.println("Failed to decrypt existing DB secret key from db.properties. " + e.getMessage());
        return;
    }

    if (!oldDBKey.equals(dbSecretKey)) {
        System.out.println("Incorrect MS Secret Key or DB Secret Key");
        return;
    }

    System.out.println("Secret key provided matched the key in db.properties");
    final String encryptionType = dbProps.getProperty("db.cloud.encryption.type");

    if (newMSKey == null) {
        System.out.println("No change in MS Key. Skipping migrating db.properties");
    } else {
        if (!keyChanger.migrateProperties(dbPropsFile, dbProps, newMSKey, newDBKey)) {
            System.out.println("Failed to update db.properties");
            return;
        } else {
            //db.properties updated successfully
            if (encryptionType.equals("file")) {
                //update key file with new MS key
                try {
                    FileWriter fwriter = new FileWriter(keyFile);
                    BufferedWriter bwriter = new BufferedWriter(fwriter);
                    bwriter.write(newMSKey);
                    bwriter.close();
                } catch (IOException e) {
                    System.out.println("Failed to write new secret to file. Please update the file manually");
                }
            }
        }
    }

    boolean success = false;
    if (newDBKey == null || newDBKey.equals(oldDBKey)) {
        System.out.println("No change in DB Secret Key. Skipping Data Migration");
    } else {
        EncryptionSecretKeyChecker.initEncryptorForMigration(oldMSKey);
        try {
            success = keyChanger.migrateData(oldDBKey, newDBKey);
        } catch (Exception e) {
            System.out.println("Error during data migration");
            e.printStackTrace();
            success = false;
        }
    }

    if (success) {
        System.out.println("Successfully updated secret key(s)");
    } else {
        System.out.println("Data Migration failed. Reverting db.properties");
        //revert db.properties
        try {
            backupDBProps.save();
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
        if (encryptionType.equals("file")) {
            //revert secret key in file
            try {
                FileWriter fwriter = new FileWriter(keyFile);
                BufferedWriter bwriter = new BufferedWriter(fwriter);
                bwriter.write(oldMSKey);
                bwriter.close();
            } catch (IOException e) {
                System.out.println("Failed to revert to old secret to file. Please update the file manually");
            }
        }
    }
}

From source file:controllers.oer.NtToEs.java

public static void main(String... args) throws ElasticsearchException, FileNotFoundException, IOException {
    if (args.length != 1 && args.length != 2) {
        System.out.println("Pass the root directory to crawl. "
                + "Will recursively gather all content from *.nt "
                + "files with identical names, convert these to " + "compact JSON-LD and index it in ES. "
                + "If a second argument is passed it is processed " + "as a TSV file that maps file names (w/o "
                + "extensions) to IDs to be used for ES. Else the " + "file names (w/o extensions) are used.");
        args = new String[] { "../oer-data/tmp", "../oer-data/src/main/resources/internalId2uuid.tsv" };
        System.out.println("Using defaults: " + Arrays.asList(args));
    }/*w  w  w  . j  a  v a  2  s. c o  m*/
    if (args.length == 2)
        initMap(args[1]);
    TripleCrawler crawler = new TripleCrawler();
    Files.walkFileTree(Paths.get(args[0]), crawler);
    createIndex(config(), INDEX);
    process(crawler.data);
}

From source file:com.dattack.dbping.cli.PingCli.java

/**
 * The <code>main</code> method.
 *
 * @param args/*from  w ww  .j av  a2s .  c o m*/
 *            the program arguments
 */
public static void main(final String[] args) {

    final Options options = createOptions();

    try {
        final CommandLineParser parser = new DefaultParser();
        final CommandLine cmd = parser.parse(options, args);
        final String[] filenames = cmd.getOptionValues(FILE_OPTION);
        final String[] taskNames = cmd.getOptionValues(TASK_NAME_OPTION);

        HashSet<String> hs = null;
        if (taskNames != null) {
            hs = new HashSet<>(Arrays.asList(taskNames));
        }

        final PingEngine ping = new PingEngine();
        ping.execute(filenames, hs);

    } catch (@SuppressWarnings("unused") final ParseException e) {
        showUsage(options);
    } catch (final ConfigurationException | DattackParserException e) {
        System.err.println(e.getMessage());
    }
}

From source file:org.schemaspy.Main.java

public static void main(String[] argv) throws Exception {
    Logger logger = Logger.getLogger(Main.class.getName());

    final AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(
            "org.schemaspy.service");
    applicationContext.register(SchemaAnalyzer.class);

    if (argv.length == 1 && "-gui".equals(argv[0])) { // warning: serious temp hack
        new MainFrame().setVisible(true);
        return;/*  ww  w  .  j a  v  a 2s.  c  o m*/
    }

    SchemaAnalyzer analyzer = applicationContext.getBean(SchemaAnalyzer.class);

    int rc = 1;

    try {
        rc = analyzer.analyze(new Config(argv)) == null ? 1 : 0;
    } catch (ConnectionFailure couldntConnect) {
        logger.log(Level.WARNING, "Connection Failure", couldntConnect);
        rc = 3;
    } catch (EmptySchemaException noData) {
        logger.log(Level.WARNING, "Empty schema", noData);
        rc = 2;
    } catch (InvalidConfigurationException badConfig) {
        logger.info("");
        if (badConfig.getParamName() != null)
            logger.log(Level.WARNING, "Bad parameter specified for " + badConfig.getParamName());
        logger.log(Level.WARNING, "Bad config " + badConfig.getMessage());
        if (badConfig.getCause() != null && !badConfig.getMessage().endsWith(badConfig.getMessage()))
            logger.log(Level.WARNING, " caused by " + badConfig.getCause().getMessage());

        logger.log(Level.FINE, "Command line parameters: " + Arrays.asList(argv));
        logger.log(Level.FINE, "Invalid configuration detected", badConfig);
    } catch (ProcessExecutionException badLaunch) {
        logger.log(Level.WARNING, badLaunch.getMessage(), badLaunch);
    } catch (Exception exc) {
        logger.log(Level.SEVERE, exc.getMessage(), exc);
    }

    System.exit(rc);
}