Example usage for com.google.api.client.googleapis.auth.oauth2 GoogleAuthorizationCodeFlow.Builder GoogleAuthorizationCodeFlow.Builder

List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleAuthorizationCodeFlow.Builder GoogleAuthorizationCodeFlow.Builder

Introduction

In this page you can find the example usage for com.google.api.client.googleapis.auth.oauth2 GoogleAuthorizationCodeFlow.Builder GoogleAuthorizationCodeFlow.Builder.

Prototype

public Builder(HttpTransport transport, JsonFactory jsonFactory, GoogleClientSecrets clientSecrets,
        Collection<String> scopes) 

Source Link

Usage

From source file:org.blom.martin.stream2gdrive.Stream2GDrive.java

License:Apache License

public static void main(String[] args) throws Exception {
    Options opt = new Options();

    opt.addOption("?", "help", false, "Show usage.");
    opt.addOption("V", "version", false, "Print version information.");
    opt.addOption("v", "verbose", false, "Display progress status.");

    opt.addOption("p", "parent", true, "Operate inside this Google Drive folder instead of root.");
    opt.addOption("o", "output", true, "Override output/destination file name");
    opt.addOption("m", "mime", true, "Override guessed MIME type.");
    opt.addOption("C", "chunk-size", true, "Set transfer chunk size, in MiB. Default is 10.0 MiB.");
    opt.addOption("r", "auto-retry", false,
            "Enable automatic retry with exponential backoff in case of error.");

    opt.addOption(null, "oob", false, "Provide OAuth authentication out-of-band.");

    try {/*from   www.  jav a  2s.  co m*/
        CommandLine cmd = new GnuParser().parse(opt, args, false);
        args = cmd.getArgs();

        if (cmd.hasOption("version")) {
            String version = "?";
            String date = "?";

            try {
                Properties props = new Properties();
                props.load(resource("/build.properties"));

                version = props.getProperty("version", "?");
                date = props.getProperty("date", "?");
            } catch (Exception ignored) {
            }

            System.err.println(String.format("%s %s. Build %s (%s)", APP_NAME, APP_VERSION, version, date));
            System.err.println();
        }

        if (cmd.hasOption("help")) {
            throw new ParseException(null);
        }

        if (args.length < 1) {
            if (cmd.hasOption("version")) {
                return;
            } else {
                throw new ParseException("<cmd> missing");
            }
        }

        String command = args[0];

        JsonFactory jf = JacksonFactory.getDefaultInstance();
        HttpTransport ht = GoogleNetHttpTransport.newTrustedTransport();
        GoogleClientSecrets gcs = GoogleClientSecrets.load(jf, resource("/client_secrets.json"));

        Set<String> scopes = new HashSet<String>();
        scopes.add(DriveScopes.DRIVE_FILE);
        scopes.add(DriveScopes.DRIVE_METADATA_READONLY);

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(ht, jf, gcs, scopes)
                .setDataStoreFactory(new FileDataStoreFactory(appDataDir())).build();

        VerificationCodeReceiver vcr = !cmd.hasOption("oob") ? new LocalServerReceiver()
                : new GooglePromptReceiver();

        Credential creds = new AuthorizationCodeInstalledApp(flow, vcr).authorize("user");

        List<HttpRequestInitializer> hrilist = new ArrayList<HttpRequestInitializer>();
        hrilist.add(creds);

        if (cmd.hasOption("auto-retry")) {
            ExponentialBackOff.Builder backoffBuilder = new ExponentialBackOff.Builder()
                    .setInitialIntervalMillis(6 * 1000) // 6 seconds initial retry period
                    .setMaxElapsedTimeMillis(45 * 60 * 1000) // 45 minutes maximum total wait time
                    .setMaxIntervalMillis(15 * 60 * 1000) // 15 minute maximum interval
                    .setMultiplier(1.85).setRandomizationFactor(0.5);
            // Expected total waiting time before giving up = sum([6*1.85^i for i in range(10)])
            // ~= 55 minutes
            // Note that Google API's HttpRequest allows for up to 10 retry.
            hrilist.add(new ExponentialBackOffHttpRequestInitializer(backoffBuilder));
        }
        HttpRequestInitializerStacker hristack = new HttpRequestInitializerStacker(hrilist);

        Drive client = new Drive.Builder(ht, jf, hristack).setApplicationName(APP_NAME + "/" + APP_VERSION)
                .build();

        boolean verbose = cmd.hasOption("verbose");
        float chunkSize = Float.parseFloat(cmd.getOptionValue("chunk-size", "10.0"));

        String root = null;

        if (cmd.hasOption("parent")) {
            root = findWorkingDirectory(client, cmd.getOptionValue("parent"));
        }

        if (command.equals("get")) {
            String file;

            if (args.length < 2) {
                throw new ParseException("<file> missing");
            } else if (args.length == 2) {
                file = args[1];
            } else {
                throw new ParseException("Too many arguments");
            }

            download(client, ht, root, file, cmd.getOptionValue("output", file), verbose, chunkSize);
        } else if (command.equals("put")) {
            String file;

            if (args.length < 2) {
                throw new ParseException("<file> missing");
            } else if (args.length == 2) {
                file = args[1];
            } else {
                throw new ParseException("Too many arguments");
            }

            upload(client, file, root, cmd.getOptionValue("output", new File(file).getName()),
                    cmd.getOptionValue("mime",
                            new javax.activation.MimetypesFileTypeMap().getContentType(file)),
                    verbose, chunkSize);
        } else if (command.equals("trash")) {
            String file;

            if (args.length < 2) {
                throw new ParseException("<file> missing");
            } else if (args.length == 2) {
                file = args[1];
            } else {
                throw new ParseException("Too many arguments");
            }

            trash(client, root, file);
        } else if (command.equals("md5") || command.equals("list")) {
            if (args.length > 1) {
                throw new ParseException("Too many arguments");
            }

            list(client, root, command.equals("md5"));
        } else {
            throw new ParseException("Invalid command: " + command);
        }
    } catch (ParseException ex) {
        PrintWriter pw = new PrintWriter(System.err);
        HelpFormatter hf = new HelpFormatter();

        hf.printHelp(pw, 80, "stream2gdrive [OPTIONS] <cmd> [<options>]",
                "  Commands: get <file>, list, md5, put <file>, trash <file>.", opt, 2, 8,
                "Use '-' as <file> for standard input.");

        if (ex.getMessage() != null && !ex.getMessage().isEmpty()) {
            pw.println();
            hf.printWrapped(pw, 80, String.format("Error: %s.", ex.getMessage()));
        }

        pw.flush();
        System.exit(EX_USAGE);
    } catch (NumberFormatException ex) {
        System.err.println("Invalid decimal number: " + ex.getMessage() + ".");
        System.exit(EX_USAGE);
    } catch (IOException ex) {
        System.err.println("I/O error: " + ex.getMessage() + ".");
        System.exit(EX_IOERR);
    }
}