Java Code Examples for com.google.auth.oauth2.GoogleCredentials

The following examples show how to use com.google.auth.oauth2.GoogleCredentials. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: java-docs-samples   Source File: DicomStoreSetIamPolicy.java    License: Apache License 2.0 6 votes vote down vote up
private static CloudHealthcare createClient() throws IOException {
  // Use Application Default Credentials (ADC) to authenticate the requests
  // For more information see https://cloud.google.com/docs/authentication/production
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

  // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
  HttpRequestInitializer requestInitializer =
      request -> {
        new HttpCredentialsAdapter(credential).initialize(request);
        request.setConnectTimeout(60000); // 1 minute connect timeout
        request.setReadTimeout(60000); // 1 minute read timeout
      };

  // Build the client for interacting with the service.
  return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
      .setApplicationName("your-application-name")
      .build();
}
 
Example 2
Source Project: curiostack   Source File: FirebaseAuthModule.java    License: MIT License 6 votes vote down vote up
@Provides
@Singleton
static FirebaseApp firebaseApp(FirebaseAuthConfig config) {
  final FirebaseOptions options;
  try {
    options =
        new FirebaseOptions.Builder()
            .setCredentials(
                GoogleCredentials.fromStream(
                    new ByteArrayInputStream(
                        Base64.getDecoder().decode(config.getServiceAccountBase64()))))
            .setDatabaseUrl("https://" + config.getProjectId() + ".firebaseio.com")
            .build();
  } catch (IOException e) {
    throw new UncheckedIOException("Could not read certificate.", e);
  }
  return FirebaseApp.initializeApp(options);
}
 
Example 3
Source Project: java-docs-samples   Source File: Hl7v2StoreGet.java    License: Apache License 2.0 6 votes vote down vote up
private static CloudHealthcare createClient() throws IOException {
  // Use Application Default Credentials (ADC) to authenticate the requests
  // For more information see https://cloud.google.com/docs/authentication/production
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

  // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
  HttpRequestInitializer requestInitializer =
      request -> {
        new HttpCredentialsAdapter(credential).initialize(request);
        request.setConnectTimeout(60000); // 1 minute connect timeout
        request.setReadTimeout(60000); // 1 minute read timeout
      };

  // Build the client for interacting with the service.
  return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
      .setApplicationName("your-application-name")
      .build();
}
 
Example 4
Source Project: bazel-buildfarm   Source File: GoogleAuthUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static Credentials newCredentials(
    @Nullable InputStream credentialsFile, List<String> authScopes) throws IOException {
  try {
    GoogleCredentials creds =
        credentialsFile == null
            ? GoogleCredentials.getApplicationDefault()
            : GoogleCredentials.fromStream(credentialsFile);
    if (!authScopes.isEmpty()) {
      creds = creds.createScoped(authScopes);
    }
    return creds;
  } catch (IOException e) {
    String message = "Failed to init auth credentials: " + e.getMessage();
    throw new IOException(message, e);
  }
}
 
Example 5
Source Project: java-docs-samples   Source File: FhirResourceCreate.java    License: Apache License 2.0 6 votes vote down vote up
private static CloudHealthcare createClient() throws IOException {
  // Use Application Default Credentials (ADC) to authenticate the requests
  // For more information see https://cloud.google.com/docs/authentication/production
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

  // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
  HttpRequestInitializer requestInitializer =
      request -> {
        new HttpCredentialsAdapter(credential).initialize(request);
        request.setConnectTimeout(60000); // 1 minute connect timeout
        request.setReadTimeout(60000); // 1 minute read timeout
      };

  // Build the client for interacting with the service.
  return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
      .setApplicationName("your-application-name")
      .build();
}
 
Example 6
public ContainerRegistryAuthSupplier build() {
  final GoogleCredentials credentials = this.credentials.createScoped(scopes);

  // log some sort of identifier for the credentials, which requires looking at the
  // instance type
  if (credentials instanceof ServiceAccountCredentials) {
    final String clientEmail = ((ServiceAccountCredentials) credentials).getClientEmail();
    log.info("loaded credentials for service account with clientEmail={}", clientEmail);
  } else if (credentials instanceof UserCredentials) {
    final String clientId = ((UserCredentials) credentials).getClientId();
    log.info("loaded credentials for user account with clientId={}", clientId);
  }

  final Clock clock = Clock.systemDefaultZone();
  final DefaultCredentialRefresher refresher = new DefaultCredentialRefresher();

  return new ContainerRegistryAuthSupplier(credentials, clock, minimumExpiryMillis, refresher);
}
 
Example 7
Source Project: java-docs-samples   Source File: FhirStoreCreate.java    License: Apache License 2.0 6 votes vote down vote up
private static CloudHealthcare createClient() throws IOException {
  // Use Application Default Credentials (ADC) to authenticate the requests
  // For more information see https://cloud.google.com/docs/authentication/production
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

  // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
  HttpRequestInitializer requestInitializer =
      request -> {
        new HttpCredentialsAdapter(credential).initialize(request);
        request.setConnectTimeout(60000); // 1 minute connect timeout
        request.setReadTimeout(60000); // 1 minute read timeout
      };

  // Build the client for interacting with the service.
  return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
      .setApplicationName("your-application-name")
      .build();
}
 
Example 8
Source Project: java-docs-samples   Source File: DatasetList.java    License: Apache License 2.0 6 votes vote down vote up
private static CloudHealthcare createClient() throws IOException {
  // Use Application Default Credentials (ADC) to authenticate the requests
  // For more information see https://cloud.google.com/docs/authentication/production
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

  // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
  HttpRequestInitializer requestInitializer =
      request -> {
        new HttpCredentialsAdapter(credential).initialize(request);
        request.setConnectTimeout(60000); // 1 minute connect timeout
        request.setReadTimeout(60000); // 1 minute read timeout
      };

  // Build the client for interacting with the service.
  return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
      .setApplicationName("your-application-name")
      .build();
}
 
Example 9
/** Delete this device from Cloud IoT. */
public static void deleteDevice(
    String deviceId, String projectId, String cloudRegion, String registryName)
    throws GeneralSecurityException, IOException {
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
  final CloudIot service =
      new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
          .setApplicationName(APP_NAME)
          .build();

  final String devicePath =
      String.format(
          "projects/%s/locations/%s/registries/%s/devices/%s",
          projectId, cloudRegion, registryName, deviceId);

  System.out.println("Deleting device " + devicePath);
  service.projects().locations().registries().devices().delete(devicePath).execute();
}
 
Example 10
Source Project: cloud-spanner-r2dbc   Source File: GrpcClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUserAgentConfig()
    throws IOException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
  GrpcClient grpcClient = new GrpcClient(GoogleCredentials.getApplicationDefault());
  Channel channel = grpcClient.getSpanner().getChannel();
  Class innerChannelWrapperClass = Class.forName("io.grpc.internal.ForwardingManagedChannel");
  Class channelImplClass = Class.forName("io.grpc.internal.ManagedChannelImpl");

  Field deletegateField = innerChannelWrapperClass.getDeclaredField("delegate");
  deletegateField.setAccessible(true);
  Field userAgentField = channelImplClass.getDeclaredField("userAgent");
  userAgentField.setAccessible(true);

  assertTrue(Pattern.matches("cloud-spanner-r2dbc/[0-9A-Za-z._-]+",
      (String) userAgentField.get(deletegateField.get(channel))));
}
 
Example 11
/**
 * Builds {@link GoogleCredentials} using the provided credentials path and credentials JSON.
 *
 * <p>{@code credentialsPath} and {@code credentialsJson} are mutually exclusive.
 * So if both are provided (are non-{@code null}), this is an error.
 *
 * <p>If either @code credentialsPath} or {@code credentialsJson} is provided,
 * it's used to construct the credentials.
 *
 * <p>If none are provided, the default GCP SDK credentials acquisition mechanism is used.
 *
 * @param credentialsPath the credential path, can be {@code null}.
 * @param credentialsJson the credential JSON string, can be {@code null}.
 * @return a {@link GoogleCredentials} constructed based on the input.
 * @throws IOException              if some error getting the credentials happen.
 * @throws IllegalArgumentException
 * if both {@code credentialsPath} and {@code credentialsJson} are non-{@code null}.
 */
public static GoogleCredentials build(final String credentialsPath,
                                      final String credentialsJson) throws IOException, IllegalArgumentException {
    if (credentialsPath != null && credentialsJson != null) {
        throw new IllegalArgumentException("Both credentialsPath and credentialsJson cannot be non-null.");
    }

    if (credentialsPath != null) {
        log.debug("Using provided credentials path");
        return getCredentialsFromPath(credentialsPath);
    }

    if (credentialsJson != null) {
        log.debug("Using provided credentials JSON");
        return getCredentialsFromJson(credentialsJson);
    }

    log.debug("Using default credentials");
    return GoogleCredentials.getApplicationDefault();
}
 
Example 12
Source Project: java-docs-samples   Source File: DatasetSetIamPolicy.java    License: Apache License 2.0 6 votes vote down vote up
private static CloudHealthcare createClient() throws IOException {
  // Use Application Default Credentials (ADC) to authenticate the requests
  // For more information see https://cloud.google.com/docs/authentication/production
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

  // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
  HttpRequestInitializer requestInitializer =
      request -> {
        new HttpCredentialsAdapter(credential).initialize(request);
        request.setConnectTimeout(60000); // 1 minute connect timeout
        request.setReadTimeout(60000); // 1 minute read timeout
      };

  // Build the client for interacting with the service.
  return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
      .setApplicationName("your-application-name")
      .build();
}
 
Example 13
Source Project: java-docs-samples   Source File: ListServiceAccountKeys.java    License: Apache License 2.0 6 votes vote down vote up
private static Iam initService() throws GeneralSecurityException, IOException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
  // Initialize the IAM service, which can be used to send requests to the IAM API.
  Iam service =
      new Iam.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-account-keys")
          .build();
  return service;
}
 
Example 14
Source Project: java-docs-samples   Source File: FhirStoreGetIamPolicy.java    License: Apache License 2.0 6 votes vote down vote up
private static CloudHealthcare createClient() throws IOException {
  // Use Application Default Credentials (ADC) to authenticate the requests
  // For more information see https://cloud.google.com/docs/authentication/production
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

  // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
  HttpRequestInitializer requestInitializer =
      request -> {
        new HttpCredentialsAdapter(credential).initialize(request);
        request.setConnectTimeout(60000); // 1 minute connect timeout
        request.setReadTimeout(60000); // 1 minute read timeout
      };

  // Build the client for interacting with the service.
  return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
      .setApplicationName("your-application-name")
      .build();
}
 
Example 15
Source Project: java-docs-samples   Source File: FhirStoreGetMetadata.java    License: Apache License 2.0 6 votes vote down vote up
private static CloudHealthcare createClient() throws IOException {
  // Use Application Default Credentials (ADC) to authenticate the requests
  // For more information see https://cloud.google.com/docs/authentication/production
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

  // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
  HttpRequestInitializer requestInitializer =
      request -> {
        new HttpCredentialsAdapter(credential).initialize(request);
        request.setConnectTimeout(60000); // 1 minute connect timeout
        request.setReadTimeout(60000); // 1 minute read timeout
      };

  // Build the client for interacting with the service.
  return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
      .setApplicationName("your-application-name")
      .build();
}
 
Example 16
Source Project: grpc-java   Source File: AbstractInteropTest.java    License: Apache License 2.0 6 votes vote down vote up
/** Test JWT-based auth. */
public void jwtTokenCreds(InputStream serviceAccountJson) throws Exception {
  final SimpleRequest request = SimpleRequest.newBuilder()
      .setResponseSize(314159)
      .setPayload(Payload.newBuilder()
          .setBody(ByteString.copyFrom(new byte[271828])))
      .setFillUsername(true)
      .build();

  ServiceAccountCredentials credentials = (ServiceAccountCredentials)
      GoogleCredentials.fromStream(serviceAccountJson);
  TestServiceGrpc.TestServiceBlockingStub stub = blockingStub
      .withCallCredentials(MoreCallCredentials.from(credentials));
  SimpleResponse response = stub.unaryCall(request);
  assertEquals(credentials.getClientEmail(), response.getUsername());
  assertEquals(314159, response.getPayload().getBody().size());
}
 
Example 17
Source Project: nifi   Source File: GCPCredentialsServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultingToApplicationDefault() throws Exception {
    final TestRunner runner = TestRunners.newTestRunner(MockCredentialsServiceProcessor.class);
    final GCPCredentialsControllerService serviceImpl = new GCPCredentialsControllerService();
    runner.addControllerService("gcpCredentialsProvider", serviceImpl);

    runner.enableControllerService(serviceImpl);

    runner.assertValid(serviceImpl);

    final GCPCredentialsService service = (GCPCredentialsService) runner.getProcessContext()
            .getControllerServiceLookup().getControllerService("gcpCredentialsProvider");

    assertNotNull(service);
    final GoogleCredentials credentials = service.getGoogleCredentials();
    assertNotNull(credentials);
}
 
Example 18
Source Project: java-docs-samples   Source File: Hl7v2StoreSetIamPolicy.java    License: Apache License 2.0 6 votes vote down vote up
private static CloudHealthcare createClient() throws IOException {
  // Use Application Default Credentials (ADC) to authenticate the requests
  // For more information see https://cloud.google.com/docs/authentication/production
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

  // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
  HttpRequestInitializer requestInitializer =
      request -> {
        new HttpCredentialsAdapter(credential).initialize(request);
        request.setConnectTimeout(60000); // 1 minute connect timeout
        request.setReadTimeout(60000); // 1 minute read timeout
      };

  // Build the client for interacting with the service.
  return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
      .setApplicationName("your-application-name")
      .build();
}
 
Example 19
Source Project: java-docs-samples   Source File: HL7v2MessageGet.java    License: Apache License 2.0 6 votes vote down vote up
private static CloudHealthcare createClient() throws IOException {
  // Use Application Default Credentials (ADC) to authenticate the requests
  // For more information see https://cloud.google.com/docs/authentication/production
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

  // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
  HttpRequestInitializer requestInitializer =
      request -> {
        new HttpCredentialsAdapter(credential).initialize(request);
        request.setConnectTimeout(60000); // 1 minute connect timeout
        request.setReadTimeout(60000); // 1 minute read timeout
      };

  // Build the client for interacting with the service.
  return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
      .setApplicationName("your-application-name")
      .build();
}
 
Example 20
Source Project: firebase-admin-java   Source File: TestUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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(
      "https://accounts.google.com/o/oauth2/token");
  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;
}
 
Example 21
Source Project: nifi   Source File: AbstractGCSTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testStorageOptionsConfiguration() throws Exception {
    reset(storage);
    final TestRunner runner = buildNewRunner(getProcessor());

    final AbstractGCSProcessor processor = getProcessor();
    final GoogleCredentials mockCredentials = mock(GoogleCredentials.class);

    final StorageOptions options = processor.getServiceOptions(runner.getProcessContext(),
            mockCredentials);

    assertEquals("Project IDs should match",
            PROJECT_ID, options.getProjectId());

    assertEquals("Retry counts should match",
            RETRIES.intValue(), options.getRetrySettings().getMaxAttempts());

    assertSame("Credentials should be configured correctly",
            mockCredentials, options.getCredentials());
}
 
Example 22
Source Project: halyard   Source File: GoogleKms.java    License: Apache License 2.0 6 votes vote down vote up
private static GoogleCredentials loadKmsCredential(String jsonPath) throws IOException {
  GoogleCredentials credentials;
  if (!jsonPath.isEmpty()) {
    FileInputStream stream = new FileInputStream(jsonPath);
    credentials = GoogleCredentials.fromStream(stream);
    log.info("Loaded kms credentials from " + jsonPath);
  } else {
    log.info("Using kms default application credentials.");
    credentials = GoogleCredentials.getApplicationDefault();
  }

  if (credentials.createScopedRequired()) {
    credentials = credentials.createScoped(CloudKMSScopes.all());
  }

  return credentials;
}
 
Example 23
Source Project: cassandra-backup   Source File: GCPModule.java    License: Apache License 2.0 6 votes vote down vote up
private GoogleCredentials resolveGoogleCredentials(final AbstractOperationRequest operationRequest) {
    final String dataKey = "gcp";

    final String namespace = operationRequest.resolveKubernetesNamespace();
    final String secretName = operationRequest.resolveSecretName();

    try {
        Optional<byte[]> gcpCredentials = new SecretReader(coreV1ApiProvider).read(namespace,
                                                                                   secretName,
                                                                                   dataKey);

        if (!gcpCredentials.isPresent()) {
            throw new GCPModuleException(format("GCP credentials from Kubernetes namespace %s from secret %s under key %s were not set.",
                                                namespace,
                                                secretName,
                                                dataKey));
        }

        return GoogleCredentials.fromStream(new ByteArrayInputStream(gcpCredentials.get()))
            .createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));
    } catch (final Exception ex) {
        throw new GCPModuleException(format("Unable to resolve data for key %s on secret %s", dataKey, secretName), ex);
    }
}
 
Example 24
Source Project: java-docs-samples   Source File: FhirResourceSearchPost.java    License: Apache License 2.0 6 votes vote down vote up
private static CloudHealthcare createClient() throws IOException {
  // Use Application Default Credentials (ADC) to authenticate the requests
  // For more information see https://cloud.google.com/docs/authentication/production
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

  // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
  HttpRequestInitializer requestInitializer =
      request -> {
        new HttpCredentialsAdapter(credential).initialize(request);
        request.setConnectTimeout(60000); // 1 minute connect timeout
        request.setReadTimeout(60000); // 1 minute read timeout
      };

  // Build the client for interacting with the service.
  return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
      .setApplicationName("your-application-name")
      .build();
}
 
Example 25
Source Project: daq   Source File: CloudIotManager.java    License: Apache License 2.0 6 votes vote down vote up
private void initializeCloudIoT() {
  projectPath = "projects/" + projectId + "/locations/" + cloudRegion;
  try {
    System.err.println("Initializing with default credentials...");
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
    cloudIotService =
        new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
            .setApplicationName("com.google.iot.bos")
            .build();
    cloudIotRegistries = cloudIotService.projects().locations().registries();
    System.err.println("Created service for project " + projectPath);
  } catch (Exception e) {
    throw new RuntimeException("While initializing Cloud IoT project " + projectPath, e);
  }
}
 
Example 26
Source Project: java-docs-samples   Source File: DicomStoreGet.java    License: Apache License 2.0 6 votes vote down vote up
private static CloudHealthcare createClient() throws IOException {
  // Use Application Default Credentials (ADC) to authenticate the requests
  // For more information see https://cloud.google.com/docs/authentication/production
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

  // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
  HttpRequestInitializer requestInitializer =
      request -> {
        new HttpCredentialsAdapter(credential).initialize(request);
        request.setConnectTimeout(60000); // 1 minute connect timeout
        request.setReadTimeout(60000); // 1 minute read timeout
      };

  // Build the client for interacting with the service.
  return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
      .setApplicationName("your-application-name")
      .build();
}
 
Example 27
Source Project: java-docs-samples   Source File: StorageFactory.java    License: Apache License 2.0 6 votes vote down vote up
private static Storage buildService() throws IOException, GeneralSecurityException {
  HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
  JsonFactory jsonFactory = new JacksonFactory();
  GoogleCredentials credential = GoogleCredentials.getApplicationDefault();

  // Depending on the environment that provides the default credentials (for
  // example: 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()) {
    Collection<String> scopes = StorageScopes.all();
    credential = credential.createScoped(scopes);
  }

  return new Storage.Builder(transport, jsonFactory, new HttpCredentialsAdapter(credential))
      .setApplicationName("GCS Samples")
      .build();
}
 
Example 28
Source Project: java-docs-samples   Source File: FhirStoreGet.java    License: Apache License 2.0 6 votes vote down vote up
private static CloudHealthcare createClient() throws IOException {
  // Use Application Default Credentials (ADC) to authenticate the requests
  // For more information see https://cloud.google.com/docs/authentication/production
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

  // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
  HttpRequestInitializer requestInitializer =
      request -> {
        new HttpCredentialsAdapter(credential).initialize(request);
        request.setConnectTimeout(60000); // 1 minute connect timeout
        request.setReadTimeout(60000); // 1 minute read timeout
      };

  // Build the client for interacting with the service.
  return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
      .setApplicationName("your-application-name")
      .build();
}
 
Example 29
@Test
public void testDefaultingToApplicationDefault() throws Exception {
    final TestRunner runner = TestRunners.newTestRunner(MockCredentialsServiceProcessor.class);
    final GCPCredentialsControllerService serviceImpl = new GCPCredentialsControllerService();
    runner.addControllerService("gcpCredentialsProvider", serviceImpl);

    runner.enableControllerService(serviceImpl);

    runner.assertValid(serviceImpl);

    final GCPCredentialsService service = (GCPCredentialsService) runner.getProcessContext()
            .getControllerServiceLookup().getControllerService("gcpCredentialsProvider");

    assertNotNull(service);
    final GoogleCredentials credentials = service.getGoogleCredentials();
    assertNotNull(credentials);
}
 
Example 30
Source Project: nifi   Source File: AbstractBQTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBiqQueryOptionsConfiguration() throws Exception {
    reset(bq);
    final TestRunner runner = buildNewRunner(getProcessor());

    final AbstractBigQueryProcessor processor = getProcessor();
    final GoogleCredentials mockCredentials = mock(GoogleCredentials.class);

    final BigQueryOptions options = processor.getServiceOptions(runner.getProcessContext(),
            mockCredentials);

    assertEquals("Project IDs should match",
            PROJECT_ID, options.getProjectId());

    assertEquals("Retry counts should match",
            RETRIES.intValue(), options.getRetrySettings().getMaxAttempts());

    assertSame("Credentials should be configured correctly",
            mockCredentials, options.getCredentials());
}