com.google.api.services.storage.StorageScopes Java Examples

The following examples show how to use com.google.api.services.storage.StorageScopes. 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: GoogleStorage.java    From halyard with Apache License 2.0 7 votes vote down vote up
private static GoogleCredentials loadStorageCredential(String jsonPath) throws IOException {
  GoogleCredentials credentials;
  if (!jsonPath.isEmpty()) {
    FileInputStream stream = new FileInputStream(jsonPath);
    credentials = GoogleCredentials.fromStream(stream);
    log.info("Loaded storage credentials from " + jsonPath);
  } else {
    log.info("Using storage default application credentials.");
    credentials = GoogleCredentials.getApplicationDefault();
  }

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

  return credentials;
}
 
Example #2
Source File: GcsStorageService.java    From front50 with Apache License 2.0 6 votes vote down vote up
private GoogleCredentials loadCredential(String jsonPath) throws IOException {
  GoogleCredentials credentials = null;

  if (!jsonPath.isEmpty()) {
    FileInputStream stream = new FileInputStream(jsonPath);
    credentials = GoogleCredentials.fromStream(stream);
    log.info("Loaded credentials from {}", value("jsonPath", jsonPath));
  } else {
    log.info(
        "spinnaker.gcs.enabled without spinnaker.gcs.jsonPath. "
            + "Using default application credentials. Using default credentials.");
    credentials = GoogleCredentials.getApplicationDefault();
  }

  return credentials.createScopedRequired()
      ? credentials.createScoped(Collections.singleton(StorageScopes.DEVSTORAGE_FULL_CONTROL))
      : credentials;
}
 
Example #3
Source File: HttpHealthcareApiClient.java    From beam with 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 #4
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 #5
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 #6
Source File: GoogleBinaryStore.java    From usergrid with Apache License 2.0 5 votes vote down vote up
private synchronized Storage getService() throws IOException, GeneralSecurityException {

        logger.trace("Getting Google Cloud Storage service");

        // leave this here for tests because they do things like manipulate properties dynamically to test invalid values
        this.bucketName = properties.getProperty( "usergrid.binary.bucketname" );


        if (instance == null) {

            // Google provides different authentication types which are different based on if the application is
            // running within GCE(Google Compute Engine) or GAE (Google App Engine). If Usergrid is running in
            // GCE or GAE, the SDK will automatically authenticate and get access to
            // cloud storage. Else, the full path to a credential file should be provided in the following environment variable
            //
            //     GOOGLE_APPLICATION_CREDENTIALS
            //
            // The SDK will attempt to load the credential file for a service account. See the following
            // for more info: https://developers.google.com/identity/protocols/application-default-credentials#howtheywork
            GoogleCredentials credentials = GoogleCredentials.getApplicationDefault().createScoped(StorageScopes.all());


            final TransportOptions transportOptions = HttpTransportOptions.newBuilder()
                .setConnectTimeout(30000) // in milliseconds
                .setReadTimeout(30000) // in milliseconds
                .build();

            instance = StorageOptions.newBuilder()
                .setCredentials(credentials)
                .setTransportOptions(transportOptions)
                .build()
                .getService();
        }

        return instance;
    }
 
Example #7
Source File: StorageFactory.java    From dlp-dataflow-deidentification with Apache License 2.0 5 votes vote down vote up
private static Storage buildService() throws IOException, GeneralSecurityException {
  HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
  JsonFactory jsonFactory = new JacksonFactory();
  GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);

  if (credential.createScopedRequired()) {
    Collection<String> scopes = StorageScopes.all();
    credential = credential.createScoped(scopes);
  }

  return new Storage.Builder(transport, jsonFactory, credential)
      .setApplicationName("GCS")
      .build();
}
 
Example #8
Source File: GCSOptions.java    From dataflow-java with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> create(PipelineOptions options) {
  return ImmutableList.<String>builder()
    .add(DataflowScopes.USERINFO_EMAIL)
    .add(GenomicsScopes.GENOMICS)
    .add(StorageScopes.DEVSTORAGE_READ_WRITE)
    .build();
}
 
Example #9
Source File: GoogleUtils.java    From kork with Apache License 2.0 5 votes vote down vote up
static GoogleCredentials buildGoogleCredentials() throws IOException {
  GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();

  if (credentials.createScopedRequired()) {
    credentials =
        credentials.createScoped(Collections.singleton(StorageScopes.DEVSTORAGE_READ_ONLY));
  }

  return credentials;
}
 
Example #10
Source File: StorageSample.java    From cloud-storage-docs-json-api-examples with Apache License 2.0 5 votes vote down vote up
/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception {
  // Load client secrets.
  GoogleClientSecrets clientSecrets = null;
  try {
    clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
        new InputStreamReader(StorageSample.class.getResourceAsStream(String.format("/%s",CLIENT_SECRET_FILENAME))));
    if (clientSecrets.getDetails().getClientId() == null ||
        clientSecrets.getDetails().getClientSecret() == null) {
        throw new Exception("client_secrets not well formed.");
    }
  } catch (Exception e) {
    System.out.println("Problem loading client_secrets.json file. Make sure it exists, you are " + 
                      "loading it with the right path, and a client ID and client secret are " +
                      "defined in it.\n" + e.getMessage());
    System.exit(1);
  }

  // Set up authorization code flow.
  // Ask for only the permissions you need. Asking for more permissions will
  // reduce the number of users who finish the process for giving you access
  // to their accounts. It will also increase the amount of effort you will
  // have to spend explaining to users what you are doing with their data.
  // Here we are listing all of the available scopes. You should remove scopes
  // that you are not actually using.
  Set<String> scopes = new HashSet<String>();
  scopes.add(StorageScopes.DEVSTORAGE_FULL_CONTROL);
  scopes.add(StorageScopes.DEVSTORAGE_READ_ONLY);
  scopes.add(StorageScopes.DEVSTORAGE_READ_WRITE);

  GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
      httpTransport, JSON_FACTORY, clientSecrets, scopes)
      .setDataStoreFactory(dataStoreFactory)
      .build();
  // Authorize.
  VerificationCodeReceiver receiver = 
      AUTH_LOCAL_WEBSERVER ? new LocalServerReceiver() : new GooglePromptReceiver();
  return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");    
}
 
Example #11
Source File: GoogleStorageCacheManager.java    From simpleci with MIT License 5 votes vote down vote up
private Storage createClient() throws IOException, GeneralSecurityException {
    GoogleCredential credential = GoogleCredential.fromStream(
            new ByteArrayInputStream(settings.serviceAccount.getBytes(StandardCharsets.UTF_8)))
                                                  .createScoped(Collections.singleton(StorageScopes.CLOUD_PLATFORM));

    NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    return new Storage.Builder(
            httpTransport, JSON_FACTORY, null).setApplicationName(APPLICATION_NAME)
                                              .setHttpRequestInitializer(credential).build();
}
 
Example #12
Source File: GcsWaitIT.java    From digdag with Apache License 2.0 5 votes vote down vote up
private Storage gcsClient(GoogleCredential credential)
{
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(StorageScopes.all());
    }
    return new Storage.Builder(transport, jsonFactory, credential)
            .setApplicationName("digdag-test")
            .build();
}
 
Example #13
Source File: BigQueryIT.java    From digdag with Apache License 2.0 5 votes vote down vote up
private Storage gcsClient(GoogleCredential credential)
{
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(StorageScopes.all());
    }
    return new Storage.Builder(transport, jsonFactory, credential)
            .setApplicationName("digdag-test")
            .build();
}
 
Example #14
Source File: GcsUploader.java    From incubator-heron with Apache License 2.0 5 votes vote down vote up
private Credential createCredentials(Config configuration) throws IOException {
  final String credentialsPath = GcsContext.getCredentialsPath(configuration);
  if (!Strings.isNullOrEmpty(credentialsPath)) {
    LOG.info("Using credentials from file: " + credentialsPath);
    return GoogleCredential
        .fromStream(new FileInputStream(credentialsPath))
        .createScoped(StorageScopes.all());
  }

  // if a credentials path is not provided try using the application default one.
  LOG.info("Using default application credentials");
  return GoogleCredential.getApplicationDefault().createScoped(StorageScopes.all());
}
 
Example #15
Source File: GoogleProfileReader.java    From halyard with Apache License 2.0 5 votes vote down vote up
private Storage createGoogleStorage(boolean useApplicationDefaultCreds) {
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  String applicationName = "Spinnaker/Halyard";
  HttpRequestInitializer requestInitializer = null;

  if (useApplicationDefaultCreds) {
    try {
      com.google.auth.oauth2.GoogleCredentials credentials =
          com.google.auth.oauth2.GoogleCredentials.getApplicationDefault();
      if (credentials.createScopedRequired()) {
        credentials =
            credentials.createScoped(
                Collections.singleton(StorageScopes.DEVSTORAGE_FULL_CONTROL));
      }
      requestInitializer = GoogleCredentials.setHttpTimeout(credentials);
      log.info("Loaded application default credential for reading BOMs & profiles.");
    } catch (Exception e) {
      log.debug(
          "No application default credential could be loaded for reading BOMs & profiles. Continuing unauthenticated: {}",
          e.getMessage());
    }
  }
  if (requestInitializer == null) {
    requestInitializer = GoogleCredentials.retryRequestInitializer();
  }

  return new Storage.Builder(
          GoogleCredentials.buildHttpTransport(), jsonFactory, requestInitializer)
      .setApplicationName(applicationName)
      .build();
}
 
Example #16
Source File: GoogleWriteableProfileRegistry.java    From halyard with Apache License 2.0 5 votes vote down vote up
private com.google.auth.oauth2.GoogleCredentials loadCredentials(String jsonPath)
    throws IOException {
  com.google.auth.oauth2.GoogleCredentials credentials;
  if (!jsonPath.isEmpty()) {
    FileInputStream stream = new FileInputStream(jsonPath);
    credentials =
        com.google.auth.oauth2.GoogleCredentials.fromStream(stream)
            .createScoped(Collections.singleton(StorageScopes.DEVSTORAGE_FULL_CONTROL));
    log.info("Loaded credentials from " + jsonPath);
  } else {
    log.info("Using default application credentials.");
    credentials = com.google.auth.oauth2.GoogleCredentials.getApplicationDefault();
  }
  return credentials;
}
 
Example #17
Source File: GCSFilesSource.java    From policyscanner with Apache License 2.0 5 votes vote down vote up
private static Storage constructStorageApiStub() throws GeneralSecurityException, IOException {
  JsonFactory jsonFactory = new JacksonFactory();
  HttpTransport transport;
  transport = GoogleNetHttpTransport.newTrustedTransport();
  GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
  if (credential.createScopedRequired()) {
    Collection<String> scopes = StorageScopes.all();
    credential = credential.createScoped(scopes);
  }
  return new Storage.Builder(transport, jsonFactory, credential)
      .setApplicationName("GCS Samples")
      .build();
}
 
Example #18
Source File: GoogleClientFactory.java    From kayenta with Apache License 2.0 5 votes vote down vote up
public Storage getStorage() throws IOException {
  HttpTransport httpTransport = buildHttpTransport();
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  GoogleCredentials credentials = getCredentials(StorageScopes.all());
  HttpRequestInitializer reqInit = setHttpTimeout(credentials);
  String applicationName = "Spinnaker/" + applicationVersion;

  return new Storage.Builder(httpTransport, jsonFactory, reqInit)
      .setApplicationName(applicationName)
      .build();
}