Java Code Examples for com.google.api.client.googleapis.util.Utils#getDefaultJsonFactory()

The following examples show how to use com.google.api.client.googleapis.util.Utils#getDefaultJsonFactory() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
Source File: GoogleCredentialsBundle.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private GoogleCredentialsBundle(GoogleCredentials googleCredentials) {
  checkNotNull(googleCredentials);
  this.googleCredentials = googleCredentials;
  this.httpTransport = Utils.getDefaultTransport();
  this.jsonFactory = Utils.getDefaultJsonFactory();
  this.httpRequestInitializer = new HttpCredentialsAdapter(googleCredentials);
}
 
Example 8
Source File: InstanceIdClientImplTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private static InstanceIdClientImpl initInstanceIdClient(
    final MockLowLevelHttpResponse mockResponse,
    final HttpResponseInterceptor interceptor) {

  MockHttpTransport transport = new MockHttpTransport.Builder()
      .setLowLevelHttpResponse(mockResponse)
      .build();
  return new InstanceIdClientImpl(
      transport.createRequestFactory(),
      Utils.getDefaultJsonFactory(),
      interceptor);
}
 
Example 9
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 10
Source File: FirebaseUserManagerTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testImportUsersWithHash() throws Exception {
  TestResponseInterceptor interceptor = initializeAppForUserManagement("{}");
  ImportUserRecord user1 = ImportUserRecord.builder()
      .setUid("user1")
      .build();
  ImportUserRecord user2 = ImportUserRecord.builder()
      .setUid("user2")
      .setPasswordHash("password".getBytes())
      .build();

  List<ImportUserRecord> users = ImmutableList.of(user1, user2);
  UserImportHash hash = new UserImportHash("MOCK_HASH") {
    @Override
    protected Map<String, Object> getOptions() {
      return ImmutableMap.<String, Object>of("key1", "value1", "key2", true);
    }
  };
  UserImportResult result = FirebaseAuth.getInstance().importUsersAsync(users,
      UserImportOptions.withHash(hash)).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(4, parsed.size());
  List<Map<String, Object>> expected = ImmutableList.of(
      user1.getProperties(jsonFactory),
      user2.getProperties(jsonFactory)
  );
  assertEquals(expected, parsed.get("users"));
  assertEquals("MOCK_HASH", parsed.get("hashAlgorithm"));
  assertEquals("value1", parsed.get("key1"));
  assertEquals(Boolean.TRUE, parsed.get("key2"));
}
 
Example 11
Source File: FirebaseUserManagerTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testImportUsersError() throws Exception {
  TestResponseInterceptor interceptor = initializeAppForUserManagement(
      TestUtils.loadResource("importUsersError.json"));
  ImportUserRecord user1 = ImportUserRecord.builder()
      .setUid("user1")
      .build();
  ImportUserRecord user2 = ImportUserRecord.builder()
      .setUid("user2")
      .build();
  ImportUserRecord user3 = ImportUserRecord.builder()
      .setUid("user3")
      .build();

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

  ErrorInfo error = result.getErrors().get(0);
  assertEquals(0, error.getIndex());
  assertEquals("Some error occurred in user1", error.getReason());
  error = result.getErrors().get(1);
  assertEquals(2, error.getIndex());
  assertEquals("Another error occurred in user3", error.getReason());

  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),
      user3.getProperties(jsonFactory)
  );
  assertEquals(expected, parsed.get("users"));
}
 
Example 12
Source File: FirebaseUserManagerTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testRevokeRefreshTokens() throws Exception {
  TestResponseInterceptor interceptor = initializeAppForUserManagement(
      TestUtils.loadResource("createUser.json"));
  // should not throw
  FirebaseAuth.getInstance().revokeRefreshTokensAsync("testuser").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"));
  assertNotNull(parsed.get("validSince"));
}
 
Example 13
Source File: ListUsersPageTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private static ExportedUserRecord newUser(String uid, String passwordHash) throws IOException {
  JsonFactory jsonFactory = Utils.getDefaultJsonFactory();
  DownloadAccountResponse.User parsed = jsonFactory.fromString(
      String.format("{\"localId\":\"%s\", \"passwordHash\":\"%s\"}", uid, passwordHash),
      DownloadAccountResponse.User.class);
  return new ExportedUserRecord(parsed, jsonFactory);
}
 
Example 14
Source File: ManagedServiceAccountKeyCredential.java    From styx with Apache License 2.0 4 votes vote down vote up
private TokenResponse requestToken(String signedJwt) throws IOException {
  var tokenRequest = new TokenRequest(Utils.getDefaultTransport(), Utils.getDefaultJsonFactory(),
      new GenericUrl(getTokenServerEncodedUrl()), "urn:ietf:params:oauth:grant-type:jwt-bearer");
  tokenRequest.put("assertion", signedJwt);
  return tokenRequest.execute();
}
 
Example 15
Source File: ServiceAccountUsageAuthorizer.java    From styx with Apache License 2.0 4 votes vote down vote up
static ServiceAccountUsageAuthorizer create(String serviceAccountUserRole,
                                            AuthorizationPolicy authorizationPolicy,
                                            GoogleCredentials credentials,
                                            String gsuiteUserEmail,
                                            String serviceName,
                                            String message,
                                            List<String> administrators,
                                            List<String> blacklist) {

  final HttpTransport httpTransport;
  try {
    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  } catch (GeneralSecurityException | IOException e) {
    throw new RuntimeException(e);
  }

  final JsonFactory jsonFactory = Utils.getDefaultJsonFactory();

  final CloudResourceManager crm = new CloudResourceManager.Builder(
      httpTransport, jsonFactory, new HttpCredentialsAdapter(credentials.createScoped(IamScopes.all())))
      .setApplicationName(serviceName)
      .build();

  final Iam iam = new Iam.Builder(
      httpTransport, jsonFactory, new HttpCredentialsAdapter(credentials.createScoped(IamScopes.all())))
      .setApplicationName(serviceName)
      .build();

  final GoogleCredential directoryCredential = new ManagedServiceAccountKeyCredential.Builder(iam)
      .setServiceAccountId(ServiceAccounts.serviceAccountEmail(credentials))
      .setServiceAccountUser(gsuiteUserEmail)
      .setServiceAccountScopes(Set.of(ADMIN_DIRECTORY_GROUP_MEMBER_READONLY))
      .build();

  final Directory directory = new Directory.Builder(httpTransport, jsonFactory, directoryCredential)
      .setApplicationName(serviceName)
      .build();

  return new Impl(iam, crm, directory, serviceAccountUserRole, authorizationPolicy,
      Impl.DEFAULT_WAIT_STRATEGY, Impl.DEFAULT_RETRY_STOP_STRATEGY, message, administrators, blacklist);
}
 
Example 16
Source File: GCSOptions.java    From dataflow-java with Apache License 2.0 4 votes vote down vote up
@Override
public JsonFactory create(PipelineOptions options) {
  return Utils.getDefaultJsonFactory();
}
 
Example 17
Source File: InstanceIdClientImplTest.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
@Test(expected = NullPointerException.class)
public void testRequestFactoryIsNull() {
  new InstanceIdClientImpl(null, Utils.getDefaultJsonFactory());
}
 
Example 18
Source File: ListUsersPageTest.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
private static ExportedUserRecord newUser(String uid) throws IOException {
  JsonFactory jsonFactory = Utils.getDefaultJsonFactory();
  DownloadAccountResponse.User parsed = jsonFactory.fromString(
      String.format("{\"localId\":\"%s\"}", uid), DownloadAccountResponse.User.class);
  return new ExportedUserRecord(parsed, jsonFactory);
}
 
Example 19
Source File: InstanceIdClientImplTest.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
private InstanceIdClient initClientWithFaultyTransport() {
  return new InstanceIdClientImpl(
      TestUtils.createFaultyHttpTransport().createRequestFactory(),
      Utils.getDefaultJsonFactory());
}
 
Example 20
Source File: KmsDecrypter.java    From dbeam with Apache License 2.0 4 votes vote down vote up
private CloudKMS kms() throws IOException {
  final HttpTransport transport = transport().orElseGet(Utils::getDefaultTransport);
  final JsonFactory jsonFactory = Utils.getDefaultJsonFactory();
  final Credentials credentials =
      credentials().isPresent()
          ? credentials().get()
          : GoogleCredentials.getApplicationDefault();
  return KmsDecrypter.kms(
      transport, jsonFactory, new HttpCredentialsAdapter(scoped(credentials)));
}