/** * Saves persistently a download performed by a user. * * @param size download size. * @param start_date date downloading start. * @param user associate user to download. */ @Transactional @Caching (evict = { @CacheEvict (value = "network_download_count", key = "#user.getUUID ()", condition = "#user != null"), @CacheEvict (value = "network_download_size", key = "#user.getUUID ()", condition = "#user != null") }) public void createDownloadUsage (final Long size, final Date start_date, final User user) { if (size == null || size < 0 || start_date == null || user == null) { throw new IllegalArgumentException ("Invalid parameters"); } NetworkUsage download_usage = new NetworkUsage (); download_usage.setSize (size); download_usage.setDate (start_date); download_usage.setUser (user); download_usage.setIsDownload (true); networkUsageDao.create (download_usage); }
@Transactional(readOnly = false, propagation = Propagation.REQUIRED) @CacheEvict ( value = { "product_count", "product", "products" }, allEntries = true ) public void removeUnprocessed() { long start = System.currentTimeMillis(); Iterator<Product> products = getUnprocessedProducts(); while (products.hasNext()) { Product product = products.next(); if (product != null) { products.remove(); } } LOGGER.debug("Cleanup incomplete processed products in " + (System.currentTimeMillis() - start) + "ms"); }
@Transactional (readOnly=false, propagation=Propagation.REQUIRED) @Caching (evict = { @CacheEvict(value = "user", allEntries = true), @CacheEvict(value = "userByName", allEntries = true)}) public void resetPassword(String code, String new_password) throws RootNotModifiableException, RequiredFieldMissingException, EmailNotSentException { User u = userDao.getUserFromUserCode (code); if (u == null) { throw new UserNotExistingException (); } checkRoot (u); u.setPassword (new_password); checkRequiredFields (u); userDao.update (u); }
/** * Update given User, after checking required fields. * * @param user * @throws RootNotModifiableException * @throws RequiredFieldMissingException */ @PreAuthorize ("isAuthenticated ()") @Transactional (readOnly=false, propagation=Propagation.REQUIRED) @Caching (evict = { @CacheEvict(value = "user", key = "#user.getUUID ()"), @CacheEvict(value = "userByName", key = "#user.username.toLowerCase()")}) public void selfUpdateUser (User user) throws RootNotModifiableException, RequiredFieldMissingException, EmailNotSentException { User u = userDao.read (user.getUUID ()); checkRoot (u); u.setEmail (user.getEmail ()); u.setFirstname (user.getFirstname ()); u.setLastname (user.getLastname ()); u.setAddress (user.getAddress ()); u.setPhone (user.getPhone ()); u.setCountry (user.getCountry ()); u.setUsage (user.getUsage ()); u.setSubUsage (user.getSubUsage ()); u.setDomain (user.getDomain ()); u.setSubDomain (user.getSubDomain ()); checkRequiredFields (u); userDao.update (u); }
@PreAuthorize ("hasRole('ROLE_DATA_MANAGER')") @Transactional (readOnly=false, propagation=Propagation.REQUIRED) @CacheEvict (value = "products", allEntries = true) public void removeProducts (String uuid, Long[] pids) { collectionDao.removeProducts (uuid, pids, null); long start = new Date ().getTime (); for (Long pid: pids) { try { searchService.index(productDao.read(pid)); } catch (Exception e) { throw new RuntimeException("Cannot update Solr index", e); } } long end = new Date ().getTime (); LOGGER.info("[SOLR] Remove " + pids.length + " product(s) from collection spent " + (end-start) + "ms" ); }
@Transactional (readOnly=false, propagation=Propagation.REQUIRED) @CacheEvict (value = "products", allEntries = true) public void systemAddProduct (String uuid, Long pid, boolean followRights) { Collection collection = collectionDao.read (uuid); Product product = productDao.read (pid); this.addProductInCollection(collection, product); try { searchService.index(product); } catch (Exception e) { throw new RuntimeException("Cannot update Solr index", e); } }
@Override @Transactional(rollbackFor = Exception.class) @Caching(evict = { @CacheEvict(value = "getOneArticleById", key = "#root.target.oneArticleKey + #article.id"), @CacheEvict(value = "getArticlesCount", key = "#root.target.articleCountKey + #username") }) public long insertOneArticle(Article article) { long articleId = idWorker.nextId(); article.setId(articleId); article.setCreatedTime(new Date()); // add the created time article.setModifiedTime(new Date()); // add the modified time articleMapper.insertOneArticle(article); logger.info(article.getUsername() + " insert article " + article.getId() + " successfully"); deleteAllPagesCache(article.getUsername()); return articleId; }
@Override @Transactional(rollbackFor = Exception.class) @CacheEvict(value = "getAllTags", key = "#root.target.allTagsKey + #username") public Tag insertOneTag(String tagName, String username) { Tag isTag = getOneTagByName(tagName, username); // 标签已经存在 if (isTag != null ) { return isTag; } Tag tag = new Tag(); tag.setName(tagName); tag.setUsername(username); tag.setId(idWorker.nextId()); tag.setCreatedTime(new Date()); tag.setModifiedTime(new Date()); tagMapper.insertOneTag(tag); logger.info(username + " insert tag " + tag.getId() + " successfully"); return tag; }
@Override @CacheEvict(cacheNames = "employee", key = "#empID") public void delete(int empID) { logger.info("Запрос к базе на удаление сотрудника с ID: " + empID); String hql = "update EmployeeHistory E set E.isActive = false, " + "E.endDate = :currentTimestamp, E.isDeleted = true" + " where (E.empID = :empID) and (E.isActive = :state)"; Timestamp currentTime = Timestamp.valueOf(LocalDateTime.now()); Session session = getSession(); try{ session.createQuery(hql) .setTimestamp("currentTimestamp", currentTime) .setInteger("empID", empID) .setBoolean("state", true) .executeUpdate(); }catch (HibernateException e){ logger.error(e.getStackTrace()); throw new MyRuntimeException(StuffExceptions.DATABASE_ERROR); } }
@Override @CacheEvict(cacheNames = "employee", key = "#employee.empID", beforeInvocation = true) public Employee updateEmployee(Employee employee) { EmployeeHistory employeeHistory = new EmployeeHistory(employee); logger.info("Запрос к базе на изменение сотрудника с ID: " + employee.getEmpID()); Timestamp currentTime = Timestamp.valueOf(LocalDateTime.now()); String hql = "update EmployeeHistory E set E.isActive = false, E.endDate = :currentTimestamp " + "where (E.empID = :empId) and (E.isActive = :state)"; Session session = getSession(); try { session.createQuery(hql) .setTimestamp("currentTimestamp", currentTime) .setInteger("empId", employee.getEmpID()) .setBoolean("state", true).executeUpdate(); employeeHistory.setStartDate(currentTime); session.save(employeeHistory); } catch (HibernateException e){ logger.error(e.getStackTrace()); throw new MyRuntimeException(StuffExceptions.DATABASE_ERROR); } return read(employee.getEmpID()); }
@Caching(evict = { @CacheEvict(value = CACHE_POST, key = "#post.id.toString()"), @CacheEvict(value = CACHE_COUNT_USER_TAG_POSTS, key = "#post.user.id.toString().concat('_tags_posts_count')", allEntries = true), @CacheEvict(value = TagService.CACHE_COUNT_USER, key = "#post.user.id.toString().concat('_posts_count')") }) @Transactional public void deletePost(Post post) { PostStatus status = post.getStatus(); postRepository.delete(post.getId()); if (status == PostStatus.PUBLIC) { Set<Tag> tags = tagRepository.findPostTags(post.getId()); hotPostService.removeHotPost(post); hotPostService.removeTaggedPost(post, tags); newPostsService.remove(post.getId()); newPostsService.removeTaggedPost(post.getId(), tags); countingService.decPublicPostsCount(); tags.forEach(tagService::decreasePostCountByOne); // 标签文章统计需要减一 } PostSearchService.deleteIndex(post.getId()); countingService.decPostsCount(); }
@Transactional @CacheEvict(value=CACHE_COUNT_USER, key="#userId.toString().concat('_followed_tags_count')") public synchronized Long followTag(Long userId, Tag tag) { User user = userRepository.findOne(userId); if (user.getFollowingTags().contains(tag)) return tag.getFollowersCount(); user.getFollowingTags().add(tag); userRepository.save(user); tag.setFollowersCount(tag.getFollowersCount() + 1); tagRepository.save(tag); return tag.getFollowersCount(); }
@Transactional @CacheEvict(value=CACHE_COUNT_USER, key="#userId.toString().concat('_followed_tags_count')") public synchronized Long unFollowTag(Long userId, Tag tag) { User user = userRepository.findOne(userId); if (!user.getFollowingTags().contains(tag)) return tag.getFollowersCount(); user.getFollowingTags().remove(tag); userRepository.save(user); tag.setFollowersCount(tag.getFollowersCount() - 1); tagRepository.save(tag); return tag.getFollowersCount(); }
@Override @Caching( evict = { @CacheEvict(key="#object.id"), @CacheEvict(cacheResolver="secondaryCacheResolver", allEntries=true) } ) public T delete(T object) throws DataAccessException { if (logger.isDebugEnabled()) logger.debug("type {} delete", type); try { mongoOperations.remove(object); return object; } catch (Exception e) { throw new DataAccessException(e); } }
@Override @CacheEvict( value = GlobalCacheConstant.USER_DETAILS_SERVICE_NAMESPACE, allEntries = true, condition = "#result != null" ) public boolean deleteRelatePermissionResource ( List< PermissionResourceVO > vos ) { final List< Long > resourceIds = vos.parallelStream() .map( PermissionResourceVO::getId ) .collect( Collectors.toList() ); // 删除资源 AssertUtils.isTrue( ! super.deleteBatchIds( resourceIds ) , "资源删除失败" ); // 删除相关角色资源中间表信息 final List< Long > middleIds = rolePermissionResourceService.selectObjs( new Condition() .in( "permission_resource_id" , resourceIds ) .setSqlSelect( "id" ) ); if ( CollectionUtils.isNotEmpty( middleIds ) ) { AssertUtils.isTrue( ! rolePermissionResourceService.deleteBatchIds( middleIds ) , "资源删除失败" ); } return true; }
/** * Patch movie by movie id. * * @param id movie id * @param movie movie object */ @CacheEvict(cacheNames = "movie", key = "#id") public void patchMovie(String id, Movie movie) { try { this.restTemplate.patchForObject("/movies/" + id, new HttpEntity<>(movie), Void.class); } catch (Exception e) { logger.error("Error patching movie: ", e); } }
/** * 数据库标记删除,并删除redis里的存值 * * @param paraCode code */ @CacheEvict(value = "mysql:busiSupportCacheService:commSysPara", key = "#paraCode") public void delCommSysParaValue(String paraCode) { CommSysPara para = new CommSysPara(); para.setSys0DelTime(new Date()); para.setSys0DelState((byte) 1); CommSysParaExample example = new CommSysParaExample(); example.createCriteria().andSysParaCodeEqualTo(paraCode); commSysParaMapper.updateByExampleSelective(para, example); }
@CacheEvict(value = "mysql:busiSupportCacheService:omsCommSysPara", key = "#paraCode") public void delOmsCommSysParaValue(String paraCode) { OmsCommSysPara para = new OmsCommSysPara(); para.setSys0DelTime(new Date()); para.setSys0DelState((byte) 1); OmsCommSysParaExample example = new OmsCommSysParaExample(); example.createCriteria().andSysParaCodeEqualTo(paraCode); omsCommSysParaMapper.updateByExampleSelective(para, example); }
@Caching(// evict = { // @CacheEvict(value = KEY_USER, key = "#id"), // @CacheEvict(value = KEY_USER_FIND, allEntries = true) // }) public void delete(Long id) { userDao.delete(id); }
@Override @Transactional @CacheEvict(value = "env", allEntries = true) public void addVolume(Application application, VolumeAssociationDTO volumeAssociationDTO) throws ServiceException, CheckException { checkVolumeFormat(volumeAssociationDTO); Volume volume = null; if (!volumeService.loadAllVolumes().stream().filter(v -> v.getName().equals(volumeAssociationDTO.getVolumeName())).findAny() .isPresent()) { VolumeList volumeList = null; try { volumeList = dockerClient.listVolumes(); } catch (InterruptedException | DockerException e) { throw new ServiceException("Action failed"); } if(volumeList.volumes().stream().filter(v -> v.name().equals(volumeAssociationDTO.getVolumeName() )).findFirst().orElse(null) == null) { throw new CheckException("This volume does not exist"); } else { volume = volumeService.registerNewVolume(volumeAssociationDTO.getVolumeName()); } } else { volume = volumeService.findByName(volumeAssociationDTO.getVolumeName()); } if(volumeAssociationService.checkVolumeAssociationPathAlreadyPresent(volumeAssociationDTO.getPath(), application.getServer().getId()) > 0) { throw new CheckException("This path is already use !"); } VolumeAssociation volumeAssociation = new VolumeAssociation(new VolumeAssociationId(application.getServer(), volume), volumeAssociationDTO.getPath(), volumeAssociationDTO.getMode()); volumeService.saveAssociation(volumeAssociation); volume.getVolumeAssociations().add(volumeAssociation); application.getServer().getVolumeAssociations().add(volumeAssociation); stopAndRemoveServer(application.getServer(), application); recreateAndMountVolumes(application.getServer(), application); }
@Transactional (readOnly=false, propagation=Propagation.REQUIRED) @CacheEvict (value = {"indexes"}, key = "#product_id") public void setIndexes(Long product_id, List<MetadataIndex>indexes) { Product product = productDao.read (product_id); product.setIndexes (indexes); productDao.update (product); }
/** * Create given User, after checking required fields. * No @PreAuthorize. * * @param user * @throws RequiredFieldMissingException * @throws RootNotModifiableException */ @Transactional(readOnly=false) @CacheEvict(value = "userByName", key = "#user?.getUsername().toLowerCase()") public void systemCreateUser(User user) throws RequiredFieldMissingException, RootNotModifiableException, EmailNotSentException { checkRequiredFields(user); checkRoot(user); userDao.create(user); }
/** * Delete user corresponding to given id. * * @param uuid User id. * @throws RootNotModifiableException */ @PreAuthorize ("hasRole('ROLE_USER_MANAGER')") @Transactional (readOnly=false, propagation=Propagation.REQUIRED) @Caching (evict = { @CacheEvict(value = "user", allEntries = true), @CacheEvict(value = "userByName", allEntries = true)}) public void deleteUser (String uuid) throws RootNotModifiableException, EmailNotSentException { User u = userDao.read (uuid); checkRoot (u); SecurityContextProvider.forceLogout (u.getUsername ()); userDao.removeUser (u); }
@PreAuthorize ("hasRole('ROLE_DATA_MANAGER')") @Transactional (readOnly=false, propagation=Propagation.REQUIRED) @CacheEvict (value = "products", allEntries = true) public void addProducts (String uuid, Long[] pids) { for (int i = 0; i < pids.length; i++) { systemAddProduct (uuid, pids[i], true); } }
@Transactional @CacheEvict (value = "products", allEntries = true) public void addProductInCollection(Collection collection, Product product) { Collection c = collectionDao.read(collection.getUUID()); if (!c.getProducts().contains(product)) { c.getProducts().add(product); collectionDao.update(c); } }
@PreAuthorize ("hasRole('ROLE_SYSTEM_MANAGER')") @Transactional (readOnly=false, propagation=Propagation.REQUIRED) @Caching (evict = { @CacheEvict (value = "user", allEntries = true), @CacheEvict (value = "userByName", allEntries = true)}) public void changeRootPassword (String new_pwd, String old_pwd) { User root = userDao.getByName ( cfgManager.getAdministratorConfiguration ().getName ()); PasswordEncryption encryption = root.getPasswordEncryption (); if (encryption != PasswordEncryption.NONE) { try { MessageDigest md = MessageDigest.getInstance( encryption.getAlgorithmKey()); old_pwd = new String( Hex.encode(md.digest(old_pwd.getBytes("UTF-8")))); } catch (Exception e) { throw new UserBadEncryptionException ( "There was an error while encrypting password of root user", e); } } if ( (old_pwd == null) || ("".equals (old_pwd)) || ( !root.getPassword ().equals (old_pwd))) throw new SecurityException ("Wrong password."); if ( (new_pwd == null) || "".equals (new_pwd.trim ())) throw new SecurityException ("New password cannot be empty."); String password = new_pwd.trim (); root.setPassword (password); userDao.update (root); }
@Override @Transactional(rollbackFor = Exception.class) @Caching(evict = { @CacheEvict(value = "getOneArticleById", key = "#root.target.oneArticleKey + #articleTag.articleId"), @CacheEvict(value = "getOneTagById", key = "#root.target.oneTagKey + #tagId"), @CacheEvict(value = "getAllTags", key = "#root.target.allTagsKey + #username") }) public boolean insertOneArticleTag(ArticleTag articleTag, String username) { articleTagMapper.insertOneArticleTag(articleTag); logger.info(username + " insert articleTag " + articleTag.toString() + " successfully"); return true; }
@Override @Transactional(rollbackFor = Exception.class) @Caching(evict = { @CacheEvict(value = "getOneArticleById", key = "#root.target.oneArticleKey + #articleTag.articleId"), @CacheEvict(value = "getOneTagById", key = "#root.target.oneTagKey + #tagId"), @CacheEvict(value = "getAllTags", key = "#root.target.allTagsKey + #username") }) public boolean deleteOneArticleTag(ArticleTag articleTag, String username) { articleTagMapper.deleteOneArticleTag(articleTag); logger.info(username + " delete articleTag " + articleTag.toString() + " successfully"); return true; }
@Override @Transactional(rollbackFor = Exception.class) @Caching(evict = { @CacheEvict(value = "getOneArticleById", key = "#root.target.oneArticleKey + #articleId"), @CacheEvict(value = "getArticlesCount", key = "#root.target.articleCountKey + #username") }) public boolean deleteOneArticleById(long articleId, String username) { articleMapper.deleteOneArticleById(articleId); logger.info(username + " delete article " + articleId + " successfully"); deleteAllPagesCache(username); // delete all pages' cache return true; }
@Override @Transactional(rollbackFor = Exception.class) @Caching(evict = { @CacheEvict(value = "getOneArticleById", key = "#root.target.oneArticleKey + #article.id"), @CacheEvict(value = "getArticlesOfOnePage", key = "#username + #page") }) public boolean updateOneArticle(Article article, String username, int page) { // note: article object only contains id, title, body property article.setModifiedTime(new Date()); articleMapper.updateOneArticle(article); logger.info(username + " update article " + article.getId() + " successfully"); return true; }
@Override @Transactional(rollbackFor = Exception.class) @Caching(evict = { @CacheEvict(value = "getOneTagById", key = "#root.target.oneTagKey + #tagId"), @CacheEvict(value = "getAllTags", key = "#root.target.allTagsKey + #username") }) public boolean deleteOneTagById(long tagId, String username) { tagMapper.deleteOneTagById(tagId); logger.info(username + " delete tag " + tagId + " successfully"); return true; }
@PostMapping("/save") @CacheEvict(cacheNames = "product", key = "123") public ModelAndView save(@Valid ProductForm form, BindingResult bindingResult, Map<String, Object> map) { if (bindingResult.hasErrors()) { map.put("msg", bindingResult.getFieldError().getDefaultMessage()); map.put("url", "/seller/product/index"); return new ModelAndView("common/error", map); } try { ProductInfo productInfo = new ProductInfo(); //更新 if (!StringUtils.isEmpty(form.getProductId())) { productInfo = productService.findOne(form.getProductId()); } //新增 else { form.setProductId(KeyUtil.genUniqueKey()); } BeanUtils.copyProperties(form, productInfo); productService.save(productInfo); } catch (Exception ex) { map.put("msg", ex.getMessage()); map.put("url", "/seller/product/index"); return new ModelAndView("common/error", map); } map.put("url", "/seller/product/list"); return new ModelAndView("common/success", map); }
@Scheduled(cron = STUDENT_NEIGHBORHOOD_CACHE_EVICT_CRON) @CacheEvict(value = STUDENT_NEIGHBORHOOD_CACHE_NAME, allEntries = true) public void rebuildStudentNeighborhood() { log.info("Cleared student neighborhood cache"); studentNeighborhoodStore.getStudentNeighborhood(); // causes the data model to be rebuilt and cached }
@CacheEvict(value = "user", key = "#user.getId()") public User createUser(User user) { User result = null; if(!userRepository.exists(user.getId())) { result = userRepository.save(user); } return result; }
@CacheEvict(value = "user", key = "#id") public boolean deleteUser(Long id) { boolean deleted = false; if (userRepository.exists(id)) { userRepository.delete(id); deleted = true; } return deleted; }
@Caching(evict = { @CacheEvict(value = TRANSFER_APPLICATIONS_CACHE_NAME, key = "#person.personalCode"), @CacheEvict(value = CONTACT_DETAILS_CACHE_NAME, key = "#person.personalCode"), @CacheEvict(value = ACCOUNT_STATEMENT_CACHE_NAME, key = "#person.personalCode") }) public void clearCache(Person person) { clearTransferApplicationsCache(person); clearContactDetailsCache(person); clearAccountStatementCache(person); }
@CacheEvict(value="settingsCache", allEntries = true) public void update(Map<String, String> maps) { if(null == maps || maps.size() == 0) { return; } maps.forEach((key,val)->{ settingsMapper.updateForKey(key, val); }); }
@Override @Caching(evict = {@CacheEvict(cacheNames = "empCertificates", key = "#certificate.ownerId", beforeInvocation = true)}) public void create(Certificate certificate) { logger.info("Запрос к базе на создание сертификата"); Session session = getSession(); try { session.save(certificate); } catch (Exception ex) { logger.error(ex.getStackTrace()); throw new MyRuntimeException(StuffExceptions.DATABASE_ERROR); } }
@Override @Caching(evict = {@CacheEvict(cacheNames = "empCertificates", allEntries = true, beforeInvocation = true)}) public void deleteCertByNum(int certNum) { logger.info("Запрос к базе на удаление сертификата с номером: " + certNum); Session session = getSession(); try { session.createQuery("DELETE Certificate C where C.number = :certNum") .setParameter("certNum", certNum).executeUpdate(); } catch (Exception ex) { logger.error(ex.getStackTrace()); throw new MyRuntimeException(StuffExceptions.DATABASE_ERROR); } }