List of usage examples for org.apache.commons.lang RandomStringUtils randomAlphanumeric
public static String randomAlphanumeric(int count)
Creates a random string whose length is the number of characters specified.
Characters will be chosen from the set of alpha-numeric characters.
From source file:com.xtructure.xutil.valid.UTestValidateUtils.java
public void assertThatWithMultiplePredicatesBehavesAsExpected() { String assertionName = RandomStringUtils.randomAlphanumeric(10); boolean valid = assertThat(assertionName, new Object(), isNotNull(), isNotNull()); if (!valid) { throw new AssertionError(); }/*from w ww . j a v a 2s.co m*/ try { assertThat(assertionName, null, isNotNull(), isNotNull()); } catch (AssertionError e) { if (!String.format("%s (%s): %s", assertionName, null, isNotNull()).equals(e.getMessage())) { throw new AssertionError(); } } }
From source file:com.xtructure.xutil.valid.UTestValidateUtils.java
public void assertThatWithValidationStrategyBehavesAsExpected() { String assertionName = RandomStringUtils.randomAlphanumeric(10); TestValidationStrategy<Object> validationStrategy = new TestValidationStrategy<Object>(isNotNull()); boolean valid = assertThat(assertionName, new Object(), validationStrategy); if (!valid) { throw new AssertionError(); }/*from ww w . j ava2 s . c o m*/ try { assertThat(assertionName, null, validationStrategy); } catch (AssertionError e) { if (!String.format("%s (%s): %s", assertionName, null, isNotNull()).equals(e.getMessage())) { throw new AssertionError(); } } }
From source file:com.flexive.tests.embedded.MandatorTest.java
/** * Test active/inactive mandators concerning login * * @throws Exception on errors//w w w . j a va 2s . c o m */ public void activeLogin() throws Exception { String name = "USR_" + RandomStringUtils.randomAlphanumeric(10); String pwd = RandomStringUtils.randomAlphanumeric(10); final AccountEdit account = new AccountEdit().setName(name).setLoginName(name).setEmail("test@flexive.org") .setMandatorId(testMandator); long accountId = EJBLookup.getAccountEngine().create(account, pwd); try { me.activate(testMandator); logout(); //check if login/logout works while active login(name, pwd); logout(); login(TestUsers.SUPERVISOR); me.deactivate(testMandator); try { EJBLookup.getAccountEngine().login(name, pwd, false); Assert.fail("Expected an account of a deactivated mandator to not be able to log in."); } catch (FxLoginFailedException e) { //expected } logout(); login(TestUsers.SUPERVISOR); me.activate(testMandator); //check if login/logout works again login(name, pwd); logout(); } finally { login(TestUsers.SUPERVISOR); EJBLookup.getAccountEngine().remove(accountId); } }
From source file:com.magnet.mmx.server.plugin.mmxmgmt.servlet.MMXUserResourceTest.java
private MMXUserInfo getUserInfo(boolean isAdmin) { MMXUserInfo userInfo = new MMXUserInfo(); userInfo.setAppId(RandomStringUtils.randomAlphabetic(10)); userInfo.setEmail(RandomStringUtils.randomAlphabetic(5) + "@magnet.com"); userInfo.setName(RandomStringUtils.randomAlphabetic(5) + " " + RandomStringUtils.randomAlphabetic(5)); userInfo.setUsername(RandomStringUtils.randomAlphabetic(10)); userInfo.setPassword(RandomStringUtils.randomAlphanumeric(4 + RandomUtils.nextInt(6))); userInfo.setIsAdmin(isAdmin);/* w w w . jav a 2 s. c o m*/ return userInfo; }
From source file:com.google.cloud.bigtable.hbase.TestPut.java
@Test public void testPutSameTimestamp() throws Exception { byte[] rowKey = Bytes.toBytes("testrow-" + RandomStringUtils.randomAlphanumeric(8)); byte[] qualifier = Bytes.toBytes("testqual-" + RandomStringUtils.randomAlphanumeric(8)); byte[] value1 = Bytes.toBytes("testvalue-" + RandomStringUtils.randomAlphanumeric(8)); byte[] value2 = Bytes.toBytes("testvalue-" + RandomStringUtils.randomAlphanumeric(8)); long timestamp = System.currentTimeMillis(); Table table = getConnection().getTable(TABLE_NAME); Put put = new Put(rowKey); put.addColumn(COLUMN_FAMILY, qualifier, timestamp, value1); table.put(put);/*from w w w .j ava2 s . com*/ put = new Put(rowKey); put.addColumn(COLUMN_FAMILY, qualifier, timestamp, value2); table.put(put); Get get = new Get(rowKey); get.addColumn(COLUMN_FAMILY, qualifier); get.setMaxVersions(5); Result result = table.get(get); Assert.assertEquals(1, result.size()); Assert.assertTrue(result.containsColumn(COLUMN_FAMILY, qualifier)); Assert.assertEquals(timestamp, result.getColumnLatestCell(COLUMN_FAMILY, qualifier).getTimestamp()); Assert.assertArrayEquals(value2, CellUtil.cloneValue(result.getColumnLatestCell(COLUMN_FAMILY, qualifier))); table.close(); }
From source file:edu.duke.cabig.c3pr.webservice.integration.StudyUtilityWebServiceTest.java
private void executeQueryStudyRegistryStatusTest() throws SecurityExceptionFaultMessage, StudyUtilityFaultMessage { StudyUtility service = getService(); // return study status QueryStudyRegistryStatusRequest request = new QueryStudyRegistryStatusRequest(); final DocumentIdentifier studyId = createStudyPrimaryIdentifier(); request.setStudyIdentifier(studyId); List<PermissibleStudySubjectRegistryStatus> list = service.queryStudyRegistryStatus(request).getStatuses() .getItem();// w ww . j a v a 2 s . co m assertEquals(1, list.size()); assertEquals(STATUS_ACTIVE, list.get(0).getRegistryStatus().getCode().getCode()); // study does not exist. studyId.getIdentifier().setExtension(RandomStringUtils.randomAlphanumeric(32)); try { service.queryStudyRegistryStatus(request); fail(); } catch (StudyUtilityFaultMessage e) { logger.info("Unexistent study creation passed."); } }
From source file:gov.nih.nci.cabig.caaers.service.ProxyWebServiceFacade.java
public List<Study> searchStudies(String searchText) { List<Study> studyList = new ArrayList<Study>(); if (StringUtils.isNotEmpty(searchText)) { try {/*from ww w .ja v a 2s . c o m*/ //invoke the webservice Map<String, String> criteriaMap = new HashMap<String, String>(); criteriaMap.put("documentTitle", searchText); criteriaMap.put("nciDocumentNumber", searchText); criteriaMap.put("localDocumentNumber", searchText); String correlationId = RandomStringUtils.randomAlphanumeric(15); String message = buildMessage(correlationId, "adeers", SEARCH_STUDY_ENTITY_NAME, SEARCH_STUDY_OPERATION_NAME, "sync", criteriaMap); String xmlSearchResult = simpleSendAndReceive(message); // Added the line to fix CAAERS-5799 issue xmlSearchResult = xmlSearchResult.replaceAll("encoding=\"UTF-8\"", "encoding=\"ISO-8859-1\""); if (log.isDebugEnabled()) log.debug("xmlSearchResult : for (" + searchText + ") :" + xmlSearchResult); String xmlStudies = xsltTransformer.toText(xmlSearchResult, "xslt/c2a_generic_response.xslt"); if (StringUtils.isEmpty(xmlStudies)) return studyList; Studies studies = (Studies) unmarshaller.unmarshal(new StringReader(xmlStudies)); for (gov.nih.nci.cabig.caaers.integration.schema.study.Study dtoStudy : studies.getStudy()) { Study domainStudy = new LocalStudy(); studyConverter.convertStudyDtoToStudyDomain(dtoStudy, domainStudy); //the following extra steps are need for the UI to get a valid Study structure. domainStudy.addStudyFundingSponsor(domainStudy.getFundingSponsor().getStudyFundingSponsor()); OrganizationAssignedIdentifier identifier = domainStudy.getFundingSponsor() .getOrganizationAssignedIdentifier(); identifier.setOrganization( domainStudy.getFundingSponsor().getStudyFundingSponsor().getOrganization()); domainStudy.addIdentifier(identifier); SystemAssignedIdentifier systemAssignedIdentifier = new SystemAssignedIdentifier(); systemAssignedIdentifier.setSystemName("CTEP-ESYS"); systemAssignedIdentifier.setType("Other"); systemAssignedIdentifier.setValue(domainStudy.getFundingSponsorIdentifierValue()); domainStudy.addIdentifier(systemAssignedIdentifier); studyList.add(domainStudy); } } catch (Exception e) { log.error("Error occured while invoking ServiceMix Study Search : " + e.getMessage(), e); log.info("Returning empty study list : unable to search in adeers for (" + searchText + ") :"); throw new CaaersSystemException(e.getMessage(), e); } } return studyList; }
From source file:gov.nih.nci.cabig.caaers.service.ProxyWebServiceFacadeUnitTest.java
public void testConcurrency() throws Exception { EasyMock.expect(configuration.get(Configuration.ESB_WS_URL)) .andReturn("http://localhost:8196/GenericProcessorService").anyTimes(); replayMocks();//from w w w . j a v a 2 s. c o m ExecutorService executor = Executors.newFixedThreadPool(10); List<Future<String>> list = new ArrayList<Future<String>>(); List<String> correlationIDs = new ArrayList<String>(); int NUM_OF_LOOPS = 0; for (int i = 0; i < NUM_OF_LOOPS; i++) { for (EntityOperation entityOperation : EntityOperation.values()) { String correlationId = RandomStringUtils.randomAlphanumeric(10); correlationIDs.add(correlationId); System.out.println(entityOperation + " - " + correlationId); Callable<String> worker = new ProxyWebServiceCallable(correlationId, entityOperation.getQualifiedName(), entityOperation.getOperationName(), proxyWebServiceFacade); Future<String> submit = executor.submit(worker); list.add(submit); } Thread.sleep(10000); } //System.out.println(list.size()); // Now retrieve the result for (int i = 0; i < list.size(); i++) { try { Matcher m = Pattern.compile("coorelationId=\"(.*)\"><system").matcher(list.get(i).get()); String correlationId = ""; try { correlationId = m.group(1); } catch (Exception e) { System.out.println("no correlation id found"); } System.out.println("\n[expected, actual] - [" + correlationIDs.get(i) + ", " + correlationId + "]"); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } executor.shutdown(); verifyMocks(); }
From source file:io.kamax.mxisd.session.SessionMananger.java
public IThreePidSession createRemote(String sid, String secret) { ThreePidSession session = getSessionIfValidated(sid, secret); log.info("Creating remote 3PID session for {} with local session [{}] to {}", session.getThreePid(), sid); boolean isLocal = isLocal(session.getThreePid()); PolicySource policy = cfg.getPolicy().getValidation().forIf(isLocal); if (!policy.isEnabled() || !policy.toRemote()) { throw new NotAllowedException("Validating " + (isLocal ? "local" : "remote") + " 3PID is not allowed"); }//from www. j a v a2s. co m log.info("Remote 3PID is allowed by policy"); List<String> servers = mxCfg.getIdentity().getServers(policy.getToRemote().getServer()); if (servers.isEmpty()) { throw new FeatureNotAvailable("Remote 3PID sessions are enabled but server list is " + "misconstrued (invalid ID or empty list"); } String is = servers.get(0); String url = IdentityServerUtils.findIsUrlForDomain(is).orElse(is); log.info("Will use IS endpoint {}", url); String remoteSecret = session.isRemote() ? session.getRemoteSecret() : RandomStringUtils.randomAlphanumeric(16); JsonObject body = new JsonObject(); body.addProperty("client_secret", remoteSecret); body.addProperty(session.getThreePid().getMedium(), session.getThreePid().getAddress()); body.addProperty("send_attempt", session.increaseAndGetRemoteAttempt()); if (ThreePidMedium.PhoneNumber.is(session.getThreePid().getMedium())) { try { Phonenumber.PhoneNumber msisdn = phoneUtil.parse("+" + session.getThreePid().getAddress(), null); String country = phoneUtil.getRegionCodeForNumber(msisdn).toUpperCase(); body.addProperty("phone_number", phoneUtil.format(msisdn, PhoneNumberUtil.PhoneNumberFormat.NATIONAL)); body.addProperty("country", country); } catch (NumberParseException e) { throw new InternalServerError(e); } } else { body.addProperty(session.getThreePid().getMedium(), session.getThreePid().getAddress()); } log.info("Requesting remote session with attempt {}", session.getRemoteAttempt()); HttpPost tokenReq = RestClientUtils.post( url + "/_matrix/identity/api/v1/validate/" + session.getThreePid().getMedium() + "/requestToken", body); try (CloseableHttpResponse response = client.execute(tokenReq)) { int status = response.getStatusLine().getStatusCode(); if (status < 200 || status >= 300) { JsonObject obj = parser.parseOptional(response) .orElseThrow(() -> new RemoteIdentityServerException("Status " + status)); throw new RemoteIdentityServerException( obj.get("errcode").getAsString() + ": " + obj.get("error").getAsString()); } RequestTokenResponse data = new GsonParser().parse(response, RequestTokenResponse.class); log.info("Remote Session ID: {}", data.getSid()); session.setRemoteData(url, data.getSid(), remoteSecret, 1); storage.updateThreePidSession(session.getDao()); log.info("Updated Session {} with remote data", sid); return session; } catch (IOException e) { log.warn("Failed to create remote session with {} for {}: {}", url, session.getThreePid(), e.getMessage()); throw new RemoteIdentityServerException(e.getMessage()); } }
From source file:com.flexive.tests.embedded.persistence.ValueTest.java
@Test public void valueTest() throws Exception { GregorianCalendar gc_multi_date = new GregorianCalendar(1940, 11, 22); GregorianCalendar gc_multi_date2 = new GregorianCalendar(1997, 9, 21); GregorianCalendar gc_single_date = new GregorianCalendar(1974, 0, 12); GregorianCalendar gc_single_date2 = new GregorianCalendar(1974, 3, 17); GregorianCalendar gc_multi_datetime = new GregorianCalendar(1940, 11, 22, 3, 30, 20); GregorianCalendar gc_multi_datetime2 = new GregorianCalendar(1997, 9, 21, 7, 40, 30); GregorianCalendar gc_single_datetime = new GregorianCalendar(1974, 0, 12, 4, 35, 45); GregorianCalendar gc_single_datetime2 = new GregorianCalendar(1974, 3, 17, 14, 30, 15); String s_single = "ABC"; String s_multi = "DEF"; String s_single_big = RandomStringUtils.randomAlphanumeric(50000); String s_multi_big = RandomStringUtils.randomAlphanumeric(50000); File testFile = new File("test.file"); if (!testFile.exists()) testFile = new File("src/framework/testresources/image/Exif.JPG"); if (!testFile.exists()) return;/*from w w w . j a v a 2 s . c om*/ FileInputStream fis = new FileInputStream(testFile); long time = System.currentTimeMillis(); BinaryDescriptor binary = new BinaryDescriptor(testFile.getName(), testFile.length(), fis); System.out.println("size: " + binary.getSize() + " time: " + (System.currentTimeMillis() - time)); System.out.println("==valueTest== Handle received for " + binary.getName() + ": " + binary.getHandle()); fis.close(); TestData[] data = { new TestData<FxHTML>(FxDataType.HTML, new FxHTML(false, s_single).setTidyHTML(true), new FxHTML(true, s_multi)), new TestData<FxString>(FxDataType.String1024, new FxString(false, s_single), new FxString(true, s_multi)), new TestData<FxString>(FxDataType.Text, new FxString(false, s_single_big), new FxString(true, s_multi_big)), new TestData<FxNumber>(FxDataType.Number, new FxNumber(false, Integer.MAX_VALUE), new FxNumber(true, Integer.MIN_VALUE)), new TestData<FxLargeNumber>(FxDataType.LargeNumber, new FxLargeNumber(false, Long.MAX_VALUE), new FxLargeNumber(true, Long.MIN_VALUE)), new TestData<FxFloat>(FxDataType.Float, new FxFloat(false, 123213213213.2222221f), new FxFloat(true, 1f)), new TestData<FxDouble>(FxDataType.Double, new FxDouble(false, 0.000000000000001d), new FxDouble(true, 1d)), new TestData<FxBoolean>(FxDataType.Boolean, new FxBoolean(false, true), new FxBoolean(true, false)), new TestData<FxDate>(FxDataType.Date, new FxDate(false, gc_single_date.getTime()), new FxDate(true, gc_multi_date.getTime())), new TestData<FxDateTime>(FxDataType.DateTime, new FxDateTime(false, gc_single_datetime.getTime()), new FxDateTime(true, gc_multi_datetime.getTime())), new TestData<FxDateRange>(FxDataType.DateRange, new FxDateRange(false, new DateRange(gc_single_date.getTime(), gc_single_date2.getTime())), new FxDateRange(true, new DateRange(gc_multi_date.getTime(), gc_multi_date2.getTime()))), new TestData<FxDateTimeRange>(FxDataType.DateTimeRange, new FxDateTimeRange(false, new DateRange(gc_single_datetime.getTime(), gc_single_datetime2.getTime())), new FxDateTimeRange(true, new DateRange(gc_multi_datetime.getTime(), gc_multi_datetime2.getTime()))), new TestData<FxBinary>(FxDataType.Binary, new FxBinary(false, binary), new FxBinary(true, binary)), new TestData<FxReference>(FxDataType.Reference, new FxReference(false, new ReferencedContent(RPK1)), new FxReference(true, new ReferencedContent(RPK1))) }; FxType testType; StringBuilder sbErr = new StringBuilder(100); for (TestData test : data) { try { System.out.println("Testing " + test.dataType.name() + " ..."); test.testConsistency(); createProperty(test.dataType); testType = CacheAdmin.getEnvironment().getType(TYPE_NAME); FxContent content = co.initialize(testType.getId()); content.setValue("/VTS" + test.dataType.name() + "[1]", test._single.copy()); // content.getPropertyData("/VT" + test.dataType.name() + "[1]").createNew(FxPropertyData.POSITION_BOTTOM); content.setValue("/VTM" + test.dataType.name() + "[1]", test._multi.copy().setValueData(43)); FxPK pk = co.save(content); FxContent loaded = co.load(pk); FxValue loadedSingle = loaded.getPropertyData("/VTS" + test.dataType.name() + "[1]").getValue(); FxValue loadedMulti = loaded.getPropertyData("/VTM" + test.dataType.name() + "[1]").getValue(); test.testSingleValue(loadedSingle); test.testMultiValue(loadedMulti); Assert.assertEquals((int) loadedSingle.getValueData(), 42); Assert.assertEquals((int) loadedMulti.getValueData(), 43); pk = co.save(loaded); loaded = co.load(pk); loadedSingle = loaded.getPropertyData("/VTS" + test.dataType.name() + "[1]").getValue(); loadedMulti = loaded.getPropertyData("/VTM" + test.dataType.name() + "[1]").getValue(); test.testSingleValue(loadedSingle); test.testMultiValue(loadedMulti); Assert.assertEquals((int) loadedSingle.getValueData(), 42); Assert.assertEquals((int) loadedMulti.getValueData(), 43); co.remove(pk); if (test.dataType == FxDataType.Reference) { //additional tests content = co.initialize(testType.getId()); content.setValue("/VTM" + test.dataType.name() + "[1]", new FxReference(true, new ReferencedContent(RPK1))); try { //set to a new pk content.setValue("/VTS" + test.dataType.name() + "[1]", new FxReference(false, new ReferencedContent(new FxPK()))); co.save(content); //expected to fail Assert.fail("Invalid PK (new) for a reference should fail!"); } catch (Exception e) { //expected } try { //set to a non existing pk content.setValue("/VTS" + test.dataType.name() + "[1]", new FxReference(false, new ReferencedContent(new FxPK(123456)))); co.save(content); //expected to fail Assert.fail("Invalid PK (non existant) for a reference should fail!"); } catch (Exception e) { //expected } try { //set to an existing pk, but wrong type content.setValue("/VTS" + test.dataType.name() + "[1]", new FxReference(false, new ReferencedContent(RPK2))); co.save(content); //expected to fail Assert.fail("Invalid PK (wrong type) for a reference should fail!"); } catch (Exception e) { //expected } try { //set to an existing pk, but wrong type content.setValue("/VTS" + test.dataType.name() + "[1]", RPK1); co.save(content); //expected to work } catch (Exception e) { e.printStackTrace(); Assert.fail("Correct PK for a reference should not fail!"); //expected } } } catch (Throwable e) { sbErr.append("Failed DataType: [").append(test.dataType.name()).append("] with: ") .append(e.getMessage()).append("\n"); e.printStackTrace(); } finally { try { removeProperty(test.dataType); } catch (Exception e) { LOG.warn("Failed to remove property", e); } } } if (sbErr.length() > 0) Assert.fail(sbErr.toString()); }