Java Code Examples for org.keycloak.common.util.Time#currentTimeMillis()

The following examples show how to use org.keycloak.common.util.Time#currentTimeMillis() . 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: CacheableStorageProviderModel.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public long getLifespan() {
    UserStorageProviderModel.CachePolicy policy = getCachePolicy();
    long lifespan = -1;
    if (policy == null || policy == UserStorageProviderModel.CachePolicy.DEFAULT) {
        lifespan = -1;
    } else if (policy == CacheableStorageProviderModel.CachePolicy.EVICT_DAILY) {
        if (getEvictionHour() > -1 && getEvictionMinute() > -1) {
            lifespan = dailyTimeout(getEvictionHour(), getEvictionMinute()) - Time.currentTimeMillis();
        }
    } else if (policy == CacheableStorageProviderModel.CachePolicy.EVICT_WEEKLY) {
        if (getEvictionDay() > 0 && getEvictionHour() > -1 && getEvictionMinute() > -1) {
            lifespan = weeklyTimeout(getEvictionDay(), getEvictionHour(), getEvictionMinute()) - Time.currentTimeMillis();
        }
    } else if (policy == CacheableStorageProviderModel.CachePolicy.MAX_LIFESPAN) {
        lifespan = getMaxLifespan();
    }
    return lifespan;
}
 
Example 2
Source File: DefaultBruteForceProtector.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isTemporarilyDisabled(KeycloakSession session, RealmModel realm, UserModel user) {
    UserLoginFailureModel failure = session.sessions().getUserLoginFailure(realm, user.getId());

    if (failure != null) {
        int currTime = (int) (Time.currentTimeMillis() / 1000);
        int failedLoginNotBefore = failure.getFailedLoginNotBefore();
        if (currTime < failedLoginNotBefore) {
            logger.debugv("Current: {0} notBefore: {1}", currTime, failedLoginNotBefore);
            return true;
        }
    }


    return false;
}
 
Example 3
Source File: ClientListenerExecutorDecorator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void submitImpl(K key, MyClientEvent event, Runnable r) {
    logger.debugf("Submitting event to the executor: %s . eventsInProgress size: %d, eventsQueue size: %d", event.toString(), eventsInProgress.size(), eventsQueue.size());

    eventsInProgress.put(key, event);

    Runnable decoratedRunnable = () -> {
        Long start = null;
        try {
            if (logger.isDebugEnabled()) {
                start = Time.currentTimeMillis();
            }

            r.run();
        } finally {
            synchronized (lock) {
                eventsInProgress.remove(key);

                if (logger.isDebugEnabled()) {
                    long took = Time.currentTimeMillis() - start;
                    logger.debugf("Finished processing event by the executor: %s, took: %d ms. EventsInProgress size: %d", event.toString(), took, eventsInProgress.size());
                }

                pollQueue(key);
            }
        }
    };

    try {
        decorated.submit(decoratedRunnable);
    } catch (RejectedExecutionException ree) {
        eventsInProgress.remove(key);

        logger.errorf("Rejected execution of task for the event '%s' . Try to increase the pool size. Pool is '%s'", event.toString(), decorated.toString());
        throw ree;
    }
}
 
Example 4
Source File: JpaUserProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void addConsent(RealmModel realm, String userId, UserConsentModel consent) {
    String clientId = consent.getClient().getId();

    UserConsentEntity consentEntity = getGrantedConsentEntity(userId, clientId, LockModeType.NONE);
    if (consentEntity != null) {
        throw new ModelDuplicateException("Consent already exists for client [" + clientId + "] and user [" + userId + "]");
    }

    long currentTime = Time.currentTimeMillis();

    consentEntity = new UserConsentEntity();
    consentEntity.setId(KeycloakModelUtils.generateId());
    consentEntity.setUser(em.getReference(UserEntity.class, userId));
    StorageId clientStorageId = new StorageId(clientId);
    if (clientStorageId.isLocal()) {
        consentEntity.setClientId(clientId);
    } else {
        consentEntity.setClientStorageProvider(clientStorageId.getProviderId());
        consentEntity.setExternalClientId(clientStorageId.getExternalId());
    }

    consentEntity.setCreatedDate(currentTime);
    consentEntity.setLastUpdatedDate(currentTime);
    em.persist(consentEntity);
    em.flush();

    updateGrantedConsentEntity(consentEntity, consent);
}
 
Example 5
Source File: JpaUserFederatedStorageProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void addConsent(RealmModel realm, String userId, UserConsentModel consent) {
    createIndex(realm, userId);
    String clientId = consent.getClient().getId();

    FederatedUserConsentEntity consentEntity = getGrantedConsentEntity(userId, clientId, LockModeType.NONE);
    if (consentEntity != null) {
        throw new ModelDuplicateException("Consent already exists for client [" + clientId + "] and user [" + userId + "]");
    }

    consentEntity = new FederatedUserConsentEntity();
    consentEntity.setId(KeycloakModelUtils.generateId());
    consentEntity.setUserId(userId);
    StorageId clientStorageId = new StorageId(clientId);
    if (clientStorageId.isLocal()) {
        consentEntity.setClientId(clientId);
    } else {
        consentEntity.setClientStorageProvider(clientStorageId.getProviderId());
        consentEntity.setExternalClientId(clientStorageId.getExternalId());
    }
    consentEntity.setRealmId(realm.getId());
    consentEntity.setStorageProviderId(new StorageId(userId).getProviderId());
    long currentTime = Time.currentTimeMillis();
    consentEntity.setCreatedDate(currentTime);
    consentEntity.setLastUpdatedDate(currentTime);
    em.persist(consentEntity);
    em.flush();

    updateGrantedConsentEntity(consentEntity, consent);

}
 
Example 6
Source File: CacheableStorageProviderModel.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public boolean shouldInvalidate(CachedObject cached) {
    boolean invalidate = false;
    if (!isEnabled()) {
        invalidate = true;
    } else {
        CacheableStorageProviderModel.CachePolicy policy = getCachePolicy();
        if (policy != null) {
            //String currentTime = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date(Time.currentTimeMillis()));
            if (policy == CacheableStorageProviderModel.CachePolicy.NO_CACHE) {
                invalidate = true;
            } else if (cached.getCacheTimestamp() < getCacheInvalidBefore()) {
                invalidate = true;
            } else if (policy == CacheableStorageProviderModel.CachePolicy.MAX_LIFESPAN) {
                if (cached.getCacheTimestamp() + getMaxLifespan() < Time.currentTimeMillis()) {
                    invalidate = true;
                }
            } else if (policy == CacheableStorageProviderModel.CachePolicy.EVICT_DAILY) {
                long dailyBoundary = dailyEvictionBoundary(getEvictionHour(), getEvictionMinute());
                if (cached.getCacheTimestamp() <= dailyBoundary) {
                    invalidate = true;
                }
            } else if (policy == CacheableStorageProviderModel.CachePolicy.EVICT_WEEKLY) {
                int oneWeek = 7 * 24 * 60 * 60 * 1000;
                long weeklyTimeout = weeklyTimeout(getEvictionDay(), getEvictionHour(), getEvictionMinute());
                long lastTimeout = weeklyTimeout - oneWeek;
                //String timeout = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date(weeklyTimeout));
                //String stamp = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date(cached.getCacheTimestamp()));
                if (cached.getCacheTimestamp() <= lastTimeout) {
                    invalidate = true;
                }
            }
        }
    }
    return invalidate;
}
 
Example 7
Source File: CacheableStorageProviderModel.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static long dailyEvictionBoundary(int hour, int minute) {
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(Time.currentTimeMillis());
    cal.set(Calendar.HOUR_OF_DAY, hour);
    cal.set(Calendar.MINUTE, minute);
    if (cal.getTimeInMillis() > Time.currentTimeMillis()) {
        // if daily evict for today hasn't happened yet set boundary
        // to yesterday's time of eviction
        cal.add(Calendar.DAY_OF_YEAR, -1);
    }
    return cal.getTimeInMillis();
}
 
Example 8
Source File: DefaultBruteForceProtector.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void logFailure(LoginEvent event) {
    ServicesLogger.LOGGER.loginFailure(event.userId, event.ip);
    failures++;
    long delta = 0;
    if (lastFailure > 0) {
        delta = Time.currentTimeMillis() - lastFailure;
        if (delta > (long)maxDeltaTimeSeconds * 1000L) {
            totalTime = 0;

        } else {
            totalTime += delta;
        }
    }
}
 
Example 9
Source File: PathCache.java    From keycloak with Apache License 2.0 5 votes vote down vote up
CacheEntry(String key, PathConfig value, long maxAge) {
    this.key = key;
    this.value = value;
    if(maxAge == -1) {
        expiration = -1;
    } else {
        expiration = Time.currentTimeMillis() + maxAge;
    }
}
 
Example 10
Source File: LDAPOperationManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private <R> R execute(LdapOperation<R> operation, LdapContext context, LDAPOperationDecorator decorator) throws NamingException {
    if (context == null) {
        throw new IllegalArgumentException("Ldap context cannot be null");
    }

    Long start = null;

    if (perfLogger.isDebugEnabled()) {
        start = Time.currentTimeMillis();
    }

    try {
        if (decorator != null) {
            decorator.beforeLDAPOperation(context, operation);
        }

        return operation.execute(context);
    } finally {
        if (perfLogger.isDebugEnabled()) {
            long took = Time.currentTimeMillis() - start;

            if (took > 100) {
                perfLogger.debugf("\n%s\ntook: %d ms\n", operation.toString(), took);
            } else if (perfLogger.isTraceEnabled()) {
                perfLogger.tracef("\n%s\ntook: %d ms\n", operation.toString(), took);
            }
        }
    }
}
 
Example 11
Source File: PathCache.java    From keycloak with Apache License 2.0 4 votes vote down vote up
boolean isExpired() {
    return expiration != -1 ? Time.currentTimeMillis() > expiration : false;
}