Example usage for org.springframework.cache Cache put

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

Introduction

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

Prototype

void put(Object key, @Nullable Object value);

Source Link

Document

Associate the specified value with the specified key in this cache.

Usage

From source file:net.eusashead.spring.gaecache.GaeCacheITCase.java

@Test
public void testEvictAll() throws Exception {

    // Create 2 caches
    Cache cache1 = cacheManager.getCache("cache1");
    Cache cache2 = cacheManager.getCache("cache2");

    // 2 objects for 2 caches
    Foo foo1 = new Foo(new FooKey(1l), "foo1");
    cache1.put(GaeCacheKey.create("foo1"), foo1);
    Foo foo2 = new Foo(new FooKey(2l), "foo2");
    cache2.put(GaeCacheKey.create("foo2"), foo2);

    // Are they cached?
    assertCached(ms, foo1, "cache1", "foo1");
    assertCached(ms, foo2, "cache2", "foo2");

    // Clear cache 2
    cache2.clear();//  ww w.  java 2  s .c o  m

    // Make sure cache 1 is OK
    assertCached(ms, foo1, "cache1", "foo1");

    // Make sure the cleared cache is clear
    assertNotCached(ms, "cache2", "foo2");

}

From source file:com.github.dactiv.fear.user.service.account.AccountService.java

/**
 * ???/*from w w  w. j ava  2 s .  com*/
 *
 * @param mail ???
 * @throws Exception
 */
public void sendValidMail(String mail) throws Exception {

    Boolean flag = Apis.invoke("accountService", "isUsernameUnique", mail);

    if (!flag) {
        throw new ServiceException("" + mail + "");
    }

    Map<String, Object> principal = Subjects.getPrincipal();
    String id = new Md5Hash(mail + principal.get("id") + System.currentTimeMillis()).toHex();

    ValidToken entity = new MailValidToken(id, new Date(), mail, principal);
    Cache cache = cacheManager.getCache(validMailCacheName);

    cache.put(id, entity);

    Template template = freemarkerConfiguration.getTemplate("registration.ftl", "UTF-8");
    String message = FreeMarkerTemplateUtils.processTemplateIntoString(template, entity);

    Mail mailEntity = new Mail(mail, "?", message, Boolean.TRUE);
    Apis.invoke("messageService", "sendMail", mailEntity);
}

From source file:com.github.dactiv.fear.user.service.account.AccountService.java

/**
 * ???/*from   w w w . j a v  a 2 s  . c  om*/
 *
 * @param user ?
 * @throws Exception
 */
private void sendForgetPasswordMail(Map<String, Object> user) throws Exception {
    String email = Casts.cast(user.get("email"), String.class);

    if (StringUtils.isEmpty(email)) {
        throw new ServiceException("?[" + user.get("username") + "]?");
    }

    String id = new Md5Hash(email + user.get("id") + System.currentTimeMillis()).toHex();

    ValidToken entity = new ValidToken(id, new Date(), user);
    Cache cache = cacheManager.getCache(forgotPasswordCacheName);

    cache.put(id, entity);

    Map<String, Object> data = new HashMap<>();

    data.put("user", user);
    data.put("vme", entity);

    Template template = freemarkerConfiguration.getTemplate("forgot-password.ftl", "UTF-8");
    String message = FreeMarkerTemplateUtils.processTemplateIntoString(template, data);

    Mail mailEntity = new Mail(email, "??", message, Boolean.TRUE);
    Apis.invoke("messageService", "sendMail", mailEntity);

}

From source file:de.iew.services.impl.MessageBundleServiceImpl.java

protected void putBundleIntoCach(MessageBundleStore messageBundleStore, String basename) {
    Cache cache = this.cacheManager.getCache(this.cacheName);
    if (cache != null) {
        String cacheKey = messageBundleKey(messageBundleStore.getLanguageCode(),
                messageBundleStore.getCountryCode(), basename);
        cache.put(cacheKey, messageBundleStore);
    }//from  w w w. ja  v  a  2 s . c  o m
}

From source file:com.github.dactiv.fear.user.service.account.AccountService.java

/**
 * ?? key//  ww  w  . j a  v a 2 s  . c om
 *
 * @param id key
 *
 * @return ??? map?
 */
public ValidToken validForgotPassword(String id) {

    Cache cache = cacheManager.getCache(forgotPasswordCacheName);
    ValidToken entity = cache.get(id, ValidToken.class);
    if (entity == null) {
        throw new TokenNotFoundException("???");
    }

    try {

        long creationTime = entity.getCreationDate().getTime();
        long currentTime = System.currentTimeMillis();

        if (currentTime - creationTime > forgotPasswordExpiredTime) {
            throw new TokenExpiredException("ID[" + entity.getId() + "]");
        }
    } finally {
        cache.evict(id);
    }

    Map<String, Object> principal = entity.getPrincipal();
    id = new Md5Hash(principal.get("id").toString() + System.currentTimeMillis()).toHex();
    ValidToken validToken = new ValidToken(id, new Date(), principal);

    cache = cacheManager.getCache(resetPasswordCacheName);
    cache.put(id, validToken);

    return validToken;
}

From source file:org.hsweb.web.controller.login.AuthorizeController.java

/**
 * ,?,?./* w  w w  . j  av  a2s  .  c om*/
 * <ul>
 * <li>
 * ???{@link ConfigService#getInt(String, String, int)}:login,error.max_number,5
 * </li>
 * <li>
 * ???{@link ConfigService#getInt(String, String, int)}:login,error.wait_minutes,10
 * <p>
 * </li>
 * </ul>
 *
 * @param username ??
 * @param password ?
 * @param request  {@link HttpServletRequest}
 * @return 
 * @throws AuthorizeForbiddenException ??
 * @throws NotFoundException           ?
 * @throws Exception                   
 */
@RequestMapping(value = "/login", method = RequestMethod.POST)
@AccessLogger("")
public ResponseMessage login(@RequestParam String username, @RequestParam String password,
        HttpServletRequest request) throws Exception {
    //??
    String userIp = WebUtil.getIpAddr(request);
    int maxErrorNumber = configService.getInt("login", "error.max_number", 5);
    int waitMinutes = configService.getInt("login", "error.wait_minutes", 10);
    Cache cache = cacheManager.getCache("login.error");
    String cachePrefix = username.concat("@").concat(userIp);
    String timeCacheKey = cachePrefix.concat("-time");
    String numberCacheKey = cachePrefix.concat("-number");
    Integer error_number = cache.get(numberCacheKey, Integer.class);
    Long error_time = cache.get(timeCacheKey, Long.class);
    long now_time = System.currentTimeMillis();
    if (error_number != null && error_time != null) {
        if ((now_time - error_time) / 1000 / 60d > waitMinutes) {
            cache.evict(timeCacheKey);
            cache.evict(numberCacheKey);
            error_number = 0;
            error_time = 0l;
        }
        if (error_number >= maxErrorNumber)
            throw new AuthorizeForbiddenException("?,"
                    + (waitMinutes - ((now_time - error_time) / 1000 / 60)) + "??!");
    }
    User user = userService.selectByUserName(username);
    if (user == null || user.getStatus() != 1)
        throw new NotFoundException("?");
    //?
    if (!user.getPassword().equals(MD5.encode(password))) {
        if (error_number == null)
            error_number = 0;
        cache.put(timeCacheKey, System.currentTimeMillis());
        cache.put(numberCacheKey, ++error_number);
        throw new AuthorizeForbiddenException(
                "?,??" + (maxErrorNumber - error_number) + "");
    }
    cache.evict(timeCacheKey);
    cache.evict(numberCacheKey);
    user.setPassword("");//?
    if (user.getUsername().equals("admin"))
        userService.initAdminUser(user);
    else
        user.initRoleInfo();
    User newUser = new User();
    BeanUtilsBean.getInstance().getPropertyUtils().copyProperties(newUser, user);
    httpSessionManager.addUser(newUser, request.getSession());
    return ResponseMessage.ok();
}

From source file:org.hsweb.web.oauth2.service.OAuth2ServiceImpl.java

@Override
@Transactional(noRollbackFor = AccessTimeoutException.class)
public User getUserByAccessToken(String accessToken) {
    OAuth2Access auth2Access = null;/*  w w  w. j a  va2  s. c  om*/
    Cache cache = null;
    String cacheKey = "accessToken:".concat(accessToken);
    boolean inCache = false;
    if (cacheManager != null) {
        cache = cacheManager.getCache(cacheName);
        if (cache != null) {
            Cache.ValueWrapper wrapper = cache.get(cacheKey);
            if (wrapper != null) {
                auth2Access = (OAuth2Access) wrapper.get();
                inCache = true;
            }
        }
    }
    if (auth2Access == null)
        auth2Access = oAuth2AccessMapper.selectByAccessToken(accessToken);
    if (auth2Access == null) {
        return null;
    }
    //?
    if (auth2Access.getLeftTime() <= 0) {
        if (cache != null) {
            cache.evict(cacheKey);
        }
        // TODO: 16-8-17 token
        oAuth2AccessMapper.deleteById(auth2Access.getId());
        throw new AuthorizeException("expired_token");
    }
    if (!inCache) {
        User user = userService.selectByPk(auth2Access.getUserId());
        user.initRoleInfo();
        user.setPassword(null);
        User newUser = new User();
        try {
            BeanUtilsBean.getInstance().getPropertyUtils().copyProperties(newUser, user);
        } catch (Exception e) {
        }
        auth2Access.setUser(newUser);
        cache.put(cacheKey, auth2Access);
        return newUser;
    } else {
        return auth2Access.getUser();
    }
}

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 {/*from  w w  w . j a  v a2s . co m*/
            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 {//w  w w.  ja v a2 s  .  c  om
            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);
    } else {/*  w  ww .j  a v  a  2  s .co  m*/
        token = (String) valueWrapper.get();
    }

    return token;
}