Java Code Examples for org.apache.commons.lang.math.RandomUtils#nextInt()

The following examples show how to use org.apache.commons.lang.math.RandomUtils#nextInt() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SignUpControll.java    From rebuild with GNU General Public License v3.0 7 votes vote down vote up
@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);
}
 
Example 2
Source File: BatchInputFileServiceTest.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @see junit.framework.TestCase#setUp()
 */
@Override
protected void setUp() throws Exception {
    super.setUp();

    batchInputFileService = SpringContext.getBean(BatchInputFileService.class);
    pcdoBatchInputFileType = SpringContext.getBean(ProcurementCardInputFileType.class);
    collectorBatchInputFileType = SpringContext.getBean(CollectorXmlInputFileType.class);
    sampleBatchInputFileType = SpringContext.getBean(BatchInputFileType.class,"sampleTest2FlatFileInputFileType");

    testFileIdentifier = "junit" + RandomUtils.nextInt();
    validPCDOFileContents = BatchInputFileServiceTest.class.getClassLoader().getResourceAsStream(TEST_BATCH_XML_DIRECTORY + "BatchInputValidPCDO.xml");
    validCollectorFileContents = BatchInputFileServiceTest.class.getClassLoader().getResourceAsStream(TEST_BATCH_XML_DIRECTORY + "BatchInputValidCollector.xml");
    validSampleFileContents = BatchInputFileServiceTest.class.getClassLoader().getResourceAsStream(TEST_BATCH_XML_DIRECTORY + "BatchInputFileWithNoExtension");
    

    validWorkgroupUser = SpringContext.getBean(org.kuali.rice.kim.api.identity.PersonService.class).getPersonByPrincipalName(Data4.USER_ID2);
    invalidWorkgroupUser = SpringContext.getBean(org.kuali.rice.kim.api.identity.PersonService.class).getPersonByPrincipalName(Data4.USER_ID1);

    createdTestFiles = new ArrayList();
}
 
Example 3
Source File: NodeMap5.java    From util4j with Apache License 2.0 6 votes vote down vote up
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();
	}
 
Example 4
Source File: SampleUtils.java    From api-mining with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 5
Source File: AtomReadRestraintTest.java    From tddl with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 6
Source File: SeleniumSelect.java    From phoenix.webui.framework with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 7
Source File: SampleUtils.java    From tassal with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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;
}
 
Example 8
Source File: Node_bit4.java    From util4j with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
		byte[] data=new byte[131075];
		for(int i=0;i<data.length;i++)
		{
			data[i]=(byte) RandomUtils.nextInt(125);
		}
		Scanner sc=new Scanner(System.in);
//		sc.nextLine();
//		new Test().testMap(data);
		sc.nextLine();
		new Test().testNMap(data);
		sc.nextLine();
	}
 
Example 9
Source File: NodeMap_first.java    From util4j with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
		byte[] data=new byte[1024*1024*10];
		for(int i=0;i<data.length;i++)
		{
			data[i]=(byte) RandomUtils.nextInt(255);
		}
		System.out.println(data.length);
		System.out.println(Integer.toHexString(data.length));
		Scanner sc=new Scanner(System.in);
//		sc.nextLine();
//		new Test().testMap(data);
		sc.nextLine();
		new Test().testNMap(data);
		sc.nextLine();
	}
 
Example 10
Source File: HystrixController.java    From Spring-Boot-Examples with MIT License 5 votes vote down vote up
@HystrixCommand(fallbackMethod = "fallback")
@GetMapping
String hystrixMethod(){
    if (RandomUtils.nextInt(10) > 5) {
        return "Bingo!";
    }
    throw new RuntimeException();
}
 
Example 11
Source File: HystrixSecondController.java    From Spring-Boot-Examples with MIT License 5 votes vote down vote up
@HystrixCommand(fallbackMethod = "fallback")
@GetMapping
String hystrixSecondMethod(){
    if (RandomUtils.nextInt(10) > 5) {
        return "Bingo!";
    }
    throw new RuntimeException();
}
 
Example 12
Source File: StylishEval.java    From naturalize with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void runSingleExperiment() throws IOException {
	final BaseIdentifierRenamings idRenamer = new BaseIdentifierRenamings(
			tokenizer);
	final FormattingRenamings formattingRenaming = new FormattingRenamings();
	final List<File> selectedFiles = buildRenamersAndGetTargetMethods(
			idRenamer, formattingRenaming);

	final List<String> allToks = Lists.newArrayList(idRenamer.getLM()
			.getTrie().getVocabulary());
	Collections.shuffle(allToks);
	for (final File f : selectedFiles) {
		try {
			for (final Entry<String, MethodDeclaration> method : MethodRetriever
					.getMethodNodes(f).entrySet()) {
				final Collection<String> snippetIdentifiers = scopeExtractor
						.getFromNode(method.getValue()).values();
				final String toRename;
				if (!snippetIdentifiers.isEmpty()) {
					toRename = (String) snippetIdentifiers.toArray()[RandomUtils
							.nextInt(snippetIdentifiers.size())];
				} else {
					continue;
				}
				evaluatePerformanceOn(method.getValue(),
						FileUtils.readFileToString(f), idRenamer,
						formattingRenaming, toRename);
			}
		} catch (Throwable e) {
			LOGGER.warning(ExceptionUtils.getFullStackTrace(e));
		}

	}

}
 
Example 13
Source File: Task.java    From util4j with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
	long time=RandomUtils.nextInt(5000);
	try {
		Thread.sleep(time);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	log.debug("name="+name+",sleep="+time);
}
 
Example 14
Source File: SampleUtilsTest.java    From api-mining with GNU General Public License v3.0 5 votes vote down vote up
/**
 * This test may be flakey, due to its probabilistic nature.
 */
@Test
public void testRandomPartitionAvgBehavior() {
	// Check a random sample of 100 randomly created partitions and elements
	// that are statistically "ok".
	for (int i = 0; i < 100; i++) {
		final Map<Integer, Double> partitionWeights = Maps.newHashMap();
		final Map<Integer, Double> elementWeights = Maps.newHashMap();

		final int nPartitions = RandomUtils.nextInt(99) + 1;
		final int nElements = RandomUtils.nextInt(1000) + 5000;

		for (int partition = 0; partition < nPartitions; partition++) {
			partitionWeights.put(partition, RandomUtils.nextDouble());
		}
		for (int element = 0; element < nElements; element++) {
			elementWeights.put(element, RandomUtils.nextDouble());
		}

		final Multimap<Integer, Integer> partitions = SampleUtils
				.randomPartition(elementWeights, partitionWeights);
		final double partitionsTotalSum = StatsUtil.sum(partitionWeights
				.values());

		double sumDifference = 0;
		for (final int partitionId : partitions.keySet()) {
			final int partitionSize = partitions.get(partitionId).size();
			final double expectedPartitionPct = partitionWeights
					.get(partitionId) / partitionsTotalSum;
			final double actualPartitionPct = ((double) partitionSize)
					/ nElements;
			sumDifference += Math.abs(expectedPartitionPct
					- actualPartitionPct);
		}

		// On average we are not off by 1%
		assertEquals(sumDifference / partitions.keySet().size(), 0, 1E-2);

	}
}
 
Example 15
Source File: TableScanOperation_LargeRegionCount_IT.java    From spliceengine with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
public void selectFromMultipleRegions() throws Exception {
    final int ROW_COUNT = 1000 + RandomUtils.nextInt(1000);
    final int SPLIT_COUNT = 1 + RandomUtils.nextInt(33); // this line largely determines how long this test takes
    final String TABLE_NAME = "REGIONS";

    System.out.println("-------------------------------------------------------");
    System.out.println("SPLIT_COUNT=" + SPLIT_COUNT + " ROW_COUNT=" + ROW_COUNT);
    System.out.println("-------------------------------------------------------");

    //
    // After table creation HBaseRegionCache has cached a map of this tables conglomerateId to HRegionInfo
    // for one region.
    //
    new TableCreator(methodWatcher.getOrCreateConnection())
            .withCreate("create table %s (a int)")
            .withInsert("insert into %s values(?)")
            .withRows(new IntegerRows(ROW_COUNT, 1))
            .withTableName(TABLE_NAME)
            .create();

    //
    // Split split split
    //
    long conglomId = methodWatcher.getConglomId(TABLE_NAME, SCHEMA_NAME);
    splitTable(conglomId, SPLIT_COUNT);

    //
    // Sleep until we are sure the HBaseRegionCache has been updated to reflect the splits.  In production
    // our scans would just be serial until the HBaseRegionCache gets updated.  For manual testing I set the cache
    // refresh period to 1 second.
    //
    Thread.sleep(2000);


    //
    // select the entire table
    //
    List<Integer> actualTableContent = methodWatcher.queryList("select a from " + TABLE_NAME);
    assertListContainsRange(actualTableContent, ROW_COUNT, 0, ROW_COUNT - 1);

    //
    // select with restrictions
    //
    actualTableContent = methodWatcher.queryList("select a from " + TABLE_NAME + " where a >= 100 and a <= " + (ROW_COUNT - 101));
    assertListContainsRange(actualTableContent, ROW_COUNT - 200, 100, ROW_COUNT - 101);
}
 
Example 16
Source File: SignUpControll.java    From rebuild with GNU General Public License v3.0 4 votes vote down vote up
@RequestMapping("captcha")
public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
	Font font = new Font(Font.SERIF, Font.BOLD & Font.ITALIC, 22 + RandomUtils.nextInt(8));
	int codeLen = 4 + RandomUtils.nextInt(3);
	CaptchaUtil.out(160, 41, codeLen, font, request, response);
}
 
Example 17
Source File: Randoms.java    From mango with Apache License 2.0 4 votes vote down vote up
public static int randomInt(int n) {
  return RandomUtils.nextInt(n);
}
 
Example 18
Source File: TestOrcStoragePushdown.java    From spork with Apache License 2.0 4 votes vote down vote up
private static void createInputData() throws Exception {
    pigServer = new PigServer(ExecType.LOCAL);

    new File(inpbasedir).mkdirs();
    new File(outbasedir).mkdirs();
    String inputTxtFile = inpbasedir + File.separator + "input.txt";
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(inputTxtFile), "UTF-8"));
    long[] lVal = new long[] {100L, 200L, 300L};
    float[] fVal = new float[] {50.0f, 100.0f, 200.0f, 300.0f};
    double[] dVal = new double[] {1000.11, 2000.22, 3000.33};
    StringBuilder sb = new StringBuilder();
    for (int i=1; i <= 10000; i++) {
        sb.append((i > 6500 && i <= 9000) ? true : false).append("\t"); //boolean
        sb.append((i > 1000 && i < 3000) ? 1 : 5).append("\t"); //byte
        sb.append((i > 2500 && i <= 4500) ? 100 : 200).append("\t"); //short
        sb.append(i).append("\t"); //int
        sb.append(lVal[i%3]).append("\t"); //long
        sb.append(fVal[i%4]).append("\t"); //float
        sb.append((i > 2500 && i < 3500) ? dVal[i%3] : dVal[i%1]).append("\t"); //double
        sb.append((i%2 == 1 ? "" : RandomStringUtils.random(100).replaceAll("\t", " ")
                .replaceAll("\n", " ").replaceAll("\r", " "))).append("\t"); //bytearray
        sb.append((i%2 == 0 ? "" : RandomStringUtils.random(100).replaceAll("\t", " ")
                .replaceAll("\n", " ").replaceAll("\r", " "))).append("\t"); //string
        int year;
        if (i > 5000 && i <= 8000) { //datetime
            year = RandomUtils.nextInt(4)+2010;
        } else {
            year = RandomUtils.nextInt(10)+2000;
        }
        sb.append(new DateTime(year, RandomUtils.nextInt(12)+1,
                RandomUtils.nextInt(28)+1, RandomUtils.nextInt(24), RandomUtils.nextInt(60),
                DateTimeZone.UTC).toString()).append("\t"); // datetime
        String bigString;
        if (i>7500) {
            bigString = RandomStringUtils.randomNumeric(9) + "." + RandomStringUtils.randomNumeric(5);
        } else {
            bigString = "1" + RandomStringUtils.randomNumeric(9) + "." + RandomStringUtils.randomNumeric(5);
        }
        sb.append(new BigDecimal(bigString)).append("\n"); //bigdecimal
        bw.write(sb.toString());
        sb.setLength(0);
    }
    bw.close();

    // Store only 1000 rows in each row block (MIN_ROW_INDEX_STRIDE is 1000. So can't use less than that)
    pigServer.registerQuery("A = load '" + Util.generateURI(inputTxtFile, pigServer.getPigContext()) + "' as (f1:boolean, f2:int, f3:int, f4:int, f5:long, f6:float, f7:double, f8:bytearray, f9:chararray, f10:datetime, f11:bigdecimal);");
    pigServer.registerQuery("store A into '" + Util.generateURI(INPUT, pigServer.getPigContext()) +"' using OrcStorage('-r 1000 -s 100000');");
    Util.copyFromLocalToCluster(cluster, INPUT, INPUT);
}
 
Example 19
Source File: CarreraDataInspection.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
private void sendMessage() {
    if (producer == null) {
        LOGGER.error("[INVALID_PRODUCER],broker={}, producer is null", broker);
        return;
    }

    rateLimiter.acquire();

    String topic = clusterConfig.getTopic();
    int bodyLen = RandomUtils.nextInt(clusterConfig.getMaxBodyLen()) + 1;
    byte[] body = org.apache.commons.lang3.RandomUtils.nextBytes(bodyLen);

    int keyLen = RandomUtils.nextInt(clusterConfig.getMaxKeyLen()) + 8;
    String key = TimeUtils.getCurTime() + "_" + RandomStringUtils.randomAlphanumeric(keyLen);

    int tagLen = RandomUtils.nextInt(clusterConfig.getMaxTagLen()) + 1;
    String tag = tagLen > 0 ? RandomStringUtils.randomAlphabetic(tagLen) : null;

    com.xiaojukeji.carrera.thrift.Message message = CarreraProducer.buildMessage(topic, -2/* random */, TimeUtils.getCurTime(), body, key, tag);
    messageMap.put(key, message);

    while (true) {
        if (producer == null) {
            LOGGER.error("[INVALID_PRODUCER],broker={}, producer is null", broker);
            return;
        }
        long curTime = TimeUtils.getCurTime();
        Result ret = producer.sendMessage(message);

        if (ret.code == CarreraReturnCode.OK) {
            LOGGER.info("SendMessage success, broker={}, ret={}, cnt={}, sendCost={}", broker, ret, msgCnt.incrementAndGet(), TimeUtils.getElapseTime(curTime));
            return;
        } else if (ret.code == CarreraReturnCode.FAIL_TOPIC_NOT_ALLOWED || ret.code == CarreraReturnCode.FAIL_TOPIC_NOT_EXIST) {
            LOGGER.info("SendMessage failed, broker={}, ret={}, cnt={}", broker, ret, msgCnt.incrementAndGet());
            try {
                Thread.sleep(60000L);
            } catch (InterruptedException e) {
                LOGGER.error("Thread.sleep exception", e);
            }
        } else {
            LOGGER.error("SendMessage failed, broker={}, ret={}", broker, ret);
        }
    }
}
 
Example 20
Source File: XPathTest.java    From spork with Apache License 2.0 3 votes vote down vote up
private String expandXml() {
    
    final StringBuilder sb = new StringBuilder();
    
    final int max = RandomUtils.nextInt(100);
    
    for(int i = 0; i < max; i++) {
        sb.append("<expansion>This is an expansion of the xml to simulate random sized xml" + i + "</expansion>"); 
    }
    
    return sb.toString();
}