javax.validation.constraints.AssertTrue#com.google.auth.oauth2.GoogleCredentials源码实例Demo

下面列出了javax.validation.constraints.AssertTrue#com.google.auth.oauth2.GoogleCredentials 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

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();
}
 
源代码2 项目: curiostack   文件: FirebaseAuthModule.java
@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);
}
 
源代码3 项目: java-docs-samples   文件: Hl7v2StoreGet.java
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();
}
 
源代码4 项目: bazel-buildfarm   文件: GoogleAuthUtils.java
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);
  }
}
 
源代码5 项目: java-docs-samples   文件: FhirResourceCreate.java
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();
}
 
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);
}
 
源代码7 项目: java-docs-samples   文件: FhirStoreCreate.java
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();
}
 
源代码8 项目: java-docs-samples   文件: DatasetList.java
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();
}
 
/** 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();
}
 
源代码10 项目: cloud-spanner-r2dbc   文件: GrpcClientTest.java
@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))));
}
 
/**
 * 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();
}
 
源代码12 项目: java-docs-samples   文件: DatasetSetIamPolicy.java
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();
}
 
源代码13 项目: java-docs-samples   文件: ListServiceAccountKeys.java
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;
}
 
源代码14 项目: java-docs-samples   文件: FhirStoreGetIamPolicy.java
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();
}
 
源代码15 项目: java-docs-samples   文件: FhirStoreGetMetadata.java
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();
}
 
源代码16 项目: grpc-java   文件: AbstractInteropTest.java
/** 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());
}
 
源代码17 项目: nifi   文件: GCPCredentialsServiceTest.java
@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);
}
 
源代码18 项目: java-docs-samples   文件: Hl7v2StoreSetIamPolicy.java
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();
}
 
源代码19 项目: java-docs-samples   文件: HL7v2MessageGet.java
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();
}
 
源代码20 项目: firebase-admin-java   文件: TestUtils.java
/**
 * 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;
}
 
源代码21 项目: nifi   文件: AbstractGCSTest.java
@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());
}
 
源代码22 项目: halyard   文件: GoogleKms.java
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;
}
 
源代码23 项目: cassandra-backup   文件: GCPModule.java
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);
    }
}
 
源代码24 项目: java-docs-samples   文件: FhirResourceSearchPost.java
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();
}
 
源代码25 项目: daq   文件: CloudIotManager.java
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);
  }
}
 
源代码26 项目: java-docs-samples   文件: DicomStoreGet.java
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();
}
 
源代码27 项目: java-docs-samples   文件: StorageFactory.java
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();
}
 
源代码28 项目: java-docs-samples   文件: FhirStoreGet.java
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();
}
 
@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);
}
 
源代码30 项目: nifi   文件: AbstractBQTest.java
@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());
}