Example usage for org.springframework.cache Cache get

List of usage examples for org.springframework.cache Cache get

Introduction

In this page you can find the example usage for org.springframework.cache Cache get.

Prototype

@Nullable
ValueWrapper get(Object key);

Source Link

Document

Return the value to which this cache maps the specified key.

Usage

From source file:org.kuali.rice.kim.impl.role.RoleServiceImpl.java

protected Role getRoleFromCache(String namespaceCode, String name) {
    Cache cache = cacheManager.getCache(Role.Cache.NAME);
    Cache.ValueWrapper cachedValue = cache.get("namespaceCode=" + namespaceCode + "|name=" + name);
    if (cachedValue != null) {
        return (Role) cachedValue.get();
    }/*from w ww.jav a2  s  .c om*/
    return null;
}

From source file:org.kuali.rice.kim.impl.role.RoleServiceImpl.java

protected List<String> getQualifiersForExactMatch(String kimTypeId, RoleTypeService roleTypeService) {
    String cacheKey = "{getQualifiersForExactMatch}kimTypeId=" + kimTypeId;
    Cache cache = cacheManager.getCache(Role.Cache.NAME);
    Cache.ValueWrapper value = cache.get(cacheKey);
    List<String> qualifiers = new ArrayList<String>();
    if (value == null) {
        try {//from  w  w  w. ja v a 2  s . c o  m
            qualifiers = roleTypeService.getQualifiersForExactMatch();
            cache.put(cacheKey, qualifiers);
        } catch (Exception e) {
            LOG.warn("Caught exception when attempting to invoke a role type service", e);
        }
    } else {
        qualifiers = (List<String>) value.get();
    }
    return qualifiers;
}

From source file:org.opentestsystem.delivery.testreg.persistence.criteria.NCESIDValidator.java

@SuppressWarnings("unchecked")
private Sb11Entity findByNationwideId(final String nationwideIdentifier, final FormatType format) {

    if (format == FormatType.INSTITUTION) {
        final Cache ncesidCache = this.cacheManager.getCache("institution.ncesid");

        final ValueWrapper cacheGet = ncesidCache.get("ncesids");

        if (cacheGet != null) {

            final HashSet<String> ncesIdSet = (HashSet<String>) cacheGet.get();

            if (!ncesIdSet.contains(nationwideIdentifier)) {
                return null;
            }//www.ja  v a2  s.co  m
        }
    }

    final Map<String, String[]> reqMap = new HashMap<String, String[]>();
    reqMap.put(DistrictEntitySearchRequest.SEARCH_KEY_NCESID, new String[] { nationwideIdentifier });
    final AbstractTestRegSearchRequest searchRequest = new DistrictEntitySearchRequest(reqMap);
    searchRequest.setFilter(false);
    final SearchResponse<? extends Sb11Entity> response = this.sb11EntityService
            .searchDomainObjects(searchRequest, format);
    if (!CollectionUtils.isEmpty(response.getSearchResults())) {
        final Sb11Entity dbEntity = response.getSearchResults().get(0);
        return dbEntity;
    }
    return null;
}

From source file:org.opentestsystem.delivery.testreg.rest.SubjectController.java

/**
 * Updates Subject.//from  w ww  .  ja  va 2  s  . com
 * @param subject to be saved.
 * @param response HttpServletResponse.
 * @return Subject updated subject object.
 */
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/subject/{subjectId}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE, produces = {
        MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public Subject updateSubject(@PathVariable final String subjectId, @RequestBody @Valid final Subject subject,
        final HttpServletResponse response) {
    Subject subjectDb = subjectService.getSubject(subjectId);
    if (subject == null || subjectDb == null || StringUtils.isEmpty(subject.getId())
            || !subjectId.equals(subject.getId())) {
        throw new LocalizedException("subject.invalid.id");
    } else {
        Map<String, String[]> params = new HashMap<String, String[]>();
        params.put(StudentSearchRequest.SEARCH_KEY_ACCOM_SUBJECT, new String[] { subjectDb.getCode() });
        AbstractSearchRequest searchRequest = new StudentSearchRequest(params);
        SearchResponse<TestRegistrationBase> searchResponse = studentService.searchDomainObjects(searchRequest,
                FormatType.STUDENT);
        for (TestRegistrationBase base : searchResponse.getSearchResults()) {
            Student student = (Student) base;
            Object[] accommodations = student.getAccommodations();

            int accSize = 0;
            if (accommodations != null) {
                accSize = accommodations.length;
                for (int i = 0; i < accSize; i++) {

                    Object obj = accommodations[i];
                    Map<String, Object> acc = (Map<String, Object>) obj;
                    if (acc.get("subject") != null
                            && acc.get("subject").toString().equalsIgnoreCase(subjectDb.getCode())) {
                        acc.put("subject", subject.getCode());
                        accommodations[i] = acc;
                    }
                }
            }
            //update student now
            studentService.saveDomainObject(student);
        }
        //update resource family
        List<ResourceFamily> resourceFamily = resourceFamilyService.findBySubject(subjectDb.getCode());
        for (ResourceFamily rf : resourceFamily) {
            List<AccFamilySubject> subjects = rf.getSubject();
            for (int i = 0; i < subjects.size(); i++) {
                AccFamilySubject sub = subjects.get(i);
                if (sub.getCode().equalsIgnoreCase(subjectDb.getCode())) {
                    sub.setCode(subject.getCode());
                }
            }
            rf.setSubject(subjects);
            resourceFamilyService.saveResourceFamily(rf);
        }
        //update cache
        final Cache accommodationToCache = cacheManager.getCache("accommodationCache");
        List<MasterResourceAccommodation> masterAccommodations = null;
        if (accommodationToCache != null && subjectDb.getCode() != null) {
            for (String grade : gradeLevel.values()) {
                masterAccommodations = new ArrayList<MasterResourceAccommodation>();
                ValueWrapper cacheGet = accommodationToCache
                        .get(ARTHelpers.generateKey(grade, subjectDb.getCode()));
                if (cacheGet != null) {
                    masterAccommodations = (List<MasterResourceAccommodation>) cacheGet.get();
                    accommodationToCache.evict(ARTHelpers.generateKey(grade, subjectDb.getCode()));
                    accommodationToCache.put(ARTHelpers.generateKey(grade, subject.getCode()),
                            masterAccommodations);
                }
            }
        }
        Subject savedSubject = subjectService.saveSubject(subject);
        response.setHeader("Location", savedSubject.getUrl());
        return savedSubject;
    }
}

From source file:org.opentestsystem.delivery.testreg.service.impl.TestRegUserDetailsServiceImpl.java

@Override
public Set<String> getMongoIdsOfEntitiesCurrentUserHasAccessTo(StudentSecurity studentSecurity) {
    String userName;//from w w  w.  j a v a 2  s. c  o  m
    Collection<SbacRole> sbacRoles;
    if (studentSecurity == null) {
        SbacUser sbacUser = getCurrentUser();
        userName = sbacUser.getUsername();
        sbacRoles = sbacUser.getRoles();
    } else {
        userName = studentSecurity.getUserName();
        sbacRoles = studentSecurity.getSbacRoles();
    }

    long start = System.currentTimeMillis();
    LOGGER.trace("*********** looking up all entities that current user has access to ***********");
    Cache roleToEntityCache = cacheManager.getCache(ROLE_TO_ENTITY_CACHENAME);
    Set<String> mongoIdsOfEntitiesUserHasAccessTo = null;
    if (roleToEntityCache != null) {
        ValueWrapper cacheGet = roleToEntityCache.get(userName);
        if (cacheGet != null) {
            mongoIdsOfEntitiesUserHasAccessTo = (Set<String>) cacheGet.get();
        }
    }

    if (mongoIdsOfEntitiesUserHasAccessTo == null) {
        LOGGER.trace("********* entity to role map cache does not exist, rebuild **************");
        mongoIdsOfEntitiesUserHasAccessTo = buildEntityToRoleMapForUser(userName, sbacRoles);
        if (cacheManager.getCache(ROLE_TO_ENTITY_CACHENAME) != null) {
            cacheManager.getCache(ROLE_TO_ENTITY_CACHENAME).put(userName, mongoIdsOfEntitiesUserHasAccessTo);
        }
    }

    LOGGER.trace("********* entity to role map cache exists **************");
    LOGGER.trace("getMongoIdsOfEntitiesCurrentUserHasAccessTo took: " + (System.currentTimeMillis() - start));
    return mongoIdsOfEntitiesUserHasAccessTo;
}

From source file:org.opentestsystem.delivery.testreg.service.impl.TestRegUserDetailsServiceImpl.java

private synchronized Set<String> buildEntityToRoleMapForUser(final String userName,
        Collection<SbacRole> sbacRoles) {

    // We need to check right at the beginning to make sure that the user cache doesn't exist
    // it may have been created by a different thread while another was waiting for the
    // synchronize lock. If the cache does exist for the user, send it back, otherwise create it.

    Cache roleToEntitiesCache = cacheManager.getCache(ROLE_TO_ENTITY_CACHENAME);
    Set<String> mongoIdsOfEntitiesUserHasAccessTo = null;

    if (roleToEntitiesCache != null) {
        ValueWrapper cacheGet = roleToEntitiesCache.get(userName);
        if (cacheGet != null) {
            mongoIdsOfEntitiesUserHasAccessTo = (Set<String>) cacheGet.get();
        }/*w ww  .  j  a v a2s . co  m*/
    }

    if (mongoIdsOfEntitiesUserHasAccessTo == null) {
        mongoIdsOfEntitiesUserHasAccessTo = new HashSet<>();
        Map<String, Set<String>> uberMap = testRegUberEntityRelationshipService.getUberEntityRelationshipMap();
        for (SbacRole sbacRole : sbacRoles) {
            String effectiveEntityMongoId = convertRoleToEffectiveEntityMongoId(sbacRole);
            if (effectiveEntityMongoId == null) {
                LOGGER.error("unable to determine effectiveEntityMongoId from role: " + sbacRole);
            } else if (!uberMap.containsKey(effectiveEntityMongoId)) {
                LOGGER.error("the effectiveEntityMongoId (" + effectiveEntityMongoId
                        + ") for this role wasn't found in the uber entity relationship map!");
            } else {

                // recursive approach
                // addAllChildMongoIds(effectiveEntityMongoId, mongoIdsOfEntitiesUserHasAccessTo, uberMap);

                // non-recursive alternative
                mongoIdsOfEntitiesUserHasAccessTo
                        .addAll(findAllChildrenMongoIds(effectiveEntityMongoId, uberMap));

            }
        }
    }

    return mongoIdsOfEntitiesUserHasAccessTo;
}

From source file:org.springframework.cache.interceptor.YJFCacheAspectSupport.java

private CacheStatus inspectCacheables(Collection<CacheOperationContext> cacheables) {
    Map<CacheOperationContext, Object> cUpdates = new LinkedHashMap<CacheOperationContext, Object>(
            cacheables.size());//from  w w w .  j  ava2s  .c  o m

    boolean updateRequire = false;
    Object retVal = null;

    if (!cacheables.isEmpty()) {
        boolean log = logger.isTraceEnabled();
        boolean atLeastOnePassed = false;

        for (CacheOperationContext context : cacheables) {
            if (context.isConditionPassing()) {
                atLeastOnePassed = true;
                Object key = context.generateKey();

                if (log) {
                    logger.trace("Computed cache key " + key + " for operation " + context.operation);
                }
                if (key == null) {
                    throw new IllegalArgumentException(
                            "Null key returned for cache operation (maybe you are using named params on classes without debug info?) "
                                    + context.operation);
                }

                // add op/key (in case an update is discovered later on)
                cUpdates.put(context, key);

                boolean localCacheHit = false;

                // check whether the cache needs to be inspected or not (the method will be invoked anyway)
                if (!updateRequire) {
                    for (Cache cache : context.getCaches()) {
                        Cache.ValueWrapper wrapper = cache.get(key);
                        if (wrapper != null) {
                            retVal = wrapper.get();
                            localCacheHit = true;
                            break;
                        }
                    }
                }

                if (!localCacheHit) {
                    updateRequire = true;
                }
            } else {
                if (log) {
                    logger.trace("Cache condition failed on method " + context.method + " for operation "
                            + context.operation);
                }
            }
        }

        // return a status only if at least on cacheable matched
        if (atLeastOnePassed) {
            return new CacheStatus(cUpdates, updateRequire, retVal);
        }
    }

    return null;
}