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:grails.plugin.cache.web.filter.PageFragmentCachingFilter.java

protected CacheStatus inspectCacheables(Collection<CacheOperationContext> cacheables) {

    if (cacheables.isEmpty()) {
        return null;
    }/*w w  w.  ja  v  a  2s. c o m*/

    Map<CacheOperationContext, Object> cUpdates = new LinkedHashMap<CacheOperationContext, Object>(
            cacheables.size());

    boolean trace = log.isTraceEnabled();
    boolean updateRequired = false;
    boolean atLeastOne = false;

    ValueWrapper valueWrapper = null;

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

            if (trace) {
                log.trace("Computed cache key {} for operation {}", new Object[] { key, 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 (!updateRequired) {
                for (Cache cache : context.getCaches()) {
                    ValueWrapper wrapper = cache.get(key);
                    if (wrapper != null) {
                        valueWrapper = wrapper;
                        localCacheHit = true;
                        break;
                    }
                }
            }

            if (!localCacheHit) {
                updateRequired = true;
            }
        } else {
            if (trace) {
                log.trace("Cache condition failed on method {} for operation {}",
                        new Object[] { context.method, context.operation });
            }
        }
    }

    // return a status only if at least one cacheable matched
    if (atLeastOne) {
        return new CacheStatus(cUpdates, updateRequired, valueWrapper);
    }

    return null;
}

From source file:com.muk.services.api.impl.PayPalPaymentService.java

private String getTokenHeader() {
    final Cache cache = cacheManager.getCache(ServiceConstants.CacheNames.paymentApiTokenCache);
    final String token = "paypal";
    ValueWrapper valueWrapper = cache.get(token);
    String cachedHeader = StringUtils.EMPTY;

    if (valueWrapper == null || valueWrapper.get() == null) {
        try {/*w ww .ja va 2 s  .com*/
            final String value = securityCfgService.getPayPalClientId() + ":"
                    + keystoreService.getPBEKey(securityCfgService.getPayPalClientId());

            final HttpHeaders headers = new HttpHeaders();
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            headers.add(HttpHeaders.AUTHORIZATION,
                    "Basic " + nonceService.encode(value.getBytes(StandardCharsets.UTF_8)));

            final MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
            body.add("grant_type", "client_credentials");

            final HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(
                    body, headers);

            final ResponseEntity<JsonNode> response = restTemplate.postForEntity(
                    securityCfgService.getPayPalUri() + "/oauth2/token", request, JsonNode.class);

            cache.put(token, response.getBody().get("access_token").asText());
            valueWrapper = cache.get(token);
            cachedHeader = (String) valueWrapper.get();
        } catch (final IOException ioEx) {
            LOG.error("Failed read keystore", ioEx);
            cachedHeader = StringUtils.EMPTY;
        } catch (final GeneralSecurityException secEx) {
            LOG.error("Failed to get key", secEx);
            cachedHeader = StringUtils.EMPTY;
        }
    } else {
        cachedHeader = (String) valueWrapper.get();
    }

    return "Bearer " + cachedHeader;
}

From source file:com.muk.services.api.impl.StripePaymentService.java

private String getTokenHeader() {
    final Cache cache = cacheManager.getCache(ServiceConstants.CacheNames.paymentApiTokenCache);
    final String token = "stripe";
    ValueWrapper valueWrapper = cache.get(token);
    String cachedHeader = StringUtils.EMPTY;

    if (valueWrapper == null || valueWrapper.get() == null) {
        try {//from   w w  w.j a  v  a2s  .  com
            final String value = keystoreService.getPBEKey(securityCfgService.getStripeClientId());

            cache.put(token, value);
            valueWrapper = cache.get(token);
            cachedHeader = (String) valueWrapper.get();
        } catch (final IOException ioEx) {
            LOG.error("Failed read keystore", ioEx);
            cachedHeader = StringUtils.EMPTY;
        } catch (final GeneralSecurityException secEx) {
            LOG.error("Failed to get key", secEx);
            cachedHeader = StringUtils.EMPTY;
        }
    } else {
        cachedHeader = (String) valueWrapper.get();
    }

    return "Bearer " + cachedHeader;
}

From source file:com.muk.services.util.GoogleOAuthService.java

@Override
public String authorizeRequest(String scope, String privateKeyAlias, String serviceAccount) {
    final Cache cache = cacheManager.getCache(ServiceConstants.CacheNames.externalTokenCache);
    final ValueWrapper valueWrapper = cache.get(CACHE_KEY);
    String token = StringUtils.EMPTY;

    if (valueWrapper == null || valueWrapper.get() == null) {
        final String jwt = createClaim(scope, privateKeyAlias, serviceAccount);
        token = requestAccessToken(jwt);

        cache.put(CACHE_KEY, token);/*  w  ww  . j  a  v  a 2s . c o m*/
    } else {
        token = (String) valueWrapper.get();
    }

    return token;
}

From source file:com.sliu.framework.app.sys.security.DefaultInvocationSecurityMetadataSource.java

public final Collection<ConfigAttribute> lookupAttributes(String url) {
    if (this.stripQueryStringFromUrls) {
        int firstQuestionMarkIndex = url.indexOf("?");
        if (firstQuestionMarkIndex != -1) {
            url = url.substring(0, firstQuestionMarkIndex);
        }//from   ww w .j  a va 2s .  c  o  m
    }
    if (this.urlMatcher.requiresLowerCaseUrl()) {
        url = url.toLowerCase();
        log.debug("lookupAttributes", "Converted URL to lowercase, from: '" + url + "'; to: '" + url + "'");
    }
    Cache cache = this.cacheManager.getCache("resources");
    Object obj = cache.get("FilterInvoSecMetaKey");
    if (obj == null) {
        try {
            loadSecurityMetadataSource();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    try {
        if (lastmodified != menu.getFile().lastModified()) {
            cache.evict("FilterInvoSecMetaKey");
            cache.evict("FunctionChildMap");
            cache.evict("FunctionMap");
            loadSecurityMetadataSource();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (idUrlMap.get(url) != null)
        url = idUrlMap.get(url);

    Collection<ConfigAttribute> attributes = extractMatchingAttributes(url, this.httpMap);

    return attributes;
}

From source file:org.eclipse.hawkbit.repository.jpa.model.CacheFieldEntityListener.java

/**
 * enriches the JPA entities after loading the entity from the SQL database.
 * // w  w w.  j a va  2 s.  c o m
 * @param target
 *            the target which has been loaded from the database
 */
@PostLoad
public void postLoad(final Object target) {
    if (target instanceof Identifiable) {
        final CacheManager cacheManager = CacheManagerHolder.getInstance().getCacheManager();
        @SuppressWarnings("rawtypes")
        final String id = ((Identifiable) target).getId().toString();
        final Class<? extends Object> type = target.getClass();
        findCacheFields(type, id, (field, cacheKey, id1) -> {
            final Cache cache = cacheManager.getCache(type.getName());
            final ValueWrapper valueWrapper = cache
                    .get(CacheKeys.entitySpecificCacheKey(id1.toString(), cacheKey));
            if (valueWrapper != null && valueWrapper.get() != null) {
                FieldUtils.writeField(field, target, valueWrapper.get(), true);
            }
        });
    }
}

From source file:org.entando.entando.aps.system.services.cache.CacheInfoManager.java

public Object getFromCache(String targhetCache, String key) {
    Cache cache = this.getCache(targhetCache);
    Cache.ValueWrapper element = cache.get(key);
    if (null == element) {
        return null;
    }/* ww  w  . ja va  2 s .  c om*/
    if (isExpired(targhetCache, key)) {
        this.flushEntry(targhetCache, key);
        return null;
    }
    return element.get();
}

From source file:org.kuali.rice.kim.document.rule.AttributeValidationHelper.java

protected KimAttribute getAttributeDefinitionById(String id) {
    CacheManager cm = CoreImplServiceLocator.getCacheManagerRegistry()
            .getCacheManagerByCacheName(KimAttribute.Cache.NAME);
    Cache cache = cm.getCache(KimAttribute.Cache.NAME);
    String cacheKey = "id=" + id;
    ValueWrapper valueWrapper = cache.get(cacheKey);

    if (valueWrapper != null) {
        return (KimAttribute) valueWrapper.get();
    }// w  w w.  j a va2 s  .c  om

    KimAttributeBo attributeImpl = KradDataServiceLocator.getDataObjectService().find(KimAttributeBo.class, id);
    KimAttribute attribute = KimAttributeBo.to(attributeImpl);
    cache.put(cacheKey, attribute);

    return attribute;
}

From source file:org.kuali.rice.kim.document.rule.AttributeValidationHelper.java

protected KimAttribute getAttributeDefinitionByName(String attributeName) {
    CacheManager cm = CoreImplServiceLocator.getCacheManagerRegistry()
            .getCacheManagerByCacheName(KimAttribute.Cache.NAME);
    Cache cache = cm.getCache(KimAttribute.Cache.NAME);
    String cacheKey = "name=" + attributeName;
    ValueWrapper valueWrapper = cache.get(cacheKey);

    if (valueWrapper != null) {
        return (KimAttribute) valueWrapper.get();
    }//from w w  w.j a  v a2s.  c o m

    List<KimAttributeBo> attributeImpls = KradDataServiceLocator.getDataObjectService().findMatching(
            KimAttributeBo.class,
            QueryByCriteria.Builder.forAttribute(KRADPropertyConstants.ATTRIBUTE_NAME, attributeName).build())
            .getResults();
    KimAttribute attribute = null;
    if (!attributeImpls.isEmpty()) {
        attribute = KimAttributeBo.to(attributeImpls.get(0));
    }

    cache.put(cacheKey, attribute);

    return attribute;
}

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

protected Role getRoleFromCache(String id) {
    Cache cache = cacheManager.getCache(Role.Cache.NAME);
    Cache.ValueWrapper cachedValue = cache.get("id=" + id);
    if (cachedValue != null) {
        return (Role) cachedValue.get();
    }/*from ww w .j ava 2s  . co m*/
    return null;
}