com.google.api.client.googleapis.javanet.GoogleNetHttpTransport Java Examples

The following examples show how to use com.google.api.client.googleapis.javanet.GoogleNetHttpTransport. 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 File: DeviceRegistryExample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Delete this registry from Cloud IoT. */
protected 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 #2
Source File: SearchHelper.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Factory method for {@code SearchHelper} objects.
 *
 * @param searchAuthInfo object containing the info to authenticate the impersonated user
 * @param searchApplicationId ID of the serving application linked to the data sourced containing
 *  the items to serving (this is can be obtained from the Admin console)
 * @param rootUrl URL of the Indexing API
 */
public static SearchHelper createSearchHelper(
    SearchAuthInfo searchAuthInfo, String searchApplicationId, Optional<String> rootUrl)
    throws GeneralSecurityException, IOException {
  HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
  Credential credential = createCredentials(transport, searchAuthInfo);

  CloudSearch.Builder builder =
      new CloudSearch.Builder(
              transport,
              JSON_FACTORY,
              createChainedHttpRequestInitializer(credential, RETRY_REQUEST_INITIALIZER))
          .setApplicationName(SEARCH_APPLICATION_NAME);
  rootUrl.ifPresent(r -> builder.setRootUrl(r));
  return new SearchHelper(builder.build(), searchApplicationId);
}
 
Example #3
Source File: PhotosLibraryClientFactory.java    From java-photoslibrary with Apache License 2.0 6 votes vote down vote up
private static Credentials getUserCredentials(String credentialsPath, List<String> selectedScopes)
    throws IOException, GeneralSecurityException {
  GoogleClientSecrets clientSecrets =
      GoogleClientSecrets.load(
          JSON_FACTORY, new InputStreamReader(new FileInputStream(credentialsPath)));
  String clientId = clientSecrets.getDetails().getClientId();
  String clientSecret = clientSecrets.getDetails().getClientSecret();

  GoogleAuthorizationCodeFlow flow =
      new GoogleAuthorizationCodeFlow.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JSON_FACTORY,
              clientSecrets,
              selectedScopes)
          .setDataStoreFactory(new FileDataStoreFactory(DATA_STORE_DIR))
          .setAccessType("offline")
          .build();
  LocalServerReceiver receiver =
      new LocalServerReceiver.Builder().setPort(LOCAL_RECEIVER_PORT).build();
  Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
  return UserCredentials.newBuilder()
      .setClientId(clientId)
      .setClientSecret(clientSecret)
      .setRefreshToken(credential.getRefreshToken())
      .build();
}
 
Example #4
Source File: DeleteServiceAccountKey.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static Iam initService() throws GeneralSecurityException, IOException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
  // Initialize the IAM service, which can be used to send requests to the IAM API.
  Iam service =
      new Iam.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-account-keys")
          .build();
  return service;
}
 
Example #5
Source File: ListServiceAccounts.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static Iam initService() throws GeneralSecurityException, IOException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
  // Initialize the IAM service, which can be used to send requests to the IAM API.
  Iam service =
      new Iam.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-accounts")
          .build();
  return service;
}
 
Example #6
Source File: QuickstartV2.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public static CloudResourceManager initializeService()
    throws IOException, GeneralSecurityException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));

  // Creates the Cloud Resource Manager service object.
  CloudResourceManager service =
      new CloudResourceManager.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-accounts")
          .build();
  return service;
}
 
Example #7
Source File: CloudiotPubsubExampleServer.java    From java-docs-samples with 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();
}
 
Example #8
Source File: MlEngineModel.java    From zoltar with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a Google Cloud ML Engine backed model.
 *
 * @param id {@link Model.Id} needs to be created with the following format:
 *     <pre>"projects/{PROJECT_ID}/models/{MODEL_ID}"</pre>
 *     or
 *     <pre>"projects/{PROJECT_ID}/models/{MODEL_ID}/versions/{MODEL_VERSION}"</pre>
 */
public static MlEngineModel create(final Model.Id id)
    throws IOException, GeneralSecurityException {
  final HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  final JsonFactory jsonFactory = Utils.getDefaultJsonFactory();
  final GoogleCredential credential =
      GoogleCredential.getApplicationDefault()
          .createScoped(CloudMachineLearningEngineScopes.all());

  final CloudMachineLearningEngine mlEngine =
      new CloudMachineLearningEngine.Builder(httpTransport, jsonFactory, credential)
          .setApplicationName(APPLICATION_NAME)
          .build();

  return new AutoValue_MlEngineModel(id, mlEngine, httpTransport);
}
 
Example #9
Source File: EnableServiceAccount.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static Iam initService() throws GeneralSecurityException, IOException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
  // Initialize the IAM service, which can be used to send requests to the IAM API.
  Iam service =
      new Iam.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-accounts")
          .build();
  return service;
}
 
Example #10
Source File: StorageFactory.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static Storage buildService() throws IOException, GeneralSecurityException {
  HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
  JsonFactory jsonFactory = new JacksonFactory();
  GoogleCredentials credential = GoogleCredentials.getApplicationDefault();

  // Depending on the environment that provides the default credentials (for
  // example: Compute Engine, App Engine), the credentials may require us to
  // specify the scopes we need explicitly.  Check for this case, and inject
  // the Cloud Storage scope if required.
  if (credential.createScopedRequired()) {
    Collection<String> scopes = StorageScopes.all();
    credential = credential.createScoped(scopes);
  }

  return new Storage.Builder(transport, jsonFactory, new HttpCredentialsAdapter(credential))
      .setApplicationName("GCS Samples")
      .build();
}
 
Example #11
Source File: DeleteServiceAccount.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static Iam initService() throws GeneralSecurityException, IOException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
  // Initialize the IAM service, which can be used to send requests to the IAM API.
  Iam service =
      new Iam.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-accounts")
          .build();
  return service;
}
 
Example #12
Source File: CloudIotManager.java    From daq with 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 #13
Source File: ListServiceAccountKeys.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static Iam initService() throws GeneralSecurityException, IOException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
  // Initialize the IAM service, which can be used to send requests to the IAM API.
  Iam service =
      new Iam.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-account-keys")
          .build();
  return service;
}
 
Example #14
Source File: DeviceRegistryExample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Retrieves registry metadata from a project. * */
protected static DeviceRegistry getRegistry(
    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 registryPath =
      String.format(
          "projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);

  return service.projects().locations().registries().get(registryPath).execute();
}
 
Example #15
Source File: SetPolicy.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public static CloudResourceManager createCloudResourceManagerService()
    throws IOException, GeneralSecurityException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));

  CloudResourceManager service =
      new CloudResourceManager.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-accounts")
          .build();
  return service;
}
 
Example #16
Source File: GetPolicy.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public static CloudResourceManager createCloudResourceManagerService()
    throws IOException, GeneralSecurityException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));

  CloudResourceManager service =
      new CloudResourceManager.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-accounts")
          .build();
  return service;
}
 
Example #17
Source File: DeviceRegistryExample.java    From java-docs-samples with 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 File: GCPProject.java    From policyscanner with Apache License 2.0 6 votes vote down vote up
/**
 * Return the Projects api object used for accessing the Cloud Resource Manager Projects API.
 * @return Projects api object used for accessing the Cloud Resource Manager Projects API
 * @throws GeneralSecurityException Thrown if there's a permissions error.
 * @throws IOException Thrown if there's an IO error initializing the API object.
 */
public static synchronized Projects getProjectsApiStub()
    throws GeneralSecurityException, IOException {
  if (projectApiStub != null) {
    return projectApiStub;
  }
  HttpTransport transport;
  GoogleCredential credential;
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  transport = GoogleNetHttpTransport.newTrustedTransport();
  credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
  if (credential.createScopedRequired()) {
    Collection<String> scopes = CloudResourceManagerScopes.all();
    credential = credential.createScoped(scopes);
  }
  projectApiStub = new CloudResourceManager
      .Builder(transport, jsonFactory, credential)
      .build()
      .projects();
  return projectApiStub;
}
 
Example #19
Source File: GCPServiceAccount.java    From policyscanner with Apache License 2.0 6 votes vote down vote up
/**
 * Get the API stub for accessing the IAM Service Accounts API.
 * @return ServiceAccounts api stub for accessing the IAM Service Accounts API.
 * @throws IOException Thrown if there's an IO error initializing the api connection.
 * @throws GeneralSecurityException Thrown if there's a security error
 * initializing the connection.
 */
public static ServiceAccounts getServiceAccountsApiStub() throws IOException, GeneralSecurityException {
  if (serviceAccountsApiStub == null) {
    HttpTransport transport;
    GoogleCredential credential;
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    transport = GoogleNetHttpTransport.newTrustedTransport();
    credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
    if (credential.createScopedRequired()) {
      Collection<String> scopes = IamScopes.all();
      credential = credential.createScoped(scopes);
    }
    serviceAccountsApiStub = new Iam.Builder(transport, jsonFactory, credential)
        .build()
        .projects()
        .serviceAccounts();
  }
  return serviceAccountsApiStub;
}
 
Example #20
Source File: TestPermissions.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public static CloudResourceManager createCloudResourceManagerService()
    throws IOException, GeneralSecurityException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));

  CloudResourceManager service =
      new CloudResourceManager.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-accounts")
          .build();
  return service;
}
 
Example #21
Source File: CreateServiceAccount.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static Iam initService() throws GeneralSecurityException, IOException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
  // Initialize the IAM service, which can be used to send requests to the IAM API.
  Iam service =
      new Iam.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-accounts")
          .build();
  return service;
}
 
Example #22
Source File: DisableServiceAccount.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static Iam initService() throws GeneralSecurityException, IOException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
  // Initialize the IAM service, which can be used to send requests to the IAM API.
  Iam service =
      new Iam.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-accounts")
          .build();
  return service;
}
 
Example #23
Source File: DeviceRegistryExample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Delete the given device from the registry. */
protected static void deleteDevice(
    String deviceId, String projectId, String cloudRegion, String registryName)
    throws GeneralSecurityException, IOException {
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
  final CloudIot service =
      new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
          .setApplicationName(APP_NAME)
          .build();

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

  System.out.println("Deleting device " + devicePath);
  service.projects().locations().registries().devices().delete(devicePath).execute();
}
 
Example #24
Source File: StorageHandler.java    From tech-gallery with Apache License 2.0 6 votes vote down vote up
/**
 * Method to create the service or get the service if is already created.
 *
 * @author <a href="mailto:[email protected]"> João Felipe de Medeiros Moreira </a>
 * @since 13/10/2015
 *
 * @return the Storage service already created.
 *
 * @throws IOException in case a IO problem.
 * @throws GeneralSecurityException in case a security problem.
 */
private static Storage getService() throws IOException, GeneralSecurityException {
  logger.finest("###### Getting the storage service");
  if (null == storageService) {
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = GoogleCredential.getApplicationDefault();
    // Depending on the environment that provides the default credentials (e.g. Compute Engine,
    // App Engine), the credentials may require us to specify the scopes we need explicitly.
    // Check for this case, and inject the Cloud Storage scope if required.
    if (credential.createScopedRequired()) {
      credential = credential.createScoped(StorageScopes.all());
    }
    storageService = new Storage.Builder(httpTransport, JSON_FACTORY, credential)
        .setApplicationName(APPLICATION_NAME).build();
  }
  return storageService;
}
 
Example #25
Source File: StyxScheduler.java    From styx with Apache License 2.0 6 votes vote down vote up
private static ServiceAccountKeyManager createServiceAccountKeyManager() {
  try {
    final HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    final JsonFactory jsonFactory = Utils.getDefaultJsonFactory();
    final GoogleCredential credential = GoogleCredential
        .getApplicationDefault(httpTransport, jsonFactory)
        .createScoped(IamScopes.all());
    final Iam iam = new Iam.Builder(
        httpTransport, jsonFactory, credential)
        .setApplicationName(SERVICE_NAME)
        .build();
    return new ServiceAccountKeyManager(iam);
  } catch (GeneralSecurityException | IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #26
Source File: CoreSocketFactory.java    From cloud-sql-jdbc-socket-factory with Apache License 2.0 6 votes vote down vote up
private static SQLAdmin createAdminApiClient(HttpRequestInitializer requestInitializer) {
  HttpTransport httpTransport;
  try {
    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  } catch (GeneralSecurityException | IOException err) {
    throw new RuntimeException("Unable to initialize HTTP transport", err);
  }

  String rootUrl = System.getProperty(API_ROOT_URL_PROPERTY);
  String servicePath = System.getProperty(API_SERVICE_PATH_PROPERTY);

  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  SQLAdmin.Builder adminApiBuilder =
      new Builder(httpTransport, jsonFactory, requestInitializer)
          .setApplicationName(getUserAgents());
  if (rootUrl != null) {
    logTestPropertyWarning(API_ROOT_URL_PROPERTY);
    adminApiBuilder.setRootUrl(rootUrl);
  }
  if (servicePath != null) {
    logTestPropertyWarning(API_SERVICE_PATH_PROPERTY);
    adminApiBuilder.setServicePath(servicePath);
  }
  return adminApiBuilder.build();
}
 
Example #27
Source File: PubSubWrapper.java    From eip with MIT License 6 votes vote down vote up
/**
     * Setup authorization for local app based on private key.
     * See <a href="https://cloud.google.com/pubsub/configure">cloud.google.com/pubsub/configure</a>
     */
    private void createClient(String private_key_file, String email) throws IOException, GeneralSecurityException {
        HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
        GoogleCredential credential = new GoogleCredential.Builder()
                .setTransport(transport)
                .setJsonFactory(JSON_FACTORY)
                .setServiceAccountScopes(PubsubScopes.all())
                .setServiceAccountId(email)
                .setServiceAccountPrivateKeyFromP12File(new File(private_key_file))
                .build();
        // Please use custom HttpRequestInitializer for automatic retry upon failures.
//        HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential);
        pubsub = new Pubsub.Builder(transport, JSON_FACTORY, credential)
                .setApplicationName("eaipubsub")
                .build();
    }
 
Example #28
Source File: StorageSample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Fetches the listing of the given bucket.
 *
 * @param bucketName the name of the bucket to list.
 * @return the raw XML containing the listing of the bucket.
 * @throws IOException if there's an error communicating with Cloud Storage.
 * @throws GeneralSecurityException for errors creating https connection.
 */
public static String listBucket(final String bucketName)
    throws IOException, GeneralSecurityException {
  // [START snippet]
  // Build an account credential.
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(STORAGE_SCOPE));

  // Set up and execute a Google Cloud Storage request.
  String uri = "https://storage.googleapis.com/" + URLEncoder.encode(bucketName, "UTF-8");

  HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  HttpRequestFactory requestFactory =
      httpTransport.createRequestFactory(new HttpCredentialsAdapter(credential));
  GenericUrl url = new GenericUrl(uri);

  HttpRequest request = requestFactory.buildGetRequest(url);
  HttpResponse response = request.execute();
  String content = response.parseAsString();
  // [END snippet]

  return content;
}
 
Example #29
Source File: FaceDetectApp.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Connects to the Vision API using Application Default Credentials. */
public static Vision getVisionService() throws IOException, GeneralSecurityException {
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault().createScoped(VisionScopes.all());
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  return new Vision.Builder(
          GoogleNetHttpTransport.newTrustedTransport(),
          jsonFactory,
          new HttpCredentialsAdapter(credential))
      .setApplicationName(APPLICATION_NAME)
      .build();
}
 
Example #30
Source File: GcsClientImpl.java    From exhibitor with Apache License 2.0 5 votes vote down vote up
@Override
public Storage getClient() throws Exception {
    Credential credential = authorize();
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    return new Storage.Builder(httpTransport, JSON_FACTORY, credential)
            .setApplicationName(APPLICATION_NAME).build();
}