下面列出了怎么用org.apache.commons.lang.math.RandomUtils的API类实例代码及写法,或者点击链接到github查看源代码。
@RequestMapping("checkout-name")
public void checkoutName(HttpServletRequest request, HttpServletResponse response) throws IOException {
String fullName = getParameterNotNull(request, "fullName");
fullName = fullName.replaceAll("[^a-zA-Z0-9\u4e00-\u9fa5]", "");
String loginName = HanLP.convertToPinyinString(fullName, "", false);
if (loginName.length() > 20) {
loginName = loginName.substring(0, 20);
}
if (BlackList.isBlack(loginName)) {
writeSuccess(response);
return;
}
for (int i = 0; i < 100; i++) {
if (Application.getUserStore().existsName(loginName)) {
loginName += RandomUtils.nextInt(99);
} else {
break;
}
}
loginName = loginName.toLowerCase();
writeSuccess(response, loginName);
}
private Intent createIntent(Key key, long mac, NodeId node, Multimap<NodeId, Device> devices) {
// choose a random device for which this node is master
List<Device> deviceList = devices.get(node).stream().collect(Collectors.toList());
Device device = deviceList.get(RandomUtils.nextInt(deviceList.size()));
//FIXME we currently ignore the path length and always use the same device
TrafficSelector selector = DefaultTrafficSelector.builder()
.matchEthDst(MacAddress.valueOf(mac)).build();
TrafficTreatment treatment = DefaultTrafficTreatment.emptyTreatment();
ConnectPoint ingress = new ConnectPoint(device.id(), PortNumber.portNumber(1));
ConnectPoint egress = new ConnectPoint(device.id(), PortNumber.portNumber(2));
return PointToPointIntent.builder()
.appId(appId)
.key(key)
.selector(selector)
.treatment(treatment)
.filteredIngressPoint(new FilteredConnectPoint(ingress))
.filteredEgressPoint(new FilteredConnectPoint(egress))
.build();
}
/**
* 生成验证码
*
* @param key
* @param level complexity 1<2<3
* @return
*/
public static String generate(String key, int level) {
String vcode;
if (level == 3) {
vcode = CodecUtils.randomCode(20);
} else if (level == 2) {
vcode = CodecUtils.randomCode(8);
} else {
vcode = RandomUtils.nextInt(999999999) + "888888";
vcode = vcode.substring(0, 6);
}
// 缓存 10 分钟
Application.getCommonCache().put("VCode-" + key, vcode, CommonCache.TS_HOUR / 6);
return vcode;
}
@Test
public void lessThanReadRestraintByDynamicTest() throws InterruptedException {
if (ASTATICISM_TEST) {
return;
}
int executCount = 10;
int readCount = RandomUtils.nextInt(executCount);
MockServer.setConfigInfo(TAtomConstants.getAppDataId(APPNAME, DBKEY_0),
" maxPoolSize=100\r\nuserName=tddl\r\nminPoolSize=1\r\nreadRestrictTimes=" + executCount + "\r\n");
TimeUnit.SECONDS.sleep(SLEEP_TIME);
String sql = "select * from normaltbl_0001 where pk=?";
for (int i = 0; i < readCount; i++) {
try {
Map rs = tddlJT.queryForMap(sql, new Object[] { RANDOM_ID });
Assert.assertEquals(time, String.valueOf(rs.get("gmt_create")));
executCount--;
} catch (DataAccessException ex) {
}
}
Assert.assertTrue(executCount >= 0);
}
/**
* 添加一条测试记录
*
* @return
*/
protected ID addRecordOfTestAllFields() {
Entity testEntity = MetadataHelper.getEntity(TEST_ENTITY);
// 自动添加权限
if (!Application.getSecurityManager().allowCreate(getSessionUser(), testEntity.getEntityCode())) {
Record p = EntityHelper.forNew(EntityHelper.RolePrivileges, UserService.SYSTEM_USER);
p.setID("roleId", SIMPLE_ROLE);
p.setInt("entity", testEntity.getEntityCode());
p.setString("definition", "{'A':1,'R':1,'C':4,'S':1,'D':1,'U':1}");
Application.getCommonService().create(p, Boolean.FALSE);
Application.getUserStore().refreshRole(SIMPLE_ROLE);
}
Record record = EntityHelper.forNew(testEntity.getEntityCode(), getSessionUser());
record.setString("text", "TEXT-" + RandomUtils.nextLong());
return Application.getGeneralEntityService().create(record).getPrimary();
}
@Override
public WebElement randomSelect(Element ele)
{
Select select = createSelect(ele);
if(select != null)
{
List<WebElement> options = select.getOptions();
if(CollectionUtils.isNotEmpty(options))
{
int count = options.size();
int index = RandomUtils.nextInt(count);
index = (index == 0 ? 1 : index); //通常第一个选项都是无效的选项
select.selectByIndex(index);
return options.get(index);
}
}
return null;
}
/**
* Build worker node entity by IP and PORT
*/
private WorkerNodeEntity buildWorkerNode() {
WorkerNodeEntity workerNodeEntity = new WorkerNodeEntity();
if (DockerUtils.isDocker()) {
workerNodeEntity.setType(WorkerNodeType.CONTAINER.value());
workerNodeEntity.setHostName(DockerUtils.getDockerHost());
workerNodeEntity.setPort(DockerUtils.getDockerPort());
} else {
workerNodeEntity.setType(WorkerNodeType.ACTUAL.value());
workerNodeEntity.setHostName(NetUtils.getLocalAddress());
workerNodeEntity.setPort(System.currentTimeMillis() + "-" + RandomUtils.nextInt(100000));
}
return workerNodeEntity;
}
@Test
public void givenAtlasAndCounter_whenRegister_thenPublishedToAtlas() throws Exception {
Counter counter = new BasicCounter(MonitorConfig
.builder("test")
.withTag("servo", "counter")
.build());
DefaultMonitorRegistry
.getInstance()
.register(counter);
assertThat(atlasValuesOfTag("servo"), not(containsString("counter")));
for (int i = 0; i < 3; i++) {
counter.increment(RandomUtils.nextInt(10));
SECONDS.sleep(1);
counter.increment(-1 * RandomUtils.nextInt(10));
SECONDS.sleep(1);
}
assertThat(atlasValuesOfTag("servo"), containsString("counter"));
}
public static void main(String[] args) {
byte[] data=new byte[1024*1024];
for(int i=0;i<data.length;i++)
{
data[i]=(byte) RandomUtils.nextInt(255);
}
Test t=new Test();
Scanner sc=new Scanner(System.in);
sc.nextLine();
// t.testtMap(data);
// sc.nextLine();
// t.testMap(data);
// sc.nextLine();
t.testNMap(data);
sc.nextLine();
}
public static void main(String[] args) {
byte[] data=new byte[1024*1024];
for(int i=0;i<data.length;i++)
{
data[i]=(byte) RandomUtils.nextInt(255);
}
Test t=new Test();
Scanner sc=new Scanner(System.in);
sc.nextLine();
// t.testtMap(data);
// sc.nextLine();
// t.testMap(data);
// sc.nextLine();
t.testNMap(data);
sc.nextLine();
}
public static void test(int x,int y,int radio,boolean print)
{
byte[] array=new byte[x*y];
for(int i=0;i<array.length;i++)
{
array[i]=(byte) RandomUtils.nextInt(radio);
}
byte[][] data=getData(array, x, y);
if(print)
{
printArray(data);
}
byte[] zipData=gzipData(array);
if(print)
{
printArray(getData(zipData, x, y));
}
int zipLen=zipData.length;
int len=array.length-zipLen;
int p=(int) ((len*1.0f/array.length)*100);
System.out.println("压缩后长度:"+zipLen+",节省空间:"+p+"%");
}
@Test
public void testNodeListAtScale() {
final int nodeSize = 10000;
final List<String> nodes = generateRandomStrings(nodeSize);
final long start1 = System.currentTimeMillis();
final KetamaNodeLocator locator = new KetamaNodeLocator(nodes);
// Make sure the initialization doesn't take too long.
// System.out.println("Duration: " + (System.currentTimeMillis() - start1));
assertTrue((System.currentTimeMillis() - start1) < 5000);
final List<String> keys = generateRandomStrings(5 + RandomUtils.nextInt(5));
for (final String key : keys) {
final long start2 = System.currentTimeMillis();
final List<String> superlist = locator.getPriorityList(key, nodeSize);
// System.out.println("Duration: " + (System.currentTimeMillis() - start2));
assertTrue((System.currentTimeMillis() - start2) < 200);
assertEquals(nodeSize, superlist.size());
}
}
/**
* Can be used with xml configuration file or properties file
*
* @param datakey
*/
public void fillFromConfig(String datakey) {
List<Object[]> set = DataProviderUtil.getDataSetAsMap(datakey,"");
if (set.isEmpty()) {
return;
}
int index = 0;
if (set.size() > 1) {
if (ApplicationProperties.BEAN_POPULATE_RANDOM.getBoolenVal(false)) {
// get random index from 0 to size-1.
index = RandomUtils.nextInt(set.size());
} else {
// get next index, if index exceeds size then start with 0.
int cindex = getBundle().getInt(RetryAnalyzer.RETRY_INVOCATION_COUNT, 0);
index = cindex % set.size();
}
}
fillData(set.get(index)[0]);
}
private byte[] getTuple()
{
int securityCode = adId % 30;
if (securityCode < 10) {
securityCode += 10;
}
StringBuilder sb = new StringBuilder();
sb.append(adId + ","); //adId
sb.append((adId + 10) + ","); //campaignId
sb.append("TestAdd" + ","); //adName
sb.append("2.2" + ","); //bidPrice
sb.append(startDateFormat.format(calendar.getTime()) + ","); //startDate
sb.append(endDateFormat.format(calendar.getTime()) + ","); //endDate
sb.append(adId + 10 + ","); //securityCode
sb.append(RandomUtils.nextBoolean() + ","); //active
sb.append(RandomUtils.nextBoolean() ? "OPTIMIZE," : "NO_OPTIMIZE,"); //optimized
sb.append(PARENT_CAMPAIGN); //parentCampaign
adId++;
return String.valueOf(sb).getBytes();
}
@Test
public void lessThanWriteRestraintTest() throws InterruptedException {
if (ASTATICISM_TEST) {
return;
}
int executCount = 10;
int writeCount = RandomUtils.nextInt(executCount);
MockServer.setConfigInfo(TAtomConstants.getAppDataId(APPNAME, DBKEY_0),
" maxPoolSize=100\r\nuserName=tddl\r\nminPoolSize=1\r\nwriteRestrictTimes=" + executCount + "\r\n");
TimeUnit.SECONDS.sleep(SLEEP_TIME);
String sql = "update normaltbl_0001 set gmt_create=? where pk=?";
for (int i = 0; i < writeCount; i++) {
try {
int rs = tddlJT.update(sql, new Object[] { nextDay, RANDOM_ID });
Assert.assertEquals(1, rs);
executCount--;
} catch (DataAccessException ex) {
}
}
Assert.assertTrue(executCount >= 0);
}
@Test
public void lessThanReadRestraintByDynamicTest() throws InterruptedException {
if (ASTATICISM_TEST) {
return;
}
int executCount = 10;
int readCount = RandomUtils.nextInt(executCount);
MockServer.setConfigInfo(TAtomConstants.getAppDataId(APPNAME, DBKEY_0),
" maxPoolSize=100\r\nuserName=tddl\r\nminPoolSize=1\r\nreadRestrictTimes=" + executCount + "\r\n");
TimeUnit.SECONDS.sleep(SLEEP_TIME);
String sql = "select * from normaltbl_0001 where pk=?";
for (int i = 0; i < readCount; i++) {
try {
Map rs = tddlJT.queryForMap(sql, new Object[] { RANDOM_ID });
Assert.assertEquals(time, String.valueOf(rs.get("gmt_create")));
executCount--;
} catch (DataAccessException ex) {
}
}
Assert.assertTrue(executCount >= 0);
}
/**
* Get a uniformly random element from a Collection.
*
* @param collection
* @return
*/
public static <T> T getRandomElement(final Collection<T> collection) {
final int randPos = RandomUtils
.nextInt(checkNotNull(collection).size());
T selected = null;
int index = 0;
for (final T element : collection) {
if (index == randPos) {
selected = element;
break;
}
index++;
}
return selected;
}
/**
* Get a uniformly random element from a Collection.
*
* @param collection
* @return
*/
public static <T> T getRandomElement(final Collection<T> collection) {
final int randPos = RandomUtils
.nextInt(checkNotNull(collection).size());
T selected = null;
int index = 0;
for (final T element : collection) {
if (index == randPos) {
selected = element;
break;
}
index++;
}
return selected;
}
@Test
public void lessThanWriteRestraintTest() throws InterruptedException {
if (ASTATICISM_TEST) {
return;
}
int executCount = 10;
int writeCount = RandomUtils.nextInt(executCount);
MockServer.setConfigInfo(TAtomConstants.getAppDataId(APPNAME, DBKEY_0),
" maxPoolSize=100\r\nuserName=tddl\r\nminPoolSize=1\r\nwriteRestrictTimes=" + executCount + "\r\n");
TimeUnit.SECONDS.sleep(SLEEP_TIME);
String sql = "update normaltbl_0001 set gmt_create=? where pk=?";
for (int i = 0; i < writeCount; i++) {
try {
int rs = tddlJT.update(sql, new Object[] { nextDay, RANDOM_ID });
Assert.assertEquals(1, rs);
executCount--;
} catch (DataAccessException ex) {
}
}
Assert.assertTrue(executCount >= 0);
}
public ResponseContext loginUser(final RequestContext request, final String username, final String password) {
Date date = new Date(System.currentTimeMillis() + 3600000);
return new ResponseContext()
.contentType(Util.getMediaType(request))
.header("X-Rate-Limit", String.valueOf(5000))
.header("X-Expires-After", date.toString())
.entity("Logged in user session: " + RandomUtils.nextLong());
}
public synchronized Node getNode() {
int cnt = healthyNodes.size();
if (cnt == 0) { //no more healthy nodes
return null;
}
int idx = RandomUtils.nextInt(cnt);
return healthyNodes.get(idx);
}
private List<NodeId> getRandomNode() {
NodeId me = clusterService.getLocalNode().id();
List<NodeId> nodes = clusterService.getNodes().stream()
.map(ControllerNode::id)
.filter(node -> !Objects.equals(node, me))
.collect(Collectors.toList());
if (nodes.isEmpty()) {
return ImmutableList.of();
}
return ImmutableList.of(nodes.get(RandomUtils.nextInt(nodes.size())));
}
/**
* Build worker node entity by IP and PORT
*/
private WorkerNodeEntity buildWorkerNode() {
WorkerNodeEntity workerNodeEntity = new WorkerNodeEntity();
if (DockerUtils.isDocker()) {
workerNodeEntity.setType(WorkerNodeType.CONTAINER.value());
workerNodeEntity.setHostName(DockerUtils.getDockerHost());
workerNodeEntity.setPort(DockerUtils.getDockerPort());
} else {
workerNodeEntity.setType(WorkerNodeType.ACTUAL.value());
workerNodeEntity.setHostName(NetUtils.getLocalAddress());
workerNodeEntity.setPort(System.currentTimeMillis() + "-" + RandomUtils.nextInt(100000));
}
return workerNodeEntity;
}
public synchronized Node getNode() {
int cnt = healthyNodes.size();
if (cnt == 0) { //no more healthy nodes
return null;
}
int idx = RandomUtils.nextInt(cnt);
return healthyNodes.get(idx);
}
private String getContactXMLChunk(String addressType,
PurchaseOrderDocument po){
String returnXML =
" <Contact addressID=\"" + RandomUtils.nextInt() + "\" role=\"" + addressType + "\"> <!-- addressId=Random Unique Id -->\n" +
" <Name xml:lang=\"en\">" + po.getDeliveryCampusCode() + " - " + po.getDeliveryBuildingName() + "</Name> <!-- Format:CampusCode - Bldg Nm -->\n" +
" <PostalAddress>\n" +
" <Street>" + StringUtils.defaultString(po.getDeliveryBuildingLine1Address()) + "</Street>\n" +
" <Street>" + StringUtils.defaultString(po.getDeliveryBuildingLine2Address()) + "</Street>\n" +
" <City>" + StringUtils.defaultString(po.getDeliveryCityName()) + "</City>\n" +
" <State>" + StringUtils.defaultString(po.getDeliveryStateCode()) + "</State>\n" +
" <PostalCode>" + StringUtils.defaultString(po.getDeliveryPostalCode()) + "</PostalCode>\n" +
" <Country isoCountryCode=\"" + StringUtils.defaultString(po.getDeliveryCountryCode()) + "\">\n" +
" " + StringUtils.defaultString(po.getDeliveryCountryName()) + "\n" +
" </Country>\n" +
" </PostalAddress>\n";
if (StringUtils.isNotEmpty(po.getDeliveryToEmailAddress())){
returnXML += " <Email name=\"" + po.getDeliveryToEmailAddress() + "\">" + po.getDeliveryToEmailAddress() + "</Email>\n";
}
if (StringUtils.isNotEmpty(po.getDeliveryToPhoneNumber())){
returnXML +=
" <Phone name=\"" + po.getDeliveryToPhoneNumber() + "\">\n" +
" <TelephoneNumber>\n" +
" <CountryCode isoCountryCode=\"US\">1</CountryCode>\n" +
" <AreaOrCityCode>" + getPhoneNumber(AREA_C0DE, po.getDeliveryToPhoneNumber()) + "</AreaOrCityCode>\n" +
" <Number>" + getPhoneNumber(PHONE_NUMBER, po.getDeliveryToPhoneNumber()) + "</Number>\n" +
" </TelephoneNumber>\n" +
" </Phone>\n";
}
returnXML += " </Contact>\n";
return returnXML;
}
/**
* 中文 -> 拼音(仅保留字母数字)
* 全英文+数字直接返回,不支持的字符会使用随机数
*
* @param text
* @return
*/
protected String toPinyinName(final String text) {
String identifier = text;
if (text.length() < 4) {
identifier = "rb" + text + RandomUtils.nextInt(10);
}
// 全英文直接返回
if (identifier.matches("[a-zA-Z0-9]+")) {
if (!CharSet.ASCII_ALPHA.contains(identifier.charAt(0))
|| BlackList.isBlack(identifier) || BlackList.isSQLKeyword(identifier)) {
identifier = "rb" + identifier;
}
return identifier;
}
identifier = HanLP.convertToPinyinString(identifier, "", false);
identifier = identifier.replaceAll("[^a-zA-Z0-9]", "");
if (StringUtils.isBlank(identifier)) {
identifier = String.valueOf(System.currentTimeMillis() / 1000);
}
char start = identifier.charAt(0);
if (!CharSet.ASCII_ALPHA.contains(start)) {
identifier = "rb" + identifier;
}
identifier = identifier.toLowerCase();
if (identifier.length() > 42) {
identifier = identifier.substring(0, 42);
}
if (!StringHelper.isIdentifier(identifier)) {
throw new ModifiyMetadataException("无效名称 : " + text);
}
return identifier;
}
/**
* @return
*/
protected static String[] createApp() {
String appId = (100000000 + RandomUtils.nextInt(899999999)) + "";
String appSecret = CodecUtils.randomCode(40);
Record record = FormDataBuilder.builder(EntityHelper.RebuildApi)
.add("appId", appId)
.add("appSecret", appSecret)
.add("bindUser", UserService.SYSTEM_USER)
.buildRecord(UserService.SYSTEM_USER);
Application.getCommonService().create(record, false);
RebuildApiManager.instance.clean(appId);
return new String[]{appId, appSecret};
}
/**
* TODO: Fix this test. It should not have a hard-coded URL for finding the schema.
*/
@ConfigureContext(session = kfs, shouldCommitTransactions=false)
public void PATCHFIX_testPaymentRequestDocumentCreation()
throws Exception{
String acceptFile = "accept.xml";
changeCurrentUser(khuntley);
RequisitionDocument reqDoc = RequisitionDocumentFixture.REQ_ONLY_REQUIRED_FIELDS.createRequisitionDocument();
AccountingDocumentTestUtils.testRouteDocument(reqDoc, SpringContext.getBean(DocumentService.class));
Integer reqId = reqDoc.getPurapDocumentIdentifier();
changeCurrentUser(kfs);
PurchaseOrderDocument poDocument = createPODoc(reqId);
String vendorDUNS = RandomUtils.nextInt() + "";
if (StringUtils.isEmpty(poDocument.getVendorDetail().getVendorDunsNumber())){
VendorDetail vd = SpringContext.getBean(VendorService.class).getByVendorNumber(poDocument.getVendorNumber());
vd.setVendorDunsNumber(vendorDUNS);
SpringContext.getBean(VendorService.class).saveVendorHeader(vd);
}else{
vendorDUNS = poDocument.getVendorDetail().getVendorDunsNumber();
}
String poNumber = poDocument.getPurapDocumentIdentifier().toString();
createItemMappingsRecords(poDocument.getVendorHeaderGeneratedIdentifier()+"", poDocument.getVendorDetailAssignedIdentifier()+"");
updateUnitPriceVariance();
String xmlChunk = ElectronicInvoiceHelperServiceFixture.getCXMLForPaymentDocCreation(vendorDUNS,poNumber);
writeXMLFile(xmlChunk, acceptFile);
ElectronicInvoiceLoad load = SpringContext.getBean(ElectronicInvoiceHelperService.class).loadElectronicInvoices();
assertFalse(load.containsRejects());
File acceptedFileInAcceptDir = new File(electronicInvoiceInputFileType.getDirectoryPath() + File.separator + "accept" + File.separator + acceptFile);
assertTrue(acceptedFileInAcceptDir.exists());
}
@HystrixCommand(fallbackMethod = "fallback")
@GetMapping
String hystrixMethod(){
if (RandomUtils.nextInt(10) > 5) {
return "Bingo!";
}
throw new RuntimeException();
}
public void test6()
{
SnapshotBuffer base=new SnapshotBuffer();
byte[] mb10=new byte[1024*1024*10];
for(int i=0;i<mb10.length;i++)
{
mb10[i]=(byte) RandomUtils.nextInt(255);
}
byte[] mb20=new byte[1024*1024*10];
for(int i=0;i<mb20.length;i++)
{
mb20[i]=(byte) RandomUtils.nextInt(255);
}
System.out.println("数据准备完毕"+mb10.length+"/"+mb20.length);
//写入耗时
long t=System.currentTimeMillis();
base.writeBytes(mb10);
long a1=System.currentTimeMillis()-t;
t=System.currentTimeMillis();
System.out.println("写入耗时:"+a1);
//快照写入耗时
SnapshotBuffer buff=base.snapshot();
buff.writeBytes(mb20);
long b1=System.currentTimeMillis()-t;
t=System.currentTimeMillis();
System.out.println("快照写入耗时:"+b1);
//读取耗时
byte[] data1=new byte[base.readableBytes()];
base.readBytes(data1);
long a2=System.currentTimeMillis()-t;
t=System.currentTimeMillis();
System.out.println("读取耗时:"+a2);
//快照读取耗时
byte[] data2=new byte[buff.readableBytes()];
buff.readBytes(data2);
long b2=System.currentTimeMillis()-t;
System.out.println("快照读取耗时:"+b2);
System.out.println(a1+","+a2+","+b1+","+b2);
}