javax.persistence.CacheStoreMode Java Examples

The following examples show how to use javax.persistence.CacheStoreMode. 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: RealmsResource.java    From bouncr with Eclipse Public License 1.0 6 votes vote down vote up
@Decision(HANDLE_OK)
public List<Realm> list(RealmSearchParams params, Application application, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Realm> query = cb.createQuery(Realm.class);
    Root<Realm> realmRoot = query.from(Realm.class);
    query.distinct(true);

    Join<Application, Realm> applicationJoin = realmRoot.join("application");
    List<Predicate> predicates = new ArrayList<>();
    predicates.add(cb.equal(applicationJoin.get("id"), application.getId()));
    Optional.ofNullable(params.getQ())
            .ifPresent(q -> {
                String likeExpr = "%" + q.replaceAll("%", "_%") + "%";
                predicates.add(cb.like(realmRoot.get("name"), likeExpr, '_'));
            });

    query.where(predicates.toArray(Predicate[]::new));
    query.orderBy(cb.asc(realmRoot.get("id")));


    return em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .setFirstResult(params.getOffset())
            .setMaxResults(params.getLimit())
            .getResultList();
}
 
Example #2
Source File: OidcApplicationsResoruce.java    From bouncr with Eclipse Public License 1.0 6 votes vote down vote up
@Decision(HANDLE_OK)
public List<OidcApplication> list(OidcApplicationSearchParams params, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<OidcApplication> query = cb.createQuery(OidcApplication.class);
    Root<OidcApplication> oidcApplicationRoot = query.from(OidcApplication.class);

    List<Predicate> predicates = new ArrayList<>();
    Optional.ofNullable(params.getQ())
            .ifPresent(q -> {
                String likeExpr = "%" + q.replaceAll("%", "_%") + "%";
                predicates.add(cb.like(oidcApplicationRoot.get("name"), likeExpr, '_'));
            });
    if (!predicates.isEmpty()) {
        query.where(predicates.toArray(Predicate[]::new));
    }
    query.orderBy(cb.asc(oidcApplicationRoot.get("id")));
    return em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .setFirstResult(params.getOffset())
            .setMaxResults(params.getLimit())
            .getResultList();
}
 
Example #3
Source File: RolePermissionsResource.java    From bouncr with Eclipse Public License 1.0 6 votes vote down vote up
@Decision(DELETE)
public RolePermissionsRequest delete(RolePermissionsRequest deleteRequest, Role role, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Permission> query = cb.createQuery(Permission.class);
    Root<Permission> permissionRoot = query.from(Permission.class);
    query.where(permissionRoot.get("name").in(deleteRequest));
    List<Permission> permissions = em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .getResultList();

    EntityTransactionManager tx = new EntityTransactionManager(em);

    tx.required(() -> {
        HashSet<Permission> rolePermissions = new HashSet<>(role.getPermissions());
        rolePermissions.removeAll(permissions);
        role.setPermissions(new ArrayList<>(rolePermissions));
    });

    return deleteRequest;
}
 
Example #4
Source File: RolePermissionsResource.java    From bouncr with Eclipse Public License 1.0 6 votes vote down vote up
@Decision(POST)
public RolePermissionsRequest create(RolePermissionsRequest createRequest, Role role, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Permission> query = cb.createQuery(Permission.class);
    Root<Permission> permissionRoot = query.from(Permission.class);
    query.where(permissionRoot.get("name").in(createRequest));
    List<Permission> permissions = em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .getResultList();

    EntityTransactionManager tx = new EntityTransactionManager(em);

    tx.required(() -> {
        HashSet<Permission> rolePermissions = new HashSet<>(role.getPermissions());
        rolePermissions.addAll(permissions);
        role.setPermissions(new ArrayList<>(rolePermissions));
    });

    return createRequest;
}
 
Example #5
Source File: RealmResource.java    From bouncr with Eclipse Public License 1.0 6 votes vote down vote up
@Decision(EXISTS)
public boolean exists(Parameters params, Application application, RestContext context, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Realm> query = cb.createQuery(Realm.class);
    Root<Realm> realmRoot = query.from(Realm.class);
    Join<Application, Realm> applicationJoin = realmRoot.join("application");
    query.where(cb.equal(realmRoot.get("name"), params.get("realmName")),
            cb.equal(applicationJoin.get("id"), application.getId()));

    Realm realm = em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .getResultStream().findAny().orElse(null);
    if (realm != null) {
        context.putValue(realm);
    }
    return realm != null;
}
 
Example #6
Source File: GroupUsersResource.java    From bouncr with Eclipse Public License 1.0 6 votes vote down vote up
@Decision(DELETE)
public GroupUsersRequest delete(GroupUsersRequest createRequest, Group group, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<User> query = cb.createQuery(User.class);
    Root<User> userRoot = query.from(User.class);
    query.where(userRoot.get("account").in(createRequest));
    List<User> users = em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .getResultList();

    EntityTransactionManager tx = new EntityTransactionManager(em);

    tx.required(() -> {
        HashSet<User> groupUsers = new HashSet<>(group.getUsers());
        groupUsers.removeAll(users);
        group.setUsers(new ArrayList<>(groupUsers));
    });

    return createRequest;
}
 
Example #7
Source File: GroupUsersResource.java    From bouncr with Eclipse Public License 1.0 6 votes vote down vote up
@Decision(POST)
public GroupUsersRequest create(GroupUsersRequest createRequest, Group group, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<User> query = cb.createQuery(User.class);
    Root<User> userRoot = query.from(User.class);
    query.where(userRoot.get("account").in(createRequest));
    List<User> users = em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .getResultList();

    EntityTransactionManager tx = new EntityTransactionManager(em);

    tx.required(() -> {
        HashSet<User> groupUsers = new HashSet<>(group.getUsers());
        groupUsers.addAll(users);
        group.setUsers(new ArrayList<>(groupUsers));
    });

    return createRequest;
}
 
Example #8
Source File: UserProfileVerificationResource.java    From bouncr with Eclipse Public License 1.0 6 votes vote down vote up
@Decision(EXISTS)
public boolean exists(Parameters params, RestContext context, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<UserProfileVerification> query = cb.createQuery(UserProfileVerification.class);
    Root<UserProfileVerification> userProfileVerificationRoot = query.from(UserProfileVerification.class);
    query.where(cb.equal(userProfileVerificationRoot.get("code"), params.get("code")));

    return em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .getResultStream()
            .findAny()
            .map(verification -> {
                context.putValue(verification);
                return verification;
            })
            .isPresent();
}
 
Example #9
Source File: SessionImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private CacheMode determineAppropriateLocalCacheMode(Map<String, Object> localProperties) {
	CacheRetrieveMode retrieveMode = null;
	CacheStoreMode storeMode = null;
	if ( localProperties != null ) {
		retrieveMode = determineCacheRetrieveMode( localProperties );
		storeMode = determineCacheStoreMode( localProperties );
	}
	if ( retrieveMode == null ) {
		// use the EM setting
		retrieveMode = determineCacheRetrieveMode( this.properties );
	}
	if ( storeMode == null ) {
		// use the EM setting
		storeMode = determineCacheStoreMode( this.properties );
	}
	return CacheModeHelper.interpretCacheMode( storeMode, retrieveMode );
}
 
Example #10
Source File: UserLockService.java    From bouncr with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Record the event of signing in
 *
 * @param user    the user entity
 */
public void lockUser(User user) {
    if (user != null) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<UserAction> userActionCriteria = cb.createQuery(UserAction.class);
        Root<UserAction> userActionRoot = userActionCriteria.from(UserAction.class);
        userActionCriteria.where(userActionRoot.get("actionType").in(USER_SIGNIN, USER_FAILED_SIGNIN, PASSWORD_CHANGED));
        userActionCriteria.orderBy(cb.desc(userActionRoot.get("createdAt")));

        List<UserAction> recentActions = em.createQuery(userActionCriteria)
                .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
                .setMaxResults(config.getPasswordPolicy().getNumOfTrialsUntilLock())
                .getResultList();
        if (recentActions.size() == config.getPasswordPolicy().getNumOfTrialsUntilLock() &&
                recentActions.stream()
                        .allMatch(action -> action.getActionType() == USER_FAILED_SIGNIN) &&
                user.getUserLock() == null
        ) {
            em.persist(builder(new UserLock())
                    .set(UserLock::setUser, user)
                    .set(UserLock::setLockLevel, LockLevel.LOOSE)
                    .set(UserLock::setLockedAt, LocalDateTime.now())
                    .build());
        }
    }
}
 
Example #11
Source File: PasswordPolicyService.java    From bouncr with Eclipse Public License 1.0 6 votes vote down vote up
public Problem.Violation validateUpdatePassword(PasswordCredentialUpdateRequest updateRequest) {
    if (Objects.equals(updateRequest.getNewPassword(), updateRequest.getOldPassword())) {
        return new Problem.Violation("new_password", "is the same as the old password");
    }

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<PasswordCredential> query = cb.createQuery(PasswordCredential.class);
    Root<PasswordCredential> passwordCredentialRoot = query.from(PasswordCredential.class);
    Join<User, PasswordCredential> userJoin = passwordCredentialRoot.join("user");
    query.where(cb.equal(userJoin.get("account"), updateRequest.getAccount()));
    PasswordCredential passwordCredential = em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .getResultStream().findAny().orElse(null);
    if (passwordCredential == null) {
        return new Problem.Violation("old_password", "does not match current password");
    }

    byte[] currentPassword = passwordCredential.getPassword();
    byte[] oldPassword = PasswordUtils.pbkdf2(updateRequest.getOldPassword(), passwordCredential.getSalt(), 100);
    if (!Arrays.equals(currentPassword, oldPassword)) {
        return new Problem.Violation("old_password", "does not match current password");
    }
    return conformPolicy(updateRequest.getNewPassword());
}
 
Example #12
Source File: RoleResource.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
@Decision(EXISTS)
public boolean exists(Parameters params, RestContext context, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Role> query = cb.createQuery(Role.class);
    Root<Role> roleRoot = query.from(Role.class);
    query.where(cb.equal(roleRoot.get("name"), params.get("name")));

    Role role = em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .getResultStream().findAny().orElse(null);
    if (role != null) {
        context.putValue(role);
    }
    return role != null;
}
 
Example #13
Source File: OidcProvidersResource.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
@Decision(HANDLE_OK)
public List<OidcProvider> list(OidcProviderSearchParams params, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<OidcProvider> query = cb.createQuery(OidcProvider.class);
    Root<OidcProvider> oidcProviderRoot = query.from(OidcProvider.class);
    List<Predicate> predicates = new ArrayList<>();
    Optional.ofNullable(params.getQ())
            .ifPresent(q -> {
                String likeExpr = "%" + q.replaceAll("%", "_%") + "%";
                predicates.add(cb.like(oidcProviderRoot.get("name"), likeExpr, '_'));
            });
    if (!predicates.isEmpty()) {
        query.where(predicates.toArray(Predicate[]::new));
    }

    query.orderBy(cb.asc(oidcProviderRoot.get("id")));
    return em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .setFirstResult(params.getOffset())
            .setMaxResults(params.getLimit())
            .getResultList()
            .stream()
            .map(oidcProvider -> {
                // Excludes client secret
                oidcProvider.setClientSecret(null);
                return oidcProvider;
            })
            .collect(Collectors.toList());
}
 
Example #14
Source File: RolesResource.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
@Decision(HANDLE_OK)
public List<Role> handleOk(RoleSearchParams params, UserPermissionPrincipal principal, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Role> query = cb.createQuery(Role.class);
    Root<Role> roleRoot = query.from(Role.class);
    query.distinct(true);

    List<Predicate> predicates = new ArrayList<>();
    if (!principal.hasPermission("any_roles:read")) {
        Join<Role, User> joinUsers = roleRoot.join("assignments")
                .join("group")
                .join("users");
        predicates.add(cb.equal(joinUsers.get("id"), principal.getId()));
    }
    Optional.ofNullable(params.getQ())
            .ifPresent(q -> {
                String likeExpr = "%" + q.replaceAll("%", "_%") + "%";
                predicates.add(cb.like(roleRoot.get("name"), likeExpr, '_'));
            });

    if (!predicates.isEmpty()) {
        query.where(predicates.toArray(Predicate[]::new));
    }

    query.orderBy(cb.asc(roleRoot.get("id")));

    return em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .setFirstResult(params.getOffset())
            .setMaxResults(params.getLimit())
            .getResultList();
}
 
Example #15
Source File: CacheModeHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Given a JPA {@link CacheStoreMode} and {@link CacheRetrieveMode}, determine the corresponding
 * legacy Hibernate {@link CacheMode}.
 *
 * @param storeMode The JPA shared-cache store mode.
 * @param retrieveMode The JPA shared-cache retrieve mode.
 *
 * @return Corresponding {@link CacheMode}.
 */
public static CacheMode interpretCacheMode(CacheStoreMode storeMode, CacheRetrieveMode retrieveMode) {
	if ( storeMode == null ) {
		storeMode = DEFAULT_STORE_MODE;
	}
	if ( retrieveMode == null ) {
		retrieveMode = DEFAULT_RETRIEVE_MODE;
	}

	final boolean get = ( CacheRetrieveMode.USE == retrieveMode );

	switch ( storeMode ) {
		case USE: {
			return get ? CacheMode.NORMAL : CacheMode.PUT;
		}
		case REFRESH: {
			// really (get == true) here is a bit of an invalid combo...
			return CacheMode.REFRESH;
		}
		case BYPASS: {
			return get ? CacheMode.GET : CacheMode.IGNORE;
		}
		default: {
			throw new IllegalStateException( "huh? :)" );
		}
	}
}
 
Example #16
Source File: RealmsResource.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
@Decision(PROCESSABLE)
public boolean isProcessable(Parameters params, RestContext context, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Application> query = cb.createQuery(Application.class);
    Root<Application> applicationRoot = query.from(Application.class);
    query.where(cb.equal(applicationRoot.get("name"), params.get("name")));

    Application application = em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .getResultStream().findAny().orElse(null);
    if (application != null) {
        context.putValue(application);
    }
    return application != null;
}
 
Example #17
Source File: InvitationResource.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
@Decision(EXISTS)
public boolean exists(Parameters params, RestContext context, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();

    CriteriaQuery<Invitation> query = cb.createQuery(Invitation.class);
    Root<Invitation> invitationRoot = query.from(Invitation.class);
    query.where(cb.equal(invitationRoot.get("code"), params.get("code")));
    Invitation invitation = em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .getResultStream().findAny().orElse(null);
    if (invitation != null) {
        context.putValue(invitation);
    }
    return invitation != null;
}
 
Example #18
Source File: SignInService.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
public Map<String, List<String>> getPermissionsByRealm(User user) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Assignment> assignmentCriteria = cb.createQuery(Assignment.class);
    Root<Assignment> assignmentRoot = assignmentCriteria.from(Assignment.class);
    Join<Group, Assignment> groupJoin = assignmentRoot.join("group");
    Join<User, Group> userJoin = groupJoin.join("users");
    assignmentRoot.fetch("role").fetch("permissions");
    assignmentCriteria.where(cb.equal(userJoin.get("id"), user.getId()));

    EntityGraph<Assignment> assignmentGraph = em.createEntityGraph(Assignment.class);
    assignmentGraph.addAttributeNodes("realm", "role");
    Subgraph<Role> roleGraph = assignmentGraph.addSubgraph("role");
    roleGraph.addAttributeNodes("permissions");
    Subgraph<Permission> permissionsGraph = roleGraph.addSubgraph("permissions");
    permissionsGraph.addAttributeNodes("name");

    return em.createQuery(assignmentCriteria)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .setHint("javax.persistence.fetchgraph", assignmentGraph)
            .getResultStream()
            .collect(Collectors.groupingBy(Assignment::getRealm))
            .entrySet()
            .stream()
            .collect(Collectors.toMap(
                    e -> e.getKey().getId().toString(),
                    e -> new ArrayList<>(e.getValue().stream()
                            .flatMap(v -> v.getRole().getPermissions().stream())
                            .map(Permission::getName)
                            .collect(Collectors.toSet()))));
}
 
Example #19
Source File: RealmResource.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
@Decision(PROCESSABLE)
public boolean isProcessable(Parameters params, RestContext context, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Application> query = cb.createQuery(Application.class);
    Root<Application> applicationRoot = query.from(Application.class);
    query.where(cb.equal(applicationRoot.get("name"), params.get("name")));

    Application application = em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .getResultStream().findAny().orElse(null);
    if (application != null) {
        context.putValue(application);
    }
    return application != null;
}
 
Example #20
Source File: OidcProviderResource.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
@Decision(EXISTS)
public boolean exists(Parameters params, RestContext context, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<OidcProvider> query = cb.createQuery(OidcProvider.class);
    Root<OidcProvider> oidcProviderRoot = query.from(OidcProvider.class);
    query.where(cb.equal(oidcProviderRoot.get("name"), params.get("name")));
    OidcProvider oidcProvider = em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .getResultStream().findAny().orElse(null);
    if (oidcProvider != null) {
        context.putValue(oidcProvider);
    }
    return oidcProvider != null;
}
 
Example #21
Source File: SignUpResource.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
private Invitation findInvitation(String code, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Invitation> query = cb.createQuery(Invitation.class);
    Root<Invitation> invitationRoot = query.from(Invitation.class);
    invitationRoot.fetch("groupInvitations", JoinType.LEFT);
    invitationRoot.fetch("oidcInvitations", JoinType.LEFT);
    query.where(cb.equal(invitationRoot.get("code"), code));

    return em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .getResultStream()
            .findAny()
            .orElse(null);
}
 
Example #22
Source File: PermissionResource.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
@Decision(EXISTS)
public boolean exists(Parameters params,
                      UserPermissionPrincipal principal,
                      HttpRequest request,
                      RestContext context,
                      EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Permission> query = cb.createQuery(Permission.class);
    Root<Permission> permissionRoot = query.from(Permission.class);

    List<Predicate> predicates = new ArrayList<>();
    predicates.add(cb.equal(permissionRoot.get("name"), params.get("name")));
    if ((request.getRequestMethod().equalsIgnoreCase("GET") && !principal.hasPermission("any_permission:read"))
            || (request.getRequestMethod().equalsIgnoreCase("PUT") && !principal.hasPermission("any_permission:update"))
            || (request.getRequestMethod().equalsIgnoreCase("DELETE") && !principal.hasPermission("any_permission:delete"))) {
        Join<Permission, User> userRoot = permissionRoot.join("roles")
                .join("assignments")
                .join("groups")
                .join("users");
        predicates.add(cb.equal(userRoot.get("id"), principal.getId()));
    }

    if (!predicates.isEmpty()) {
        query.where(predicates.toArray(Predicate[]::new));
    }

    query.where(cb.equal(permissionRoot.get("name"), params.get("name")));

    Permission permission = em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .getResultStream().findAny().orElse(null);
    if (permission != null) {
        context.putValue(permission);
    }
    return permission != null;
}
 
Example #23
Source File: CacheModeHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Given a JPA {@link CacheStoreMode} and {@link CacheRetrieveMode}, determine the corresponding
 * legacy Hibernate {@link CacheMode}.
 *
 * @param storeMode The JPA shared-cache store mode.
 * @param retrieveMode The JPA shared-cache retrieve mode.
 *
 * @return Corresponding {@link CacheMode}.
 */
public static CacheMode effectiveCacheMode(CacheStoreMode storeMode, CacheRetrieveMode retrieveMode) {
	if ( storeMode == null && retrieveMode == null ) {
		return null;
	}

	if ( storeMode == null ) {
		storeMode = DEFAULT_STORE_MODE;
	}
	if ( retrieveMode == null ) {
		retrieveMode = DEFAULT_RETRIEVE_MODE;
	}

	final boolean get = ( CacheRetrieveMode.USE == retrieveMode );

	switch ( storeMode ) {
		case USE: {
			return get ? CacheMode.NORMAL : CacheMode.PUT;
		}
		case REFRESH: {
			// really (get == true) here is a bit of an invalid combo...
			return CacheMode.REFRESH;
		}
		case BYPASS: {
			return get ? CacheMode.GET : CacheMode.IGNORE;
		}
		default: {
			throw new IllegalStateException( "huh? :)" );
		}
	}
}
 
Example #24
Source File: CacheModeHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static CacheStoreMode interpretCacheStoreMode(CacheMode cacheMode) {
	if ( cacheMode == null ) {
		cacheMode = DEFAULT_LEGACY_MODE;
	}

	if ( CacheMode.REFRESH == cacheMode ) {
		return CacheStoreMode.REFRESH;
	}
	if ( CacheMode.NORMAL == cacheMode || CacheMode.PUT == cacheMode ) {
		return CacheStoreMode.USE;
	}
	return CacheStoreMode.BYPASS;
}
 
Example #25
Source File: VerificationEmailResource.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
@Decision(PROCESSABLE)
public boolean processable(Parameters params, EntityManager em, RestContext context) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<User> query = builder.createQuery(User.class);
    Root<User> userRoot = query.from(User.class);
    userRoot.fetch("userProfileValues", JoinType.LEFT);
    query.where(builder.equal(userRoot.get("account"), params.get("account")));

    EntityGraph<User> userGraph = em.createEntityGraph(User.class);
    userGraph.addAttributeNodes("account", "userProfileValues");

    User user = em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .setHint("javax.persistence.fetchgraph", userGraph)
            .getResultStream().findAny().orElse(null);

    if (user != null) {
        context.putValue(user);
    } else {
        context.setMessage(Problem.valueOf(422, "User not found"));
        return false;
    }

    UserProfileValue emailValue = findMailVerification(em, user.getAccount()).map(verification -> {
        context.putValue(verification);
        return verification;
    }).flatMap(verification -> user.getUserProfileValues()
            .stream()
            .filter(v -> Objects.equals(v.getUserProfileField().getJsonName(), "email"))
            .findAny()
            .filter(v -> Objects.nonNull(v.getValue()))
    ).orElse(null);

    if (emailValue != null) {
        context.putValue(emailValue);
    }
    return emailValue != null;
}
 
Example #26
Source File: ApplicationResource.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
@Decision(EXISTS)
public boolean exists(Parameters params, RestContext context, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Application> query = cb.createQuery(Application.class);
    Root<Application> applicationRoot = query.from(Application.class);
    query.where(cb.equal(applicationRoot.get("name"), params.get("name")));

    List<ResourceField> embedEntities = some(params.get("embed"), embed -> new ResourceFilter().parse(embed))
            .orElse(Collections.emptyList());

    EntityGraph<Application> applicationGraph = em.createEntityGraph(Application.class);
    applicationGraph.addAttributeNodes("name", "description", "virtualPath", "passTo", "topPage");

    if (embedEntities.stream().anyMatch(r -> r.getName().equalsIgnoreCase("realms"))) {
        applicationRoot.fetch("realms", JoinType.LEFT);
        query.distinct(true);
        applicationGraph.addSubgraph("realms")
                .addAttributeNodes("name", "description", "url");

    }

    Application application = em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .setHint("javax.persistence.fetchgraph", applicationGraph)
            .getResultStream().findAny().orElse(null);
    if (application != null) {
        context.putValue(application);
    }
    return application != null;
}
 
Example #27
Source File: GroupUsersResource.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
@Decision(PROCESSABLE)
public boolean processable(Parameters params, RestContext context, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Group> query = cb.createQuery(Group.class);
    Root<Group> groupRoot = query.from(Group.class);
    query.where(cb.equal(groupRoot.get("name"), params.get("name")));

    Group group = em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .getResultStream().findAny().orElse(null);
    if (group != null) {
        context.putValue(group);
    }
    return group != null;
}
 
Example #28
Source File: GroupUsersResource.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
@Decision(HANDLE_OK)
public List<User> list(Group group, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<User> query = cb.createQuery(User.class);
    Root<User> userRoot = query.from(User.class);
    Join<Group, User> groupsJoin = userRoot.join("groups");
    query.where(cb.equal(groupsJoin.get("id"), group.getId()));
    query.orderBy(cb.asc(userRoot.get("id")));
    return em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .getResultList();
}
 
Example #29
Source File: RolePermissionsResource.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
@Decision(EXISTS)
public boolean exists(Parameters params, RestContext context, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Role> query = cb.createQuery(Role.class);
    Root<Role> roleRoot = query.from(Role.class);
    query.where(cb.equal(roleRoot.get("name"), params.get("name")));

    Role role = em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .getResultStream().findAny().orElse(null);
    if (role != null) {
        context.putValue(role);
    }
    return role != null;
}
 
Example #30
Source File: PermissionsResource.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
@Decision(HANDLE_OK)
public List<Permission> list(PermissionSearchParams params,
                             UserPermissionPrincipal principal,
                             EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Permission> query = cb.createQuery(Permission.class);
    Root<Permission> permissionRoot = query.from(Permission.class);
    query.distinct(true);

    List<Predicate> predicates = new ArrayList<>();
    Optional.ofNullable(params.getQ())
            .ifPresent(q -> {
                String likeExpr = "%" + q.replaceAll("%", "_%") + "%";
                predicates.add(cb.like(permissionRoot.get("name"), likeExpr, '_'));
            });
    if (!principal.hasPermission("any_permission:read")) {
        Join<Permission, User> userRoot = permissionRoot.join("roles")
                .join("assignments")
                .join("group")
                .join("users");
        predicates.add(cb.equal(userRoot.get("id"), principal.getId()));
    }

    if (!predicates.isEmpty()) {
        query.where(predicates.toArray(Predicate[]::new));
    }

    query.orderBy(cb.asc(permissionRoot.get("id")));

    return em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .setFirstResult(params.getOffset())
            .setMaxResults(params.getLimit())
            .getResultList();
}