@Test @Transactional public void createBrand() throws Exception { int databaseSizeBeforeCreate = brandRepository.findAll().size(); // Create the Brand restBrandMockMvc.perform(post("/api/brands") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(brand))) .andExpect(status().isCreated()); // Validate the Brand in the database List<Brand> brandList = brandRepository.findAll(); assertThat(brandList).hasSize(databaseSizeBeforeCreate + 1); Brand testBrand = brandList.get(brandList.size() - 1); assertThat(testBrand.getName()).isEqualTo(DEFAULT_NAME); assertThat(testBrand.getStartDate()).isEqualTo(DEFAULT_START_DATE); }
@Override @Transactional(readOnly=false) public long saveGraph(String graphName) { Object[] args = new Object[1]; args[0] = graphName; Map<String, Object> params = new HashMap<String, Object>(); params.put("name", graphName); MapSqlParameterSource sqlParameterSource = new MapSqlParameterSource(params); KeyHolder keyHolder = new GeneratedKeyHolder(); getNamedParameterJdbcTemplate().update("INSERT INTO " + schema + "waygraphs (name) VALUES (:name)", sqlParameterSource, keyHolder, new String[] {"id"}); return Long.class.cast(keyHolder.getKey()); }
@Transactional public User create(String tenantSchema, final User user) { final String sql = MessageFormat.format(TENANT_SQL_TEMPLATE, tenantSchema, "insert into user(name,password) values(?,?)"); KeyHolder holder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ps.setString(1, user.getName()); ps.setString(2, user.getPassword()); return ps; } }, holder); int newUserId = holder.getKey().intValue(); user.setId(newUserId); return user; }
@Test @Transactional public void deleteXmEntity() throws Exception { // Initialize the database xmEntityService.save(xmEntity); int databaseSizeBeforeDelete = xmEntityRepository.findAll().size(); // Get the xmEntity restXmEntityMockMvc.perform(delete("/api/xm-entities/{id}", xmEntity.getId()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); // Validate Elasticsearch is empty boolean xmEntityExistsInEs = xmEntitySearchRepository.exists(xmEntity.getId()); assertThat(xmEntityExistsInEs).isFalse(); // Validate the database is empty List<XmEntity> xmEntityList = xmEntityRepository.findAll(); assertThat(xmEntityList).hasSize(databaseSizeBeforeDelete - 1); }
@Test @Transactional public void deleteDepartment() throws Exception { // Initialize the database departmentRepository.saveAndFlush(department); int databaseSizeBeforeDelete = departmentRepository.findAll().size(); // Get the department restDepartmentMockMvc.perform(delete("/api/departments/{id}", department.getId()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); // Validate the database is empty List<Department> departmentList = departmentRepository.findAll(); assertThat(departmentList).hasSize(databaseSizeBeforeDelete - 1); }
/** * Add new shopping list for a given user * * @param userName * name of the user for which to create the new list * @param newListName * name of the new list * @return newly created list * @throws UserNotFoundException * if user with given name doesn't exist * @throws ListTooLongException if size of the list containing ShoppingLists would exceed limit of Short type after adding new ShoppingList */ @PreAuthorize("hasRole('USER')") @Transactional(readOnly = false) public ShoppingList addShoppingListToUserByName(String userName, String newListName) { LOGGER.debug("addShoppingListToUserByName: user: {}, listName: {}", userName, newListName); AppUser user = getUser(userName); //throws UserNotFoundException // get count of user lists short count = shoppingListRepository.countByOwnerName(userName); if (count == Short.MAX_VALUE) throw new ListTooLongException(ListTooLongException.listType.SHOPPING_LIST, user.getId()); count++; ShoppingList list = user.addShoppingList(newListName, count); list = shoppingListRepository.save(list); LOGGER.info("addShoppingListToUserByName: Created new list: {}", list); return list; }
@Override @Transactional(rollbackFor = Exception.class) public void update(SysUserEntity user) throws Exception { if (StringUtils.isBlank(user.getPassword())) { user.setPassword(null); } else { user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex()); } sysUserDao.update(user); //检查角色是否越权 checkRole(user); //保存用户与角色关系 sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList()); }
@Transactional public long create(String cluster, String path, String data, User creator, Action action, ReviewStatus reviewStatus) throws ShepherException { if (creator == null) { throw ShepherException.createIllegalParameterException(); } Stat stat = nodeDAO.getStat(cluster, path, true); long snapshotId = snapshotBiz.getOriginalId(path, cluster, ReviewUtil.DEFAULT_CREATOR, stat, action, true); long newSnapshotId = snapshotBiz.create(cluster, path, data, creator.getName(), action, ReviewUtil.DEFAULT_MTIME, ReviewStatus.NEW, stat.getVersion() + 1, ReviewUtil.DEFAULT_REVIEWER).getId(); Set<String> masters = teamBiz.listUserNamesByPathAndUser(creator.getId(), cluster, path, Role.MASTER); String reviewers = this.asStringReviewers(masters); long reviewId = reviewBiz.create(cluster, path, snapshotId, newSnapshotId, reviewStatus, creator.getName(), ReviewUtil.DEFAULT_REVIEWER, action).getId(); logger.info("Create review request, reviewId={}, creator={}, reviewers={}", reviewId, creator, reviewers); mailSenderFactory.getMailSender().noticeUpdate(masters, creator.getName(), path, cluster, serverUrl + "/reviews/" + reviewId); return reviewId; }
@Override @Transactional public void edit(HierarchyTopic topic) { HierarchyTopic oldTopic = dao.findById(topic.getId()); ensureEditRights(oldTopic); dao.unlinkFromSession(oldTopic); topic.setListPosition(oldTopic.getListPosition()); dao.deleteAny(oldTopic.getName()); dao.deleteAny(oldTopic.getShortDescription()); dao.deleteAny(oldTopic.getLongDescription()); dao.deleteAny(oldTopic.getResultsSectionName()); dao.deleteAny(oldTopic.getSubtopicsSectionName()); dao.saveOrUpdate(topic); }
@Test @Transactional public void testUpdate() { User user = new User(); user.setId(UUID.randomUUID().toString()); user.setName("tom"); JpaUtil.persist(user); user = new User(); user.setId(UUID.randomUUID().toString()); user.setName("lisi"); JpaUtil.persist(user); Linu linu = JpaUtil.linu(User.class); linu.equal("name", "lisi").set("name", "kevin"); Assert.isTrue(linu.update() == 1, "Not Success."); JpaUtil.removeAll(User.class); }
@Override @Transactional(rollbackFor=Exception.class) public boolean bindAgent(Integer appId, String appAgentList) { if (null == appId) { return false; } String[] arr = appAgentList.split(","); for(String appAgent: arr){ String[] info = appAgent.split("[_]"); if(info==null||info.length!=2){ continue; } AppAgent app =new AppAgent(); app.setAppId(appId); app.setIp(info[0].trim()); app.setAssetId(info[1].trim()); supervisorDao.addAppAgent(app); } noticeHeartbeat(); return true; }
@Transactional @Override public boolean addJobTrigger(ScheduleJobEntity job) { try { Scheduler scheduler = schedulerFactoryBean.getScheduler(); // 表达式调度构建器 CronScheduleBuilder scheduleBuilder = CronScheduleBuilder .cronSchedule(job.getCronExpression()); // 按新的cronExpression表达式构建一个新的trigger CronTrigger trigger = newTrigger() .forJob(job.getJobKey()) //绑定job .withIdentity(job.getTriggerKey()) .startAt(job.getStartDate()) // job开始日期 .endAt(job.getEndDate())// job结束日期 .withSchedule(scheduleBuilder).build(); // 将trigger添加到quartz的scheduler容器 scheduler.scheduleJob(trigger); return Boolean.TRUE; } catch (SchedulerException e) { throw new ServiceException(e); } }
@Override @Transactional(readOnly=true) public List<ISubscription> getSubscriptionsForGraph(String graphName, String groupName) { if (groupName == null) { return getSubscriptionsForGraph(graphName); } else { Object[] args = new Object[2]; args[0] = graphName; args[1] = groupName; // <graphName> => lies waygraphs => <graph_id> => lies subscription_groups => <group_id> => lies subscriptions return getJdbcTemplate().query("SELECT s.*, sg.name AS group_name, sg.graph_id AS group_graph_id, wg.name AS graph_name " + "FROM " + schema + "subscriptions AS s, " + schema + "subscription_groups AS sg " + "LEFT JOIN " + schema + "waygraphs AS wg ON sg.graph_id = wg.id " + "WHERE s.group_id = sg.id AND sg.graph_id = (SELECT w.id FROM " + schema + "waygraphs AS w WHERE name = ?) " + "AND sg.name = ?", args, subscriptionRowMapper); } }
@Override @Transactional(propagation = Propagation.MANDATORY) public ListMultimap<Item, Attachment> getAttachmentsForItems(Collection<Item> items) { if( items.isEmpty() ) { return ImmutableListMultimap.of(); } List<Attachment> attachments = getHibernateTemplate().findByNamedParam( "select a from Item i join i.attachments a where i in (:items) order by index(a) ASC", "items", items); ListMultimap<Item, Attachment> multiMap = ArrayListMultimap.create(); for( Attachment attachment : attachments ) { multiMap.put(attachment.getItem(), attachment); } return multiMap; }
@Override @Transactional @RequiresPrivilege(priv = "EDIT_SYSTEM_SETTINGS") public void delete(long id) { MimeEntry mime = mimeEntryDao.findById(id); if( mime == null ) { throw new NotFoundException("MimeEntry with id " + id + " not found."); } if( MimeMigrator.EQUELLA_TYPES.contains(mime.getType()) ) { throw new AccessDeniedException("You cannot remove the equella/* mime types"); } mimeEntryDao.delete(mime); mimeTypesChanged(); }
@Transactional public void delete(SurveyDirectory parentDirectory) { String id=parentDirectory.getId(); //目录ID,为1的为系统默认注册用户目录不能删除 if(!"1".equals(id)){ //设为不可见 parentDirectory.setVisibility(0); Criterion criterion=Restrictions.eq("parentId", parentDirectory.getId()); List<SurveyDirectory> directories=findList(criterion); if(directories!=null){ for (SurveyDirectory surveyDirectory : directories) { delete(surveyDirectory); } } } }
@Test @Transactional public void getLevel() throws Exception { // Initialize the database levelRepository.saveAndFlush(level); // Get the level restLevelMockMvc.perform(get("/api/levels/{id}", level.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.id").value(level.getId().intValue())) .andExpect(jsonPath("$.name").value(DEFAULT_NAME.toString())) .andExpect(jsonPath("$.description").value(DEFAULT_DESCRIPTION.toString())); }
/** * Creates or updates a bookmark. If created, the ID of the bookmark will be set by this method. */ @Transactional public void createOrUpdateBookmark(Bookmark bookmark) { int n = update("update bookmark set position_millis=?, comment=?, changed=? where media_file_id=? and username=?", bookmark.getPositionMillis(), bookmark.getComment(), bookmark.getChanged(), bookmark.getMediaFileId(), bookmark.getUsername()); if (n == 0) { update("insert into bookmark (" + INSERT_COLUMNS + ") values (" + questionMarks(INSERT_COLUMNS) + ")", bookmark.getMediaFileId(), bookmark.getPositionMillis(), bookmark.getUsername(), bookmark.getComment(), bookmark.getCreated(), bookmark.getChanged()); int id = queryForInt("select id from bookmark where media_file_id=? and username=?", 0, bookmark.getMediaFileId(), bookmark.getUsername()); bookmark.setId(id); } }
@Transactional(rollbackFor = ServiceException.class) public void transfer(String sourceAcctId, String targetAcctId, double amount) throws ServiceException { this.nativeAccountService.decreaseAmount(sourceAcctId, amount); this.increaseAmount(targetAcctId, amount); // throw new ServiceException("rollback"); }
@Test @Transactional public void createUserWithExistingEmail() throws Exception { // Initialize the database userRepository.saveAndFlush(user); int databaseSizeBeforeCreate = userRepository.findAll().size(); Set<String> autorities = new HashSet<>(); autorities.add("ROLE_USER"); ManagedUserVM managedUserVM = new ManagedUserVM( null, "anotherlogin", DEFAULT_PASSWORD, DEFAULT_FIRSTNAME, DEFAULT_LASTNAME, DEFAULT_EMAIL, // this email should already be used true, DEFAULT_IMAGEURL, DEFAULT_LANGKEY, null, null, null, null, autorities); // Create the User restUserMockMvc.perform(post("/api/users") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isBadRequest()); // Validate the User in the database List<User> userList = userRepository.findAll(); assertThat(userList).hasSize(databaseSizeBeforeCreate); }
@Test @Transactional public void updateImageResource() throws Exception { // Initialize the database imageResourceRepository.saveAndFlush(imageResource); int databaseSizeBeforeUpdate = imageResourceRepository.findAll().size(); // Update the imageResource imageResource.setName(UPDATED_NAME); imageResource.setLoResImage(UPDATED_LO_RES_IMAGE); imageResource.setLoResImageContentType(UPDATED_LO_RES_IMAGE_CONTENT_TYPE); imageResource.setHiResImage(UPDATED_HI_RES_IMAGE); imageResource.setHiResImageContentType(UPDATED_HI_RES_IMAGE_CONTENT_TYPE); restImageResourceMockMvc.perform(put("/api/imageResources") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(imageResource))) .andExpect(status().isOk()); // Validate the ImageResource in the database List<ImageResource> imageResources = imageResourceRepository.findAll(); assertThat(imageResources).hasSize(databaseSizeBeforeUpdate); ImageResource testImageResource = imageResources.get(imageResources.size() - 1); assertThat(testImageResource.getName()).isEqualTo(UPDATED_NAME); assertThat(testImageResource.getLoResImage()).isEqualTo(UPDATED_LO_RES_IMAGE); assertThat(testImageResource.getLoResImageContentType()).isEqualTo(UPDATED_LO_RES_IMAGE_CONTENT_TYPE); assertThat(testImageResource.getHiResImage()).isEqualTo(UPDATED_HI_RES_IMAGE); assertThat(testImageResource.getHiResImageContentType()).isEqualTo(UPDATED_HI_RES_IMAGE_CONTENT_TYPE); }
@Override @Transactional public RoleEntity removePrivilegeFromRole(String code, String privilegeName) { RolePrivilegeEntity userRole = rolePrivilegeRepository.findByRoleCodeAndPrivilegeName(code, privilegeName); rolePrivilegeRepository.delete(userRole); return findRoleByCode(code); }
@Transactional public Package downloadPackage(PackageMetadata packageMetadata) { Assert.notNull(packageMetadata, "Can't download PackageMetadata, it is a null value."); // Database contains the package file from a previous upload if (packageMetadata.getPackageFile() != null) { return deserializePackageFromDatabase(packageMetadata); } else { return downloadAndDeserializePackage(packageMetadata); } }
@Test @Transactional public void equalsVerifier() throws Exception { TestUtil.equalsVerifier(Balance.class); Balance balance1 = new Balance(); balance1.setId(1L); Balance balance2 = new Balance(); balance2.setId(balance1.getId()); assertThat(balance1).isEqualTo(balance2); balance2.setId(2L); assertThat(balance1).isNotEqualTo(balance2); balance1.setId(null); assertThat(balance1).isNotEqualTo(balance2); }
@Override @Transactional(propagation=Propagation.REQUIRES_NEW) public void update(IGraphImportState graphImportState) { Object[] args = new Object[3]; args[0] = graphImportState.getServerName(); args[1] = graphImportState.getViewName(); args[2] = graphImportState.getVersion(); Boolean entryExists = getJdbcTemplate().queryForObject("SELECT EXISTS (SELECT servername FROM " + schema + GRAPH_IMPORT_STATES_TABLE + " WHERE servername = ? AND viewname = ? AND version = ?)", args, Boolean.class); if (entryExists != null && entryExists) { args = new Object[4]; args[0] = graphImportState.getState().toString(); args[1] = graphImportState.getServerName(); args[2] = graphImportState.getViewName(); args[3] = graphImportState.getVersion(); getJdbcTemplate().update("UPDATE " + schema + GRAPH_IMPORT_STATES_TABLE + " SET state = ? " + "WHERE servername = ? AND viewname = ? AND version = ?", args); } else { args = new Object[4]; args[0] = graphImportState.getServerName(); args[1] = graphImportState.getViewName(); args[2] = graphImportState.getVersion(); args[3] = graphImportState.getState().toString(); getJdbcTemplate().update("INSERT INTO " + schema + GRAPH_IMPORT_STATES_TABLE + " (servername, viewname, version, state, timestamp) " + " VALUES (?, ?, ?, ?, now())", args); } }
@Test @Transactional public void getPhotoLocationBeacon() throws Exception { // Initialize the database photoLocationBeaconRepository.saveAndFlush(photoLocationBeacon); // Get the photoLocationBeacon restPhotoLocationBeaconMockMvc.perform(get("/api/photoLocationBeacons/{id}", photoLocationBeacon.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.id").value(photoLocationBeacon.getId().intValue())) .andExpect(jsonPath("$.x").value(DEFAULT_X)) .andExpect(jsonPath("$.y").value(DEFAULT_Y)) .andExpect(jsonPath("$.tolerance").value(DEFAULT_TOLERANCE)); }
@Override @Transactional(readOnly = false) public void deleteConfigurationValue(String env, String key) { Map<String, Object> paramMap = new HashMap<>(); paramMap.put("config_key", key); paramMap.put("config_env", env); namedParameterJdbcTemplate.update(this.deleteQuery, paramMap); }
@Transactional(readOnly = false) @Override public void deleteById(String userId) { Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("userId", userId); //删除用户角色中间表数据 userRoleService.deleteUserRoleByUserId(userId); //删除用户群组中间表数据 userGroupService.deleteSysUserGroupByUserIdOrGroupId(userId,null); //删除用户表数据 userDao.delete(userId); }
@Override @Transactional(readOnly=true) public boolean checkIfGraphExists(String graphName) { Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("graphName", graphName); return getNamedParameterJdbcTemplate().queryForObject("SELECT EXISTS (SELECT name FROM " + schema + "waygraphs WHERE name = :graphName)", paramMap, Boolean.class); }
@Override @Transactional(rollbackFor = Exception.class) public Map<String, Object> createToken(long userId) throws Exception { //生成一个token String token = UUID.randomUUID().toString(); //当前时间 LocalDate now = LocalDate.now(); //过期时间 LocalDateTime expireTime = LocalDateTime.now().plusHours(12); //判断是否生成过token TokenEntity tokenEntity = queryByUserId(userId); if (tokenEntity == null) { tokenEntity = new TokenEntity(); tokenEntity.setUserId(userId); tokenEntity.setToken(token); tokenEntity.setUpdateTime(now); tokenEntity.setExpireTime(expireTime); //保存token save(tokenEntity); } else { tokenEntity.setToken(token); tokenEntity.setUpdateTime(now); tokenEntity.setExpireTime(expireTime); //更新token update(tokenEntity); } Map<String, Object> map = new HashMap<>(16); map.put("token", token); map.put("expire", EXPIRE); return map; }
@Override @Transactional public void delete(String id) { //设为不可见 QuestionBank questionBank=get(id); questionBank.setVisibility(0); questionBankDao.save(questionBank); Criterion criterion=Restrictions.eq("parentId", questionBank.getId()); List<QuestionBank> banks=findList(criterion); if(banks!=null){ for (QuestionBank questionBank2 : banks) { delete(questionBank2); } } }
@Test @Transactional public void searchSubCategory() throws Exception { // Initialize the database subCategoryService.save(subCategory); // Search the subCategory restSubCategoryMockMvc.perform(get("/api/_search/sub-categories?query=id:" + subCategory.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(subCategory.getId().intValue()))) .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString()))); }
@Override @Transactional(readOnly=false) public void save(ISource source) { Map<String, Object> params = new HashMap<String, Object>(); params.put("sourceName", source.getName()); MapSqlParameterSource sqlParameterSource = new MapSqlParameterSource(params); KeyHolder keyHolder = new GeneratedKeyHolder(); getNamedParameterJdbcTemplate().update("INSERT INTO " + schema + "sources (name) VALUES (:sourceName)", sqlParameterSource, keyHolder, new String[] {"id"}); int id = Integer.class.cast(keyHolder.getKey()); source.setId(id); }
@Override @Transactional(readOnly = true) public List<Event> findForUser(final String email) { Event example = new Event(); CalendarUser cu = new CalendarUser(); cu.setEmail(email); example.setOwner(cu); return repository.findAll(Example.of(example)); }
@Test @Transactional public void getNonExistingTag() throws Exception { // Get the tag restTagMockMvc.perform(get("/api/tags/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); }
@Override @Transactional(propagation = Propagation.NEVER) public void itemOperationEvent(ItemOperationEvent event) { try { operateAll(event.getOperation(), null); } catch( WorkflowException ex ) { logger.error(CurrentLocale.get("com.tle.core.services.item.error.operation"), ex); } }