Java Code Examples for org.apache.commons.lang3.RandomStringUtils#random()

The following examples show how to use org.apache.commons.lang3.RandomStringUtils#random() . 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: SelectionOperatorPerformanceTest.java    From jtwig-core with Apache License 2.0 6 votes vote down vote up
@Test
public void select() throws Exception {
    GroupedTimingStatistics groupedTimingStatistics = new GroupedTimingStatistics();
    groupedTimingStatistics.setStartTime(System.currentTimeMillis());

    JtwigTemplate jtwigTemplate = JtwigTemplate.inlineTemplate("{{ var.nested.field[0] }}");
    for (int i = 0; i < SIZE; i++) {
        StopWatch stopWatch = new StopWatch("selection");
        String random = RandomStringUtils.random(6);
        JtwigModel jtwigModel = newModel().with("var", new SelectionTest.TestClass(random));
        stopWatch.start();
        jtwigTemplate.render(jtwigModel);
        stopWatch.stop();
        groupedTimingStatistics.addStopWatch(stopWatch);
    }

    groupedTimingStatistics.setStopTime(System.currentTimeMillis());
    System.out.println(groupedTimingStatistics.toString());
}
 
Example 2
Source File: MongoDbIntegrationTests.java    From spring-tutorials with Apache License 2.0 6 votes vote down vote up
@Test
public void test_MongoTemplate_UpdateFirst() {
	String firstName = "firstName"+ RandomStringUtils.random(3);
	String lastName  = "lastName"+ RandomStringUtils.random(3);
	savePerson(firstName, lastName);

	final String updateFirstNameTo = "TESTER";
	mongoTemplate.updateFirst(
			query(where("lastname").is(lastName)),
			update("firstname", updateFirstNameTo),
			Person.class);

	Person foundPerson = mongoTemplate.findOne(
			query(where("lastname").is(lastName)),
			Person.class);

	Assert.isTrue(foundPerson != null, "Must not be null");
	Assert.isTrue(foundPerson.getFirstname().equals(updateFirstNameTo), "Must have changed");
}
 
Example 3
Source File: TestTypedRDBTableStore.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsExist() throws Exception {
  try (Table<String, String> testTable = createTypedTable(
      "Eighth")) {
    String key =
        RandomStringUtils.random(10);
    String value = RandomStringUtils.random(10);
    testTable.put(key, value);
    Assert.assertTrue(testTable.isExist(key));

    String invalidKey = key + RandomStringUtils.random(1);
    Assert.assertFalse(testTable.isExist(invalidKey));

    testTable.delete(key);
    Assert.assertFalse(testTable.isExist(key));
  }
}
 
Example 4
Source File: AccountResourceIntTest.java    From Spring-5.0-Projects with MIT License 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 5
Source File: AccountResourceIntTest.java    From 21-points with Apache License 2.0 6 votes vote down vote up
@Test
@Transactional
@WithMockUser("change-password-wrong-existing-password")
public void testChangePasswordWrongExistingPassword() throws Exception {
    User user = new User();
    String currentPassword = RandomStringUtils.random(60);
    user.setPassword(passwordEncoder.encode(currentPassword));
    user.setLogin("change-password-wrong-existing-password");
    user.setEmail("[email protected]");
    userRepository.saveAndFlush(user);

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

    User updatedUser = userRepository.findOneByLogin("change-password-wrong-existing-password").orElse(null);
    assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isFalse();
    assertThat(passwordEncoder.matches(currentPassword, updatedUser.getPassword())).isTrue();
}
 
Example 6
Source File: WalletTest.java    From offspring with MIT License 5 votes vote down vote up
private String generate() {
  String symbols = "!\"$%^&*()-_=+[{]};:'@#~|,<.>/?\n\t\\\r";
  String alphaNum = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890";
  int low = 96;
  int high = 145;
  Random random = new Random();
  int count = random.nextInt(high - low) + low;
  return RandomStringUtils.random(count, symbols + alphaNum);
}
 
Example 7
Source File: ScenarioBuilderTest.java    From validator with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasicAttributes() {
    final ContentRepository repository = Simple.createContentRepository();
    final String random = RandomStringUtils.random(5);
    final ScenarioBuilder builder = createScenario();
    builder.name(random).description(random);
    final Result<Scenario, String> result = builder.build(repository);
    assertThat(result.isValid()).isTrue();
    final ScenarioType config = result.getObject().getConfiguration();
    assertThat(config.getName()).isEqualTo(random);
    assertThat(config.getDescription()).isNotNull();
    assertThat(config.getDescription().getPOrOlOrUl()).isNotEmpty();
}
 
Example 8
Source File: FileAgentTest.java    From PeerWasp with MIT License 5 votes vote down vote up
@Test
public void testReadWrongKey() throws IOException {
	String data = RandomStringUtils.random(1000);
	fileAgent.writeCache("key", data.getBytes());
	byte[] read = fileAgent.readCache("wrongKey");
	assertNull(read);
}
 
Example 9
Source File: Utils.java    From peer-os with Apache License 2.0 5 votes vote down vote up
/**
 * Generate random password. If no digits and no special characters included, letters will be used by default.
 *
 * @param minLength password minimum length
 * @param maxLength password maximum length
 * @param digits include digits
 * @param letters include ASCII letters(both lower and upper case)
 * @param specialChars include following characters: "!@#$%^&*()-=[]{};:.,"
 */
public static String generatePassword( int minLength, int maxLength, boolean digits, boolean letters,
                                       boolean specialChars )
{
    Preconditions.checkArgument( minLength > 0, "Invalid min length" );
    Preconditions.checkArgument( maxLength > 0 && maxLength >= minLength, "Invalid max length" );

    StringBuilder chars = new StringBuilder();

    if ( letters || !digits && !specialChars )
    {
        chars.append( "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" );
    }

    if ( digits )
    {
        chars.append( "0123456789" );
    }

    if ( specialChars )
    {
        chars.append( "!#$%^&*()=[]{};:.,<>?" );
    }

    int length = minLength + new Random().nextInt( maxLength - minLength );

    return RandomStringUtils.random( length, chars.toString() );
}
 
Example 10
Source File: MediaEntityTestITCase.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void update() throws IOException {
  final UUID uuid = UUID.fromString("f89dee73-af9f-4cd4-b330-db93c25ff3c7");
  final Advertisement adv = getContainer().getAdvertisements().getByKey(uuid);
  final String random = RandomStringUtils.random(124, "abcdefghijklmnopqrstuvwxyz");
  adv.uploadStream(getContainer().newEdmStreamValue("application/octet-stream", IOUtils.toInputStream(random)));
  getContainer().flush();
  assertEquals(random,
      IOUtils.toString(getContainer().getAdvertisements().getByKey(uuid).loadStream().getStream()));
  getService().getContext().detachAll();
}
 
Example 11
Source File: DirectServiceEndpointFinderTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private ServiceEndpointRequest<HttpsServiceEndpoint> createServiceEndpointRequest(String hostAddressString, Integer port) {
    String targetInstanceId = RandomStringUtils.random(10);
    HostEndpoint hostEndpoint = mock(HostEndpoint.class);
    when(hostEndpoint.getHostAddressString()).thenReturn(hostAddressString);
    int randomValue = RandomUtils.nextInt(0, 2);
    ServiceFamily<HttpsServiceEndpoint> serviceFamily = (randomValue == 0) ? ServiceFamilies.GATEWAY : ServiceFamilies.KNOX;
    return ServiceEndpointRequest.createDefaultServiceEndpointRequest(targetInstanceId, hostEndpoint, port, serviceFamily, false);
}
 
Example 12
Source File: RandomUtil.java    From vjtools with Apache License 2.0 4 votes vote down vote up
/**
 * 随机字母,固定长度
 */
public static String randomLetterFixLength(int length) {
	return RandomStringUtils.random(length, 0, 0, true, false, null, threadLocalRandom());
}
 
Example 13
Source File: Hash.java    From codenjoy with GNU General Public License v3.0 4 votes vote down vote up
public static String getRandomId() {
    return RandomStringUtils.random(ID_LENGTH, "abcdefghijklmnopqrstuvwxyz1234567890");
}
 
Example 14
Source File: RandomUtil.java    From vjtools with Apache License 2.0 4 votes vote down vote up
/**
 * 随机字母或数字,固定长度
 */
public static String randomStringFixLength(int length) {
	return RandomStringUtils.random(length, 0, 0, true, true, null, threadLocalRandom());
}
 
Example 15
Source File: DataGenerator.java    From twister2 with Apache License 2.0 4 votes vote down vote up
private static String generateRandom(int length) {
  boolean useLetters = true;
  boolean useNumbers = false;
  return RandomStringUtils.random(length, useLetters, useNumbers);
}
 
Example 16
Source File: RandomUtil.java    From vjtools with Apache License 2.0 4 votes vote down vote up
/**
 * 随机字母,固定长度
 */
public static String randomLetterFixLength(int length) {
	return RandomStringUtils.random(length, 0, 0, true, false, null, threadLocalRandom());
}
 
Example 17
Source File: RandomUtil.java    From vjtools with Apache License 2.0 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 18
Source File: BaseServiceImplTest.java    From commercetools-sync-java with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
void fetchMatchingResources_WithKeySet_ShouldFetchResourcesAndCacheKeys() {
    //preparation
    final String key1 = RandomStringUtils.random(15);
    final String key2 = RandomStringUtils.random(15);

    final HashSet<String> resourceKeys = new HashSet<>();
    resourceKeys.add(key1);
    resourceKeys.add(key2);

    final Product mock1 = mock(Product.class);
    when(mock1.getId()).thenReturn(RandomStringUtils.random(15));
    when(mock1.getKey()).thenReturn(key1);

    final Product mock2 = mock(Product.class);
    when(mock2.getId()).thenReturn(RandomStringUtils.random(15));
    when(mock2.getKey()).thenReturn(key2);

    final PagedQueryResult result = mock(PagedQueryResult.class);
    when(result.getResults()).thenReturn(Arrays.asList(mock1, mock2));

    when(client.execute(any(ProductQuery.class))).thenReturn(completedFuture(result));

    //test fetch
    final Set<Product> resources = service
        .fetchMatchingProductsByKeys(resourceKeys)
        .toCompletableFuture().join();

    //assertions
    assertThat(resources).containsExactlyInAnyOrder(mock1, mock2);
    verify(client, times(1)).execute(any(ProductQuery.class));

    //test caching
    final Optional<String> cachedKey1 = service
        .getIdFromCacheOrFetch(mock1.getKey())
        .toCompletableFuture().join();

    final Optional<String> cachedKey2 = service
        .getIdFromCacheOrFetch(mock2.getKey())
        .toCompletableFuture().join();

    //assertions
    assertThat(cachedKey1).contains(mock1.getId());
    assertThat(cachedKey2).contains(mock2.getId());
    // still 1 request from the first #fetchMatchingProductsByKeys call
    verify(client, times(1)).execute(any(ProductQuery.class));
}
 
Example 19
Source File: RandomUtil.java    From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * 随机字母或数字,随机长度
 */
public static String randomStringRandomLength(int minLength, int maxLength) {
	return RandomStringUtils.random(nextInt(minLength, maxLength), 0, 0, true, true, null, threadLocalRandom());
}
 
Example 20
Source File: RandomisedUrlService.java    From sakai with Educational Community License v2.0 2 votes vote down vote up
/**
 * Generate a random of RandomisedUrlService.SECURE length
 * @return
 */
private String generateSecure() {
	return RandomStringUtils.random(SECURE, true, true);
}