/** * Returns the cumulative downloaded size by a user on a given period. * * @param user associate user to downloads. * @param period period time in millisecond. * @return cumulative downloaded size. */ @Transactional (readOnly = true) @Cacheable (value = "network_download_size", key = "#user.getUUID ()", condition = "#user != null") public Long getDownloadedSizeByUserSince (final User user, final Long period) { Objects.requireNonNull (user, "'user' parameter is null"); Objects.requireNonNull (period, "'period' parameter is null"); long current_timestamp = System.currentTimeMillis (); if (period < 0 || period > current_timestamp) { throw new IllegalArgumentException ("period time too high"); } Date date = new Date (current_timestamp - period); return networkUsageDao.getDownloadedSizeByUserSince (user, date); }
@Cacheable(value = Constants.CACHE_NAMESPACE + "sysDics") public Map<String, Map<String, String>> getAllDic() { Map<String, Object> params = InstanceUtil.newHashMap(); params.put("orderBy", "type_,sort_no"); List<SysDic> list = queryList(params); Map<String, Map<String, String>> resultMap = InstanceUtil.newHashMap(); for (SysDic sysDic : list) { if (sysDic != null) { String key = sysDic.getType(); if (resultMap.get(key) == null) { Map<String, String> dicMap = InstanceUtil.newHashMap(); resultMap.put(key, dicMap); } if (StringUtils.isNotBlank(sysDic.getParentCode())) { resultMap.get(key).put(sysDic.getParentCode() + sysDic.getCode(), sysDic.getCodeText()); } else { resultMap.get(key).put(sysDic.getCode(), sysDic.getCodeText()); } } } return resultMap; }
@Override @Cacheable(cacheNames = "gradleVersions", sync = true) public List<GradleVersion> getFinalVersionsGreaterEquals(GradleVersion minVersion) { List<GradleVersion> allVersions = new ArrayList<>(); JSONArray versions = new JSONArray(remoteGradleVersionResolver.getAllVersions()); for (int i = 0; i < versions.length(); i++) { JSONObject version = versions.getJSONObject(i); if (isFinalVersion(version)) { GradleVersion semanticVersion = new GradleVersion(version.getString(VERSION_ATTRIBUTE)); if (isGreaterEquals(minVersion, semanticVersion)) { allVersions.add(semanticVersion); } } } return allVersions; }
/** * Returns number of downloads by a user on a given period. * * @param user associate user to downloads. * @param period period time in millisecond. * @return number of downloads. */ @Transactional (readOnly = true) @Cacheable (value = "network_download_count", key = "#user.getUUID ()", condition = "#user != null") public int countDownloadsByUserSince (final User user, final Long period) { Objects.requireNonNull (user, "'user' parameter is null"); Objects.requireNonNull (period, "'period' parameter is null"); long current_timestamp = System.currentTimeMillis (); if (period < 0 || period > current_timestamp) { throw new IllegalArgumentException ("period time too high"); } Date date = new Date (current_timestamp - period); return networkUsageDao.countDownloadByUserSince (user, date); }
/** * Download secrets cli binary. For better performance, the file resource * is cached in memory (for 5 min, default cache timeout) if it's less * than 10 MB. * * @return file resource. * @throws IOException throws if any error reading the file. */ @GetMapping("/download") @Cacheable("secrets-cli") @ApiOperation(value = "Download Secrets CLI latest version.") public ResponseEntity<Resource> download() throws IOException { File file = cliPath.toFile(); if (file.exists() && file.isFile() && file.length() < 10_000_000) { log.info("Downloading the secrets cli."); ByteArrayResource bar = new ByteArrayResource(Files.readAllBytes(cliPath)); return ResponseEntity.ok() .header("Content-disposition", "attachment;filename=" + file.getName()) .contentLength(file.length()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(bar); } else { log.error(format("Invalid secrets cli binary %s. Size: %d bytes.", cliPath, file.length())); throw new KeywhizException(INTERNAL_SERVER_ERROR.value(), "Latest secret cli binary is not available on server."); } }
@Cacheable(value = Constants.CACHE_NAMESPACE + "sysParamName") public String getName(String key) { if (StringUtils.isBlank(key)) { return ""; } Map<String, Object> params = InstanceUtil.newHashMap(); params.put("orderBy", "type_,sort_no"); List<SysParam> list = queryList(params); for (SysParam sysParam : list) { if (sysParam != null) { if (key.equals(sysParam.getParamKey())) { return sysParam.getRemark(); } } } return ""; }
@Override @Cacheable(cacheNames = "subdepts", key = "#depId") public List<Department> getAllSubDepts(Integer depId) { logger.info("Запрос к базе на чтение подразделений отдела с ID: " + depId); List<Department> departments; Session session = getSession(); try{ String sqlQueryForSubDepts1 = "SELECT DEPT_ID, PARENT_DEPT_ID, DEPT_NAME, DEPT_HEAD_ID FROM DEPARTMENT START WITH PARENT_DEPT_ID = :deptId CONNECT BY PRIOR DEPT_ID = PARENT_DEPT_ID"; departments = session.createSQLQuery(sqlQueryForSubDepts1) .addEntity(Department.class) .setParameter("deptId", depId) .list(); }catch (HibernateException e){ logger.error(e.getStackTrace()); throw new MyRuntimeException(StuffExceptions.DATABASE_ERROR); } return departments; }
/** * Return user corresponding to given user name. * * @param name User name. * @throws RootNotModifiableException */ @PreAuthorize ("hasAnyRole('ROLE_USER_MANAGER','ROLE_DATA_MANAGER','ROLE_SYSTEM_MANAGER')") @Transactional (readOnly=true, propagation=Propagation.REQUIRED) @Cacheable (value = "userByName", key = "#name?.toLowerCase()") public User getUserByName (String name) throws RootNotModifiableException { User u = this.getUserNoCheck (name); checkRoot (u); return u; }
@Cacheable(value = CACHE_COUNT_USER_TAG_POSTS, key = "#userId.toString().concat('_tags_posts_count')") public List<PostTagCountDTO> countUserPostsByTags(Long userId) { List<Object[]> counts = postRepository.countUserPostsByTags(userId); List<PostTagCountDTO> result = new ArrayList<>(); counts.forEach(count -> result.add(new PostTagCountDTO((Long) count[0], (Tag) count[1]))); return result; }
/** * Return the binary content of the resource at the specified location. * @param location a resource location * @return the content of the resource */ @Cacheable("project-resources") public byte[] getBinaryResource(String location) { try (InputStream stream = getInputStream(location)) { return StreamUtils.copyToByteArray(stream); } catch (IOException ex) { throw new IllegalStateException("Cannot get resource", ex); } }
@Cacheable(value = CONTACT_DETAILS_CACHE_NAME, key = "#person.personalCode") public UserPreferences getContactDetails(Person person) { String url = episServiceUrl + "/contact-details"; log.info("Getting contact details from {} for {} {}", url, person.getFirstName(), person.getLastName()); ResponseEntity<UserPreferences> response = restTemplate.exchange( url, HttpMethod.GET, new HttpEntity(getHeaders()), UserPreferences.class); return response.getBody(); }
@Override @Cacheable(key="#id" ,unless="#result == null") public T getById(Object id) throws DataAccessException { if (logger.isDebugEnabled()) logger.debug("type {} getById", type); try{ return mongoOperations.findById(id, type); }catch(Exception e){ throw new DataAccessException(e); } }
@Override @Cacheable( value = "message") public boolean saveMessage(Message message) throws WebQQServiceException { if(Objects.isNull(message.getSendUser())){ message.setSendUser(new User(SecurityContextUtils.getCurrentUser())); } return doSaveMessage(message); }
@Cacheable(value = Constants.CACHE_NAMESPACE + "sysDics") public Map<String, String> queryDicByType(String key) { Map<String, String> resultMap = applicationContext.getBean(SysDicService.class).getAllDic().get(key); if (resultMap == null) { return InstanceUtil.newHashMap(); } return resultMap; }
/** * 自动生成key * * @param id * @return */ @Cacheable(value = "userCache", keyGenerator = "wiselyKeyGenerator") public Person getPerson(String id) { log.info("[userCacheManager]没有缓存,则执行下面内容。"); Person person = new Person(); person.setAge(10); person.setGender("男"); person.setName(id); person.setId(id); return person; }
@Cacheable(cacheNames = "topOwners", keyGenerator="customKeyGenerator") public List<TopOwnerDTO> getTopOwnerByRealmId(int realmId) { int limit = 100; List<TopOwnerDTO> topOwners = new ArrayList<>(limit * 3); List<Object[]> list = auctionRepository.getOwnerTopQuantities(realmId, limit); updateTopOwnerList(list, topOwners, TopOwnerDTO.QUANTITY); updateTopOwnerList(auctionRepository.getOwnerTopSepcies(realmId, limit), topOwners, TopOwnerDTO.SPECIES); updateTopOwnerList(auctionRepository.getOwnerTopWorths(realmId, limit), topOwners, TopOwnerDTO.WORTH); return topOwners; }
@Transactional (readOnly=true, propagation=Propagation.REQUIRED) @Cacheable (value = {"indexes"}, key = "#product_id") public List<MetadataIndex> getIndexes(Long product_id) { Product product = productDao.read (product_id); if (product == null) return new ArrayList<MetadataIndex> (); Hibernate.initialize (product.getIndexes ()); return product.getIndexes (); }
@Override @Cacheable(STUDENT_NEIGHBORHOOD_CACHE_NAME) public UserNeighborhood getStudentNeighborhood() { DataModel model = buildDataModel(); UserSimilarity similarity = buildSimilarityIndex(model); return new ThresholdUserNeighborhood(0.3, similarity, model); }
@Cacheable(value = "busiSupport:securityService:csrfResourceUrls", key = "#p0") @CacheDuration(expireSeconds = 60 * 60) @Override public List<ResourceUrl> getCsrfResourceUrls(String systemCode) { ResourceUrlExample example = new ResourceUrlExample(); example.createCriteria() .andSysDelStateEqualTo(false) .andNeedCsrfEqualTo(true).andSystemCodeEqualTo(systemCode); return resourceUrlMapper.selectByExample(example); }
/** * 拿参数来当key * * @param id * @return */ @Cacheable(value = "demoCache", key = "#id") public Person getPerson2(String id) { log.info("[demoCacheManager]没有缓存,则执行下面内容。"); Person person = new Person(); person.setAge(10); person.setGender("男"); person.setName(id); person.setId(id); return person; }
@Cacheable(value = TRANSFER_APPLICATIONS_CACHE_NAME, key = "#person.personalCode") public List<TransferExchangeDTO> getTransferApplications(Person person) { String url = episServiceUrl + "/exchanges"; log.info("Getting exchanges from {} for {} {}", url, person.getFirstName(), person.getLastName()); ResponseEntity<TransferExchangeDTO[]> response = restTemplate.exchange( url, HttpMethod.GET, new HttpEntity(getHeaders()), TransferExchangeDTO[].class); return asList(response.getBody()); }
/** * Returns the number of product belonging to the given Collection. * <p><b>This method requires roles ROLE_DATA_MANAGER | ROLE_SEARCH.</b> * @param filter an optionnal `where` clause (without the "where" token). * @param collection_uuid the `Id` of the parent collection. * @return number of Products. */ @PreAuthorize ("hasAnyRole('ROLE_DATA_MANAGER','ROLE_SEARCH')") @Transactional (readOnly=true, propagation=Propagation.REQUIRED) @Cacheable (value = "product_count", key = "{#filter, #collection_uuid}") public Integer count(String filter, String collection_uuid) { return productDao.count(filter, collection_uuid); }
@Cacheable @Override public <T extends Properties> T get(Class<T> clazz) { Property entity = propertyRepository.findOne(clazz.getSimpleName()); if (entity != null) { return JsonUtils.fromString(entity.getJson(), clazz); } return null; }
private void addCacheExpires(final Class clazz, final Map<String, Long> cacheExpires) { ReflectionUtils.doWithMethods(clazz, method -> { ReflectionUtils.makeAccessible(method); CacheDuration cacheDuration = findCacheDuration(clazz, method); Cacheable cacheable = findAnnotation(method, Cacheable.class); CacheConfig cacheConfig = findAnnotation(clazz, CacheConfig.class); Set<String> cacheNames = findCacheNames(cacheConfig, cacheable); for (String cacheName : cacheNames) { if (cacheDuration != null) { cacheExpires.put(cacheName, cacheDuration.expireSeconds()); } } }, method -> null != findAnnotation(method, Cacheable.class)); }
/** * 查询指定code的value值,并存到redis,如果redis有值,则直接返回,不访问数据库 * sync = true 表示并发情况下,只允许一个线程访问数据库 * * @param paraCode code * @return 对应的值 */ @Cacheable(value = "mysql:busiSupportCacheService:commSysPara", key = "#paraCode", sync = true) public String getCommSysParaValue(String paraCode) { CommSysParaExample example = new CommSysParaExample(); example.createCriteria().andSysParaCodeEqualTo(paraCode).andSys0DelStateEqualTo((byte) 0); example.setOrderByClause("f_id desc"); PageHelper.startPage(1, 1, false); List<CommSysPara> commSysParas = commSysParaMapper.selectByExample(example); if (commSysParas == null || commSysParas.size() == 0) { return null; } return commSysParas.get(0).getSysParaValue(); }
@Cacheable(value = "mysql:busiSupportCacheService:omsCommSysPara", key = "#paraCode", sync = true) public String getOmsCommSysParaValue(String paraCode) { OmsCommSysParaExample example = new OmsCommSysParaExample(); example.createCriteria().andSysParaCodeEqualTo(paraCode).andSys0DelStateEqualTo((byte) 0); example.setOrderByClause("f_id desc"); PageHelper.startPage(1, 1, false); List<OmsCommSysPara> omsCommSysParas = omsCommSysParaMapper.selectByExample(example); if (omsCommSysParas == null || omsCommSysParas.size() == 0) { return null; } return omsCommSysParas.get(0).getSysParaValue(); }
/** * 通过id查询物品 * @param itemId 物品id * @return 物品信息 */ @Cacheable(cacheNames = "items", keyGenerator="customKeyGenerator") public Item findById(Integer itemId) { Item item = itemRepository.findOne(itemId); if (item != null) { if (item.getItemClass() == 2 || item.getItemClass() == 3 || item.getItemClass() == 4) { // 过滤,减少数据库查询 item.setBonusLists(itemBonusRepository.findBonusListsByItemId(item.getId())); } else { item.setBonusLists(new ArrayList<>(0)); } } return item; }
@Override @Cacheable(value = "git.tags", key = "#node.getPath()", condition = "#refresh == false") public List<String> tags(Node node, boolean refresh) { GitClient client = gitClientInstance(node); try { return client.tags(); } catch (GitException e) { throw new IllegalStatusException("Cannot load tag list from git: " + e.getMessage()); } }
/** * 获取一周内的物品搜索统计 * * @return 统计结果列表 */ @Cacheable(cacheNames = "itemSearchStatistics", keyGenerator="customKeyGenerator") public List<ItemSearchStatisticDTO> findWeeklyItemSearchStatisticsByType(Integer page, Integer size) { List<ItemSearchStatisticDTO> itemSearchStatisticDTOList = new ArrayList<>(size); // 每周 LocalDate localDate = LocalDate.now().plusDays(-7); List<Object[]> result = itemSearchStatisticRepository.findStartFrom(localDate.toString(), page * size, size); for (Object[] itemSearchStatistic : result) { int itemId = ((Number)itemSearchStatistic[0]).intValue(); int searchCount = ((Number)itemSearchStatistic[1]).intValue(); Item item = itemRepository.findOne(itemId); itemSearchStatisticDTOList.add(new ItemSearchStatisticDTO(itemId, item.getName(), item.getIcon(), searchCount, ItemSearchStatisticDTO.WEEKLY)); } return itemSearchStatisticDTOList; }
@Override @Cacheable(cacheNames = CacheConstants.DEVICE_CREDENTIALS_CACHE, unless="#result == null") public DeviceCredentials findDeviceCredentialsByCredentialsId(String credentialsId) { log.trace("Executing findDeviceCredentialsByCredentialsId [{}]", credentialsId); validateString(credentialsId, "Incorrect credentialsId " + credentialsId); return deviceCredentialsDao.findByCredentialsId(credentialsId); }
@Cacheable(value = "telement_role", key = "'role_element_'+#role") public List<TElementVo> getListByRole(String role) { List<TElementVo> resultList = new ArrayList<>(); List<TElement> tElements = mapper.getListByRole(role); tElements.forEach(tElement -> { TElementVo tElementVo = new TElementVo(); BeanUtils.copyProperties(tElement,tElementVo); resultList.add(tElementVo); }); return resultList; }
@Override @Cacheable(value="liquiduser") public User findByUserName(String userName) { Map<String, Object> params = new HashMap<String, Object>(); params.put("userName", userName); List<User> users = ((IUserDao) dao).findAll(params); if (users.isEmpty()) { return null; } else { return users.get(0); } }
@Override @Cacheable(cacheResolver="secondaryCacheResolver" ,unless="#result == null") public List<T> getAll() throws DataAccessException { if (logger.isDebugEnabled()) logger.debug("type {} getAll", type); try { return mongoOperations.findAll(type); } catch (Exception e) { throw new DataAccessException(e); } }
@Cacheable(value = "busiSupport:securityService:userRoles", key = "#p0 + '_' +#p1") @CacheDuration @Override public List<Role> getUserRoleList(String username, Byte accountType) { String systemCode = AccountType.getSystemCode(accountType); CustomerUserDetail userDetail = securityDao.getUserDetailByName(username, accountType, systemCode); return userDetail == null ? null : userDetail.getRoles(); }
@Cacheable( key = "#username", condition = "#username != null" ) @Override public UserDetails loadUserByUsername ( String username ) throws UsernameNotFoundException { if ( StringUtils.isBlank( username ) ) { throw new UsernameNotFoundException( String.format( "该'%s'用户名不存在." , username ) ); } User user = userService.findByUsername( username ); if ( user == null ) { throw new UsernameNotFoundException( String.format( "该'%s'用户名不存在." , username ) ); } // 虽然说可以对SuperAdmin和Root直接放行,但在程序上还是应该让他们有归属,该有的角色和权限信息还是得有 List< Role > roles = roleService.listByUserId( user.getId() ); final List< RolePermissionResource > rolePermissionResources = rolePermissionResourceService.listByUserId( user.getId() ); final List< PermissionResourceVO > permissionResource = permissionResourceService.listUserPermissionByRolePermissionResource( rolePermissionResources ); return new JwtUser( user.getId() , user.getUsername() , user.getPassword() , user.getNickName() , user.getRealName() , user.getEmail() , user.getPhone() , user.getUserImageUrl() , user.getLastPasswordResetDate() , user.getCreateUserId() , user.getCreateTime() , user.getUpdateTime() , user.getRemark() , user.getEnabled() , roles , permissionResource , rolePermissionResources ); }
@Cacheable(cacheNames = "json_result", key = "#type") public String getJsonValue(int type) { log.info("getJsonValue by : " + type); // to know the result is mock data or not. // nature of caching, it will save into cache if there is no key. Result result = resultService.findResultByType(type); String json = null; if(result != null) { json = messageSender.getGson().toJson(getResultDTO(result)); } return json; }
@Cacheable(value = Constants.CACHE_NAMESPACE + "sysParams") public Map<String, String> getAllParams() { Map<String, Object> params = InstanceUtil.newHashMap(); params.put("orderBy", "type_,sort_no"); List<SysParam> list = queryList(params); Map<String, String> resultMap = InstanceUtil.newHashMap(); for (SysParam sysParam : list) { if (sysParam != null) { resultMap.put(sysParam.getParamKey(), sysParam.getParamValue()); } } return resultMap; }
@PreAuthorize ("hasAnyRole('ROLE_DATA_MANAGER','ROLE_SEARCH')") @Transactional (readOnly = true, propagation = Propagation.REQUIRED) @Cacheable (value = "product_count", key = "{#filter, null}") public Integer count(String filter) { return productDao.count(filter, null); }
@Cacheable(CsapCoreService.TIMEOUT_CACHE_60s) synchronized public ArrayNode allAdminUsers () { ArrayNode users = jacksonMapper.createArrayNode() ; // remove calls for other hosts csapApp.getAllPackages() .getServiceInstances( "admin" ) .filter( instance -> ! instance.getHostName().equals( Application.getHOST_NAME() ) ) .map( this::getUsersOnRemoteAdmins ) .forEach( users::addAll ); // add the local host entries users.addAll( getActive() ) ; // now make them distinct HashSet<String> uniqueUsers = new HashSet<>() ; users.forEach( userJson -> uniqueUsers.add( userJson.asText() )); // Now transform users.removeAll() ; uniqueUsers.forEach( users::add ); return users ; }
@PreAuthorize ("hasAnyRole('ROLE_DATA_MANAGER','ROLE_SEARCH')") @Transactional (readOnly=true, propagation=Propagation.REQUIRED) @Cacheable (value = "products", key = "#ids") public List<Product> getProducts (List<Long> ids) { return productDao.read(ids); }