本文整理了Java中org.keycloak.common.util.Time
类的一些代码示例,展示了Time
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Time
类的具体详情如下:
包路径:org.keycloak.common.util.Time
类名称:Time
暂无
代码示例来源:origin: org.uberfire/uberfire-security-management-keycloak
private boolean tokenExpired() {
return accessTokenResponse != null && (Time.currentTime() + minTokenValidity) >= expirationTime;
}
}
代码示例来源:origin: org.keycloak/keycloak-adapter-core
CacheEntry(String key, PathConfig value, long maxAge) {
this.key = key;
this.value = value;
if(maxAge == -1) {
expiration = -1;
} else {
expiration = Time.currentTimeMillis() + maxAge;
}
}
代码示例来源:origin: org.keycloak/keycloak-model-jpa
@Override
public void waitForLock() {
boolean locked = false;
long startTime = Time.toMillis(Time.currentTime());
long timeToGiveUp = startTime + (getChangeLogLockWaitTime());
boolean nextAttempt = true;
while (nextAttempt) {
locked = acquireLock();
if (!locked) {
int remainingTime = ((int)(timeToGiveUp / 1000)) - Time.currentTime();
if (remainingTime > 0) {
log.debugf("Will try to acquire log another time. Remaining time: %d seconds", remainingTime);
} else {
nextAttempt = false;
}
} else {
nextAttempt = false;
}
}
if (!locked) {
int timeout = ((int)(getChangeLogLockWaitTime() / 1000));
throw new IllegalStateException("Could not acquire change log lock within specified timeout " + timeout + " seconds. Currently locked by other transaction");
}
}
代码示例来源:origin: org.keycloak.testsuite/integration-arquillian-testsuite-providers
@GET
@Path("/time-offset")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, String> getTimeOffset() {
Map<String, String> response = new HashMap<>();
response.put("currentTime", String.valueOf(Time.currentTime()));
response.put("offset", String.valueOf(Time.getOffset()));
return response;
}
代码示例来源:origin: org.keycloak/keycloak-model-sessions-infinispan
private void removeExpiredClientInitialAccess(RealmModel realm) {
Iterator<String> itr = sessionCache.entrySet().stream().filter(ClientInitialAccessPredicate.create(realm.getId()).expired(Time.currentTime())).map(Mappers.sessionId()).iterator();
while (itr.hasNext()) {
tx.remove(sessionCache, itr.next());
}
}
代码示例来源:origin: org.keycloak/keycloak-model-sessions-infinispan
@Override
public void removeExpired(RealmModel realm) {
UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
if (s.getRealm().equals(realm.getId()) && (s.getLastSessionRefresh() < Time.currentTime() - realm.getSsoSessionIdleTimeout() || s.getStarted() < Time.currentTime() - realm.getSsoSessionMaxLifespan())) {
itr.remove();
int expired = Time.currentTime() - RealmInfoUtil.getDettachedClientSessionLifespan(realm);
Iterator<ClientSessionEntity> citr = clientSessions.values().iterator();
while (citr.hasNext()) {
while (itr.hasNext()) {
UserSessionEntity s = itr.next();
if (s.getRealm().equals(realm.getId()) && (s.getLastSessionRefresh() < Time.currentTime() - realm.getOfflineSessionIdleTimeout())) {
itr.remove();
remove(s, true);
while (citr.hasNext()) {
ClientSessionEntity s = citr.next();
if (s.getRealmId().equals(realm.getId()) && (s.getTimestamp() < Time.currentTime() - realm.getOfflineSessionIdleTimeout())) {
citr.remove();
while (iaitr.hasNext()) {
ClientInitialAccessEntity e = iaitr.next();
if (e.getRealmId().equals(realm.getId()) && (e.getExpires() < Time.currentTime())) {
iaitr.remove();
代码示例来源:origin: org.keycloak/keycloak-model-sessions-infinispan
private void removeExpiredOfflineClientSessions(RealmModel realm) {
UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
int expiredOffline = Time.currentTime() - realm.getOfflineSessionIdleTimeout();
Iterator<String> itr = offlineSessionCache.entrySet().stream().filter(ClientSessionPredicate.create(realm.getId()).expiredRefresh(expiredOffline)).map(Mappers.sessionId()).iterator();
while (itr.hasNext()) {
String sessionId = itr.next();
tx.remove(offlineSessionCache, sessionId);
persister.removeClientSession(sessionId, true);
}
}
代码示例来源:origin: org.keycloak/keycloak-model-jpa
@Override
public void removeExpired(RealmModel realm) {
int expiredOffline = Time.currentTime() - realm.getOfflineSessionIdleTimeout() - SessionTimeoutHelper.PERIODIC_CLEANER_IDLE_TIMEOUT_WINDOW_SECONDS;
String offlineStr = offlineToString(true);
logger.tracef("Trigger removing expired user sessions for realm '%s'", realm.getName());
int cs = em.createNamedQuery("deleteExpiredClientSessions")
.setParameter("realmId", realm.getId())
.setParameter("lastSessionRefresh", expiredOffline)
.setParameter("offline", offlineStr)
.executeUpdate();
int us = em.createNamedQuery("deleteExpiredUserSessions")
.setParameter("realmId", realm.getId())
.setParameter("lastSessionRefresh", expiredOffline)
.setParameter("offline", offlineStr)
.executeUpdate();
logger.debugf("Removed %d expired user sessions and %d expired client sessions in realm '%s'", us, cs, realm.getName());
}
代码示例来源:origin: org.keycloak/keycloak-model-infinispan
private void removeExpiredUserSessions(RealmModel realm) {
int expired = Time.currentTime() - realm.getSsoSessionMaxLifespan();
int expiredRefresh = Time.currentTime() - realm.getSsoSessionIdleTimeout() - SessionTimeoutHelper.PERIODIC_CLEANER_IDLE_TIMEOUT_WINDOW_SECONDS;
int expiredRememberMe = Time.currentTime() - (realm.getSsoSessionMaxLifespanRememberMe() > 0 ? realm.getSsoSessionMaxLifespanRememberMe() : realm.getSsoSessionMaxLifespan());
int expiredRefreshRememberMe = Time.currentTime() - (realm.getSsoSessionIdleTimeoutRememberMe() > 0 ? realm.getSsoSessionIdleTimeoutRememberMe() : realm.getSsoSessionIdleTimeout()) -
SessionTimeoutHelper.PERIODIC_CLEANER_IDLE_TIMEOUT_WINDOW_SECONDS;
代码示例来源:origin: org.keycloak/keycloak-model-infinispan
protected void sendMessage(KeycloakSession kcSession, Map<String, SessionData> refreshesToSend) {
Map<String, Set<String>> sessionIdsByRealm =
refreshesToSend.entrySet().stream().collect(
Collectors.groupingBy(entry -> entry.getValue().getRealmId(),
Collectors.mapping(Map.Entry::getKey, Collectors.toSet())));
// Update DB with a bit lower value than current time to ensure 'revokeRefreshToken' will work correctly taking server
int lastSessionRefresh = Time.currentTime() - SessionTimeoutHelper.PERIODIC_TASK_INTERVAL_SECONDS;
if (logger.isDebugEnabled()) {
logger.debugf("Updating %d userSessions with lastSessionRefresh: %d", refreshesToSend.size(), lastSessionRefresh);
}
UserSessionPersisterProvider persister = kcSession.getProvider(UserSessionPersisterProvider.class);
for (Map.Entry<String, Set<String>> entry : sessionIdsByRealm.entrySet()) {
RealmModel realm = kcSession.realms().getRealm(entry.getKey());
// Case when realm was deleted in the meantime. UserSessions were already deleted as well (callback for realm deletion)
if (realm == null) {
continue;
}
Set<String> userSessionIds = entry.getValue();
persister.updateLastSessionRefreshes(realm, lastSessionRefresh, userSessionIds, offline);
}
}
}
代码示例来源:origin: org.keycloak/keycloak-model-sessions-infinispan
private void removeExpiredUserSessions(RealmModel realm) {
int expired = Time.currentTime() - realm.getSsoSessionMaxLifespan();
int expiredRefresh = Time.currentTime() - realm.getSsoSessionIdleTimeout();
Iterator<Map.Entry<String, SessionEntity>> itr = sessionCache.entrySet().stream().filter(UserSessionPredicate.create(realm.getId()).expired(expired, expiredRefresh)).iterator();
while (itr.hasNext()) {
UserSessionEntity entity = (UserSessionEntity) itr.next().getValue();
tx.remove(sessionCache, entity.getId());
if (entity.getClientSessions() != null) {
for (String clientSessionId : entity.getClientSessions()) {
tx.remove(sessionCache, clientSessionId);
}
}
}
}
代码示例来源:origin: org.keycloak/keycloak-model-infinispan
@Override
public void removeExpired(RealmModel realm) {
log.debugf("Removing expired sessions");
int expired = Time.currentTime() - RealmInfoUtil.getDettachedClientSessionLifespan(realm);
// Each cluster node cleanups just local sessions, which are those owned by himself (+ few more taking l1 cache into account)
Iterator<Map.Entry<String, RootAuthenticationSessionEntity>> itr = CacheDecorators.localCache(cache)
.entrySet()
.stream()
.filter(RootAuthenticationSessionPredicate.create(realm.getId()).expired(expired))
.iterator();
int counter = 0;
while (itr.hasNext()) {
counter++;
RootAuthenticationSessionEntity entity = itr.next().getValue();
tx.remove(cache, entity.getId());
}
log.debugf("Removed %d expired authentication sessions for realm '%s'", counter, realm.getName());
}
代码示例来源:origin: org.keycloak/keycloak-model-infinispan
protected void setupPeriodicTimer(KeycloakSession kcSession, AbstractLastSessionRefreshStore store, long timerIntervalMs, String eventKey) {
TimerProvider timer = kcSession.getProvider(TimerProvider.class);
timer.scheduleTask((KeycloakSession keycloakSession) -> {
store.checkSendingMessage(keycloakSession, Time.currentTime());
}, timerIntervalMs, eventKey);
}
}
代码示例来源:origin: org.keycloak/keycloak-model-infinispan
@Override
public OfflinePersistentWorkerResult loadSessions(KeycloakSession session, OfflinePersistentLoaderContext loaderContext, OfflinePersistentWorkerContext ctx) {
int first = ctx.getWorkerId() * sessionsPerSegment;
log.tracef("Loading sessions for segment: %d", ctx.getSegment());
UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
List<UserSessionModel> sessions = persister.loadUserSessions(first, sessionsPerSegment, true, ctx.getLastCreatedOn(), ctx.getLastSessionId());
log.tracef("Sessions loaded from DB - segment: %d", ctx.getSegment());
UserSessionModel lastSession = null;
if (!sessions.isEmpty()) {
lastSession = sessions.get(sessions.size() - 1);
// Save to memory/infinispan
session.sessions().importUserSessions(sessions, true);
}
int lastCreatedOn = lastSession==null ? Time.currentTime() + 100000 : lastSession.getStarted();
String lastSessionId = lastSession==null ? FIRST_SESSION_ID : lastSession.getId();
log.tracef("Sessions imported to infinispan - segment: %d, lastCreatedOn: %d, lastSessionId: %s", ctx.getSegment(), lastCreatedOn, lastSessionId);
return new OfflinePersistentWorkerResult(true, ctx.getSegment(), ctx.getWorkerId(), lastCreatedOn, lastSessionId);
}
代码示例来源:origin: org.keycloak/keycloak-model-api
public static boolean validPasswordToken(RealmModel realm, UserModel user, String encodedPasswordToken) {
try {
JWSInput jws = new JWSInput(encodedPasswordToken);
if (!RSAProvider.verify(jws, realm.getPublicKey())) {
return false;
}
PasswordToken passwordToken = jws.readJsonContent(PasswordToken.class);
if (!passwordToken.getRealm().equals(realm.getName())) {
return false;
}
if (!passwordToken.getUser().equals(user.getId())) {
return false;
}
if (Time.currentTime() - passwordToken.getTimestamp() > realm.getAccessCodeLifespanUserAction()) {
return false;
}
return true;
} catch (JWSInputException e) {
return false;
}
}
代码示例来源:origin: adorsys/xs2a
client = create(oidcContext);
ClientModel clientModel = session.getContext().getRealm().getClientByClientId(client.getClientId());
updatePairwiseSubMappers(clientModel, SubjectType.parse(clientOIDC.getSubjectType()),
clientOIDC.getSectorIdentifierUri());
updateClientRepWithProtocolMappers(clientModel, client);
URI uri = session.getContext().getUri().getAbsolutePathBuilder().path(client.getClientId()).build();
OIDCClientRepresentationExtended clientOIDCResponse = DescriptionConverterExt.toExternalResponse(session, client, uri);
clientOIDCResponse.setClientIdIssuedAt(Time.currentTime());
return Response.created(uri).entity(clientOIDCResponse).build();
} catch (ClientRegistrationException cre) {
代码示例来源:origin: org.keycloak/keycloak-events-api
private void send() {
event.setTime(Time.toMillis(Time.currentTime()));
if (store != null) {
if (realm.getEnabledEventTypes() != null && !realm.getEnabledEventTypes().isEmpty() ? realm.getEnabledEventTypes().contains(event.getType().name()) : event.getType().isSaveByDefault()) {
try {
store.onEvent(event);
} catch (Throwable t) {
log.error("Failed to save event", t);
}
}
}
if (listeners != null) {
for (EventListenerProvider l : listeners) {
try {
l.onEvent(event);
} catch (Throwable t) {
log.error("Failed to send type to " + l, t);
}
}
}
}
代码示例来源:origin: org.keycloak/keycloak-model-mongo
@Override
public void waitForLock() {
boolean locked = false;
long startTime = Time.toMillis(Time.currentTime());
long timeToGiveUp = startTime + (factory.getLockWaitTimeoutMillis());
while (!locked && Time.toMillis(Time.currentTime()) < timeToGiveUp) {
locked = acquireLock();
if (!locked) {
int remainingTime = ((int)(timeToGiveUp / 1000)) - Time.currentTime();
logger.debugf("Waiting for changelog lock... Remaining time: %d seconds", remainingTime);
try {
Thread.sleep(factory.getLockRecheckTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
if (!locked) {
DBObject query = new BasicDBObject("_id", 1);
DBCursor cursor = db.getCollection(DB_LOCK_COLLECTION).find(query);
String lockedBy;
if (cursor.hasNext()) {
DBObject dbObj = cursor.next();
lockedBy = dbObj.get("lockedBy") + " since " + Time.toDate(((int)((long) dbObj.get("lockedSince") / 1000)));
} else {
lockedBy = "UNKNOWN";
}
throw new IllegalStateException("Could not acquire change log lock. Currently locked by " + lockedBy);
}
}
代码示例来源:origin: Doccrazy/keycloak-protocol-cas
@Override
public Response authenticated(AuthenticationSessionModel authSession, UserSessionModel userSession, ClientSessionContext clientSessionCtx) {
AuthenticatedClientSessionModel clientSession = clientSessionCtx.getClientSession();
String service = authSession.getRedirectUri();
//TODO validate service
OAuth2Code codeData = new OAuth2Code(UUID.randomUUID(),
Time.currentTime() + userSession.getRealm().getAccessCodeLifespan(),
null, null, authSession.getRedirectUri(), null, null);
String code = OAuth2CodeParser.persistCode(session, clientSession, codeData);
KeycloakUriBuilder uriBuilder = KeycloakUriBuilder.fromUri(service);
uriBuilder.queryParam(TICKET_RESPONSE_PARAM, SERVICE_TICKET_PREFIX + code);
URI redirectUri = uriBuilder.build();
Response.ResponseBuilder location = Response.status(302).location(redirectUri);
return location.build();
}
代码示例来源:origin: org.keycloak/keycloak-model-jpa
@Override
public void addConsent(RealmModel realm, String userId, UserConsentModel consent) {
createIndex(realm, userId);
String clientId = consent.getClient().getId();
FederatedUserConsentEntity consentEntity = getGrantedConsentEntity(userId, clientId);
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);
}
内容来源于网络,如有侵权,请联系作者删除!