类org.apache.commons.lang.RandomStringUtils源码实例Demo

下面列出了怎么用org.apache.commons.lang.RandomStringUtils的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: usergrid   文件: ImportCollectionIT.java
@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();
}
 
源代码2 项目: usergrid   文件: ExportServiceIT.java
@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();
}
 
@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]);
    }
  }
}
 
源代码4 项目: spacewalk   文件: CommonFactory.java
/**
 * 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;
}
 
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);
}
 
源代码6 项目: rice   文件: TermMaintenanceNewAft.java
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);
}
 
源代码7 项目: dhis2-core   文件: SmsMessageSenderTest.java
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 );
    }
}
 
源代码8 项目: tddl5   文件: BatchInsertTest.java
/**
 * 有部分列没有使用绑定变量,会造成顺序不一致,测试此时的映射情况
 * 
 * @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);
}
 
源代码9 项目: kubernetes-plugin   文件: KubernetesSlave.java
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;
}
 
源代码10 项目: indexr   文件: BytesUtilTest.java
@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;
    }
}
 
@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);
}
 
源代码12 项目: OpenAs2App   文件: FileMonitorTest.java
@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);

}
 
源代码13 项目: incubator-atlas   文件: TestUtils.java
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;
}
 
private JdbcEntryData createJdbcEntry(Collection<String> colNames, int colSize) {
  List<JdbcEntryDatum> datumList = new ArrayList<>();
  for (String colName : colNames) {
    JdbcEntryDatum datum = new JdbcEntryDatum(colName, RandomStringUtils.randomAlphabetic(colSize));
    datumList.add(datum);
  }
  return new JdbcEntryData(datumList);
}
 
@BeforeClass(alwaysRun = true)
protected void init() throws Exception {
    super.init();
    loadESBConfigurationFromClasspath("artifacts/ESB/jaxrs/putpeopleproxy.xml");
    tomcatServerManager = new TomcatServerManager(AppConfig.class.getName(), "jaxrs", 8080);
    tomcatServerManager.startServer();
    personEmail = "testName" + RandomStringUtils.randomAlphanumeric(6) + "@wso2.com";
}
 
源代码16 项目: GeoTriples   文件: XMLMappingGeneratorTrans.java
private String getGTName(QName name) {
	if (name == null) {
		return null;
	}
	if (name.getNamespaceURI() == null) {
		return name.getLocalPart();
	}
	if (name.getNamespaceURI().isEmpty()) {
		return name.getLocalPart();
	}
	if (name.getLocalPart() == null) {
		return null;
	}
	if (name.getLocalPart().isEmpty()) {
		return null;
	}
	String prefix = namespaces.get(name.getNamespaceURI());
	if (prefix != null) {
		return prefix + ":" + name.getLocalPart();
	}
	String newprefix = new String(name.getNamespaceURI());
	// newprefix+="#";
	String newrandomstring = RandomStringUtils.random(5, true, false);
	namespaces.put(newprefix, newrandomstring);
	return newrandomstring + ":" + name.getLocalPart();

}
 
源代码17 项目: hadoop   文件: FSTestWrapper.java
public FSTestWrapper(String testRootDir) {
  // Use default test dir if not provided
  if (testRootDir == null || testRootDir.isEmpty()) {
    testRootDir = System.getProperty("test.build.data", "build/test/data");
  }
  // salt test dir with some random digits for safe parallel runs
  this.testRootDir = testRootDir + "/"
      + RandomStringUtils.randomAlphanumeric(10);
}
 
源代码18 项目: symphonyx   文件: Sessions.java
/**
 * Logins the specified user from the specified request.
 *
 * <p>
 * If no session of the specified request, do nothing.
 * </p>
 *
 * @param request the specified request
 * @param response the specified response
 * @param user the specified user, for example,      <pre>
 * {
 *     "oId": "",
 *     "userPassword": ""
 * }
 * </pre>
 */
public static void login(final HttpServletRequest request, final HttpServletResponse response, final JSONObject user) {
    final HttpSession session = request.getSession(false);

    if (null == session) {
        LOGGER.warn("The session is null");

        return;
    }

    session.setAttribute(User.USER, user);
    session.setAttribute(Common.CSRF_TOKEN, RandomStringUtils.randomAlphanumeric(12));

    try {
        final JSONObject cookieJSONObject = new JSONObject();

        cookieJSONObject.put(Keys.OBJECT_ID, user.optString(Keys.OBJECT_ID));
        cookieJSONObject.put(Common.TOKEN, user.optString(User.USER_PASSWORD));

        final Cookie cookie = new Cookie("b3log-latke", cookieJSONObject.toString());

        cookie.setPath("/");
        cookie.setMaxAge(COOKIE_EXPIRY);
        cookie.setHttpOnly(true); // HTTP Only

        response.addCookie(cookie);
    } catch (final Exception e) {
        LOGGER.log(Level.WARN, "Can not write cookie", e);
    }
}
 
源代码19 项目: atlas   文件: AtlasHiveHookContext.java
public String getQualifiedName(Table table) {
    String tableName = table.getTableName();

    if (table.isTemporary()) {
        if (SessionState.get() != null && SessionState.get().getSessionId() != null) {
            tableName = tableName + TEMP_TABLE_PREFIX + SessionState.get().getSessionId();
        } else {
            tableName = tableName + TEMP_TABLE_PREFIX + RandomStringUtils.random(10);
        }
    }

    return (table.getDbName() + QNAME_SEP_ENTITY_NAME + tableName + QNAME_SEP_METADATA_NAMESPACE).toLowerCase() + getMetadataNamespace();
}
 
源代码20 项目: incubator-pinot   文件: OnHeapDictionariesTest.java
/**
 * Helper method to build a segment with random data as per the schema.
 *
 * @param segmentDirName Name of segment directory
 * @param segmentName Name of segment
 * @param schema Schema for segment
 * @return Schema built for the segment
 * @throws Exception
 */
private Schema buildSegment(String segmentDirName, String segmentName, TableConfig tableConfig, Schema schema)
    throws Exception {

  SegmentGeneratorConfig config = new SegmentGeneratorConfig(tableConfig, schema);
  config.setOutDir(segmentDirName);
  config.setFormat(FileFormat.AVRO);
  config.setSegmentName(segmentName);

  Random random = new Random(RANDOM_SEED);

  List<GenericRow> rows = new ArrayList<>(NUM_ROWS);

  for (int rowId = 0; rowId < NUM_ROWS; rowId++) {
    HashMap<String, Object> map = new HashMap<>();

    map.put(INT_COLUMN, random.nextInt());
    map.put(LONG_COLUMN, random.nextLong());
    map.put(FLOAT_COLUMN, random.nextFloat());
    map.put(DOUBLE_COLUMN, random.nextDouble());
    map.put(STRING_COLUMN, RandomStringUtils.randomAscii(100));

    GenericRow genericRow = new GenericRow();
    genericRow.init(map);
    rows.add(genericRow);
  }

  SegmentIndexCreationDriverImpl driver = new SegmentIndexCreationDriverImpl();
  driver.init(config, new GenericRowRecordReader(rows));
  driver.build();

  LOGGER.info("Built segment {} at {}", segmentName, segmentDirName);
  return schema;
}
 
源代码21 项目: distkv   文件: DistkvListBenchmark.java
@Setup
public void init() {
  TestUtil.startRpcServer(8082);

  dummyData = ImmutableList.of(
          RandomStringUtils.random(5),
          RandomStringUtils.random(5),
          RandomStringUtils.random(5));

  asyncClient = new DefaultAsyncClient(PROTOCOL);
  client = new DefaultDistkvClient(PROTOCOL);
  client.lists().put(KEY_LIST_SYNC, dummyData);
  asyncClient.lists().put(KEY_LIST_ASYNC, dummyData);
}
 
源代码22 项目: keycloak   文件: UserInvalidationClusterTest.java
@Override
protected UserRepresentation createTestEntityRepresentation() {
    String firstName = "user";
    String lastName = RandomStringUtils.randomAlphabetic(5);
    UserRepresentation user = new UserRepresentation();
    user.setUsername(firstName + "_" + lastName);
    user.setEmail(user.getUsername() + "@email.test");
    user.setFirstName(firstName);
    user.setLastName(lastName);
    return user;
}
 
源代码23 项目: rice   文件: WebDriverLegacyITBase.java
private String searchForAvailableCode(int codeLength) throws InterruptedException {
    String randomCode = RandomStringUtils.randomAlphabetic(codeLength).toUpperCase();
    waitAndTypeByName("code", randomCode);
    waitAndClickSearch();
    int attemptCount = 1;
    waitForTextPresent("You have entered the primary key for this table");
    while (!isTextPresent("No values match this search.") && attemptCount < 25) {
        randomCode = Character.toString((char) (randomCode.toCharArray()[0] + attemptCount++));
        clearTextByName("code");
        waitAndTypeByName("code", randomCode);
        waitAndClickSearch();
        waitForTextPresent("You have entered the primary key for this table");
    }
    return randomCode;
}
 
源代码24 项目: chassis   文件: ZookeeperElbFilterTest.java
@Test
public void randomUnmatchedELB() {
    LoadBalancerDescription loadBalancer = new LoadBalancerDescription();
    List<ListenerDescription> listenerDescriptions = new ArrayList<>();
    listenerDescriptions.add(new ListenerDescription());
    loadBalancer.setListenerDescriptions(listenerDescriptions);
    loadBalancer.setLoadBalancerName(RandomStringUtils.random(5,"abcd"));
    Assert.assertFalse(filter.accept(loadBalancer));
}
 
源代码25 项目: usergrid   文件: QueueResourceTest.java
@Test
public void testCreateQueue() throws URISyntaxException {

    // create a queue

    String queueName = "qrt_create_" + RandomStringUtils.randomAlphanumeric( 10 );
    Map<String, Object> queueMap = new HashMap<String, Object>() {{
        put("name", queueName);
    }};
    Response response = target("queues").request()
            .post( Entity.entity( queueMap, MediaType.APPLICATION_JSON_TYPE));

    Assert.assertEquals( 201, response.getStatus() );
    URIStrategy uriStrategy = StartupListener.INJECTOR.getInstance( URIStrategy.class );
    Assert.assertEquals( uriStrategy.queueURI( queueName ).toString(), response.getHeaderString( "location" ) );

    // get queue by name

    response = target("queues").path( queueName ).path( "config" ).request().get();
    Assert.assertEquals( 200, response.getStatus() );
    ApiResponse apiResponse = response.readEntity( ApiResponse.class );
    Assert.assertNotNull( apiResponse.getQueues() );
    Assert.assertFalse( apiResponse.getQueues().isEmpty() );
    Assert.assertEquals( 1, apiResponse.getQueues().size() );
    Assert.assertEquals( queueName, apiResponse.getQueues().iterator().next().getName() );

    response = target("queues").path( queueName ).queryParam( "confirm", true ).request().delete();
    Assert.assertEquals( 200, response.getStatus() );
}
 
源代码26 项目: incubator-atlas   文件: KafkaNotificationTest.java
@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();
}
 
源代码27 项目: simple-spring-memcached   文件: TestDAOImpl.java
@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));
}
 
源代码28 项目: big-c   文件: RandomTextDataGenerator.java
/**
 * 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);
  }
}
 
源代码29 项目: grakn   文件: ConcurrencyIT.java
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;
}
 
源代码30 项目: kubernetes-client   文件: ResourceIT.java
@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();
}
 
 类所在包
 同包方法