com.google.api.client.http.HttpRequestInitializer Java Examples

The following examples show how to use com.google.api.client.http.HttpRequestInitializer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: connector-sdk   Author: google-cloudsearch   File: LocalFileCredentialFactoryTest.java    License: Apache License 2.0 9 votes vote down vote up
@Test
public void testNullServiceAccountIdJson() throws Exception {
  File tmpfile =
      temporaryFolder.newFile("testNullServiceAccountIdJson" + SERVICE_ACCOUNT_FILE_JSON);
  GoogleCredential mockCredential = new MockGoogleCredential.Builder().build();
  List<String> scopes = Arrays.asList("profile");
  when(mockCredentialHelper.getJsonCredential(
      eq(tmpfile.toPath()),
      any(HttpTransport.class),
      any(JsonFactory.class),
      any(HttpRequestInitializer.class),
      eq(scopes)))
      .thenReturn(mockCredential);
  LocalFileCredentialFactory subject =
      new LocalFileCredentialFactory.Builder()
          .setServiceAccountKeyFilePath(tmpfile.getAbsolutePath())
          .build();
  subject.getCredential(Arrays.asList("email"));
  assertEquals(mockCredential, subject.getCredential(scopes));
}
 
Example #2
Source Project: connector-sdk   Author: google-cloudsearch   File: LocalFileCredentialFactory.java    License: Apache License 2.0 8 votes vote down vote up
GoogleCredential getJsonCredential(
    Path keyPath,
    HttpTransport transport,
    JsonFactory jsonFactory,
    HttpRequestInitializer httpRequestInitializer,
    Collection<String> scopes)
    throws IOException {
  try (InputStream is = newInputStream(keyPath)) {
    GoogleCredential credential =
        GoogleCredential.fromStream(is, transport, jsonFactory).createScoped(scopes);
    return new GoogleCredential.Builder()
        .setServiceAccountId(credential.getServiceAccountId())
        .setServiceAccountScopes(scopes)
        .setServiceAccountPrivateKey(credential.getServiceAccountPrivateKey())
        .setTransport(transport)
        .setJsonFactory(jsonFactory)
        .setRequestInitializer(httpRequestInitializer)
        .build();
  }
}
 
Example #3
Source Project: connector-sdk   Author: google-cloudsearch   File: LocalFileCredentialFactoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCredentialP12() throws Exception {
  File tmpfile = temporaryFolder.newFile(SERVICE_ACCOUNT_FILE_P12);
  GoogleCredential mockCredential = new MockGoogleCredential.Builder().build();
  List<String> scopes = Arrays.asList("profile, calendar");
  when(mockCredentialHelper.getP12Credential(
      eq("ServiceAccount"),
      eq(tmpfile.toPath()),
      any(HttpTransport.class),
      any(JsonFactory.class),
      any(HttpRequestInitializer.class),
      eq(scopes)))
      .thenReturn(mockCredential);
  LocalFileCredentialFactory credentialFactory =
      new LocalFileCredentialFactory.Builder()
          .setServiceAccountKeyFilePath(tmpfile.getAbsolutePath())
          .setServiceAccountId("ServiceAccount")
          .build();
  assertEquals(mockCredential, credentialFactory.getCredential(scopes));
}
 
Example #4
Source Project: connector-sdk   Author: google-cloudsearch   File: LocalFileCredentialFactoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testfromConfigurationJsonKey() throws Exception {
  File tmpfile = temporaryFolder.newFile("testfromConfiguration" + SERVICE_ACCOUNT_FILE_JSON);
  createConfig(tmpfile.getAbsolutePath(), "");
  GoogleCredential mockCredential = new MockGoogleCredential.Builder().build();
  List<String> scopes = Arrays.asList("profile");
  when(mockCredentialHelper.getJsonCredential(
      eq(tmpfile.toPath()),
      any(HttpTransport.class),
      any(JsonFactory.class),
      any(HttpRequestInitializer.class),
      eq(scopes)))
      .thenReturn(mockCredential);
  LocalFileCredentialFactory credentialFactory = LocalFileCredentialFactory.fromConfiguration();
  assertEquals(mockCredential, credentialFactory.getCredential(scopes));
}
 
Example #5
Source Project: java-docs-samples   Author: GoogleCloudPlatform   File: FhirStorePatch.java    License: Apache License 2.0 6 votes vote down vote up
private static CloudHealthcare createClient() throws IOException {
  // Use Application Default Credentials (ADC) to authenticate the requests
  // For more information see https://cloud.google.com/docs/authentication/production
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

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

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

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

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

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

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

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

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

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

  // Build the client for interacting with the service.
  return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
      .setApplicationName("your-application-name")
      .build();
}
 
Example #11
Source Project: Xero-Java   Author: XeroAPI   File: ApiClient.java    License: MIT License 6 votes vote down vote up
public ApiClient(
    String basePath,
    HttpTransport transport,
    HttpRequestInitializer initializer,
    ObjectMapper objectMapper,
    HttpRequestFactory reqFactory
) {
    this.basePath = basePath == null ? defaultBasePath : (
        basePath.endsWith("/") ? basePath.substring(0, basePath.length() - 1) : basePath
    );
    if (transport != null) {
        this.httpTransport = transport;
    }
    this.httpRequestFactory = (reqFactory != null ? reqFactory : (transport == null ? Utils.getDefaultTransport() : transport).createRequestFactory(initializer) );
    this.objectMapper = (objectMapper == null ? createDefaultObjectMapper() : objectMapper);
}
 
Example #12
Source Project: UTubeTV   Author: sgehrman   File: YouTubeAPI.java    License: The Unlicense 6 votes vote down vote up
public YouTube youTube() {
  if (youTube == null) {
    try {
      HttpRequestInitializer credentials;

      if (mUseAuthCredentials)
        credentials = Auth.getCredentials(mContext, mUseDefaultAccount);
      else
        credentials = Auth.nullCredentials(mContext);

      youTube = new YouTube.Builder(new NetHttpTransport(), new AndroidJsonFactory(), credentials).setApplicationName("YouTubeAPI")
          .build();
    } catch (Exception e) {
      e.printStackTrace();
    } catch (Throwable t) {
      t.printStackTrace();
    }
  }

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

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

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

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

  // Build the client for interacting with the service.
  return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
      .setApplicationName("your-application-name")
      .build();
}
 
Example #15
Source Project: appengine-gcs-client   Author: GoogleCloudPlatform   File: URLFetchUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDescribeRequestAndResponseForApiClient() throws Exception {
  HttpRequestInitializer initializer = mock(HttpRequestInitializer.class);
  NetHttpTransport transport = new NetHttpTransport();
  Storage storage = new Storage.Builder(transport, new JacksonFactory(), initializer)
      .setApplicationName("bla").build();
  HttpRequest request = storage.objects().delete("bucket", "object").buildHttpRequest();
  request.getHeaders().clear();
  request.getHeaders().put("k1", "v1");
  request.getHeaders().put("k2", "v2");
  HttpResponseException exception = null;
  try {
    request.execute();
  } catch (HttpResponseException ex) {
    exception = ex;
  }
  String expected = "Request: DELETE " + Storage.DEFAULT_BASE_URL + "b/bucket/o/object\n"
      + "k1: v1\nk2: v2\n\nno content\n\nResponse: 40";
  String result =
      URLFetchUtils.describeRequestAndResponse(new HTTPRequestInfo(request), exception);
  assertTrue(expected + "\nis not a prefix of:\n" + result, result.startsWith(expected));
}
 
Example #16
Source Project: cloud-pubsub-samples-java   Author: googlearchive   File: PubsubUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Builds a new Pubsub client and returns it.
 *
 * @param httpTransport HttpTransport for Pubsub client.
 * @param jsonFactory JsonFactory for Pubsub client.
 * @return Pubsub client.
 * @throws IOException when we can not get the default credentials.
 */
public static Pubsub getClient(final HttpTransport httpTransport,
                               final JsonFactory jsonFactory)
        throws IOException {
    Preconditions.checkNotNull(httpTransport);
    Preconditions.checkNotNull(jsonFactory);
    GoogleCredential credential = GoogleCredential.getApplicationDefault();
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(PubsubScopes.all());
    }
    // Please use custom HttpRequestInitializer for automatic
    // retry upon failures.
    HttpRequestInitializer initializer =
            new RetryHttpInitializerWrapper(credential);
    return new Pubsub.Builder(httpTransport, jsonFactory, initializer)
            .setApplicationName(APPLICATION_NAME)
            .build();
}
 
Example #17
Source Project: java-docs-samples   Author: GoogleCloudPlatform   File: DeviceRegistryExample.java    License: Apache License 2.0 6 votes vote down vote up
/** Retrieves device metadata from a registry. * */
protected static List<DeviceState> getDeviceStates(
    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("Retrieving device states " + devicePath);

  ListDeviceStatesResponse resp =
      service.projects().locations().registries().devices().states().list(devicePath).execute();

  return resp.getDeviceStates();
}
 
Example #18
Source Project: beam   Author: apache   File: HttpHealthcareApiClient.java    License: Apache License 2.0 6 votes vote down vote up
private void initClient() throws IOException {

    credentials = GoogleCredentials.getApplicationDefault();
    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        new AuthenticatedRetryInitializer(
            credentials.createScoped(
                CloudHealthcareScopes.CLOUD_PLATFORM, StorageScopes.CLOUD_PLATFORM_READ_ONLY));

    client =
        new CloudHealthcare.Builder(
                new NetHttpTransport(), new JacksonFactory(), requestInitializer)
            .setApplicationName("apache-beam-hl7v2-io")
            .build();
    httpClient =
        HttpClients.custom().setRetryHandler(new DefaultHttpRequestRetryHandler(10, false)).build();
  }
 
Example #19
Source Project: java-docs-samples   Author: GoogleCloudPlatform   File: FhirStoreGetIamPolicy.java    License: Apache License 2.0 6 votes vote down vote up
private static CloudHealthcare createClient() throws IOException {
  // Use Application Default Credentials (ADC) to authenticate the requests
  // For more information see https://cloud.google.com/docs/authentication/production
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

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

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

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

  // Build the client for interacting with the service.
  return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
      .setApplicationName("your-application-name")
      .build();
}
 
Example #21
Source Project: nomulus   Author: google   File: RequestFactoryModuleTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test_provideHttpRequestFactory_remote() throws Exception {
  // Make sure that example.com creates a request factory with the UNITTEST client id but no
  boolean origIsLocal = RegistryConfig.CONFIG_SETTINGS.get().appEngine.isLocal;
  RegistryConfig.CONFIG_SETTINGS.get().appEngine.isLocal = false;
  try {
    HttpRequestFactory factory =
        RequestFactoryModule.provideHttpRequestFactory(credentialsBundle);
    HttpRequestInitializer initializer = factory.getInitializer();
    assertThat(initializer).isNotNull();
    // HttpRequestFactory#buildGetRequest() calls initialize() once.
    HttpRequest request = factory.buildGetRequest(new GenericUrl("http://localhost"));
    verify(httpRequestInitializer).initialize(request);
    assertThat(request.getConnectTimeout()).isEqualTo(REQUEST_TIMEOUT_MS);
    assertThat(request.getReadTimeout()).isEqualTo(REQUEST_TIMEOUT_MS);
    verifyNoMoreInteractions(httpRequestInitializer);
  } finally {
    RegistryConfig.CONFIG_SETTINGS.get().appEngine.isLocal = origIsLocal;
  }
}
 
Example #22
Source Project: cloud-pubsub-mqtt-proxy   Author: GoogleCloudPlatform   File: GcloudPubsub.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Constructor that will automatically instantiate a Google Cloud Pub/Sub instance.
 *
 * @throws IOException when the initialization of the Google Cloud Pub/Sub client fails.
 */
public GcloudPubsub() throws IOException {
  if (CLOUD_PUBSUB_PROJECT_ID == null) {
    throw new IllegalStateException(GCLOUD_PUBSUB_PROJECT_ID_NOT_SET_ERROR);
  }
  try {
    serverName = InetAddress.getLocalHost().getCanonicalHostName();
  } catch (UnknownHostException e) {
    throw new IllegalStateException("Unable to retrieve the hostname of the system");
  }
  HttpTransport httpTransport = checkNotNull(Utils.getDefaultTransport());
  JsonFactory jsonFactory = checkNotNull(Utils.getDefaultJsonFactory());
  GoogleCredential credential = GoogleCredential.getApplicationDefault(
      httpTransport, jsonFactory);
  if (credential.createScopedRequired()) {
    credential = credential.createScoped(PubsubScopes.all());
  }
  HttpRequestInitializer initializer =
      new RetryHttpInitializerWrapper(credential);
  pubsub = new Pubsub.Builder(httpTransport, jsonFactory, initializer).build();
  logger.info("Google Cloud Pub/Sub Initialization SUCCESS");
}
 
Example #23
Source Project: java-docs-samples   Author: GoogleCloudPlatform   File: HL7v2MessageIngest.java    License: Apache License 2.0 6 votes vote down vote up
private static CloudHealthcare createClient() throws IOException {
  // Use Application Default Credentials (ADC) to authenticate the requests
  // For more information see https://cloud.google.com/docs/authentication/production
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

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

  // Build the client for interacting with the service.
  return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
      .setApplicationName("your-application-name")
      .build();
}
 
Example #24
Source Project: java-docs-samples   Author: GoogleCloudPlatform   File: CloudiotPubsubExampleServer.java    License: Apache License 2.0 6 votes vote down vote up
/** Delete this registry from Cloud IoT. */
public static void deleteRegistry(String cloudRegion, String projectId, 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 registryPath =
      String.format(
          "projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);

  System.out.println("Deleting: " + registryPath);
  service.projects().locations().registries().delete(registryPath).execute();
}
 
Example #25
Source Project: java-docs-samples   Author: GoogleCloudPlatform   File: BuildIapRequest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Clone request and add an IAP Bearer Authorization header with signed JWT token.
 *
 * @param request Request to add authorization header
 * @param iapClientId OAuth 2.0 client ID for IAP protected resource
 * @return Clone of request with Bearer style authorization header with signed jwt token.
 * @throws IOException exception creating signed JWT
 */
public static HttpRequest buildIapRequest(HttpRequest request, String iapClientId)
    throws IOException {

  IdTokenProvider idTokenProvider = getIdTokenProvider();
  IdTokenCredentials credentials =
      IdTokenCredentials.newBuilder()
          .setIdTokenProvider(idTokenProvider)
          .setTargetAudience(iapClientId)
          .build();

  HttpRequestInitializer httpRequestInitializer = new HttpCredentialsAdapter(credentials);

  return httpTransport
      .createRequestFactory(httpRequestInitializer)
      .buildRequest(request.getRequestMethod(), request.getUrl(), request.getContent());
}
 
Example #26
Source Project: java-docs-samples   Author: GoogleCloudPlatform   File: DatasetGetIamPolicy.java    License: Apache License 2.0 6 votes vote down vote up
private static CloudHealthcare createClient() throws IOException {
  // Use Application Default Credentials (ADC) to authenticate the requests
  // For more information see https://cloud.google.com/docs/authentication/production
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

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

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

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

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

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

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

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

  // Build the client for interacting with the service.
  return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
      .setApplicationName("your-application-name")
      .build();
}
 
Example #30
Source Project: java-docs-samples   Author: GoogleCloudPlatform   File: CloudiotPubsubExampleServer.java    License: Apache License 2.0 6 votes vote down vote up
/** 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();
}