com.google.api.client.util.Clock Java Examples

The following examples show how to use com.google.api.client.util.Clock. 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: FirebaseTokenUtils.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
static FirebaseTokenVerifierImpl createIdTokenVerifier(FirebaseApp app, Clock clock) {
  String projectId = ImplFirebaseTrampolines.getProjectId(app);
  checkState(!Strings.isNullOrEmpty(projectId),
      "Must initialize FirebaseApp with a project ID to call verifyIdToken()");
  IdTokenVerifier idTokenVerifier = newIdTokenVerifier(
      clock, ID_TOKEN_ISSUER_PREFIX, projectId);
  GooglePublicKeysManager publicKeysManager = newPublicKeysManager(
      app.getOptions(), clock, ID_TOKEN_CERT_URL);
  return FirebaseTokenVerifierImpl.builder()
      .setShortName("ID token")
      .setMethod("verifyIdToken()")
      .setDocUrl("https://firebase.google.com/docs/auth/admin/verify-id-tokens")
      .setJsonFactory(app.getOptions().getJsonFactory())
      .setPublicKeysManager(publicKeysManager)
      .setIdTokenVerifier(idTokenVerifier)
      .build();
}
 
Example #2
Source File: FirebaseTokenUtils.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
static FirebaseTokenVerifierImpl createSessionCookieVerifier(FirebaseApp app, Clock clock) {
  String projectId = ImplFirebaseTrampolines.getProjectId(app);
  checkState(!Strings.isNullOrEmpty(projectId),
      "Must initialize FirebaseApp with a project ID to call verifySessionCookie()");
  IdTokenVerifier idTokenVerifier = newIdTokenVerifier(
      clock, SESSION_COOKIE_ISSUER_PREFIX, projectId);
  GooglePublicKeysManager publicKeysManager = newPublicKeysManager(
      app.getOptions(), clock, SESSION_COOKIE_CERT_URL);
  return FirebaseTokenVerifierImpl.builder()
      .setJsonFactory(app.getOptions().getJsonFactory())
      .setPublicKeysManager(publicKeysManager)
      .setIdTokenVerifier(idTokenVerifier)
      .setShortName("session cookie")
      .setMethod("verifySessionCookie()")
      .setDocUrl("https://firebase.google.com/docs/auth/admin/manage-cookies")
      .build();
}
 
Example #3
Source File: PubsubUnboundedSource.java    From beam with Apache License 2.0 6 votes vote down vote up
/** Construct an unbounded source to consume from the Pubsub {@code subscription}. */
public PubsubUnboundedSource(
    Clock clock,
    PubsubClientFactory pubsubFactory,
    @Nullable ValueProvider<ProjectPath> project,
    @Nullable ValueProvider<TopicPath> topic,
    @Nullable ValueProvider<SubscriptionPath> subscription,
    @Nullable String timestampAttribute,
    @Nullable String idAttribute,
    boolean needsAttributes) {
  this(
      clock,
      pubsubFactory,
      project,
      topic,
      subscription,
      timestampAttribute,
      idAttribute,
      needsAttributes,
      false);
}
 
Example #4
Source File: PubsubUnboundedSource.java    From beam with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
PubsubUnboundedSource(
    Clock clock,
    PubsubClientFactory pubsubFactory,
    @Nullable ValueProvider<ProjectPath> project,
    @Nullable ValueProvider<TopicPath> topic,
    @Nullable ValueProvider<SubscriptionPath> subscription,
    @Nullable String timestampAttribute,
    @Nullable String idAttribute,
    boolean needsAttributes,
    boolean needsMessageId) {
  checkArgument(
      (topic == null) != (subscription == null),
      "Exactly one of topic and subscription must be given");
  this.clock = clock;
  this.pubsubFactory = checkNotNull(pubsubFactory);
  this.project = project;
  this.topic = topic;
  this.subscription = subscription;
  this.timestampAttribute = timestampAttribute;
  this.idAttribute = idAttribute;
  this.needsAttributes = needsAttributes;
  this.needsMessageId = needsMessageId;
}
 
Example #5
Source File: IdTokenVerifierTest.java    From google-oauth-java-client with Apache License 2.0 6 votes vote down vote up
public void testBuilder() throws Exception {
  IdTokenVerifier.Builder builder =
      new IdTokenVerifier.Builder().setIssuer(ISSUER).setAudience(TRUSTED_CLIENT_IDS);
  assertEquals(Clock.SYSTEM, builder.getClock());
  assertEquals(ISSUER, builder.getIssuer());
  assertEquals(Collections.singleton(ISSUER), builder.getIssuers());
  assertTrue(TRUSTED_CLIENT_IDS.equals(builder.getAudience()));
  Clock clock = new MyClock();
  builder.setClock(clock);
  assertEquals(clock, builder.getClock());
  IdTokenVerifier verifier = builder.build();
  assertEquals(clock, verifier.getClock());
  assertEquals(ISSUER, verifier.getIssuer());
  assertEquals(Collections.singleton(ISSUER), builder.getIssuers());
  assertEquals(TRUSTED_CLIENT_IDS, Lists.newArrayList(verifier.getAudience()));
}
 
Example #6
Source File: HotKeyLoggerTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Test
public void throttlesLoggingHotKeyMessage() {
  HotKeyLogger hotKeyLogger = new HotKeyLogger(clock);

  clock.setTime(Clock.SYSTEM.currentTimeMillis());
  assertFalse(hotKeyLogger.isThrottled());
  assertTrue(hotKeyLogger.isThrottled());

  // The class throttles every 5 minutes, so the first time it is called is true. The second time
  // is throttled and returns false.
  clock.setTime(clock.currentTimeMillis() + Duration.standardMinutes(5L).getMillis());
  assertFalse(hotKeyLogger.isThrottled());
  assertTrue(hotKeyLogger.isThrottled());

  // Test that the state variable is set and can log again in 5 minutes.
  clock.setTime(clock.currentTimeMillis() + Duration.standardMinutes(5L).getMillis());
  assertFalse(hotKeyLogger.isThrottled());
  assertTrue(hotKeyLogger.isThrottled());
}
 
Example #7
Source File: CredentialFromAccessTokenProviderClassFactory.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
/** Creates a {@link Credential} based on information from the access token provider. */
private static Credential getCredentialFromAccessTokenProvider(
    AccessTokenProvider accessTokenProvider, Collection<String> scopes)
    throws IOException, GeneralSecurityException {
  Preconditions.checkArgument(
      accessTokenProvider.getAccessToken() != null, "Access Token cannot be null!");
  GoogleCredential credential =
      GoogleCredentialWithAccessTokenProvider.fromAccessTokenProvider(
          Clock.SYSTEM, accessTokenProvider);
  return credential.createScoped(scopes);
}
 
Example #8
Source File: GoogleIdTokenVerifierTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testBuilder() throws Exception {
  GoogleIdTokenVerifier.Builder builder = new GoogleIdTokenVerifier.Builder(
      new GooglePublicKeysManagerTest.PublicCertsMockHttpTransport(), new JacksonFactory()).setIssuer(
      ISSUER).setAudience(TRUSTED_CLIENT_IDS);
  assertEquals(Clock.SYSTEM, builder.getClock());
  assertEquals(ISSUER, builder.getIssuer());
  assertTrue(TRUSTED_CLIENT_IDS.equals(builder.getAudience()));
  Clock clock = new FixedClock(4);
  builder.setClock(clock);
  assertEquals(clock, builder.getClock());
  IdTokenVerifier verifier = builder.build();
  assertEquals(clock, verifier.getClock());
  assertEquals(ISSUER, verifier.getIssuer());
  assertEquals(TRUSTED_CLIENT_IDS, Lists.newArrayList(verifier.getAudience()));
}
 
Example #9
Source File: WorkProgressUpdater.java    From beam with Apache License 2.0 5 votes vote down vote up
/**
 * @param checkpointPeriodSec the desired amount of time in seconds between periodic checkpoints;
 *     if no periodic checkpoints are desired then pass {@link Integer#MAX_VALUE}
 */
public WorkProgressUpdater(WorkExecutor worker, int checkpointPeriodSec) {
  this(
      worker,
      checkpointPeriodSec,
      Executors.newSingleThreadScheduledExecutor(
          new ThreadFactoryBuilder()
              .setDaemon(true)
              .setNameFormat("WorkProgressUpdater-%d")
              .build()),
      Clock.SYSTEM);
}
 
Example #10
Source File: WorkProgressUpdater.java    From beam with Apache License 2.0 5 votes vote down vote up
/**
 * @param checkpointPeriodSec the desired amount of time in seconds between periodic checkpoints;
 *     if no periodic checkpoints are desired then pass {@link Integer#MAX_VALUE}
 * @param executor the desired executor, can be used to inject a executor for testing
 * @param clock the desired clock, can be used to inject a mock clock for testing
 */
@VisibleForTesting
protected WorkProgressUpdater(
    WorkExecutor worker,
    int checkpointPeriodSec,
    ScheduledExecutorService executor,
    Clock clock) {
  this.worker = worker;
  this.checkpointPeriodSec = checkpointPeriodSec;
  this.executor = executor;
  this.clock = clock;
}
 
Example #11
Source File: CredentialFromAccessTokenProviderClassFactory.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
static GoogleCredential fromAccessTokenProvider(
    Clock clock, AccessTokenProvider accessTokenProvider) {
  GoogleCredentialWithAccessTokenProvider withProvider =
      new GoogleCredentialWithAccessTokenProvider(clock, accessTokenProvider);
  AccessToken accessToken =
      Preconditions.checkNotNull(
          accessTokenProvider.getAccessToken(), "Access Token cannot be null!");

  withProvider
      .setAccessToken(accessToken.getToken())
      .setExpirationTimeMilliseconds(accessToken.getExpirationTimeMilliSeconds());
  // TODO: This should be setting the refresh token as well.
  return withProvider;
}
 
Example #12
Source File: DataflowWorkProgressUpdater.java    From beam with Apache License 2.0 5 votes vote down vote up
/**
 * The {@link ScheduledExecutorService} parameter is used to inject a stubbed executor that uses
 * virtual time for testing, and the {@link Clock} parameter is used to inject a mock clock that
 * provides virtual time.
 */
@VisibleForTesting
DataflowWorkProgressUpdater(
    WorkItemStatusClient workItemStatusClient,
    WorkItem workItem,
    WorkExecutor worker,
    ScheduledExecutorService executor,
    Clock clock,
    HotKeyLogger hotKeyLogger) {
  super(worker, Integer.MAX_VALUE, executor, clock);
  this.workItemStatusClient = workItemStatusClient;
  this.workItem = workItem;
  this.hotKeyLogger = hotKeyLogger;
}
 
Example #13
Source File: GoogleCredentialWithIamAccessToken.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
public GoogleCredentialWithIamAccessToken(
    HttpTransport transport,
    HttpRequestInitializer initializer,
    String serviceAccountName,
    ImmutableList<String> scopes)
    throws IOException {
  this(transport, initializer, serviceAccountName, scopes, Clock.SYSTEM);
}
 
Example #14
Source File: GoogleCredentialWithIamAccessToken.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public GoogleCredentialWithIamAccessToken(
    HttpTransport transport,
    HttpRequestInitializer initializer,
    String serviceAccountName,
    ImmutableList<String> scopes,
    Clock clock)
    throws IOException {
  this.serviceAccountResource = DEFAULT_SERVICE_ACCOUNT_NAME_PREFIX + serviceAccountName;
  this.initializer = initializer;
  this.transport = transport;
  this.scopes = scopes;
  this.clock = clock;
  initialize();
}
 
Example #15
Source File: LaggedGoogleCloudStorage.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isObjectVisible(Clock clock, GoogleCloudStorageItemInfo itemInfo) {
  long currentTime = clock.currentTimeMillis();
  // In order to avoid non-determinism in tests, we'll use the object name's hashcode mod
  // MAX_LIST_LAG_MS to generate a per-object delta between 0 and MAX_LIST_LAG_MS.
  long objectLag = Math.abs(
      itemInfo.getObjectName().hashCode() % DEFAULT_MAX_LIST_LAG_MS);
  return currentTime > itemInfo.getCreationTime() + objectLag;
}
 
Example #16
Source File: LaggedGoogleCloudStorage.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
public LaggedGoogleCloudStorage(
    final GoogleCloudStorage delegate,
    final Clock clock,
    final ListVisibilityCalculator listVisibilityCalculator) {
  this.delegate = delegate;
  this.clock = clock;
  this.listVisibilityCalculator = listVisibilityCalculator;
}
 
Example #17
Source File: GoogleCloudStorageTest.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
@Parameters
public static Collection<Object[]> getConstructorArguments() throws IOException {
  GoogleCloudStorage gcs = new InMemoryGoogleCloudStorage();
  GoogleCloudStorage zeroLaggedGcs =
      new LaggedGoogleCloudStorage(
          new InMemoryGoogleCloudStorage(),
          Clock.SYSTEM,
          ListVisibilityCalculator.IMMEDIATELY_VISIBLE);
  GoogleCloudStorage performanceCachingGcs =
      new PerformanceCachingGoogleCloudStorage(
          new InMemoryGoogleCloudStorage(), PerformanceCachingGoogleCloudStorageOptions.DEFAULT);
  return Arrays.asList(
      new Object[] {gcs}, new Object[] {zeroLaggedGcs}, new Object[] {performanceCachingGcs});
}
 
Example #18
Source File: FirebaseTokenUtils.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
static FirebaseTokenFactory createTokenFactory(FirebaseApp firebaseApp, Clock clock) {
  try {
    return new FirebaseTokenFactory(
        firebaseApp.getOptions().getJsonFactory(),
        clock,
        CryptoSigners.getCryptoSigner(firebaseApp));
  } catch (IOException e) {
    throw new IllegalStateException(
        "Failed to initialize FirebaseTokenFactory. Make sure to initialize the SDK "
            + "with service account credentials or specify a service account "
            + "ID with iam.serviceAccounts.signBlob permission. Please refer to "
            + "https://firebase.google.com/docs/auth/admin/create-custom-tokens for more "
            + "details on creating custom tokens.", e);
  }
}
 
Example #19
Source File: FirebaseTokenUtils.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private static GooglePublicKeysManager newPublicKeysManager(
    FirebaseOptions options, Clock clock, String certUrl) {
  return new GooglePublicKeysManager.Builder(
      options.getHttpTransport(), UNQUOTED_CTRL_CHAR_JSON_FACTORY)
      .setClock(clock)
      .setPublicCertsEncodedUrl(certUrl)
      .build();
}
 
Example #20
Source File: FirebaseTokenUtils.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private static IdTokenVerifier newIdTokenVerifier(
    Clock clock, String issuerPrefix, String projectId) {
  return new IdTokenVerifier.Builder()
      .setClock(clock)
      .setAudience(ImmutableList.of(projectId))
      .setIssuer(issuerPrefix + projectId)
      .build();
}
 
Example #21
Source File: GCalGoogleOAuth.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
private static Credential newCredential(String userId, DataStore<StoredCredential> credentialDataStore) {

        Credential.Builder builder = new Credential.Builder(BearerToken.authorizationHeaderAccessMethod())
                .setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY)
                .setTokenServerEncodedUrl("https://accounts.google.com/o/oauth2/token")
                .setClientAuthentication(new ClientParametersAuthentication(client_id, client_secret))
                .setRequestInitializer(null).setClock(Clock.SYSTEM);

        builder.addRefreshListener(new DataStoreCredentialRefreshListener(userId, credentialDataStore));

        return builder.build();
    }
 
Example #22
Source File: RetryUnsuccessfulResponseHandlerTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testRetryAfterGivenAsDate() throws IOException {
  SimpleDateFormat dateFormat =
          new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
  dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
  Date date = new Date(1000);
  Clock clock = new FixedClock(date.getTime());
  String retryAfter = dateFormat.format(new Date(date.getTime() + 30000));

  MultipleCallSleeper sleeper = new MultipleCallSleeper();
  RetryUnsuccessfulResponseHandler handler = new RetryUnsuccessfulResponseHandler(
      testRetryConfig(sleeper), clock);
  CountingLowLevelHttpRequest failingRequest = CountingLowLevelHttpRequest.fromStatus(
      503, ImmutableMap.of("retry-after", retryAfter));
  HttpRequest request = TestUtils.createRequest(failingRequest);
  request.setUnsuccessfulResponseHandler(handler);
  request.setNumberOfRetries(4);

  try {
    request.execute();
    fail("No exception thrown for HTTP error");
  } catch (HttpResponseException e) {
    assertEquals(503, e.getStatusCode());
  }

  assertEquals(4, sleeper.getCount());
  assertArrayEquals(new long[]{30000, 30000, 30000, 30000}, sleeper.getDelays());
  assertEquals(5, failingRequest.getCount());
}
 
Example #23
Source File: PubsubIO.java    From beam with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
/**
 * Set's the internal Clock.
 *
 * <p>Only for use by unit tests.
 */
Read<T> withClock(Clock clock) {
  return toBuilder().setClock(clock).build();
}
 
Example #24
Source File: FirebaseAuth.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private static FirebaseAuth fromApp(final FirebaseApp app) {
  return FirebaseAuth.builder()
      .setFirebaseApp(app)
      .setTokenFactory(new Supplier<FirebaseTokenFactory>() {
        @Override
        public FirebaseTokenFactory get() {
          return FirebaseTokenUtils.createTokenFactory(app, Clock.SYSTEM);
        }
      })
      .setIdTokenVerifier(new Supplier<FirebaseTokenVerifier>() {
        @Override
        public FirebaseTokenVerifier get() {
          return FirebaseTokenUtils.createIdTokenVerifier(app, Clock.SYSTEM);
        }
      })
      .setCookieVerifier(new Supplier<FirebaseTokenVerifier>() {
        @Override
        public FirebaseTokenVerifier get() {
          return FirebaseTokenUtils.createSessionCookieVerifier(app, Clock.SYSTEM);
        }
      })
      .setUserManager(new Supplier<FirebaseUserManager>() {
        @Override
        public FirebaseUserManager get() {
          return new FirebaseUserManager(app);
        }
      })
      .build();
}
 
Example #25
Source File: FirebaseTokenFactory.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
public FirebaseTokenFactory(JsonFactory jsonFactory, Clock clock, CryptoSigner signer) {
  this.jsonFactory = checkNotNull(jsonFactory);
  this.clock = checkNotNull(clock);
  this.signer = checkNotNull(signer);
}
 
Example #26
Source File: GoogleCloudStorageFileSystemOptionsUnitTest.java    From hadoop-connectors with Apache License 2.0 4 votes vote down vote up
public GoogleCloudStorage createGcs(GoogleCloudStorageOptions options) {
  return new LaggedGoogleCloudStorage(
      new InMemoryGoogleCloudStorage(options),
      Clock.SYSTEM,
      ListVisibilityCalculator.IMMEDIATELY_VISIBLE);
}
 
Example #27
Source File: ComputeCredential.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
@Override
public Builder setClock(Clock clock) {
  return (Builder) super.setClock(clock);
}
 
Example #28
Source File: GoogleAuthorizationCodeFlow.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
/**
 * @since 1.11
 */
@Override
public Builder setClock(Clock clock) {
  return (Builder) super.setClock(clock);
}
 
Example #29
Source File: GooglePublicKeysManager.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
/** Returns the clock. */
public final Clock getClock() {
  return clock;
}
 
Example #30
Source File: GooglePublicKeysManager.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
/** Returns the clock. */
public final Clock getClock() {
  return clock;
}