List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleCredential createScoped
@Beta
public GoogleCredential createScoped(Collection<String> scopes)
From source file:com.dataartisans.flink.dataflow.util.PortableConfiguration.java
License:Apache License
public static Pubsub createPubsubClient(HttpTransport httpTransport, JsonFactory jsonFactory) throws IOException { Preconditions.checkNotNull(httpTransport); Preconditions.checkNotNull(jsonFactory); GoogleCredential credential = GoogleCredential.getApplicationDefault(httpTransport, jsonFactory); // In some cases, you need to add the scope explicitly. if (credential.createScopedRequired()) { credential = credential.createScoped(PubsubScopes.all()); }/*from www .ja va2s.com*/ // Please use custom HttpRequestInitializer for automatic // retry upon failures. We provide a simple reference // implementation in the "Retry Handling" section. HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential); return new Pubsub.Builder(httpTransport, jsonFactory, initializer).build(); }
From source file:com.example.bigquery.LabelsSample.java
License:Apache License
/** * Add or modify a label on a dataset./* ww w . j av a2s . c o m*/ * * <p>See <a href="https://cloud.google.com/bigquery/docs/labeling-datasets">the BigQuery * documentation</a>. */ public static void labelDataset(String projectId, String datasetId, String labelKey, String labelValue) throws IOException { // Authenticate requests using Google Application Default credentials. GoogleCredential credential = GoogleCredential.getApplicationDefault(); credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/bigquery")); // Get a new access token. // Note that access tokens have an expiration. You can reuse a token rather than requesting a // new one if it is not yet expired. credential.refreshToken(); String accessToken = credential.getAccessToken(); // Set the content of the request. Dataset dataset = new Dataset(); dataset.addLabel(labelKey, labelValue); HttpContent content = new JsonHttpContent(JSON_FACTORY, dataset); // Send the request to the BigQuery API. String urlFormat = "https://www.googleapis.com/bigquery/v2/projects/%s/datasets/%s" + "?fields=labels&access_token=%s"; GenericUrl url = new GenericUrl(String.format(urlFormat, projectId, datasetId, accessToken)); HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(); HttpRequest request = requestFactory.buildPostRequest(url, content); request.setParser(JSON_FACTORY.createJsonObjectParser()); // Workaround for transports which do not support PATCH requests. // See: http://stackoverflow.com/a/32503192/101923 request.setHeaders(new HttpHeaders().set("X-HTTP-Method-Override", "PATCH")); HttpResponse response = request.execute(); // Check for errors. if (response.getStatusCode() != 200) { throw new RuntimeException(response.getStatusMessage()); } Dataset responseDataset = response.parseAs(Dataset.class); System.out.printf("Updated label \"%s\" with value \"%s\"\n", labelKey, responseDataset.getLabels().get(labelKey)); }
From source file:com.example.bigquery.LabelsSample.java
License:Apache License
/** * Add or modify a label on a table.// ww w.j av a 2 s . c om * * <p>See <a href="https://cloud.google.com/bigquery/docs/labeling-datasets">the BigQuery * documentation</a>. */ public static void labelTable(String projectId, String datasetId, String tableId, String labelKey, String labelValue) throws IOException { // Authenticate requests using Google Application Default credentials. GoogleCredential credential = GoogleCredential.getApplicationDefault(); credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/bigquery")); // Get a new access token. // Note that access tokens have an expiration. You can reuse a token rather than requesting a // new one if it is not yet expired. credential.refreshToken(); String accessToken = credential.getAccessToken(); // Set the content of the request. Table table = new Table(); table.addLabel(labelKey, labelValue); HttpContent content = new JsonHttpContent(JSON_FACTORY, table); // Send the request to the BigQuery API. String urlFormat = "https://www.googleapis.com/bigquery/v2/projects/%s/datasets/%s/tables/%s" + "?fields=labels&access_token=%s"; GenericUrl url = new GenericUrl(String.format(urlFormat, projectId, datasetId, tableId, accessToken)); HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(); HttpRequest request = requestFactory.buildPostRequest(url, content); request.setParser(JSON_FACTORY.createJsonObjectParser()); // Workaround for transports which do not support PATCH requests. // See: http://stackoverflow.com/a/32503192/101923 request.setHeaders(new HttpHeaders().set("X-HTTP-Method-Override", "PATCH")); HttpResponse response = request.execute(); // Check for errors. if (response.getStatusCode() != 200) { throw new RuntimeException(response.getStatusMessage()); } Table responseTable = response.parseAs(Table.class); System.out.printf("Updated label \"%s\" with value \"%s\"\n", labelKey, responseTable.getLabels().get(labelKey)); }
From source file:com.example.CryptFile.java
License:Apache License
/** * Creates an authorized CloudKMS client service using Application Default Credentials. * * @return an authorized CloudKMS client * @throws IOException if there's an error getting the default credentials. *///from w ww . j a va2s.c o m public static CloudKMS createAuthorizedClient() throws IOException { // Create the credential HttpTransport transport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); // Authorize the client using Application Default Credentials // @see https://g.co/dv/identity/protocols/application-default-credentials GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory); // Depending on the environment that provides the default credentials (e.g. Compute Engine, App // Engine), the credentials may require us to specify the scopes we need explicitly. // Check for this case, and inject the scope if required. if (credential.createScopedRequired()) { credential = credential.createScoped(CloudKMSScopes.all()); } return new CloudKMS.Builder(transport, jsonFactory, credential).setApplicationName("CloudKMS CryptFile") .build(); }
From source file:com.example.Quickstart.java
License:Apache License
/** * Creates an authorized CloudKMS client service using Application Default Credentials. * * @return an authorized CloudKMS client * @throws IOException if there's an error getting the default credentials. *///from w w w. j av a2 s. c om public static CloudKMS createAuthorizedClient() throws IOException { // Create the credential HttpTransport transport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); // Authorize the client using Application Default Credentials // @see https://g.co/dv/identity/protocols/application-default-credentials GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory); // Depending on the environment that provides the default credentials (e.g. Compute Engine, App // Engine), the credentials may require us to specify the scopes we need explicitly. // Check for this case, and inject the scope if required. if (credential.createScopedRequired()) { credential = credential.createScoped(CloudKMSScopes.all()); } return new CloudKMS.Builder(transport, jsonFactory, credential).setApplicationName("CloudKMS snippets") .build(); }
From source file:com.gcloud.poc.DataFlow_File2File.java
License:Apache License
private static Storage getService() throws IOException, GeneralSecurityException { if (null == storageService) { GoogleCredential credential = GoogleCredential.getApplicationDefault(); // Depending on the environment that provides the default credentials (e.g. Compute Engine, // App Engine), the credentials may require us to specify the scopes we need explicitly. // Check for this case, and inject the Cloud Storage scope if required. if (credential.createScopedRequired()) { credential = credential.createScoped(StorageScopes.all()); }/*from w w w . ja v a 2s .co m*/ HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); storageService = new Storage.Builder(httpTransport, JSON_FACTORY, credential) .setApplicationName(APPLICATION_NAME).build(); } return storageService; }
From source file:com.google.cloud.bigquery.samples.GettingStarted.java
License:Apache License
/** * Creates an authorized Bigquery client service using Application Default Credentials. * * @return an authorized Bigquery client * @throws IOException if there's an error getting the default credentials. *///w w w . j a v a 2s.c o m public static Bigquery createAuthorizedClient() throws IOException { // Create the credential HttpTransport transport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory); // Depending on the environment that provides the default credentials (e.g. Compute Engine, App // Engine), the credentials may require us to specify the scopes we need explicitly. // Check for this case, and inject the Bigquery scope if required. if (credential.createScopedRequired()) { credential = credential.createScoped(BigqueryScopes.all()); } return new Bigquery.Builder(transport, jsonFactory, credential).setApplicationName("Bigquery Samples") .build(); }
From source file:com.google.cloud.crypto.tink.subtle.ServiceAccountGcpCredentialFactory.java
License:Apache License
@Override public GoogleCredential createCredential(String kmsKeyUri /* unused */) throws IOException { GoogleCredential cred; if (serviceAccount.isPresent()) { cred = createServiceAccountGoogleCredential(serviceAccount.get()); } else {/*from ww w.jav a 2 s . co m*/ cred = GoogleCredential.getApplicationDefault(); } cred = cred.createScoped(GcpScopes.all()); return cred; }
From source file:com.google.cloud.crypto.tink.tinkey.TinkeyUtil.java
License:Apache License
/** * @return a {@code GoogleCredential}, using the service account in {@code credentialFile}. * If {@code credentialFile} is null, returns an * <a href="https://g.co/dv/identity/protocols/application-default-credentials">application * default credential</a>./*from w ww . j a v a 2 s . c om*/ */ public static GoogleCredential readGoogleCredential(File credentialFile) throws IOException { GoogleCredential cred; if (credentialFile != null) { byte[] credBytes = Files.readAllBytes(credentialFile.toPath()); cred = GoogleCredential.fromStream(new ByteArrayInputStream(credBytes)); } else { cred = GoogleCredential.getApplicationDefault(); } // Depending on the environment that provides the default credentials (e.g. Compute Engine, App // Engine), the credentials may require us to specify the scopes we need explicitly. // Check for this case, and inject the scope if required. if (cred.createScopedRequired()) { cred = cred.createScoped(CloudKMSScopes.all()); } return cred; }
From source file:com.google.cloud.dataflow.examples.complete.game.injector.InjectorUtils.java
License:Apache License
/** * Builds a new Pubsub client and returns it. *///from ww w . j a v a 2 s . com public static Pubsub getClient(final HttpTransport httpTransport, final JsonFactory jsonFactory) throws IOException { Preconditions.checkNotNull(httpTransport); Preconditions.checkNotNull(jsonFactory); GoogleCredential credential = GoogleCredential.getApplicationDefault(httpTransport, jsonFactory); if (credential.createScopedRequired()) { credential = credential.createScoped(PubsubScopes.all()); } if (credential.getClientAuthentication() != null) { System.out.println("\n***Warning! You are not using service account credentials to " + "authenticate.\nYou need to use service account credentials for this example," + "\nsince user-level credentials do not have enough pubsub quota,\nand so you will run " + "out of PubSub quota very quickly.\nSee " + "https://developers.google.com/identity/protocols/application-default-credentials."); System.exit(1); } HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential); return new Pubsub.Builder(httpTransport, jsonFactory, initializer).setApplicationName(APP_NAME).build(); }