com.google.auth.Credentials

Here are the examples of the java api com.google.auth.Credentials taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

90 Examples 7

19 Source : DatastoreIntegrationTestConfiguration.java
with Apache License 2.0
from spring-cloud

/**
 * Config clreplaced for the integration tests.
 *
 * @author Chengyuan Zhao
 */
@Configuration
@PropertySource("application-test.properties")
@EnableDatastoreRepositories
@EnableTransactionManagement
public clreplaced DatastoreIntegrationTestConfiguration {

    private final String projectId = new DefaultGcpProjectIdProvider().getProjectId();

    private final Credentials credentials = new DefaultCredentialsProvider(org.springframework.cloud.gcp.core.Credentials::new).getCredentials();

    @Value("${test.integration.datastore.namespacePrefix}")
    private String namespacePrefix;

    public DatastoreIntegrationTestConfiguration() throws IOException {
    }

    @Bean
    public TransactionalTemplateService transactionalTemplateService() {
        return new TransactionalTemplateService();
    }

    @Bean
    DatastoreTransactionManager datastoreTransactionManager(Datastore datastore) {
        return new DatastoreTransactionManager(() -> datastore);
    }

    @Bean
    public Datastore datastore() {
        DatastoreOptions.Builder builder = DatastoreOptions.newBuilder().setProjectId(this.projectId).setHeaderProvider(new UserAgentHeaderProvider(this.getClreplaced())).setCredentials(this.credentials);
        if (this.namespacePrefix != null) {
            builder.setNamespace(this.namespacePrefix + System.currentTimeMillis());
        }
        return builder.build().getService();
    }

    @Bean
    public DatastoreMappingContext datastoreMappingContext() {
        return new DatastoreMappingContext();
    }

    @Bean
    public DatastoreEnreplacedyConverter datastoreEnreplacedyConverter(DatastoreMappingContext datastoreMappingContext, ObjectToKeyFactory objectToKeyFactory) {
        return new DefaultDatastoreEnreplacedyConverter(datastoreMappingContext, objectToKeyFactory);
    }

    @Bean
    public ObjectToKeyFactory objectToKeyFactory(Datastore datastore) {
        return new DatastoreServiceObjectToKeyFactory(() -> datastore);
    }

    @Bean
    public DatastoreTemplate datastoreTemplate(Datastore datastore, DatastoreMappingContext datastoreMappingContext, DatastoreEnreplacedyConverter datastoreEnreplacedyConverter, ObjectToKeyFactory objectToKeyFactory) {
        return new DatastoreTemplate(() -> datastore, datastoreEnreplacedyConverter, datastoreMappingContext, objectToKeyFactory);
    }
}

19 Source : GoogleConfigPropertySourceLocator.java
with Apache License 2.0
from spring-cloud

/**
 * Custom {@link PropertySourceLocator} for Google Cloud Runtime Configurator API.
 *
 * @author Jisha Abubaker
 * @author Mike Eltsufin
 *
 * @since 1.1
 */
public clreplaced GoogleConfigPropertySourceLocator implements PropertySourceLocator {

    private static final String RUNTIMECONFIG_API_ROOT = "https://runtimeconfig.googleapis.com/v1beta1/";

    private static final String ALL_VARIABLES_PATH = "projects/{project}/configs/{name}_{profile}/variables?returnValues=true";

    private static final String PROPERTY_SOURCE_NAME = "spring-cloud-gcp";

    private static final String AUTHORIZATION_HEADER = "Authorization";

    private String projectId;

    private Credentials credentials;

    private String name;

    private String profile;

    private int timeout;

    private boolean enabled;

    public GoogleConfigPropertySourceLocator(GcpProjectIdProvider projectIdProvider, CredentialsProvider credentialsProvider, GcpConfigProperties gcpConfigProperties) throws IOException {
        replacedert.notNull(gcpConfigProperties, "Google Config properties must not be null");
        if (gcpConfigProperties.isEnabled()) {
            replacedert.notNull(credentialsProvider, "Credentials provider cannot be null");
            replacedert.notNull(projectIdProvider, "Project ID provider cannot be null");
            this.credentials = gcpConfigProperties.getCredentials().hasKey() ? new DefaultCredentialsProvider(gcpConfigProperties).getCredentials() : credentialsProvider.getCredentials();
            this.projectId = (gcpConfigProperties.getProjectId() != null) ? gcpConfigProperties.getProjectId() : projectIdProvider.getProjectId();
            replacedert.notNull(this.credentials, "Credentials must not be null");
            replacedert.notNull(this.projectId, "Project ID must not be null");
            this.timeout = gcpConfigProperties.getTimeoutMillis();
            this.name = gcpConfigProperties.getName();
            this.profile = gcpConfigProperties.getProfile();
            this.enabled = gcpConfigProperties.isEnabled();
            replacedert.notNull(this.name, "Config name must not be null");
            replacedert.notNull(this.profile, "Config profile must not be null");
        }
    }

    private HttpEnreplacedy<Void> getAuthorizedRequest() throws IOException {
        HttpHeaders headers = new HttpHeaders();
        Map<String, List<String>> credentialHeaders = this.credentials.getRequestMetadata();
        replacedert.notNull(credentialHeaders, "No valid credential header(s) found");
        credentialHeaders.forEach((key, values) -> values.forEach((value) -> headers.add(key, value)));
        replacedert.isTrue(headers.containsKey(AUTHORIZATION_HEADER), "Authorization header required");
        // Adds product version header for usage metrics
        new UserAgentHeaderProvider(this.getClreplaced()).getHeaders().forEach(headers::add);
        return new HttpEnreplacedy<>(headers);
    }

    GoogleConfigEnvironment getRemoteEnvironment() throws IOException, HttpClientErrorException {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setReadTimeout(this.timeout);
        RestTemplate template = new RestTemplate(requestFactory);
        HttpEnreplacedy<Void> requestEnreplacedy = getAuthorizedRequest();
        ResponseEnreplacedy<GoogleConfigEnvironment> response = template.exchange(RUNTIMECONFIG_API_ROOT + ALL_VARIABLES_PATH, HttpMethod.GET, requestEnreplacedy, GoogleConfigEnvironment.clreplaced, this.projectId, this.name, this.profile);
        if (!response.getStatusCode().is2xxSuccessful()) {
            throw new HttpClientErrorException(response.getStatusCode(), "Invalid response from Runtime Configurator API");
        }
        return response.getBody();
    }

    @Override
    public PropertySource<?> locate(Environment environment) {
        if (!this.enabled) {
            return new MapPropertySource(PROPERTY_SOURCE_NAME, Collections.emptyMap());
        }
        Map<String, Object> config;
        try {
            GoogleConfigEnvironment googleConfigEnvironment = getRemoteEnvironment();
            replacedert.notNull(googleConfigEnvironment, "Configuration not in expected format.");
            config = googleConfigEnvironment.getConfig();
        } catch (Exception ex) {
            String message = String.format("Error loading configuration for %s/%s_%s", this.projectId, this.name, this.profile);
            throw new RuntimeException(message, ex);
        }
        return new MapPropertySource(PROPERTY_SOURCE_NAME, config);
    }

    public String getProjectId() {
        return this.projectId;
    }
}

19 Source : CredentialsDecoratingClient.java
with Apache License 2.0
from openzipkin

clreplaced CredentialsDecoratingClient extends SimpleDecoratingHttpClient implements AutoCloseable {

    static Function<HttpClient, HttpClient> newDecorator(Credentials credentials) {
        return client -> new CredentialsDecoratingClient(client, credentials);
    }

    final Credentials credentials;

    final ExecutorService executor;

    private CredentialsDecoratingClient(HttpClient delegate, Credentials credentials) {
        super(delegate);
        this.credentials = credentials;
        executor = Executors.newSingleThreadExecutor();
    }

    @Override
    public HttpResponse execute(ClientRequestContext ctx, HttpRequest req) {
        final URI uri;
        try {
            uri = new URI("https", req.authority(), req.path(), null, null);
        } catch (URISyntaxException e) {
            return HttpResponse.ofFailure(e);
        }
        CompletableFuture<HttpResponse> responseFuture = new CompletableFuture<>();
        credentials.getRequestMetadata(uri, executor, new RequestMetadataCallback() {

            @Override
            public void onSuccess(Map<String, List<String>> map) {
                HttpRequest newReq = req;
                if (map != null) {
                    newReq = req.withHeaders(req.headers().withMutations(headers -> {
                        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                            headers.add(HttpHeaderNames.of(entry.getKey()), entry.getValue());
                        }
                    }));
                }
                try {
                    responseFuture.complete(unwrap().execute(ctx, newReq));
                } catch (Exception e) {
                    responseFuture.completeExceptionally(e);
                }
            }

            @Override
            public void onFailure(Throwable throwable) {
                responseFuture.completeExceptionally(throwable);
            }
        });
        return HttpResponse.from(responseFuture);
    }

    @Override
    public void close() {
        executor.shutdownNow();
    }
}

19 Source : CredentialsDecoratingClient.java
with Apache License 2.0
from openzipkin

static Function<HttpClient, HttpClient> newDecorator(Credentials credentials) {
    return client -> new CredentialsDecoratingClient(client, credentials);
}

19 Source : DatastoreUtil.java
with MIT License
from mercari

public static Datastore getDatastore(final String projectId, final Credentials credential) {
    final HttpRequestInitializer initializer;
    if (credential != null) {
        initializer = new ChainingHttpRequestInitializer(new HttpCredentialsAdapter(credential), new RetryHttpRequestInitializer());
    } else {
        initializer = new RetryHttpRequestInitializer();
    }
    return DatastoreFactory.get().create(new DatastoreOptions.Builder().projectId(projectId).initializer(initializer).host(HOST).build());
}

19 Source : BigQueryUtil.java
with MIT License
from mercari

private static String getUserDefaultProject(final Credentials credential) {
    if (credential instanceof UserCredentials) {
        return ((UserCredentials) credential).getQuotaProjectId();
    }
    return null;
}

19 Source : MoreCallCredentials.java
with Apache License 2.0
from grpc-nebula

/**
 * Converts a Google Auth Library {@link Credentials} to {@link CallCredentials}.
 *
 * <p>Although this is a stable API, note that the returned instance's API is not stable. You are
 * free to use the clreplaced name {@code CallCredentials} and preplaced the instance to other code, but the
 * instance can't be called directly from code expecting stable behavior. See {@link
 * CallCredentials}.
 */
public static CallCredentials from(Credentials creds) {
    return new GoogleAuthLibraryCallCredentials(creds);
}

19 Source : GoogleConfigPropertySourceLocator.java
with Apache License 2.0
from GoogleCloudPlatform

/**
 * Custom {@link PropertySourceLocator} for Google Cloud Runtime Configurator API.
 *
 * @author Jisha Abubaker
 * @author Mike Eltsufin
 *
 * @since 1.1
 */
public clreplaced GoogleConfigPropertySourceLocator implements PropertySourceLocator {

    private static final String RUNTIMECONFIG_API_ROOT = "https://runtimeconfig.googleapis.com/v1beta1/";

    private static final String ALL_VARIABLES_PATH = "projects/{project}/configs/{name}_{profile}/variables?returnValues=true";

    private static final String PROPERTY_SOURCE_NAME = "spring-cloud-gcp";

    private static final String AUTHORIZATION_HEADER = "Authorization";

    private String projectId;

    private Credentials credentials;

    private String name;

    private String profile;

    private int timeout;

    private boolean enabled;

    public GoogleConfigPropertySourceLocator(GcpProjectIdProvider projectIdProvider, CredentialsProvider credentialsProvider, GcpConfigProperties gcpConfigProperties) throws IOException {
        replacedert.notNull(gcpConfigProperties, "Google Config properties must not be null");
        if (gcpConfigProperties.isEnabled()) {
            replacedert.notNull(credentialsProvider, "Credentials provider cannot be null");
            replacedert.notNull(projectIdProvider, "Project ID provider cannot be null");
            this.credentials = gcpConfigProperties.getCredentials().hasKey() ? new DefaultCredentialsProvider(gcpConfigProperties).getCredentials() : credentialsProvider.getCredentials();
            this.projectId = (gcpConfigProperties.getProjectId() != null) ? gcpConfigProperties.getProjectId() : projectIdProvider.getProjectId();
            replacedert.notNull(this.credentials, "Credentials must not be null");
            replacedert.notNull(this.projectId, "Project ID must not be null");
            this.timeout = gcpConfigProperties.getTimeoutMillis();
            this.name = gcpConfigProperties.getName();
            this.profile = gcpConfigProperties.getProfile();
            this.enabled = gcpConfigProperties.isEnabled();
            replacedert.notNull(this.name, "Config name must not be null");
            replacedert.notNull(this.profile, "Config profile must not be null");
        }
    }

    private HttpEnreplacedy<Void> getAuthorizedRequest() throws IOException {
        HttpHeaders headers = new HttpHeaders();
        Map<String, List<String>> credentialHeaders = this.credentials.getRequestMetadata();
        replacedert.notNull(credentialHeaders, "No valid credential header(s) found");
        credentialHeaders.forEach((key, values) -> values.forEach(value -> headers.add(key, value)));
        replacedert.isTrue(headers.containsKey(AUTHORIZATION_HEADER), "Authorization header required");
        // Adds product version header for usage metrics
        new UserAgentHeaderProvider(this.getClreplaced()).getHeaders().forEach(headers::add);
        return new HttpEnreplacedy<>(headers);
    }

    GoogleConfigEnvironment getRemoteEnvironment() throws IOException, HttpClientErrorException {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setReadTimeout(this.timeout);
        RestTemplate template = new RestTemplate(requestFactory);
        HttpEnreplacedy<Void> requestEnreplacedy = getAuthorizedRequest();
        ResponseEnreplacedy<GoogleConfigEnvironment> response = template.exchange(RUNTIMECONFIG_API_ROOT + ALL_VARIABLES_PATH, HttpMethod.GET, requestEnreplacedy, GoogleConfigEnvironment.clreplaced, this.projectId, this.name, this.profile);
        if (!response.getStatusCode().is2xxSuccessful()) {
            throw new HttpClientErrorException(response.getStatusCode(), "Invalid response from Runtime Configurator API");
        }
        return response.getBody();
    }

    @Override
    public PropertySource<?> locate(Environment environment) {
        if (!this.enabled) {
            return new MapPropertySource(PROPERTY_SOURCE_NAME, Collections.emptyMap());
        }
        Map<String, Object> config;
        try {
            GoogleConfigEnvironment googleConfigEnvironment = getRemoteEnvironment();
            replacedert.notNull(googleConfigEnvironment, "Configuration not in expected format.");
            config = googleConfigEnvironment.getConfig();
        } catch (Exception ex) {
            String message = String.format("Error loading configuration for %s/%s_%s", this.projectId, this.name, this.profile);
            throw new RuntimeException(message, ex);
        }
        return new MapPropertySource(PROPERTY_SOURCE_NAME, config);
    }

    public String getProjectId() {
        return this.projectId;
    }
}

19 Source : MetricExporter.java
with Apache License 2.0
from GoogleCloudPlatform

public static MetricExporter createWithConfiguration(MetricConfiguration configuration) throws IOException {
    String projectId = configuration.getProjectId();
    MetricServiceStub stub = configuration.getMetricServiceStub();
    if (stub == null) {
        Credentials credentials = configuration.getCredentials() == null ? GoogleCredentials.getApplicationDefault() : configuration.getCredentials();
        return MetricExporter.createWithCredentials(projectId, credentials, configuration.getDeadline(), configuration.getDescriptorStrategy());
    }
    return MetricExporter.createWithClient(projectId, new CloudMetricClientImpl(MetricServiceClient.create(stub)), configuration.getDescriptorStrategy());
}

19 Source : BigQueryReadClientFactory.java
with Apache License 2.0
from GoogleCloudDataproc

/**
 * Since Guice recommends to avoid injecting closeable resources (see
 * https://github.com/google/guice/wiki/Avoid-Injecting-Closable-Resources), this factory creates
 * short lived clients that can be closed independently.
 */
public clreplaced BigQueryReadClientFactory implements Serializable {

    private final Credentials credentials;

    // using the user agent as HeaderProvider is not serializable
    private final UserAgentHeaderProvider userAgentHeaderProvider;

    @Inject
    public BigQueryReadClientFactory(BigQueryCredentialsSupplier bigQueryCredentialsSupplier, UserAgentHeaderProvider userAgentHeaderProvider) {
        // using Guava's optional as it is serializable
        this.credentials = bigQueryCredentialsSupplier.getCredentials();
        this.userAgentHeaderProvider = userAgentHeaderProvider;
    }

    BigQueryReadClient createBigQueryReadClient() {
        try {
            BigQueryReadSettings.Builder clientSettings = BigQueryReadSettings.newBuilder().setTransportChannelProvider(BigQueryReadSettings.defaultGrpcTransportProviderBuilder().setHeaderProvider(userAgentHeaderProvider).build()).setCredentialsProvider(FixedCredentialsProvider.create(credentials));
            return BigQueryReadClient.create(clientSettings.build());
        } catch (IOException e) {
            throw new UncheckedIOException("Error creating BigQueryStorageClient", e);
        }
    }
}

19 Source : BigQueryCredentialsSupplier.java
with Apache License 2.0
from GoogleCloudDataproc

public clreplaced BigQueryCredentialsSupplier {

    private final Credentials credentials;

    public BigQueryCredentialsSupplier(Optional<String> accessToken, Optional<String> credentialsKey, Optional<String> credentialsFile) {
        if (accessToken.isPresent()) {
            this.credentials = createCredentialsFromAccessToken(accessToken.get());
        } else if (credentialsKey.isPresent()) {
            this.credentials = createCredentialsFromKey(credentialsKey.get());
        } else if (credentialsFile.isPresent()) {
            this.credentials = createCredentialsFromFile(credentialsFile.get());
        } else {
            this.credentials = createDefaultCredentials();
        }
    }

    private static Credentials createCredentialsFromAccessToken(String accessToken) {
        return GoogleCredentials.create(new AccessToken(accessToken, null));
    }

    private static Credentials createCredentialsFromKey(String key) {
        try {
            return GoogleCredentials.fromStream(new ByteArrayInputStream(Base64.decodeBase64(key)));
        } catch (IOException e) {
            throw new UncheckedIOException("Failed to create Credentials from key", e);
        }
    }

    private static Credentials createCredentialsFromFile(String file) {
        try {
            return GoogleCredentials.fromStream(new FileInputStream(file));
        } catch (IOException e) {
            throw new UncheckedIOException("Failed to create Credentials from file", e);
        }
    }

    public static Credentials createDefaultCredentials() {
        try {
            return GoogleCredentials.getApplicationDefault();
        } catch (IOException e) {
            throw new UncheckedIOException("Failed to create default Credentials", e);
        }
    }

    public Credentials getCredentials() {
        return credentials;
    }
}

19 Source : GoogleAdsClientTest.java
with Apache License 2.0
from googleads

/**
 * Tests building a client without the use of a properties file.
 */
@Test
public void buildWithoutPropertiesFile_supportsAllFields() throws IOException {
    Credentials credentials = UserCredentials.newBuilder().setClientId(CLIENT_ID).setClientSecret(CLIENT_SECRET).setRefreshToken(REFRESH_TOKEN).build();
    GoogleAdsClient client = GoogleAdsClient.newBuilder().setCredentials(credentials).setDeveloperToken(DEVELOPER_TOKEN).setLoginCustomerId(LOGIN_CUSTOMER_ID).setTransportChannelProvider(localChannelProvider).build();
    replacedertGoogleAdsClient(client, true);
}

19 Source : GoogleAdsClientTest.java
with Apache License 2.0
from googleads

/**
 * Verifies that builder supports nullable loginCustomerId.
 */
@Test
public void build_loginCustomerId_allowsNullable() {
    Credentials credentials = UserCredentials.newBuilder().setClientId(CLIENT_ID).setClientSecret(CLIENT_SECRET).setRefreshToken(REFRESH_TOKEN).build();
    GoogleAdsClient client = GoogleAdsClient.newBuilder().setCredentials(credentials).setDeveloperToken(DEVELOPER_TOKEN).build();
    replacedertNull("invalid login-customer-id", client.getLoginCustomerId());
}

19 Source : GoogleAdsClientTest.java
with Apache License 2.0
from googleads

/**
 * Tests that the loginCustomerId can be unset when cloning the client via builder methods. This
 * is important so that users can easily change the login customer ID.
 */
@Test
public void setLoginCustomerId_canClearOnceSet() {
    Credentials credentials = UserCredentials.newBuilder().setClientId(CLIENT_ID).setClientSecret(CLIENT_SECRET).setRefreshToken(REFRESH_TOKEN).build();
    GoogleAdsClient client = GoogleAdsClient.newBuilder().setCredentials(credentials).setDeveloperToken(DEVELOPER_TOKEN).setLoginCustomerId(1L).build();
    client = client.toBuilder().setLoginCustomerId(null).build();
    replacedertNull("Unable to clear loginCustomerId", client.getLoginCustomerId());
}

19 Source : GCPUtils.java
with Apache License 2.0
from data-integrations

public static BigQuery getBigQuery(String project, @Nullable Credentials credentials) {
    BigQueryOptions.Builder bigqueryBuilder = BigQueryOptions.newBuilder().setProjectId(project);
    if (credentials != null) {
        bigqueryBuilder.setCredentials(credentials);
    }
    return bigqueryBuilder.build().getService();
}

19 Source : GCPUtils.java
with Apache License 2.0
from data-integrations

public static Storage getStorage(String project, @Nullable Credentials credentials) {
    StorageOptions.Builder builder = StorageOptions.newBuilder().setProjectId(project);
    if (credentials != null) {
        builder.setCredentials(credentials);
    }
    return builder.build().getService();
}

19 Source : StackdriverExporter.java
with Apache License 2.0
from census-instrumentation

/**
 * Creates and registers the Stackdriver Trace exporter to the OpenCensus library for an explicit
 * project ID and using explicit credentials. Only one Stackdriver exporter can be registered at
 * any point.
 *
 * @param credentials a credentials used to authenticate API calls.
 * @param projectId the cloud project id.
 * @throws IllegalStateException if a Stackdriver exporter is already registered.
 * @since 0.6
 */
public static void createAndRegisterWithCredentialsAndProjectId(Credentials credentials, String projectId) throws IOException {
    StackdriverTraceExporter.createAndRegister(StackdriverTraceConfiguration.builder().setCredentials(credentials).setProjectId(projectId).build());
}

19 Source : StackdriverStatsExporter.java
with Apache License 2.0
from census-instrumentation

/**
 * Creates a StackdriverStatsExporter for an explicit project ID and using explicit credentials,
 * with default Monitored Resource.
 *
 * <p>Only one Stackdriver exporter can be created.
 *
 * @param credentials a credentials used to authenticate API calls.
 * @param projectId the cloud project id.
 * @param exportInterval the interval between pushing stats to StackDriver.
 * @throws IllegalStateException if a Stackdriver exporter already exists.
 * @deprecated in favor of {@link #createAndRegister(StackdriverStatsConfiguration)}.
 * @since 0.9
 */
@Deprecated
public static void createAndRegisterWithCredentialsAndProjectId(Credentials credentials, String projectId, Duration exportInterval) throws IOException {
    checkNotNull(credentials, "credentials");
    checkNotNull(projectId, "projectId");
    checkNotNull(exportInterval, "exportInterval");
    createInternal(credentials, projectId, exportInterval, DEFAULT_RESOURCE, null, null, DEFAULT_CONSTANT_LABELS, DEFAULT_DEADLINE, null);
}

19 Source : GoogleAuthUtils.java
with Apache License 2.0
from bazelbuild

@VisibleForTesting
public static CallCredentials newCallCredentials(@Nullable InputStream credentialsFile, List<String> authScope) throws IOException {
    Credentials creds = newCredentials(credentialsFile, authScope);
    if (creds != null) {
        return MoreCallCredentials.from(creds);
    }
    return null;
}

19 Source : GoogleAuthUtils.java
with Apache License 2.0
from bazelbuild

/**
 * Create a new {@link CallCredentials} object.
 *
 * @throws IOException in case the call credentials can't be constructed.
 */
public static CallCredentials newCallCredentials(AuthAndTLSOptions options) throws IOException {
    Credentials creds = newCredentials(options);
    if (creds != null) {
        return MoreCallCredentials.from(creds);
    }
    return null;
}

19 Source : StorageConfig.java
with BSD 3-Clause "New" or "Revised" License
from all-of-us

@Bean(name = WGS_EXTRACTION_STORAGE)
@RequestScope(proxyMode = ScopedProxyMode.DEFAULT)
Storage wgsExtractionStorage(@Qualifier(FireCloudConfig.WGS_EXTRACTION_SA_CREDENTIALS) Credentials credentials) {
    return StorageOptions.newBuilder().setCredentials(credentials).build().getService();
}

18 Source : LoggingAppender.java
with Apache License 2.0
from spring-cloud

/**
 * Wraps {@link com.google.cloud.logging.logback.LoggingAppender#getLoggingOptions()} to
 * add {@link UserAgentHeaderProvider} configuration, so that usage can be properly
 * attributed to Spring Cloud GCP.
 */
@Override
protected LoggingOptions getLoggingOptions() {
    if (loggingOptions == null) {
        LoggingOptions.Builder loggingOptionsBuilder = LoggingOptions.newBuilder();
        // only credentials are set in the options of the parent clreplaced
        Credentials credentials = super.getLoggingOptions().getCredentials();
        if (credentials != null) {
            loggingOptionsBuilder.setCredentials(credentials);
        }
        // set User-Agent
        loggingOptionsBuilder.setHeaderProvider(new UserAgentHeaderProvider(this.getClreplaced()));
        this.loggingOptions = loggingOptionsBuilder.build();
    }
    return this.loggingOptions;
}

18 Source : KmsDecrypter.java
with Apache License 2.0
from spotify

private CloudKMS kms() throws IOException {
    final HttpTransport transport = transport().orElseGet(Utils::getDefaultTransport);
    final JsonFactory jsonFactory = Utils.getDefaultJsonFactory();
    final Credentials credentials = credentials().isPresent() ? credentials().get() : GoogleCredentials.getApplicationDefault();
    return KmsDecrypter.kms(transport, jsonFactory, new HttpCredentialsAdapter(scoped(credentials)));
}

18 Source : KmsDecrypter.java
with Apache License 2.0
from spotify

private static Credentials scoped(final Credentials credentials) {
    if (credentials instanceof GoogleCredentials) {
        return ((GoogleCredentials) credentials).createScoped(CloudKMSScopes.all());
    }
    return credentials;
}

18 Source : GCSConfig.java
with Apache License 2.0
from spinnaker

public static Storage getGoogleCloudStorage(@Qualifier("gcsCredentials") Credentials credentials, GcsProperties properties) {
    return StorageOptions.newBuilder().setCredentials(credentials).setProjectId(properties.getProject()).build().getService();
}

18 Source : ExampleUtils.java
with MIT License
from Rookout

private static HttpRequestInitializer chainHttpRequestInitializer(Credentials credential, HttpRequestInitializer httpRequestInitializer) {
    if (credential == null) {
        return new ChainingHttpRequestInitializer(new NullCredentialInitializer(), httpRequestInitializer);
    } else {
        return new ChainingHttpRequestInitializer(new HttpCredentialsAdapter(credential), httpRequestInitializer);
    }
}

18 Source : StorageUtil.java
with MIT License
from mercari

public static Storage storage() {
    final HttpTransport transport = new NetHttpTransport();
    final JsonFactory jsonFactory = new JacksonFactory();
    try {
        final Credentials credential = GoogleCredentials.getApplicationDefault();
        final HttpRequestInitializer initializer = new ChainingHttpRequestInitializer(new HttpCredentialsAdapter(credential), // Do not log 404. It clutters the output and is possibly even required by the caller.
        new RetryHttpRequestInitializer(ImmutableList.of(404)));
        return new Storage.Builder(transport, jsonFactory, initializer).setApplicationName("StorageClient").build();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

18 Source : BigQueryUtil.java
with MIT License
from mercari

private static Job getQueryDryRunJob(final String projectId, final String query) {
    final HttpTransport transport = new NetHttpTransport();
    final JsonFactory jsonFactory = new JacksonFactory();
    try {
        final Credentials credential = GoogleCredentials.getApplicationDefault();
        final HttpRequestInitializer initializer = new ChainingHttpRequestInitializer(new HttpCredentialsAdapter(credential), // Do not log 404. It clutters the output and is possibly even required by the caller.
        new RetryHttpRequestInitializer(ImmutableList.of(404)));
        final Bigquery bigquery = new Bigquery.Builder(transport, jsonFactory, initializer).setApplicationName("BigQueryClient").build();
        final String queryRunProjectId;
        if (projectId != null) {
            queryRunProjectId = projectId;
        } else {
            queryRunProjectId = getUserDefaultProject(credential);
        }
        return getQueryDryRunJob(bigquery, queryRunProjectId, query);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

18 Source : BigQueryUtil.java
with MIT License
from mercari

public static Bigquery getBigquery() {
    final HttpTransport transport = new NetHttpTransport();
    final JsonFactory jsonFactory = new JacksonFactory();
    try {
        final Credentials credential = GoogleCredentials.getApplicationDefault();
        final HttpRequestInitializer initializer = new ChainingHttpRequestInitializer(new HttpCredentialsAdapter(credential), // Do not log 404. It clutters the output and is possibly even required by the caller.
        new RetryHttpRequestInitializer(ImmutableList.of(404)));
        return new Bigquery.Builder(transport, jsonFactory, initializer).setApplicationName("BigQueryClient").build();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

18 Source : BigQueryUtil.java
with MIT License
from mercari

public static TableSchema getTableSchemaFromTable(final String tableName, final String defaultProjectId) {
    final Bigquery bigquery = getBigquery();
    try {
        final Credentials credential = GoogleCredentials.getApplicationDefault();
        final String queryRunProjectId;
        if (defaultProjectId != null) {
            queryRunProjectId = defaultProjectId;
        } else {
            queryRunProjectId = getUserDefaultProject(credential);
        }
        final TableReference tableReference = getTableReference(tableName, queryRunProjectId);
        final Table table = bigquery.tables().get(tableReference.getProjectId(), tableReference.getDatasetId(), tableReference.getTableId()).execute();
        return table.getSchema();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

18 Source : DatastoreIntegrationTestConfiguration.java
with Apache License 2.0
from GoogleCloudPlatform

/**
 * Config clreplaced for the integration tests.
 *
 * @author Chengyuan Zhao
 */
@Configuration
@PropertySource("application-test.properties")
@EnableDatastoreRepositories
@EnableTransactionManagement
public clreplaced DatastoreIntegrationTestConfiguration {

    private final String projectId = new DefaultGcpProjectIdProvider().getProjectId();

    private final Credentials credentials = new DefaultCredentialsProvider(com.google.cloud.spring.core.Credentials::new).getCredentials();

    @Value("${test.integration.datastore.namespacePrefix}")
    private String namespacePrefix;

    public DatastoreIntegrationTestConfiguration() throws IOException {
    }

    @Bean
    public TransactionalTemplateService transactionalTemplateService() {
        return new TransactionalTemplateService();
    }

    @Bean
    DatastoreTransactionManager datastoreTransactionManager(Datastore datastore) {
        return new DatastoreTransactionManager(() -> datastore);
    }

    @Bean
    public Datastore datastore() {
        DatastoreOptions.Builder builder = DatastoreOptions.newBuilder().setProjectId(this.projectId).setHeaderProvider(new UserAgentHeaderProvider(this.getClreplaced())).setCredentials(this.credentials);
        if (this.namespacePrefix != null) {
            builder.setNamespace(this.namespacePrefix + System.currentTimeMillis());
        }
        return builder.build().getService();
    }

    @Bean
    public DatastoreMappingContext datastoreMappingContext() {
        return new DatastoreMappingContext();
    }

    @Bean
    public DatastoreEnreplacedyConverter datastoreEnreplacedyConverter(DatastoreMappingContext datastoreMappingContext, ObjectToKeyFactory objectToKeyFactory) {
        return new DefaultDatastoreEnreplacedyConverter(datastoreMappingContext, objectToKeyFactory);
    }

    @Bean
    public ObjectToKeyFactory objectToKeyFactory(Datastore datastore) {
        return new DatastoreServiceObjectToKeyFactory(() -> datastore);
    }

    @Bean
    public DatastoreTemplate datastoreTemplate(Datastore datastore, DatastoreMappingContext datastoreMappingContext, DatastoreEnreplacedyConverter datastoreEnreplacedyConverter, ObjectToKeyFactory objectToKeyFactory) {
        return new DatastoreTemplate(() -> datastore, datastoreEnreplacedyConverter, datastoreMappingContext, objectToKeyFactory);
    }
}

18 Source : TraceExporter.java
with Apache License 2.0
from GoogleCloudPlatform

public static TraceExporter createWithConfiguration(TraceConfiguration configuration) throws IOException {
    String projectId = configuration.getProjectId();
    TraceServiceStub stub = configuration.getTraceServiceStub();
    if (stub == null) {
        Credentials credentials = configuration.getCredentials() == null ? GoogleCredentials.getApplicationDefault() : configuration.getCredentials();
        return TraceExporter.createWithCredentials(projectId, credentials, configuration.getFixedAttributes(), configuration.getDeadline());
    }
    return TraceExporter.createWithClient(projectId, new CloudTraceClientImpl(TraceServiceClient.create(stub)), configuration.getFixedAttributes());
}

18 Source : MetricConfigurationTest.java
with Apache License 2.0
from GoogleCloudPlatform

@RunWith(JUnit4.clreplaced)
public clreplaced MetricConfigurationTest {

    private static final Credentials FAKE_CREDENTIALS = GoogleCredentials.newBuilder().setAccessToken(new AccessToken("fake", new Date(100))).build();

    private static final String PROJECT_ID = "project";

    @Test
    public void testDefaultConfigurationSucceeds() {
        MetricConfiguration configuration = MetricConfiguration.builder().setProjectId(PROJECT_ID).build();
        replacedertNull(configuration.getCredentials());
        replacedertEquals(PROJECT_ID, configuration.getProjectId());
        replacedertNull(configuration.getMetricServiceStub());
    }

    @Test
    public void testSetAllConfigurationFieldsSucceeds() {
        MetricConfiguration configuration = MetricConfiguration.builder().setProjectId(PROJECT_ID).setCredentials(FAKE_CREDENTIALS).build();
        replacedertEquals(FAKE_CREDENTIALS, configuration.getCredentials());
        replacedertEquals(PROJECT_ID, configuration.getProjectId());
    }

    @Test
    public void testConfigurationWithNullProjectIdFails() {
        Builder builder = MetricConfiguration.builder();
        replacedertThrows(NullPointerException.clreplaced, () -> builder.setProjectId(null));
    }

    @Test
    public void testConfigurationWithEmptyProjectIdFails() {
        Builder builder = MetricConfiguration.builder();
        builder.setProjectId("");
        replacedertThrows(IllegalArgumentException.clreplaced, builder::build);
    }

    @Test
    public void testConfigurationWithDefaultProjectIdSucceeds() {
        String defaultProjectId = ServiceOptions.getDefaultProjectId();
        if (defaultProjectId != null) {
            MetricConfiguration configuration = MetricConfiguration.builder().build();
            replacedertEquals(defaultProjectId, configuration.getProjectId());
        }
    }
}

18 Source : FakeApiCallContext.java
with Apache License 2.0
from GoogleCloudPlatform

@Override
public ApiCallContext withCredentials(Credentials credentials) {
    return this.toBuilder().setCredentials(credentials).build();
}

18 Source : GcloudAuthModule.java
with MIT License
from curioswitch

@Provides
@Singleton
public static AccessTokenProvider accessTokenProvider(AccessTokenProvider.Factory factory, Credentials credentials) {
    return factory.create(credentials);
}

18 Source : StackdriverTraceConfigurationTest.java
with Apache License 2.0
from census-instrumentation

/**
 * Unit tests for {@link StackdriverTraceConfiguration}.
 */
@RunWith(JUnit4.clreplaced)
public clreplaced StackdriverTraceConfigurationTest {

    private static final Credentials FAKE_CREDENTIALS = GoogleCredentials.newBuilder().setAccessToken(new AccessToken("fake", new Date(100))).build();

    private static final String PROJECT_ID = "project";

    private static final Duration ONE_MINUTE = Duration.create(60, 0);

    private static final Duration NEG_ONE_MINUTE = Duration.create(-60, 0);

    @Rule
    public final ExpectedException thrown = ExpectedException.none();

    @Test
    public void defaultConfiguration() {
        StackdriverTraceConfiguration configuration;
        try {
            configuration = StackdriverTraceConfiguration.builder().build();
        } catch (Exception e) {
            // Some test hosts may not have cloud project ID set up.
            configuration = StackdriverTraceConfiguration.builder().setProjectId("test").build();
        }
        replacedertThat(configuration.getCredentials()).isNull();
        replacedertThat(configuration.getProjectId()).isNotNull();
        replacedertThat(configuration.getTraceServiceStub()).isNull();
        replacedertThat(configuration.getFixedAttributes()).isEmpty();
        replacedertThat(configuration.getDeadline()).isEqualTo(StackdriverTraceConfiguration.DEFAULT_DEADLINE);
    }

    @Test
    public void updateAll() {
        Map<String, AttributeValue> attributes = Collections.singletonMap("key", AttributeValue.stringAttributeValue("val"));
        StackdriverTraceConfiguration configuration = StackdriverTraceConfiguration.builder().setCredentials(FAKE_CREDENTIALS).setProjectId(PROJECT_ID).setFixedAttributes(attributes).setDeadline(ONE_MINUTE).build();
        replacedertThat(configuration.getCredentials()).isEqualTo(FAKE_CREDENTIALS);
        replacedertThat(configuration.getProjectId()).isEqualTo(PROJECT_ID);
        replacedertThat(configuration.getFixedAttributes()).isEqualTo(attributes);
        replacedertThat(configuration.getDeadline()).isEqualTo(ONE_MINUTE);
    }

    @Test
    public void disallowNullProjectId() {
        StackdriverTraceConfiguration.Builder builder = StackdriverTraceConfiguration.builder();
        thrown.expect(NullPointerException.clreplaced);
        builder.setProjectId(null);
    }

    @Test
    public void disallowEmptyProjectId() {
        StackdriverTraceConfiguration.Builder builder = StackdriverTraceConfiguration.builder();
        builder.setProjectId("");
        thrown.expect(IllegalArgumentException.clreplaced);
        builder.build();
    }

    @Test
    public void allowToUseDefaultProjectId() {
        String defaultProjectId = ServiceOptions.getDefaultProjectId();
        if (defaultProjectId != null) {
            StackdriverTraceConfiguration configuration = StackdriverTraceConfiguration.builder().build();
            replacedertThat(configuration.getProjectId()).isEqualTo(defaultProjectId);
        }
    }

    @Test
    public void disallowNullFixedAttributes() {
        StackdriverTraceConfiguration.Builder builder = StackdriverTraceConfiguration.builder().setProjectId("test");
        thrown.expect(NullPointerException.clreplaced);
        builder.setFixedAttributes(null);
    }

    @Test
    public void disallowNullFixedAttributeKey() {
        StackdriverTraceConfiguration.Builder builder = StackdriverTraceConfiguration.builder().setProjectId("test");
        Map<String, AttributeValue> attributes = Collections.singletonMap(null, AttributeValue.stringAttributeValue("val"));
        builder.setFixedAttributes(attributes);
        thrown.expect(NullPointerException.clreplaced);
        builder.build();
    }

    @Test
    public void disallowNullFixedAttributeValue() {
        StackdriverTraceConfiguration.Builder builder = StackdriverTraceConfiguration.builder().setProjectId("test");
        Map<String, AttributeValue> attributes = Collections.singletonMap("key", null);
        builder.setFixedAttributes(attributes);
        thrown.expect(NullPointerException.clreplaced);
        builder.build();
    }

    @Test
    public void disallowZeroDuration() {
        StackdriverTraceConfiguration.Builder builder = StackdriverTraceConfiguration.builder().setProjectId("test");
        builder.setDeadline(StackdriverTraceConfiguration.Builder.ZERO);
        thrown.expect(IllegalArgumentException.clreplaced);
        builder.build();
    }

    @Test
    public void disallowNegativeDuration() {
        StackdriverTraceConfiguration.Builder builder = StackdriverTraceConfiguration.builder().setProjectId("test");
        builder.setDeadline(NEG_ONE_MINUTE);
        thrown.expect(IllegalArgumentException.clreplaced);
        builder.build();
    }
}

18 Source : StackdriverTraceExporter.java
with Apache License 2.0
from census-instrumentation

/**
 * Creates and registers the Stackdriver Trace exporter to the OpenCensus library. Only one
 * Stackdriver exporter can be registered at any point.
 *
 * <p>If the {@code credentials} in the provided {@link StackdriverTraceConfiguration} is not set,
 * the exporter will use the default application credentials. See {@link
 * GoogleCredentials#getApplicationDefault}.
 *
 * <p>If the {@code projectId} in the provided {@link StackdriverTraceConfiguration} is not set,
 * the exporter will use the default project ID. See {@link ServiceOptions#getDefaultProjectId}.
 *
 * @param configuration the {@code StackdriverTraceConfiguration} used to create the exporter.
 * @throws IllegalStateException if a Stackdriver exporter is already registered.
 * @since 0.12
 */
public static void createAndRegister(StackdriverTraceConfiguration configuration) throws IOException {
    synchronized (monitor) {
        checkState(handler == null, "Stackdriver exporter is already registered.");
        Credentials credentials = configuration.getCredentials();
        String projectId = configuration.getProjectId();
        StackdriverV2ExporterHandler handler;
        TraceServiceStub stub = configuration.getTraceServiceStub();
        if (stub == null) {
            handler = StackdriverV2ExporterHandler.createWithCredentials(projectId, credentials != null ? credentials : GoogleCredentials.getApplicationDefault(), configuration.getFixedAttributes(), configuration.getDeadline());
        } else {
            handler = StackdriverV2ExporterHandler.createWithStub(projectId, TraceServiceClient.create(stub), configuration.getFixedAttributes());
        }
        registerInternal(handler);
    }
}

18 Source : StackdriverStatsExporterTest.java
with Apache License 2.0
from census-instrumentation

/**
 * Unit tests for {@link StackdriverStatsExporter}.
 */
@RunWith(JUnit4.clreplaced)
public clreplaced StackdriverStatsExporterTest {

    private static final String PROJECT_ID = "projectId";

    private static final Duration ONE_MINUTE = Duration.create(60, 0);

    private static final Duration NEG_ONE_MINUTE = Duration.create(-60, 0);

    private static final Credentials FAKE_CREDENTIALS = GoogleCredentials.newBuilder().setAccessToken(new AccessToken("fake", new Date(100))).build();

    private static final StackdriverStatsConfiguration CONFIGURATION = StackdriverStatsConfiguration.builder().setCredentials(FAKE_CREDENTIALS).setProjectId("project").build();

    @Rule
    public final ExpectedException thrown = ExpectedException.none();

    @Test
    public void createWithNullStackdriverStatsConfiguration() throws IOException {
        thrown.expect(NullPointerException.clreplaced);
        thrown.expectMessage("configuration");
        StackdriverStatsExporter.createAndRegister((StackdriverStatsConfiguration) null);
    }

    @Test
    public void createWithNegativeDuration_WithConfiguration() throws IOException {
        StackdriverStatsConfiguration configuration = StackdriverStatsConfiguration.builder().setCredentials(FAKE_CREDENTIALS).setProjectId(PROJECT_ID).setExportInterval(NEG_ONE_MINUTE).build();
        thrown.expect(IllegalArgumentException.clreplaced);
        thrown.expectMessage("Export interval must be positive");
        StackdriverStatsExporter.createAndRegister(configuration);
    }

    @Test
    @SuppressWarnings("deprecation")
    public void createWithNullCredentials() throws IOException {
        thrown.expect(NullPointerException.clreplaced);
        thrown.expectMessage("credentials");
        StackdriverStatsExporter.createAndRegisterWithCredentialsAndProjectId(null, PROJECT_ID, ONE_MINUTE);
    }

    @Test
    @SuppressWarnings("deprecation")
    public void createWithNullProjectId() throws IOException {
        thrown.expect(NullPointerException.clreplaced);
        thrown.expectMessage("projectId");
        StackdriverStatsExporter.createAndRegisterWithCredentialsAndProjectId(GoogleCredentials.newBuilder().build(), null, ONE_MINUTE);
    }

    @Test
    @SuppressWarnings("deprecation")
    public void createWithNullDuration() throws IOException {
        thrown.expect(NullPointerException.clreplaced);
        thrown.expectMessage("exportInterval");
        StackdriverStatsExporter.createAndRegisterWithCredentialsAndProjectId(GoogleCredentials.newBuilder().build(), PROJECT_ID, null);
    }

    @Test
    @SuppressWarnings("deprecation")
    public void createWithNegativeDuration() throws IOException {
        thrown.expect(IllegalArgumentException.clreplaced);
        thrown.expectMessage("Export interval must be positive");
        StackdriverStatsExporter.createAndRegisterWithCredentialsAndProjectId(GoogleCredentials.newBuilder().build(), PROJECT_ID, NEG_ONE_MINUTE);
    }

    @Test
    public void createExporterTwice() throws IOException {
        StackdriverStatsExporter.createAndRegister(CONFIGURATION);
        try {
            thrown.expect(IllegalStateException.clreplaced);
            thrown.expectMessage("Stackdriver stats exporter is already created.");
            StackdriverStatsExporter.createAndRegister(CONFIGURATION);
        } finally {
            StackdriverStatsExporter.unregister();
        }
    }

    @Test
    public void unregister() throws IOException {
        // unregister has no effect if exporter is not yet registered.
        StackdriverStatsExporter.unregister();
        try {
            StackdriverStatsExporter.createAndRegister(CONFIGURATION);
            StackdriverStatsExporter.unregister();
            StackdriverStatsExporter.createAndRegister(CONFIGURATION);
        } finally {
            StackdriverStatsExporter.unregister();
        }
    }

    @Test
    @SuppressWarnings("deprecation")
    public void createWithNullMonitoredResource() throws IOException {
        thrown.expect(NullPointerException.clreplaced);
        thrown.expectMessage("monitoredResource");
        StackdriverStatsExporter.createAndRegisterWithMonitoredResource(ONE_MINUTE, null);
    }

    @Test
    public void createMetricServiceClient() throws IOException {
        MetricServiceClient client;
        synchronized (StackdriverStatsExporter.monitor) {
            client = StackdriverStatsExporter.createMetricServiceClient(FAKE_CREDENTIALS, DEFAULT_DEADLINE);
        }
        replacedertThat(client.getSettings().getCredentialsProvider().getCredentials()).isEqualTo(FAKE_CREDENTIALS);
        replacedertThat(client.getSettings().getTransportChannelProvider()).isInstanceOf(InstantiatingGrpcChannelProvider.clreplaced);
        // There's no way to get HeaderProvider from TransportChannelProvider.
        replacedertThat(client.getSettings().getTransportChannelProvider().needsHeaders()).isFalse();
    }

    @Test
    public void createMetricServiceClient_WithoutCredentials() {
        try {
            MetricServiceClient client;
            synchronized (StackdriverStatsExporter.monitor) {
                client = StackdriverStatsExporter.createMetricServiceClient(null, DEFAULT_DEADLINE);
            }
            replacedertThat(client.getSettings().getCredentialsProvider()).isInstanceOf(GoogleCredentialsProvider.clreplaced);
            replacedertThat(client.getSettings().getTransportChannelProvider()).isInstanceOf(InstantiatingGrpcChannelProvider.clreplaced);
            // There's no way to get HeaderProvider from TransportChannelProvider.
            replacedertThat(client.getSettings().getTransportChannelProvider().needsHeaders()).isFalse();
        } catch (IOException e) {
        // This test depends on the Application Default Credentials settings (environment variable
        // GOOGLE_APPLICATION_CREDENTIALS). Some hosts may not have the expected environment settings
        // and this test should be skipped in that case.
        }
    }
}

18 Source : StackdriverStatsExporter.java
with Apache License 2.0
from census-instrumentation

// Use createInternal() (instead of constructor) to enforce singleton.
private static void createInternal(@Nullable Credentials credentials, String projectId, Duration exportInterval, MonitoredResource monitoredResource, @Nullable String metricNamePrefix, @Nullable String displayNamePrefix, Map<LabelKey, LabelValue> constantLabels, Duration deadline, @Nullable MetricServiceStub stub) throws IOException {
    synchronized (monitor) {
        checkState(instance == null, "Stackdriver stats exporter is already created.");
        MetricServiceClient client = stub == null ? createMetricServiceClient(credentials, deadline) : MetricServiceClient.create(stub);
        instance = new StackdriverStatsExporter(projectId, client, exportInterval, monitoredResource, metricNamePrefix, displayNamePrefix, constantLabels);
    }
}

18 Source : StackdriverStatsExporter.java
with Apache License 2.0
from census-instrumentation

// Initialize MetricServiceClient inside lock to avoid creating multiple clients.
@GuardedBy("monitor")
@VisibleForTesting
static MetricServiceClient createMetricServiceClient(@Nullable Credentials credentials, Duration deadline) throws IOException {
    MetricServiceSettings.Builder settingsBuilder = MetricServiceSettings.newBuilder().setTransportChannelProvider(InstantiatingGrpcChannelProvider.newBuilder().setHeaderProvider(OPENCENSUS_USER_AGENT_HEADER_PROVIDER).build());
    if (credentials != null) {
        settingsBuilder.setCredentialsProvider(FixedCredentialsProvider.create(credentials));
    }
    org.threeten.bp.Duration stackdriverDuration = org.threeten.bp.Duration.ofMillis(deadline.toMillis());
    // We use createMetricDescriptor and createTimeSeries APIs in this exporter.
    settingsBuilder.createMetricDescriptorSettings().setSimpleTimeoutNoRetries(stackdriverDuration);
    settingsBuilder.createTimeSeriesSettings().setSimpleTimeoutNoRetries(stackdriverDuration);
    return MetricServiceClient.create(settingsBuilder.build());
}

18 Source : GoogleCredentialsInterceptor.java
with GNU Affero General Public License v3.0
from brandall76

/**
 * Authenticates the gRPC channel.
 */
public clreplaced GoogleCredentialsInterceptor implements ClientInterceptor {

    private final Credentials mCredentials;

    private Metadata mCached;

    private Map<String, List<String>> mLastMetadata;

    public GoogleCredentialsInterceptor(Credentials credentials) {
        mCredentials = credentials;
    }

    @Override
    public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(final MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, final Channel next) {
        return new ClientInterceptors.CheckedForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {

            @Override
            protected void checkedStart(Listener<RespT> responseListener, Metadata headers) throws StatusException {
                Metadata cachedSaved;
                URI uri = serviceUri(next, method);
                synchronized (GoogleCredentialsInterceptor.this) {
                    Map<String, List<String>> latestMetadata = getRequestMetadata(uri);
                    if (mLastMetadata == null || mLastMetadata != latestMetadata) {
                        mLastMetadata = latestMetadata;
                        mCached = toHeaders(mLastMetadata);
                    }
                    cachedSaved = mCached;
                }
                headers.merge(cachedSaved);
                delegate().start(responseListener, headers);
            }
        };
    }

    /**
     * Generate a JWT-specific service URI. The URI is simply an identifier with enough
     * information for a service to know that the JWT was intended for it. The URI will
     * commonly be verified with a simple string equality check.
     */
    private URI serviceUri(Channel channel, MethodDescriptor<?, ?> method) throws StatusException {
        String authority = channel.authority();
        if (authority == null) {
            throw Status.UNAUTHENTICATED.withDescription("Channel has no authority").asException();
        }
        // Always use HTTPS, by definition.
        final String scheme = "https";
        final int defaultPort = 443;
        String path = "/" + MethodDescriptor.extractFullServiceName(method.getFullMethodName());
        URI uri;
        try {
            uri = new URI(scheme, authority, path, null, null);
        } catch (URISyntaxException e) {
            throw Status.UNAUTHENTICATED.withDescription("Unable to construct service URI for auth").withCause(e).asException();
        }
        // The default port must not be present. Alternative ports should be present.
        if (uri.getPort() == defaultPort) {
            uri = removePort(uri);
        }
        return uri;
    }

    private URI removePort(URI uri) throws StatusException {
        try {
            return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), -1, /* port */
            uri.getPath(), uri.getQuery(), uri.getFragment());
        } catch (URISyntaxException e) {
            throw Status.UNAUTHENTICATED.withDescription("Unable to construct service URI after removing port").withCause(e).asException();
        }
    }

    private Map<String, List<String>> getRequestMetadata(URI uri) throws StatusException {
        try {
            return mCredentials.getRequestMetadata(uri);
        } catch (IOException e) {
            throw Status.UNAUTHENTICATED.withCause(e).asException();
        }
    }

    private static Metadata toHeaders(Map<String, List<String>> metadata) {
        Metadata headers = new Metadata();
        if (metadata != null) {
            for (String key : metadata.keySet()) {
                Metadata.Key<String> headerKey = Metadata.Key.of(key, Metadata.ASCII_STRING_MARSHALLER);
                for (String value : metadata.get(key)) {
                    headers.put(headerKey, value);
                }
            }
        }
        return headers;
    }
}

18 Source : HttpBlobStore.java
with Apache License 2.0
from bazelbuild

public static HttpBlobStore create(URI uri, int timeoutMillis, int remoteMaxConnections, @Nullable final Credentials creds) throws URISyntaxException, SSLException {
    return new HttpBlobStore(NioEventLoopGroup::new, NioSocketChannel.clreplaced, uri, timeoutMillis, remoteMaxConnections, creds, null);
}

18 Source : AbstractHttpHandler.java
with Apache License 2.0
from bazelbuild

/**
 * Common functionality shared by concrete clreplacedes.
 */
abstract clreplaced AbstractHttpHandler<T extends HttpObject> extends SimpleChannelInboundHandler<T> implements ChannelOutboundHandler {

    private final Credentials credentials;

    public AbstractHttpHandler(Credentials credentials) {
        this.credentials = credentials;
    }

    protected ChannelPromise userPromise;

    @SuppressWarnings("FutureReturnValueIgnored")
    protected void failAndResetUserPromise(Throwable t) {
        if (userPromise != null && !userPromise.isDone()) {
            userPromise.setFailure(t);
        }
        userPromise = null;
    }

    @SuppressWarnings("FutureReturnValueIgnored")
    protected void succeedAndResetUserPromise() {
        userPromise.setSuccess();
        userPromise = null;
    }

    protected void addCredentialHeaders(HttpRequest request, URI uri) throws IOException {
        String userInfo = uri.getUserInfo();
        if (userInfo != null) {
            String value = BaseEncoding.base64Url().encode(userInfo.getBytes(Charsets.UTF_8));
            request.headers().set(HttpHeaderNames.AUTHORIZATION, "Basic " + value);
            return;
        }
        if (credentials == null || !credentials.hasRequestMetadata()) {
            return;
        }
        Map<String, List<String>> authHeaders = credentials.getRequestMetadata(uri);
        if (authHeaders == null || authHeaders.isEmpty()) {
            return;
        }
        for (Map.Entry<String, List<String>> entry : authHeaders.entrySet()) {
            String name = entry.getKey();
            for (String value : entry.getValue()) {
                request.headers().add(name, value);
            }
        }
    }

    protected String constructPath(URI uri, String hash, boolean isCas) {
        StringBuilder builder = new StringBuilder();
        builder.append(uri.getPath());
        if (!uri.getPath().endsWith("/")) {
            builder.append('/');
        }
        builder.append(isCas ? "cas/" : "ac/").append(hash);
        return builder.toString();
    }

    protected String constructHost(URI uri) {
        return uri.getHost() + ":" + uri.getPort();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable t) {
        failAndResetUserPromise(t);
        ctx.fireExceptionCaught(t);
    }

    @SuppressWarnings("FutureReturnValueIgnored")
    @Override
    public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) {
        ctx.bind(localAddress, promise);
    }

    @SuppressWarnings("FutureReturnValueIgnored")
    @Override
    public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {
        ctx.connect(remoteAddress, localAddress, promise);
    }

    @SuppressWarnings("FutureReturnValueIgnored")
    @Override
    public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) {
        failAndResetUserPromise(new ClosedChannelException());
        ctx.disconnect(promise);
    }

    @SuppressWarnings("FutureReturnValueIgnored")
    @Override
    public void close(ChannelHandlerContext ctx, ChannelPromise promise) {
        failAndResetUserPromise(new ClosedChannelException());
        ctx.close(promise);
    }

    @SuppressWarnings("FutureReturnValueIgnored")
    @Override
    public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) {
        failAndResetUserPromise(new ClosedChannelException());
        ctx.deregister(promise);
    }

    @SuppressWarnings("FutureReturnValueIgnored")
    @Override
    public void read(ChannelHandlerContext ctx) {
        ctx.read();
    }

    @SuppressWarnings("FutureReturnValueIgnored")
    @Override
    public void flush(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        failAndResetUserPromise(new ClosedChannelException());
        ctx.fireChannelInactive();
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        failAndResetUserPromise(new IOException("handler removed"));
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) {
        failAndResetUserPromise(new ClosedChannelException());
        ctx.fireChannelUnregistered();
    }
}

17 Source : GcsFileSystemRegistrar.java
with Apache License 2.0
from spotify

@Override
public Iterable<FileSystem> load(Map<String, String> env) {
    Credentials credentials = getCredentials(env);
    StorageOptions options = StorageOptions.getDefaultInstance().toBuilder().setCredentials(credentials).build();
    return Collections.singletonList(new GcsFileSystem(options.getService()));
}

17 Source : GCSValidator.java
with Apache License 2.0
from spinnaker

@Override
public void validate(ConfigProblemSetBuilder ps, GcsPersistentStore n) {
    GcsProperties gcsProperties = getGoogleCloudStorageProperties(n);
    try {
        Credentials credentials = GCSConfig.getGcsCredentials(gcsProperties);
        Storage googleCloudStorage = GCSConfig.getGoogleCloudStorage(credentials, gcsProperties);
        ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat(GcsStorageService.clreplaced.getName() + "-%s").build());
        GcsStorageService storageService = new GcsStorageService(googleCloudStorage, n.getBucket(), n.getBucketLocation(), n.getRootFolder(), n.getProject(), new ObjectMapper(), executor);
        storageService.ensureBucketExists();
    } catch (Exception e) {
        ps.addProblem(Severity.ERROR, "Failed to ensure the required bucket \"" + n.getBucket() + "\" exists: " + e.getMessage());
    }
}

17 Source : GoogleAuthLibraryCallCredentials.java
with Apache License 2.0
from grpc-nebula

/**
 * Wraps {@link Credentials} as a {@link CallCredentials}.
 */
final clreplaced GoogleAuthLibraryCallCredentials extends CallCredentials2 {

    private static final Logger log = Logger.getLogger(GoogleAuthLibraryCallCredentials.clreplaced.getName());

    private static final JwtHelper jwtHelper = createJwtHelperOrNull(GoogleAuthLibraryCallCredentials.clreplaced.getClreplacedLoader());

    private static final Clreplaced<? extends Credentials> googleCredentialsClreplaced = loadGoogleCredentialsClreplaced();

    private final boolean requirePrivacy;

    @VisibleForTesting
    final Credentials creds;

    private Metadata lastHeaders;

    private Map<String, List<String>> lastMetadata;

    public GoogleAuthLibraryCallCredentials(Credentials creds) {
        this(creds, jwtHelper);
    }

    @VisibleForTesting
    GoogleAuthLibraryCallCredentials(Credentials creds, JwtHelper jwtHelper) {
        checkNotNull(creds, "creds");
        boolean requirePrivacy = false;
        if (googleCredentialsClreplaced != null) {
            // All GoogleCredentials instances are bearer tokens and should only be used on private
            // channels. This catches all return values from GoogleCredentials.getApplicationDefault().
            // This should be checked before upgrading the Service Account to JWT, as JWT is also a bearer
            // token.
            requirePrivacy = googleCredentialsClreplaced.isInstance(creds);
        }
        if (jwtHelper != null) {
            creds = jwtHelper.tryServiceAccountToJwt(creds);
        }
        this.requirePrivacy = requirePrivacy;
        this.creds = creds;
    }

    @Override
    public void thisUsesUnstableApi() {
    }

    @Override
    public void applyRequestMetadata(RequestInfo info, Executor appExecutor, final MetadataApplier applier) {
        SecurityLevel security = info.getSecurityLevel();
        if (requirePrivacy && security != SecurityLevel.PRIVACY_AND_INTEGRITY) {
            applier.fail(Status.UNAUTHENTICATED.withDescription("Credentials require channel with PRIVACY_AND_INTEGRITY security level. " + "Observed security level: " + security));
            return;
        }
        String authority = checkNotNull(info.getAuthority(), "authority");
        final URI uri;
        try {
            uri = serviceUri(authority, info.getMethodDescriptor());
        } catch (StatusException e) {
            applier.fail(e.getStatus());
            return;
        }
        // Credentials is expected to manage caching internally if the metadata is fetched over
        // the network.
        creds.getRequestMetadata(uri, appExecutor, new RequestMetadataCallback() {

            @Override
            public void onSuccess(Map<String, List<String>> metadata) {
                // Some implementations may preplaced null metadata.
                // Re-use the headers if getRequestMetadata() returns the same map. It may return a
                // different map based on the provided URI, i.e., for JWT. However, today it does not
                // cache JWT and so we won't bother tring to save its return value based on the URI.
                Metadata headers;
                try {
                    synchronized (GoogleAuthLibraryCallCredentials.this) {
                        if (lastMetadata == null || lastMetadata != metadata) {
                            lastHeaders = toHeaders(metadata);
                            lastMetadata = metadata;
                        }
                        headers = lastHeaders;
                    }
                } catch (Throwable t) {
                    applier.fail(Status.UNAUTHENTICATED.withDescription("Failed to convert credential metadata").withCause(t));
                    return;
                }
                applier.apply(headers);
            }

            @Override
            public void onFailure(Throwable e) {
                if (e instanceof IOException) {
                    // Since it's an I/O failure, let the call be retried with UNAVAILABLE.
                    applier.fail(Status.UNAVAILABLE.withDescription("Credentials failed to obtain metadata").withCause(e));
                } else {
                    applier.fail(Status.UNAUTHENTICATED.withDescription("Failed computing credential metadata").withCause(e));
                }
            }
        });
    }

    /**
     * Generate a JWT-specific service URI. The URI is simply an identifier with enough information
     * for a service to know that the JWT was intended for it. The URI will commonly be verified with
     * a simple string equality check.
     */
    private static URI serviceUri(String authority, MethodDescriptor<?, ?> method) throws StatusException {
        // Always use HTTPS, by definition.
        final String scheme = "https";
        final int defaultPort = 443;
        String path = "/" + MethodDescriptor.extractFullServiceName(method.getFullMethodName());
        URI uri;
        try {
            uri = new URI(scheme, authority, path, null, null);
        } catch (URISyntaxException e) {
            throw Status.UNAUTHENTICATED.withDescription("Unable to construct service URI for auth").withCause(e).asException();
        }
        // The default port must not be present. Alternative ports should be present.
        if (uri.getPort() == defaultPort) {
            uri = removePort(uri);
        }
        return uri;
    }

    private static URI removePort(URI uri) throws StatusException {
        try {
            return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), -1, /* port */
            uri.getPath(), uri.getQuery(), uri.getFragment());
        } catch (URISyntaxException e) {
            throw Status.UNAUTHENTICATED.withDescription("Unable to construct service URI after removing port").withCause(e).asException();
        }
    }

    // BaseEncoding is stable in Guava 20.0
    @SuppressWarnings("BetaApi")
    private static Metadata toHeaders(@Nullable Map<String, List<String>> metadata) {
        Metadata headers = new Metadata();
        if (metadata != null) {
            for (String key : metadata.keySet()) {
                if (key.endsWith("-bin")) {
                    Metadata.Key<byte[]> headerKey = Metadata.Key.of(key, Metadata.BINARY_BYTE_MARSHALLER);
                    for (String value : metadata.get(key)) {
                        headers.put(headerKey, BaseEncoding.base64().decode(value));
                    }
                } else {
                    Metadata.Key<String> headerKey = Metadata.Key.of(key, Metadata.ASCII_STRING_MARSHALLER);
                    for (String value : metadata.get(key)) {
                        headers.put(headerKey, value);
                    }
                }
            }
        }
        return headers;
    }

    @VisibleForTesting
    @Nullable
    static JwtHelper createJwtHelperOrNull(ClreplacedLoader loader) {
        Clreplaced<?> rawServiceAccountClreplaced;
        try {
            // Specify loader so it can be overridden in tests
            rawServiceAccountClreplaced = Clreplaced.forName("com.google.auth.oauth2.ServiceAccountCredentials", false, loader);
        } catch (ClreplacedNotFoundException ex) {
            return null;
        }
        Exception caughtException;
        try {
            return new JwtHelper(rawServiceAccountClreplaced, loader);
        } catch (ClreplacedNotFoundException ex) {
            caughtException = ex;
        } catch (NoSuchMethodException ex) {
            caughtException = ex;
        }
        if (caughtException != null) {
            // Failure is a bug in this clreplaced, but we still choose to gracefully recover
            log.log(Level.WARNING, "Failed to create JWT helper. This is unexpected", caughtException);
        }
        return null;
    }

    @Nullable
    private static Clreplaced<? extends Credentials> loadGoogleCredentialsClreplaced() {
        Clreplaced<?> rawGoogleCredentialsClreplaced;
        try {
            // Can't use a loader as it disables ProGuard's reference detection and would fail to rename
            // this reference. Unfortunately this will initialize the clreplaced.
            rawGoogleCredentialsClreplaced = Clreplaced.forName("com.google.auth.oauth2.GoogleCredentials");
        } catch (ClreplacedNotFoundException ex) {
            log.log(Level.FINE, "Failed to load GoogleCredentials", ex);
            return null;
        }
        return rawGoogleCredentialsClreplaced.replacedubclreplaced(Credentials.clreplaced);
    }

    @VisibleForTesting
    static clreplaced JwtHelper {

        private final Clreplaced<? extends Credentials> serviceAccountClreplaced;

        private final Constructor<? extends Credentials> jwtConstructor;

        private final Method getScopes;

        private final Method getClientId;

        private final Method getClientEmail;

        private final Method getPrivateKey;

        private final Method getPrivateKeyId;

        public JwtHelper(Clreplaced<?> rawServiceAccountClreplaced, ClreplacedLoader loader) throws ClreplacedNotFoundException, NoSuchMethodException {
            serviceAccountClreplaced = rawServiceAccountClreplaced.replacedubclreplaced(Credentials.clreplaced);
            getScopes = serviceAccountClreplaced.getMethod("getScopes");
            getClientId = serviceAccountClreplaced.getMethod("getClientId");
            getClientEmail = serviceAccountClreplaced.getMethod("getClientEmail");
            getPrivateKey = serviceAccountClreplaced.getMethod("getPrivateKey");
            getPrivateKeyId = serviceAccountClreplaced.getMethod("getPrivateKeyId");
            Clreplaced<? extends Credentials> jwtClreplaced = Clreplaced.forName("com.google.auth.oauth2.ServiceAccountJwtAccessCredentials", false, loader).replacedubclreplaced(Credentials.clreplaced);
            jwtConstructor = jwtClreplaced.getConstructor(String.clreplaced, String.clreplaced, PrivateKey.clreplaced, String.clreplaced);
        }

        public Credentials tryServiceAccountToJwt(Credentials creds) {
            if (!serviceAccountClreplaced.isInstance(creds)) {
                return creds;
            }
            Exception caughtException;
            try {
                creds = serviceAccountClreplaced.cast(creds);
                Collection<?> scopes = (Collection<?>) getScopes.invoke(creds);
                if (scopes.size() != 0) {
                    // Leave as-is, since the scopes may limit access within the service.
                    return creds;
                }
                return jwtConstructor.newInstance(getClientId.invoke(creds), getClientEmail.invoke(creds), getPrivateKey.invoke(creds), getPrivateKeyId.invoke(creds));
            } catch (IllegalAccessException ex) {
                caughtException = ex;
            } catch (InvocationTargetException ex) {
                caughtException = ex;
            } catch (InstantiationException ex) {
                caughtException = ex;
            }
            if (caughtException != null) {
                // Failure is a bug in this clreplaced, but we still choose to gracefully recover
                log.log(Level.WARNING, "Failed converting service account credential to JWT. This is unexpected", caughtException);
            }
            return creds;
        }
    }
}

17 Source : ClientAuthInterceptor.java
with Apache License 2.0
from grpc-nebula

/**
 * Client interceptor that authenticates all calls by binding header data provided by a credential.
 * Typically this will populate the Authorization header but other headers may also be filled out.
 *
 * <p>Uses the new and simplified Google auth library:
 * https://github.com/google/google-auth-library-java
 *
 * @deprecated use {@link MoreCallCredentials#from(Credentials)} instead.
 */
@Deprecated
public final clreplaced ClientAuthInterceptor implements ClientInterceptor {

    private final Credentials credentials;

    private Metadata cached;

    private Map<String, List<String>> lastMetadata;

    public ClientAuthInterceptor(Credentials credentials, @SuppressWarnings("unused") Executor executor) {
        this.credentials = Preconditions.checkNotNull(credentials, "credentials");
    // TODO(louiscryan): refresh token asynchronously with this executor.
    }

    @Override
    public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(final MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, final Channel next) {
        // TODO(ejona86): If the call fails for Auth reasons, this does not properly propagate info that
        // would be in WWW-Authenticate, because it does not yet have access to the header.
        return new CheckedForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {

            @Override
            protected void checkedStart(Listener<RespT> responseListener, Metadata headers) throws StatusException {
                Metadata cachedSaved;
                URI uri = serviceUri(next, method);
                synchronized (ClientAuthInterceptor.this) {
                    // TODO(louiscryan): This is icky but the current auth library stores the same
                    // metadata map until the next refresh cycle. This will be fixed once
                    // https://github.com/google/google-auth-library-java/issues/3
                    // is resolved.
                    // getRequestMetadata() may return a different map based on the provided URI, i.e., for
                    // JWT. However, today it does not cache JWT and so we won't bother tring to cache its
                    // return value based on the URI.
                    Map<String, List<String>> latestMetadata = getRequestMetadata(uri);
                    if (lastMetadata == null || lastMetadata != latestMetadata) {
                        lastMetadata = latestMetadata;
                        cached = toHeaders(lastMetadata);
                    }
                    cachedSaved = cached;
                }
                headers.merge(cachedSaved);
                delegate().start(responseListener, headers);
            }
        };
    }

    /**
     * Generate a JWT-specific service URI. The URI is simply an identifier with enough information
     * for a service to know that the JWT was intended for it. The URI will commonly be verified with
     * a simple string equality check.
     */
    private URI serviceUri(Channel channel, MethodDescriptor<?, ?> method) throws StatusException {
        String authority = channel.authority();
        if (authority == null) {
            throw Status.UNAUTHENTICATED.withDescription("Channel has no authority").asException();
        }
        // Always use HTTPS, by definition.
        final String scheme = "https";
        final int defaultPort = 443;
        String path = "/" + MethodDescriptor.extractFullServiceName(method.getFullMethodName());
        URI uri;
        try {
            uri = new URI(scheme, authority, path, null, null);
        } catch (URISyntaxException e) {
            throw Status.UNAUTHENTICATED.withDescription("Unable to construct service URI for auth").withCause(e).asException();
        }
        // The default port must not be present. Alternative ports should be present.
        if (uri.getPort() == defaultPort) {
            uri = removePort(uri);
        }
        return uri;
    }

    private URI removePort(URI uri) throws StatusException {
        try {
            return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), -1, /* port */
            uri.getPath(), uri.getQuery(), uri.getFragment());
        } catch (URISyntaxException e) {
            throw Status.UNAUTHENTICATED.withDescription("Unable to construct service URI after removing port").withCause(e).asException();
        }
    }

    private Map<String, List<String>> getRequestMetadata(URI uri) throws StatusException {
        try {
            return credentials.getRequestMetadata(uri);
        } catch (IOException e) {
            throw Status.UNAUTHENTICATED.withDescription("Unable to get request metadata").withCause(e).asException();
        }
    }

    private static final Metadata toHeaders(Map<String, List<String>> metadata) {
        Metadata headers = new Metadata();
        if (metadata != null) {
            for (String key : metadata.keySet()) {
                Metadata.Key<String> headerKey = Metadata.Key.of(key, Metadata.ASCII_STRING_MARSHALLER);
                for (String value : metadata.get(key)) {
                    headers.put(headerKey, value);
                }
            }
        }
        return headers;
    }
}

17 Source : TraceConfigurationTest.java
with Apache License 2.0
from GoogleCloudPlatform

/**
 * Unit tests for {@link TraceConfiguration}.
 */
@RunWith(JUnit4.clreplaced)
public clreplaced TraceConfigurationTest {

    private static final Credentials FAKE_CREDENTIALS = GoogleCredentials.newBuilder().setAccessToken(new AccessToken("fake", new Date(100))).build();

    private static final String PROJECT_ID = "project";

    private static final Duration ONE_MINUTE = Duration.ofSeconds(60, 0);

    private static final Duration NEG_ONE_MINUTE = Duration.ofSeconds(-60, 0);

    @Test
    public void defaultConfiguration() {
        // Some test hosts may not have cloud project ID set up, so setting it explicitly
        TraceConfiguration configuration = TraceConfiguration.builder().setProjectId("test").build();
        replacedertNull(configuration.getCredentials());
        replacedertNotNull(configuration.getProjectId());
        replacedertNull(configuration.getTraceServiceStub());
        replacedertTrue(configuration.getFixedAttributes().isEmpty());
        replacedertEquals(TraceConfiguration.DEFAULT_DEADLINE, configuration.getDeadline());
    }

    @Test
    public void setAllConfigurationFields() {
        Map<String, AttributeValue> attributes = Collections.singletonMap("key", AttributeValue.newBuilder().setBoolValue(true).build());
        // set all the fields different from their default values
        TraceConfiguration configuration = TraceConfiguration.builder().setCredentials(FAKE_CREDENTIALS).setProjectId(PROJECT_ID).setFixedAttributes(attributes).setDeadline(ONE_MINUTE).build();
        // make sure the changes are reflected
        replacedertEquals(FAKE_CREDENTIALS, configuration.getCredentials());
        replacedertEquals(PROJECT_ID, configuration.getProjectId());
        replacedertEquals(attributes, configuration.getFixedAttributes());
        replacedertEquals(ONE_MINUTE, configuration.getDeadline());
    }

    @Test
    public void disallowNullProjectId() {
        TraceConfiguration.Builder builder = TraceConfiguration.builder();
        replacedertThrows(NullPointerException.clreplaced, () -> builder.setProjectId(null));
    }

    @Test
    public void disallowEmptyProjectId() {
        TraceConfiguration.Builder builder = TraceConfiguration.builder();
        builder.setProjectId("");
        replacedertThrows(IllegalArgumentException.clreplaced, builder::build);
    }

    @Test
    public void allowToUseDefaultProjectId() {
        String defaultProjectId = ServiceOptions.getDefaultProjectId();
        // some test providers might not have project IDs set up
        if (defaultProjectId != null) {
            TraceConfiguration configuration = TraceConfiguration.builder().build();
            replacedertEquals(defaultProjectId, configuration.getProjectId());
        }
    }

    @Test
    public void disallowNullFixedAttributes() {
        TraceConfiguration.Builder builder = TraceConfiguration.builder().setProjectId("test");
        replacedertThrows(NullPointerException.clreplaced, () -> builder.setFixedAttributes(null));
    }

    @Test
    public void disallowNullFixedAttributeKey() {
        TraceConfiguration.Builder builder = TraceConfiguration.builder().setProjectId("test");
        Map<String, AttributeValue> attributes = Collections.singletonMap(null, AttributeValue.newBuilder().setBoolValue(true).build());
        builder.setFixedAttributes(attributes);
        replacedertThrows(NullPointerException.clreplaced, builder::build);
    }

    @Test
    public void disallowNullFixedAttributeValue() {
        TraceConfiguration.Builder builder = TraceConfiguration.builder().setProjectId("test");
        Map<String, AttributeValue> attributes = Collections.singletonMap("key", null);
        builder.setFixedAttributes(attributes);
        replacedertThrows(NullPointerException.clreplaced, builder::build);
    }

    @Test
    public void disallowZeroDuration() {
        TraceConfiguration.Builder builder = TraceConfiguration.builder().setProjectId("test");
        builder.setDeadline(TraceConfiguration.Builder.ZERO);
        replacedertThrows(IllegalArgumentException.clreplaced, builder::build);
    }

    @Test
    public void disallowNegativeDuration() {
        TraceConfiguration.Builder builder = TraceConfiguration.builder().setProjectId("test");
        builder.setDeadline(NEG_ONE_MINUTE);
        replacedertThrows(IllegalArgumentException.clreplaced, builder::build);
    }
}

17 Source : TraceExporter.java
with Apache License 2.0
from GoogleCloudPlatform

private static TraceExporter createWithCredentials(String projectId, Credentials credentials, Map<String, AttributeValue> fixedAttributes, Duration deadline) throws IOException {
    TraceServiceSettings.Builder builder = TraceServiceSettings.newBuilder().setCredentialsProvider(FixedCredentialsProvider.create(checkNotNull(credentials, "credentials")));
    // We only use the batchWriteSpans API in this exporter.
    builder.batchWriteSpansSettings().setSimpleTimeoutNoRetries(org.threeten.bp.Duration.ofMillis(deadline.toMillis()));
    return new TraceExporter(projectId, new CloudTraceClientImpl(TraceServiceClient.create(builder.build())), fixedAttributes);
}

17 Source : BigQueryCredentialsSupplierTest.java
with Apache License 2.0
from GoogleCloudDataproc

@Test
public void testCredentialsFromKey() throws Exception {
    String json = createServiceAccountJson("key");
    String credentialsKey = Base64.getEncoder().encodeToString(json.getBytes(StandardCharsets.UTF_8));
    Credentials credentials = new BigQueryCredentialsSupplier(Optional.empty(), Optional.of(credentialsKey), Optional.empty()).getCredentials();
    replacedertThat(credentials).isInstanceOf(ServiceAccountCredentials.clreplaced);
    ServiceAccountCredentials serviceAccountCredentials = (ServiceAccountCredentials) credentials;
    replacedertThat(serviceAccountCredentials.getProjectId()).isEqualTo("key");
    replacedertThat(serviceAccountCredentials.getClientEmail()).isEqualTo(CLIENT_EMAIL);
    replacedertThat(serviceAccountCredentials.getClientId()).isEqualTo(CLIENT_ID);
    replacedertThat(serviceAccountCredentials.getQuotaProjectId()).isEqualTo(QUOTA_PROJECT);
}

See More Examples