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.preload.EncodedDataInBinaryFileOut.java

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

    RClient rClient = null;/*from w  ww.  ja  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 ProjectCreationOptions instance
         * to specify data inputs that "pre-heat" the R session
         * workspace or working directory for your project.
         */
        ProjectCreationOptions options = new ProjectCreationOptions();

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

        log.info("[ PRELOAD INPUT  ] DeployR-encoded R input set on "
                + "project creation, [ ProjectCreationOptions.rinputs ].");

        /*
         * Create a temporary project (R session) passing a 
         * ProjectCreationOptions to "pre-heat" data into the
         * workspace and/or working directory.
         */
        rProject = rUser.createProject(options);

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

        /*
         * 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, null);

        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:edu.scripps.fl.pubchem.app.ResultDownloader.java

public static void main(String[] args) throws Exception {
    CommandLineHandler clh = new CommandLineHandler() {
        public void configureOptions(Options options) {
            options.addOption(OptionBuilder.withLongOpt("data_url").withType("").withValueSeparator('=')
                    .hasArg().create());
        }/*from w w w .ja  v a 2s.  co  m*/
    };
    args = clh.handle(args);
    String data_url = clh.getCommandLine().getOptionValue("data_url");
    ResultDownloader rd = new ResultDownloader();

    if (data_url != null)
        rd.setDataUrl(new URL(data_url));
    else
        rd.setDataUrl(new URL("ftp://ftp.ncbi.nlm.nih.gov/pubchem/Bioassay/CSV/"));
    if (args.length == 0)
        rd.process();
    else {
        Integer[] list = (Integer[]) ConvertUtils.convert(args, Integer[].class);
        rd.process(((List<Integer>) Arrays.asList(list)).iterator());
    }
}

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

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

    RClient rClient = null;//from   www  .j av a 2 s . c o m
    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 ProjectCreationOptions instance
         * to specify data inputs that "pre-heat" the R session
         * workspace or working directory for your project.
         */
        ProjectCreationOptions options = new ProjectCreationOptions();

        /* 
         * Load an R object literal "hipStarUrl" into the
         * workspace on project initialization.
         *
         * The R script execution that follows will check 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("[ PRELOAD INPUT  ] External data source input "
                + "set on project creation, [ ProjectCreationOptions.rinputs ].");

        /*
         * Create a temporary project (R session) passing a 
         * ProjectCreationOptions to "pre-heat" data into the
         * workspace and/or working directory.
         */
        rProject = rUser.createProject(options);

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

        /*
         * 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, null);

        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:edu.msu.cme.rdp.graph.sandbox.KmerStartsFromKnown.java

public static void main(String[] args) throws Exception {
    final KmerStartsWriter out;
    final boolean translQuery;
    final int wordSize;
    final int translTable;

    try {/*from  www  .  j  av  a 2  s. c o m*/
        CommandLine cmdLine = new PosixParser().parse(options, args);
        args = cmdLine.getArgs();

        if (args.length < 2) {
            throw new Exception("Unexpected number of arguments");
        }

        if (cmdLine.hasOption("out")) {
            out = new KmerStartsWriter(cmdLine.getOptionValue("out"));
        } else {
            out = new KmerStartsWriter(System.out);
        }

        if (cmdLine.hasOption("transl-table")) {
            translTable = Integer.valueOf(cmdLine.getOptionValue("transl-table"));
        } else {
            translTable = 11;
        }

        translQuery = cmdLine.hasOption("transl-kmer");
        wordSize = Integer.valueOf(args[0]);

    } catch (Exception e) {
        new HelpFormatter().printHelp("KmerStartsFromKnown <word_size> [name=]<ref_file> ...", options);
        System.err.println(e.getMessage());
        System.exit(1);
        throw new RuntimeException("Stupid jvm"); //While this will never get thrown it is required to make sure javac doesn't get confused about uninitialized variables
    }

    long startTime = System.currentTimeMillis();

    /*
     * if (args.length == 4) { maxThreads = Integer.valueOf(args[3]); } else
     * {
     */

    //}

    System.err.println("Starting kmer mapping at " + new Date());
    System.err.println("*  References:              " + Arrays.asList(args));
    System.err.println("*  Kmer length:             " + wordSize);

    for (int index = 1; index < args.length; index++) {
        String refName;
        String refFileName = args[index];
        if (refFileName.contains("=")) {
            String[] lexemes = refFileName.split("=");
            refName = lexemes[0];
            refFileName = lexemes[1];
        } else {
            String tmpName = new File(refFileName).getName();
            if (tmpName.contains(".")) {
                refName = tmpName.substring(0, tmpName.lastIndexOf("."));
            } else {
                refName = tmpName;
            }
        }

        File refFile = new File(refFileName);

        if (SeqUtils.guessSequenceType(refFile) != SequenceType.Nucleotide) {
            throw new Exception("Reference file " + refFile + " contains " + SeqUtils.guessFileFormat(refFile)
                    + " sequences but expected nucleotide sequences");
        }

        SequenceReader seqReader = new SequenceReader(refFile);
        Sequence seq;

        while ((seq = seqReader.readNextSequence()) != null) {
            if (seq.getSeqName().startsWith("#")) {
                continue;
            }
            ModelPositionKmerGenerator kmers = new ModelPositionKmerGenerator(seq.getSeqString(), wordSize,
                    SequenceType.Nucleotide);

            for (char[] charmer : kmers) {
                int pos = kmers.getModelPosition() - 1;
                if (translQuery) {
                    if (pos % 3 != 0) {
                        continue;
                    } else {
                        pos /= 3;
                    }
                }

                String kmer = new String(charmer);

                out.write(new KmerStart(refName, seq.getSeqName(), seq.getSeqName(), kmer, 1, pos, translQuery,
                        (translQuery ? ProteinUtils.getInstance().translateToProtein(kmer, true, translTable)
                                : null)));

            }
        }
        seqReader.close();
    }
    out.close();
}

From source file:com.eternitywall.ots.OtsCli.java

public static void main(String[] args) {
    // Create the Options
    Options options = new Options();
    options.addOption("c", "calendar", true,
            "Create timestamp with the aid of a remote calendar. May be specified multiple times.");
    options.addOption("k", "key", true, "Signature key file of private remote calendars.");
    options.addOption("d", "digest", true, "Verify a (hex-encoded) digest rather than a file.");
    options.addOption("a", "algorithm", true,
            "Pass the hashing algorithm of the document to timestamp: SHA256(default), SHA1, RIPEMD160.");
    options.addOption("m", "", true,
            "Commitments are sent to remote calendars in the event of timeout the timestamp is considered done if at least M calendars replied.");
    options.addOption("s", "shrink", false, "Shrink upgraded timestamp.");
    options.addOption("V", "version", false, "Print " + title + " version.");
    options.addOption("v", "verbose", false, "Be more verbose..");
    options.addOption("f", "file", true,
            "Specify target file explicitly (default: original file present in the same directory without .ots)");
    options.addOption("h", "help", false, "print this help.");

    // Parse the args to retrieve options & command
    CommandLineParser parser = new BasicParser();
    try {//  w  w  w  . j a v  a  2  s  .  co  m
        CommandLine line = parser.parse(options, args);
        // args are the arguments passed to the  the application via the main method

        if (line.hasOption("c")) {
            String[] cals = line.getOptionValues("c");
            calendarsUrl.addAll(Arrays.asList(cals));
        }

        if (line.hasOption("m")) {
            m = Integer.valueOf(line.getOptionValue("m"));
        }

        if (line.hasOption("k")) {
            signatureFile = line.getOptionValue("k");
            calendarsUrl.clear();
        }

        if (line.hasOption("s")) {
            shrink = true;
        }

        if (line.hasOption("v")) {
            verbose = true;
        }

        if (line.hasOption("V")) {
            System.out.println("Version: " + title + " v." + version + '\n');
            return;
        }

        if (line.hasOption("h")) {
            showHelp();
            return;
        }

        if (line.hasOption("d")) {
            shasum = Utils.hexToBytes(line.getOptionValue("d"));
        }

        if (line.hasOption("f")) {
            verifyFile = line.getOptionValue("f");
        }

        if (line.hasOption("a")) {
            algorithm = line.getOptionValue("a");
            if (!Arrays.asList(algorithms).contains(algorithm.toUpperCase())) {
                System.out.println("Algorithm: " + algorithm + " not supported\n");
                return;
            }
        }

        if (line.getArgList().isEmpty()) {
            showHelp();
            return;
        }

        cmd = line.getArgList().get(0);
        files = line.getArgList().subList(1, line.getArgList().size());
    } catch (Exception e) {
        System.out.println(title + ": invalid parameters ");
        return;
    }

    // Parse the command
    switch (cmd) {
    case "info":
    case "i":
        if (files.isEmpty()) {
            System.out.println("Show information on a timestamp given as argument.\n");
            System.out.println(title + " info: bad options ");
            break;
        }

        info(files.get(0), verbose);

        break;
    case "stamp":
    case "s":
        if (!files.isEmpty()) {
            multistamp(files, calendarsUrl, m, signatureFile, algorithm);
        } else if (shasum != null) {
            Hash hash = new Hash(shasum, algorithm);
            stamp(hash, calendarsUrl, m, signatureFile);
        } else {
            System.out.println("Create timestamp with the aid of a remote calendar.\n");
            System.out.println(title + ": bad options number ");
        }

        break;
    case "verify":
    case "v":
        if (!files.isEmpty()) {
            Hash hash = null;

            if (shasum != null) {
                hash = new Hash(shasum, algorithm);
            }

            if (verifyFile == null) {
                verifyFile = files.get(0).replace(".ots", "");
            }

            verify(files.get(0), hash, verifyFile);
        } else {
            System.out.println("Verify the timestamp attestations given as argument.\n");
            System.out.println(title + ": bad options number ");
        }

        break;
    case "upgrade":
    case "u":
        if (files.isEmpty()) {
            System.out.println("Upgrade remote calendar timestamps to be locally verifiable.\n");
            System.out.println(title + ": bad options number ");
            break;
        }

        upgrade(files.get(0), shrink);

        break;
    default:
        System.out.println(title + ": bad option: " + cmd);
    }
}

From source file:TwitterClustering.java

public static void main(String[] args) throws FileNotFoundException, IOException {
    // TODO code application logic here

    File outFile = new File(args[3]);
    Scanner s = new Scanner(new File(args[1])).useDelimiter(",");
    JSONParser parser = new JSONParser();
    Set<Cluster> clusterSet = new HashSet<Cluster>();
    HashMap<String, Tweet> tweets = new HashMap();
    FileWriter fw = new FileWriter(outFile.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);

    // init/*  w  w w. j  av a  2 s  .c o  m*/
    try {

        Object obj = parser.parse(new FileReader(args[2]));

        JSONArray jsonArray = (JSONArray) obj;

        for (int i = 0; i < jsonArray.size(); i++) {

            Tweet twt = new Tweet();
            JSONObject jObj = (JSONObject) jsonArray.get(i);
            String text = jObj.get("text").toString();

            long sum = 0;
            for (int y = 0; y < text.toCharArray().length; y++) {

                sum += (int) text.toCharArray()[y];
            }

            String[] token = text.split(" ");
            String tID = jObj.get("id").toString();

            Set<String> mySet = new HashSet<String>(Arrays.asList(token));
            twt.setAttributeValue(sum);
            twt.setText(mySet);
            twt.setTweetID(tID);
            tweets.put(tID, twt);

        }

        // preparing initial clusters
        int i = 0;
        while (s.hasNext()) {
            String id = s.next();// id
            Tweet t = tweets.get(id.trim());
            clusterSet.add(new Cluster(i + 1, t, new LinkedList()));
            i++;
        }

        Iterator it = tweets.entrySet().iterator();

        for (int l = 0; l < 2; l++) { // limit to 25 iterations

            while (it.hasNext()) {
                Map.Entry me = (Map.Entry) it.next();

                // calculate distance to each centroid
                Tweet p = (Tweet) me.getValue();
                HashMap<Cluster, Float> distMap = new HashMap();

                for (Cluster clust : clusterSet) {

                    distMap.put(clust, jaccardDistance(p.getText(), clust.getCentroid().getText()));
                }

                HashMap<Cluster, Float> sorted = (HashMap<Cluster, Float>) sortByValue(distMap);

                sorted.keySet().iterator().next().getMembers().add(p);

            }

            // calculate new centroid and update Clusterset
            for (Cluster clust : clusterSet) {

                TreeMap<String, Long> tDistMap = new TreeMap();

                Tweet newCentroid = null;
                Long avgSumDist = new Long(0);
                for (int j = 0; j < clust.getMembers().size(); j++) {

                    avgSumDist += clust.getMembers().get(j).getAttributeValue();
                    tDistMap.put(clust.getMembers().get(j).getTweetID(),
                            clust.getMembers().get(j).getAttributeValue());
                }
                if (clust.getMembers().size() != 0) {
                    avgSumDist /= (clust.getMembers().size());
                }

                ArrayList<Long> listValues = new ArrayList<Long>(tDistMap.values());

                if (tDistMap.containsValue(findClosestNumber(listValues, avgSumDist))) {
                    // found closest
                    newCentroid = tweets
                            .get(getKeyByValue(tDistMap, findClosestNumber(listValues, avgSumDist)));
                    clust.setCentroid(newCentroid);
                }

            }

        }
        // create an iterator
        Iterator iterator = clusterSet.iterator();

        // check values
        while (iterator.hasNext()) {

            Cluster c = (Cluster) iterator.next();
            bw.write(c.getId() + "\t");
            System.out.print(c.getId() + "\t");

            for (Tweet t : c.getMembers()) {
                bw.write(t.getTweetID() + ", ");
                System.out.print(t.getTweetID() + ",");

            }
            bw.write("\n");
            System.out.println("");
        }

        System.out.println("");

        System.out.println("SSE " + sumSquaredErrror(clusterSet));

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        bw.close();
        fw.close();
    }
}

From source file:com.edduarte.protbox.Protbox.java

public static void main(String... args) {

    // activate debug / verbose mode
    if (args.length != 0) {
        List<String> argsList = Arrays.asList(args);
        if (argsList.contains("-v")) {
            Constants.verbose = true;//from  w w  w  . j av a 2  s.  c o  m
        }
    }

    // use System's look and feel
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception ex) {
        // If the System's look and feel is not obtainable, continue execution with JRE look and feel
    }

    // check this is a single instance
    try {
        new ServerSocket(1882);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null,
                "Another instance of Protbox is already running.\n" + "Please close the other instance first.",
                "Protbox already running", JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }

    // check if System Tray is supported by this operative system
    if (!SystemTray.isSupported()) {
        JOptionPane.showMessageDialog(null,
                "Your operative system does not support system tray functionality.\n"
                        + "Please try running Protbox on another operative system.",
                "System tray not supported", JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }

    // add PKCS11 providers
    FileFilter fileFilter = new AndFileFilter(new WildcardFileFilter(Lists.newArrayList("*.config")),
            HiddenFileFilter.VISIBLE);

    File[] providersConfigFiles = new File(Constants.PROVIDERS_DIR).listFiles(fileFilter);

    if (providersConfigFiles != null) {
        for (File f : providersConfigFiles) {
            try {
                List<String> lines = FileUtils.readLines(f);
                String aliasLine = lines.stream().filter(line -> line.contains("alias")).findFirst().get();
                lines.remove(aliasLine);
                String alias = aliasLine.split("=")[1].trim();

                StringBuilder sb = new StringBuilder();
                for (String s : lines) {
                    sb.append(s);
                    sb.append("\n");
                }

                Provider p = new SunPKCS11(new ReaderInputStream(new StringReader(sb.toString())));
                Security.addProvider(p);

                pkcs11Providers.put(p.getName(), alias);

            } catch (IOException | ProviderException ex) {
                if (ex.getMessage().equals("Initialization failed")) {
                    ex.printStackTrace();

                    String s = "The following error occurred:\n" + ex.getCause().getMessage()
                            + "\n\nIn addition, make sure you have "
                            + "an available smart card reader connected before opening the application.";
                    JTextArea textArea = new JTextArea(s);
                    textArea.setColumns(60);
                    textArea.setLineWrap(true);
                    textArea.setWrapStyleWord(true);
                    textArea.setSize(textArea.getPreferredSize().width, 1);

                    JOptionPane.showMessageDialog(null, textArea, "Error loading PKCS11 provider",
                            JOptionPane.ERROR_MESSAGE);
                    System.exit(1);
                } else {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(null,
                            "Error while setting up PKCS11 provider from configuration file " + f.getName()
                                    + ".\n" + ex.getMessage(),
                            "Error loading PKCS11 provider", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }

    // adds a shutdown hook to save instantiated directories into files when the application is being closed
    Runtime.getRuntime().addShutdownHook(new Thread(Protbox::exit));

    // get system tray and run tray applet
    tray = SystemTray.getSystemTray();
    SwingUtilities.invokeLater(() -> {

        if (Constants.verbose) {
            logger.info("Starting application");
        }

        //Start a new TrayApplet object
        trayApplet = TrayApplet.getInstance();
    });

    // prompts the user to choose which provider to use
    ProviderListWindow.showWindow(Protbox.pkcs11Providers.keySet(), providerName -> {

        // loads eID token
        eIDTokenLoadingWindow.showPrompt(providerName, (returnedUser, returnedCertificateData) -> {
            user = returnedUser;
            certificateData = returnedCertificateData;

            // gets a password to use on the saved registry files (for loading and saving)
            final AtomicReference<Consumer<SecretKey>> consumerHolder = new AtomicReference<>(null);
            consumerHolder.set(password -> {
                registriesPasswordKey = password;
                try {
                    // if there are serialized files, load them if they can be decoded by this user's private key
                    final List<SavedRegistry> serializedDirectories = new ArrayList<>();
                    if (Constants.verbose) {
                        logger.info("Reading serialized registry files...");
                    }

                    File[] registryFileList = new File(Constants.REGISTRIES_DIR).listFiles();
                    if (registryFileList != null) {
                        for (File f : registryFileList) {
                            if (f.isFile()) {
                                byte[] data = FileUtils.readFileToByteArray(f);
                                try {
                                    Cipher cipher = Cipher.getInstance("AES");
                                    cipher.init(Cipher.DECRYPT_MODE, registriesPasswordKey);
                                    byte[] registryDecryptedData = cipher.doFinal(data);
                                    serializedDirectories.add(new SavedRegistry(f, registryDecryptedData));
                                } catch (GeneralSecurityException ex) {
                                    if (Constants.verbose) {
                                        logger.info("Inserted Password does not correspond to " + f.getName());
                                    }
                                }
                            }
                        }
                    }

                    // if there were no serialized directories, show NewDirectory window to configure the first folder
                    if (serializedDirectories.isEmpty() || registryFileList == null) {
                        if (Constants.verbose) {
                            logger.info("No registry files were found: running app as first time!");
                        }
                        NewRegistryWindow.start(true);

                    } else { // there were serialized directories
                        loadRegistry(serializedDirectories);
                        trayApplet.repaint();
                        showTrayApplet();
                    }

                } catch (AWTException | IOException | GeneralSecurityException | ReflectiveOperationException
                        | ProtboxException ex) {

                    JOptionPane.showMessageDialog(null,
                            "The inserted password was invalid! Please try another one!", "Invalid password!",
                            JOptionPane.ERROR_MESSAGE);
                    insertPassword(consumerHolder.get());
                }
            });
            insertPassword(consumerHolder.get());
        });
    });
}

From source file:com.eviware.loadui.launcher.LoadUILauncher.java

public static void main(String[] args) {
    for (String arg : args) {
        System.out.println("LoadUILauncher arg: " + arg);
        if (arg.contains("cmd")) {
            List<String> argList = new ArrayList<>(Arrays.asList(args));
            argList.remove(arg);/* w w  w .  j a  v a 2 s.c om*/
            String[] newArgs = argList.toArray(new String[argList.size()]);
            Application.launch(CommandApplication.class, newArgs);
            return;
        }
    }

    Application.launch(FXApplication.class, args);

    // Is the below just old legacy code from JavaFX 1?

    //      System.setSecurityManager( null );
    //
    //      LoadUILauncher launcher = new LoadUILauncher( args );
    //      launcher.init();
    //      launcher.start();
    //
    //      new Thread( new LauncherWatchdog( launcher.framework, 20000 ), "loadUI Launcher Watchdog" ).start();
}

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

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

    RClient rClient = null;//from   w w  w.  ja v  a  2 s.com

    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 the AnonymousProjectExecutionOptions object
         * to specify data inputs and output to the 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.
         */
        AnonymousProjectExecutionOptions options = new AnonymousProjectExecutionOptions();

        /* 
         * 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 an analytics Web service as an authenticated
         * user based on a repository-managed R script:
         * /testuser/example-data-io/dataIO.R
         */
        RScriptExecution exec = rClient.executeScript("dataIO.R", "example-data-io", "testuser", null, options);

        log.info("[   EXECUTION    ] Discrete R script " + "execution completed [ RScriptExecution ].");

        /*
         * 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 " + ex);
                } finally {
                    IOUtils.closeQuietly(fis);
                }
            }
        }

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

}

From source file:gov.nih.nci.cacis.mirth.XSLForMirthFormatter.java

/**
 * @param args - main method args// w  w w  .j a  v  a 2  s.c o m
 * @throws IOException - error thrown, if any
 * @throws URISyntaxException - error thrown, if any
 */
public static void main(String[] args) throws IOException, URISyntaxException {
    if (args.length < 2) {
        LOG.error("Usage: XSLForMirthFormatter <formatted-file-output-dir> <xsl-file-1> <xsl-file-2> ...");
        System.exit(1);
    }
    final List<String> lst = new ArrayList<String>(Arrays.asList(args));
    lst.remove(0);
    final XSLForMirthFormatter frmtr = new XSLForMirthFormatter();
    frmtr.formatXSL(args[0], (String[]) lst.toArray(new String[lst.size()]));
}