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

项目:subsonic    文件:ShareService.java   
public Share createShare(HttpServletRequest request, List<MediaFile> files) throws Exception {

        Share share = new Share();
        share.setName(RandomStringUtils.random(5, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"));
        share.setCreated(new Date());
        share.setUsername(securityService.getCurrentUsername(request));

        Calendar expires = Calendar.getInstance();
        expires.add(Calendar.YEAR, 1);
        share.setExpires(expires.getTime());

        shareDao.createShare(share);
        for (MediaFile file : files) {
            shareDao.createSharedFiles(share.getId(), file.getPath());
        }
        LOG.info("Created share '" + share.getName() + "' with " + files.size() + " file(s).");

        return share;
    }
项目:configx    文件:AppService.java   
/**
 * 创建新App对象
 *
 * @param name
 * @param description
 * @param admins
 * @param developers
 * @return
 */
private App newApp(String name, String description, String admins, String developers) {
    Date now = new Date();

    App app = new App();
    // 设置名称和描述
    app.setName(name);
    app.setDescription(description);
    app.setAppKey(RandomStringUtils.randomAlphanumeric(18));
    app.setAppSecret(RandomStringUtils.randomAlphanumeric(32));
    app.setAdmins(admins);
    app.setDevelopers(developers);

    app.setCreator(UserContext.name());
    app.setCreateTime(now);

    return app;
}
项目:configx    文件:SessionService.java   
/**
 * 创建token
 *
 * @param email
 */
public String createToken(String email) {
    String token = getToken(email);
    if (StringUtils.isNotEmpty(token)) {
        return token;
    }

    // 分配token
    token = RandomStringUtils.randomAlphanumeric(32);
    Session session = new Session();
    session.setEmail(email);
    session.setToken(token);
    sessionMapper.insert(session);

    return token;
}
项目:renren-fast    文件:SysUserServiceImpl.java   
@Override
@Transactional
public void save(SysUserEntity user) {
    user.setCreateTime(new Date());
    //sha256加密
    String salt = RandomStringUtils.randomAlphanumeric(20);
    user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
    user.setSalt(salt);
    sysUserDao.save(user);

    //检查角色是否越权
    checkRole(user);

    //保存用户与角色关系
    sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
}
项目:alfresco-repository    文件:PropertyTypeConverterTest.java   
@Test
public void testGetPersistentTypeForStrings()
{
    DefaultPropertyTypeConverter defaultPropertyTypeConverter = new DefaultPropertyTypeConverter();

    // Check string.
    PropertyValueEntity.PersistedType persistedType = PropertyValueEntity.getPersistedTypeEnum("test", defaultPropertyTypeConverter);
    assertEquals(PropertyValueEntity.PersistedType.STRING, persistedType);

    // String value with length greater than the DB supported threshold.
    String stringValue = RandomStringUtils.randomAlphanumeric(2001);
    // ... persisted as blobs (see MNT-17523 for details).
    persistedType = PropertyValueEntity.getPersistedTypeEnum(stringValue, defaultPropertyTypeConverter);
    assertEquals(PropertyValueEntity.PersistedType.SERIALIZABLE, persistedType);

    // String value with length less than the DB supported threshold.
    stringValue = RandomStringUtils.randomAlphanumeric(1999);
    // ... persisted as strings
    persistedType = PropertyValueEntity.getPersistedTypeEnum(stringValue, defaultPropertyTypeConverter);
    assertEquals(PropertyValueEntity.PersistedType.STRING, persistedType);
}
项目:airsonic    文件:ShareService.java   
public Share createShare(HttpServletRequest request, List<MediaFile> files) throws Exception {

        Share share = new Share();
        share.setName(RandomStringUtils.random(5, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"));
        share.setCreated(new Date());
        share.setUsername(securityService.getCurrentUsername(request));

        Calendar expires = Calendar.getInstance();
        expires.add(Calendar.YEAR, 1);
        share.setExpires(expires.getTime());

        shareDao.createShare(share);
        for (MediaFile file : files) {
            shareDao.createSharedFiles(share.getId(), file.getPath());
        }
        LOG.info("Created share '" + share.getName() + "' with " + files.size() + " file(s).");

        return share;
    }
项目:osc-core    文件:SecurityGroupMemberHookCheckTaskTestData.java   
private static SecurityGroupMember createUnBindedSfcSecurityGroupMember(Set<VMPort> ports) {
    VirtualizationConnector vc = mock(VirtualizationConnector.class);
    when(vc.getControllerType()).thenReturn(NEUTRON_SFC_CONTROLLER);

    SecurityGroup sg = mock(SecurityGroup.class);
    when(sg.getVirtualizationConnector()).thenReturn(vc);
    when(sg.getServiceFunctionChain()).thenReturn(mock(ServiceFunctionChain.class));

    SecurityGroupMember sgm = mock(SecurityGroupMember.class);
    when(sgm.getSecurityGroup()).thenReturn(sg);
    when(sgm.getType()).thenReturn(SecurityGroupMemberType.values()[new Random().nextInt(2)]);
    when(sgm.getMemberName()).thenReturn("member_" + RandomStringUtils.random(5));
    when(sgm.getVmPorts()).thenReturn(ports);
    when(sgm.getId()).thenReturn(SGM_ID);

    return sgm;
}
项目:light-4-j-plugin-wrapper    文件:UtilitiesServiceImpl.java   
private String createAccount(int index) throws ServerError{
    String email = props.getProperty("email-prefix") + RandomStringUtils.randomAlphanumeric(6)+props.getProperty("email-suffix");

    // ********************** Signup Express (Account Create) **********************
    String accountCreateURLPath = props.getProperty("account-create-url-path");
    String accountCreateBody = props.getProperty("account-create-body");

    accountCreateBody=accountCreateBody.replaceAll("<token>",  props.getProperty("acccess-token"));
    accountCreateBody=accountCreateBody.replaceAll("<org>",  "Org-98");
    accountCreateBody=accountCreateBody.replaceAll("<username>",  email);
    accountCreateBody=accountCreateBody.replaceAll("<email>",  email);
    accountCreateBody=accountCreateBody.replaceAll("<password>", props.getProperty("default-password"));

    String fullurl = HOST+accountCreateURLPath;
    HttpResponse resp = apiAccessor.post(fullurl, accountCreateBody);

    String body = resp.getBody();

    //TODO - Use a Jackson JSON to Object creator and get the id that way.
    int indexOfStartOfId = body.indexOf("id\":") + 4;
    int indexOfEndOfId = body.indexOf(",");

    String accountId = body.substring(indexOfStartOfId, indexOfEndOfId);
    return accountId;

}
项目:alfresco-remote-api    文件:InviteServiceTest.java   
public void testStartInviteForSameInviteeButTwoDifferentSites()
    throws Exception
{
    final String inviteeUsername = INVITEE_FIRSTNAME + "_" + INVITEE_LASTNAME;
    final String inviteeEmail = INVITEE_EMAIL_PREFIX + RandomStringUtils.randomAlphanumeric(6) + "@" + INVITEE_EMAIL_DOMAIN;

    // Create person
    AuthenticationUtil.runAs(new RunAsWork<Object>()
    {
        public Object doWork() throws Exception
        {
            createPerson(INVITEE_FIRSTNAME, INVITEE_LASTNAME, inviteeUsername, inviteeEmail);
            return null;
        }

    }, AuthenticationUtil.getSystemUserName());

    JSONObject result = startInvite(INVITEE_FIRSTNAME, INVITEE_LASTNAME, inviteeEmail, INVITEE_SITE_ROLE, SITE_SHORT_NAME_INVITE_1,
            Status.STATUS_CREATED);

    startInvite(INVITEE_FIRSTNAME, INVITEE_LASTNAME, inviteeEmail, INVITEE_SITE_ROLE, SITE_SHORT_NAME_INVITE_2, Status.STATUS_CREATED);
}
项目:my-spring-boot-project    文件:SysUserServiceImpl.java   
@Override
@Transactional(rollbackFor = Exception.class)
public void save(SysUserEntity user) throws Exception {
    user.setCreateTime(LocalDateTime.now());
    //sha256加密
    String salt = RandomStringUtils.randomAlphanumeric(20);
    user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
    user.setSalt(salt);
    sysUserDao.save(user);

    //检查角色是否越权
    checkRole(user);

    //保存用户与角色关系
    sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
}
项目:BUbiNG    文件:GZIPArchiveWriterTest.java   
public static List<byte[]> writeArchive(final String path, final int n, final boolean randomized) throws IOException {
FileOutputStream fos = new FileOutputStream(path);
GZIPArchiveWriter gzaw = new GZIPArchiveWriter(fos);
GZIPArchive.WriteEntry we;
List<byte[]> contents = new ArrayList<>();
for (int i = 0; i < n; i++) {
    we = gzaw.getEntry("Test " + i, "Comment " + i, new Date());
    final byte[] content = Util.toByteArray(
        randomized ? "MAGIC" + RandomStringUtils.randomAscii(1024 * (1 + i)) : "Hello, world " + i + "!\n");
    we.deflater.write(content);
    contents.add(content);
    we.deflater.close();
}
gzaw.close();
return contents;
   }
项目:ditb    文件:HRegion.java   
/**
 * Convenience method creating new HRegions. Used by createTable. The {@link WAL} for the created
 * region needs to be closed explicitly, if it is not null. Use {@link HRegion#getWAL()} to get
 * access.
 *
 * @param info       Info for region to create.
 * @param rootDir    Root directory for HBase instance
 * @param tableDir   table directory
 * @param wal        shared WAL
 * @param initialize - true to initialize the region
 * @param ignoreWAL  - true to skip generate new wal if it is null, mostly for createTable
 * @return new HRegion
 * @throws IOException
 */
public static HRegion createHRegion(final HRegionInfo info, final Path rootDir,
    final Path tableDir, final Configuration conf, final HTableDescriptor hTableDescriptor,
    final WAL wal, final boolean initialize, final boolean ignoreWAL) throws IOException {
  LOG.info("creating HRegion " + info.getTable().getNameAsString() + " HTD == " + hTableDescriptor
      + " RootDir = " + rootDir + " Table name == " + info.getTable().getNameAsString());
  FileSystem fs = FileSystem.get(conf);
  HRegionFileSystem.createRegionOnFileSystem(conf, fs, tableDir, info);
  WAL effectiveWAL = wal;
  if (wal == null && !ignoreWAL) {
    // TODO HBASE-11983 There'll be no roller for this wal?
    // The WAL subsystem will use the default rootDir rather than the passed
    // in rootDir
    // unless I pass along via the conf.
    Configuration confForWAL = new Configuration(conf);
    confForWAL.set(HConstants.HBASE_DIR, rootDir.toString());
    effectiveWAL = (new WALFactory(confForWAL,
        Collections.<WALActionsListener>singletonList(new MetricsWAL()),
        "hregion-" + RandomStringUtils.randomNumeric(8))).getWAL(info.getEncodedNameAsBytes());
  }
  HRegion region =
      HRegion.newHRegion(tableDir, effectiveWAL, fs, conf, info, hTableDescriptor, null);
  if (initialize) region.initialize(null);
  return region;
}
项目:ditb    文件:MockStoreFileGenerator.java   
protected StoreFile createMockStoreFile(final long sizeInBytes, final long seqId) {
  StoreFile mockSf = mock(StoreFile.class);
  StoreFile.Reader reader = mock(StoreFile.Reader.class);
  String stringPath = "/hbase/testTable/regionA/"
      + RandomStringUtils.random(FILENAME_LENGTH, 0, 0, true, true, null, random);
  Path path = new Path(stringPath);


  when(reader.getSequenceID()).thenReturn(seqId);
  when(reader.getTotalUncompressedBytes()).thenReturn(sizeInBytes);
  when(reader.length()).thenReturn(sizeInBytes);

  when(mockSf.getPath()).thenReturn(path);
  when(mockSf.excludeFromMinorCompaction()).thenReturn(false);
  when(mockSf.isReference()).thenReturn(false); // TODO come back to
  // this when selection takes this into account
  when(mockSf.getReader()).thenReturn(reader);
  String toString = Objects.toStringHelper("MockStoreFile")
      .add("isReference", false)
      .add("fileSize", StringUtils.humanReadableInt(sizeInBytes))
      .add("seqId", seqId)
      .add("path", stringPath).toString();
  when(mockSf.toString()).thenReturn(toString);

  return mockSf;
}
项目:cuba    文件:RestFilterParserTest.java   
@Test
public void testOrGroup() throws Exception {
    new StrictExpectations() {{
        RandomStringUtils.randomAlphabetic(anyInt); result = "stringParamName";
        RandomStringUtils.randomAlphabetic(anyInt); result = "intParamName";
        RandomStringUtils.randomAlphabetic(anyInt); result = "booleanParamName";
    }};

    String data = readDataFromFile("data/restFilter3.json");
    MetaClass metaClass = metadata.getClass("test$TestEntity");
    RestFilterParseResult parseResult = restFilterParser.parse(data, metaClass);

    String expectedJpqlWhere = "(({E}.stringField <> :stringParamName or " +
            "{E}.intField > :intParamName) and " +
            "{E}.booleanField = :booleanParamName)";
    assertEquals(expectedJpqlWhere, parseResult.getJpqlWhere());

    Map<String, Object> queryParameters = parseResult.getQueryParameters();

    assertEquals("stringValue", queryParameters.get("stringParamName"));
    assertEquals(100, queryParameters.get("intParamName"));
    assertEquals(true, queryParameters.get("booleanParamName"));
}
项目:cuba    文件:RestFilterParserTest.java   
@Test
public void testStartsWithOperator() throws Exception {
    new StrictExpectations() {{
        RandomStringUtils.randomAlphabetic(anyInt); result = "paramName1";
    }};

    String data = readDataFromFile("data/restFilter6.json");
    MetaClass metaClass = metadata.getClass("test$TestEntity");
    RestFilterParseResult parseResult = restFilterParser.parse(data, metaClass);

    String expectedJpqlWhere = "({E}.stringField like :paramName1)";
    assertEquals(expectedJpqlWhere, parseResult.getJpqlWhere());

    Map<String, Object> queryParameters = parseResult.getQueryParameters();
    assertEquals("(?i)AAA%", queryParameters.get("paramName1"));
}
项目:Netty-Resteasy-Spring    文件:RedisRateLimiter.java   
private boolean doPeriod(Jedis jedis, String keyPrefix, int period) {
    String[] keyNames = getKeyNames(jedis, keyPrefix);
    //返回2个,第1个是秒计数10位,第2个是微秒6位
    List<String> jedisTime = jedis.time();
    String currentScore = jedisTime.get(0);
    //不用UUID是因为UUID是36个字符比较长,下面方法只有20位,而且冲突可能性已很少
    String currentVal = jedisTime.get(0)+jedisTime.get(1)+RandomStringUtils.randomAlphanumeric(4);
    String previousSectionBeginScore = (Long.parseLong(currentScore) - getPeriodSecond()) + "";
    String expires = getExpire()+"";
    List<String> keys = new ArrayList<String>();
    keys.add(keyNames[0]);
    keys.add(keyNames[1]);
    List<String> argvs = new ArrayList<String>();
    argvs.add(currentScore);
    argvs.add(currentVal);
    argvs.add(previousSectionBeginScore);
    argvs.add(expires);
    argvs.add(permitsPerUnit+"");
    Long val = (Long)jedis.eval(LUA_PERIOD_SCRIPT, keys, argvs);
    return (val > 0);
}
项目:cuba    文件:RestFilterParserTest.java   
@Test
public void testInOperator() throws Exception {
    new StrictExpectations() {{
        RandomStringUtils.randomAlphabetic(anyInt); result = "paramName1";
    }};

    String data = readDataFromFile("data/restFilter5.json");
    MetaClass metaClass = metadata.getClass("test$TestEntity");
    RestFilterParseResult parseResult = restFilterParser.parse(data, metaClass);

    String expectedJpqlWhere = "({E}.intField in :paramName1)";
    assertEquals(expectedJpqlWhere, parseResult.getJpqlWhere());

    Map<String, Object> queryParameters = parseResult.getQueryParameters();

    List<Integer> param1Value = (List<Integer>) queryParameters.get("paramName1");
    assertEquals(Arrays.asList(1, 2, 3), param1Value);
}
项目:gluu    文件:OpenIdClient.java   
/**
 * {@inheritDoc}
 */
public String getRedirectionUrl(final WebContext context) {
    init();

    final String state = RandomStringUtils.randomAlphanumeric(10);
    final String nonce = RandomStringUtils.randomAlphanumeric(10);

    final AuthorizationRequest authorizationRequest = new AuthorizationRequest(Arrays.asList(ResponseType.CODE), this.clientId, this.appConfiguration.getOpenIdScopes(),
            this.appConfiguration.getOpenIdRedirectUrl(), null);

    authorizationRequest.setState(state);
    authorizationRequest.setNonce(nonce);

    context.setSessionAttribute(getName() + STATE_PARAMETER, state);

    final String redirectionUrl = this.openIdConfiguration.getAuthorizationEndpoint() + "?" + authorizationRequest.getQueryString();
    logger.debug("oxAuth redirection Url: '{}'", redirectionUrl);

    return redirectionUrl;
}
项目: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;
    }
}
项目:external-workspace-manager-plugin    文件:CustomWorkspaceTest.java   
@Test
public void customWorkspaceUsingPathParameterWithConstantFolder() throws Exception {
    String folder = "constant";
    WorkflowJob job = j.jenkins.createProject(WorkflowJob.class, RandomStringUtils.randomAlphanumeric(7));
    job.setDefinition(new CpsFlowDefinition(format("" +
            "def customPath = \"%s/${env.JOB_NAME}/${env.BUILD_NUMBER}\" \n" +
            "def extWorkspace = exwsAllocate diskPoolId: '%s', path: customPath \n" +
            "node { \n" +
            "   exws (extWorkspace) { \n" +
            "       writeFile file: 'foobar.txt', text: 'foobar' \n" +
            "   } \n" +
            "} \n", folder, DISK_POOL_ID)));

    WorkflowRun run = j.assertBuildStatusSuccess(job.scheduleBuild2(0));
    verifyWorkspacePath(format("%s/%s/%d", folder, job.getFullName(), run.getNumber()), run);
}
项目:hadoop-manta    文件:MantaFileSystemIT.java   
@Test
public void canCalculateRangeChecksumsRemotely() throws IOException {
    Path file = new Path(testPathPrefix + "checksum-" + UUID.randomUUID() + ".txt");
    int size = (int)MantaFileSystem.DEFAULT_THRESHOLD_FOR_REMOTE_CHECKSUM_CALC + 10;
    byte[] randomData = RandomStringUtils.randomAlphanumeric(size).getBytes(Charsets.UTF_8);

    try (InputStream in = new ByteArrayInputStream(randomData)){
        client.put(file.toString(), in);
    }

    int length = 1024;
    byte[] calculatedMd5 = DigestUtils.md5(Arrays.copyOfRange(randomData, 0, length));
    byte[] hdfsMd5 = fs.getFileChecksumRemotely(file.toString(), length).getBytes();

    Assert.assertArrayEquals("MD5 checksum from HDFS driver was not correct",
            calculatedMd5, hdfsMd5);
}
项目:devramble    文件:PersonService.java   
@Cacheable(cacheNames = "persons", key = "#id")
public Person getPerson(int id) throws Exception {
    Thread.sleep(3000); // simulate latency
    Person person = null;
    if (personMap.containsKey(id)) {
        person = personMap.get(id);
    } else {
        person = new Person();
        person.setId(id);
        person.setFirstname(RandomStringUtils.randomAlphanumeric(10));
        person.setLastname(RandomStringUtils.randomAlphanumeric(15));

        personMap.put(id, person);
    }

    return person;
}
项目:cuba    文件:RestFilterParserTest.java   
@Test
public void testParseSimpleFilter() throws Exception {
    new StrictExpectations() {{
        RandomStringUtils.randomAlphabetic(anyInt); result = "stringParamName";
        RandomStringUtils.randomAlphabetic(anyInt); result = "intParamName";
        RandomStringUtils.randomAlphabetic(anyInt); result = "booleanParamName";
    }};

    String data = readDataFromFile("data/restFilter1.json");
    MetaClass metaClass = metadata.getClass("test$TestEntity");
    RestFilterParseResult parseResult = restFilterParser.parse(data, metaClass);

    String expectedJpqlWhere = "({E}.stringField <> :stringParamName and " +
            "{E}.intField > :intParamName and " +
            "{E}.booleanField = :booleanParamName)";
    assertEquals(expectedJpqlWhere, parseResult.getJpqlWhere());

    Map<String, Object> queryParameters = parseResult.getQueryParameters();

    assertEquals("stringValue", queryParameters.get("stringParamName"));
    assertEquals(100, queryParameters.get("intParamName"));
    assertEquals(true, queryParameters.get("booleanParamName"));
}
项目:run-selector-plugin    文件:ParameterizedRunFilterTest.java   
@Test
public void testConfigureBuildFilterParameter() throws Exception {
    RunFilterParameter param = new RunFilterParameter(
        "PARAM",
        "description",
        new AndRunFilter(
            new ParametersRunFilter("PARAM1=VALUE1"),
            new SavedRunFilter()
        )
    );
    WorkflowJob job = j.jenkins.createProject(
            WorkflowJob.class,
            RandomStringUtils.randomAlphanumeric(7)
    );
    job.addProperty(new ParametersDefinitionProperty(param));
    j.configRoundtrip((Item)job);
    j.assertEqualDataBoundBeans(
        param,
        job.getProperty(ParametersDefinitionProperty.class)
            .getParameterDefinition("PARAM")
    );
}
项目:run-selector-plugin    文件:ParameterizedRunFilterTest.java   
@Test
public void testIsSelectableWithDefault() throws Exception {
    WorkflowJob selecter = j.jenkins.createProject(
        WorkflowJob.class,
        RandomStringUtils.randomAlphanumeric(7)
    );
    selecter.addProperty(new ParametersDefinitionProperty(
        new RunFilterParameter(
            "FILTER",
            "description",
            new SavedRunFilter()
        )
    ));
    selecter.setDefinition(new CpsFlowDefinition(String.format(
        "def runWrapper = selectRun"
        + " job: '%s',"
        + " filter: [$class: 'ParameterizedRunFilter', parameter: '${FILTER}'],"
        + " verbose: true;"
        + "assert(runWrapper.id == '%s')",
        jobToSelect.getFullName(),
        runToSelect1.getId()
    )));

    j.assertBuildStatusSuccess(selecter.scheduleBuild2(0));
}
项目:OpenCyclos    文件:ElementServiceImpl.java   
/**
 * Generate a member username
 */
private String generateUsername(final int length) {
    String generated;
    boolean exists;
    do {
        // Generate a random number
        generated = RandomStringUtils.randomNumeric(length);
        if (generated.charAt(0) == '0') {
            // The first character cannot be zero
            generated = (new Random().nextInt(8) + 1) + generated.substring(1);
        }
        // Check if such username exists
        try {
            userDao.load(generated);
            exists = true;
        } catch (final EntityNotFoundException e) {
            exists = false;
        }
    } while (exists);
    return generated;
}
项目:LiteGraph    文件:GraphReadPerformanceTest.java   
@Override
protected void afterLoadGraphWith(final Graph g) throws Exception {
    ids.clear();
    final int numVertices = 10000;
    final Random r = new Random(854939487556l);
    for (int i = 0; i < numVertices; i++) {
        final Vertex v = g.addVertex("oid", i, "name", RandomStringUtils.randomAlphabetic(r.nextInt(1024)));
        ids.add(v.id());
    }

    final Distribution inDist = new PowerLawDistribution(2.3);
    final Distribution outDist = new PowerLawDistribution(2.8);
    final DistributionGenerator generator = DistributionGenerator.build(g)
            .label("knows")
            .seedGenerator(r::nextLong)
            .outDistribution(outDist)
            .inDistribution(inDist)
            .edgeProcessor(e -> e.<Double>property("weight", r.nextDouble()))
            .expectedNumEdges(numVertices * 3).create();
    edgeCount = generator.generate();
}
项目:big-c    文件:DirectoryCollection.java   
/**
 * Function to test whether a dir is working correctly by actually creating a
 * random directory.
 *
 * @param dir
 *          the dir to test
 */
private void verifyDirUsingMkdir(File dir) throws IOException {

  String randomDirName = RandomStringUtils.randomAlphanumeric(5);
  File target = new File(dir, randomDirName);
  int i = 0;
  while (target.exists()) {

    randomDirName = RandomStringUtils.randomAlphanumeric(5) + i;
    target = new File(dir, randomDirName);
    i++;
  }
  try {
    DiskChecker.checkDir(target);
  } finally {
    FileUtils.deleteQuietly(target);
  }
}
项目:cuba    文件:RelatedEntitiesBean.java   
protected CustomCondition getParentEntitiesCondition(List<Object> parentIds, String parentPrimaryKey, CollectionDatasource datasource,
                                                     String filterComponentName, MetaClass parentMetaClass) {
    String conditionName = String.format("related_%s", RandomStringUtils.randomAlphabetic(6));
    CustomCondition condition = new CustomCondition(getConditionXmlElement(conditionName, parentMetaClass), AppConfig.getMessagesPack(),
            filterComponentName, datasource);


    Class<?> parentPrimaryKeyClass = parentMetaClass.getPropertyNN(parentPrimaryKey).getJavaType();
    condition.setJavaClass(parentPrimaryKeyClass);
    condition.setHidden(true);
    condition.setInExpr(true);

    int randInt = new Random().nextInt((99999 - 11111) + 1) + 11111;
    String paramName = String.format("component$%s.%s%s", filterComponentName, conditionName, randInt);

    condition.setParam(getParentEntitiesParam(parentIds, parentPrimaryKey, datasource, parentPrimaryKeyClass, paramName, parentMetaClass));

    return condition;
}
项目:hazelcast-eureka    文件:EurekaOneDiscoveryStrategyTest.java   
@Test
public void shouldOnlyDiscoverInstancesWithValidAddress(){
    Application application = new Application();
    InstanceInfo mockInfo = mock(InstanceInfo.class);
    when(mockInfo.getId()).thenReturn(RandomStringUtils.random(42));
    when(mockInfo.getStatus()).thenReturn(InstanceInfo.InstanceStatus.UP);
    when(mockInfo.getIPAddr()).thenReturn("local");

    application.addInstance(mockInfo);

    when(eurekaClient.getApplication(APPLICATION_NAME)).thenReturn(application);

    Iterable<DiscoveryNode> nodes = strategy.discoverNodes();

    verify(eurekaClient).getApplication(APPLICATION_NAME);
    verify(mockInfo).getStatus();
    verify(mockInfo).getIPAddr();

    assertThat(nodes.iterator().hasNext(), is(false));
}
项目:hadoop-oss    文件: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);
}
项目:hadoop-oss    文件:FileContextMainOperationsBaseTest.java   
@Before
public void setUp() throws Exception {
  File testBuildData = new File(System.getProperty("test.build.data",
          "build/test/data"), RandomStringUtils.randomAlphanumeric(10));
  Path rootPath = new Path(testBuildData.getAbsolutePath(), 
          "root-uri");
  localFsRootPath = rootPath.makeQualified(LocalFileSystem.NAME, null);
  fc.mkdir(getTestRootPath(fc, "test"), FileContext.DEFAULT_PERM, true);
}
项目:alfresco-repository    文件:NameBasedUserNameGenerator.java   
/**
 * Returns a generated user name
 * 
 * @return the generated user name
 */
public String generateUserName(String firstName, String lastName, String emailAddress, int seed)
{
    String userName;

    String pattern = namePattern;

    String initial = firstName.toLowerCase().substring(0,1);

    userName = pattern
        .replace("%i%", initial)
        .replace("%firstName%", cleanseName(firstName))
        .replace("%lastName%", cleanseName(lastName))
        .replace("%emailAddress%", emailAddress.toLowerCase());

    if(seed > 0)
    {
        if (userName.length() < userNameLength + 3)
        {
             userName = userName + RandomStringUtils.randomNumeric(3);  
        }
        else
        {
            // truncate the user name and slap on 3 random characters
            userName = userName.substring(0, userNameLength -3) + RandomStringUtils.randomNumeric(3);
        }
    }

    return userName;
}
项目:alfresco-repository    文件:AuditComponentTest.java   
public void testAuditTruncatedValues()
{
    final String rootPath = "/test/one.one/two.one";

    // String value with length grater then the DB supported threshold.
    final String stringValue = RandomStringUtils.randomAlphanumeric(SchemaBootstrap.DEFAULT_MAX_STRING_LENGTH + 1);
    final MLText mlTextValue = new MLText();
    mlTextValue.put(Locale.ENGLISH, stringValue);

    final RetryingTransactionCallback<Map<String, Serializable>> testCallback = new RetryingTransactionCallback<Map<String, Serializable>>()
    {
        public Map<String, Serializable> execute() throws Throwable
        {
            final Map<String, Serializable> values = new HashMap<>();
            values.put("/3.1/4.1", stringValue);
            values.put("/3.1/4.2", mlTextValue);

            return auditComponent.recordAuditValues(rootPath, values);
        }
    };
    RunAsWork<Map<String, Serializable>> testRunAs = new RunAsWork< Map<String, Serializable>>()
    {
        public Map<String, Serializable> doWork() throws Exception
        {
            return transactionService.getRetryingTransactionHelper().doInTransaction(testCallback);
        }
    };

    Map<String, Serializable> result = AuthenticationUtil.runAs(testRunAs, "SomeOtherUser");

    // Check that the values aren't truncated.
    assertEquals(stringValue, result.get("/test/1.1/2.1/3.1/4.1/value.1"));
    assertEquals(mlTextValue, result.get("/test/1.1/2.1/3.1/4.2/value.2"));
}
项目:cyoastudio    文件:DataStorage.java   
public String makeIdentifier() {
    String iden = null;
    do {
        iden = RandomStringUtils.randomAlphanumeric(32);
    } while (hasFile(iden));
    return iden;
}
项目:airsonic    文件:PlayerService.java   
/**
 * Returns a player associated to the special "guest" user, creating it if necessary.
 */
public Player getGuestPlayer(HttpServletRequest request) {

    // Create guest user if necessary.
    User user = securityService.getUserByName(User.USERNAME_GUEST);
    if (user == null) {
        user = new User(User.USERNAME_GUEST, RandomStringUtils.randomAlphanumeric(30), null);
        user.setStreamRole(true);
        securityService.createUser(user);
    }

    // Look for existing player.
    List<Player> players = getPlayersForUserAndClientId(User.USERNAME_GUEST, null);
    if (!players.isEmpty()) {
        return players.get(0);
    }

    // Create player if necessary.
    Player player = new Player();
    if (request != null ) {
        player.setIpAddress(request.getRemoteAddr());
    }
    player.setUsername(User.USERNAME_GUEST);
    createPlayer(player);

    return player;
}
项目:airsonic    文件:SonosService.java   
@Override
public LastUpdate getLastUpdate() {
    LastUpdate result = new LastUpdate();
    // Effectively disabling caching
    result.setCatalog(RandomStringUtils.randomAlphanumeric(8));
    result.setFavorites(RandomStringUtils.randomAlphanumeric(8));
    return result;
}