Example usage for com.google.api.client.googleapis.extensions.java6.auth.oauth2 GooglePromptReceiver GooglePromptReceiver

List of usage examples for com.google.api.client.googleapis.extensions.java6.auth.oauth2 GooglePromptReceiver GooglePromptReceiver

Introduction

In this page you can find the example usage for com.google.api.client.googleapis.extensions.java6.auth.oauth2 GooglePromptReceiver GooglePromptReceiver.

Prototype

GooglePromptReceiver

Source Link

Usage

From source file:com.google.cloud.genomics.api.client.GenomicsSample.java

License:Open Source License

public static void main(String[] args) throws IOException {
    CommandLine cmdLine = new CommandLine();

    try {// w  w  w  . jav  a2  s.com
        // Parse the command line
        cmdLine.setArgs(args);

        // Authorization
        BaseCommand command = cmdLine.getCommand();
        List<String> scopes = command.getScopes();
        VerificationCodeReceiver receiver = command.noLocalServer ? new GooglePromptReceiver()
                : new LocalServerReceiver();

        GenomicsFactory genomicsFactory = GenomicsFactory.builder("genomics_java_client").setScopes(scopes)
                .setUserName("user" + scopes.toString())
                .setVerificationCodeReceiver(Suppliers.ofInstance(receiver)).setRootUrl(command.rootUrl)
                .setServicePath("/").build();

        File clientSecrets = new File(command.clientSecretsFilename);
        if (!clientSecrets.exists()) {
            System.err.println("Client secrets file " + command.clientSecretsFilename + " does not exist."
                    + " Visit https://cloud.google.com/genomics/install-genomics-tools#authenticate to learn how"
                    + " to install a client_secrets.json file.  If you have installed a client_secrets.json"
                    + " in a specific location, use --client_secrets_filename <path>/client_secrets.json.");
            return;
        }

        File dataStoreFile = new File(System.getProperty("user.home"), ".store/genomics_java_client");
        command.setDataStoreFactory(new ReadableFileDataStoreFactory(dataStoreFile));
        command.handleRequest(genomicsFactory.fromClientSecretsFile(clientSecrets));

    } catch (IllegalArgumentException | ParameterException e) {
        cmdLine.printHelp(e.getMessage() + "\n", System.out);
    } catch (GoogleJsonResponseException e) {
        System.out.println("API request failed: " + BaseCommand.getErrorMessage(e));
    } catch (IllegalStateException e) {
        System.out.println(e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:com.google.cloud.genomics.gatk.common.GenomicsApiDataSource.java

License:Open Source License

private Genomics initGenomicsApi() throws GeneralSecurityException, IOException {
    LOG.info("Initializing Genomics API for " + rootUrl);
    if (!clientSecretsFilename.isEmpty()) {
        File clientSecrets = new File(clientSecretsFilename);
        if (!clientSecrets.exists()) {
            throw new IOException("Client secrets file " + clientSecretsFilename + " does not exist."
                    + " Visit https://cloud.google.com/genomics/install-genomics-tools#authenticate to learn how"
                    + " to install a client_secrets.json file.  If you have installed a client_secrets.json"
                    + " in a specific location, use --client_secrets_filename <path>/client_secrets.json.");
        }/*w w  w . j av  a  2 s .c  o  m*/
        LOG.info("Using client secrets file " + clientSecretsFilename);

        VerificationCodeReceiver receiver = noLocalServer ? new GooglePromptReceiver()
                : new LocalServerReceiver();
        GenomicsFactory genomicsFactory = GenomicsFactory.builder("genomics_java_client").setRootUrl(rootUrl)
                .setServicePath("/").setVerificationCodeReceiver(Suppliers.ofInstance(receiver)).build();
        return genomicsFactory.fromClientSecretsFile(clientSecrets);
    } else {
        final Genomics.Builder builder = new Genomics.Builder(GoogleNetHttpTransport.newTrustedTransport(),
                JacksonFactory.getDefaultInstance(), new HttpRequestInitializer() {
                    @Override
                    public void initialize(HttpRequest httpRequest) throws IOException {
                        httpRequest.setReadTimeout(20000);
                        httpRequest.setConnectTimeout(20000);
                    }
                }).setApplicationName("genomics_java_client").setRootUrl(rootUrl).setServicePath("/");
        return builder.build();
    }
}

From source file:com.google.cloud.genomics.gatk.common.GenomicsDataSourceBase.java

License:Open Source License

protected GenomicsFactory initGenomicsFactory() throws GeneralSecurityException, IOException {
    VerificationCodeReceiver receiver = noLocalServer ? new GooglePromptReceiver() : new LocalServerReceiver();
    return GenomicsFactory.builder("genomics_java_client").setRootUrl(rootUrl).setServicePath("/")
            .setVerificationCodeReceiver(Suppliers.ofInstance(receiver)).build();
}

From source file:com.google.cloud.genomics.gettingstarted.MainExample.java

License:Open Source License

public static void main(String[] args) throws IOException {
    Arguments arguments = new Arguments();
    JCommander parser = new JCommander(arguments);

    try {/*  ww w .j av  a  2s  . co  m*/
        // Parse the command line
        parser.parse(args);

        // Authorization
        VerificationCodeReceiver receiver = arguments.noLocalServer ? new GooglePromptReceiver()
                : new LocalServerReceiver();
        GenomicsFactory genomicsFactory = GenomicsFactory.builder("getting_started_java")
                .setScopes(Lists.newArrayList(GenomicsScopes.GENOMICS))
                .setVerificationCodeReceiver(Suppliers.ofInstance(receiver)).build();

        File clientSecrets = new File(arguments.clientSecretsFilename);
        if (!clientSecrets.exists()) {
            System.err.println("Client secrets file " + arguments.clientSecretsFilename + " does not exist."
                    + " Visit https://cloud.google.com/genomics/install-genomics-tools#authenticate to learn how"
                    + " to install a client_secrets.json file.  If you have installed a client_secrets.json"
                    + " in a specific location, use --client_secrets_filename <path>/client_secrets.json.");
            return;
        }
        Genomics genomics = genomicsFactory.fromClientSecretsFile(clientSecrets);

        //
        // This example gets the read bases for a sample at specific a position
        //
        String datasetId = "10473108253681171589"; // This is the 1000 Genomes dataset ID
        String sample = "NA12872";
        String referenceName = "22";
        final Long referencePosition = 51003835L;

        // 1. First find the read group set ID for the sample
        SearchReadGroupSetsRequest readsetsReq = new SearchReadGroupSetsRequest()
                .setDatasetIds(Lists.newArrayList(datasetId)).setName(sample);

        List<ReadGroupSet> readGroupSets = genomics.readgroupsets().search(readsetsReq)
                .setFields("readGroupSets(id)").execute().getReadGroupSets();
        if (readGroupSets == null || readGroupSets.size() != 1) {
            System.err
                    .println("Searching for " + sample + " didn't return the right number of read group sets");
            return;
        }

        String readGroupSetId = readGroupSets.get(0).getId();

        // 2. Once we have the read group set ID,
        // lookup the reads at the position we are interested in
        SearchReadsRequest readsReq = new SearchReadsRequest()
                .setReadGroupSetIds(Lists.newArrayList(readGroupSetId)).setReferenceName(referenceName)
                .setStart(referencePosition).setEnd(referencePosition + 1);

        List<Read> reads = genomics.reads().search(readsReq).setFields("alignments(alignment,alignedSequence)")
                .execute().getAlignments();

        Map<Character, Integer> baseCounts = Maps.newHashMap();
        for (Read read : reads) {
            int index = (int) (referencePosition - read.getAlignment().getPosition().getPosition());

            // Note: This is simplistic - the cigar should be considered for real code
            Character base = read.getAlignedSequence().charAt(index);

            if (!baseCounts.containsKey(base)) {
                baseCounts.put(base, 0);
            }
            baseCounts.put(base, baseCounts.get(base) + 1);
        }

        System.out.println(sample + " bases on " + referenceName + " at " + referencePosition + " are");
        for (Map.Entry<Character, Integer> entry : baseCounts.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }

        //
        // This example gets the variants for a sample at a specific position
        //

        // 1. First find the call set ID for the sample
        SearchCallSetsRequest callSetsReq = new SearchCallSetsRequest()
                .setVariantSetIds(Lists.newArrayList(datasetId)).setName(sample);

        List<CallSet> callSets = genomics.callsets().search(callSetsReq).setFields("callSets(id)").execute()
                .getCallSets();
        if (callSets == null || callSets.size() != 1) {
            System.err.println("Searching for " + sample + " didn't return the right number of call sets");
            return;
        }

        String callSetId = callSets.get(0).getId();

        // 2. Once we have the call set ID,
        // lookup the variants that overlap the position we are interested in
        SearchVariantsRequest variantsReq = new SearchVariantsRequest()
                .setCallSetIds(Lists.newArrayList(callSetId)).setReferenceName(referenceName)
                .setStart(referencePosition).setEnd(referencePosition + 1);

        Variant variant = genomics.variants().search(variantsReq)
                .setFields("variants(names,referenceBases,alternateBases,calls(genotype))").execute()
                .getVariants().get(0);

        String variantName = variant.getNames().get(0);

        List<String> genotype = Lists.newArrayList();
        for (Integer g : variant.getCalls().get(0).getGenotype()) {
            if (g == 0) {
                genotype.add(variant.getReferenceBases());
            } else {
                genotype.add(variant.getAlternateBases().get(g - 1));
            }
        }

        System.out.println("the called genotype is " + Joiner.on(',').join(genotype) + " at " + variantName);

    } catch (ParameterException e) {
        System.err.append(e.getMessage()).append("\n");
        parser.usage();
    } catch (IllegalStateException e) {
        System.err.println(e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:com.google.cloud.hadoop.util.CredentialFactory.java

License:Open Source License

/**
 * Initialized OAuth2 credential for the "installed application" flow; where the credential
 * typically represents an actual end user (instead of a service account), and is stored
 * as a refresh token in a local FileCredentialStore.
 * @param clientId OAuth2 client ID identifying the 'installed app'
 * @param clientSecret OAuth2 client secret
 * @param filePath full path to a ".json" file for storing the credential
 * @param scopes list of well-formed scopes desired in the credential
 * @return credential with desired scopes, possibly obtained from loading {@code filePath}.
 * @throws IOException on IO error/*from  w  w w  . ja v  a 2  s  .  c om*/
 */
public Credential getCredentialFromFileCredentialStoreForInstalledApp(String clientId, String clientSecret,
        String filePath, List<String> scopes) throws IOException, GeneralSecurityException {
    LOG.debug("getCredentialFromFileCredentialStoreForInstalledApp({}, {}, {}, {})", clientId, clientSecret,
            filePath, scopes);
    Preconditions.checkArgument(!Strings.isNullOrEmpty(clientId), "clientId must not be null or empty");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(clientSecret), "clientSecret must not be null or empty");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(filePath), "filePath must not be null or empty");
    Preconditions.checkArgument(scopes != null, "scopes must not be null or empty");

    // Initialize client secrets.
    GoogleClientSecrets.Details details = new GoogleClientSecrets.Details();
    details.setClientId(clientId);
    details.setClientSecret(clientSecret);
    GoogleClientSecrets clientSecrets = new GoogleClientSecrets();
    clientSecrets.setInstalled(details);

    // Set up file credential store.
    FileCredentialStore credentialStore = new FileCredentialStore(new File(filePath), JSON_FACTORY);

    // Set up authorization code flow.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(getHttpTransport(), JSON_FACTORY,
            clientSecrets, scopes).setCredentialStore(credentialStore)
                    .setRequestInitializer(new CredentialHttpRetryInitializer()).build();

    // Authorize access.
    return new AuthorizationCodeInstalledApp(flow, new GooglePromptReceiver()).authorize("user");
}

From source file:edu.berkeley.cs.amplab.calldiff.Main.java

License:Apache License

private static Genomics createGenomics(Optional<String> apiKey, Optional<Boolean> noLocalServer,
        Optional<String> clientSecretsFile, Optional<String> serviceAccountId, Optional<String> p12File,
        Optional<String> rootUrl, Optional<Integer> timeout) throws GeneralSecurityException, IOException {
    boolean useApiKey = apiKey.isPresent(), useClientSecrets = clientSecretsFile.isPresent(),
            useServiceAccount = serviceAccountId.isPresent() && p12File.isPresent();

    VerificationCodeReceiver receiver = (noLocalServer.isPresent() && noLocalServer.get() == true)
            ? new GooglePromptReceiver()
            : new LocalServerReceiver();

    GenomicsFactory.Builder builder = GenomicsFactory.builder("calldiff")
            .setVerificationCodeReceiver(Suppliers.ofInstance(receiver));

    rootUrl.ifPresent(url -> builder.setRootUrl(url));
    timeout.ifPresent(ms -> builder.setConnectTimeout(ms).setReadTimeout(ms));

    GenomicsFactory factory = builder.build();
    if (!useApiKey && !useClientSecrets && !useServiceAccount) {
        throw new IllegalStateException(
                "Specify one of { --api_key, --client_secrets_file, " + "(--service_account_id, --p12_file) }");
    } else if (useApiKey && !useClientSecrets && !useServiceAccount) {
        return factory.fromApiKey(apiKey.get());
    } else if (!useApiKey && useClientSecrets && !useServiceAccount) {
        return factory.fromClientSecretsFile(new File(clientSecretsFile.get()));
    } else if (!useApiKey && !useClientSecrets && useServiceAccount) {
        return factory.fromServiceAccount(serviceAccountId.get(), new File(p12File.get()));
    }//from  w w w . jav  a  2s . c o m
    throw new IllegalStateException("Specify only one of { --api_key, --client_secrets_file, "
            + "(--service_account_id, --p12_file) }");
}

From source file:me.tango.devops.google.CredentialsManager.java

License:Apache License

/**
 * Authorizes the installed application to access user's protected data.
 *///  w  ww.  j  av a 2s  .c o  m
public static Credential authorize() throws IOException {
    // Load client secrets.
    final byte[] bytes = Files.toByteArray(new File(clientSecretFile));
    final GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
            new InputStreamReader(new ByteArrayInputStream(bytes)));
    if (clientSecrets.getDetails().getClientId() == null
            || clientSecrets.getDetails().getClientSecret() == null) {
        throw new IllegalStateException("client_secrets not well formed.");
    }

    // Set up authorization code flow.
    // Ask for only the permissions you need. Asking for more permissions will
    // reduce the number of users who finish the process for giving you access
    // to their accounts. It will also increase the amount of effort you will
    // have to spend explaining to users what you are doing with their data.
    // Here we are listing all of the available scopes. You should remove scopes
    // that you are not actually using.
    final Set<String> scopes = new HashSet<String>();
    scopes.add(StorageScopes.DEVSTORAGE_FULL_CONTROL);
    scopes.add(StorageScopes.DEVSTORAGE_READ_ONLY);
    scopes.add(StorageScopes.DEVSTORAGE_READ_WRITE);

    final GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport,
            JSON_FACTORY, clientSecrets, scopes).setDataStoreFactory(dataStoreFactory).build();
    // Authorize.
    final VerificationCodeReceiver receiver = AUTH_LOCAL_WEBSERVER ? new LocalServerReceiver()
            : new GooglePromptReceiver();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}

From source file:name.herve.gcms.CalendarWrapper.java

License:Open Source License

private Credential authorize() throws Exception {
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory,
            new InputStreamReader(getClass().getResourceAsStream("/client_secrets.json")));
    if (clientSecrets.getDetails().getClientId().startsWith("Enter")
            || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
        System.out.println("Enter Client ID and Secret from https://code.google.com/apis/console/?api=plus "
                + "into plus-cmdline-sample/src/main/resources/client_secrets.json");
        System.exit(1);//from  ww  w  .java  2 s  . c o  m
    }
    FileCredentialStore credentialStore = new FileCredentialStore(
            new File(System.getProperty("user.home"), ".credentials/calendar.json"), jsonFactory);
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory,
            clientSecrets, Collections.singleton(CalendarScopes.CALENDAR)).setCredentialStore(credentialStore)
                    .build();
    return new AuthorizationCodeInstalledApp(flow, new GooglePromptReceiver()).authorize("user");
}

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  . ja v  a 2  s.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);
    }
}

From source file:org.ut.biolab.medsavant.app.google.original.GenomicsSample.java

License:Open Source License

private static Credential exchangeCode() throws IOException {
    GoogleAuthorizationCodeFlow flow = getFlow();
    return new AuthorizationCodeInstalledApp(flow, new GooglePromptReceiver())
            .authorize(System.getProperty("user.name"));
}