Java Code Examples for org.springframework.transaction.annotation.Transactional

The following are top voted examples for showing how to use org.springframework.transaction.annotation.Transactional. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: spring-io   File: BrandResourceIntTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 2
Project: graphium   File: WayGraphVersionMetadataDaoImpl.java   View source code 6 votes vote down vote up
@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());
}
 
Example 3
Project: multitenancybymycat   File: UserDao.java   View source code 6 votes vote down vote up
@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;
}
 
Example 4
Project: xm-ms-entity   File: XmEntityResourceIntTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 5
Project: TorgCRM-Server   File: DepartmentResourceIntTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 6
Project: codemotion-2017-taller-de-jhipster   File: TaskResourceIntTest.java   View source code 6 votes vote down vote up
@Test
@Transactional
@WithMockUser(username="[email protected]",authorities={"ROLE_USER"}, password = "user")
public void deleteTaskWithUser() throws Exception {
    // Initialize the database
    taskRepository.saveAndFlush(taskUser);
    int databaseSizeBeforeDelete = taskRepository.findAll().size();

    // Get the task
    restTaskMockMvc.perform(delete("/api/tasks/{id}", taskUser.getId())
        .accept(TestUtil.APPLICATION_JSON_UTF8))
        .andExpect(status().isOk());

    // Validate the database is empty
    List<Task> taskList = taskRepository.findAll();
    assertThat(taskList).hasSize(databaseSizeBeforeDelete - 1);
}
 
Example 7
Project: Smart-Shopping   File: RepositoryService.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 8
Project: my-spring-boot-project   File: SysUserServiceImpl.java   View source code 6 votes vote down vote up
@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());
}
 
Example 9
Project: shepher   File: ReviewService.java   View source code 6 votes vote down vote up
@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;
}
 
Example 10
Project: patient-portal   File: AccountResourceIntTest.java   View source code 6 votes vote down vote up
@Test
@Transactional
public void testFinishPasswordResetTooSmall() throws Exception {
    User user = new User();
    user.setPassword(RandomStringUtils.random(60));
    user.setLogin("finish-password-reset-too-small");
    user.setEmail("[email protected]");
    user.setResetDate(Instant.now().plusSeconds(60));
    user.setResetKey("reset key too small");
    userRepository.saveAndFlush(user);

    KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM();
    keyAndPassword.setKey(user.getResetKey());
    keyAndPassword.setNewPassword("foo");

    restMvc.perform(
        post("/api/account/reset_password/finish")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
        .andExpect(status().isBadRequest());

    User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null);
    assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isFalse();
}
 
Example 11
Project: Equella   File: HierarchyServiceImpl.java   View source code 6 votes vote down vote up
@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);
}
 
Example 12
Project: linq   File: LinuTests.java   View source code 6 votes vote down vote up
@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);
}
 
Example 13
Project: supervisor   File: AppServiceImpl.java   View source code 6 votes vote down vote up
@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;
}
 
Example 14
Project: webside   File: ScheduleJobServiceImpl.java   View source code 6 votes vote down vote up
@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);
	}
}
 
Example 15
Project: graphium   File: SubscriptionDaoImpl.java   View source code 6 votes vote down vote up
@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);
	}
}
 
Example 16
Project: Equella   File: ItemDaoImpl.java   View source code 6 votes vote down vote up
@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;
}
 
Example 17
Project: Equella   File: MimeTypeServiceImpl.java   View source code 6 votes vote down vote up
@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();
}
 
Example 18
Project: DWSurvey   File: SurveyDirectoryManagerImpl.java   View source code 6 votes vote down vote up
@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);
			}
		}
	}
}
 
Example 19
Project: buenojo   File: LevelResourceIntTest.java   View source code 5 votes vote down vote up
@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()));
}
 
Example 20
Project: airsonic   File: BookmarkDao.java   View source code 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 21
Project: ByteJTA-sample   File: MultiDsTransferServiceImpl.java   View source code 5 votes vote down vote up
@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");
}
 
Example 22
Project: devoxxus-jhipster-microservices-demo   File: UserResourceIntTest.java   View source code 5 votes vote down vote up
@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);
}
 
Example 23
Project: buenojo   File: ImageResourceResourceTest.java   View source code 5 votes vote down vote up
@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);
  }
 
Example 24
Project: theskeleton   File: RoleServiceImpl.java   View source code 5 votes vote down vote up
@Override
@Transactional
public RoleEntity removePrivilegeFromRole(String code, String privilegeName) {
	RolePrivilegeEntity userRole = rolePrivilegeRepository.findByRoleCodeAndPrivilegeName(code, privilegeName);
	rolePrivilegeRepository.delete(userRole);
	return findRoleByCode(code);
}
 
Example 25
Project: spring-cloud-skipper   File: PackageService.java   View source code 5 votes vote down vote up
@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);
	}
}
 
Example 26
Project: xm-ms-balance   File: BalanceResourceIntTest.java   View source code 5 votes vote down vote up
@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);
}
 
Example 27
Project: graphium   File: GraphImportStateDaoImpl.java   View source code 5 votes vote down vote up
@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);			
	}

}
 
Example 28
Project: buenojo   File: PhotoLocationBeaconResourceTest.java   View source code 5 votes vote down vote up
@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));
}
 
Example 29
Project: Armory   File: AccountResourceIntTest.java   View source code 5 votes vote down vote up
@Test
@Transactional
public void testRegisterAdminIsIgnored() throws Exception {
    ManagedUserVM validUser = new ManagedUserVM(
        null,                   // id
        "badguy",               // login
        "password",             // password
        "Bad",                  // firstName
        "Guy",                  // lastName
        "[email protected]",   // e-mail
        true,                   // activated
        "http://placehold.it/50x50", //imageUrl
        "en",                   // langKey
        null,                   // createdBy
        null,                   // createdDate
        null,                   // lastModifiedBy
        null,                   // lastModifiedDate
        new HashSet<>(Arrays.asList(AuthoritiesConstants.ADMIN)));

    restMvc.perform(
        post("/api/register")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(validUser)))
        .andExpect(status().isCreated());

    Optional<User> userDup = userRepository.findOneByLogin("badguy");
    assertThat(userDup.isPresent()).isTrue();
    assertThat(userDup.get().getAuthorities()).hasSize(1)
        .containsExactly(authorityRepository.findOne(AuthoritiesConstants.USER));
}
 
Example 30
Project: spring-configuration-support   File: ConfigurationDaoJdbcImpl.java   View source code 5 votes vote down vote up
@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);
}
 
Example 31
Project: mumu   File: SysUserServiceImpl.java   View source code 5 votes vote down vote up
@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);
}
 
Example 32
Project: graphium   File: WayGraphVersionMetadataDaoImpl.java   View source code 5 votes vote down vote up
@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);
}
 
Example 33
Project: my-spring-boot-project   File: TokenServiceImpl.java   View source code 5 votes vote down vote up
@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;
}
 
Example 34
Project: DWSurvey   File: QuestionBankManagerImpl.java   View source code 5 votes vote down vote up
@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);
		}
	}
}
 
Example 35
Project: spring-io   File: SubCategoryResourceIntTest.java   View source code 5 votes vote down vote up
@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())));
}
 
Example 36
Project: graphium   File: SourceDaoImpl.java   View source code 5 votes vote down vote up
@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);
}
 
Example 37
Project: Spring-Security-Third-Edition   File: JpaEventDao.java   View source code 5 votes vote down vote up
@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));
}
 
Example 38
Project: devoxxus-jhipster-microservices-demo   File: TagResourceIntTest.java   View source code 5 votes vote down vote up
@Test
@Transactional
public void getNonExistingTag() throws Exception {
    // Get the tag
    restTagMockMvc.perform(get("/api/tags/{id}", Long.MAX_VALUE))
        .andExpect(status().isNotFound());
}
 
Example 39
Project: devoxxus-jhipster-microservices-demo   File: AccountResourceIntTest.java   View source code 5 votes vote down vote up
@Test
@Transactional
public void testRegisterValid() throws Exception {
    ManagedUserVM validUser = new ManagedUserVM(
        null,                   // id
        "joe",                  // login
        "password",             // password
        "Joe",                  // firstName
        "Shmoe",                // lastName
        "[email protected]",      // e-mail
        true,                   // activated
        "http://placehold.it/50x50", //imageUrl
        "en",                   // langKey
        null,                   // createdBy
        null,                   // createdDate
        null,                   // lastModifiedBy
        null,                   // lastModifiedDate
        new HashSet<>(Arrays.asList(AuthoritiesConstants.USER)));

    restMvc.perform(
        post("/api/register")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(validUser)))
        .andExpect(status().isCreated());

    Optional<User> user = userRepository.findOneByLogin("joe");
    assertThat(user.isPresent()).isTrue();
}
 
Example 40
Project: Equella   File: ItemServiceImpl.java   View source code 5 votes vote down vote up
@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);
	}
}