List of usage examples for org.apache.commons.lang RandomStringUtils randomAlphabetic
public static String randomAlphabetic(int count)
Creates a random string whose length is the number of characters specified.
Characters will be chosen from the set of alphabetic characters.
From source file:com.alibaba.otter.node.etl.common.db.DbPerfIntergration.java
@Test public void test_stack() { DbMediaSource dbMediaSource = new DbMediaSource(); dbMediaSource.setId(1L);/*w ww. j a v a 2 s . co m*/ dbMediaSource.setDriver("com.mysql.jdbc.Driver"); dbMediaSource.setUsername("otter"); dbMediaSource.setPassword("otter"); dbMediaSource.setUrl("jdbc:mysql://127.0.0.1:3306/retl"); dbMediaSource.setEncode("UTF-8"); dbMediaSource.setType(DataMediaType.MYSQL); DbDataMedia dataMedia = new DbDataMedia(); dataMedia.setSource(dbMediaSource); dataMedia.setId(1L); dataMedia.setName("ljhtable1"); dataMedia.setNamespace("otter"); final DbDialect dbDialect = dbDialectFactory.getDbDialect(2L, dataMedia.getSource()); want.object(dbDialect).clazIs(MysqlDialect.class); final TransactionTemplate transactionTemplate = dbDialect.getTransactionTemplate(); // ?? int minute = 5; int nextId = 1; final int thread = 10; final int batch = 50; final String sql = "insert into otter.ljhtable1 values(? , ? , ? , ?)"; final CountDownLatch latch = new CountDownLatch(thread); ExecutorService executor = new ThreadPoolExecutor(thread, thread, 60, TimeUnit.SECONDS, new ArrayBlockingQueue(thread * 2), new NamedThreadFactory("load"), new ThreadPoolExecutor.CallerRunsPolicy()); for (int sec = 0; sec < minute * 60; sec++) { // long startTime = System.currentTimeMillis(); for (int i = 0; i < thread; i++) { final int start = nextId + i * batch; executor.submit(new Runnable() { public void run() { try { transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { JdbcTemplate jdbcTemplate = dbDialect.getJdbcTemplate(); return jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() { public void setValues(PreparedStatement ps, int idx) throws SQLException { int id = start + idx; StatementCreatorUtils.setParameterValue(ps, 1, Types.INTEGER, null, id); StatementCreatorUtils.setParameterValue(ps, 2, Types.VARCHAR, null, RandomStringUtils.randomAlphabetic(1000)); // RandomStringUtils.randomAlphabetic() long time = new Date().getTime(); StatementCreatorUtils.setParameterValue(ps, 3, Types.TIMESTAMP, new Timestamp(time)); StatementCreatorUtils.setParameterValue(ps, 4, Types.TIMESTAMP, new Timestamp(time)); } public int getBatchSize() { return batch; } }); } }); } finally { latch.countDown(); } } }); } long endTime = System.currentTimeMillis(); try { latch.await(1000 * 60L - (endTime - startTime), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } if (latch.getCount() != 0) { System.out.println("perf is not enough!"); System.exit(-1); } endTime = System.currentTimeMillis(); System.out.println("Time cost : " + (System.currentTimeMillis() - startTime)); try { TimeUnit.MILLISECONDS.sleep(1000L - (endTime - startTime)); } catch (InterruptedException e) { e.printStackTrace(); } nextId = nextId + thread * batch; } executor.shutdown(); }
From source file:com.magnet.mmx.server.plugin.mmxmgmt.api.user.MMXUsersResourceTest.java
public static AppEntity createRandomApp() throws Exception { String serverUserId = "serverUser"; String appName = "usersresourcetestapp"; String appId = RandomStringUtils.randomAlphanumeric(10); String apiKey = UUID.randomUUID().toString(); String googleApiKey = UUID.randomUUID().toString(); String googleProjectId = RandomStringUtils.randomAlphanumeric(8); String apnsPwd = RandomStringUtils.randomAlphanumeric(10); String ownerId = RandomStringUtils.randomAlphabetic(10); String ownerEmail = RandomStringUtils.randomAlphabetic(4) + "@magnet.com"; String guestSecret = RandomStringUtils.randomAlphabetic(10); boolean apnsProductionEnvironment = false; AppEntity appEntity = new AppEntity(); appEntity.setServerUserId(serverUserId); appEntity.setName(appName);//w w w . ja va 2s .c o m appEntity.setAppId(appId); appEntity.setAppAPIKey(apiKey); appEntity.setGoogleAPIKey(googleApiKey); appEntity.setGoogleProjectId(googleProjectId); appEntity.setApnsCertPassword(apnsPwd); appEntity.setOwnerId(ownerId); appEntity.setOwnerEmail(ownerEmail); appEntity.setGuestSecret(guestSecret); appEntity.setApnsCertProduction(apnsProductionEnvironment); DBTestUtil.getAppDAO().persist(appEntity); return appEntity; }
From source file:com.magnet.mmx.server.plugin.mmxmgmt.api.tags.MMXDeviceTagsResourceTest.java
private static DeviceEntity createRandomDeviceEntity(AppEntity appEntity, int index) { DeviceEntity deviceEntity = new DeviceEntity(); deviceEntity.setAppId(appEntity.getAppId()); deviceEntity.setName(RandomStringUtils.randomAlphabetic(5) + " " + RandomStringUtils.randomAlphabetic(5)); deviceEntity.setOsType(OSType.ANDROID); deviceEntity.setCreated(new Date()); deviceEntity.setOwnerId(appEntity.getOwnerId()); deviceEntity.setStatus(DeviceStatus.ACTIVE); deviceEntity.setDeviceId("mmxdevicetagsresourcetestdevice" + "_" + index); deviceEntity.setPhoneNumber("+213" + RandomStringUtils.randomNumeric(7)); deviceEntity.setPhoneNumberRev(StringUtils.reverse(deviceEntity.getPhoneNumber())); DBTestUtil.getDeviceDAO().persist(deviceEntity); return deviceEntity; }
From source file:eu.scape_project.spacip.ContainerProcessing.java
/** * Prepare input//from w ww . j a v a 2 s .c o m * * @param pt * @throws IOException IO Error * @throws java.lang.InterruptedException */ public void prepareInput(Path pt) throws InterruptedException, IOException { FileSystem fs = FileSystem.get(context.getConfiguration()); InputStream containerFileStream = fs.open(pt); String containerFileName = pt.getName(); ArchiveReader reader = ArchiveReaderFactory.get(containerFileName, containerFileStream, true); long currTM = System.currentTimeMillis(); String unpackHdfsPath = conf.get("unpack_hdfs_path", "spacip_unpacked"); String hdfsUnpackDirStr = StringUtils.normdir(unpackHdfsPath, Long.toString(currTM)); String hdfsJoboutputPath = conf.get("tooloutput_hdfs_path", "spacip_tooloutput"); String hdfsOutputDirStr = StringUtils.normdir(hdfsJoboutputPath, Long.toString(currTM)); Iterator<ArchiveRecord> recordIterator = reader.iterator(); recordIterator.next(); // skip filedesc record (arc filedesc) // Number of files which should be processed per invokation int numItemsPerInvocation = conf.getInt("num_items_per_task", 50); int numItemCounter = numItemsPerInvocation; // List of input files to be processed String inliststr = ""; // List of output files to be generated String outliststr = ""; try { while (recordIterator.hasNext()) { ArchiveRecord nativeArchiveRecord = recordIterator.next(); String recordKey = getRecordKey(nativeArchiveRecord); String outFileName = RandomStringUtils.randomAlphabetic(25); String hdfsPathStr = hdfsUnpackDirStr + outFileName; Path hdfsPath = new Path(hdfsPathStr); String outputFileSuffix = conf.get("output_file_suffix", ".fits.xml"); String hdfsOutPathStr = hdfsOutputDirStr + outFileName + outputFileSuffix; FSDataOutputStream hdfsOutStream = fs.create(hdfsPath); ContainerProcessing.recordToOutputStream(nativeArchiveRecord, hdfsOutStream); Text key = new Text(recordKey); Text value = new Text(fs.getHomeDirectory() + File.separator + hdfsOutPathStr); mos.write("keyfilmapping", key, value); String scapePlatformInvoke = conf.get("scape_platform_invoke", "fits dirxml"); Text ptmrkey = new Text(scapePlatformInvoke); // for the configured number of items per invokation, add the // files to the input and output list of the command. inliststr += "," + fs.getHomeDirectory() + File.separator + hdfsPathStr; outliststr += "," + fs.getHomeDirectory() + File.separator + hdfsOutPathStr; if (numItemCounter > 1 && recordIterator.hasNext()) { numItemCounter--; } else if (numItemCounter == 1 || !recordIterator.hasNext()) { inliststr = inliststr.substring(1); // cut off leading comma outliststr = outliststr.substring(1); // cut off leading comma String pattern = conf.get("tomar_param_pattern", "%1$s %2$s"); String ptMrStr = StringUtils.formatCommandOutput(pattern, inliststr, outliststr); Text ptmrvalue = new Text(ptMrStr); // emit tomar input line where the key is the tool invokation // (tool + operation) and the value is the parameter list // where input and output strings contain file lists. mos.write("tomarinput", ptmrkey, ptmrvalue); numItemCounter = numItemsPerInvocation; inliststr = ""; outliststr = ""; } } } catch (Exception ex) { mos.write("error", new Text("Error"), new Text(pt.toString())); } }
From source file:io.pravega.test.system.ControllerFailoverTest.java
@Test(timeout = 180000) public void failoverTest() throws URISyntaxException, InterruptedException { String scope = "testFailoverScope" + RandomStringUtils.randomAlphabetic(5); String stream = "testFailoverStream" + RandomStringUtils.randomAlphabetic(5); int initialSegments = 2; List<Integer> segmentsToSeal = Collections.singletonList(0); Map<Double, Double> newRangesToCreate = new HashMap<>(); newRangesToCreate.put(0.0, 0.25);/*from w w w . j a va 2 s . c om*/ newRangesToCreate.put(0.25, 0.5); long lease = 29000; long maxExecutionTime = 60000; long scaleGracePeriod = 30000; // Connect with first controller instance. URI controllerUri = getTestControllerServiceURI(); Controller controller = new ControllerImpl(controllerUri); // Create scope, stream, and a transaction with high timeout value. controller.createScope(scope).join(); log.info("Scope {} created successfully", scope); createStream(controller, scope, stream, ScalingPolicy.fixed(initialSegments)); log.info("Stream {}/{} created successfully", scope, stream); long txnCreationTimestamp = System.nanoTime(); TxnSegments txnSegments = controller .createTransaction(new StreamImpl(scope, stream), lease, maxExecutionTime, scaleGracePeriod).join(); log.info("Transaction {} created successfully, beginTime={}", txnSegments.getTxnId(), txnCreationTimestamp); // Initiate scale operation. It will block until ongoing transaction is complete. CompletableFuture<Boolean> scaleFuture = controller .scaleStream(new StreamImpl(scope, stream), segmentsToSeal, newRangesToCreate, EXECUTOR_SERVICE) .getFuture(); // Ensure that scale is not yet done. log.info("Status of scale operation isDone={}", scaleFuture.isDone()); Assert.assertTrue(!scaleFuture.isDone()); // Now stop the controller instance executing scale operation. stopTestControllerService(); log.info("Successfully stopped test controller service"); // Connect to another controller instance. controllerUri = getControllerURI(); controller = new ControllerImpl(controllerUri); // Fetch status of transaction. log.info("Fetching status of transaction {}, time elapsed since its creation={}", txnSegments.getTxnId(), System.nanoTime() - txnCreationTimestamp); Transaction.Status status = controller .checkTransactionStatus(new StreamImpl(scope, stream), txnSegments.getTxnId()).join(); log.info("Transaction {} status={}", txnSegments.getTxnId(), status); if (status == Transaction.Status.OPEN) { // Abort the ongoing transaction. log.info("Trying to abort transaction {}, by sending request to controller at {}", txnSegments.getTxnId(), controllerUri); controller.abortTransaction(new StreamImpl(scope, stream), txnSegments.getTxnId()).join(); } // Scale operation should now complete on the second controller instance. // Sleep for some time for it to complete Thread.sleep(90000); // Ensure that the stream has 3 segments now. log.info("Checking whether scale operation succeeded by fetching current segments"); StreamSegments streamSegments = controller.getCurrentSegments(scope, stream).join(); log.info("Current segment count=", streamSegments.getSegments().size()); Assert.assertEquals(initialSegments - segmentsToSeal.size() + newRangesToCreate.size(), streamSegments.getSegments().size()); }
From source file:edu.sampleu.kim.api.identity.IdentityPersonCreateNewAftBase.java
public void testIdentityPersonCreateNew() throws Exception { selectFrameIframePortlet();// ww w .ja va 2s .c o m waitAndClickByXpath(CREATE_NEW_XPATH); waitAndTypeByName("document.documentHeader.documentDescription", "Test description of person"); selectByName("newAffln.affiliationTypeCode", "Staff"); selectByName("newAffln.campusCode", "BL - BLOOMINGTON"); waitAndClickByName("newAffln.dflt"); waitAndClickByName("methodToCall.addAffln.anchor"); waitAndTypeByName("document.affiliations[0].newEmpInfo.employeeId", "9999999999"); waitAndClickByName("document.affiliations[0].newEmpInfo.primary"); selectByName("document.affiliations[0].newEmpInfo.employmentStatusCode", "Active"); selectByName("document.affiliations[0].newEmpInfo.employmentTypeCode", "Professional"); waitAndTypeByName("document.affiliations[0].newEmpInfo.baseSalaryAmount", "99999"); waitAndTypeByXpath("//*[@id='document.affiliations[0].newEmpInfo.primaryDepartmentCode']", "BL-BUS"); waitAndClickByName("methodToCall.addEmpInfo.line0.anchor"); waitAndClickByName("methodToCall.showAllTabs"); selectByName("newName.nameCode", "Primary"); waitAndTypeByName("newName.firstName", "Marco"); waitAndTypeByName("newName.lastName", "Simoncelli"); waitAndClickByName("newName.dflt"); waitAndClickByName("methodToCall.addName.anchor"); selectByName("newAddress.addressTypeCode", "Work"); waitAndTypeByName("newAddress.line1", "123 Address Ln"); waitAndTypeByName("newAddress.city", "Bloomington"); selectByName("newAddress.stateProvinceCode", "INDIANA"); waitAndTypeByName("newAddress.postalCode", "47408"); selectByName("newAddress.countryCode", "United States"); waitAndClickByName("newAddress.dflt"); waitAndClickByName("methodToCall.addAddress.anchor"); selectByName("newPhone.phoneTypeCode", "Work"); waitAndTypeByName("newPhone.phoneNumber", "855-555-5555"); selectByName("newPhone.countryCode", "United States"); waitAndClickByName("newPhone.dflt"); waitAndClickByName("methodToCall.addPhone.anchor"); waitAndTypeByName("newEmail.emailAddress", "email@provider.net"); selectByName("newEmail.emailTypeCode", "Work"); waitAndClickByName("newEmail.dflt"); waitAndClickByName("methodToCall.addEmail.anchor"); waitAndTypeByName("document.principalName", RandomStringUtils.randomAlphabetic(12).toLowerCase()); //Expand All , Submit , Close and Don't Save. waitAndClickByName("methodToCall.route"); checkForDocError(); // assertTextPresent("Document was successfully submitted."); waitAndClickByName("methodToCall.close"); // waitAndClickByName("methodToCall.processAnswer.button1"); }
From source file:io.sidecar.event.EventTest.java
@Test(description = "A key tag can't be over 40 characters", expectedExceptions = IllegalArgumentException.class) public void singleKeyTagCantHaveOver40Chars() { createBuilderWithExpectedValues()/*w ww .jav a 2 s .co m*/ .keytags(newArrayList(new KeyTag(RandomStringUtils.randomAlphabetic(41), Sets.newHashSet("foo")))) .build(); }
From source file:edu.sampleu.admin.CampusActionListAftBase.java
private void reattemptPrimaryKey() throws InterruptedException { int attempts = 0; while (isTextPresent("a record with the same primary key already exists.") && ++attempts <= 10) { jGrowl("record with the same primary key already exists trying another, attempt: " + attempts); clearTextByName("document.newMaintainableObject.code"); // primary key String randomNumbeForCode = RandomStringUtils.randomNumeric(1); String randomAlphabeticForCode = RandomStringUtils.randomAlphabetic(1); jiraAwareTypeByName("document.newMaintainableObject.code", randomNumbeForCode + randomAlphabeticForCode); waitAndClickByName("methodToCall.route"); waitForProgress("Submitting..."); }// w w w . ja va 2 s .c om }
From source file:com.magnet.mmx.server.plugin.mmxmgmt.api.tags.MMXUserTagsResourceTest.java
private static TestUserDao.UserEntity createRandomUser(AppEntity appEntity, int index) throws Exception { TestUserDao.UserEntity ue = new TestUserDao.UserEntity(); ue.setEmail(RandomStringUtils.randomAlphabetic(5) + "@" + RandomStringUtils.randomAlphabetic(8) + ".com"); ue.setName(RandomStringUtils.randomAlphabetic(5) + " " + RandomStringUtils.randomAlphabetic(5)); ue.setPlainPassword(RandomStringUtils.randomAlphabetic(10)); ue.setEncryptedPassword(RandomStringUtils.randomAlphabetic(80)); ue.setCreationDate(org.jivesoftware.util.StringUtils.dateToMillis(new Date())); ue.setModificationDate(org.jivesoftware.util.StringUtils.dateToMillis(new Date())); ue.setUsername("MMXUserTagsResourceTestUser" + "_" + index + "%" + appEntity.getAppId()); ue.setUsernameNoAppId("MMXUserTagsResourceTestUser" + "_" + index); DBTestUtil.getTestUserDao().persist(ue); return ue;//w w w . j a v a 2s . com }
From source file:com.haulmont.restapi.service.filter.RestFilterParserTest.java
@Test public void testEnumCondition() throws Exception { new StrictExpectations() { {//from w w w .j a v a2s.c o m RandomStringUtils.randomAlphabetic(anyInt); result = "paramName1"; } }; String data = readDataFromFile("data/restFilter4.json"); MetaClass metaClass = metadata.getClass("test$TestEntity"); RestFilterParseResult parseResult = restFilterParser.parse(data, metaClass); String expectedJpqlWhere = "({E}.enumField = :paramName1)"; assertEquals(expectedJpqlWhere, parseResult.getJpqlWhere()); Map<String, Object> queryParameters = parseResult.getQueryParameters(); assertEquals(TestEnum.ENUM_VALUE_1, queryParameters.get("paramName1")); }