Java Code Examples for org.apache.commons.lang3.RandomStringUtils

The following are top voted examples for showing how to use org.apache.commons.lang3.RandomStringUtils. 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: patient-portal   File: AccountResourceIntTest.java   Source Code and License 6 votes vote down vote up
@Test
@Transactional
@WithMockUser("change-password-too-long")
public void testChangePasswordTooLong() throws Exception {
    User user = new User();
    user.setPassword(RandomStringUtils.random(60));
    user.setLogin("change-password-too-long");
    user.setEmail("[email protected]");
    userRepository.saveAndFlush(user);

    restMvc.perform(post("/api/account/change_password").content(RandomStringUtils.random(101)))
        .andExpect(status().isBadRequest());

    User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null);
    assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
 
Example 2
Project: spring-io   File: AccountResourceIntTest.java   Source Code and License 6 votes vote down vote up
@Test
@Transactional
@WithMockUser("change-password-too-small")
public void testChangePasswordTooSmall() throws Exception {
    User user = new User();
    user.setPassword(RandomStringUtils.random(60));
    user.setLogin("change-password-too-small");
    user.setEmail("[email protected]");
    userRepository.saveAndFlush(user);

    restMvc.perform(post("/api/account/change_password").content("new"))
        .andExpect(status().isBadRequest());

    User updatedUser = userRepository.findOneByLogin("change-password-too-small").orElse(null);
    assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
 
Example 3
Project: TorgCRM-Server   File: AccountResourceIntTest.java   Source Code and 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
Project: patient-portal   File: AccountResourceIntTest.java   Source Code and 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 5
Project: patient-portal   File: AccountResourceIntTest.java   Source Code and License 6 votes vote down vote up
@Test
@Transactional
public void testActivateAccount() throws Exception {
    final String activationKey = "some activation key";
    User user = new User();
    user.setLogin("activate-account");
    user.setEmail("[email protected]");
    user.setPassword(RandomStringUtils.random(60));
    user.setActivated(false);
    user.setActivationKey(activationKey);

    userRepository.saveAndFlush(user);

    restMvc.perform(get("/api/activate?key={activationKey}", activationKey))
        .andExpect(status().isOk());

    user = userRepository.findOneByLogin(user.getLogin()).orElse(null);
    assertThat(user.getActivated()).isTrue();
}
 
Example 6
Project: patient-portal   File: AccountResourceIntTest.java   Source Code and License 6 votes vote down vote up
@Test
@Transactional
@WithMockUser("change-password-too-small")
public void testChangePasswordTooSmall() throws Exception {
    User user = new User();
    user.setPassword(RandomStringUtils.random(60));
    user.setLogin("change-password-too-small");
    user.setEmail("[email protected]");
    userRepository.saveAndFlush(user);

    restMvc.perform(post("/api/account/change_password").content("new"))
        .andExpect(status().isBadRequest());

    User updatedUser = userRepository.findOneByLogin("change-password-too-small").orElse(null);
    assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
 
Example 7
Project: tokamak   File: RolesEndpointAcceptanceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldBeAbleToUpdateARole() {
	RoleRepresentation role = role().thatIs().persistent(token).build();
	pause(1000);

	role.setName(RandomStringUtils.randomAlphabetic(10));

	Result<RoleRepresentation> result = client.update(role, token.getAccessToken());
	assertThat(result).accepted().withResponseCode(200);

	RoleRepresentation updated = result.getInstance();
	assertThat(updated.getId()).startsWith("rol_");
	assertThat(updated.getCreated()).isNotNull();
	assertThat(updated.getUpdated()).isNotNull();

	assertThat(updated.getCreated()).isEqualTo(role.getCreated());
	assertThat(updated.getCreated()).isBefore(updated.getUpdated());
	assertThat(updated.getUpdated()).isAfter(role.getUpdated());

	assertThat(updated.getName()).isEqualTo(role.getName());
}
 
Example 8
Project: spring-io   File: AccountResourceIntTest.java   Source Code and License 6 votes vote down vote up
@Test
@Transactional
@WithMockUser("change-password")
public void testChangePassword() throws Exception {
    User user = new User();
    user.setPassword(RandomStringUtils.random(60));
    user.setLogin("change-password");
    user.setEmail("[email protected]");
    userRepository.saveAndFlush(user);

    restMvc.perform(post("/api/account/change_password").content("new password"))
        .andExpect(status().isOk());

    User updatedUser = userRepository.findOneByLogin("change-password").orElse(null);
    assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isTrue();
}
 
Example 9
Project: TorgCRM-Server   File: AccountResourceIntTest.java   Source Code and License 6 votes vote down vote up
@Test
@Transactional
public void testActivateAccount() throws Exception {
    final String activationKey = "some activation key";
    User user = new User();
    user.setLogin("activate-account");
    user.setEmail("[email protected]");
    user.setPassword(RandomStringUtils.random(60));
    user.setActivated(false);
    user.setActivationKey(activationKey);

    userRepository.saveAndFlush(user);

    restMvc.perform(get("/api/activate?key={activationKey}", activationKey))
        .andExpect(status().isOk());

    user = userRepository.findOneByLogin(user.getLogin()).orElse(null);
    assertThat(user.getActivated()).isTrue();
}
 
Example 10
Project: qualitoast   File: AccountResourceIntTest.java   Source Code and License 6 votes vote down vote up
@Test
@Transactional
public void testActivateAccount() throws Exception {
    final String activationKey = "some activation key";
    User user = new User();
    user.setLogin("activate-account");
    user.setEmail("[email protected]");
    user.setPassword(RandomStringUtils.random(60));
    user.setActivated(false);
    user.setActivationKey(activationKey);

    userRepository.saveAndFlush(user);

    restMvc.perform(get("/api/activate?key={activationKey}", activationKey))
        .andExpect(status().isOk());

    user = userRepository.findOneByLogin(user.getLogin()).orElse(null);
    assertThat(user.getActivated()).isTrue();
}
 
Example 11
Project: codemotion-2017-taller-de-jhipster   File: AccountResourceIntTest.java   Source Code and License 6 votes vote down vote up
@Test
@Transactional
public void testActivateAccount() throws Exception {
    final String activationKey = "some activation key";
    User user = new User();
    user.setLogin("activate-account");
    user.setEmail("[email protected]");
    user.setPassword(RandomStringUtils.random(60));
    user.setActivated(false);
    user.setActivationKey(activationKey);

    userRepository.saveAndFlush(user);

    restMvc.perform(get("/api/activate?key={activationKey}", activationKey))
        .andExpect(status().isOk());

    user = userRepository.findOneByLogin(user.getLogin()).orElse(null);
    assertThat(user.getActivated()).isTrue();
}
 
Example 12
Project: codemotion-2017-taller-de-jhipster   File: AccountResourceIntTest.java   Source Code and License 6 votes vote down vote up
@Test
@Transactional
@WithMockUser("change-password-too-small")
public void testChangePasswordTooSmall() throws Exception {
    User user = new User();
    user.setPassword(RandomStringUtils.random(60));
    user.setLogin("change-password-too-small");
    user.setEmail("[email protected]");
    userRepository.saveAndFlush(user);

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

    User updatedUser = userRepository.findOneByLogin("change-password-too-small").orElse(null);
    assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
 
Example 13
Project: qualitoast   File: AccountResourceIntTest.java   Source Code and License 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 14
Project: todo-list-webapp-angular2-spring-mvc-boot-data-rest   File: TodoControllerIntegrationTest.java   Source Code and License 6 votes vote down vote up
@Before
public void prepareData(){
       TodoEntity nullNameTodo = new TodoEntity();

       TodoEntity emptyNameTodo = new TodoEntity();
       emptyNameTodo.setName("");

       TodoEntity emptyNameButWithSpacesTodo = new TodoEntity();
       emptyNameButWithSpacesTodo.setName("    ");

       TodoEntity name101charsTodo = new TodoEntity();
       name101charsTodo.setName(RandomStringUtils.randomAlphanumeric(101));

       TodoEntity name500CharsTodo = new TodoEntity();
       name500CharsTodo.setName(RandomStringUtils.randomAlphanumeric(500));

       improperNameTodoList = Arrays.asList(nullNameTodo, emptyNameTodo, emptyNameButWithSpacesTodo, name101charsTodo, name500CharsTodo);

       TodoEntity name100charsTodo = new TodoEntity();
       name100charsTodo.setName(RandomStringUtils.randomAlphanumeric(100));

       TodoEntity nameOneCharTodo = new TodoEntity();
       nameOneCharTodo.setName("a");

       properNameTodoList = Arrays.asList(name100charsTodo, nameOneCharTodo);
   }
 
Example 15
Project: spring-io   File: AccountResourceIntTest.java   Source Code and License 6 votes vote down vote up
@Test
@Transactional
@WithMockUser("change-password-too-long")
public void testChangePasswordTooLong() throws Exception {
    User user = new User();
    user.setPassword(RandomStringUtils.random(60));
    user.setLogin("change-password-too-long");
    user.setEmail("[email protected]");
    userRepository.saveAndFlush(user);

    restMvc.perform(post("/api/account/change_password").content(RandomStringUtils.random(101)))
        .andExpect(status().isBadRequest());

    User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null);
    assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
 
Example 16
Project: selenium-testng-template   File: DownloadUtils.java   Source Code and License 6 votes vote down vote up
public static final String download(RemoteWebDriver driver, String url) {
	String folder = DOWNLOAD_PATH + RandomStringUtils.randomAlphabetic(10);
	new File(folder).mkdirs();

	Map<String, String> headers = new HashMap<String, String>();
	headers.put("Cookie", getCookie(driver));
	byte[] data = HttpUtils.get(url, headers);
	try {
		String filename;
		String contentDisposition = headers.get("Content-Disposition");
		if (StringUtils.contains(contentDisposition, "=")) {
			filename = contentDisposition.substring(contentDisposition.indexOf("=") + 1);
		} else {
			filename = new URL(url).getPath();
			if (filename.contains("/")) {
				filename = filename.substring(filename.lastIndexOf("/") + 1);
			}
		}
		IOUtils.write(data, new FileOutputStream(folder + "/" + filename));
		return folder + "/" + filename;
	} catch (Exception e) {
		throw new RuntimeException("Download failed!", e);
	}
}
 
Example 17
Project: patient-portal   File: AccountResourceIntTest.java   Source Code and License 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 18
Project: xm-uaa   File: SocialService.java   Source Code and License 5 votes vote down vote up
private User createUserIfNotExist(UserProfile userProfile, String langKey, String imageUrl) {
    String email = userProfile.getEmail();
    if (StringUtils.isBlank(email)) {
        log.error("Cannot create social user because email is null");
        throw new IllegalArgumentException("Email cannot be null");
    } else {
        Optional<UserLogin> user = userLoginRepository.findOneByLoginIgnoreCase(email);
        if (user.isPresent()) {
            log.info("User already exist associate the connection to this account");
            return user.get().getUser();
        }
    }
    String encryptedPassword = passwordEncoder.encode(RandomStringUtils.random(10));
    Set<Authority> authorities = new HashSet<>(1);
    authorities.add(authorityRepository.findOne("ROLE_USER"));

    User newUser = new User();
    newUser.setUserKey(UUID.randomUUID().toString());
    newUser.setPassword(encryptedPassword);
    newUser.setFirstName(userProfile.getFirstName());
    newUser.setLastName(userProfile.getLastName());
    newUser.setActivated(true);
    newUser.setAuthorities(authorities);
    newUser.setLangKey(langKey);
    newUser.setImageUrl(imageUrl);

    UserLogin userLogin = new UserLogin();
    userLogin.setUser(newUser);
    userLogin.setTypeKey(UserLoginType.EMAIL.getValue());
    userLogin.setLogin(email);

    newUser.getLogins().add(userLogin);
    return userRepository.save(newUser);
}
 
Example 19
Project: DoApp   File: GenericPathPatternURIGenerator.java   Source Code and License 5 votes vote down vote up
public static MalIntent getSemivalidSchemeHostPortPathPatternURIMalIntent(IntentDataInfo datafield) {

        MalIntent mal = new MalIntent(datafield);
        String scheme = datafield.scheme;

        String host = datafield.host;
        host = host.replace("*", RandomStringUtils.randomAlphanumeric(10));

        String pathPattern = datafield.pathPattern;
        String semivalidPathPattern;

        if (pathPattern.contains(".*") || pathPattern.contains("*")) {
            semivalidPathPattern = pathPattern.replace(".*", RandomStringUtils.randomAlphabetic(10));
            semivalidPathPattern = semivalidPathPattern.replace("*", RandomStringUtils.randomAlphanumeric(10));

            if (pathPattern.charAt(0) == '/') {
                mal.setData(Uri.parse(scheme + "://" + host + semivalidPathPattern));
            }
            mal.setData(Uri.parse(scheme + "://" + host + "/" + semivalidPathPattern));
        } else {
            semivalidPathPattern = RandomStringUtils.randomAlphabetic(10);
            if (pathPattern.equals("") || pathPattern.charAt(0) == '/') {
                mal.setData(Uri.parse(scheme + "://" + host + semivalidPathPattern));
            }
            mal.setData(Uri.parse(scheme + "://" + host + "/" + semivalidPathPattern));

        }


        return mal;
    }
 
Example 20
Project: conf4j   File: ConsulFileConfigurationSourceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testReloadStrategyIsNotNullWhenCallingReloadOnChange() throws Exception {
    ConsulFileConfigurationSource source;
    String filePath = RandomStringUtils.randomAlphanumeric(15);

    source = createConfigurationSource(filePath, true, false);
    assertThat(source.shouldWatchForChange()).isFalse();
    assertThat(source.getReloadStrategy()).isNull();

    source = createConfigurationSource(filePath, true, true);
    assertThat(source.shouldWatchForChange()).isTrue();
    assertThat(source.getReloadStrategy()).isNotNull();
}
 
Example 21
Project: raven   File: Test.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
		String str = "";
		for(int i = 0; i < 5; i++)
		{
			//System.out.println(RandomStringUtils.randomNumeric(8));
			str += RandomStringUtils.randomNumeric(4)+",";
		}
		
		System.out.println(str);
		System.out.println(str.substring(0,str.lastIndexOf(",")));
//		for(int i = 0;i<10;i++){
//			method1();
//		}
		
//		if(Days.daysBetween(DateUtils.parseDate("2016-10-25 00:00:00"),DateTime.now()).getDays() == 0){
//			System.out.println("today");
//		}
		
		String dtStr = DateUtils.getCurrentTimeStr();
		dtStr = dtStr.substring(0, dtStr.lastIndexOf(" ")) + " 00:00:00";
		System.out.println(dtStr);

		regexPhoneTest("17700001111");

        setTimeout(1000,2000);
        System.out.println(JsonUtils.obj2json(getTimeout()));
    }
 
Example 22
Project: TorgCRM-Server   File: UserResourceIntTest.java   Source Code and License 5 votes vote down vote up
/**
 * Create a User.
 *
 * This is a static method, as tests for other entities might also need it,
 * if they test an entity which has a required relationship to the User entity.
 */
public static User createEntity(EntityManager em) {
    User user = new User();
    user.setLogin(DEFAULT_LOGIN + RandomStringUtils.randomAlphabetic(5));
    user.setPassword(RandomStringUtils.random(60));
    user.setActivated(true);
    user.setEmail(RandomStringUtils.randomAlphabetic(5) + DEFAULT_EMAIL);
    user.setFirstName(DEFAULT_FIRSTNAME);
    user.setLastName(DEFAULT_LASTNAME);
    user.setImageUrl(DEFAULT_IMAGEURL);
    user.setLangKey(DEFAULT_LANGKEY);
    return user;
}
 
Example 23
Project: xm-uaa   File: UserServiceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
public void assertThatUserCanResetPassword() {
    UserLogin userLogin = new UserLogin();
    userLogin.setTypeKey(UserLoginType.EMAIL.getValue());
    userLogin.setLogin("[email protected]");

    User user = new User();
    user.setUserKey("test");
    user.setPassword(RandomStringUtils.random(60));
    user.getLogins().add(userLogin);
    userLogin.setUser(user);

    String oldPassword = user.getPassword();
    Instant daysAgo = Instant.now().minus(2, ChronoUnit.HOURS);
    String resetKey = RandomUtil.generateResetKey();
    user.setActivated(true);
    user.setResetDate(daysAgo);
    user.setResetKey(resetKey);
    userRepository.save(user);

    Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
    assertThat(maybeUser.isPresent()).isTrue();
    assertThat(maybeUser.get().getResetDate()).isNull();
    assertThat(maybeUser.get().getResetKey()).isNull();
    assertThat(maybeUser.get().getPassword()).isNotEqualTo(oldPassword);

    userRepository.delete(user);
}
 
Example 24
Project: resilient-transport-service   File: BookingRepositoryTest.java   Source Code and License 5 votes vote down vote up
private Address createAddress() {
    Address senderAddress = new Address();
    senderAddress.setCity(RandomStringUtils.randomAlphanumeric(20));
    senderAddress.setPostcode(RandomStringUtils.randomAlphanumeric(7));
    senderAddress.setCountry(RandomStringUtils.randomAlphanumeric(20));
    senderAddress.setStreet(RandomStringUtils.randomAlphanumeric(15));
    senderAddress.setStreetNumber("23b");

    return senderAddress;
}
 
Example 25
Project: jhipster-microservices-example   File: AccountResourceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
@Transactional
@WithMockUser("save-invalid-email")
public void testSaveInvalidEmail() throws Exception {
    User user = new User();
    user.setLogin("save-invalid-email");
    user.setEmail("[email protected]");
    user.setPassword(RandomStringUtils.random(60));
    user.setActivated(true);

    userRepository.saveAndFlush(user);

    UserDTO userDTO = new UserDTO(
        null,                   // id
        "not-used",          // login
        "firstname",                // firstName
        "lastname",                  // lastName
        "invalid email",    // email
        false,                   // activated
        "http://placehold.it/50x50", //imageUrl
        "en",                   // langKey
        null,                   // createdBy
        null,                   // createdDate
        null,                   // lastModifiedBy
        null,                   // lastModifiedDate
        new HashSet<>(Collections.singletonList(AuthoritiesConstants.ADMIN))
    );

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

    assertThat(userRepository.findOneByEmail("invalid email")).isNotPresent();
}
 
Example 26
Project: aws-lambda-proxy-java   File: MethodHandlerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldReturnOkIfRequiredHeadersArePresent() throws Exception {
    Collection<String> requiredHeaders = Stream.of("header1", "header2")
            .map(Util::randomizeCase)
            .collect(toList());
    SampleMethodHandler sampleMethodHandlerWithRequiredHeaders = new SampleMethodHandler(requiredHeaders);
    sampleMethodHandlerWithRequiredHeaders.registerPerContentType(CONTENT_TYPE_1, contentTypeMapper1);
    sampleMethodHandlerWithRequiredHeaders.registerPerAccept(ACCEPT_TYPE_1, acceptMapper1);
    int output = 0;
    Map<String, String> headers = requiredHeaders.stream().collect(toConcurrentMap(
            identity(),
            header -> RandomStringUtils.randomAlphabetic(5)
    ));
    randomiseKeyValues(headers);
    ApiGatewayProxyRequest requestWithRequiredHeaders = new ApiGatewayProxyRequestBuilder()
            .withContext(context)
            .withHeaders(headers)
            .build();
    when(contentTypeMapper1.toInput(requestWithRequiredHeaders, context)).thenReturn(output);
    when(acceptMapper1.outputToResponse(output)).thenReturn(new ApiGatewayProxyResponse.ApiGatewayProxyResponseBuilder()
            .withStatusCode(OK.getStatusCode())
            .build());

    ApiGatewayProxyResponse response = sampleMethodHandlerWithRequiredHeaders.handle(requestWithRequiredHeaders, singletonList(CONTENT_TYPE_1), singletonList(ACCEPT_TYPE_1), context);

    assertThat(response.getStatusCode()).isEqualTo(OK.getStatusCode());
}
 
Example 27
Project: tokamak   File: AuthorityValidationTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldNotBeAbleToCreateAnAuthorityWhenTheAuthorityNameAlredyExists() {
	String name = RandomStringUtils.randomAlphanumeric(15);

	authority().withName(name).save();
	onCreate(authority().withName(name).build()).rejected().withError("ATH-0003", "This authority name is already in use.", ResourceConflictException.class);
}
 
Example 28
Project: spring-io   File: AccountResourceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
@Transactional
public void testRequestPasswordReset() 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);

    restMvc.perform(post("/api/account/reset_password/init")
        .content("[email protected]"))
        .andExpect(status().isOk());
}
 
Example 29
Project: PACE   File: BenchmarkBase.java   Source Code and License 5 votes vote down vote up
/**
 * Get random bytes.
 *
 * @param count
 *          Number of bytes.
 * @param textual
 *          Whether the generated data should be textual.
 * @return The random bytes.
 */
private byte[] getRandomBytes(int count, boolean textual) {
  if (textual) {
    return RandomStringUtils.random(count, 0, 0, true, true, null, rand).getBytes(StandardCharsets.US_ASCII);
  } else {
    byte[] data = new byte[count];
    rand.nextBytes(data);
    return data;
  }
}
 
Example 30
Project: qualitoast   File: AccountResourceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
@Transactional
public void testRequestPasswordReset() 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);

    restMvc.perform(post("/api/account/reset-password/init")
        .content("[email protected]"))
        .andExpect(status().isOk());
}
 
Example 31
Project: qualitoast   File: AccountResourceIntTest.java   Source Code and 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 32
Project: ParquetUtils   File: ParquetGeneratorEngine.java   Source Code and License 5 votes vote down vote up
public Iterable<Row> call(ParquetGeneratorBean x) throws IOException {
	List<Row> result = new ArrayList<Row>(x.getNumRecord());
	Random random = new Random(x.getSeed());
	for (int i = 0; i < x.getNumRecord(); i++) {
		List<Object> temp = new ArrayList<Object>(x.getStructRecord().size());
		for (Map.Entry<String, String> entry : x.getStructRecord().entrySet()) {

			switch (entry.getValue().toLowerCase()) {
			case "string":
				temp.add(RandomStringUtils.randomAlphabetic(5));
				break;
			case "int":
				temp.add(random.nextInt());
				break;
			case "double":
				temp.add(random.nextDouble());
				break;
			case "dictionary":
				temp.add(names.get(random.nextInt(names.size())));
				break;

			}
		}
		if (!temp.isEmpty()) {
			result.add(RowFactory.create(temp.toArray()));
		}
	}
	return result;

}
 
Example 33
Project: qualitoast   File: AccountResourceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
@Transactional
@WithMockUser("save-invalid-email")
public void testSaveInvalidEmail() throws Exception {
    User user = new User();
    user.setLogin("save-invalid-email");
    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("invalid email");
    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());

    assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent();
}
 
Example 34
Project: tokamak   File: ClientValidationTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldNotBeAbleToCreateAClientIfTheClientIdAlreadyExists() {
	String clientId = RandomStringUtils.randomAlphanumeric(15);
	client().withClientId(clientId).withGrantType(grantType).save();

	onCreate(client().withClientId(clientId).withGrantType(grantType).build()).rejected().withError("CLI-0003", "This client id is already in use.", ResourceConflictException.class);
}
 
Example 35
Project: cas-5.1.0   File: AzureAuthenticatorGenerateTokenAction.java   Source Code and License 5 votes vote down vote up
@Override
public Event doExecute(final RequestContext requestContext) throws Exception {
    final Integer code = Integer.valueOf(RandomStringUtils.randomNumeric(8));
    final AzureAuthenticatorTokenCredential c = new AzureAuthenticatorTokenCredential();
    c.setToken(code.toString());
    WebUtils.putCredential(requestContext, c);
    requestContext.getFlowScope().put("azureToken", code);

    if (mode == MultifactorAuthenticationProperties.Azure.AuthenticationModes.POUND) {
        return new EventFactorySupport().event(this, "authenticate");
    }
    return success();
}
 
Example 36
Project: minlia-iot-xapi   File: BrcbWechatPaymentAlipayApiTest.java   Source Code and License 5 votes vote down vote up
@Test
  public void test_payment_app_with_success_result() {

    //创建请求体
    BrcbPaymentAlipayAppRequestBody body = new BrcbPaymentAlipayAppRequestBody();


    body.setNotifyUrl("http://will.dev.pufubao.net/n/brcb");
    body.setOutTradeNo("OUTTRADENO-" + RandomStringUtils.randomNumeric(4));
    body.setSpbillCreateIp("127.0.0.1");
    body.setOutTradeNo("TEST-ORDER-" + RandomStringUtils.randomNumeric(10));//
    body.setTotalFee("1");
    body.setBody("测试支付");
    body.setNonceStr(RandomStringUtils.randomAlphabetic(30));

    //返回被封装成2层
    //1. 状态化的返回体, 负责整体api调用是否成功型封装
    //2. 具体业务需要的返回体, 在状态化的返回体中 payload中承载, 负责业务返回
    BrcbStatefulApiResponseBody<BrcbPaymentAlipayAppResponseBody> statefulApiResponseBody = (BrcbStatefulApiResponseBody) brcbAlipayPaymentApi
        .sandbox(true)
        .app(body);

    //断言状态化返回体不可以为空
    assertNotNull(statefulApiResponseBody);
//
//    //由于提交的参数不全, 所以预期出现以下错误
//    assertEquals("FAIL", statefulApiResponseBody.getReturnCode());
//    assertEquals("结算信息不存在", statefulApiResponseBody.getReturnMsg());

  }
 
Example 37
Project: metanome-algorithms   File: BloomFilterTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testHugeBloomFilter() {
    BloomFilter<String> filter1 = new BloomFilter<>(1000000, 3, bitVectorFactory);
    for (int i = 0; i < 100000; i++) {
        String s = RandomStringUtils.randomAlphabetic(i % 25 + 1);
        //System.out.println(s);
        filter1.add(s);
    }
    // TODO check normal distribution
}
 
Example 38
Project: ja-micro   File: KafkaFailoverIntegrationTest.java   Source Code and License 5 votes vote down vote up
@Ignore
@Test
public void producerSendsToNonExistingTopic() {
    ServiceProperties serviceProperties = fillServiceProperties();

    Topic cruft = new Topic("cruft");
    Topic lard = new Topic("lard");

    Producer producer = new ProducerFactory(serviceProperties).createProducer();

    String key = RandomStringUtils.randomAscii(5);
    SayHelloToCmd payload = SayHelloToCmd.newBuilder().setName(key).build();

    Message request = Messages.requestFor(cruft, lard, key, payload, new OrangeContext());

    producer.send(request);

    // Results:
    // 1.) NO topic auto creation i.e. KAFKA_AUTO_CREATE_TOPICS_ENABLE = false
    // 2017-04-12 18:14:41,239 [Time-limited test] DEBUG c.s.s.f.kafka.messaging.Producer - Sending message com.sixt.service.framework.kafka.messaging.SayHelloToCmd with key O+oRQ to topic cruft
    // loads of: 2017-04-12 18:14:41,340 [kafka-producer-network-thread | producer-2] WARN  o.apache.kafka.clients.NetworkClient - Error while fetching metadata with correlation id 0 : {cruft=UNKNOWN_TOPIC_OR_PARTITION}
    // and finally: org.apache.kafka.common.errors.TimeoutException: Failed to update metadata after 60000 ms.
    // 2.) WITH topic auto creation i.e. KAFKA_AUTO_CREATE_TOPICS_ENABLE = true
    // 2017-04-12 18:18:24,488 [Time-limited test] DEBUG c.s.s.f.kafka.messaging.Producer - Sending message com.sixt.service.framework.kafka.messaging.SayHelloToCmd with key uXdJ~ to topic cruft
    // one: 2017-04-12 18:18:24,638 [kafka-producer-network-thread | producer-2] WARN  o.apache.kafka.clients.NetworkClient - Error while fetching metadata with correlation id 0 : {cruft=LEADER_NOT_AVAILABLE
    // and finally: success
}
 
Example 39
Project: TorgCRM-Server   File: AccountResourceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
@Transactional
@WithMockUser("save-existing-email-and-login")
public void testSaveExistingEmailAndLogin() throws Exception {
    User user = new User();
    user.setLogin("save-existing-email-and-login");
    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("save-existing-email-and-login").orElse(null);
    assertThat(updatedUser.getEmail()).isEqualTo("[email protected]");
}
 
Example 40
Project: conf4j   File: EtcdFileConfigurationSourceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testConfigLoadedWithPropertiesFile() throws Exception {
    String filePath = "test.properties";
    String expectedMessage = RandomStringUtils.randomAlphanumeric(12);

    putFileInEtcd(filePath, String.format("message=%s", expectedMessage));
    testConfigLoaded(filePath, expectedMessage);
}
 
Example 41
Project: tokamak   File: RoleValidationTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldNotBeAbleToCreateARoleWhenTheRoleNameAlredyExists() {
	String name = RandomStringUtils.randomAlphanumeric(15);
	role().withName(name).save();

	onCreate(role().withName(name).build()).rejected().withError("ROL-0003", "This role name is already in use.", ResourceConflictException.class);
}
 
Example 42
Project: tokamak   File: PasswordPolicyValidationTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldNotBeAbleToCreateAPasswordPolicyWhenThePasswordPolicyNameAlredyExists() {
	String name = RandomStringUtils.randomAlphanumeric(15);

	passwordPolicy().withName(name).save();
	onCreate(passwordPolicy().withName(name).build()).rejected().withError("POL-0001", "This policy name is already in use.", ResourceConflictException.class);
}
 
Example 43
Project: randomito-all   File: MinMaxAnnotationPostProcessor.java   Source Code and License 5 votes vote down vote up
@Override
public Object process(AnnotationInfo ctx, Object value) throws Exception {
    if (!ctx.isAnnotationPresent(Min.class)
            && !ctx.isAnnotationPresent(Max.class)) {
        return value;
    }
    long minValue = 1;
    if (ctx.isAnnotationPresent(Min.class)) {
        minValue = ctx.getAnnotation(Min.class).value();
    }
    long maxValue = 50;
    if (ctx.isAnnotationPresent(Max.class)) {
        maxValue = ctx.getAnnotation(Max.class).value();
    }
    if (Number.class.isAssignableFrom(value.getClass())) {
        return range(String.valueOf(minValue), String.valueOf(maxValue), value.getClass());
    } else if (value instanceof String) {
        String strVal = (String) value;
        if (strVal.length() < minValue) {
            strVal += RandomStringUtils.randomAlphabetic((int) minValue - strVal.length());
        } else if (strVal.length() > maxValue) {
            strVal = strVal.substring(0, (int) maxValue);
        }
        return strVal;
    }
    return value;
}
 
Example 44
Project: spring-boot-start-current   File: AggregationServiceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void intoUser () throws Exception {
	User         user     = new User();
	final String username = "admin" + RandomStringUtils.randomNumeric( 3 );
	user.setEmail( "[email protected]" )
		.setNickName( "披荆斩棘" )
		.setUsername( username )
		.setEnabled( true )
		.setPassword( passwordEncoder.encode( "123456" ) );
	aggregationService.intoUser( user );

	System.err.println( "username = " + username );

}
 
Example 45
Project: xm-ms-dashboard   File: DefaultProfileResourceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
@Transactional
public void getDefaultProfileByRoleKey() throws Exception {
    String randRoleKey = RandomStringUtils.randomAlphabetic(5);
    int databaseSizeBeforeCreate = defaultProfileService.findAllByRoleKey(randRoleKey).size();

    defaultProfile.setRoleKey(randRoleKey);
    defaultProfileService.saveAndFlush(defaultProfile);

    // Get the defaultProfile by roleKey
    List<DefaultProfile> defaultProfiles = defaultProfileService.findAllByRoleKey(randRoleKey);
    assertThat(defaultProfiles).hasSize(databaseSizeBeforeCreate + 1);
    DefaultProfile testDefaultProfile = defaultProfiles.get(defaultProfiles.size() - 1);
    assertThat(testDefaultProfile.getRoleKey()).isEqualTo(randRoleKey);
}
 
Example 46
Project: codemotion-2017-taller-de-jhipster   File: UserResourceIntTest.java   Source Code and License 5 votes vote down vote up
/**
 * Create a User.
 *
 * This is a static method, as tests for other entities might also need it,
 * if they test an entity which has a required relationship to the User entity.
 */
public static User createEntity(EntityManager em) {
    User user = new User();
    user.setLogin(DEFAULT_LOGIN + RandomStringUtils.randomAlphabetic(5));
    user.setPassword(RandomStringUtils.random(60));
    user.setActivated(true);
    user.setEmail(RandomStringUtils.randomAlphabetic(5) + DEFAULT_EMAIL);
    user.setFirstName(DEFAULT_FIRSTNAME);
    user.setLastName(DEFAULT_LASTNAME);
    user.setImageUrl(DEFAULT_IMAGEURL);
    user.setLangKey(DEFAULT_LANGKEY);
    return user;
}
 
Example 47
Project: OpenLRW   File: XAPIExceptionHandlerAdvice.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(Exception.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public XAPIErrorInfo exception(final HttpServletRequest request, Exception e) throws Exception {
    final String logMessageReferenceId = RandomStringUtils.randomAlphanumeric(8);
    final XAPIErrorInfo result = new XAPIErrorInfo(HttpStatus.INTERNAL_SERVER_ERROR, request, "Unexpected error [reference ID: " + logMessageReferenceId + "].");
    logger.debug("Unexpected XAPI exception [refId: {}]: {}", logMessageReferenceId, e);
    this.logError(result);
    return result;
}
 
Example 48
Project: speakTogether   File: UserResourceIntTest.java   Source Code and License 4 votes vote down vote up
@Test
@Transactional
public void updateUserExistingEmail() throws Exception {
    // Initialize the database with 2 users
    userRepository.saveAndFlush(user);

    User anotherUser = new User();
    anotherUser.setLogin("jhipster");
    anotherUser.setPassword(RandomStringUtils.random(60));
    anotherUser.setActivated(true);
    anotherUser.setEmail("[email protected]");
    anotherUser.setFirstName("java");
    anotherUser.setLastName("hipster");
    anotherUser.setImageUrl("");
    anotherUser.setLangKey("en");
    userRepository.saveAndFlush(anotherUser);

    // Update the user
    User updatedUser = userRepository.findOne(user.getId());

    Set<String> authorities = new HashSet<>();
    authorities.add("ROLE_USER");
    ManagedUserVM managedUserVM = new ManagedUserVM(
        updatedUser.getId(),
        updatedUser.getLogin(),
        updatedUser.getPassword(),
        updatedUser.getFirstName(),
        updatedUser.getLastName(),
        "[email protected]",  // this email should already be used by anotherUser
        updatedUser.getActivated(),
        updatedUser.getImageUrl(),
        updatedUser.getLangKey(),
        updatedUser.getCreatedBy(),
        updatedUser.getCreatedDate(),
        updatedUser.getLastModifiedBy(),
        updatedUser.getLastModifiedDate(),
        authorities);

    restUserMockMvc.perform(put("/api/users")
        .contentType(TestUtil.APPLICATION_JSON_UTF8)
        .content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
        .andExpect(status().isBadRequest());
}
 
Example 49
Project: tokamak   File: AudienceValidationTest.java   Source Code and License 4 votes vote down vote up
@Test
public void shouldNotBeAbleToUpdateAnAudienceWhenTheAudienceDescriptionIsGreaterThan255Characters() {
	onUpdate(audience().withDescription(RandomStringUtils.randomAlphabetic(256)).build()).rejected().withError("AUD-0004", "An audience description cannot be greater than 255 characters.", UnprocessableEntityException.class);
}
 
Example 50
Project: xm-uaa   File: AccountResourceIntTest.java   Source Code and License 4 votes vote down vote up
@Test
@Transactional
public void testSaveExistingEmail() throws Exception {
    TenantContext.setCurrent(new TenantInfo("XM", null, "test1", null, null, null, null));

    UserLogin userLogin = new UserLogin();
    userLogin.setTypeKey(UserLoginType.EMAIL.getValue());
    userLogin.setLogin("save-existing-email");

    User user = new User();
    user.setUserKey("test");
    user.setPassword(RandomStringUtils.random(60));
    user.setActivated(true);
    userLogin.setUser(user);
    user.getLogins().add(userLogin);

    userRepository.saveAndFlush(user);

    User anotherUser = new User();
    anotherUser.setUserKey("test1");
    anotherUser.setPassword(RandomStringUtils.random(60));
    anotherUser.setActivated(true);

    userRepository.saveAndFlush(anotherUser);

    UserDTO userDTO = new UserDTO(
        anotherUser.getId(),                   // id
        "firstname",               // firstName
        "lastname",                  // lastName
        "http://placehold.it/50x50", //imageUrl
        false,                   // activated
        "en",                   // langKey
        null,                   // createdBy
        null,                   // createdDate
        null,                   // lastModifiedBy
        null,                   // lastModifiedDate
        new HashSet<>(Collections.singletonList(AuthoritiesConstants.ADMIN)),
        "test1",
        null, null, null, Collections.singletonList(userLogin)
    );

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

    User updatedUser = userRepository.findOne(anotherUser.getId());
    assertThat(updatedUser.getFirstName()).isNullOrEmpty();
    assertThat(updatedUser.getLastName()).isNullOrEmpty();
    assertThat(updatedUser.getImageUrl()).isNullOrEmpty();
}
 
Example 51
Project: YouTrends   File: UserDAO.java   Source Code and License 4 votes vote down vote up
public String registerUserIfNotExist(User user)
{
    String password = RandomStringUtils.random(10, "zvnjfsqw1234567890");

    String query = "SELECT * FROM Users WHERE id = ?";
    String insertQuery = "INSERT INTO Users (id, firstName, lastName, userName, language, isBot, password) " +
                         "VALUES (?, ?, ?, ?, ?, ?, ?) " +
                         "ON CONFLICT (id) DO UPDATE SET " +
                         "firstName = ?," +
                         "lastName =?," +
                         "userName = ?," +
                         "language = ?";

    try
    {
        StringBuilder stringBuilder = new StringBuilder();

        jdbcTemplate.query(query, result ->
        {
            String pas = result.getString("password");
            if (pas != null)
            {
                stringBuilder.append(pas);
            }
        }, user.getId());

        if (stringBuilder.length() == 0)
        {
            jdbcTemplate.update(insertQuery,
                                user.getId(),
                                user.getFirstName(),
                                user.getLastName(),
                                user.getUserName(),
                                user.getLanguageCode(),
                                user.getBot(),
                                password,

                                user.getFirstName(),
                                user.getLastName(),
                                user.getUserName(),
                                user.getLanguageCode()
                                );
            return password;
        }
    }
    catch (Exception e)
    {
        logger.error("Error", e);
    }

    return null;
}
 
Example 52
Project: tokamak   File: AudienceValidationTest.java   Source Code and License 4 votes vote down vote up
@Test
public void shouldNotBeAbleToCreateAnAudienceWhenTheAudienceDescriptionIsGreaterThan255Characters() {
	onCreate(audience().withDescription(RandomStringUtils.randomAlphabetic(256)).build()).rejected().withError("AUD-0004", "An audience description cannot be greater than 255 characters.", UnprocessableEntityException.class);
}
 
Example 53
Project: flink-connectors   File: FlinkPravegaInputFormatITCase.java   Source Code and License 4 votes vote down vote up
/**
 * Verifies that the input format:
 *  - correctly reads all records in a given set of multiple Pravega streams
 *  - allows multiple executions
 */
@Test
public void testBatchInput() throws Exception {
    final int numElements1 = 100;
    final int numElements2 = 300;

    // set up the stream
    final String streamName1 = RandomStringUtils.randomAlphabetic(20);
    final String streamName2 = RandomStringUtils.randomAlphabetic(20);

    final Set<String> streams = new HashSet<>();
    streams.add(streamName1);
    streams.add(streamName2);

    SETUP_UTILS.createTestStream(streamName1, 3);
    SETUP_UTILS.createTestStream(streamName2, 5);

    try (
            final EventStreamWriter<Integer> eventWriter1 = SETUP_UTILS.getIntegerWriter(streamName1);
            final EventStreamWriter<Integer> eventWriter2 = SETUP_UTILS.getIntegerWriter(streamName2);

            // create the producer that writes to the stream
            final ThrottledIntegerWriter producer1 = new ThrottledIntegerWriter(
                    eventWriter1,
                    numElements1,
                    numElements1 + 1, // no need to block writer for a batch test
                    0
            );

            final ThrottledIntegerWriter producer2 = new ThrottledIntegerWriter(
                    eventWriter2,
                    numElements2,
                    numElements2 + 1, // no need to block writer for a batch test
                    0
            )
    ) {
        // write batch input
        producer1.start();
        producer2.start();

        producer1.sync();
        producer2.sync();

        final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(3);

        // simple pipeline that reads from Pravega and collects the events
        DataSet<Integer> integers = env.createInput(
                new FlinkPravegaInputFormat<>(
                        SETUP_UTILS.getControllerUri(),
                        SETUP_UTILS.getScope(),
                        streams,
                        new IntDeserializer()),
                BasicTypeInfo.INT_TYPE_INFO
        );

        // verify that all events were read
        Assert.assertEquals(numElements1 + numElements2, integers.collect().size());

        // this verifies that the input format allows multiple passes
        Assert.assertEquals(numElements1 + numElements2, integers.collect().size());
    }
}
 
Example 54
Project: WebAutomation_AllureParallel   File: RandomGenerator.java   Source Code and License 4 votes vote down vote up
public static String GenerateRandomASCIICharacters(int length)
{
	return RandomStringUtils.randomAscii(length).toString();
}
 
Example 55
Project: util   File: RandomUtil.java   Source Code and License 4 votes vote down vote up
/**
 * 随机字母或数字,随机长度
 */
public static String randomStringRandomLength(Random random, int minLength, int maxLength) {
	return RandomStringUtils.random(nextInt(random, minLength, maxLength), 0, 0, true, true, null, random);
}
 
Example 56
Project: util   File: RandomUtil.java   Source Code and License 4 votes vote down vote up
/**
 * 随机ASCII字符(含字母,数字及其他符号),固定长度
 */
public static String randomAsciiFixLength(Random random, int length) {
	return RandomStringUtils.random(length, 32, 127, false, false, null, random);
}
 
Example 57
Project: clemon   File: GuidUtil.java   Source Code and License 4 votes vote down vote up
public static String generateClientSecret(){
	return RandomStringUtils.random(20, true, true);
}
 
Example 58
Project: codemotion-2017-taller-de-jhipster   File: AccountResourceIntTest.java   Source Code and License 4 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(
        null,                   // id
        "not-used",          // login
        "firstname",                // firstName
        "lastname",                  // lastName
        "[email protected]",    // email
        false,                   // activated
        "http://placehold.it/50x50", //imageUrl
        Constants.DEFAULT_LANGUAGE,// langKey
        null,                   // createdBy
        null,                   // createdDate
        null,                   // lastModifiedBy
        null,                   // lastModifiedDate
        new HashSet<>(Collections.singletonList(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 59
Project: jhipster-microservices-example   File: UserResourceIntTest.java   Source Code and License 4 votes vote down vote up
@Test
@Transactional
public void updateUserExistingEmail() throws Exception {
    // Initialize the database with 2 users
    userRepository.saveAndFlush(user);
    userSearchRepository.save(user);

    User anotherUser = new User();
    anotherUser.setLogin("jhipster");
    anotherUser.setPassword(RandomStringUtils.random(60));
    anotherUser.setActivated(true);
    anotherUser.setEmail("[email protected]");
    anotherUser.setFirstName("java");
    anotherUser.setLastName("hipster");
    anotherUser.setImageUrl("");
    anotherUser.setLangKey("en");
    userRepository.saveAndFlush(anotherUser);
    userSearchRepository.save(anotherUser);

    // Update the user
    User updatedUser = userRepository.findOne(user.getId());

    Set<String> authorities = new HashSet<>();
    authorities.add("ROLE_USER");
    ManagedUserVM managedUserVM = new ManagedUserVM(
        updatedUser.getId(),
        updatedUser.getLogin(),
        updatedUser.getPassword(),
        updatedUser.getFirstName(),
        updatedUser.getLastName(),
        "[email protected]",  // this email should already be used by anotherUser
        updatedUser.getActivated(),
        updatedUser.getImageUrl(),
        updatedUser.getLangKey(),
        updatedUser.getCreatedBy(),
        updatedUser.getCreatedDate(),
        updatedUser.getLastModifiedBy(),
        updatedUser.getLastModifiedDate(),
        authorities);

    restUserMockMvc.perform(put("/api/users")
        .contentType(TestUtil.APPLICATION_JSON_UTF8)
        .content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
        .andExpect(status().isBadRequest());
}
 
Example 60
Project: jhipster-microservices-example   File: UserResourceIntTest.java   Source Code and License 4 votes vote down vote up
@Test
@Transactional
public void updateUserExistingLogin() throws Exception {
    // Initialize the database
    userRepository.saveAndFlush(user);
    userSearchRepository.save(user);

    User anotherUser = new User();
    anotherUser.setLogin("jhipster");
    anotherUser.setPassword(RandomStringUtils.random(60));
    anotherUser.setActivated(true);
    anotherUser.setEmail("[email protected]");
    anotherUser.setFirstName("java");
    anotherUser.setLastName("hipster");
    anotherUser.setImageUrl("");
    anotherUser.setLangKey("en");
    userRepository.saveAndFlush(anotherUser);
    userSearchRepository.save(anotherUser);

    // Update the user
    User updatedUser = userRepository.findOne(user.getId());

    Set<String> authorities = new HashSet<>();
    authorities.add("ROLE_USER");
    ManagedUserVM managedUserVM = new ManagedUserVM(
        updatedUser.getId(),
        "jhipster", // this login should already be used by anotherUser
        updatedUser.getPassword(),
        updatedUser.getFirstName(),
        updatedUser.getLastName(),
        updatedUser.getEmail(),
        updatedUser.getActivated(),
        updatedUser.getImageUrl(),
        updatedUser.getLangKey(),
        updatedUser.getCreatedBy(),
        updatedUser.getCreatedDate(),
        updatedUser.getLastModifiedBy(),
        updatedUser.getLastModifiedDate(),
        authorities);

    restUserMockMvc.perform(put("/api/users")
        .contentType(TestUtil.APPLICATION_JSON_UTF8)
        .content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
        .andExpect(status().isBadRequest());
}