com.google.api.client.googleapis.auth.oauth2.GoogleCredential Java Examples

The following examples show how to use com.google.api.client.googleapis.auth.oauth2.GoogleCredential. 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: LocalFileCredentialFactory.java    From connector-sdk with 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 #2
Source File: GcpIamClientAuthenticationProvider.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
public static GcpCredentialSupplier getGoogleCredential(
		VaultEnvironmentProperties.GcpIamProperties gcp) {
	return () -> {

		VaultEnvironmentProperties.GcpCredentials credentialProperties = gcp
				.getCredentials();
		if (credentialProperties.getLocation() != null) {
			return GoogleCredential.fromStream(
					credentialProperties.getLocation().getInputStream());
		}

		if (StringUtils.hasText(credentialProperties.getEncodedKey())) {
			return GoogleCredential.fromStream(new ByteArrayInputStream(Base64
					.getDecoder().decode(credentialProperties.getEncodedKey())));
		}

		return GoogleCredential.getApplicationDefault();
	};
}
 
Example #3
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 #4
Source File: DatastoreTest.java    From async-datastore-client with Apache License 2.0 6 votes vote down vote up
private DatastoreConfig datastoreConfig() {
  final DatastoreConfig.Builder config = DatastoreConfig.builder()
      .connectTimeout(5000)
      .requestTimeout(1000)
      .maxConnections(5)
      .requestRetry(3)
      .version(VERSION)
      .host(DATASTORE_HOST)
      .project(PROJECT);

  if (NAMESPACE != null) {
    config.namespace(NAMESPACE);
  }

  if (KEY_PATH != null) {
    try {
      FileInputStream creds = new FileInputStream(new File(KEY_PATH));
      config.credential(GoogleCredential.fromStream(creds).createScoped(DatastoreConfig.SCOPES));
    }  catch (final IOException e) {
      System.err.println("Failed to load credentials " + e.getMessage());
      System.exit(1);
    }
  }

  return config.build();
}
 
Example #5
Source File: GuiMain.java    From google-sites-liberation with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve OAuth 2.0 credentials.
 * 
 * @return OAuth 2.0 Credential instance.
 * @throws IOException
 */
private Credential getCredentials() throws IOException {
  String code = tokenField.getText();
  HttpTransport transport = new NetHttpTransport();
  JacksonFactory jsonFactory = new JacksonFactory();
  String CLIENT_SECRET = "EPME5fbwiNLCcMsnj3jVoXeY";

  // Step 2: Exchange -->
  GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(
      transport, jsonFactory, CLIENT_ID, CLIENT_SECRET, code,
      REDIRECT_URI).execute();
  // End of Step 2 <--

  // Build a new GoogleCredential instance and return it.
  return new GoogleCredential.Builder()
      .setClientSecrets(CLIENT_ID, CLIENT_SECRET)
      .setJsonFactory(jsonFactory).setTransport(transport).build()
      .setAccessToken(response.getAccessToken())
      .setRefreshToken(response.getRefreshToken());
}
 
Example #6
Source File: GoogleSpreadsheet.java    From pdi-google-spreadsheet-plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static String getAccessToken(String email, KeyStore pks) throws Exception {
    PrivateKey pk = getPrivateKey(pks);
    if (pk != null && !email.equals("")) {
        try {
            GoogleCredential credential = new GoogleCredential.Builder().setTransport(GoogleSpreadsheet.HTTP_TRANSPORT)
                    .setJsonFactory(GoogleSpreadsheet.JSON_FACTORY).setServiceAccountScopes(GoogleSpreadsheet.SCOPES).setServiceAccountId(email)
                    .setServiceAccountPrivateKey(pk).build();

            HttpRequestFactory requestFactory = GoogleSpreadsheet.HTTP_TRANSPORT.createRequestFactory(credential);
            GenericUrl url = new GenericUrl(GoogleSpreadsheet.getSpreadsheetFeedURL().toString());
            HttpRequest request = requestFactory.buildGetRequest(url);
            request.execute();
            return credential.getAccessToken();
        } catch (Exception e) {
            throw new Exception("Error fetching Access Token", e);
        }
    }
    return null;
}
 
Example #7
Source File: DatastoreFactoryTest.java    From google-cloud-datastore with Apache License 2.0 6 votes vote down vote up
/**
 * Specifying both credential and transport, the factory will use the
 * transport specified and not the one in the credential.
 */
@Test
public void makeClient_WithCredentialTransport() {
  NetHttpTransport credTransport = new NetHttpTransport();
  NetHttpTransport transport = new NetHttpTransport();
  GoogleCredential credential = new GoogleCredential.Builder()
      .setTransport(credTransport)
      .build();
  DatastoreOptions options = new DatastoreOptions.Builder()
      .projectId(PROJECT_ID)
      .credential(credential)
      .transport(transport)
      .build();
  HttpRequestFactory f = factory.makeClient(options);
  assertNotSame(credTransport, f.getTransport());
  assertEquals(transport, f.getTransport());
}
 
Example #8
Source File: AdHocReportDownloadHelperTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);

  Enum<?> downloadFormat = TestDownloadFormat.CSV;
  Mockito.<Enum<?>>when(reportRequest.getDownloadFormat()).thenReturn(downloadFormat);

  credential = new GoogleCredential.Builder().setTransport(new NetHttpTransport())
      .setJsonFactory(new JacksonFactory()).build();
  credential.setAccessToken("TEST_ACCESS_TOKEN");

  AdWordsSession session = new AdWordsSession.Builder()
      .withUserAgent("TEST_APP")
      .withOAuth2Credential(credential)
      .withEndpoint(testHttpServer.getServerUrl())
      .withDeveloperToken("TEST_DEVELOPER_TOKEN")
      .withClientCustomerId("TEST_CLIENT_CUSTOMER_ID")
      .build();

  helper =
      new GenericAdWordsServices()
          .getBootstrapper()
          .getInstanceOf(session, AdHocReportDownloadHelper.class);
  exceptionBuilder = DetailedReportDownloadResponseException::new;
}
 
Example #9
Source File: PubsubUtils.java    From cloud-pubsub-samples-java with 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(httpTransport, jsonFactory);
    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(APP_NAME)
            .build();
}
 
Example #10
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 #11
Source File: FirebaseOptionsTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createOptionsWithOnlyMandatoryValuesSet() throws IOException {
  FirebaseOptions firebaseOptions =
      new FirebaseOptions.Builder()
          .setCredentials(GoogleCredentials.fromStream(ServiceAccount.EDITOR.asStream()))
          .build();
  assertNotNull(firebaseOptions.getJsonFactory());
  assertNotNull(firebaseOptions.getHttpTransport());
  assertNotNull(firebaseOptions.getThreadManager());
  assertNull(firebaseOptions.getDatabaseUrl());
  assertNull(firebaseOptions.getStorageBucket());
  assertEquals(0, firebaseOptions.getConnectTimeout());
  assertEquals(0, firebaseOptions.getReadTimeout());

  GoogleCredentials credentials = firebaseOptions.getCredentials();
  assertNotNull(credentials);
  assertTrue(credentials instanceof ServiceAccountCredentials);
  assertEquals(
      GoogleCredential.fromStream(ServiceAccount.EDITOR.asStream()).getServiceAccountId(),
      ((ServiceAccountCredentials) credentials).getClientEmail());
  assertNull(firebaseOptions.getFirestoreOptions());
}
 
Example #12
Source File: DatastoreHelper.java    From google-cloud-datastore with Apache License 2.0 6 votes vote down vote up
private static Credential getCredentialFromEnv() throws GeneralSecurityException, IOException {
  if (System.getenv(LOCAL_HOST_ENV_VAR) != null) {
    logger.log(Level.INFO, "{0} environment variable was set. Not using credentials.",
        new Object[] {LOCAL_HOST_ENV_VAR});
    return null;
  }
  String serviceAccount = System.getenv(SERVICE_ACCOUNT_ENV_VAR);
  String privateKeyFile = System.getenv(PRIVATE_KEY_FILE_ENV_VAR);
  if (serviceAccount != null && privateKeyFile != null) {
    logger.log(Level.INFO, "{0} and {1} environment variables were set. "
        + "Using service account credential.",
        new Object[] {SERVICE_ACCOUNT_ENV_VAR, PRIVATE_KEY_FILE_ENV_VAR});
    return getServiceAccountCredential(serviceAccount, privateKeyFile);
  }
  return GoogleCredential.getApplicationDefault()
      .createScoped(DatastoreOptions.SCOPES);
}
 
Example #13
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 #14
Source File: CredentialStore.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public Optional<Credential> load() {
     Properties properties = new Properties();
     try {
File file = getAuthenticationFile(options);
         if(!file.exists() || !file.canRead()) {
             LOGGER.log(Level.FINE, "Cannot find or read properties file. Returning empty credentials.");
             return Optional.empty();
         }
         properties.load(new FileReader(file));
         HttpTransport httpTransport = new NetHttpTransport();
         JsonFactory jsonFactory = new JacksonFactory();
         GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(jsonFactory)
                 .setTransport(httpTransport).setClientSecrets(OAuth2ClientCredentials.CLIENT_ID, OAuth2ClientCredentials.CLIENT_SECRET).build();
         credential.setAccessToken(properties.getProperty(PROP_ACCESS_TOKEN));
         credential.setRefreshToken(properties.getProperty(PROP_REFRESH_TOKEN));
         return Optional.of(credential);
     } catch (IOException e) {
         throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to load properties file: " + e.getMessage(), e);
     }
 }
 
Example #15
Source File: ClientAuthenticationFactory.java    From spring-cloud-vault with Apache License 2.0 6 votes vote down vote up
private GoogleCredential getGoogleCredential(GcpIamProperties gcp)
		throws IOException {

	GcpCredentials credentialProperties = gcp.getCredentials();
	if (credentialProperties.getLocation() != null) {
		return GoogleCredential
				.fromStream(credentialProperties.getLocation().getInputStream());
	}

	if (StringUtils.hasText(credentialProperties.getEncodedKey())) {
		return GoogleCredential.fromStream(new ByteArrayInputStream(
				Base64.getDecoder().decode(credentialProperties.getEncodedKey())));
	}

	return GoogleCredential.getApplicationDefault();
}
 
Example #16
Source File: GSpreadFeedProcessor.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * helper method to refresh the access token and authenticate
 *
 * @throws Exception
 */
private void refreshAndAuthenticate() throws Exception {
    GoogleCredential credential = getBaseCredential();
    credential.setAccessToken(this.accessToken);
    credential.setRefreshToken(this.refreshToken);
    credential.refreshToken();
    this.accessToken = credential.getAccessToken();
    this.service.setOAuth2Credentials(credential);
}
 
Example #17
Source File: StyxScheduler.java    From styx with Apache License 2.0 5 votes vote down vote up
private static Container createGkeClient() {
  try {
    final HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    final JsonFactory jsonFactory = Utils.getDefaultJsonFactory();
    final GoogleCredential credential =
        GoogleCredential.getApplicationDefault(httpTransport, jsonFactory)
            .createScoped(ContainerScopes.all());
    return new Container.Builder(httpTransport, jsonFactory, credential)
        .setApplicationName(SERVICE_NAME)
        .build();
  } catch (GeneralSecurityException | IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #18
Source File: EndToEndTestBase.java    From styx with Apache License 2.0 5 votes vote down vote up
private void setUpServiceAccounts() throws IOException {
  // Create workflow service account
  iam = new Iam.Builder(
      Utils.getDefaultTransport(), Utils.getDefaultJsonFactory(),
      GoogleCredential.getApplicationDefault().createScoped(IamScopes.all()))
      .setApplicationName(testNamespace)
      .build();
  workflowServiceAccount = iam.projects().serviceAccounts()
      .create("projects/styx-oss-test",
          new CreateServiceAccountRequest().setAccountId(workflowServiceAccountId)
              .setServiceAccount(new ServiceAccount().setDisplayName(testNamespace)))
      .execute();
  log.info("Created workflow test service account: {}", workflowServiceAccount.getEmail());

  // Set up workflow service account permissions
  var workflowServiceAccountFqn = "projects/styx-oss-test/serviceAccounts/" + workflowServiceAccount.getEmail();
  var workflowServiceAccountPolicy = iam.projects().serviceAccounts()
      .getIamPolicy(workflowServiceAccountFqn)
      .execute();
  if (workflowServiceAccountPolicy.getBindings() == null) {
    workflowServiceAccountPolicy.setBindings(new ArrayList<>());
  }
  workflowServiceAccountPolicy.getBindings()
      .add(new Binding().setRole("projects/styx-oss-test/roles/StyxWorkflowServiceAccountUser")
          .setMembers(List.of("serviceAccount:[email protected]")));
  // TODO: set up a styx service account instead of using styx-circle-ci@
  workflowServiceAccountPolicy.getBindings()
      .add(new Binding().setRole("roles/iam.serviceAccountKeyAdmin")
          .setMembers(List.of("serviceAccount:[email protected]")));
  iam.projects().serviceAccounts().setIamPolicy(workflowServiceAccountFqn,
      new SetIamPolicyRequest().setPolicy(workflowServiceAccountPolicy))
      .execute();
}
 
Example #19
Source File: GetRefreshTokenWithoutPropertiesFile.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
private static Credential getOAuth2Credential(GoogleClientSecrets clientSecrets)
    throws Exception {
  GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder(
      new NetHttpTransport(),
      new JacksonFactory(),
      clientSecrets,
      Arrays.asList(SCOPE))
      // Set the access type to offline so that the token can be refreshed.
      // By default, the library will automatically refresh tokens when it
      // can, but this can be turned off by setting
      // api.admanager.refreshOAuth2Token=false in your ads.properties file.
      .setAccessType("offline").build();

  String authorizeUrl =
      authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build();
  System.out.printf("Paste this url in your browser:%n%s%n", authorizeUrl);

  // Wait for the authorization code.
  System.out.println("Type the code you received here: ");
  @SuppressWarnings("DefaultCharset") // Reading from stdin, so default charset is appropriate.
  String authorizationCode = new BufferedReader(new InputStreamReader(System.in)).readLine();

  // Authorize the OAuth2 token.
  GoogleAuthorizationCodeTokenRequest tokenRequest =
      authorizationFlow.newTokenRequest(authorizationCode);
  tokenRequest.setRedirectUri(CALLBACK_URL);
  GoogleTokenResponse tokenResponse = tokenRequest.execute();

  // Create the OAuth2 credential.
  GoogleCredential credential = new GoogleCredential.Builder()
      .setTransport(new NetHttpTransport())
      .setJsonFactory(new JacksonFactory())
      .setClientSecrets(clientSecrets)
      .build();

  // Set authorized credentials.
  credential.setFromTokenResponse(tokenResponse);

  return credential;
}
 
Example #20
Source File: GcpCredentialProvider.java    From digdag with Apache License 2.0 5 votes vote down vote up
private GoogleCredential googleCredential(String credential)
{
    try {
        return GoogleCredential.fromStream(new ByteArrayInputStream(credential.getBytes(UTF_8)));
    }
    catch (IOException e) {
        throw new TaskExecutionException(e);
    }
}
 
Example #21
Source File: DefaultDhisConfigurationProvider.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Optional<GoogleAccessToken> getGoogleAccessToken()
{
    if ( !getGoogleCredential().isPresent() )
    {
        return Optional.empty();
    }

    GoogleCredential credential = getGoogleCredential().get();

    try
    {
        if ( !credential.refreshToken() || credential.getExpiresInSeconds() == null )
        {
            log.warn( "There is no refresh token to be retrieved" );

            return Optional.empty();
        }
    }
    catch ( IOException ex )
    {
        throw new IllegalStateException( "Could not retrieve refresh token: " + ex.getMessage(), ex );
    }

    GoogleAccessToken token = new GoogleAccessToken();

    token.setAccessToken( credential.getAccessToken() );
    token.setClientId( getProperty( ConfigurationKey.GOOGLE_SERVICE_ACCOUNT_CLIENT_ID ) );
    token.setExpiresInSeconds( credential.getExpiresInSeconds() );
    token.setExpiresOn( LocalDateTime.now().plusSeconds( token.getExpiresInSeconds() ) );

    return Optional.of( token );
}
 
Example #22
Source File: GceApi.java    From simpleci with MIT License 5 votes vote down vote up
private Compute createApi(GoogleComputeProvider provider) throws IOException, GeneralSecurityException {
    GoogleCredential credential = GoogleCredential
            .fromStream(new ByteArrayInputStream(provider.gcAccount.serviceAccount.getBytes(StandardCharsets.UTF_8)))
            .createScoped(Collections.singleton(ComputeScopes.COMPUTE));

    NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    return new Compute.Builder(
            httpTransport, JSON_FACTORY, null).setApplicationName(APPLICATION_NAME)
                                              .setHttpRequestInitializer(credential).build();
}
 
Example #23
Source File: AuthenticatorFactoryTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Override
CloudResourceManager buildCloudResourceManager(HttpTransport httpTransport,
                                               JsonFactory jsonFactory,
                                               GoogleCredential credential,
                                               String service) {
  return cloudResourceManager;
}
 
Example #24
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 #25
Source File: BaseTest.java    From java-samples with Apache License 2.0 5 votes vote down vote up
public Sheets buildService(GoogleCredential credential) throws IOException,
    GeneralSecurityException {
  return new Sheets.Builder(
      GoogleNetHttpTransport.newTrustedTransport(),
      JacksonFactory.getDefaultInstance(),
      credential)
      .setApplicationName("Sheets API Snippets")
      .build();
}
 
Example #26
Source File: FirebaseService.java    From zhcet-web with Apache License 2.0 5 votes vote down vote up
private void initializeFirebase() throws IOException {
    try {
        String messagingScope = "https://www.googleapis.com/auth/firebase.messaging";
        googleCredential = GoogleCredential.fromStream(firebaseLocator.getServiceAccountStream())
                .createScoped(Collections.singletonList(messagingScope));
        GoogleCredentials googleCredentials = GoogleCredentials.fromStream(firebaseLocator.getServiceAccountStream());

        projectId = ((ServiceAccountCredentials) googleCredentials).getProjectId();

        if (projectId == null)
            throw new RuntimeException("Project ID must not be null");

        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredentials(googleCredentials)
                .setDatabaseUrl(getDatabaseUrl())
                .setStorageBucket(getStorageBucket())
                .build();

        FirebaseApp.initializeApp(options);
        log.info(ConsoleHelper.green("Firebase Initialized"));
    } catch (IllegalStateException ise) {
        log.info(ConsoleHelper.yellow("Firebase already initialized"));
    } catch (IllegalArgumentException e) {
        uninitialized = true;
        log.error("Firebase couldn't be initialized", e);
    }
}
 
Example #27
Source File: BaseTest.java    From java-samples with Apache License 2.0 5 votes vote down vote up
public Drive buildDriveService(GoogleCredential credential)
        throws IOException, GeneralSecurityException {
    return new Drive.Builder(
            GoogleNetHttpTransport.newTrustedTransport(),
            JacksonFactory.getDefaultInstance(),
            credential)
            .setApplicationName("Slides API Snippets")
            .build();
}
 
Example #28
Source File: ServiceAccountConfiguration.java    From play-work with Apache License 2.0 5 votes vote down vote up
public static Pubsub createPubsubClient(String serviceAccountEmail, String privateKeyFilePath)
    throws IOException, GeneralSecurityException {
  HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
  GoogleCredential credential = new GoogleCredential.Builder()
      .setTransport(transport)
      .setJsonFactory(JSON_FACTORY)
      .setServiceAccountScopes(PubsubScopes.all())

      // Obtain this from the "APIs & auth" -> "Credentials"
      // section in the Google Developers Console:
      // https://console.developers.google.com/
      // (and put the e-mail address into your system property obviously)
      .setServiceAccountId(serviceAccountEmail)

      // Download this file from "APIs & auth" -> "Credentials"
      // section in the Google Developers Console:
      // https://console.developers.google.com/
      .setServiceAccountPrivateKeyFromP12File(new File(privateKeyFilePath))
      .build();


  // Please use custom HttpRequestInitializer for automatic
  // retry upon failures.  We provide a simple reference
  // implementation in the "Retry Handling" section.
  HttpRequestInitializer initializer =
      new RetryHttpInitializerWrapper(credential);
  return new Pubsub.Builder(transport, JSON_FACTORY, initializer)
      .setApplicationName("PubSub Example")
      .build();
}
 
Example #29
Source File: NewsInjector.java    From cloud-pubsub-samples-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Cloud Pub/Sub client.
 */
public Pubsub createPubsubClient()
  throws IOException, GeneralSecurityException {
  HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
  GoogleCredential credential = GoogleCredential.getApplicationDefault();
  HttpRequestInitializer initializer =
      new RetryHttpInitializerWrapper(credential);
  return new Pubsub.Builder(transport, JSON_FACTORY, initializer).build();
}
 
Example #30
Source File: FirebaseOptionsTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createOptionsWithAllValuesSet() throws IOException {
  GsonFactory jsonFactory = new GsonFactory();
  NetHttpTransport httpTransport = new NetHttpTransport();
  FirestoreOptions firestoreOptions = FirestoreOptions.newBuilder()
      .setTimestampsInSnapshotsEnabled(true)
      .build();
  FirebaseOptions firebaseOptions =
      new FirebaseOptions.Builder()
          .setDatabaseUrl(FIREBASE_DB_URL)
          .setStorageBucket(FIREBASE_STORAGE_BUCKET)
          .setCredentials(GoogleCredentials.fromStream(ServiceAccount.EDITOR.asStream()))
          .setProjectId(FIREBASE_PROJECT_ID)
          .setJsonFactory(jsonFactory)
          .setHttpTransport(httpTransport)
          .setThreadManager(MOCK_THREAD_MANAGER)
          .setConnectTimeout(30000)
          .setReadTimeout(60000)
          .setFirestoreOptions(firestoreOptions)
          .build();
  assertEquals(FIREBASE_DB_URL, firebaseOptions.getDatabaseUrl());
  assertEquals(FIREBASE_STORAGE_BUCKET, firebaseOptions.getStorageBucket());
  assertEquals(FIREBASE_PROJECT_ID, firebaseOptions.getProjectId());
  assertSame(jsonFactory, firebaseOptions.getJsonFactory());
  assertSame(httpTransport, firebaseOptions.getHttpTransport());
  assertSame(MOCK_THREAD_MANAGER, firebaseOptions.getThreadManager());
  assertEquals(30000, firebaseOptions.getConnectTimeout());
  assertEquals(60000, firebaseOptions.getReadTimeout());
  assertSame(firestoreOptions, firebaseOptions.getFirestoreOptions());

  GoogleCredentials credentials = firebaseOptions.getCredentials();
  assertNotNull(credentials);
  assertTrue(credentials instanceof ServiceAccountCredentials);
  assertEquals(
      GoogleCredential.fromStream(ServiceAccount.EDITOR.asStream()).getServiceAccountId(),
      ((ServiceAccountCredentials) credentials).getClientEmail());
}