下面列出了怎么用org.apache.commons.lang3.RandomStringUtils的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
@Transactional
@WithMockUser("change-password-empty")
public void testChangePasswordEmpty() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.random(60));
user.setLogin("change-password-empty");
user.setEmail("[email protected]");
userRepository.saveAndFlush(user);
restMvc.perform(post("/api/account/change-password").content(RandomStringUtils.random(0)))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null);
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
private void addNameRecord() {
WebMarkupContainer nameRecordingContainer = new WebMarkupContainer("nameRecordingContainer");
nameRecordingContainer.add(new Label("nameRecordingLabel", new ResourceModel("profile.name.recording")));
WebMarkupContainer audioPlayer = new WebMarkupContainer("audioPlayer");
final String slash = Entity.SEPARATOR;
final StringBuilder path = new StringBuilder();
path.append(slash);
path.append("direct");
path.append(slash);
path.append("profile");
path.append(slash);
path.append(userProfile.getUserUuid());
path.append(slash);
path.append("pronunciation");
path.append("?v=");
path.append(RandomStringUtils.random(8, true, true));
audioPlayer.add(new AttributeModifier("src", path.toString()));
nameRecordingContainer.add(audioPlayer);
add(nameRecordingContainer);
if (profileLogic.getUserNamePronunciation(userProfile.getUserUuid()) == null) nameRecordingContainer.setVisible(false);
else visibleFieldCount++;
}
@Test
@Transactional
public void testFinishPasswordResetTooSmall() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.random(60));
user.setLogin("finish-password-reset-too-small");
user.setEmail("[email protected]");
user.setResetDate(Instant.now().plusSeconds(60));
user.setResetKey("reset key too small");
userRepository.saveAndFlush(user);
KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM();
keyAndPassword.setKey(user.getResetKey());
keyAndPassword.setNewPassword("foo");
restMvc.perform(
post("/api/account/reset-password/finish")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null);
assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isFalse();
}
@Test
public void testMissingKey() {
SecurityConfig securityConfig = new SecurityConfig(conf);
CertificateServer testCA = new DefaultCAServer("testCA",
RandomStringUtils.randomAlphabetic(4),
RandomStringUtils.randomAlphabetic(4), caStore);
Consumer<SecurityConfig> caInitializer =
((DefaultCAServer) testCA).processVerificationStatus(
DefaultCAServer.VerificationStatus.MISSING_KEYS);
try {
caInitializer.accept(securityConfig);
fail("code should not reach here, exception should have been thrown.");
} catch (IllegalStateException e) {
// This also is a runtime exception. Hence not caught by junit expected
// exception.
assertTrue(e.toString().contains("Missing Keys"));
}
}
@Test
public void mustProcessGroupAnnotationCorrectly() throws IOException {
populateGroupCollection();
int totalQuantity = testGroupRepository.getTotalQuantityForOneItem("abc");
assertEquals(12, totalQuantity);
List<TestGroupResultsBean> results = testGroupRepository.salesBySalesDate();
assertNotNull(results);
totalQuantity = testGroupRepository.getTotalQuantityForOneItem("xyz");
assertEquals(30, totalQuantity);
totalQuantity = testGroupRepository.getTotalQuantityForOneItem("jkl");
assertEquals(1, totalQuantity);
Integer noQuantity = testGroupRepository.getTotalQuantityForOneItem(RandomStringUtils.random(10));
assertNull(noQuantity);
}
@Override
public void listByAge(UserRpcProto.AgeRequest request, StreamObserver<UserRpcProto.UserResponse> responseObserver) {
logger.info("Server Rec listByAge request...");
// 构造响应,模拟业务逻辑
UserRpcProto.UserResponse response = UserRpcProto.UserResponse.newBuilder()
.setCode(0)
.setMsg("success")
.addUser(MessageProto.User.newBuilder()
.setName(RandomStringUtils.randomAlphabetic(5))
.setAge(request.getAge()).build())
.addUser(MessageProto.User.newBuilder()
.setName(RandomStringUtils.randomAlphabetic(5))
.setAge(request.getAge()).build())
.addUser(MessageProto.User.newBuilder()
.setName(RandomStringUtils.randomAlphabetic(5))
.setAge(request.getAge()).build())
.build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
@Test
@Description("Handles the DELETE request for a single SoftwareModule within SP. Required Permission: "
+ SpPermission.DELETE_REPOSITORY)
public void deleteArtifact() throws Exception {
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
final byte random[] = RandomStringUtils.random(5).getBytes();
final Artifact artifact = artifactManagement
.create(new ArtifactUpload(new ByteArrayInputStream(random), sm.getId(), "file1", false, 0));
mockMvc.perform(delete(
MgmtRestConstants.SOFTWAREMODULE_V1_REQUEST_MAPPING + "/{softwareModuleId}/artifacts/{artifactId}",
sm.getId(), artifact.getId())).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andDo(this.document.document(pathParameters(
parameterWithName("softwareModuleId").description(ApiModelPropertiesGeneric.ITEM_ID),
parameterWithName("artifactId").description(ApiModelPropertiesGeneric.ITEM_ID))));
}
@Test
@Transactional
@WithMockUser("change-password-too-long")
public void testChangePasswordTooLong() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.random(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password-too-long");
user.setEmail("[email protected]");
userRepository.saveAndFlush(user);
restMvc.perform(post("/api/account/change-password")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, RandomStringUtils.random(101)))))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null);
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
@Test
public void testCountEstimatedRowsInTable() throws Exception {
try (Table<String, String> testTable = createTypedTable(
"Ninth")) {
// Add a few keys
final int numKeys = 12345;
for (int i = 0; i < numKeys; i++) {
String key =
RandomStringUtils.random(10);
String value = RandomStringUtils.random(10);
testTable.put(key, value);
}
long keyCount = testTable.getEstimatedKeyCount();
// The result should be larger than zero but not exceed(?) numKeys
Assert.assertTrue(keyCount > 0 && keyCount <= numKeys);
}
}
@Test
public void moveKey() throws Exception {
byte[] key =
RandomStringUtils.random(10).getBytes(StandardCharsets.UTF_8);
byte[] value =
RandomStringUtils.random(10).getBytes(StandardCharsets.UTF_8);
try (Table firstTable = rdbStore.getTable(families.get(1))) {
firstTable.put(key, value);
try (Table<byte[], byte[]> secondTable = rdbStore
.getTable(families.get(2))) {
rdbStore.move(key, firstTable, secondTable);
byte[] newvalue = secondTable.get(key);
// Make sure we have value in the second table
Assert.assertNotNull(newvalue);
//and it is same as what we wrote to the FirstTable
Assert.assertArrayEquals(value, newvalue);
}
// After move this key must not exist in the first table.
Assert.assertNull(firstTable.get(key));
}
}
@Test
@Transactional
public void testFinishPasswordResetTooSmall() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.random(60));
user.setLogin("finish-password-reset-too-small");
user.setEmail("[email protected]");
user.setResetDate(Instant.now().plusSeconds(60));
user.setResetKey("reset key too small");
userRepository.saveAndFlush(user);
KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM();
keyAndPassword.setKey(user.getResetKey());
keyAndPassword.setNewPassword("foo");
restMvc.perform(
post("/api/account/reset-password/finish")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null);
assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isFalse();
}
@Override
protected void prepare() throws Exception {
String ccConfig1 = "{\n" +
" \"__type__\" : \"org.squirrelframework.cloud.resource.security.rsa.RSAPrivateKeyConfig\", \n"+
" \"privateKey\" : \""+test_private_key+"\"\n"+
"}";
zkConfigClient.create().creatingParentsIfNeeded().forPath("/codec/rsa/private", ccConfig1.getBytes());
String ccConfig2 = "{\n" +
" \"__type__\" : \"org.squirrelframework.cloud.resource.security.rsa.RSAPublicKeyConfig\", \n"+
" \"publicKey\" : \""+test_public_key+"\"\n"+
"}";
zkConfigClient.create().creatingParentsIfNeeded().forPath("/codec/rsa/public", ccConfig2.getBytes());
String ccConfig3 = "{\n" +
" \"__type__\" : \"org.squirrelframework.cloud.resource.security.md5.Md5SignatureConfig\", \n"+
" \"secretKey\" : \""+RandomStringUtils.randomAlphabetic(32)+"\"\n"+
"}";
zkConfigClient.create().creatingParentsIfNeeded().forPath("/codec/md5", ccConfig3.getBytes());
}
@Test
public void batchDelete() throws Exception {
try (Table testTable = rdbStore.getTable("Fifth");
BatchOperation batch = rdbStore.initBatchOperation()) {
//given
byte[] key =
RandomStringUtils.random(10).getBytes(StandardCharsets.UTF_8);
byte[] value =
RandomStringUtils.random(10).getBytes(StandardCharsets.UTF_8);
testTable.put(key, value);
Assert.assertNotNull(testTable.get(key));
//when
testTable.deleteWithBatch(batch, key);
rdbStore.commitBatchOperation(batch);
//then
Assert.assertNull(testTable.get(key));
}
}
@Test
public void testRwRouteWithTransaction2(){
userMapper.findByStatus((short)1);
transactionTemplate.execute(new TransactionCallback<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
userMapper.findByStatus((short)2);
UserEntity entity = new UserEntity();
entity.setCreatedAt(new Date());
entity.setEmail(RandomStringUtils.random(6, true, true) + "@163.com");
entity.setMobile("13800"+RandomUtils.nextLong(100000, 999999));
entity.setType((short)1);
entity.setStatus((short)1);
userMapper.insert(entity);
userMapper.findByStatus((short)2);
return null;
}
});
System.out.println();
}
public static void main(String[] args) throws Exception {
ZkClient zkClient = new ZkClient("127.0.0.1:2181", 10000, 5000, new ZKStringSerializer());
ExecutorService service = Executors.newFixedThreadPool(5);
for (int i = 0; i < 100; i++) {
service.execute(new Runnable() {
@Override
public void run() {
String path = KafkaConst.ZK_PRODUCER_ACK_PATH + RandomStringUtils.random(5, true, true);
zkClient.createEphemeral(path);
System.out.println(path);
}
});
if(i % 5 == 0){
Thread.sleep(500);
System.out.println("Sleep");
}
}
}
@Test
@Transactional
@WithMockUser("change-password-empty")
public void testChangePasswordEmpty() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.random(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password-empty");
user.setEmail("[email protected]");
userRepository.saveAndFlush(user);
restAccountMockMvc.perform(post("/api/account/change-password")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "")))
)
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null);
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
@Test
@Transactional
@WithMockUser("change-password-too-long")
public void testChangePasswordTooLong() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.random(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password-too-long");
user.setEmail("[email protected]");
userRepository.saveAndFlush(user);
String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MAX_LENGTH + 1);
restMvc.perform(post("/api/account/change-password")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword))))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null);
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
public static OzoneBucket createVolumeAndBucket(MiniOzoneCluster cluster)
throws IOException {
final int attempts = 5;
for (int i = 0; i < attempts; i++) {
try {
String volumeName = "volume" + RandomStringUtils.randomNumeric(5);
String bucketName = "bucket" + RandomStringUtils.randomNumeric(5);
return createVolumeAndBucket(cluster, volumeName, bucketName);
} catch (OMException e) {
if (e.getResult() != OMException.ResultCodes.VOLUME_ALREADY_EXISTS &&
e.getResult() != OMException.ResultCodes.BUCKET_ALREADY_EXISTS) {
throw e;
}
}
}
throw new IllegalStateException("Could not create unique volume/bucket " +
"in " + attempts + " attempts");
}
@Test
public void validate_rejectsAlternativeNamesThatAreTooLong() {
final String maxLengthAlternativeName = RandomStringUtils.randomAlphabetic(57) + "." + RandomStringUtils.randomNumeric(63) +
"." + RandomStringUtils.randomAlphabetic(63) + "." + RandomStringUtils.randomAlphabetic(63) + ".com";
subject.setAlternativeNames(new String[]{"abc.com", maxLengthAlternativeName});
subject.validate();
final String overlyLongAlternativeName = "." + RandomStringUtils.randomAlphabetic(58) + "." + RandomStringUtils.randomNumeric(63) +
"." + RandomStringUtils.randomAlphabetic(63) + "." + RandomStringUtils.randomAlphabetic(63) + ".co";
subject.setAlternativeNames(new String[]{"abc.com", overlyLongAlternativeName});
try {
subject.validate();
fail("should throw");
} catch (final ParameterizedValidationException e) {
assertThat(e.getMessage(), equalTo(ErrorMessages.Credential.INVALID_CERTIFICATE_PARAMETER));
assertThat(e.getParameters(), equalTo(new Object[]{"alternative name", 253}));
}
}
@Test
@Transactional
public void testFinishPasswordReset() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.random(60));
user.setLogin("finish-password-reset");
user.setEmail("[email protected]");
user.setResetDate(Instant.now().plusSeconds(60));
user.setResetKey("reset key");
userRepository.saveAndFlush(user);
KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM();
keyAndPassword.setKey(user.getResetKey());
keyAndPassword.setNewPassword("new password");
restMvc.perform(
post("/api/account/reset-password/finish")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
.andExpect(status().isOk());
User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null);
assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isTrue();
}
private String generateRandomName() {
return IntStream.range(0, 5)
.mapToObj(i -> RandomStringUtils.randomAlphanumeric(15))
.filter(this::isUnique)
.limit(1)
.findFirst()
.orElse("");
}
/**
* Test move.
*
* @throws IOException Signals that an I/O exception has occurred.
*/
@Test
public void testMove() throws IOException {
Path path =
Paths.get(
tempFile.getParent().toString(),
RandomStringUtils.randomNumeric(10));
String linkPath = SymbolicLinkHelper.move(
path.toString(),
tempFile.toString());
path.toFile().deleteOnExit();
assertTrue(SymbolicLinkHelper.isSymbolicLink(linkPath));
}
private void generateJsonLengthInvalid() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date newDate = new Date();
sendToKafka(RawDataGen.builder()
.timestamp(df.format(newDate))
.type("generateJsonLengthInvalid")
.project("project_demo")
.messageSend(RandomStringUtils.randomAlphanumeric(3000))
.build());
}
/**
* Tests writing to non-default certificate file name.
*
* @throws IOException - on Error.
* @throws SCMSecurityException - on Error.
* @throws NoSuchProviderException - on Error.
* @throws NoSuchAlgorithmException - on Error.
* @throws CertificateException - on Error.
*/
@Test
public void writeCertificate2() throws IOException, SCMSecurityException,
NoSuchProviderException, NoSuchAlgorithmException, CertificateException {
HDDSKeyGenerator keyGenerator =
new HDDSKeyGenerator(conf);
X509CertificateHolder cert =
SelfSignedCertificate.newBuilder()
.setSubject(RandomStringUtils.randomAlphabetic(4))
.setClusterID(RandomStringUtils.randomAlphabetic(4))
.setScmID(RandomStringUtils.randomAlphabetic(4))
.setBeginDate(LocalDate.now())
.setEndDate(LocalDate.now().plus(1, ChronoUnit.DAYS))
.setConfiguration(keyGenerator.getSecurityConfig()
.getConfiguration())
.setKey(keyGenerator.generateKey())
.makeCA()
.build();
CertificateCodec codec =
new CertificateCodec(keyGenerator.getSecurityConfig(), "ca");
codec.writeCertificate(cert, "newcert.crt", false);
// Rewrite with force support
codec.writeCertificate(cert, "newcert.crt", true);
X509CertificateHolder x509CertificateHolder =
codec.readCertificate(codec.getLocation(), "newcert.crt");
assertNotNull(x509CertificateHolder);
}
@BeforeClass
public static void setUp() {
for (int i = 0; i < data.length; i++) {
data[i] = RandomStringUtils.random(50 + i % 200);
size += data[i].length();
}
}
@Override
public UserCredentials requestPasswordReset(String email) {
log.trace("Executing requestPasswordReset email [{}]", email);
validateString(email, "Incorrect email " + email);
User user = userDao.findByEmail(email);
if (user == null) {
throw new IncorrectParameterException(String.format("Unable to find user by email [%s]", email));
}
UserCredentials userCredentials = userCredentialsDao.findByUserId(user.getUuidId());
if (!userCredentials.isEnabled()) {
throw new IncorrectParameterException("Unable to reset password for inactive user");
}
userCredentials.setResetToken(RandomStringUtils.randomAlphanumeric(DEFAULT_TOKEN_LENGTH));
return saveUserCredentials(userCredentials);
}
protected void indexDoc(Object... fields) throws IOException,
SolrServerException {
SolrInputDocument doc = new SolrInputDocument();
addFields(doc, fields);
addFields(doc, "rnd_s", RandomStringUtils.random(random().nextInt(100) + 100));
UpdateRequest ureq = new UpdateRequest();
ureq.add(doc);
ModifiableSolrParams params = new ModifiableSolrParams();
ureq.setParams(params);
ureq.process(cloudClient);
}
@Override
protected void onInitialize() {
super.onInitialize();
IModel<String> valueModel = new AbstractReadOnlyModel<String>() {
@Override
public String getObject() {
return getUser().getAccessToken();
}
};
add(new TextField<String>("value", valueModel) {
@Override
protected String[] getInputTypes() {
return new String[] {"password"};
}
});
add(new CopyToClipboardLink("copy", valueModel));
add(new Link<Void>("regenerate") {
@Override
public void onClick() {
getUser().setAccessToken(RandomStringUtils.randomAlphanumeric(User.ACCESS_TOKEN_LEN));
OneDev.getInstance(UserManager.class).save(getUser());
Session.get().success("Access token regenerated");
setResponsePage(getPage());
}
}.add(new ConfirmClickModifier("This will invalidate current token and generate a new one, do you want to continue?")));
}
private void generateBlackList() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date newDate = new Date();
sendToKafka(RawDataGen.builder()
.timestamp(df.format(newDate))
.type("auditd")
.project("project_demo")
.messageSend(RandomStringUtils.randomAlphanumeric(60))
.build());
}
private static Space getSpaceTemplate(String owner, String cid) {
Space space = new Space();
space.setId(RandomStringUtils.randomAlphanumeric(8));
space.setOwner(owner);
space.setCid(cid);
space.setEnableUUID(false);
space.setClient(null);
space.setStorage(new ConnectorRef().withId(Service.configuration.DEFAULT_STORAGE_ID));
return space;
}