/** Builds a new Pubsub client and returns it. */ public static Pubsub getClient(final HttpTransport httpTransport, final JsonFactory jsonFactory) throws IOException { checkNotNull(httpTransport); 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(); }
/** * Setup authorization for local app based on private key. * See <a href="https://cloud.google.com/pubsub/configure">cloud.google.com/pubsub/configure</a> */ private void createClient(String private_key_file, String email) throws IOException, GeneralSecurityException { HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport(); GoogleCredential credential = new GoogleCredential.Builder() .setTransport(transport) .setJsonFactory(JSON_FACTORY) .setServiceAccountScopes(PubsubScopes.all()) .setServiceAccountId(email) .setServiceAccountPrivateKeyFromP12File(new File(private_key_file)) .build(); // Please use custom HttpRequestInitializer for automatic retry upon failures. // HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential); pubsub = new Pubsub.Builder(transport, JSON_FACTORY, credential) .setApplicationName("eaipubsub") .build(); }
private static GoogleCredentials createApplicationDefaultCredential() throws IOException { final MockTokenServerTransport transport = new MockTokenServerTransport(); transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN); // Set the GOOGLE_APPLICATION_CREDENTIALS environment variable for application-default // credentials. This requires us to write the credentials to the location specified by the // environment variable. File credentialsFile = File.createTempFile("google-test-credentials", "json"); PrintWriter writer = new PrintWriter(Files.newBufferedWriter(credentialsFile.toPath(), UTF_8)); writer.print(ServiceAccount.EDITOR.asString()); writer.close(); Map<String, String> environmentVariables = ImmutableMap.<String, String>builder() .put("GOOGLE_APPLICATION_CREDENTIALS", credentialsFile.getAbsolutePath()) .build(); TestUtils.setEnvironmentVariables(environmentVariables); credentialsFile.deleteOnExit(); return GoogleCredentials.getApplicationDefault(new HttpTransportFactory() { @Override public HttpTransport create() { return transport; } }); }
private static GoogleCredentials createRefreshTokenCredential() throws IOException { final MockTokenServerTransport transport = new MockTokenServerTransport(); transport.addClient(CLIENT_ID, CLIENT_SECRET); transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); Map<String, Object> secretJson = new HashMap<>(); secretJson.put("client_id", CLIENT_ID); secretJson.put("client_secret", CLIENT_SECRET); secretJson.put("refresh_token", REFRESH_TOKEN); secretJson.put("type", "authorized_user"); InputStream refreshTokenStream = new ByteArrayInputStream(JSON_FACTORY.toByteArray(secretJson)); return UserCredentials.fromStream(refreshTokenStream, new HttpTransportFactory() { @Override public HttpTransport create() { return transport; } }); }
/** * Ensures initialization of Google Application Default Credentials. Any test that depends on * ADC should consider this as a fixture, and invoke it before hand. Since ADC are initialized * once per JVM, this makes sure that all dependent tests get the same ADC instance, and * can reliably reason about the tokens minted using it. */ public static synchronized GoogleCredentials getApplicationDefaultCredentials() throws IOException { if (defaultCredentials != null) { return defaultCredentials; } final MockTokenServerTransport transport = new MockTokenServerTransport(); transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), TEST_ADC_ACCESS_TOKEN); File serviceAccount = new File("src/test/resources/service_accounts", "editor.json"); Map<String, String> environmentVariables = ImmutableMap.<String, String>builder() .put("GOOGLE_APPLICATION_CREDENTIALS", serviceAccount.getAbsolutePath()) .build(); setEnvironmentVariables(environmentVariables); defaultCredentials = GoogleCredentials.getApplicationDefault(new HttpTransportFactory() { @Override public HttpTransport create() { return transport; } }); return defaultCredentials; }
protected static HttpTransport configureMock() { return new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, final String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); response.setStatusCode(200); response.setContentType(Json.MEDIA_TYPE); if (url.startsWith(GCE_METADATA_URL)) { logger.info("--> Simulate GCE Auth/Metadata response for [{}]", url); response.setContent(readGoogleInternalJsonResponse(url)); } else { logger.info("--> Simulate GCE API response for [{}]", url); response.setContent(readGoogleApiJsonResponse(url)); } return response; } }; } }; }
/** * Builds a new Pubsub client and returns it. */ public static Pubsub getClient(final HttpTransport httpTransport, final JsonFactory jsonFactory) throws IOException { checkNotNull(httpTransport); 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(); }
/** * Return the Projects api object used for accessing the Cloud Resource Manager Projects API. * @return Projects api object used for accessing the Cloud Resource Manager Projects API * @throws GeneralSecurityException Thrown if there's a permissions error. * @throws IOException Thrown if there's an IO error initializing the API object. */ public static synchronized Projects getProjectsApiStub() throws GeneralSecurityException, IOException { if (projectApiStub != null) { return projectApiStub; } HttpTransport transport; GoogleCredential credential; JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); transport = GoogleNetHttpTransport.newTrustedTransport(); credential = GoogleCredential.getApplicationDefault(transport, jsonFactory); if (credential.createScopedRequired()) { Collection<String> scopes = CloudResourceManagerScopes.all(); credential = credential.createScoped(scopes); } projectApiStub = new CloudResourceManager .Builder(transport, jsonFactory, credential) .build() .projects(); return projectApiStub; }
/** * Get the API stub for accessing the IAM Service Accounts API. * @return ServiceAccounts api stub for accessing the IAM Service Accounts API. * @throws IOException Thrown if there's an IO error initializing the api connection. * @throws GeneralSecurityException Thrown if there's a security error * initializing the connection. */ public static ServiceAccounts getServiceAccountsApiStub() throws IOException, GeneralSecurityException { if (serviceAccountsApiStub == null) { HttpTransport transport; GoogleCredential credential; JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); transport = GoogleNetHttpTransport.newTrustedTransport(); credential = GoogleCredential.getApplicationDefault(transport, jsonFactory); if (credential.createScopedRequired()) { Collection<String> scopes = IamScopes.all(); credential = credential.createScoped(scopes); } serviceAccountsApiStub = new Iam.Builder(transport, jsonFactory, credential) .build() .projects() .serviceAccounts(); } return serviceAccountsApiStub; }
@VisibleForTesting ServiceConfigSupplier( Environment environment, HttpTransport httpTransport, JsonFactory jsonFactory, final GoogleCredential credential) { this.environment = environment; HttpRequestInitializer requestInitializer = new HttpRequestInitializer() { @Override public void initialize(HttpRequest request) throws IOException { request.setThrowExceptionOnExecuteError(false); credential.initialize(request); } }; this.serviceManagement = new ServiceManagement.Builder(httpTransport, jsonFactory, requestInitializer) .setApplicationName("Endpoints Frameworks Java") .build(); }
@VisibleForTesting static ReportedPlatforms getPlatformFromEnvironment( Map<String, String> env, Properties properties, HttpTransport transport) { if (env.containsKey("KUBERNETES_SERVICE_HOST")) { return ReportedPlatforms.GKE; } boolean hasMetadataServer = hasMetadataServer(transport); String gaeEnvironment = properties.getProperty("com.google.appengine.runtime.environment"); boolean onGae = gaeEnvironment != null && gaeEnvironment.startsWith("Production"); if (hasMetadataServer && env.containsKey("GAE_SERVICE")) { return ReportedPlatforms.GAE_FLEX; } else if (hasMetadataServer) { return ReportedPlatforms.GCE; } else if (onGae) { return ReportedPlatforms.GAE_STANDARD; } if (gaeEnvironment != null && gaeEnvironment.startsWith("Development")) { return ReportedPlatforms.DEVELOPMENT; } return ReportedPlatforms.UNKNOWN; }
@Test public void testSupplyJwksFromX509Certificate() throws NoSuchAlgorithmException, JsonProcessingException { RsaJsonWebKey rsaJsonWebKey = TestUtils.generateRsaJsonWebKey("key-id"); String cert = TestUtils.generateX509Cert(rsaJsonWebKey); String keyId = "key-id"; String json = OBJECT_WRITER.writeValueAsString(ImmutableMap.of(keyId, cert)); HttpTransport httpTransport = new TestingHttpTransport(json, null); DefaultJwksSupplier jwksSupplier = new DefaultJwksSupplier(httpTransport.createRequestFactory(), keyUriSupplier); JsonWebKeySet jsonWebKeySet = jwksSupplier.supply(ISSUER); JsonWebKey jsonWebKey = Iterables.getOnlyElement(jsonWebKeySet.getJsonWebKeys()); assertEquals(keyId, jsonWebKey.getKeyId()); assertKeysEqual(rsaJsonWebKey.getPublicKey(), jsonWebKey.getKey()); }
@Before public void before() throws Exception { when(subfactory.create( anyString(), any(HttpTransport.class), any(JsonFactory.class), any(HttpRequestInitializer.class))) .thenReturn(bigquery); when(bigquery.datasets()).thenReturn(bigqueryDatasets); when(bigqueryDatasets.insert(eq("Project-Id"), any(Dataset.class))) .thenReturn(bigqueryDatasetsInsert); when(bigquery.tables()).thenReturn(bigqueryTables); when(bigqueryTables.insert(eq("Project-Id"), any(String.class), any(Table.class))) .thenReturn(bigqueryTablesInsert); factory = new BigqueryFactory(); factory.subfactory = subfactory; factory.bigquerySchemas = new ImmutableMap.Builder<String, ImmutableList<TableFieldSchema>>() .put( "Table-Id", ImmutableList.of(new TableFieldSchema().setName("column1").setType(STRING.name()))) .put( "Table2", ImmutableList.of(new TableFieldSchema().setName("column1").setType(STRING.name()))) .build(); }
@Override public DataprocHadoopRunner build() { CredentialProvider credentialProvider = Optional.ofNullable(this.credentialProvider) .orElseGet(DefaultCredentialProvider::new); try { final HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); final JsonFactory jsonFactory = new JacksonFactory(); final GoogleCredential credentials = credentialProvider.getCredential(SCOPES); final Dataproc dataproc = new Dataproc.Builder(httpTransport, jsonFactory, credentials) .setApplicationName(APPLICATION_NAME).build(); final Storage storage = new Storage.Builder(httpTransport, jsonFactory, credentials) .setApplicationName(APPLICATION_NAME).build(); final DataprocClient dataprocClient = new DataprocClient(dataproc, storage, projectId, clusterId, clusterProperties); return new DataprocHadoopRunnerImpl(dataprocClient); } catch (Throwable e) { throw Throwables.propagate(e); } }
/** * Return a Client that is mocked to return the given HTTP response. * * @param httpResponse The full HTTP response data * @return The Client instance */ public Client mockClient(final String httpResponse) { Client client = new Client(); HttpTransport transport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); return mockResponse(response, httpResponse); } }; } }; client.setTransport(transport); return client; }
/** * Get a Google Compute Engine client object. * @param userEmail The service account's client email. * @param privateKey The service account's private key. * @param scopes The scopes used in the compute client object. * @param applicationName The application name. * @return The created Compute Engine client object. * @throws GeneralSecurityException Exception when creating http transport. * @throws IOException Exception when creating http transport. */ public static Compute getGoogleComputeClient(String userEmail, String privateKey, List<String> scopes, String applicationName) throws GeneralSecurityException, IOException { HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); GoogleCredential credential = new GoogleCredential.Builder() .setTransport(httpTransport) .setJsonFactory(JSON_FACTORY) .setServiceAccountId(userEmail) .setServiceAccountScopes(scopes) .setServiceAccountPrivateKey(privateKeyFromPkcs8(privateKey)) .build(); return new Compute.Builder(httpTransport, JSON_FACTORY, credential) .setApplicationName(applicationName) .build(); }
/** * Create a Sensor API client instance * @return * @throws IOException * @throws GeneralSecurityException */ private static Sensor getSensorEndpoint() throws IOException { CmdLineAuthenticationProvider provider = new CmdLineAuthenticationProvider(); // see https://developers.google.com/api-client-library/java/ provider.setClientSecretsFile("client_secret.json"); provider.setScopes(SCOPES); // get the oauth credentials Credential credential = provider.authorize(); // initialize the transport HttpTransport httpTransport; try { httpTransport = GoogleNetHttpTransport.newTrustedTransport(); } catch (GeneralSecurityException e) { log.log(Level.SEVERE, "failed to create transport", e); throw new IOException(e); } return new Sensor.Builder(httpTransport, JacksonFactory.getDefaultInstance(), credential) .setApplicationName(APP_NAME).setRootUrl(DEFAULT_ROOT_URL).build(); }
/** * Provides a GoogleCredential that will connect to GAE using delegated admin access. This is * needed for API calls requiring domain admin access to the relevant GAFYD using delegated * scopes, e.g. the Directory API and the Groupssettings API. * * <p>Note that you must call {@link GoogleCredential#createScoped} on the credential provided * by this method first before using it, as this does not and cannot set the scopes, and a * credential without scopes doesn't actually provide access to do anything. */ @Provides @Singleton @Named("delegatedAdmin") static GoogleCredential provideDelegatedAdminGoogleCredential( GoogleCredential googleCredential, HttpTransport httpTransport, @Config("gSuiteAdminAccountEmailAddress") String gSuiteAdminAccountEmailAddress) { return new GoogleCredential.Builder() .setTransport(httpTransport) .setJsonFactory(googleCredential.getJsonFactory()) .setServiceAccountId(googleCredential.getServiceAccountId()) .setServiceAccountPrivateKey(googleCredential.getServiceAccountPrivateKey()) // Set the scopes to empty because the default value is null, which throws an NPE in the // GoogleCredential constructor. We don't yet know the actual scopes to use here, and it // is thus the responsibility of every user of a delegated admin credential to call // createScoped() on it first to get the version with the correct scopes set. .setServiceAccountScopes(ImmutableSet.of()) .setServiceAccountUser(gSuiteAdminAccountEmailAddress) .build(); }
private static SQLAdmin createAdminApiClient(Credential credential) { HttpTransport httpTransport; try { httpTransport = GoogleNetHttpTransport.newTrustedTransport(); } catch (GeneralSecurityException | IOException e) { throw new RuntimeException("Unable to initialize HTTP transport", e); } String rootUrl = System.getProperty(API_ROOT_URL_PROPERTY); String servicePath = System.getProperty(API_SERVICE_PATH_PROPERTY); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); SQLAdmin.Builder adminApiBuilder = new Builder(httpTransport, jsonFactory, credential) .setApplicationName("Cloud SQL Java Socket Factory"); if (rootUrl != null) { logTestPropertyWarning(API_ROOT_URL_PROPERTY); adminApiBuilder.setRootUrl(rootUrl); } if (servicePath != null) { logTestPropertyWarning(API_SERVICE_PATH_PROPERTY); adminApiBuilder.setServicePath(servicePath); } return adminApiBuilder.build(); }
/** Returns a valid GoogleJsonResponseException for the given status code and error message. */ private GoogleJsonResponseException makeResponseException( final int statusCode, final String message) throws Exception { HttpTransport transport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); response.setStatusCode(statusCode); response.setContentType(Json.MEDIA_TYPE); response.setContent(String.format( "{\"error\":{\"code\":%d,\"message\":\"%s\",\"domain\":\"global\"," + "\"reason\":\"duplicate\"}}", statusCode, message)); return response; }}; }}; HttpRequest request = transport.createRequestFactory() .buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL) .setThrowExceptionOnExecuteError(false); return GoogleJsonResponseException.from(new JacksonFactory(), request.execute()); }
@Before public void setup() throws Exception { when(bigqueryFactory.create(anyString(), anyString(), anyString())).thenReturn(bigquery); when(bigqueryFactory.create( anyString(), Matchers.any(HttpTransport.class), Matchers.any(JsonFactory.class), Matchers.any(HttpRequestInitializer.class))) .thenReturn(bigquery); when(bigquery.tabledata()).thenReturn(tabledata); when(tabledata.insertAll( anyString(), anyString(), anyString(), Matchers.any(TableDataInsertAllRequest.class))).thenReturn(insertAll); action = new MetricsExportAction(); action.bigqueryFactory = bigqueryFactory; action.insertId = "insert id"; action.parameters = parameters; action.projectId = "project id"; action.tableId = "eppMetrics"; }
private HttpRequest constructHttpRequest(final String content) throws IOException { HttpTransport transport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse result = new MockLowLevelHttpResponse(); result.setContentType("application/json"); result.setContent(content); return result; } }; } }; return transport.createRequestFactory().buildGetRequest(new GenericUrl("https://google.com")) .setParser(new JsonObjectParser(new JacksonFactory())); }
private Sheets authorize() { try { InputStream in = new FileInputStream(new File(System.getenv("GOOGLE_OATH2_CREDENTIALS"))); JsonFactory factory = new JacksonFactory(); GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(factory, new InputStreamReader(in, Charset.defaultCharset())); HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport(); FileDataStoreFactory dataStoreFactory = new FileDataStoreFactory(new File(dataStoreDirectory)); List<String> scopes = Collections.singletonList(SheetsScopes.SPREADSHEETS); GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(transport, factory, clientSecrets, scopes) .setAccessType("offline") .setDataStoreFactory(dataStoreFactory) .build(); Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); return new Sheets.Builder(transport, factory, credential) .setApplicationName(APPLICATION_NAME) .build(); } catch (Exception e) { return null; } }
@Before public void setUp() { MockitoAnnotations.initMocks(this); HttpTransport lowLevelTransport = new HttpTransport() { @Override protected LowLevelHttpRequest buildRequest(String method, String url) throws IOException { return mockLowLevelRequest; } }; // Retry initializer will pass through to credential, since we can have // only a single HttpRequestInitializer, and we use multiple Credential // types in the SDK, not all of which allow for retry configuration. RetryHttpRequestInitializer initializer = new RetryHttpRequestInitializer( new MockNanoClock(), new Sleeper() { @Override public void sleep(long millis) throws InterruptedException {} }, Arrays.asList(418 /* I'm a teapot */), mockHttpResponseInterceptor); storage = new Storage.Builder(lowLevelTransport, jsonFactory, initializer) .setApplicationName("test").build(); }
private static GoogleCredential loadKmsCredential(HttpTransport transport, JsonFactory factory, String jsonPath) throws IOException { GoogleCredential credential; if (!jsonPath.isEmpty()) { FileInputStream stream = new FileInputStream(jsonPath); credential = GoogleCredential.fromStream(stream, transport, factory); log.info("Loaded kms credentials from " + jsonPath); } else { log.info("Using kms default application credentials."); credential = GoogleCredential.getApplicationDefault(); } if (credential.createScopedRequired()) { credential = credential.createScoped(CloudKMSScopes.all()); } return credential; }
@Provides static Dns provideDns( HttpTransport transport, JsonFactory jsonFactory, Function<Set<String>, ? extends HttpRequestInitializer> credential, @Config("projectId") String projectId, @Config("cloudDnsRootUrl") Optional<String> rootUrl, @Config("cloudDnsServicePath") Optional<String> servicePath) { Dns.Builder builder = new Dns.Builder(transport, jsonFactory, credential.apply(DnsScopes.all())) .setApplicationName(projectId); rootUrl.ifPresent(builder::setRootUrl); servicePath.ifPresent(builder::setServicePath); return builder.build(); }
/** * Constructs a BigqueryConnection with default settings. * * <p>We use Bigquery to generate ICANN monthly reports via large aggregate SQL queries. * * @see ActivityReportingQueryBuilder * @see google.registry.tools.BigqueryParameters for justifications of defaults. */ @Provides static BigqueryConnection provideBigqueryConnection(HttpTransport transport) { try { GoogleCredential credential = GoogleCredential .getApplicationDefault(transport, new JacksonFactory()); BigqueryConnection connection = new BigqueryConnection.Builder() .setExecutorService(MoreExecutors.newDirectExecutorService()) .setCredential(credential.createScoped(ImmutableList.of(BIGQUERY_SCOPE))) .setDatasetId(ICANN_REPORTING_DATA_SET) .setOverwrite(true) .setPollInterval(Duration.standardSeconds(1)) .build(); connection.initialize(); return connection; } catch (Throwable e) { throw new RuntimeException("Could not initialize BigqueryConnection!", e); } }
@Override public void initialise(UpdatableInjectionContext injectionContext) { super.initialise(injectionContext); // for gmail API as the setup stores the creds established at setup time in DS injectionContext.inject(AppEngineDataStoreFactory.getDefaultInstance()).as(DataStoreFactory.class); injectionContext.inject(UrlFetchTransport.getDefaultInstance()).as(HttpTransport.class); Class<? extends Mailer> mailerClass = Environment.is(Environment.DEV) ? LoggingMailer.class : GmailMailer.class; injectionContext.inject(mailerClass).as(Mailer.class); }
private static HttpTransportFactory wrap(final HttpTransport transport) { checkNotNull(transport, "HttpTransport must not be null"); return new HttpTransportFactory() { @Override public HttpTransport create() { return transport; } }; }
private FirebaseInstanceId(FirebaseApp app) { HttpTransport httpTransport = app.getOptions().getHttpTransport(); GoogleCredentials credentials = ImplFirebaseTrampolines.getCredentials(app); this.app = app; this.requestFactory = httpTransport.createRequestFactory( new HttpCredentialsAdapter(credentials)); this.jsonFactory = app.getOptions().getJsonFactory(); this.projectId = ImplFirebaseTrampolines.getProjectId(app); checkArgument(!Strings.isNullOrEmpty(projectId), "Project ID is required to access instance ID service. Use a service account credential or " + "set the project ID explicitly via FirebaseOptions. Alternatively you can also " + "set the project ID via the GCLOUD_PROJECT environment variable."); }
private static GoogleCredentials createCertificateCredential() throws IOException { final MockTokenServerTransport transport = new MockTokenServerTransport(); transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN); return ServiceAccountCredentials.fromStream(ServiceAccount.EDITOR.asStream(), new HttpTransportFactory() { @Override public HttpTransport create() { return transport; } }); }
private static Monitoring createAuthorizedMonitoringClient() throws IOException { // Grab the Application Default Credentials from the environment. // Generate these with 'gcloud beta auth application-default login' GoogleCredential credential = GoogleCredential.getApplicationDefault().createScoped(MonitoringScopes.all()); // Create and return the CloudMonitoring service object HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); return new Monitoring.Builder(httpTransport, jsonFactory, credential) .setApplicationName("Monitoring Sample") .build(); }
private boolean isClusterCollected(SpydraArgument arguments) throws IOException, GeneralSecurityException { GoogleCredential credential = GoogleCredential.fromStream( new ByteArrayInputStream(gcpUtils.credentialJsonFromEnv().getBytes())); if (credential.createScopedRequired()) { credential = credential.createScoped( Collections.singletonList("https://www.googleapis.com/auth/cloud-platform")); } HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); Dataproc dataprocService = new Dataproc.Builder(httpTransport, jsonFactory, credential) .setApplicationName("Google Cloud Platform Sample") .build(); Dataproc.Projects.Regions.Clusters.List request = dataprocService.projects().regions().clusters().list( arguments.getCluster().getOptions().get(SpydraArgument.OPTION_PROJECT), arguments.getRegion()); ListClustersResponse response; do { response = request.execute(); if (response.getClusters() == null) continue; String clusterName = arguments.getCluster().getName(); for (Cluster cluster : response.getClusters()) { if (cluster.getClusterName().equals(clusterName)) { String status = cluster.getStatus().getState(); LOGGER.info("Cluster state is" + status); return status.equals("DELETING"); } } request.setPageToken(response.getNextPageToken()); } while (response.getNextPageToken() != null); return true; }
protected synchronized HttpTransport getGceHttpTransport() throws GeneralSecurityException, IOException { if (gceHttpTransport == null) { if (validateCerts) { gceHttpTransport = GoogleNetHttpTransport.newTrustedTransport(); } else { // this is only used for testing - alternative we could use the defaul keystore but this requires special configs too.. gceHttpTransport = new NetHttpTransport.Builder().doNotValidateCertificate().build(); } } return gceHttpTransport; }
/** * Set up the Compute Engine service * * @return Compute.Builder * * @throws IOException * @throws GeneralSecurityException */ public static Compute createComputeService() throws IOException, GeneralSecurityException { HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); GoogleCredential credential = GoogleCredential.getApplicationDefault(); if (credential.createScopedRequired()) { credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/cloud-platform")); } return new Compute.Builder(httpTransport, jsonFactory, credential) .setApplicationName("b612_BetterWorld/1.0") .build(); }
MakeGETRequestTask(GoogleAccountCredential credential) { HttpTransport transport = AndroidHttp.newCompatibleTransport(); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); mService = new com.google.api.services.sheets.v4.Sheets.Builder( transport, jsonFactory, credential) .setApplicationName("Homework Manager") .build(); }
MakePOSTRequestTask(GoogleAccountCredential credential) { HttpTransport transport = AndroidHttp.newCompatibleTransport(); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); mService = new com.google.api.services.sheets.v4.Sheets.Builder( transport, jsonFactory, credential) .setApplicationName("Homework Manager") .build(); }