org.apache.commons.lang.RandomStringUtils#randomAlphanumeric ( )源码实例Demo

下面列出了org.apache.commons.lang.RandomStringUtils#randomAlphanumeric ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: chassis   文件: AppIntegrationTest.java
@SuppressWarnings("unchecked")
@Test(timeout = 40000)
   public void runSpringWithZookeeperConfig() throws Exception {
       String value = RandomStringUtils.randomAlphanumeric(5);
       TestUtils.addAppProperties(UNIT_TEST_SPRING_APP, environment, VERSION, curator, new SimpleEntry<String, String>(KEY, value));

       Arguments arguments = new Arguments();
       arguments.environment = environment;
       arguments.appClass = TestApplicationConfiguration.class.getName();
       arguments.zookeeper = zookeeper.getConnectString();
       arguments.skipModuleScanning = true;
       arguments.skipServerInstanceContextInitialization = true;

       application = new Application(arguments).start();

       //grab the TestComponent that has been component-scanned into the app's spring context.
       Map<String,TestComponent> beans = application.getApplicationContext().getBeansOfType(TestComponent.class);
       TestComponent testComponent = beans.values().iterator().next();

       //assert that the TestComponent has been injected with a property value from zookeeper.
       Assert.assertEquals(value, testComponent.getTestProperty());
   }
 
@Test
public void testGenerateResultsException() {
    final List<Object> keyObjects = new ArrayList<Object>();
    final Map<Object, String> obj2key = new HashMap<Object, String>();
    final String keyObject = RandomStringUtils.randomAlphanumeric(8);
    final String key = keyObject + "-" + RandomStringUtils.randomAlphanumeric(4);
    keyObjects.add(keyObject);
    obj2key.put(keyObject, key);
    AnnotationData data = new AnnotationData();
    data.setListIndexInKeys(0);
    coord = new ReadThroughMultiCacheAdvice.MultiCacheCoordinator(null, data);
    coord.setListKeyObjects(keyObjects);
    coord.getObj2Key().putAll(obj2key);

    try {
        coord.generateResultList();
        fail("Expected Exception");
    } catch (RuntimeException ex) {
    }

}
 
源代码3 项目: takes   文件: PsLinkedinTest.java
/**
 * PsLinkedin can login.
 * @throws Exception If some problem inside
 */
@Test
public void logins() throws Exception {
    final String tokenpath = "/uas/oauth2/accessToken";
    final String firstname = "firstName";
    final String lastname = "lastName";
    final String frodo = "Frodo";
    final String baggins = "Baggins";
    // @checkstyle MagicNumber (4 lines)
    final String code = RandomStringUtils.randomAlphanumeric(10);
    final String lapp = RandomStringUtils.randomAlphanumeric(10);
    final String lkey = RandomStringUtils.randomAlphanumeric(10);
    final String identifier = RandomStringUtils.randomAlphanumeric(10);
    final Take take = new TkFork(
        new FkRegex(
            tokenpath,
            new TokenTake(code, lapp, lkey, tokenpath)
        ),
        new FkRegex(
            "/v1/people",
            new PeopleTake(identifier, firstname, lastname, frodo, baggins)
        )
    );
    new FtRemote(take).exec(
        new LinkedinScript(
            code, lapp, lkey, identifier,
            firstname, lastname, frodo, baggins
        )
    );
}
 
源代码4 项目: jasypt   文件: TestHibernateTypes.java
/**
 * Generate data to test with
 */
private void generateData() {
    userLogin = RandomStringUtils.randomAlphabetic(5);
    userName = RandomStringUtils.randomAlphabetic(10);
    userPassword = RandomStringUtils.randomAlphanumeric(15);
    userBirthdate = Calendar.getInstance();
    try {
           userDocument = RandomStringUtils.randomAlphabetic(100).getBytes(
               "ISO-8859-1");
       } catch (UnsupportedEncodingException e) {
           assertTrue(false);
       }
}
 
源代码5 项目: 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() );
}
 
源代码6 项目: incubator-atlas   文件: TestUtils.java
public static final String randomString() {
    return RandomStringUtils.randomAlphanumeric(10);
}
 
源代码7 项目: atlas   文件: TestUtilsV2.java
public static AtlasEntity createDBEntity() {
    String dbName = RandomStringUtils.randomAlphanumeric(10);
    return createDBEntity(dbName);
}
 
源代码8 项目: atlas   文件: TestUtilsV2.java
public static AtlasEntity createTableEntity(AtlasEntity dbEntity) {
    String tableName = RandomStringUtils.randomAlphanumeric(10);
    return createTableEntity(dbEntity, tableName);
}
 
源代码9 项目: usergrid   文件: UsergridExternalProvider.java
@Override
    public UserInfo validateAndReturnUserInfo(String token, long ttl) throws Exception {
        if (token == null) {
            throw new IllegalArgumentException("ext_access_token must be specified");
        }
        if (ttl == -1) {
            throw new IllegalArgumentException("ttl must be specified");
        }

        com.codahale.metrics.Timer processingTimer = getMetricsFactory().getTimer(
            UsergridExternalProvider.class, SSO_PROCESSING_TIME);

        com.codahale.metrics.Timer.Context timerContext = processingTimer.time();

        try {
            // look up user via UG Central's /management/me endpoint.

            JsonNode accessInfoNode = getMeFromUgCentral(token);

            JsonNode userNode = accessInfoNode.get("user");

            String username = userNode.get("username").asText();

            // if user does not exist locally then we need to fix that

            UserInfo userInfo = management.getAdminUserByUsername(username);
            UUID userId = userInfo == null ? null : userInfo.getUuid();

            if (userId == null) {

                // create local user and and organizations they have on the central Usergrid instance
                logger.info("User {} does not exist locally, creating", username);

                String name = userNode.get("name").asText();
                String email = userNode.get("email").asText();
                String dummyPassword = RandomStringUtils.randomAlphanumeric(40);

                JsonNode orgsNode = userNode.get("organizations");
                Iterator<String> fieldNames = orgsNode.getFieldNames();

                if (!fieldNames.hasNext()) {
                    // no organizations for user exist in response from central Usergrid SSO
                    // so create user's personal organization and use username as organization name
                    fieldNames = Collections.singletonList(username).iterator();
                }

                // create user and any organizations that user is supposed to have

                while (fieldNames.hasNext()) {

                    String orgName = fieldNames.next();

                    if (userId == null) {
//
                        // haven't created user yet so do that now
                        OrganizationOwnerInfo ownerOrgInfo = management.createOwnerAndOrganization(
                            orgName, username, name, email, dummyPassword, true, false);

                        applicationCreator.createSampleFor(ownerOrgInfo.getOrganization());

                        userId = ownerOrgInfo.getOwner().getUuid();
                        userInfo = ownerOrgInfo.getOwner();

                        Counter createdAdminsCounter = getMetricsFactory().getCounter(
                            UsergridExternalProvider.class, SSO_CREATED_LOCAL_ADMINS);
                        createdAdminsCounter.inc();

                        logger.info("Created user {} and org {}", username, orgName);

                    } else {

                        // already created user, so just create an org
                        final OrganizationInfo organization =
                            management.createOrganization(orgName, userInfo, true);

                        applicationCreator.createSampleFor(organization);

                        logger.info("Created user {}'s other org {}", username, orgName);
                    }
                }
            }

            return userInfo;
        } catch (Exception e) {
            timerContext.stop();
            logger.debug("Error validating external token", e);
            throw e;
        }

    }
 
源代码10 项目: tddl5   文件: IbatisTypeTest.java
/**
 * ibatis 边界值最大值测试
 * 
 * @author chenhui
 * @since 5.0.1
 */
@Test
public void boundaryValue_最大值Test() throws SQLException {
    String s = RandomStringUtils.randomAlphanumeric(255);
    byte[] b = s.getBytes();
    BigDecimal big = new BigDecimal(new String("18446744073709551616.99999"));
    String da = "2015-12-31 12:59:59";
    String ti = "12:59:59";
    Boolean bl = true;
    Float f = 1.1f;
    Double d = 1.1d;
    Map<Object, Object> map = new HashMap<Object, Object>();
    map.put("pk", 1);
    map.put("varcharr", s);
    map.put("charr", s);
    map.put("varbinaryr", s);
    map.put("binaryr", s);
    map.put("blobr", b);
    map.put("textr", s);
    map.put("tinyintr", 127);
    map.put("tinyintr_1", 1);
    map.put("smallintr", 32767);
    map.put("mediumintr", 8388607);
    map.put("integerr", 2147483647);
    map.put("bigintr", 9223372036854775807l);
    map.put("utinyintr", 255);
    map.put("usmallintr", 65535);
    map.put("umediumintr", 16777215);
    map.put("uintegerr", 4294967295l);
    map.put("ubigintr", new BigDecimal("18446744073709551615"));
    map.put("bitr", bl);
    map.put("bitr_8", 127);
    map.put("floatr", f);
    map.put("doubler", d);
    map.put("decimalr", big);
    map.put("dater", da);
    map.put("timer", ti);
    map.put("datetimer", da);
    map.put("timestampr", da);
    map.put("yearr", 40);

    tddlSqlMapClient.delete("delete_test", map);
    mysqlSqlMapClient.delete("delete_test", map);
    // andorTDHSSqlMapClient.delete("delete_tdhs_test", map);

    tddlSqlMapClient.insert("insert_test", map);
    mysqlSqlMapClient.insert("insert_test", map);
    // andorTDHSSqlMapClient.insert("insert_tdhs_test", map);

    List list = tddlSqlMapClient.queryForList("select_test", map);
    row = (NormalTblRow) list.get(0);
    List listMysql = mysqlSqlMapClient.queryForList("select_test", map);
    rowMysql = (NormalTblRow) listMysql.get(0);
    rowEquals(row, rowMysql);

    map.put("pk", 2);

    tddlSqlMapClient.delete("delete_test", map);
    mysqlSqlMapClient.delete("delete_test", map);
    // andorTDHSSqlMapClient.delete("delete_tdhs_test", map);

    tddlSqlMapClient.insert("insert_test", map);
    mysqlSqlMapClient.insert("insert_test", map);
    // andorTDHSSqlMapClient.insert("insert_tdhs_test", map);

    list = tddlSqlMapClient.queryForList("select_test", map);
    row = (NormalTblRow) list.get(0);
    listMysql = mysqlSqlMapClient.queryForList("select_test", map);
    rowMysql = (NormalTblRow) listMysql.get(0);
    rowEquals(row, rowMysql);

    // andor的tdhs
    // List listTdhs =
    // andorTDHSSqlMapClient.queryForList("select_tdhs_test", map);
    // rowTdhs = (NormalTblRow) list.get(0);
    // rowEquals(rowTdhs, rowMysql);

    Map idsMap = new HashMap();
    idsMap.put("pks", Arrays.asList(1, 2));
    list = tddlSqlMapClient.queryForList("select_test_max", idsMap);
    row = (NormalTblRow) list.get(0);
    listMysql = mysqlSqlMapClient.queryForList("select_test_max", idsMap);
    rowMysql = (NormalTblRow) listMysql.get(0);
    rowEquals(row, rowMysql);

    map.put("pk", 1);
    tddlSqlMapClient.delete("delete_test", map);
    mysqlSqlMapClient.delete("delete_test", map);
    // andorTDHSSqlMapClient.insert("delete_tdhs_test", map);

    map.put("pk", 2);
    tddlSqlMapClient.delete("delete_test", map);
    mysqlSqlMapClient.delete("delete_test", map);
    // andorTDHSSqlMapClient.insert("delete_tdhs_test", map);
}
 
源代码11 项目: incubator-pinot   文件: StringDictionaryPerfTest.java
/**
 * Helper method to build a segment:
 * <ul>
 *   <li>Segment contains one string column</li>
 *   <li>Row values for the column are randomly generated strings of length 1 to 100</li>
 * </ul>
 */
private void buildSegment(int dictLength)
    throws Exception {
  Schema schema = new Schema();
  String segmentName = "perfTestSegment" + System.currentTimeMillis();
  _indexDir = new File(TMP_DIR + File.separator + segmentName);
  _indexDir.deleteOnExit();

  FieldSpec fieldSpec = new DimensionFieldSpec(COLUMN_NAME, FieldSpec.DataType.STRING, true);
  schema.addField(fieldSpec);
  TableConfig tableConfig = new TableConfigBuilder(TableType.OFFLINE).setTableName("test").build();

  _dictLength = dictLength;
  _inputStrings = new String[dictLength];

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

  Random random = new Random(System.nanoTime());
  List<GenericRow> rows = new ArrayList<>(dictLength);
  Set<String> uniqueStrings = new HashSet<>(dictLength);

  int i = 0;
  while (i < dictLength) {
    HashMap<String, Object> map = new HashMap<>();
    String randomString = RandomStringUtils
        .randomAlphanumeric(USE_FIXED_SIZE_STRING ? MAX_STRING_LENGTH : (1 + random.nextInt(MAX_STRING_LENGTH)));

    if (uniqueStrings.contains(randomString)) {
      continue;
    }

    _inputStrings[i] = randomString;
    if (uniqueStrings.add(randomString)) {
      _statistics.addValue(randomString.length());
    }
    map.put("test", _inputStrings[i++]);

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

  long start = System.currentTimeMillis();
  SegmentIndexCreationDriverImpl driver = new SegmentIndexCreationDriverImpl();
  driver.init(config, new GenericRowRecordReader(rows));
  driver.build();
  System.out.println("Total time for building segment: " + (System.currentTimeMillis() - start));
}
 
源代码12 项目: atlas   文件: ImpalaLineageITBase.java
protected String random() {
    return RandomStringUtils.randomAlphanumeric(10);
}
 
源代码13 项目: takes   文件: PsFacebookTest.java
/**
 * Tests if PsFacebook can call DefaultFacebookClient APIs.
 * @throws Exception if any error occurs
 */
@Test
public final void canLogin() throws Exception {
    final String identifier = RandomStringUtils.randomAlphanumeric(10);
    final RandomStringGenerator generator =
        new RandomStringGenerator.Builder()
            .filteredBy(
                Character::isLetterOrDigit, Character::isIdeographic
            ).build();
    final Pass pass = new PsFacebook(
        new FakeRequest(
            200,
            "HTTP OK",
            Collections.emptyList(),
            String.format(
                "access_token=%s",
                RandomStringUtils.randomAlphanumeric(10)
            ).getBytes(StandardCharsets.UTF_8)
        ),
        new DefaultWebRequestor() {
            @Override
            public Response executeGet(final String url) {
                return new Response(
                    HttpURLConnection.HTTP_OK,
                    String.format(
                        "{\"id\":\"%s\",\"name\":\"%s\"}",
                        identifier,
                        generator.generate(10)
                    )
                );
            }
        },
        generator.generate(10),
        generator.generate(10)
    );
    final Opt<Identity> identity = pass.enter(
        new RqFake(
            "GET",
            String.format(
                "?code=%s",
                RandomStringUtils.randomAlphanumeric(10)
            )
        )
    );
    MatcherAssert.assertThat(identity.has(), Matchers.is(true));
    MatcherAssert.assertThat(
        identity.get().urn(),
        CoreMatchers.equalTo(String.format("urn:facebook:%s", identifier))
    );
}
 
源代码14 项目: usergrid   文件: CollectionsResourceIT.java
/**
 * Test that index entities can be connected to un-indexed Entities and connections still work.
 */
@Test
public void testUnindexedEntityToIndexedEntityConnections() {

    // create two entities in an indexed collection

    String randomizer = RandomStringUtils.randomAlphanumeric(10);
    String indexedCollection = "col_" + randomizer;
    String indexedEntityName = "indexedEntity";

    Entity indexedEntity1 = this.app().collection( indexedCollection )
        .post( new Entity().withProp("name", indexedEntityName + "_1").withProp( "color", "orange" ) );

    Entity indexedEntity2 = this.app().collection( indexedCollection )
        .post( new Entity().withProp("name", indexedEntityName + "_2").withProp( "color", "orange" ) );

    // create an un-indexed entity

    Entity payload = new Entity();
    payload.put( "fields", "none");

    String unIndexedCollectionName = "col_" + randomizer;
    app().collection( unIndexedCollectionName ).collection( "_settings" ).post( payload );
    waitForQueueDrainAndRefreshIndex();

    String entityName1 = "unindexed1";
    Entity unindexed1 = this.app().collection( unIndexedCollectionName )
        .post( new Entity().withProp("name", entityName1).withProp( "color", "violet" ) );

    // create connections from un-indexed entity to indexed entities

    app().collection(unIndexedCollectionName).entity(unindexed1).connection("likes").entity(indexedEntity1).post();
    app().collection(unIndexedCollectionName).entity(unindexed1).connection("likes").entity(indexedEntity2).post();

    // should be able to get connections via graph from un-indexed to index

    Collection connectionsByGraph = app().collection( indexedCollection )
        .entity(unindexed1).connection( "likes" ).get();
    assertEquals( 2, connectionsByGraph.getNumOfEntities() );

    // should not be able to get connections via query from unindexed to indexed

    Collection connectionsByQuery = app().collection( indexedCollection )
        .entity(unindexed1).connection( "likes" )
        .get( new QueryParameters().setQuery( "select * where color='orange'" ));
    assertEquals( 0, connectionsByQuery.getNumOfEntities() );
}
 
/**
 * Test ping flow when a request expires, response from the server should be expired_token and 400 status.
 */
@Parameters({"clientJwksUri", "backchannelClientNotificationEndpoint", "backchannelUserCode", "userId"})
@Test
public void backchannelTokenDeliveryModePingExpiredRequest(
        final String clientJwksUri, final String backchannelClientNotificationEndpoint, final String backchannelUserCode,
        final String userId) throws InterruptedException {
    showTitle("backchannelTokenDeliveryModePingExpiredRequest");

    // 1. Dynamic Client Registration
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app", null);
    registerRequest.setJwksUri(clientJwksUri);
    registerRequest.setGrantTypes(Arrays.asList(GrantType.CIBA));

    registerRequest.setBackchannelTokenDeliveryMode(BackchannelTokenDeliveryMode.PING);
    registerRequest.setBackchannelClientNotificationEndpoint(backchannelClientNotificationEndpoint);
    registerRequest.setBackchannelAuthenticationRequestSigningAlg(AsymmetricSignatureAlgorithm.RS256);
    registerRequest.setBackchannelUserCodeParameter(true);

    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    RegisterResponse registerResponse = registerClient.exec();

    showClient(registerClient);
    assertEquals(registerResponse.getStatus(), 200, "Unexpected response code: " + registerResponse.getEntity());
    assertNotNull(registerResponse.getClientId());
    assertNotNull(registerResponse.getClientSecret());
    assertNotNull(registerResponse.getRegistrationAccessToken());
    assertNotNull(registerResponse.getClientSecretExpiresAt());

    assertTrue(registerResponse.getClaims().containsKey(BACKCHANNEL_TOKEN_DELIVERY_MODE.toString()));
    assertTrue(registerResponse.getClaims().containsKey(BACKCHANNEL_AUTHENTICATION_REQUEST_SIGNING_ALG.toString()));
    assertTrue(registerResponse.getClaims().containsKey(BACKCHANNEL_USER_CODE_PARAMETER.toString()));
    assertTrue(registerResponse.getClaims().containsKey(BACKCHANNEL_CLIENT_NOTIFICATION_ENDPOINT.toString()));
    assertEquals(registerResponse.getClaims().get(BACKCHANNEL_TOKEN_DELIVERY_MODE.toString()), BackchannelTokenDeliveryMode.PING.getValue());
    assertEquals(registerResponse.getClaims().get(BACKCHANNEL_AUTHENTICATION_REQUEST_SIGNING_ALG.toString()), AsymmetricSignatureAlgorithm.RS256.getValue());
    assertEquals(registerResponse.getClaims().get(BACKCHANNEL_USER_CODE_PARAMETER.toString()), new Boolean(true).toString());

    String clientId = registerResponse.getClientId();
    String clientSecret = registerResponse.getClientSecret();

    // 2. Authentication Request
    String bindingMessage = RandomStringUtils.randomAlphanumeric(6);
    String clientNotificationToken = UUID.randomUUID().toString();

    BackchannelAuthenticationRequest backchannelAuthenticationRequest = new BackchannelAuthenticationRequest();
    backchannelAuthenticationRequest.setScope(Arrays.asList("openid", "profile", "email", "address", "phone"));
    backchannelAuthenticationRequest.setLoginHint(userId);
    backchannelAuthenticationRequest.setClientNotificationToken(clientNotificationToken);
    backchannelAuthenticationRequest.setUserCode(backchannelUserCode);
    backchannelAuthenticationRequest.setRequestedExpiry(1);
    backchannelAuthenticationRequest.setAcrValues(Arrays.asList("auth_ldap_server", "basic"));
    backchannelAuthenticationRequest.setBindingMessage(bindingMessage);
    backchannelAuthenticationRequest.setAuthUsername(clientId);
    backchannelAuthenticationRequest.setAuthPassword(clientSecret);

    BackchannelAuthenticationClient backchannelAuthenticationClient = new BackchannelAuthenticationClient(backchannelAuthenticationEndpoint);
    backchannelAuthenticationClient.setRequest(backchannelAuthenticationRequest);
    BackchannelAuthenticationResponse backchannelAuthenticationResponse = backchannelAuthenticationClient.exec();

    showClient(backchannelAuthenticationClient);
    assertEquals(backchannelAuthenticationResponse.getStatus(), 200, "Unexpected response code: " + backchannelAuthenticationResponse.getEntity());
    assertNotNull(backchannelAuthenticationResponse.getAuthReqId());
    assertNotNull(backchannelAuthenticationResponse.getExpiresIn());
    assertNotNull(backchannelAuthenticationResponse.getInterval()); // This parameter will only be present if the Client is registered to use the Poll or Ping modes.

    // 3. Request token - expected expiration error

    TokenResponse tokenResponse;
    int pollCount = 0;
    do {
        Thread.sleep(3500);

        TokenRequest tokenRequest = new TokenRequest(GrantType.CIBA);
        tokenRequest.setAuthUsername(clientId);
        tokenRequest.setAuthPassword(clientSecret);
        tokenRequest.setAuthReqId(backchannelAuthenticationResponse.getAuthReqId());

        TokenClient tokenClient = new TokenClient(tokenEndpoint);
        tokenClient.setRequest(tokenRequest);
        tokenResponse = tokenClient.exec();

        showClient(tokenClient);
        pollCount++;
    } while (pollCount < 5 && tokenResponse.getStatus() == 400
            && tokenResponse.getErrorType() == TokenErrorResponseType.AUTHORIZATION_PENDING);

    assertEquals(tokenResponse.getStatus(), 400, "Unexpected HTTP status resposne: " + tokenResponse.getEntity());
    assertNotNull(tokenResponse.getEntity(), "The entity is null");
    assertEquals(tokenResponse.getErrorType(), TokenErrorResponseType.EXPIRED_TOKEN, "Unexpected error type, should be expired_token.");
    assertNotNull(tokenResponse.getErrorDescription());
}
 
源代码16 项目: atlas   文件: BaseResourceIT.java
protected String randomString() {
    //names cannot start with a digit
    return RandomStringUtils.randomAlphabetic(1) + RandomStringUtils.randomAlphanumeric(9);
}
 
源代码17 项目: atlas   文件: NotificationHookConsumerKafkaTest.java
protected String randomString() {
    return RandomStringUtils.randomAlphanumeric(10);
}
 
源代码18 项目: chassis   文件: ScalaCaseClassTest.java
@Test
public void testBsonSerDe() throws Exception {
	final BsonJacksonMessageSerDe serDe = new BsonJacksonMessageSerDe();

	final TestObject obj = new TestObject(RandomStringUtils.randomAlphanumeric(64), new SomeOtherObject(RandomStringUtils.randomAlphanumeric(64)));
	
	final byte[] serializedObj = serDe.serialize(obj);

	dumpToLog(serDe, serializedObj);
	
	final TestObject deserializedObj = serDe.deserialize(serializedObj, 0, serializedObj.length, TestObject.class);
	
	Assert.assertEquals(obj, deserializedObj);
}
 
源代码19 项目: usergrid   文件: ShardAllocatorTest.java
@Test
public void testBasicOperation() throws InterruptedException {

    Injector injector = getInjector();

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

    injector.getInstance( DistributedQueueService.class ); // init the INJECTOR

    ShardSerialization shardSer = injector.getInstance( ShardSerialization.class );
    QakkaFig qakkaFig           = injector.getInstance( QakkaFig.class );

    ActorSystemFig            actorSystemFig  = injector.getInstance( ActorSystemFig.class );
    ShardCounterSerialization shardCounterSer = injector.getInstance( ShardCounterSerialization.class );

    String rando = RandomStringUtils.randomAlphanumeric( 20 );

    String queueName = "queue_" + rando;
    String region = actorSystemFig.getRegionLocal();

    // Create a set of shards, each with max count

    Shard lastShard = null;

    int numShards = 4;
    long maxPerShard = qakkaFig.getMaxShardSize();

    for ( long shardId = 1; shardId < numShards + 1; shardId++ ) {

        Shard shard = new Shard( queueName, region, Shard.Type.DEFAULT, shardId, QakkaUtils.getTimeUuid());
        shardSer.createShard( shard );

        if ( shardId != numShards ) {
            shardCounterSer.incrementCounter( queueName, Shard.Type.DEFAULT, shardId, maxPerShard );

        } else {
            // Create last shard with %20 less than max
            shardCounterSer.incrementCounter( queueName, Shard.Type.DEFAULT, shardId, (long)(0.8 * maxPerShard) );
            lastShard = shard;
        }

        Thread.sleep( 10 );
    }

    Assert.assertEquals( numShards, countShards(
            cassandraClient, shardCounterSer, queueName, region, Shard.Type.DEFAULT ));

    // Run shard allocator actor by sending message to it

    ActorSystem system = ActorSystem.create("Test-" + queueName);
    ActorRef shardAllocRef = system.actorOf( Props.create(
        GuiceActorProducer.class, ShardAllocator.class), "shardallocator");

    ShardCheckRequest checkRequest = new ShardCheckRequest( queueName );
    shardAllocRef.tell( checkRequest, null ); // tell sends message, returns immediately
    Thread.sleep(2000);

    // Test that no new shards created

    Assert.assertEquals( numShards, countShards(
            cassandraClient, shardCounterSer, queueName, region, Shard.Type.DEFAULT ));

    // Increment last shard by 20% of max

    shardCounterSer.incrementCounter(
            queueName, Shard.Type.DEFAULT, lastShard.getShardId(), (long)(0.3 * maxPerShard) );

    // Run shard allocator again

    shardAllocRef.tell( checkRequest, null ); // tell sends message, returns immediately
    Thread.sleep(2000);

    // Test that, this time, a new shard was created

    Assert.assertEquals( numShards + 1, countShards(
            cassandraClient, shardCounterSer, queueName, region, Shard.Type.DEFAULT ));
}
 
源代码20 项目: usergrid   文件: RebuildIndexTest.java
@Test(timeout = 240000)
public void rebuildOneCollectionIndex() throws Exception {

    logger.info("Started rebuildOneCollectionIndex()");

    String rand = RandomStringUtils.randomAlphanumeric(5);
    final UUID appId = setup.createApplication("org_" + rand, "app_" + rand);

    final EntityManager em = setup.getEmf().getEntityManager(appId);

    final ReIndexService reIndexService = setup.getInjector().getInstance(ReIndexService.class);

    // ----------------- create a bunch of entities

    Map<String, Object> entityMap = new HashMap<String, Object>() {{
        put("key1", 1000);
        put("key2", 2000);
        put("key3", "Some value");
    }};


    List<EntityRef> entityRefs = new ArrayList<EntityRef>();
    int herderCount = 0;
    int shepardCount = 0;
    for (int i = 0; i < ENTITIES_TO_INDEX; i++) {

        final Entity entity;

        try {
            entityMap.put("key", i);

            if (i % 2 == 0) {
                entity = em.create("catherder", entityMap);
                herderCount++;
            } else {
                entity = em.create("catshepard", entityMap);
                shepardCount++;
            }
        } catch (Exception ex) {
            throw new RuntimeException("Error creating entity", ex);
        }

        entityRefs.add(new SimpleEntityRef(entity.getType(), entity.getUuid()));
        if (i % 10 == 0) {
            logger.info("Created {} entities", i);
        }
    }

    logger.info("Created {} entities", ENTITIES_TO_INDEX);
    app.waitForQueueDrainAndRefreshIndex(1000);

    // ----------------- test that we can read them, should work fine

    logger.debug("Read the data");
    retryReadData(em, "catherders", herderCount, 0, 10);
    retryReadData(em, "catshepards", shepardCount, 0, 10);

    // ----------------- delete the system and application indexes

    logger.debug("Deleting apps");
    deleteIndex(em.getApplicationId());

    // ----------------- test that we can read them, should fail

    logger.debug("Reading data, should fail this time ");

    //should be no data
    readData(em, "testTypes", 0, 0);


    //        ----------------- rebuild index for catherders only

    logger.debug("Preparing to rebuild all indexes");


    final ReIndexRequestBuilder builder =
        reIndexService.getBuilder().withApplicationId(em.getApplicationId()).withCollection("catherders");

    ReIndexService.ReIndexStatus status = reIndexService.rebuildIndex(builder);

    assertNotNull(status.getCollectionName(), "Collection name is present");

    logger.info("Rebuilt index");


    waitForRebuild(em.getApplicationId().toString(), status.getCollectionName(), reIndexService);

    //app.waitForQueueDrainAndRefreshIndex(15000);

    // ----------------- test that we can read the catherder collection and not the catshepard

    retryReadData(em, "catherders", herderCount, 0, 30);
    retryReadData(em, "catshepards", 0, 0, 30);
}