org.apache.commons.lang.RandomStringUtils Java Examples

The following examples show how to use org.apache.commons.lang.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: SmsMessageSenderTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void generateRecipients( int size )
{
    generatedRecipients.clear();

    for ( int i = 0; i < size; i++ )
    {
        String temp = RandomStringUtils.random( 10, false, true );

        if ( generatedRecipients.contains( temp ) )
        {
            i--;
            continue;
        }

        generatedRecipients.add( temp );
    }
}
 
Example #2
Source File: BatchInsertTest.java    From tddl5 with Apache License 2.0 6 votes vote down vote up
/**
 * 有部分列没有使用绑定变量,会造成顺序不一致,测试此时的映射情况
 * 
 * @author zhuoxue
 * @since 5.0.1
 */
@Test
public void insertAllFieldTestWithSomeFieldCostants() throws Exception {
    String sql = "insert into " + normaltblTableName + " values(?,?,?,?,?,'123',?)";

    List<List<Object>> params = new ArrayList();

    for (int i = 0; i < 100; i++) {
        List<Object> param = new ArrayList<Object>();
        param.add(Long.valueOf(RandomStringUtils.randomNumeric(8)));
        param.add(Long.valueOf(RandomStringUtils.randomNumeric(8)));
        param.add(gmtDay);
        param.add(gmt);
        param.add(gmt);
        // param.add(name);
        param.add(fl);

        params.add(param);
    }
    executeBatch(sql, params);

    sql = "select * from " + normaltblTableName;
    String[] columnParam = { "PK", "ID", "GMT_CREATE", "NAME", "FLOATCOL", "GMT_TIMESTAMP", "GMT_DATETIME" };
    selectContentSameAssert(sql, columnParam, Collections.EMPTY_LIST);
}
 
Example #3
Source File: FileMonitorTest.java    From OpenAs2App with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void shouldTriggerListenersWhenFileChanged() throws Exception {
    File fileToObserve = Mockito.spy(temp.newFile());

    FileMonitor fileMonitor = new FileMonitor(fileToObserve, listener);
    verifyZeroInteractions(listener);

    fileMonitor.run();
    verifyZeroInteractions(listener);

    FileUtils.write(fileToObserve, RandomStringUtils.randomAlphanumeric(1024), "UTF-8");
    doReturn(new Date().getTime() + 3).when(fileToObserve).lastModified();
    fileMonitor.run();

    verify(listener).onFileEvent(eq(fileToObserve), eq(FileMonitorListener.EVENT_MODIFIED));
    reset(listener);

    fileMonitor.run();
    verifyZeroInteractions(listener);

}
 
Example #4
Source File: KubernetesSlave.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
static String getSlaveName(PodTemplate template) {
    String randString = RandomStringUtils.random(5, "bcdfghjklmnpqrstvwxz0123456789");
    String name = template.getName();
    if (StringUtils.isEmpty(name)) {
        return String.format("%s-%s", DEFAULT_AGENT_PREFIX,  randString);
    }
    // no spaces
    name = name.replaceAll("[ _]", "-").toLowerCase();
    // keep it under 63 chars (62 is used to account for the '-')
    name = name.substring(0, Math.min(name.length(), 62 - randString.length()));
    String slaveName = String.format("%s-%s", name, randString);
    if (!slaveName.matches("[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*")) {
        return String.format("%s-%s", DEFAULT_AGENT_PREFIX, randString);
    }
    return slaveName;
}
 
Example #5
Source File: AggregationGroupByTrimmingServiceTest.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void setUp() {
  // Generate a list of random groups.
  Set<String> groupSet = new HashSet<>(NUM_GROUPS);
  while (groupSet.size() < NUM_GROUPS) {
    List<String> group = new ArrayList<>(NUM_GROUP_KEYS);
    for (int i = 0; i < NUM_GROUP_KEYS; i++) {
      // Randomly generate group key without GROUP_KEY_DELIMITER
      group.add(RandomStringUtils.random(RANDOM.nextInt(10)).replace(GroupKeyGenerator.DELIMITER, ""));
    }
    groupSet.add(buildGroupString(group));
  }
  _groups = new ArrayList<>(groupSet);

  // Explicitly set an empty group
  StringBuilder emptyGroupBuilder = new StringBuilder();
  for (int i = 1; i < NUM_GROUP_KEYS; i++) {
    emptyGroupBuilder.append(GroupKeyGenerator.DELIMITER);
  }
  _groups.set(NUM_GROUPS - 1, emptyGroupBuilder.toString());

  _trimmingService = new AggregationGroupByTrimmingService(AGGREGATION_FUNCTIONS, GROUP_BY_TOP_N);
}
 
Example #6
Source File: ImportCollectionIT.java    From usergrid with Apache License 2.0 6 votes vote down vote up
@Before
public void before() {

    boolean configured =
               !StringUtils.isEmpty(System.getProperty( SDKGlobalConfiguration.SECRET_KEY_ENV_VAR))
            && !StringUtils.isEmpty(System.getProperty( SDKGlobalConfiguration.ACCESS_KEY_ENV_VAR))
            && !StringUtils.isEmpty(System.getProperty("bucketName"));

    if ( !configured ) {
        logger.warn("Skipping test because {}, {} and bucketName not " +
            "specified as system properties, e.g. in your Maven settings.xml file.",
            new Object[] {
                SDKGlobalConfiguration.SECRET_KEY_ENV_VAR,
                SDKGlobalConfiguration.ACCESS_KEY_ENV_VAR
            });
    }

    Assume.assumeTrue( configured );

    adminUser = newOrgAppAdminRule.getAdminInfo();
    organization = newOrgAppAdminRule.getOrganizationInfo();
    applicationId = newOrgAppAdminRule.getApplicationInfo().getId();


    bucketName = bucketPrefix + RandomStringUtils.randomAlphanumeric(10).toLowerCase();
}
 
Example #7
Source File: DemoTravelCompanyCompletionRequestAft.java    From rice with Educational Community License v2.0 6 votes vote down vote up
protected void travelAccountCreateDocument(String principalName) throws Exception {
    waitAndTypeByName(DESCRIPTION_FIELD,"Travel Company Super User Test");
    String randomCode = RandomStringUtils.randomAlphabetic(9).toUpperCase();
    waitAndTypeByName(COMPANY_NAME_FIELD, "Company Name " + randomCode);

    waitAndClickByLinkText("Ad Hoc Recipients");
    waitAndTypeByName("newCollectionLines['document.adHocRoutePersons'].actionRequested", "Complete");
    waitAndTypeByName("newCollectionLines['document.adHocRoutePersons'].id", principalName);
    jGrowl("Click Add button");
    waitAndClickById("Uif-AdHocPersonCollection_add");
    waitForElementPresentByXpath(
            "//div[@data-parent=\"Uif-AdHocPersonCollection\"]/div/span[contains(text(), principalName]");
    waitAndClickByLinkText("Ad Hoc Recipients");

    waitAndClickSubmitByText();
    waitAndClickConfirmSubmitOk();
    waitForProgress("Loading...", WebDriverUtils.configuredImplicityWait() * 4);
    waitForTextPresent("Document was successfully submitted.", WebDriverUtils.configuredImplicityWait() * 2);
}
 
Example #8
Source File: BytesUtilTest.java    From indexr with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
    int valCount = 65536;
    Random random = new Random();
    ArrayList<byte[]> strings = new ArrayList<>();
    for (int i = 0; i < valCount; i++) {
        byte[] s = UTF8Util.toUtf8(RandomStringUtils.randomAlphabetic(random.nextInt(30)));
        strings.add(s);
    }

    Collections.sort(strings, comparator);

    byte[] last = null;
    for (byte[] v : strings) {
        if (last != null) {
            Assert.assertTrue(comparator.compare(last, v) <= 0);
        }
        last = v;
    }
}
 
Example #9
Source File: ExportServiceIT.java    From usergrid with Apache License 2.0 6 votes vote down vote up
@Before
public void before() {

    boolean configured =
        !StringUtils.isEmpty(System.getProperty( SDKGlobalConfiguration.SECRET_KEY_ENV_VAR))
            && !StringUtils.isEmpty(System.getProperty( SDKGlobalConfiguration.ACCESS_KEY_ENV_VAR))
            && !StringUtils.isEmpty(System.getProperty("bucketName"));

    if ( !configured ) {
        logger.warn("Skipping test because {}, {} and bucketName not " +
                "specified as system properties, e.g. in your Maven settings.xml file.",
            new Object[] {
                SDKGlobalConfiguration.SECRET_KEY_ENV_VAR,
                SDKGlobalConfiguration.ACCESS_KEY_ENV_VAR
            });
    }

    Assume.assumeTrue( configured );

    adminUser = newOrgAppAdminRule.getAdminInfo();
    organization = newOrgAppAdminRule.getOrganizationInfo();
    applicationId = newOrgAppAdminRule.getApplicationInfo().getId();

    bucketPrefix = System.getProperty( "bucketName" );
    bucketName = bucketPrefix + RandomStringUtils.randomAlphanumeric(10).toLowerCase();
}
 
Example #10
Source File: CommonFactory.java    From spacewalk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a TinyUrl
 * @param urlIn to tinyfy
 * @param expires the date we *ADD* 6 hours to to set the expiration on the URL
 * @return TinyUrl instance
 */
public static TinyUrl createTinyUrl(String urlIn, Date expires) {
    String token = RandomStringUtils.randomAlphanumeric(8);
    TinyUrl existing = lookupTinyUrl(token);
    while (existing != null) {
        log.warn("Had collision with: " + token);
        token = RandomStringUtils.randomAlphanumeric(8);
        existing = lookupTinyUrl(token);
    }

    TinyUrl url = new TinyUrl();
    Config c = new Config();
    url.setUrl(urlIn);
    url.setEnabled(true);
    url.setToken(token);
    Calendar pcal = Calendar.getInstance();
    pcal.setTime(expires);
    pcal.add(Calendar.HOUR, c.getInt("server.satellite.tiny_url_timeout", 4));
    url.setExpires(new Date(pcal.getTimeInMillis()));
    return url;
}
 
Example #11
Source File: TermMaintenanceNewAft.java    From rice with Educational Community License v2.0 6 votes vote down vote up
protected void createNewEnterDetails() throws InterruptedException {
    selectFrameIframePortlet();
    waitAndClickLinkContainingText("Create New");

    String randomCode = RandomStringUtils.randomAlphabetic(9).toUpperCase();
    waitAndTypeByName("document.newMaintainableObject.dataObject.description","New Term " + randomCode);
    waitAndTypeByName("document.newMaintainableObject.dataObject.specificationId", "T1000");
    fireEvent("document.newMaintainableObject.dataObject.specificationId", "blur");
    waitForProgressLoading();
    waitForTextPresent("campusSize");
    waitForTextPresent("java.lang.Integer");
    waitForElementPresentByXpath("//label[contains(text(),'Specification Description')]/span[contains(text(),'Size in # of students of the campus')]");
    waitAndTypeByName("document.newMaintainableObject.dataObject.parametersMap[Campus Code]","FakeCampus" + randomCode);

    waitAndClickByXpath("//button[contains(text(),'Submit')]");
    waitAndClickConfirmSubmitOk();
    waitForProgressLoading();
    waitForTextPresent("Document was successfully submitted.", WebDriverUtils.configuredImplicityWait() * 2);
    waitForTextPresent("FakeCampus" + randomCode);
}
 
Example #12
Source File: VarByteSingleColumnSingleValueReaderWriterTest.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@Test
public void testBytes()
    throws IOException {
  int initialCapacity = 5;
  int estimatedAvgStringLength = 30;
  try (VarByteSingleColumnSingleValueReaderWriter readerWriter =
      new VarByteSingleColumnSingleValueReaderWriter(_memoryManager, "StringColumn",  initialCapacity, estimatedAvgStringLength)) {
    int rows = 1000;
    Random random = new Random();
    String[] data = new String[rows];

    for (int i = 0; i < rows; i++) {
      int length = 10 + random.nextInt(100 - 10);
      data[i] = RandomStringUtils.randomAlphanumeric(length);
      readerWriter.setBytes(i, StringUtil.encodeUtf8(data[i]));
    }

    for (int i = 0; i < rows; i++) {
      Assert.assertEquals(StringUtil.decodeUtf8(readerWriter.getBytes(i)), data[i]);
    }
  }
}
 
Example #13
Source File: ObjectUpdateSynchronizerTest.java    From atlas with Apache License 2.0 5 votes vote down vote up
public void run() {
    objectUpdateSynchronizer.lockObject(CollectionUtils.arrayToList(ids));
    for (int i = 0; i < MAX_COUNT; i++) {
        outputList.add(i);
        RandomStringUtils.randomAlphabetic(20);
    }

    objectUpdateSynchronizer.releaseLockedObjects();
}
 
Example #14
Source File: AuditLogSerializationTest.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAuditLogs() throws Exception {

    CassandraClient cassandraClient = getInjector().getInstance( CassandraClientImpl.class );

    AuditLogSerialization logSerialization = getInjector().getInstance( AuditLogSerialization.class );

    // record some audit logs for a message
    UUID messageId = UUIDGen.getTimeUUID();
    String queueName = "alst_queue_" + RandomStringUtils.randomAlphanumeric( 15 );
    String source = RandomStringUtils.randomAlphanumeric( 15 );
    String dest = RandomStringUtils.randomAlphanumeric( 15 );

    int numLogs = 10;

    UUID queueMessageId1 = UUIDGen.getTimeUUID();
    for ( int i=0; i<numLogs; i++ ) {
        logSerialization.recordAuditLog( AuditLog.Action.GET, AuditLog.Status.SUCCESS,
                queueName, dest, messageId, queueMessageId1 );
        Thread.sleep(5);
    }

    UUID queueMessageId2 = UUIDGen.getTimeUUID();
    for ( int i=0; i<numLogs; i++ ) {
        logSerialization.recordAuditLog( AuditLog.Action.GET, AuditLog.Status.SUCCESS,
                queueName, dest, messageId, queueMessageId2 );
        Thread.sleep(5);
    }

    UUID queueMessageId3 = UUIDGen.getTimeUUID();
    for ( int i=0; i<numLogs; i++ ) {
        logSerialization.recordAuditLog( AuditLog.Action.GET, AuditLog.Status.SUCCESS,
                queueName, dest, messageId, queueMessageId3 );
        Thread.sleep(5);
    }

    // test that we have 3 X number of logs for the messageId
    Result<AuditLog> result = logSerialization.getAuditLogs( messageId );
    Assert.assertEquals( numLogs * 3, result.getEntities().size() );
}
 
Example #15
Source File: ProducerDriver.java    From ameliant-tools with Apache License 2.0 5 votes vote down vote up
private String generateMessage(String messageLocation, int messageSize) {
    if (messageLocation == null) {
        Validate.isTrue(messageSize > 0, "messageSize must be greater than 0");
        return RandomStringUtils.randomAlphanumeric(messageSize);
    } else {
        log.debug("Loading payload from {}", messageLocation);
        return new FileLoader().loadFileAsString(messageLocation);
    }
}
 
Example #16
Source File: ArrayBasedGlobalDictionaries.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
private String[] generateDerivedStringValuesForGD(OrigAndDerivedValueHolder valueHolder) {
  int cardinality = valueHolder._index;
  String[] values = new String[cardinality];
  for (int i = 0; i < cardinality; i++) {
    String val = (String)valueHolder._origValues[i];
    if (val == null || val.equals("") || val.equals(" ") || val.equals("null")) {
      values[i] = "null";
    } else {
      int origValLength = val.length();
      values[i] = RandomStringUtils.randomAlphanumeric(origValLength);
    }
  }
  Arrays.sort(values);
  return values;
}
 
Example #17
Source File: PathUtils.java    From hadoop with Apache License 2.0 5 votes vote down vote up
public static File getTestDir(Class<?> caller, boolean create) {
  File dir =
      new File(System.getProperty("test.build.data", "target/test/data")
          + "/" + RandomStringUtils.randomAlphanumeric(10),
          caller.getSimpleName());
  if (create) {
    dir.mkdirs();
  }
  return dir;
}
 
Example #18
Source File: CampusAftBase.java    From rice with Educational Community License v2.0 5 votes vote down vote up
private void reattemptPrimaryKey() throws InterruptedException {
    int attempts = 0;
    while (isTextPresent("a record with the same primary key already exists.") && ++attempts <= 10) {
        jGrowl("record with the same primary key already exists trying another, attempt: " + attempts);
        clearTextByName("document.newMaintainableObject.code"); // primary key
        String randomNumbeForCode = RandomStringUtils.randomNumeric(1);
        String randomAlphabeticForCode = RandomStringUtils.randomAlphabetic(1);
        jiraAwareTypeByName("document.newMaintainableObject.code", randomNumbeForCode + randomAlphabeticForCode);
        waitAndClickByName("methodToCall.route");
        waitForProgress("Submitting...");
    }
}
 
Example #19
Source File: PathUtils.java    From big-c with Apache License 2.0 5 votes vote down vote up
public static File getTestDir(Class<?> caller, boolean create) {
  File dir =
      new File(System.getProperty("test.build.data", "target/test/data")
          + "/" + RandomStringUtils.randomAlphanumeric(10),
          caller.getSimpleName());
  if (create) {
    dir.mkdirs();
  }
  return dir;
}
 
Example #20
Source File: DirectByteBufferOutputStreamTest.java    From incubator-nemo with Apache License 2.0 5 votes vote down vote up
@Test
public void testLongReWrite() throws IOException {
  String value1 = RandomStringUtils.randomAlphanumeric(10000);
  String value2 = RandomStringUtils.randomAlphanumeric(5000);
  outputStream.write(value1.getBytes());
  assertEquals(value1, new String(outputStream.toByteArray()));
  outputStream.write(value2.getBytes());
  assertEquals(value1+value2, new String(outputStream.toByteArray()));
}
 
Example #21
Source File: BHCompressTest.java    From indexr with Apache License 2.0 5 votes vote down vote up
@Test
public void test_string() {
    int item_size = 65536;
    List<UTF8String> strings = new ArrayList<>();
    for (int i = 0; i < item_size; i++) {
        strings.add(UTF8String.fromString(RandomStringUtils.random(20)));
    }
    ByteSlice bb = _from_v1(strings);
    ByteSlice cmp = BHCompressor.compressIndexedStr_v1(bb, item_size);
    ByteSlice dp = BHCompressor.decompressIndexedStr_v1(cmp, item_size);

    Assert.assertEquals(true, ByteSlice.checkEquals(bb, dp));
}
 
Example #22
Source File: CoreUtilTools.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a random alphanumeric (single case) string whose length is the number of characters specified.
 * The first character is ensured to be alphabetic.
 *
 * @param count
 *          the length of random string to create
 * @return the random string
 */
public static String randomAlphanumericString(final int count) {
  StringBuilder stringBuilder = new StringBuilder(RandomStringUtils.randomAlphabetic(1));
  if (count > 1) {
    stringBuilder.append(RandomStringUtils.randomAlphanumeric(count - 1));

  }
  String string = stringBuilder.toString();
  Assert.isNotNull(string, "string"); //$NON-NLS-1$
  return string.toUpperCase(Locale.ENGLISH);
}
 
Example #23
Source File: TestUtils.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
public static Referenceable createDBEntity() {
    Referenceable entity = new Referenceable(DATABASE_TYPE);
    String dbName = RandomStringUtils.randomAlphanumeric(10);
    entity.set(NAME, dbName);
    entity.set("description", "us db");
    return entity;
}
 
Example #24
Source File: AsyncController.java    From imooc-security with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/order")
public DeferredResult<String> order() throws Exception {
    logger.info("主线程开始");
    String orderNumber = RandomStringUtils.randomNumeric(8);
    //设置订单号
    mockQueue.setPlaceOrder(orderNumber);
    DeferredResult<String> result = new DeferredResult<>();
    //订单号和返回结果绑定
    deferredResultHolder.getMap().put(orderNumber,result);
    logger.info("主线程返回");
    return result;
}
 
Example #25
Source File: TestExecutionContextImplTest.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testWithSubjectNoProgressThread(){
	String subject = RandomStringUtils.randomAlphabetic(10);
	TestExecutionContext<String> context  = new TestExecutionContextImpl<>(subject);
	Assert.assertEquals(subject, context.getSubject());
	// Check that nothing explodes
	context.getProgressListener().setTotal(100);
	context.getProgressListener().setCompleted(5);
	context.getProgressListener().setMessage("Nearly there");
	context.getProgressListener().complete();
	context.checkCancelled();
}
 
Example #26
Source File: ResourceIT.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
  currentNamespace = session.getNamespace();
  pod1 = new PodBuilder()
    .withNewMetadata().withName("resource-pod-" + RandomStringUtils.randomAlphanumeric(6).toLowerCase(Locale.ROOT)).endMetadata()
    .withNewSpec()
    .addNewContainer().withName("nginx").withImage("nginx").endContainer()
    .endSpec()
    .build();

  client.resource(pod1).inNamespace(currentNamespace).createOrReplace();
}
 
Example #27
Source File: ConcurrencyIT.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
private static List<Record> generateRecords(int size, int noOfAttributes){
    List<Record> records = new ArrayList<>();
    for(int i = 0 ; i < size ; i++){
        List<AttributeElement> attributes = new ArrayList<>();
        attributes.add(new AttributeElement("attribute0", i));
        attributes.add(new AttributeElement("attribute1", i % 2 ==0? "even" : "odd"));
        for(int attributeNo = 2; attributeNo < noOfAttributes ; attributeNo++){
            attributes.add(new AttributeElement("attribute" + attributeNo, RandomStringUtils.random(attributeNo+5, true, true)));
        }
        records.add(new Record("someEntity", attributes));
    }
    return records;
}
 
Example #28
Source File: RandomTextDataGenerator.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor for {@link RandomTextDataGenerator}.
 * @param size the total number of words to consider.
 * @param seed Random number generator seed for repeatability
 * @param wordSize Size of each word
 */
RandomTextDataGenerator(int size, Long seed, int wordSize) {
  random = new Random(seed);
  words = new String[size];
  
  //TODO change the default with the actual stats
  //TODO do u need varied sized words?
  for (int i = 0; i < size; ++i) {
    words[i] = 
      RandomStringUtils.random(wordSize, 0, 0, true, false, null, random);
  }
}
 
Example #29
Source File: TestDAOImpl.java    From simple-spring-memcached with MIT License 5 votes vote down vote up
@Override
@ReadThroughSingleCache(namespace = "Charlie", expiration = 1000)
public String getRandomString(@ParameterValueKeyProvider final Long key) {
    try {
        Thread.sleep(500);
    } catch (InterruptedException ex) {
    }
    return RandomStringUtils.randomAlphanumeric(25 + RandomUtils.nextInt(30));
}
 
Example #30
Source File: KafkaNotificationTest.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void setup() throws Exception {
    Configuration properties = ApplicationProperties.get();
    properties.setProperty("atlas.kafka.data", "target/" + RandomStringUtils.randomAlphanumeric(5));

    kafkaNotification = new KafkaNotification(properties);
    kafkaNotification.start();
}