com.google.api.client.googleapis.util.Utils Java Examples

The following examples show how to use com.google.api.client.googleapis.util.Utils. 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: 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 #2
Source File: GcloudPubsub.java    From cloud-pubsub-mqtt-proxy with 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 #3
Source File: FirebaseUserManagerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testGeneratePasswordResetLinkWithSettings() throws Exception {
  TestResponseInterceptor interceptor = initializeAppForUserManagement(
          TestUtils.loadResource("generateEmailLink.json"));
  String link = FirebaseAuth.getInstance()
          .generatePasswordResetLinkAsync("[email protected]", ACTION_CODE_SETTINGS).get();
  assertEquals("https://mock-oob-link.for.auth.tests", link);
  checkRequestHeaders(interceptor);

  ByteArrayOutputStream out = new ByteArrayOutputStream();
  interceptor.getResponse().getRequest().getContent().writeTo(out);
  JsonFactory jsonFactory = Utils.getDefaultJsonFactory();
  GenericJson parsed = jsonFactory.fromString(new String(out.toByteArray()), GenericJson.class);
  assertEquals(3 + ACTION_CODE_SETTINGS_MAP.size(), parsed.size());
  assertEquals("[email protected]", parsed.get("email"));
  assertEquals("PASSWORD_RESET", parsed.get("requestType"));
  assertTrue((Boolean) parsed.get("returnOobLink"));
  for (Map.Entry<String, Object> entry : ACTION_CODE_SETTINGS_MAP.entrySet()) {
    assertEquals(entry.getValue(), parsed.get(entry.getKey()));
  }
}
 
Example #4
Source File: InstanceIdClientImplTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
private void checkTopicManagementRequest(
    HttpRequest request, TopicManagementResponse result) throws IOException {
  assertEquals(1, result.getSuccessCount());
  assertEquals(1, result.getFailureCount());
  assertEquals(1, result.getErrors().size());
  assertEquals(1, result.getErrors().get(0).getIndex());
  assertEquals("unknown-error", result.getErrors().get(0).getReason());

  ByteArrayOutputStream out = new ByteArrayOutputStream();
  request.getContent().writeTo(out);
  Map<String, Object> parsed = new HashMap<>();
  JsonParser parser = Utils.getDefaultJsonFactory().createJsonParser(out.toString());
  parser.parseAndClose(parsed);
  assertEquals(2, parsed.size());
  assertEquals("/topics/test-topic", parsed.get("to"));
  assertEquals(ImmutableList.of("id1", "id2"), parsed.get("registration_tokens"));
}
 
Example #5
Source File: FirebaseUserManagerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testGeneratePasswordResetLink() throws Exception {
  TestResponseInterceptor interceptor = initializeAppForUserManagement(
          TestUtils.loadResource("generateEmailLink.json"));
  String link = FirebaseAuth.getInstance()
          .generatePasswordResetLinkAsync("[email protected]").get();
  assertEquals("https://mock-oob-link.for.auth.tests", link);
  checkRequestHeaders(interceptor);

  ByteArrayOutputStream out = new ByteArrayOutputStream();
  interceptor.getResponse().getRequest().getContent().writeTo(out);
  JsonFactory jsonFactory = Utils.getDefaultJsonFactory();
  GenericJson parsed = jsonFactory.fromString(new String(out.toByteArray()), GenericJson.class);
  assertEquals(3, parsed.size());
  assertEquals("[email protected]", parsed.get("email"));
  assertEquals("PASSWORD_RESET", parsed.get("requestType"));
  assertTrue((Boolean) parsed.get("returnOobLink"));
}
 
Example #6
Source File: FirebaseUserManagerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateEmailVerificationLinkWithSettings() throws Exception {
  TestResponseInterceptor interceptor = initializeAppForUserManagement(
      TestUtils.loadResource("generateEmailLink.json"));
  String link = FirebaseAuth.getInstance()
      .generateEmailVerificationLinkAsync("[email protected]", ACTION_CODE_SETTINGS).get();
  assertEquals("https://mock-oob-link.for.auth.tests", link);
  checkRequestHeaders(interceptor);

  ByteArrayOutputStream out = new ByteArrayOutputStream();
  interceptor.getResponse().getRequest().getContent().writeTo(out);
  JsonFactory jsonFactory = Utils.getDefaultJsonFactory();
  GenericJson parsed = jsonFactory.fromString(new String(out.toByteArray()), GenericJson.class);
  assertEquals(3 + ACTION_CODE_SETTINGS_MAP.size(), parsed.size());
  assertEquals("[email protected]", parsed.get("email"));
  assertEquals("VERIFY_EMAIL", parsed.get("requestType"));
  assertTrue((Boolean) parsed.get("returnOobLink"));
  for (Map.Entry<String, Object> entry : ACTION_CODE_SETTINGS_MAP.entrySet()) {
    assertEquals(entry.getValue(), parsed.get(entry.getKey()));
  }
}
 
Example #7
Source File: ApiClient.java    From Xero-Java with 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 #8
Source File: FirebaseUserManagerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testUserUpdater() throws IOException {
  UpdateRequest update = new UpdateRequest("test");
  Map<String, Object> claims = ImmutableMap.<String, Object>of("admin", true, "package", "gold");
  Map<String, Object> map = update
      .setDisplayName("Display Name")
      .setPhotoUrl("http://test.com/example.png")
      .setEmail("[email protected]")
      .setPhoneNumber("+1234567890")
      .setEmailVerified(true)
      .setPassword("secret")
      .setCustomClaims(claims)
      .getProperties(Utils.getDefaultJsonFactory());
  assertEquals(8, map.size());
  assertEquals(update.getUid(), map.get("localId"));
  assertEquals("Display Name", map.get("displayName"));
  assertEquals("http://test.com/example.png", map.get("photoUrl"));
  assertEquals("[email protected]", map.get("email"));
  assertEquals("+1234567890", map.get("phoneNumber"));
  assertTrue((Boolean) map.get("emailVerified"));
  assertEquals("secret", map.get("password"));
  assertEquals(Utils.getDefaultJsonFactory().toString(claims), map.get("customAttributes"));
}
 
Example #9
Source File: FirebaseUserManagerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateSessionCookie() throws Exception {
  TestResponseInterceptor interceptor = initializeAppForUserManagement(
      TestUtils.loadResource("createSessionCookie.json"));
  SessionCookieOptions options = SessionCookieOptions.builder()
      .setExpiresIn(TimeUnit.HOURS.toMillis(1))
      .build();
  String cookie = FirebaseAuth.getInstance().createSessionCookieAsync("testToken", options).get();
  assertEquals("MockCookieString", cookie);
  checkRequestHeaders(interceptor);

  ByteArrayOutputStream out = new ByteArrayOutputStream();
  interceptor.getResponse().getRequest().getContent().writeTo(out);
  JsonFactory jsonFactory = Utils.getDefaultJsonFactory();
  GenericJson parsed = jsonFactory.fromString(new String(out.toByteArray()), GenericJson.class);
  assertEquals(2, parsed.size());
  assertEquals("testToken", parsed.get("idToken"));
  assertEquals(new BigDecimal(3600), parsed.get("validDuration"));
}
 
Example #10
Source File: FirebaseUserManagerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateEmailVerificationLink() throws Exception {
  TestResponseInterceptor interceptor = initializeAppForUserManagement(
      TestUtils.loadResource("generateEmailLink.json"));
  String link = FirebaseAuth.getInstance()
      .generateEmailVerificationLinkAsync("[email protected]").get();
  assertEquals("https://mock-oob-link.for.auth.tests", link);
  checkRequestHeaders(interceptor);

  ByteArrayOutputStream out = new ByteArrayOutputStream();
  interceptor.getResponse().getRequest().getContent().writeTo(out);
  JsonFactory jsonFactory = Utils.getDefaultJsonFactory();
  GenericJson parsed = jsonFactory.fromString(new String(out.toByteArray()), GenericJson.class);
  assertEquals(3, parsed.size());
  assertEquals("[email protected]", parsed.get("email"));
  assertEquals("VERIFY_EMAIL", parsed.get("requestType"));
  assertTrue((Boolean) parsed.get("returnOobLink"));
}
 
Example #11
Source File: FirebaseUserManagerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateSignInWithEmailLinkWithSettings() throws Exception {
  TestResponseInterceptor interceptor = initializeAppForUserManagement(
      TestUtils.loadResource("generateEmailLink.json"));
  String link = FirebaseAuth.getInstance()
      .generateSignInWithEmailLinkAsync("[email protected]", ACTION_CODE_SETTINGS).get();
  assertEquals("https://mock-oob-link.for.auth.tests", link);
  checkRequestHeaders(interceptor);

  ByteArrayOutputStream out = new ByteArrayOutputStream();
  interceptor.getResponse().getRequest().getContent().writeTo(out);
  JsonFactory jsonFactory = Utils.getDefaultJsonFactory();
  GenericJson parsed = jsonFactory.fromString(new String(out.toByteArray()), GenericJson.class);
  assertEquals(3 + ACTION_CODE_SETTINGS_MAP.size(), parsed.size());
  assertEquals("[email protected]", parsed.get("email"));
  assertEquals("EMAIL_SIGNIN", parsed.get("requestType"));
  assertTrue((Boolean) parsed.get("returnOobLink"));
  for (Map.Entry<String, Object> entry : ACTION_CODE_SETTINGS_MAP.entrySet()) {
    assertEquals(entry.getValue(), parsed.get(entry.getKey()));
  }
}
 
Example #12
Source File: FirebaseUserManagerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testImportUsers() throws Exception {
  TestResponseInterceptor interceptor = initializeAppForUserManagement("{}");
  ImportUserRecord user1 = ImportUserRecord.builder().setUid("user1").build();
  ImportUserRecord user2 = ImportUserRecord.builder().setUid("user2").build();

  List<ImportUserRecord> users = ImmutableList.of(user1, user2);
  UserImportResult result = FirebaseAuth.getInstance().importUsersAsync(users, null).get();
  checkRequestHeaders(interceptor);
  assertEquals(2, result.getSuccessCount());
  assertEquals(0, result.getFailureCount());
  assertTrue(result.getErrors().isEmpty());

  ByteArrayOutputStream out = new ByteArrayOutputStream();
  interceptor.getResponse().getRequest().getContent().writeTo(out);
  JsonFactory jsonFactory = Utils.getDefaultJsonFactory();
  GenericJson parsed = jsonFactory.fromString(new String(out.toByteArray()), GenericJson.class);
  assertEquals(1, parsed.size());
  List<Map<String, Object>> expected = ImmutableList.of(
      user1.getProperties(jsonFactory),
      user2.getProperties(jsonFactory)
  );
  assertEquals(expected, parsed.get("users"));
}
 
Example #13
Source File: StringUtils.java    From dockerflow with Apache License 2.0 6 votes vote down vote up
/** Deserialize from json. */
public static <T> T fromJson(String s, Class<T> c) throws IOException {
  FileUtils.LOG.debug("Deserializing from json to " + c);
  T retval;

  // For some reason, this only works for auto-generated Google API
  // classes
  if (c.toString().startsWith("com.google.api.services.")) {
    FileUtils.LOG.debug("Using Google APIs JsonParser");
    retval = Utils.getDefaultJsonFactory().createJsonParser(s).parse(c);
  } else {
    FileUtils.LOG.debug("Using Gson");
    retval = new GsonBuilder().setLenient().create().fromJson(s, c);
  }
  return retval;
}
 
Example #14
Source File: FirebaseUserManagerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetCustomAttributes() throws Exception {
  TestResponseInterceptor interceptor = initializeAppForUserManagement(
      TestUtils.loadResource("createUser.json"));
  // should not throw
  ImmutableMap<String, Object> claims = ImmutableMap.<String, Object>of(
      "admin", true, "package", "gold");
  FirebaseAuth.getInstance().setCustomUserClaimsAsync("testuser", claims).get();
  checkRequestHeaders(interceptor);

  ByteArrayOutputStream out = new ByteArrayOutputStream();
  interceptor.getResponse().getRequest().getContent().writeTo(out);
  JsonFactory jsonFactory = Utils.getDefaultJsonFactory();
  GenericJson parsed = jsonFactory.fromString(new String(out.toByteArray()), GenericJson.class);
  assertEquals("testuser", parsed.get("localId"));
  assertEquals(jsonFactory.toString(claims), parsed.get("customAttributes"));
}
 
Example #15
Source File: FirebaseCustomTokenTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateCustomTokenWithoutServiceAccountCredentials() throws Exception {
  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
  String content = Utils.getDefaultJsonFactory().toString(
      ImmutableMap.of("signature", BaseEncoding.base64().encode("test-signature".getBytes())));
  response.setContent(content);
  MockHttpTransport transport = new MultiRequestMockHttpTransport(ImmutableList.of(response));

  FirebaseOptions options = FirebaseOptions.builder()
      .setCredentials(new MockGoogleCredentials("test-token"))
      .setProjectId("test-project-id")
      .setServiceAccountId("[email protected]")
      .setHttpTransport(transport)
      .build();
  FirebaseApp app = FirebaseApp.initializeApp(options);
  FirebaseAuth auth = FirebaseAuth.getInstance(app);

  String token = auth.createCustomTokenAsync("user1").get();
  FirebaseCustomAuthToken parsedToken = FirebaseCustomAuthToken.parse(new GsonFactory(), token);
  assertEquals(parsedToken.getPayload().getUid(), "user1");
  assertEquals(parsedToken.getPayload().getSubject(), "[email protected]");
  assertEquals(parsedToken.getPayload().getIssuer(), "[email protected]");
  assertNull(parsedToken.getPayload().getDeveloperClaims());
  assertEquals("test-signature", new String(parsedToken.getSignatureBytes()));
}
 
Example #16
Source File: ServiceAccountCleanupTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void deleteExpiredTestServiceAccounts() throws IOException {
  var iam = new Iam.Builder(
      Utils.getDefaultTransport(), Utils.getDefaultJsonFactory(),
      GoogleCredential.getApplicationDefault().createScoped(IamScopes.all()))
      .setApplicationName(TestNamespaces.TEST_NAMESPACE_PREFIX)
      .build();

  var accounts = listServiceAccounts(iam);

  for (final ServiceAccount account : accounts) {
    var displayName = account.getDisplayName();
    if (displayName == null || !TestNamespaces.isExpiredTestNamespace(displayName, NOW)) {
      continue;
    }
    log.info("Deleting old test service account: {}", account.getEmail());
    try {
      var request = iam.projects().serviceAccounts()
          .delete("projects/styx-oss-test/serviceAccounts/" + account.getEmail());
      executeWithRetries(request);
    } catch (Throwable e) {
      log.error("Failed to delete old test service account: {}", account.getEmail(), e);
    }
  }
}
 
Example #17
Source File: CryptoSignersTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testMetadataService() throws IOException {
  String signature = BaseEncoding.base64().encode("signed-bytes".getBytes());
  String response = Utils.getDefaultJsonFactory().toString(
      ImmutableMap.of("signature", signature));
  MockHttpTransport transport = new MultiRequestMockHttpTransport(
      ImmutableList.of(
          new MockLowLevelHttpResponse().setContent("[email protected]"),
          new MockLowLevelHttpResponse().setContent(response)));
  FirebaseOptions options = new FirebaseOptions.Builder()
      .setCredentials(new MockGoogleCredentials("test-token"))
      .setHttpTransport(transport)
      .build();
  FirebaseApp app = FirebaseApp.initializeApp(options);
  CryptoSigner signer = CryptoSigners.getCryptoSigner(app);

  assertTrue(signer instanceof CryptoSigners.IAMCryptoSigner);
  TestResponseInterceptor interceptor = new TestResponseInterceptor();
  ((CryptoSigners.IAMCryptoSigner) signer).setInterceptor(interceptor);

  byte[] data = signer.sign("foo".getBytes());
  assertArrayEquals("signed-bytes".getBytes(), data);
  final String url = "https://iam.googleapis.com/v1/projects/-/serviceAccounts/"
      + "[email protected]:signBlob";
  assertEquals(url, interceptor.getResponse().getRequest().getUrl().toString());
}
 
Example #18
Source File: CryptoSignersTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testIAMCryptoSigner() throws IOException {
  String signature = BaseEncoding.base64().encode("signed-bytes".getBytes());
  String response = Utils.getDefaultJsonFactory().toString(
      ImmutableMap.of("signature", signature));
  MockHttpTransport transport = new MockHttpTransport.Builder()
      .setLowLevelHttpResponse(new MockLowLevelHttpResponse().setContent(response))
      .build();
  TestResponseInterceptor interceptor = new TestResponseInterceptor();
  CryptoSigners.IAMCryptoSigner signer = new CryptoSigners.IAMCryptoSigner(
      transport.createRequestFactory(),
      Utils.getDefaultJsonFactory(),
      "[email protected]");
  signer.setInterceptor(interceptor);

  byte[] data = signer.sign("foo".getBytes());
  assertArrayEquals("signed-bytes".getBytes(), data);
  final String url = "https://iam.googleapis.com/v1/projects/-/serviceAccounts/"
      + "[email protected]:signBlob";
  assertEquals(url, interceptor.getResponse().getRequest().getUrl().toString());
}
 
Example #19
Source File: GoogleIdTokenVerifierTest.java    From styx with Apache License 2.0 6 votes vote down vote up
private String createToken() throws GeneralSecurityException, IOException {
  var issuedAt = Instant.now().getEpochSecond();
  var expiredAt = issuedAt + 3600; // One hour later
  var payload = new GoogleIdToken.Payload();
  payload.setAuthorizedParty("103411466401044735393");
  payload.setEmail("[email protected]");
  payload.setEmailVerified(true);
  payload.setIssuedAtTimeSeconds(issuedAt);
  payload.setExpirationTimeSeconds(expiredAt);
  payload.setIssuer("https://accounts.google.com");
  payload.setSubject("103411466401044735393");
  GenericJson googleMetadata = new GenericJson()
      .set("compute_engine", new GenericJson()
                                 .set("instance_creation_timestamp", 1556025719L)
                                 .set("instance_id", "5850837338805153689")
                                 .set("instance_name", "gew1-metricscatalogbro-b-b7z2")
                                 .set("project_id", "metrics-catalog")
                                 .set("project_number", 283581591831L)
                                 .set("zone", "europe-west1-d")
      );
  payload.set("google", googleMetadata);

  var header = new JsonWebSignature.Header().setAlgorithm("RS256");
  return JsonWebSignature.signUsingRsaSha256(privateKey, Utils.getDefaultJsonFactory(), header, payload);
}
 
Example #20
Source File: ManagedServiceAccountKeyCredentialTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  var defaultCredentials = GoogleCredentials.getApplicationDefault();

  var serviceCredentials = ImpersonatedCredentials.create(
      defaultCredentials, SERVICE_ACCOUNT,
      List.of(), List.of("https://www.googleapis.com/auth/cloud-platform"), 300);

  try {
    serviceCredentials.refreshAccessToken();
  } catch (IOException e) {
    // Do not run this test if we do not have permission to impersonate the test user.
    Assume.assumeNoException(e);
  }

  iam = new Iam.Builder(
      Utils.getDefaultTransport(), Utils.getDefaultJsonFactory(),
      new HttpCredentialsAdapter(serviceCredentials.createScoped(IamScopes.all())))
      .setApplicationName("styx-test")
      .build();
}
 
Example #21
Source File: SchemaSample.java    From cloud-search-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Builds and initializes the client with service account credentials.
 * @return CloudSearch instance
 * @throws IOException if unable to load credentials
 */
private CloudSearch buildAuthorizedClient() throws IOException {
  // Get the service account credentials based on the GOOGLE_APPLICATION_CREDENTIALS
  // environment variable
  GoogleCredential credential = GoogleCredential.getApplicationDefault(
      Utils.getDefaultTransport(),
      Utils.getDefaultJsonFactory());
  // Ensure credentials have the correct scope
  if (credential.createScopedRequired()) {
    credential = credential.createScoped(Collections.singletonList(
        "https://www.googleapis.com/auth/cloud_search"
    ));
  }
  // Build the cloud search client
  return new CloudSearch.Builder(
      Utils.getDefaultTransport(),
      Utils.getDefaultJsonFactory(),
      credential)
      .setApplicationName("Cloud Search Samples")
      .build();
}
 
Example #22
Source File: DictionarySample.java    From cloud-search-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Builds and initializes the client with service account credentials.
 *
 * @return CloudSearch instance
 * @throws IOException if unable to read credentials
 */
private CloudSearch buildAuthorizedClient() throws IOException {
  // Get the service account credentials based on the GOOGLE_APPLICATION_CREDENTIALS
  // environment variable
  GoogleCredential credential = GoogleCredential.getApplicationDefault(
      Utils.getDefaultTransport(),
      Utils.getDefaultJsonFactory());
  // Ensure credentials have the correct scope
  if (credential.createScopedRequired()) {
    credential = credential.createScoped(Collections.singletonList(
        "https://www.googleapis.com/auth/cloud_search"
    ));
  }
  // Build the cloud search client
  return new CloudSearch.Builder(
      Utils.getDefaultTransport(),
      Utils.getDefaultJsonFactory(),
      credential)
      .setApplicationName("Cloud Search Samples")
      .build();
}
 
Example #23
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 #24
Source File: FirebaseMessagingClientImplTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private FirebaseMessagingClientImpl.Builder fullyPopulatedBuilder() {
  return FirebaseMessagingClientImpl.builder()
      .setProjectId("test-project")
      .setJsonFactory(Utils.getDefaultJsonFactory())
      .setRequestFactory(Utils.getDefaultTransport().createRequestFactory())
      .setChildRequestFactory(Utils.getDefaultTransport().createRequestFactory());
}
 
Example #25
Source File: FirebaseMessagingClientImplTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private void checkRequest(
    HttpRequest request, Map<String, Object> expected) throws IOException {
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  request.getContent().writeTo(out);
  JsonParser parser = Utils.getDefaultJsonFactory().createJsonParser(out.toString());
  Map<String, Object> parsed = new HashMap<>();
  parser.parseAndClose(parsed);
  assertEquals(expected, parsed);
}
 
Example #26
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 #27
Source File: FirebaseMessagingClientImplTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private FirebaseMessagingClientImpl initClientWithFaultyTransport() {
  HttpTransport transport = TestUtils.createFaultyHttpTransport();
  return FirebaseMessagingClientImpl.builder()
      .setProjectId("test-project")
      .setJsonFactory(Utils.getDefaultJsonFactory())
      .setRequestFactory(transport.createRequestFactory())
      .setChildRequestFactory(Utils.getDefaultTransport().createRequestFactory())
      .build();
}
 
Example #28
Source File: GoogleIdTokenVerifierTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  final var keyGen = KeyPairGenerator.getInstance("RSA");
  keyGen.initialize(571);
  KeyPair pair = keyGen.generateKeyPair();
  privateKey = pair.getPrivate();

  final var keysManager = new GooglePublicKeysManager(Utils.getDefaultTransport(), Utils.getDefaultJsonFactory());
  stubPublicKey(keysManager, pair.getPublic());

  verifier = new GoogleIdTokenVerifier(keysManager);
}
 
Example #29
Source File: GoogleIdTokenAuthTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void testMockUserCredentials() throws IOException, GeneralSecurityException, InterruptedException {
  final MockResponse tokenResponse = new MockResponse()
      .setBody(Utils.getDefaultJsonFactory().toString(ImmutableMap.of("id_token", "test-id-token")));
  metadataServer.enqueue(tokenResponse);
  metadataServer.start();

  final AccessToken accessToken = new AccessToken("test-access-token",
      Date.from(Instant.now().plus(Duration.ofDays(1))));
  final GoogleCredentials credentials = UserCredentials.newBuilder()
      .setTokenServerUri(URI.create("http://localhost:" + metadataServer.getPort() + "/get-test-token"))
      .setAccessToken(accessToken)
      .setRefreshToken("user-refresh-token")
      .setClientId("user-id")
      .setClientSecret("user-secret")
      .build();
  Assume.assumeThat(credentials, is(instanceOf(UserCredentials.class)));
  final GoogleIdTokenAuth idTokenAuth = GoogleIdTokenAuth.of(credentials);
  final Optional<String> token = idTokenAuth.getToken("http://styx.foo.bar");
  assertThat(token, is(Optional.of("test-id-token")));

  final RecordedRequest recordedRequest = metadataServer.takeRequest();
  final Map<String, String> requestBody = Splitter.on('&').withKeyValueSeparator('=')
      .split(recordedRequest.getBody().readUtf8());
  assertThat(requestBody, is(ImmutableMap.of(
      "grant_type", "refresh_token",
      "refresh_token", "user-refresh-token",
      "client_id", "user-id",
      "client_secret", "user-secret")));
  assertThat(recordedRequest.getPath(), is("/get-test-token"));
  assertThat(recordedRequest.getHeader("Authorization"), is("Bearer test-access-token"));
}
 
Example #30
Source File: ManagedServiceAccountKeyCredential.java    From styx with Apache License 2.0 5 votes vote down vote up
private String signJwt(String serviceAccount, JsonWebToken.Payload payload) throws IOException {
  var fullServiceAccountName = "projects/-/serviceAccounts/" + serviceAccount;
  var request = new SignJwtRequest()
      .setPayload(Utils.getDefaultJsonFactory().toString(payload));
  return iam.projects().serviceAccounts()
      .signJwt(fullServiceAccountName, request)
      .execute()
      .getSignedJwt();
}