Example usage for com.google.common.collect Lists newArrayList

List of usage examples for com.google.common.collect Lists newArrayList

Introduction

In this page you can find the example usage for com.google.common.collect Lists newArrayList.

Prototype

@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList(Iterator<? extends E> elements) 

Source Link

Document

Creates a mutable ArrayList instance containing the given elements; a very thin shortcut for creating an empty list and then calling Iterators#addAll .

Usage

From source file:com.linkedin.pinot.perf.PerfBenchmarkRunner.java

public static void main(String[] args) throws Exception {
    if (args.length > 0) {
        if (args[0].equalsIgnoreCase("startAllButServer") || args[0].equalsIgnoreCase("startAll")) {
            startComponents(true, true, true, false);
        }//from w w w .j  av  a2 s  .c o m

        if (args[0].equalsIgnoreCase("startServerWithPreLoadedSegments")
                || args[0].equalsIgnoreCase("startAll")) {
            String offlineTableNames = args[1];
            String indexRootDirectory = args[2];
            List<String> invertedIndexColumns = new ArrayList<>();
            if (args.length == 4) {
                String[] columns = args[3].split(",");
                for (int i = 0; i < columns.length; i++) {
                    invertedIndexColumns.add(columns[i].trim());
                }
            }
            startServerWithPreLoadedSegments(indexRootDirectory,
                    Lists.newArrayList(offlineTableNames.split(",")), invertedIndexColumns);
        }

    } else {
        System.err.println("Expected one of [startAll|startAllButServer|StartServerWithPreLoadedSegments]");
    }
}

From source file:com.google.api.services.samples.youtube.cmdline.youtube_cmdline_playlistupdates_sample.PlaylistUpdates.java

/**
 * Authorizes user, creates a playlist, adds a playlistitem with a video to that new playlist.
 *
 * @param args command line args (not used).
 *//*from   ww w . j a  v a 2  s  .  c  o m*/
public static void main(String[] args) {

    // General read/write scope for YouTube APIs.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");

    try {
        // Authorization.
        Credential credential = authorize(scopes);

        // YouTube object used to make all API requests.
        youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName("youtube-cmdline-playlistupdates-sample").build();

        // Creates a new playlist in the authorized user's channel.
        String playlistId = insertPlaylist();

        // If a valid playlist was created, adds a new playlistitem with a video to that playlist.
        insertPlaylistItem(playlistId, VIDEO_ID);

    } catch (GoogleJsonResponseException e) {
        System.err.println(
                "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());
        e.printStackTrace();
    } catch (Throwable t) {
        System.err.println("Throwable: " + t.getMessage());
        t.printStackTrace();
    }
}

From source file:com.google.api.services.samples.youtube.cmdline.youtube_cmdline_createbroadcast_sample.CreateBroadcast.java

/**
 * Creates and inserts a Live Broadcast using OAuth2 for authentication.
 *//*from   www .  j a v  a 2 s. c  o m*/
public static void main(String[] args) {

    // Scope required to wrie data to YouTube.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");

    try {
        // Authorization.
        Credential credential = authorize(scopes);

        // YouTube object used to make all API requests.
        youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName("youtube-cmdline-createbroadcast-sample").build();

        // Get the user's selected title for broadcast.
        String title = getBroadcastTitle();
        System.out.println("You chose " + title + " for broadcast title.");

        // Create a snippet with title, scheduled start and end times.
        LiveBroadcastSnippet broadcastSnippet = new LiveBroadcastSnippet();
        broadcastSnippet.setTitle(title);
        broadcastSnippet.setScheduledStartTime(new DateTime("2024-01-30T00:00:00.000Z"));
        broadcastSnippet.setScheduledEndTime(new DateTime("2024-01-31T00:00:00.000Z"));

        // Create LiveBroadcastStatus with privacy status.
        LiveBroadcastStatus status = new LiveBroadcastStatus();
        status.setPrivacyStatus("private");

        LiveBroadcast broadcast = new LiveBroadcast();
        broadcast.setKind("youtube#liveBroadcast");
        broadcast.setSnippet(broadcastSnippet);
        broadcast.setStatus(status);

        // Create the insert request
        YouTube.LiveBroadcasts.Insert liveBroadcastInsert = youtube.liveBroadcasts().insert("snippet,status",
                broadcast);

        // Request is executed and inserted broadcast is returned
        LiveBroadcast returnedBroadcast = liveBroadcastInsert.execute();

        // Print out returned results.
        System.out.println("\n================== Returned Broadcast ==================\n");
        System.out.println("  - Id: " + returnedBroadcast.getId());
        System.out.println("  - Title: " + returnedBroadcast.getSnippet().getTitle());
        System.out.println("  - Description: " + returnedBroadcast.getSnippet().getDescription());
        System.out.println("  - Published At: " + returnedBroadcast.getSnippet().getPublishedAt());
        System.out
                .println("  - Scheduled Start Time: " + returnedBroadcast.getSnippet().getScheduledStartTime());
        System.out.println("  - Scheduled End Time: " + returnedBroadcast.getSnippet().getScheduledEndTime());

        // Get the user's selected title for stream.
        title = getStreamTitle();
        System.out.println("You chose " + title + " for stream title.");

        // Create a snippet with title.
        LiveStreamSnippet streamSnippet = new LiveStreamSnippet();
        streamSnippet.setTitle(title);

        // Create content distribution network with format and ingestion type.
        LiveStreamCdn cdn = new LiveStreamCdn();
        cdn.setFormat("1080p");
        cdn.setIngestionType("rtmp");

        LiveStream stream = new LiveStream();
        stream.setKind("youtube#liveStream");
        stream.setSnippet(streamSnippet);
        stream.setCdn(cdn);

        // Create the insert request
        YouTube.LiveStreams.Insert liveStreamInsert = youtube.liveStreams().insert("snippet,cdn", stream);

        // Request is executed and inserted stream is returned
        LiveStream returnedStream = liveStreamInsert.execute();

        // Print out returned results.
        System.out.println("\n================== Returned Stream ==================\n");
        System.out.println("  - Id: " + returnedStream.getId());
        System.out.println("  - Title: " + returnedStream.getSnippet().getTitle());
        System.out.println("  - Description: " + returnedStream.getSnippet().getDescription());
        System.out.println("  - Published At: " + returnedStream.getSnippet().getPublishedAt());

        // Create the bind request
        YouTube.LiveBroadcasts.Bind liveBroadcastBind = youtube.liveBroadcasts().bind(returnedBroadcast.getId(),
                "id,contentDetails");

        // Set stream id to bind
        liveBroadcastBind.setStreamId(returnedStream.getId());

        // Request is executed and bound broadcast is returned
        returnedBroadcast = liveBroadcastBind.execute();

        // Print out returned results.
        System.out.println("\n================== Returned Bound Broadcast ==================\n");
        System.out.println("  - Broadcast Id: " + returnedBroadcast.getId());
        System.out.println("  - Bound Stream Id: " + returnedBroadcast.getContentDetails().getBoundStreamId());

    } catch (GoogleJsonResponseException e) {
        System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : "
                + e.getDetails().getMessage());
        e.printStackTrace();

    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());
        e.printStackTrace();
    } catch (Throwable t) {
        System.err.println("Throwable: " + t.getMessage());
        t.printStackTrace();
    }
}

From source file:com.google.api.services.samples.youtube.cmdline.youtube_cmdline_myuploads_sample.MyUploads.java

/**
 * Authorizes user, runs Youtube.Channnels.List get the playlist id associated with uploaded
 * videos, runs YouTube.PlaylistItems.List to get information on each video, and prints out the
 * results.//ww w  . j av a  2 s  . c om
 *
 * @param args command line args (not used).
 */
public static void main(String[] args) {

    // Scope required to upload to YouTube.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");

    try {
        // Authorization.
        Credential credential = authorize(scopes);

        // YouTube object used to make all API requests.
        youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName("youtube-cmdline-myuploads-sample").build();

        /*
         * Now that the user is authenticated, the app makes a channel list request to get the
         * authenticated user's channel. Returned with that data is the playlist id for the uploaded
         * videos. https://developers.google.com/youtube/v3/docs/channels/list
         */
        YouTube.Channels.List channelRequest = youtube.channels().list("contentDetails");
        channelRequest.setMine("true");
        /*
         * Limits the results to only the data we needo which makes things more efficient.
         */
        channelRequest.setFields("items/contentDetails,nextPageToken,pageInfo");
        ChannelListResponse channelResult = channelRequest.execute();

        /*
         * Gets the list of channels associated with the user. This sample only pulls the uploaded
         * videos for the first channel (default channel for user).
         */
        List<Channel> channelsList = channelResult.getItems();

        if (channelsList != null) {
            // Gets user's default channel id (first channel in list).
            String uploadPlaylistId = channelsList.get(0).getContentDetails().getRelatedPlaylists()
                    .getUploads();

            // List to store all PlaylistItem items associated with the uploadPlaylistId.
            List<PlaylistItem> playlistItemList = new ArrayList<PlaylistItem>();

            /*
             * Now that we have the playlist id for your uploads, we will request the playlistItems
             * associated with that playlist id, so we can get information on each video uploaded. This
             * is the template for the list call. We call it multiple times in the do while loop below
             * (only changing the nextToken to get all the videos).
             * https://developers.google.com/youtube/v3/docs/playlistitems/list
             */
            YouTube.PlaylistItems.List playlistItemRequest = youtube.playlistItems()
                    .list("id,contentDetails,snippet");
            playlistItemRequest.setPlaylistId(uploadPlaylistId);

            // This limits the results to only the data we need and makes things more efficient.
            playlistItemRequest.setFields(
                    "items(contentDetails/videoId,snippet/title,snippet/publishedAt),nextPageToken,pageInfo");

            String nextToken = "";

            // Loops over all search page results returned for the uploadPlaylistId.
            do {
                playlistItemRequest.setPageToken(nextToken);
                PlaylistItemListResponse playlistItemResult = playlistItemRequest.execute();

                playlistItemList.addAll(playlistItemResult.getItems());

                nextToken = playlistItemResult.getNextPageToken();
            } while (nextToken != null);

            // Prints results.
            prettyPrint(playlistItemList.size(), playlistItemList.iterator());
        }

    } catch (GoogleJsonResponseException e) {
        e.printStackTrace();
        System.err.println(
                "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());

    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:org.cinchapi.concourse.shell.ConcourseShell.java

/**
 * Run the program.../*from   ww w . j  a v  a 2  s. c o m*/
 * 
 * @param args - see {@link Options}
 * @throws IOException
 */
public static void main(String... args) throws IOException {
    ConsoleReader console = new ConsoleReader();
    console.setExpandEvents(false);
    Options opts = new Options();
    JCommander parser = new JCommander(opts, args);
    parser.setProgramName("concourse-shell");
    if (opts.help) {
        parser.usage();
        System.exit(1);
    }
    if (Strings.isNullOrEmpty(opts.password)) {
        opts.password = console.readLine("Password [" + opts.username + "]: ", '*');
    }
    try {
        Concourse concourse = Concourse.connect(opts.host, opts.port, opts.username, opts.password,
                opts.environment);

        final String env = concourse.getServerEnvironment();

        CommandLine.displayWelcomeBanner();
        Binding binding = new Binding();
        GroovyShell shell = new GroovyShell(binding);

        Stopwatch watch = Stopwatch.createUnstarted();
        console.println("Client Version " + Version.getVersion(ConcourseShell.class));
        console.println("Server Version " + concourse.getServerVersion());
        console.println("");
        console.println("Connected to the '" + env + "' environment.");
        console.println("");
        console.println("Type HELP for help.");
        console.println("Type EXIT to quit.");
        console.println("Use TAB for completion.");
        console.println("");
        console.setPrompt(MessageFormat.format("[{0}/cash]$ ", env));
        console.addCompleter(new StringsCompleter(getAccessibleApiMethodsUsingShortSyntax()));

        final List<String> methods = Lists.newArrayList(getAccessibleApiMethods());
        String line;
        while ((line = console.readLine().trim()) != null) {
            line = SyntaxTools.handleShortSyntax(line, methods);
            binding.setVariable("concourse", concourse);
            binding.setVariable("eq", Operator.EQUALS);
            binding.setVariable("ne", Operator.NOT_EQUALS);
            binding.setVariable("gt", Operator.GREATER_THAN);
            binding.setVariable("gte", Operator.GREATER_THAN_OR_EQUALS);
            binding.setVariable("lt", Operator.LESS_THAN);
            binding.setVariable("lte", Operator.LESS_THAN_OR_EQUALS);
            binding.setVariable("bw", Operator.BETWEEN);
            binding.setVariable("regex", Operator.REGEX);
            binding.setVariable("nregex", Operator.NOT_REGEX);
            binding.setVariable("lnk2", Operator.LINKS_TO);
            binding.setVariable("date", STRING_TO_TIME);
            binding.setVariable("time", STRING_TO_TIME);
            binding.setVariable("where", WHERE);
            binding.setVariable("tag", STRING_TO_TAG);
            if (line.equalsIgnoreCase("exit")) {
                concourse.exit();
                System.exit(0);
            } else if (line.equalsIgnoreCase("help") || line.equalsIgnoreCase("man")) {
                Process p = Runtime.getRuntime()
                        .exec(new String[] { "sh", "-c", "echo \"" + HELP_TEXT + "\" | less > /dev/tty" });
                p.waitFor();
            } else if (containsBannedCharSequence(line)) {
                System.err.println(
                        "Cannot complete command because " + "it contains an illegal character sequence.");
            } else if (Strings.isNullOrEmpty(line)) { // CON-170
                continue;
            } else {
                watch.reset().start();
                Object value = null;
                try {
                    value = shell.evaluate(line, "ConcourseShell");
                    watch.stop();
                    if (value != null) {
                        System.out.println(
                                "Returned '" + value + "' in " + watch.elapsed(TimeUnit.MILLISECONDS) + " ms");
                    } else {
                        System.out.println("Completed in " + watch.elapsed(TimeUnit.MILLISECONDS) + " ms");
                    }
                } catch (Exception e) {
                    if (e.getCause() instanceof TTransportException) {
                        die(e.getMessage());
                    } else if (e.getCause() instanceof TSecurityException) {
                        die("A security change has occurred and your " + "session cannot continue");
                    } else {
                        System.err.print("ERROR: " + e.getMessage());
                    }
                }

            }
            System.out.print("\n");
        }
    } catch (Exception e) {
        if (e.getCause() instanceof TTransportException) {
            die("Unable to connect to " + opts.username + "@" + opts.host + ":" + opts.port
                    + " with the specified password");
        } else if (e.getCause() instanceof TSecurityException) {
            die("Invalid username/password combination.");
        } else {
            die(e.getMessage());
        }
    } finally {
        try {
            TerminalFactory.get().restore();
        } catch (Exception e) {
            die(e.getMessage());
        }
    }

}

From source file:com.google.api.services.samples.youtube.cmdline.youtube_cmdline_channelbulletin_sample.ChannelBulletin.java

/**
 * Authorizes user, runs Youtube.Channnels.List to get the default channel, and posts a bulletin
 * with a video id to the user's default channel.
 *
 * @param args command line args (not used).
 *///from  w  ww . j av  a  2  s.  c om
public static void main(String[] args) {

    // Scope required to upload to YouTube.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");

    try {
        // Authorization.
        Credential credential = authorize(scopes);

        // YouTube object used to make all API requests.
        youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName("youtube-cmdline-channelbulletin-sample").build();

        /*
         * Now that the user is authenticated, the app makes a channel list request to get the
         * authenticated user's channel. https://developers.google.com/youtube/v3/docs/channels/list
         */
        YouTube.Channels.List channelRequest = youtube.channels().list("contentDetails");
        channelRequest.setMine("true");
        /*
         * Limits the results to only the data we need making your app more efficient.
         */
        channelRequest.setFields("items/contentDetails");
        ChannelListResponse channelResult = channelRequest.execute();

        /*
         * Gets the list of channels associated with the user.
         */
        List<Channel> channelsList = channelResult.getItems();

        if (channelsList != null) {
            // Gets user's default channel id (first channel in list).
            String channelId = channelsList.get(0).getId();

            /*
             * We create the snippet to set the channel we will post to and the description that goes
             * along with our bulletin.
             */
            ActivitySnippet snippet = new ActivitySnippet();
            snippet.setChannelId(channelId);
            Calendar cal = Calendar.getInstance();
            snippet.setDescription("Bulletin test video via YouTube API on " + cal.getTime());

            /*
             * We set the kind of the ResourceId to video (youtube#video). Please note, you could set
             * the type to a playlist (youtube#playlist) and use a playlist id instead of a video id.
             */
            ResourceId resource = new ResourceId();
            resource.setKind("youtube#video");
            resource.setVideoId(VIDEO_ID);

            Bulletin bulletin = new Bulletin();
            bulletin.setResourceId(resource);

            // We construct the ActivityContentDetails now that we have the Bulletin.
            ActivityContentDetails contentDetails = new ActivityContentDetails();
            contentDetails.setBulletin(bulletin);

            /*
             * Finally, we construct the activity we will write to YouTube via the API. We set the
             * snippet (covers description and channel we are posting to) and the content details
             * (covers video id and type).
             */
            Activity activity = new Activity();
            activity.setSnippet(snippet);
            activity.setContentDetails(contentDetails);

            /*
             * We specify the parts (contentDetails and snippet) we will write to YouTube. Those also
             * cover the parts that are returned.
             */
            YouTube.Activities.Insert insertActivities = youtube.activities().insert("contentDetails,snippet",
                    activity);
            // This returns the Activity that was added to the user's YouTube channel.
            Activity newActivityInserted = insertActivities.execute();

            if (newActivityInserted != null) {
                System.out
                        .println("New Activity inserted of type " + newActivityInserted.getSnippet().getType());
                System.out.println(" - Video id "
                        + newActivityInserted.getContentDetails().getBulletin().getResourceId().getVideoId());
                System.out.println(" - Description: " + newActivityInserted.getSnippet().getDescription());
                System.out.println(" - Posted on " + newActivityInserted.getSnippet().getPublishedAt());
            } else {
                System.out.println("Activity failed.");
            }

        } else {
            System.out.println("No channels are assigned to this user.");
        }
    } catch (GoogleJsonResponseException e) {
        e.printStackTrace();
        System.err.println(
                "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());

    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:tv.icntv.grade.film.grade.GradeJob.java

public static void main(String[] args) throws Exception {
    final Configuration configuration = HBaseConfiguration.create();
    configuration.addResource("grade.xml");
    String tables = configuration.get("hbase.cdn.tables");
    if (Strings.isNullOrEmpty(tables)) {
        return;// ww w.ja  v  a  2 s  .  c  o m
    }
    List<String> list = Lists.newArrayList(Splitter.on(",").split(tables));
    List<String> results = Lists.transform(list, new Function<String, String>() {
        @Override
        public String apply(@Nullable java.lang.String input) {
            return String.format(configuration.get("hdfs.directory.base.db"), new Date(), input);
        }
    });

    String[] arrays = new String[] { Joiner.on(",").join(results), configuration.get("film.see.num.table"),
            String.format(configuration.get("hdfs.directory.base.score"), new Date()),
            String.format(configuration.get("icntv.correlate.input"), new Date()) };
    int i = ToolRunner.run(configuration, new GradeJob(), arrays);
    System.exit(i);
}

From source file:org.apache.brooklyn.demo.GlobalWebFabricExample.java

public static void main(String[] argv) {
    List<String> args = Lists.newArrayList(argv);
    String port = CommandLineUtil.getCommandLineOption(args, "--port", "8081+");
    String locations = CommandLineUtil.getCommandLineOption(args, "--locations",
            Joiner.on(",").join(DEFAULT_LOCATIONS));

    BrooklynLauncher launcher = BrooklynLauncher.newInstance()
            .application(EntitySpec.create(StartableApplication.class, GlobalWebFabricExample.class)
                    .displayName("Brooklyn Global Web Fabric Example"))
            .webconsolePort(port).locations(Arrays.asList(locations)).start();

    Entities.dumpInfo(launcher.getApplications());
}

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;// w w w . j  ava  2  s  .  c  om
        }
    }

    // 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:it.anyplace.sync.client.Main.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("C", "set-config", true, "set config file for s-client");
    options.addOption("c", "config", false, "dump config");
    options.addOption("sp", "set-peers", true, "set peer, or comma-separated list of peers");
    options.addOption("q", "query", true, "query directory server for device id");
    options.addOption("d", "discovery", true, "discovery local network for device id");
    options.addOption("p", "pull", true, "pull file from network");
    options.addOption("P", "push", true, "push file to network");
    options.addOption("o", "output", true, "set output file/directory");
    options.addOption("i", "input", true, "set input file/directory");
    options.addOption("lp", "list-peers", false, "list peer addresses");
    options.addOption("a", "address", true, "use this peer addresses");
    options.addOption("L", "list-remote", false, "list folder (root) content from network");
    options.addOption("I", "list-info", false, "dump folder info from network");
    options.addOption("li", "list-info", false, "list folder info from local db");
    //        options.addOption("l", "list-local", false, "list folder content from local (saved) index");
    options.addOption("s", "search", true, "search local index for <term>");
    options.addOption("D", "delete", true, "push delete to network");
    options.addOption("M", "mkdir", true, "push directory create to network");
    options.addOption("h", "help", false, "print help");
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("s-client", options);
        return;// ww  w. j a  va 2  s. co m
    }

    File configFile = cmd.hasOption("C") ? new File(cmd.getOptionValue("C"))
            : new File(System.getProperty("user.home"), ".s-client.properties");
    logger.info("using config file = {}", configFile);
    ConfigurationService configuration = ConfigurationService.newLoader().loadFrom(configFile);
    FileUtils.cleanDirectory(configuration.getTemp());
    KeystoreHandler.newLoader().loadAndStore(configuration);
    if (cmd.hasOption("c")) {
        logger.info("configuration =\n{}", configuration.newWriter().dumpToString());
    } else {
        logger.trace("configuration =\n{}", configuration.newWriter().dumpToString());
    }
    logger.debug("{}", configuration.getStorageInfo().dumpAvailableSpace());

    if (cmd.hasOption("sp")) {
        List<String> peers = Lists.newArrayList(Lists.transform(
                Arrays.<String>asList(cmd.getOptionValue("sp").split(",")), new Function<String, String>() {
                    @Override
                    public String apply(String input) {
                        return input.trim();
                    }
                }));
        logger.info("set peers = {}", peers);
        configuration.edit().setPeers(Collections.<DeviceInfo>emptyList());
        for (String peer : peers) {
            KeystoreHandler.validateDeviceId(peer);
            configuration.edit().addPeers(new DeviceInfo(peer, null));
        }
        configuration.edit().persistNow();
    }

    if (cmd.hasOption("q")) {
        String deviceId = cmd.getOptionValue("q");
        logger.info("query device id = {}", deviceId);
        List<DeviceAddress> deviceAddresses = new GlobalDiscoveryHandler(configuration).query(deviceId);
        logger.info("server response = {}", deviceAddresses);
    }
    if (cmd.hasOption("d")) {
        String deviceId = cmd.getOptionValue("d");
        logger.info("discovery device id = {}", deviceId);
        List<DeviceAddress> deviceAddresses = new LocalDiscorveryHandler(configuration).queryAndClose(deviceId);
        logger.info("local response = {}", deviceAddresses);
    }

    if (cmd.hasOption("p")) {
        String path = cmd.getOptionValue("p");
        logger.info("file path = {}", path);
        String folder = path.split(":")[0];
        path = path.split(":")[1];
        try (SyncthingClient client = new SyncthingClient(configuration);
                BlockExchangeConnectionHandler connectionHandler = client.connectToBestPeer()) {
            InputStream inputStream = client.pullFile(connectionHandler, folder, path).waitForComplete()
                    .getInputStream();
            String fileName = client.getIndexHandler().getFileInfoByPath(folder, path).getFileName();
            File file;
            if (cmd.hasOption("o")) {
                File param = new File(cmd.getOptionValue("o"));
                file = param.isDirectory() ? new File(param, fileName) : param;
            } else {
                file = new File(fileName);
            }
            FileUtils.copyInputStreamToFile(inputStream, file);
            logger.info("saved file to = {}", file.getAbsolutePath());
        }
    }
    if (cmd.hasOption("P")) {
        String path = cmd.getOptionValue("P");
        File file = new File(cmd.getOptionValue("i"));
        checkArgument(!path.startsWith("/")); //TODO check path syntax
        logger.info("file path = {}", path);
        String folder = path.split(":")[0];
        path = path.split(":")[1];
        try (SyncthingClient client = new SyncthingClient(configuration);
                BlockPusher.FileUploadObserver fileUploadObserver = client.pushFile(new FileInputStream(file),
                        folder, path)) {
            while (!fileUploadObserver.isCompleted()) {
                fileUploadObserver.waitForProgressUpdate();
                logger.debug("upload progress {}", fileUploadObserver.getProgressMessage());
            }
            logger.info("uploaded file to network");
        }
    }
    if (cmd.hasOption("D")) {
        String path = cmd.getOptionValue("D");
        String folder = path.split(":")[0];
        path = path.split(":")[1];
        logger.info("delete path = {}", path);
        try (SyncthingClient client = new SyncthingClient(configuration);
                IndexEditObserver observer = client.pushDelete(folder, path)) {
            observer.waitForComplete();
            logger.info("deleted path");
        }
    }
    if (cmd.hasOption("M")) {
        String path = cmd.getOptionValue("M");
        String folder = path.split(":")[0];
        path = path.split(":")[1];
        logger.info("dir path = {}", path);
        try (SyncthingClient client = new SyncthingClient(configuration);
                IndexEditObserver observer = client.pushDir(folder, path)) {
            observer.waitForComplete();
            logger.info("uploaded dir to network");
        }
    }
    if (cmd.hasOption("L")) {
        try (SyncthingClient client = new SyncthingClient(configuration)) {
            client.waitForRemoteIndexAquired();
            for (String folder : client.getIndexHandler().getFolderList()) {
                try (IndexBrowser indexBrowser = client.getIndexHandler().newIndexBrowserBuilder()
                        .setFolder(folder).build()) {
                    logger.info("list folder = {}", indexBrowser.getFolder());
                    for (FileInfo fileInfo : indexBrowser.listFiles()) {
                        logger.info("\t\t{} {} {}", fileInfo.getType().name().substring(0, 1),
                                fileInfo.getPath(), fileInfo.describeSize());
                    }
                }
            }
        }
    }
    if (cmd.hasOption("I")) {
        try (SyncthingClient client = new SyncthingClient(configuration)) {
            if (cmd.hasOption("a")) {
                String deviceId = cmd.getOptionValue("a").substring(0, 63),
                        address = cmd.getOptionValue("a").substring(64);
                try (BlockExchangeConnectionHandler connection = client.getConnection(
                        DeviceAddress.newBuilder().setDeviceId(deviceId).setAddress(address).build())) {
                    client.getIndexHandler().waitForRemoteIndexAquired(connection);
                }
            } else {
                client.waitForRemoteIndexAquired();
            }
            String folderInfo = "";
            for (String folder : client.getIndexHandler().getFolderList()) {
                folderInfo += "\n\t\tfolder info : " + client.getIndexHandler().getFolderInfo(folder);
                folderInfo += "\n\t\tfolder stats : "
                        + client.getIndexHandler().newFolderBrowser().getFolderStats(folder).dumpInfo() + "\n";
            }
            logger.info("folders:\n{}\n", folderInfo);
        }
    }
    if (cmd.hasOption("li")) {
        try (SyncthingClient client = new SyncthingClient(configuration)) {
            String folderInfo = "";
            for (String folder : client.getIndexHandler().getFolderList()) {
                folderInfo += "\n\t\tfolder info : " + client.getIndexHandler().getFolderInfo(folder);
                folderInfo += "\n\t\tfolder stats : "
                        + client.getIndexHandler().newFolderBrowser().getFolderStats(folder).dumpInfo() + "\n";
            }
            logger.info("folders:\n{}\n", folderInfo);
        }
    }
    if (cmd.hasOption("lp")) {
        try (SyncthingClient client = new SyncthingClient(configuration);
                DeviceAddressSupplier deviceAddressSupplier = client.getDiscoveryHandler()
                        .newDeviceAddressSupplier()) {
            String deviceAddressesStr = "";
            for (DeviceAddress deviceAddress : Lists.newArrayList(deviceAddressSupplier)) {
                deviceAddressesStr += "\n\t\t" + deviceAddress.getDeviceId() + " : "
                        + deviceAddress.getAddress();
            }
            logger.info("device addresses:\n{}\n", deviceAddressesStr);
        }
    }
    if (cmd.hasOption("s")) {
        String term = cmd.getOptionValue("s");
        try (SyncthingClient client = new SyncthingClient(configuration);
                IndexFinder indexFinder = client.getIndexHandler().newIndexFinderBuilder().build()) {
            client.waitForRemoteIndexAquired();
            logger.info("search term = '{}'", term);
            IndexFinder.SearchCompletedEvent event = indexFinder.doSearch(term);
            if (event.hasGoodResults()) {
                logger.info("search results for term = '{}' :", term);
                for (FileInfo fileInfo : event.getResultList()) {
                    logger.info("\t\t{} {} {}", fileInfo.getType().name().substring(0, 1), fileInfo.getPath(),
                            fileInfo.describeSize());
                }
            } else if (event.hasTooManyResults()) {
                logger.info("too many results found for term = '{}'", term);
            } else {
                logger.info("no result found for term = '{}'", term);
            }
        }
    }
    //        if (cmd.hasOption("l")) {
    //            String indexDump = new IndexHandler(configuration).dumpIndex();
    //            logger.info("index dump = \n\n{}\n", indexDump);
    //        }
    IOUtils.closeQuietly(configuration);
}