org.apache.commons.lang3.RandomStringUtils Java Examples

The following examples show how to use org.apache.commons.lang3.RandomStringUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AccountResourceIntTest.java    From e-commerce-microservice with Apache License 2.0 6 votes vote down vote up
@Test
@Transactional
public void testFinishPasswordReset() throws Exception {
    User user = new User();
    user.setPassword(RandomStringUtils.random(60));
    user.setLogin("finish-password-reset");
    user.setEmail("[email protected]");
    user.setResetDate(Instant.now().plusSeconds(60));
    user.setResetKey("reset key");
    userRepository.saveAndFlush(user);

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

    restMvc.perform(
        post("/api/account/reset-password/finish")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
        .andExpect(status().isOk());

    User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null);
    assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isTrue();
}
 
Example #2
Source File: MyNamePronunciationDisplay.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
private void addNameRecord() {
    WebMarkupContainer nameRecordingContainer = new WebMarkupContainer("nameRecordingContainer");

    nameRecordingContainer.add(new Label("nameRecordingLabel", new ResourceModel("profile.name.recording")));
    WebMarkupContainer audioPlayer = new WebMarkupContainer("audioPlayer");

    final String slash = Entity.SEPARATOR;
    final StringBuilder path = new StringBuilder();
    path.append(slash);
    path.append("direct");
    path.append(slash);
    path.append("profile");
    path.append(slash);
    path.append(userProfile.getUserUuid());
    path.append(slash);
    path.append("pronunciation");
    path.append("?v=");
    path.append(RandomStringUtils.random(8, true, true));

    audioPlayer.add(new AttributeModifier("src", path.toString()));
    nameRecordingContainer.add(audioPlayer);
    add(nameRecordingContainer);

    if (profileLogic.getUserNamePronunciation(userProfile.getUserUuid()) == null) nameRecordingContainer.setVisible(false);
    else visibleFieldCount++;
}
 
Example #3
Source File: AccountResourceIntTest.java    From Full-Stack-Development-with-JHipster with MIT License 6 votes vote down vote up
@Test
@Transactional
@WithMockUser("change-password-empty")
public void testChangePasswordEmpty() throws Exception {
    User user = new User();
    user.setPassword(RandomStringUtils.random(60));
    user.setLogin("change-password-empty");
    user.setEmail("[email protected]");
    userRepository.saveAndFlush(user);

    restMvc.perform(post("/api/account/change-password").content(RandomStringUtils.random(0)))
        .andExpect(status().isBadRequest());

    User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null);
    assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
 
Example #4
Source File: TestDefaultCAServer.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Test
public void testMissingKey() {
  SecurityConfig securityConfig = new SecurityConfig(conf);
  CertificateServer testCA = new DefaultCAServer("testCA",
      RandomStringUtils.randomAlphabetic(4),
      RandomStringUtils.randomAlphabetic(4), caStore);
  Consumer<SecurityConfig> caInitializer =
      ((DefaultCAServer) testCA).processVerificationStatus(
          DefaultCAServer.VerificationStatus.MISSING_KEYS);
  try {

    caInitializer.accept(securityConfig);
    fail("code should not reach here, exception should have been thrown.");
  } catch (IllegalStateException e) {
    // This also is a runtime exception. Hence not caught by junit expected
    // exception.
    assertTrue(e.toString().contains("Missing Keys"));
  }
}
 
Example #5
Source File: AccountResourceIT.java    From alchemy with Apache License 2.0 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 #6
Source File: AggregationAnnotationTests.java    From mongodb-aggregate-query-support with Apache License 2.0 6 votes vote down vote up
@Test
public void mustProcessGroupAnnotationCorrectly() throws IOException {
  populateGroupCollection();
  int totalQuantity = testGroupRepository.getTotalQuantityForOneItem("abc");
  assertEquals(12, totalQuantity);

  List<TestGroupResultsBean> results = testGroupRepository.salesBySalesDate();
  assertNotNull(results);

  totalQuantity = testGroupRepository.getTotalQuantityForOneItem("xyz");
  assertEquals(30, totalQuantity);

  totalQuantity = testGroupRepository.getTotalQuantityForOneItem("jkl");
  assertEquals(1, totalQuantity);

  Integer noQuantity = testGroupRepository.getTotalQuantityForOneItem(RandomStringUtils.random(10));
  assertNull(noQuantity);
}
 
Example #7
Source File: UserRpcServiceImpl.java    From blog-sample with Apache License 2.0 6 votes vote down vote up
@Override
public void listByAge(UserRpcProto.AgeRequest request, StreamObserver<UserRpcProto.UserResponse> responseObserver) {
    logger.info("Server Rec listByAge request...");

    // 构造响应,模拟业务逻辑
    UserRpcProto.UserResponse response = UserRpcProto.UserResponse.newBuilder()
            .setCode(0)
            .setMsg("success")
            .addUser(MessageProto.User.newBuilder()
                    .setName(RandomStringUtils.randomAlphabetic(5))
                    .setAge(request.getAge()).build())
            .addUser(MessageProto.User.newBuilder()
                    .setName(RandomStringUtils.randomAlphabetic(5))
                    .setAge(request.getAge()).build())
            .addUser(MessageProto.User.newBuilder()
                    .setName(RandomStringUtils.randomAlphabetic(5))
                    .setAge(request.getAge()).build())
            .build();

    responseObserver.onNext(response);
    responseObserver.onCompleted();
}
 
Example #8
Source File: SoftwaremodulesDocumentationTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description("Handles the DELETE request for a single SoftwareModule within SP. Required Permission: "
        + SpPermission.DELETE_REPOSITORY)
public void deleteArtifact() throws Exception {
    final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();

    final byte random[] = RandomStringUtils.random(5).getBytes();

    final Artifact artifact = artifactManagement
            .create(new ArtifactUpload(new ByteArrayInputStream(random), sm.getId(), "file1", false, 0));

    mockMvc.perform(delete(
            MgmtRestConstants.SOFTWAREMODULE_V1_REQUEST_MAPPING + "/{softwareModuleId}/artifacts/{artifactId}",
            sm.getId(), artifact.getId())).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
            .andDo(this.document.document(pathParameters(
                    parameterWithName("softwareModuleId").description(ApiModelPropertiesGeneric.ITEM_ID),
                    parameterWithName("artifactId").description(ApiModelPropertiesGeneric.ITEM_ID))));
}
 
Example #9
Source File: AccountResourceIntTest.java    From 21-points with Apache License 2.0 6 votes vote down vote up
@Test
@Transactional
@WithMockUser("change-password-too-long")
public void testChangePasswordTooLong() throws Exception {
    User user = new User();
    String currentPassword = RandomStringUtils.random(60);
    user.setPassword(passwordEncoder.encode(currentPassword));
    user.setLogin("change-password-too-long");
    user.setEmail("[email protected]");
    userRepository.saveAndFlush(user);

    restMvc.perform(post("/api/account/change-password")
        .contentType(TestUtil.APPLICATION_JSON_UTF8)
        .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, RandomStringUtils.random(101)))))
        .andExpect(status().isBadRequest());

    User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null);
    assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
 
Example #10
Source File: TestTypedRDBTableStore.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Test
public void testCountEstimatedRowsInTable() throws Exception {
  try (Table<String, String> testTable = createTypedTable(
      "Ninth")) {
    // Add a few keys
    final int numKeys = 12345;
    for (int i = 0; i < numKeys; i++) {
      String key =
          RandomStringUtils.random(10);
      String value = RandomStringUtils.random(10);
      testTable.put(key, value);
    }
    long keyCount = testTable.getEstimatedKeyCount();
    // The result should be larger than zero but not exceed(?) numKeys
    Assert.assertTrue(keyCount > 0 && keyCount <= numKeys);
  }
}
 
Example #11
Source File: AccountResourceIntTest.java    From TeamDojo with Apache License 2.0 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 #12
Source File: TestRDBTableStore.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Test
public void batchDelete() throws Exception {
  try (Table testTable = rdbStore.getTable("Fifth");
      BatchOperation batch = rdbStore.initBatchOperation()) {

    //given
    byte[] key =
        RandomStringUtils.random(10).getBytes(StandardCharsets.UTF_8);
    byte[] value =
        RandomStringUtils.random(10).getBytes(StandardCharsets.UTF_8);
    testTable.put(key, value);
    Assert.assertNotNull(testTable.get(key));


    //when
    testTable.deleteWithBatch(batch, key);
    rdbStore.commitBatchOperation(batch);

    //then
    Assert.assertNull(testTable.get(key));
  }
}
 
Example #13
Source File: CertificateGenerationRequestParametersTest.java    From credhub with Apache License 2.0 6 votes vote down vote up
@Test
public void validate_rejectsAlternativeNamesThatAreTooLong() {
  final String maxLengthAlternativeName = RandomStringUtils.randomAlphabetic(57) + "." + RandomStringUtils.randomNumeric(63) +
    "." + RandomStringUtils.randomAlphabetic(63) + "." + RandomStringUtils.randomAlphabetic(63) + ".com";
  subject.setAlternativeNames(new String[]{"abc.com", maxLengthAlternativeName});
  subject.validate();


  final String overlyLongAlternativeName = "." + RandomStringUtils.randomAlphabetic(58) + "." + RandomStringUtils.randomNumeric(63) +
    "." + RandomStringUtils.randomAlphabetic(63) + "." + RandomStringUtils.randomAlphabetic(63) + ".co";
  subject.setAlternativeNames(new String[]{"abc.com", overlyLongAlternativeName});

  try {
    subject.validate();
    fail("should throw");
  } catch (final ParameterizedValidationException e) {
    assertThat(e.getMessage(), equalTo(ErrorMessages.Credential.INVALID_CERTIFICATE_PARAMETER));
    assertThat(e.getParameters(), equalTo(new Object[]{"alternative name", 253}));
  }
}
 
Example #14
Source File: TestDataUtil.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
public static OzoneBucket createVolumeAndBucket(MiniOzoneCluster cluster)
    throws IOException {
  final int attempts = 5;
  for (int i = 0; i < attempts; i++) {
    try {
      String volumeName = "volume" + RandomStringUtils.randomNumeric(5);
      String bucketName = "bucket" + RandomStringUtils.randomNumeric(5);
      return createVolumeAndBucket(cluster, volumeName, bucketName);
    } catch (OMException e) {
      if (e.getResult() != OMException.ResultCodes.VOLUME_ALREADY_EXISTS &&
          e.getResult() != OMException.ResultCodes.BUCKET_ALREADY_EXISTS) {
        throw e;
      }
    }
  }
  throw new IllegalStateException("Could not create unique volume/bucket " +
      "in " + attempts + " attempts");
}
 
Example #15
Source File: AccountResourceIT.java    From alchemy with Apache License 2.0 6 votes vote down vote up
@Test
@Transactional
@WithMockUser("change-password-too-long")
public void testChangePasswordTooLong() throws Exception {
    User user = new User();
    String currentPassword = RandomStringUtils.random(60);
    user.setPassword(passwordEncoder.encode(currentPassword));
    user.setLogin("change-password-too-long");
    user.setEmail("[email protected]");
    userRepository.saveAndFlush(user);

    String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MAX_LENGTH + 1);

    restMvc.perform(post("/api/account/change-password")
        .contentType(TestUtil.APPLICATION_JSON_UTF8)
        .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword))))
        .andExpect(status().isBadRequest());

    User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null);
    assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
 
Example #16
Source File: AccountResourceIT.java    From jhipster-online with Apache License 2.0 6 votes vote down vote up
@Test
    @Transactional
    @WithMockUser("change-password-empty")
    public void testChangePasswordEmpty() throws Exception {
        User user = new User();
        String currentPassword = RandomStringUtils.random(60);
        user.setPassword(passwordEncoder.encode(currentPassword));
        user.setLogin("change-password-empty");
        user.setEmail("[email protected]");
        userRepository.saveAndFlush(user);

        restAccountMockMvc.perform(post("/api/account/change-password")
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "")))
)
            .andExpect(status().isBadRequest());

        User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null);
        assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
    }
 
Example #17
Source File: ZkClientTest.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	ZkClient zkClient = new ZkClient("127.0.0.1:2181", 10000, 5000, new ZKStringSerializer());
	
	ExecutorService service = Executors.newFixedThreadPool(5);
	
	for (int i = 0; i < 100; i++) {
		service.execute(new Runnable() {
			@Override
			public void run() {
				String path = KafkaConst.ZK_PRODUCER_ACK_PATH + RandomStringUtils.random(5, true, true);
				zkClient.createEphemeral(path);
				System.out.println(path);
			}
		});
		if(i % 5 == 0){
			Thread.sleep(500);
			System.out.println("Sleep");
		}
	}
	
}
 
Example #18
Source File: MybatisTest.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
@Test
public void testRwRouteWithTransaction2(){
	
	userMapper.findByStatus((short)1);
	
	transactionTemplate.execute(new TransactionCallback<Void>() {
		@Override
		public Void doInTransaction(TransactionStatus status) {

			userMapper.findByStatus((short)2);
			
			UserEntity entity = new UserEntity();
			entity.setCreatedAt(new Date());
			entity.setEmail(RandomStringUtils.random(6, true, true) + "@163.com");
			entity.setMobile("13800"+RandomUtils.nextLong(100000, 999999));
			entity.setType((short)1);
			entity.setStatus((short)1);
			userMapper.insert(entity);
			
			userMapper.findByStatus((short)2);
			
			return null;
		}
	});
	System.out.println();
}
 
Example #19
Source File: CodecTest.java    From cloud-config with MIT License 6 votes vote down vote up
@Override
protected void prepare() throws Exception {
    String ccConfig1 = "{\n" +
            "    \"__type__\" : \"org.squirrelframework.cloud.resource.security.rsa.RSAPrivateKeyConfig\", \n"+
            "    \"privateKey\" : \""+test_private_key+"\"\n"+
            "}";
    zkConfigClient.create().creatingParentsIfNeeded().forPath("/codec/rsa/private", ccConfig1.getBytes());

    String ccConfig2 = "{\n" +
            "    \"__type__\" : \"org.squirrelframework.cloud.resource.security.rsa.RSAPublicKeyConfig\", \n"+
            "    \"publicKey\" : \""+test_public_key+"\"\n"+
            "}";
    zkConfigClient.create().creatingParentsIfNeeded().forPath("/codec/rsa/public", ccConfig2.getBytes());

    String ccConfig3 = "{\n" +
            "    \"__type__\" : \"org.squirrelframework.cloud.resource.security.md5.Md5SignatureConfig\", \n"+
            "    \"secretKey\" : \""+RandomStringUtils.randomAlphabetic(32)+"\"\n"+
            "}";
    zkConfigClient.create().creatingParentsIfNeeded().forPath("/codec/md5", ccConfig3.getBytes());
}
 
Example #20
Source File: TestRDBStore.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Test
public void moveKey() throws Exception {
  byte[] key =
      RandomStringUtils.random(10).getBytes(StandardCharsets.UTF_8);
  byte[] value =
      RandomStringUtils.random(10).getBytes(StandardCharsets.UTF_8);

  try (Table firstTable = rdbStore.getTable(families.get(1))) {
    firstTable.put(key, value);
    try (Table<byte[], byte[]> secondTable = rdbStore
        .getTable(families.get(2))) {
      rdbStore.move(key, firstTable, secondTable);
      byte[] newvalue = secondTable.get(key);
      // Make sure we have value in the second table
      Assert.assertNotNull(newvalue);
      //and it is same as what we wrote to the FirstTable
      Assert.assertArrayEquals(value, newvalue);
    }
    // After move this key must not exist in the first table.
    Assert.assertNull(firstTable.get(key));
  }
}
 
Example #21
Source File: AccountResourceIntTest.java    From Spring-5.0-Projects with MIT License 5 votes vote down vote up
@Test
@Transactional
@WithMockUser("save-account")
public void testSaveAccount() throws Exception {
    User user = new User();
    user.setLogin("save-account");
    user.setEmail("[email protected]");
    user.setPassword(RandomStringUtils.random(60));
    user.setActivated(true);

    userRepository.saveAndFlush(user);

    UserDTO userDTO = new UserDTO();
    userDTO.setLogin("not-used");
    userDTO.setFirstName("firstname");
    userDTO.setLastName("lastname");
    userDTO.setEmail("[email protected]");
    userDTO.setActivated(false);
    userDTO.setImageUrl("http://placehold.it/50x50");
    userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
    userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));

    restMvc.perform(
        post("/api/account")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(userDTO)))
        .andExpect(status().isOk());

    User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null);
    assertThat(updatedUser.getFirstName()).isEqualTo(userDTO.getFirstName());
    assertThat(updatedUser.getLastName()).isEqualTo(userDTO.getLastName());
    assertThat(updatedUser.getEmail()).isEqualTo(userDTO.getEmail());
    assertThat(updatedUser.getLangKey()).isEqualTo(userDTO.getLangKey());
    assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
    assertThat(updatedUser.getImageUrl()).isEqualTo(userDTO.getImageUrl());
    assertThat(updatedUser.getActivated()).isEqualTo(true);
    assertThat(updatedUser.getAuthorities()).isEmpty();
}
 
Example #22
Source File: AddAccountDialog.java    From offspring with MIT License 5 votes vote down vote up
private String generatePassphrase() {
  // No space, backslash, newline, tab
  String symbols = "!\"$%^&*()-_=+[{]};:'@#~|,<.>/?"; //$NON-NLS-1$
  String alphaNum = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890"; //$NON-NLS-1$
  char[] chars = new String(symbols + alphaNum).toCharArray();
  shuffleSeedText(chars);

  int low = 70;
  int high = 90;
  Random random = new Random();
  int count = random.nextInt(high - low) + low;
  return RandomStringUtils.random(count, 0, 0, false, false, chars,
      new SecureRandom());
}
 
Example #23
Source File: EventNameManager.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
private String generateRandomName() {
    return IntStream.range(0, 5)
            .mapToObj(i -> RandomStringUtils.randomAlphanumeric(15))
            .filter(this::isUnique)
            .limit(1)
            .findFirst()
            .orElse("");
}
 
Example #24
Source File: SayMethod.java    From YuRPC with Apache License 2.0 5 votes vote down vote up
@Override
public void exec(Object params) throws Exception {
    Integer id = (Integer) params;
    String value = RandomStringUtils.randomAscii(128);
    Say say = new Say(id, value);
    sayService.perform(say);
}
 
Example #25
Source File: ProductService2.java    From cloud-config with MIT License 5 votes vote down vote up
@Transactional
@RoutingKey( "#{ #product.customerId }" )
public String saveProduct(@RoutingVariable("product") Product product) throws Exception {
    if(product.getId() == null) {
        product.setId(RandomStringUtils.randomAlphabetic(16));
        productDao.save(product);
    } else {
        productDao.update(product);
    }
    return product.getId();
}
 
Example #26
Source File: XPathBuilderTest.java    From validator with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoConfig() {
    final String name = RandomStringUtils.randomAlphanumeric(5);
    final XPathBuilder b = new XPathBuilder(name);
    final Result<XPathExecutable, String> result = b.build(Simple.createContentRepository());
    assertThat(result).isNotNull();
    assertThat(result.isValid()).isFalse();
}
 
Example #27
Source File: SymbolicLinkHelperTest.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the temp link.
 *
 * @return the path
 * @throws IOException Signals that an I/O exception has occurred.
 */
private Path createTempLink() throws IOException {
	Path tempLink =
		Files.createSymbolicLink(
			Paths.get(tempFile.getParent().toString(), 
					  RandomStringUtils.randomNumeric(10)),
			tempFile);
	tempLink.toFile().deleteOnExit();
	return tempLink;
}
 
Example #28
Source File: AccountResourceIntTest.java    From ehcache3-samples with Apache License 2.0 5 votes vote down vote up
@Test
@Transactional
@WithMockUser("save-existing-email")
public void testSaveExistingEmail() throws Exception {
    User user = new User();
    user.setLogin("save-existing-email");
    user.setEmail("[email protected]");
    user.setPassword(RandomStringUtils.random(60));
    user.setActivated(true);

    userRepository.saveAndFlush(user);

    User anotherUser = new User();
    anotherUser.setLogin("save-existing-email2");
    anotherUser.setEmail("[email protected]");
    anotherUser.setPassword(RandomStringUtils.random(60));
    anotherUser.setActivated(true);

    userRepository.saveAndFlush(anotherUser);

    UserDTO userDTO = new UserDTO();
    userDTO.setLogin("not-used");
    userDTO.setFirstName("firstname");
    userDTO.setLastName("lastname");
    userDTO.setEmail("[email protected]");
    userDTO.setActivated(false);
    userDTO.setImageUrl("http://placehold.it/50x50");
    userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
    userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));

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

    User updatedUser = userRepository.findOneByLogin("save-existing-email").orElse(null);
    assertThat(updatedUser.getEmail()).isEqualTo("[email protected]");
}
 
Example #29
Source File: MybatisTest.java    From azeroth with Apache License 2.0 5 votes vote down vote up
@Test
@Transactional
public void testRwRouteWithTransaction() {
    mapper.findByStatus((short) 2);

    UserEntity entity = new UserEntity();
    entity.setCreatedAt(new Date());
    entity.setEmail(RandomStringUtils.random(6, true, true) + "@163.com");
    entity.setMobile("13800" + RandomUtils.nextLong(100000, 999999));
    entity.setType((short) 1);
    entity.setStatus((short) 1);
    mapper.insert(entity);
}
 
Example #30
Source File: AccountResourceIT.java    From jhipster-online with Apache License 2.0 5 votes vote down vote up
@Test
    @Transactional
    public void testRequestPasswordResetUpperCaseEmail() throws Exception {
        User user = new User();
        user.setPassword(RandomStringUtils.random(60));
        user.setActivated(true);
        user.setLogin("password-reset");
        user.setEmail("[email protected]");
        userRepository.saveAndFlush(user);

        restAccountMockMvc.perform(post("/api/account/reset-password/init")
            .content("[email protected]")
)
            .andExpect(status().isOk());
    }