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.edgenius.wiki.webapp.servlet.InstallServlet.java
/** * @param request//from w w w . ja v a 2 s .c o m * @param response * @throws IOException * @throws ServletException */ private void createDataRoot(String root, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean error = false; //put original input as echo back while error request.setAttribute("root", root); root = DataRoot.formatRoot(root); try { File file = FileUtil.getFile(root); if (!FileUtil.exist(root)) { if (!file.mkdirs()) { error = true; request.setAttribute("error", "Unable to create directory, please create manually."); } } else if (!file.isDirectory()) { error = true; request.setAttribute("error", "The value is not directory."); } } catch (Exception e) { log.error("Unable to locate or create data root directory:" + root, e); error = true; request.setAttribute("error", "Unexpected exception " + e.toString() + ". Please manually create root directory."); } if (error) { resetContextPath(request); request.getRequestDispatcher("/WEB-INF/pages/install/createroot.jsp").forward(request, response); } else { DataRoot.saveDataRoot(root); //detect if the global.xml, installation.properties and server.properties exist? if so, the goto upgrade page Installation install = Installation.refreshInstallation(); if (FileUtil.exist(root + Global.FILE) && FileUtil.exist(root + Server.FILE) && FileUtil.exist(root + Installation.FILE)) { if (install.getVersion() == null) { //this means file not success load install = Installation.refreshInstallation(); if (install.getInstanceID() == null) { install.setInstanceID( RandomStringUtils.randomAlphanumeric(WikiConstants.UUID_KEY_SIZE).toLowerCase()); install.setInstanceType(Installation.INSTANCE_STANDARD); Installation.saveInstallation(install); } } if (Installation.STATUS_COMPLETED.equalsIgnoreCase(install.getStatus())) { if (checkDowngrade(request, response)) { return; } else { install.setStatus(Installation.STATUS_UPGRADE); Installation.saveInstallation(install); Installation.DONE = false; //echo back some info viewUpgrade(request, response); return; } } } else { //fresh new installation - try to give an instance ID to installation.xml if (install.getInstanceID() == null) { install.setInstanceID(UUID.randomUUID().toString()); install.setInstanceType(Installation.INSTANCE_STANDARD); Installation.saveInstallation(install); } } //new installation request.getRequestDispatcher("/WEB-INF/pages/install/createlicense.jsp").forward(request, response); } }
From source file:com.xingcloud.xa.hbase.util.ByteUtils.java
public static void main(String[] args) throws UnsupportedEncodingException { String randomString = RandomStringUtils.randomAlphanumeric(10); randomString = ""; System.out.println("String is " + randomString); byte[] stringBytes = randomString.getBytes(); System.out.println("String byte array is " + Arrays.toString(stringBytes)); long l = 984121; System.out.println("Long is " + l); byte[] longBytes = toBytes(l); System.out.println("Long byte array is " + Arrays.toString(longBytes)); byte[] newBytes = new byte[stringBytes.length + longBytes.length]; System.arraycopy(stringBytes, 0, newBytes, 0, stringBytes.length); System.arraycopy(longBytes, 0, newBytes, stringBytes.length, longBytes.length); System.out.println("Combined byte array rowkey is " + Arrays.toString(newBytes)); String printableString = toStringBinary(newBytes); System.out.println("Printable string is " + printableString); String unprintableString = toString(newBytes); System.out.println("Unprintable string is " + unprintableString); System.out.println(Arrays.toString(toBytesBinary(printableString))); }
From source file:com.edgenius.wiki.service.impl.FriendServiceImpl.java
public List<String> sendInvitation(User sender, String spaceUname, String toEmailGroup, String message) { String[] emails = toEmailGroup.split("[;,]"); //check email, and only save valid email to database if (emails == null || emails.length == 0) { //no valid email address return null; }/*from w ww .ja v a 2s . c o m*/ List<String> validEmails = new ArrayList<String>(); for (String email : emails) { email = email.trim(); if (email.matches( "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$")) { validEmails.add(email); } else { log.warn("Invalid email in friend invite email group, this email will be ignore:" + email); } } if (validEmails.size() == 0) { //no valid email address log.warn("Email group does not include invalid email, invitation cancelled: " + toEmailGroup); return null; } Invitation invite = new Invitation(); invite.setCreatedDate(new Date()); invite.setCreator(sender); invite.setMessage(message); invite.setSpaceUname(spaceUname); invite.setUuid(RandomStringUtils.randomAlphanumeric(WikiConstants.UUID_KEY_SIZE).toLowerCase()); //send mail Space space = spaceService.getSpaceByUname(spaceUname); message = StringUtils.isBlank(message) ? messageService.getMessage(WikiConstants.I18N_INVITE_MESSAGE) : message; Map<String, Object> map = new HashMap<String, Object>(); map.put(WikiConstants.ATTR_USER, sender); map.put(WikiConstants.ATTR_SPACE, space); map.put(WikiConstants.ATTR_INVITE_MESSAGE, message); //space home page String url = WikiUtil.getPageRedirFullURL(spaceUname, null, null); map.put(WikiConstants.ATTR_PAGE_LINK, url); List<String> validGroup = new ArrayList<String>(); for (String email : validEmails) { try { if (Global.hasSuppress(SUPPRESS.SIGNUP)) { User user = userReadingService.getUserByEmail(email); if (user == null) { //only unregistered user to be told system is not allow sign-up map.put(WikiConstants.ATTR_SIGNUP_SUPRESSED, true); } else { map.put(WikiConstants.ATTR_SIGNUP_SUPRESSED, false); } } else { map.put(WikiConstants.ATTR_SIGNUP_SUPRESSED, false); } map.put(WikiConstants.ATTR_INVITE_URL, WebUtil.getHostAppURL() + "invite.do?s=" + URLEncoder.encode(spaceUname, Constants.UTF8) + "&i=" + invite.getUuid()); SimpleMailMessage msg = new SimpleMailMessage(); msg.setFrom(Global.DefaultNotifyMail); msg.setTo(email); mailService.sendPlainMail(msg, WikiConstants.MAIL_TEMPL_INVITE, map); validGroup.add(email); } catch (Exception e) { log.error("Failed send email to invite " + email, e); } } invite.setToEmailGroup(StringUtils.join(validGroup, ',')); invitationDAO.saveOrUpdate(invite); //if system public signup is disabled, then here need check if that invited users are register users, if not, here need send email to notice system admin to add those users. if (Global.hasSuppress(SUPPRESS.SIGNUP)) { List<String> unregistereddEmails = new ArrayList<String>(); for (String email : validGroup) { User user = userReadingService.getUserByEmail(email); if (user == null) { unregistereddEmails.add(email); } } if (!unregistereddEmails.isEmpty()) { //send email to system admin. map = new HashMap<String, Object>(); map.put(WikiConstants.ATTR_USER, sender); map.put(WikiConstants.ATTR_SPACE, space); map.put(WikiConstants.ATTR_LIST, unregistereddEmails); mailService.sendPlainToSystemAdmins(WikiConstants.MAIL_TEMPL_ADD_INVITED_USER, map); } } return validGroup; }
From source file:edu.sampleu.demo.kitchensink.UifComponentsTestForm.java
public UifComponentsTestForm() { super();/*from ww w .j ava 2s . c o m*/ uiTestObject = new UITestObject("Foo", "FooBar", "FooBear", "FooRacket"); sourceCodeField = "<bean parent=\"Uif-PrimaryActionButton\" p:actionLabel=\"Save\" p:methodToCall=\"performSave\">\n" + "  <property name=\"actionImage\">\n" + "    <bean parent=\"Uif-Image\"\n" + "      p:source=\"@{#ConfigProperties['krad.externalizable.images.url']}searchicon.png\"\n" + "      p:actionImageLocation=\"RIGHT\"/>\n" + "  </property>\n" + "</bean>"; list1.add(new UITestObject("5", "6", "7", "8", new UITestObject("1", "1", "1", "1"))); UITestObject obj1 = new UITestObject("1", "2", "3", "4", new UITestObject("1", "1", "1", "1")); obj1.setStringList(null); list1.add(obj1); UITestObject obj2 = new UITestObject("9", "10", "11", "12", new UITestObject("1", "1", "1", "1")); obj2.setStringList(new ArrayList<String>()); list1.add(obj2); list1.add(new UITestObject("13", "14", "15", "16", new UITestObject("1", "1", "1", "1"))); list1.add(new UITestObject("17", "18", "19", "20", new UITestObject("1", "1", "1", "1"))); list1.add(new UITestObject("52", "6", "7", "8", new UITestObject("1", "1", "1", "1"))); list1.add(new UITestObject("12", "2", "3", "4", new UITestObject("1", "1", "1", "1"))); list1.add(new UITestObject("92", "10", "11", "12", new UITestObject("1", "1", "1", "1"))); list1.add(new UITestObject("132", "14", "15", "16", new UITestObject("1", "1", "1", "1"))); list1.add(new UITestObject("2132", "143", "151", "126", new UITestObject("1", "1", "1", "1"))); list1.add(new UITestObject("1332", "144", "155", "156", new UITestObject("1", "1", "1", "1"))); list1.add(new UITestObject("2132", "143", "151", "126", new UITestObject("1", "1", "1", "1"))); list1.add(new UITestObject("1332", "144", "155", "156", new UITestObject("1", "1", "1", "1"))); list2.add(new UITestObject("A", "B", "C", "D")); list2.add(new UITestObject("1", "2", "3", "4")); list2.add(new UITestObject("W", "X", "Y", "Z")); list2.add(new UITestObject("a", "b", "c", "d")); list2.add(new UITestObject("a", "s", "d", "f")); list3.add(new UITestObject("A", "B", "C", "D")); list3.get(0).getSubList().add(new UITestObject("A", "B", "C", "D")); list3.get(0).getSubList().add(new UITestObject("1", "2", "3", "4")); list3.get(0).getSubList().add(new UITestObject("W", "X", "Y", "Z")); list3.add(new UITestObject("1", "2", "3", "4")); list3.get(1).getSubList().add(new UITestObject("A", "B", "C", "D")); list3.get(1).getSubList().add(new UITestObject("1", "2", "3", "4")); list3.add(new UITestObject("W", "X", "Y", "Z")); list3.get(2).getSubList().add(new UITestObject("W", "X", "Y", "Z")); list4.add(new UITestObject("A", "B", "C", "D")); list4.get(0).getSubList().add(new UITestObject("1", "B", "C", "D", new UITestObject("1", "1", "1", "1"))); list4.get(0).getSubList().add(new UITestObject("2", "2", "3", "4", new UITestObject("1", "1", "1", "1"))); list4.get(0).getSubList().add(new UITestObject("3", "X", "Y", "Z", new UITestObject("1", "1", "1", "1"))); list4.add(new UITestObject("1", "2", "3", "4")); list4.get(1).getSubList() .add(new UITestObject("4", "b", "C", "D", new UITestObject("$50.00", "1", "1", "1"))); /*list4.get(1).getSubList().add(new UITestObject("5", "s", "D", "F", new UITestObject("1","1","1","1")));*/ //triple nesting list5.add(new UITestObject("a", "a", "a", "a")); list5.get(0).getSubList().add(new UITestObject("A", "B", "C", "D")); list5.get(0).getSubList().get(0).getSubList().add(new UITestObject("a3", "3", "3", "3")); list5.get(0).getSubList().get(0).getSubList().add(new UITestObject("a3", "3", "3", "3")); list5.get(0).getSubList().add(new UITestObject("1", "2", "3", "4")); list5.get(0).getSubList().get(1).getSubList().add(new UITestObject("b3", "3", "3", "3")); list5.get(0).getSubList().get(1).getSubList().add(new UITestObject("b3", "3", "3", "3")); list5.get(0).getSubList().get(1).getSubList().add(new UITestObject("b3", "3", "3", "3")); list5.add(new UITestObject("b", "b", "b", "b")); list5.get(1).getSubList().add(new UITestObject("a", "b", "C", "D")); list5.get(1).getSubList().get(0).getSubList().add(new UITestObject("a23", "3", "3", "3")); list5.get(1).getSubList().get(0).getSubList().add(new UITestObject("a23", "3", "3", "3")); list5.get(1).getSubList().add(new UITestObject("a", "s", "D", "F")); list5.get(1).getSubList().get(1).getSubList().add(new UITestObject("b23", "3", "3", "3")); list5.get(1).getSubList().get(1).getSubList().add(new UITestObject("b23", "3", "3", "3")); groupedList1.add(new UITestObject("A", "100", "200", "300")); groupedList1.add(new UITestObject("A", "101", "200", "300")); groupedList1.add(new UITestObject("A", "102", "200", "300")); groupedList1.add(new UITestObject("A", "103", "200", "300")); groupedList1.add(new UITestObject("A", "104", "200", "300")); groupedList1.add(new UITestObject("B", "100", "200", "300")); groupedList1.add(new UITestObject("B", "101", "200", "300")); groupedList1.add(new UITestObject("B", "102", "200", "300")); groupedList1.add(new UITestObject("C", "100", "200", "300")); groupedList1.add(new UITestObject("C", "101", "200", "300")); groupedList1.add(new UITestObject("C", "102", "200", "300")); groupedList1.add(new UITestObject("C", "103", "200", "300")); groupedList1.add(new UITestObject("D", "100", "200", "300")); groupedList1.add(new UITestObject("D", "101", "200", "300")); groupedList1.add(new UITestObject("D", "102", "200", "300")); groupedList1.add(new UITestObject("D", "103", "200", "300")); groupedList1.add(new UITestObject("D", "100", "200", "300")); groupedList1.add(new UITestObject("D", "101", "200", "300")); groupedList1.add(new UITestObject("D", "102", "200", "300")); groupedList1.add(new UITestObject("D", "103", "200", "300")); groupedList1.add(new UITestObject("D", "100", "200", "300")); groupedList1.add(new UITestObject("D", "101", "200", "300")); groupedList1.add(new UITestObject("D", "102", "200", "300")); groupedList1.add(new UITestObject("D", "103", "200", "300")); groupedList1.add(new UITestObject("D", "100", "200", "300")); groupedList1.add(new UITestObject("D", "101", "200", "300")); groupedList1.add(new UITestObject("D", "102", "200", "300")); groupedList1.add(new UITestObject("D", "103", "200", "300")); groupedList1.add(new UITestObject("D", "100", "200", "300")); groupedList1.add(new UITestObject("D", "101", "200", "300")); groupedList1.add(new UITestObject("D", "102", "200", "300")); groupedList1.add(new UITestObject("D", "103", "200", "300")); groupedList1.add(new UITestObject("D", "100", "200", "300")); groupedList1.add(new UITestObject("D", "101", "200", "300")); groupedList1.add(new UITestObject("D", "102", "200", "300")); groupedList1.add(new UITestObject("D", "103", "200", "300")); groupedList2.addAll(groupedList1); groupedList3.addAll(groupedList1); doubleGroupedList.add(new UITestObject("Fall", "2001", "AAA123", "2")); doubleGroupedList.add(new UITestObject("Fall", "2001", "BBB123", "3")); doubleGroupedList.add(new UITestObject("Fall", "2001", "CCC123", "4")); doubleGroupedList.add(new UITestObject("Fall", "2001", "DDD123", "3")); doubleGroupedList.add(new UITestObject("Fall", "2002", "AAA123", "3")); doubleGroupedList.add(new UITestObject("Fall", "2002", "BBB123", "2")); doubleGroupedList.add(new UITestObject("Fall", "2002", "CCC123", "3")); doubleGroupedList.add(new UITestObject("Fall", "2003", "AAA123", "3")); doubleGroupedList.add(new UITestObject("Fall", "2003", "CCC123", "3")); doubleGroupedList.add(new UITestObject("Spring", "2001", "AAA123", "3")); doubleGroupedList.add(new UITestObject("Spring", "2001", "BBB123", "3")); doubleGroupedList.add(new UITestObject("Spring", "2001", "CCC123", "3")); doubleGroupedList.add(new UITestObject("Spring", "2002", "AAA123", "4")); doubleGroupedList.add(new UITestObject("Spring", "2002", "BBB123", "4")); doubleGroupedList.add(new UITestObject("Spring", "2002", "CCC123", "2")); doubleGroupedList.add(new UITestObject("Spring", "2003", "AAA123", "4")); doubleGroupedList.add(new UITestObject("Spring", "2003", "BBB123", "3")); doubleGroupedList.add(new UITestObject("Spring", "2003", "CCC123", "3")); doubleGroupedList.add(new UITestObject("Spring", "2003", "DDD123", "2")); for (int i = 0; i < 22; i++) { UITestObject newObj = new UITestObject(RandomStringUtils.randomAlphanumeric(6), RandomStringUtils.randomAlphanumeric(6), RandomStringUtils.randomAlphanumeric(6), RandomStringUtils.randomNumeric(1)); if (i % 2 == 0) { newObj.setBfield(true); } list6.add(newObj); } { // scope for name hiding purposes Node<String, String> item1 = new Node<String, String>("Item 1", "Item 1"); item1.addChild(new Node<String, String>("SubItem A", "SubItem A")); item1.addChild(new Node<String, String>("SubItem B", "SubItem B")); Node<String, String> item2 = new Node<String, String>("Item 2", "Item 2"); item2.addChild(new Node<String, String>("SubItem A", "SubItem A")); Node<String, String> sub2B = new Node<String, String>("SubItem B", "SubItem B"); sub2B.addChild(new Node<String, String>("Item B-1", "Item B-1")); sub2B.addChild(new Node<String, String>("Item B-2", "Item B-2")); sub2B.addChild(new Node<String, String>("Item B-3", "Item B-3")); item2.addChild(sub2B); item2.addChild(new Node<String, String>("SubItem C", "SubItem C")); Node<String, String> item3 = new Node<String, String>("Item 3", "Item 3"); item3.addChild(new Node<String, String>("SubItem A", "SubItem A")); item3.addChild(new Node<String, String>("SubItem B", "SubItem B")); item3.addChild(new Node<String, String>("SubItem C", "SubItem C")); item3.addChild(new Node<String, String>("SubItem D", "SubItem D")); Node<String, String> root = new Node<String, String>("Root", "Root"); root.addChild(item1); root.addChild(item2); root.addChild(item3); tree1.setRootElement(root); } { // scope for name hiding purposes Node<UITestObject, String> item1 = new Node<UITestObject, String>( new UITestObject("1-A", "1-B", "1-C", "1-D"), "Item 1"); item1.addChild(new Node<UITestObject, String>(new UITestObject("1SA-A", "1SA-B", "1SA-C", "1SA-D"), "SubItem A")); item1.addChild(new Node<UITestObject, String>(new UITestObject("1SB-A", "1SB-B", "1SB-C", "1SB-D"), "SubItem B")); Node<UITestObject, String> item2 = new Node<UITestObject, String>( new UITestObject("2-A", "2-B", "2-C", "2-D"), "Item 2"); item2.addChild( new Node<UITestObject, String>(new UITestObject("SA-a", "SA-b", "SA-c", "SA-d"), "SubItem A")); Node<UITestObject, String> sub2B = new Node<UITestObject, String>( new UITestObject("SB-a", "SB-b", "SB-c", "SB-d"), "SubItem B"); sub2B.addChild(new Node<UITestObject, String>(new UITestObject("AA", "BB", "CC", "DD"), "Item B-1")); sub2B.addChild(new Node<UITestObject, String>(new UITestObject("Aa", "Bb", "Cc", "Dd"), "Item B-2")); sub2B.addChild(new Node<UITestObject, String>(new UITestObject("aA", "bB", "cC", "dD"), "Item B-3")); item2.addChild(sub2B); item2.addChild( new Node<UITestObject, String>(new UITestObject("SC-a", "SC-b", "SC-c", "SC-d"), "SubItem C")); Node<UITestObject, String> item3 = new Node<UITestObject, String>( new UITestObject("3-A", "3-B", "3-C", "3-D"), "Item 3"); item3.addChild(new Node<UITestObject, String>(new UITestObject("A", "B", "C", "D"), "SubItem A")); item3.addChild(new Node<UITestObject, String>(new UITestObject("1", "2", "3", "4"), "SubItem B")); item3.addChild(new Node<UITestObject, String>(new UITestObject("w", "x", "y", "z"), "SubItem C")); item3.addChild(new Node<UITestObject, String>(new UITestObject("!", "@", "#", "$"), "SubItem D")); Node<UITestObject, String> root = new Node<UITestObject, String>( new UITestObject("foo", "bar", "baz", "roo"), "Root"); root.addChild(item1); root.addChild(item2); root.addChild(item3); tree2.setRootElement(root); } remoteFieldValuesMap = new HashMap<String, Object>(); remoteFieldValuesMap.put("remoteField1", "Apple"); remoteFieldValuesMap.put("remoteField2", "Banana"); remoteFieldValuesMap.put("remoteField3", true); remoteFieldValuesMap.put("remoteField4", "Fruit"); remoteFieldValuesMap2 = new HashMap<String, Object>(); remoteFieldValuesMap2.put("remoteField1", "Apple"); remoteFieldValuesMap2.put("remoteField2", "Banana"); remoteFieldValuesMap2.put("remoteField3", true); remoteFieldValuesMap2.put("remoteField4", "Fruit"); field88 = "Fruits"; field91 = "Read only value"; field92 = "Value 92"; field131 = new Integer(0); DateFormat dateFormat = SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT); dateList = new ArrayList<Date>(); try { dateList.add(dateFormat.parse("01/01/1990")); dateList.add(dateFormat.parse("10/31/2001")); dateList.add(dateFormat.parse("11/05/2005")); dateList.add(dateFormat.parse("02/13/2011")); } catch (Exception e) { } emptyList.clear(); }
From source file:com.cws.esolutions.core.processors.impl.ServerManagementProcessorImplTest.java
@Test public void addServerAsDevMasterDnsServer() { String name = RandomStringUtils.randomAlphanumeric(8).toLowerCase(); Service service = new Service(); service.setGuid("1fe90f9d-0ead-4caf-92f6-a64be1dcc6aa"); Server server = new Server(); server.setOsName("CentOS"); server.setDomainName("caspersbox.corp"); server.setOperIpAddress("192.168.10.55"); server.setOperHostName(RandomStringUtils.randomAlphanumeric(8).toLowerCase()); server.setMgmtIpAddress("192.168.10.155"); server.setMgmtHostName(name + "-mgt"); server.setBkIpAddress("172.16.10.55"); server.setBkHostName(name + "-bak"); server.setNasIpAddress("172.15.10.55"); server.setNasHostName(name + "-nas"); server.setServerRegion(ServiceRegion.DEV); server.setServerStatus(ServerStatus.ONLINE); server.setServerType(ServerType.DNSMASTER); server.setServerComments("app server"); server.setAssignedEngineer(userAccount); server.setCpuType("AMD 1.0 GHz"); server.setCpuCount(1);/*from w ww. j a va 2 s . com*/ server.setServerModel("Virtual Server"); server.setSerialNumber("1YU391"); server.setInstalledMemory(4096); server.setNetworkPartition(NetworkPartition.DRN); server.setService(service); ServerManagementRequest request = new ServerManagementRequest(); request.setRequestInfo(hostInfo); request.setUserAccount(userAccount); request.setServiceId("45F6BC9E-F45C-4E2E-B5BF-04F93C8F512E"); request.setTargetServer(server); request.setApplicationId("6236B840-88B0-4230-BCBC-8EC33EE837D9"); request.setApplicationName("eSolutions"); try { ServerManagementResponse response = processor.addNewServer(request); Assert.assertEquals(CoreServicesStatus.SUCCESS, response.getRequestStatus()); } catch (ServerManagementException smx) { Assert.fail(smx.getMessage()); } }
From source file:com.flexive.tests.embedded.AccountTest.java
@Test public void restApiAccountTest() throws FxLogoutFailedException, FxLoginFailedException, FxAccountInUseException, FxApplicationException { try {/* w ww. j a va 2s . c o m*/ login(TestUsers.SUPERVISOR); final long accountId = createAccount(0, 1, true, true); Account account = accountEngine.load(accountId); FxContext.startRunningAsSystem(); try { logout(); FxContext.get().login(account.getLoginName(), "unknown", true); accountEngine.addRole(accountId, Role.AccountManagement.getId()); } finally { FxContext.stopRunningAsSystem(); } assertEquals(account.getRestToken(), null); assertEquals(account.getRestTokenExpires(), 0); try { accountEngine.generateRestToken(); fail("User without REST-API role should not be allowed to create tokens"); } catch (FxNoAccessException e) { // pass } FxContext.startRunningAsSystem(); try { accountEngine.addRole(accountId, Role.RestApiAccess.getId()); } finally { FxContext.stopRunningAsSystem(); } final String token = accountEngine.generateRestToken(); assertEquals(token.length(), 64); account = accountEngine.load(accountId); assertTrue(account.getRestTokenExpires() > 0); assertFalse(account.isRestTokenExpired()); logout(); // try to login via the REST-API login call assertTrue(FxContext.getUserTicket().isGuest()); try { accountEngine.loginByRestToken("123"); fail("Invalid token format not recognized"); } catch (FxInvalidParameterException e) { // pass } try { accountEngine.loginByRestToken(RandomStringUtils.randomAlphanumeric(64)); fail("Invalid/expired token should have been rejected"); } catch (FxRestApiTokenExpiredException e) { // pass } assertTrue(FxContext.getUserTicket().isGuest()); accountEngine.loginByRestToken(token); assertEquals(FxContext.getUserTicket().getLoginName(), account.getLoginName()); accountEngine.remove(accountId); } finally { login(TestUsers.SUPERVISOR); } }
From source file:edu.duke.cabig.c3pr.webservice.integration.StudyUtilityWebServiceTest.java
private void executeUpdateConsentTest() throws DataSetException, IOException, SQLException, DatabaseUnitException, Exception { StudyUtility service = getService(); // setting updateMode in request explicitly to Replace:R, it should have same name and versionId as the one to be replaced final Consent consent = createConsent(TEST_CONSENT_TITLE, UPDATE_DISCRIMINATOR); UpdateStudyConsentRequest request = new UpdateStudyConsentRequest(); final DocumentIdentifier studyId = createStudyPrimaryIdentifier(); request.setStudyIdentifier(studyId); request.setConsent(consent);//from www .j a v a 2s .c om request.setUpdateMode(UpdateMode.R); Consent updatedConsent = service.updateStudyConsent(request).getConsent(); assertTrue(BeanUtils.deepCompare(consent, updatedConsent)); // check database data verifyData("Consents_ReplaceConsent", "", "consents", SQL_CONSENTS); verifyData("ConsentQuestions_ReplaceConsent", "", "consent_questions", SQL_CONSENT_QUESTIONS); //add consent final Consent addConsent = createConsent(TEST_CONSENT_TITLE + UPDATE_DISCRIMINATOR, ""); request.setUpdateMode(UpdateMode.AU); request.setStudyIdentifier(studyId); request.setConsent(addConsent); updatedConsent = service.updateStudyConsent(request).getConsent(); addConsent.getVersionNumberText().setUpdateMode(null); assertTrue(BeanUtils.deepCompare(addConsent, updatedConsent)); // check database data verifyData("Consents_AddConsent", "", "consents", SQL_CONSENTS); verifyData("ConsentQuestions_AddConsent", "", "consent_questions", SQL_CONSENT_QUESTIONS); //update consent // Consent name and version id uniquely determine so, consent name cannot change final Consent updateConsent = createConsent(TEST_CONSENT_TITLE, UPDATE_DISCRIMINATOR + " 2"); updateConsent.setOfficialTitle(iso.ST(TEST_CONSENT_TITLE)); updateConsent.setVersionNumberText(iso.ST(TEST_VERSION_NUMBER)); request.setUpdateMode(UpdateMode.U); request.setStudyIdentifier(studyId); request.setConsent(updateConsent); updatedConsent = service.updateStudyConsent(request).getConsent(); assertTrue(BeanUtils.deepCompare(updateConsent, updatedConsent)); // check database data verifyData("Consents_UpdateConsent", "", "consents", SQL_CONSENTS); verifyData("ConsentQuestions_UpdateConsent", "", "consent_questions", SQL_CONSENT_QUESTIONS); //update consent final Consent retireConsent = createConsent(TEST_CONSENT_TITLE, UPDATE_DISCRIMINATOR + " 2"); request.setUpdateMode(UpdateMode.D); request.setStudyIdentifier(studyId); request.setConsent(retireConsent); updatedConsent = service.updateStudyConsent(request).getConsent(); // assertTrue(BeanUtils.deepCompare(retireConsent, updatedConsent)); // check database data verifyData("Consents_RetireConsent", "", "consents", SQL_CONSENTS); //test using query // all consents of the study final QueryStudyConsentRequest request1 = new QueryStudyConsentRequest(); request1.setStudyIdentifier(studyId); List<Consent> list = service.queryStudyConsent(request1).getConsents().getItem(); assertEquals(2, list.size()); // study does not exist. studyId.getIdentifier().setExtension(RandomStringUtils.randomAlphanumeric(32)); try { service.updateStudyConsent(request); fail(); } catch (StudyUtilityFaultMessage e) { logger.info("Unexistent study creation passed."); } }
From source file:de.thm.arsnova.service.UserServiceImpl.java
@Override public void initiatePasswordReset(String username) { UserProfile userProfile = getByUsername(username); if (null == userProfile) { logger.info("Password reset failed. User {} does not exist.", username); throw new NotFoundException(); }//from w ww .j av a 2s . co m UserProfile.Account account = userProfile.getAccount(); if (System.currentTimeMillis() < account.getPasswordResetTime().getTime() + REPEATED_PASSWORD_RESET_DELAY_MS) { logger.info("Password reset failed. The reset delay for User {} is still active.", username); throw new BadRequestException(); } account.setPasswordResetKey(RandomStringUtils.randomAlphanumeric(32)); account.setPasswordResetTime(new Date()); if (null == userRepository.save(userProfile)) { logger.error("Password reset failed. {} could not be updated.", username); } String resetPasswordUrl = MessageFormat.format("{0}{1}/{2}?action=resetpassword&username={3}&key={4}", rootUrl, customizationPath, resetPasswordPath, UriUtils.encodeQueryParam(userProfile.getLoginId(), "UTF-8"), account.getPasswordResetKey()); sendEmail(userProfile, resetPasswordMailSubject, MessageFormat.format(resetPasswordMailBody, resetPasswordUrl)); }
From source file:com.edgenius.wiki.util.WikiUtil.java
/** * Get an unique string from given html. It means indexOf(htmlText) will always return -1. * // w w w . j av a 2s .co m * @param htmlText * @param multipleLines -- put newline(\n) into returned key. * @param newlineAtEnd -- only multipleLines is true, this flag is useful. If true, it puts newline end of key, * otherwise, put newline as first character of key * @return */ public static String findUniqueKey(String htmlText, boolean multipleLines, boolean newlineAtEnd) { //please note, if multipleLines flag is true, the unique part should be the part which does not include newline. //this scenario: some multipleLines key may be trimmed during markup render process. this means, so we may try to //use unique part rather than whole key part as parameter in String.index(). See MarkupRenderEngineImpl.processObjects(). String key, uniquePart; do { key = RandomStringUtils.randomAlphanumeric(WikiConstants.UUID_KEY_SIZE); uniquePart = key; if (multipleLines) { char[] bk = key.toCharArray(); if (newlineAtEnd) { //replace last character, this is requirement of NewlineFilter, which will detect \n is belong to unique key or not bk[bk.length - 1] = '\n'; uniquePart = new String(bk, 0, bk.length - 1); } else { bk[0] = '\n'; uniquePart = new String(bk, 1, bk.length - 1); } key = new String(bk); } } while (htmlText != null && htmlText.indexOf(uniquePart) != -1); return key; }
From source file:edu.duke.cabig.c3pr.webservice.integration.SubjectManagementWebServiceTest.java
private void executeCreateSubjectTestWithoutSubjectAddress() throws DataSetException, IOException, SQLException, DatabaseUnitException, Exception { SubjectManagement service = getService(); // successful subject creation. final CreateSubjectRequest request = new CreateSubjectRequest(); Subject subject = createSubject(false, false); request.setSubject(subject);// w w w. ja v a 2s . c o m Subject createdSubject = service.createSubject(request).getSubject(); assertNotNull(createdSubject); // have to ascertain that the subject's postal address is null in both request as well as in response assertNull(((Person) subject.getEntity()).getPostalAddress()); assertNull(((Person) createdSubject.getEntity()).getPostalAddress()); // If the default c3pr generated system identifier is sent in the request, there is no need to strip it from the created subject //system identifiers in response, otherwise we need to remove the default system identifier from response before doing deep compare. if (!ifC3PRDefaultSystemIdentifierSent(subject)) { stripC3PRDefaultSystemIdentifier(createdSubject); } assertTrue(BeanUtils.deepCompare(subject, createdSubject)); // not verifying data. The other test case with complete data is already doing that // verifySubjectDatabaseData(createdSubject, ""); // duplicate subject try { service.createSubject(request); fail(); } catch (SubjectAlreadyExistsExceptionFaultMessage e) { logger.info("Duplicate subject creation passed."); } // missing primary identifier subject.getEntity().getBiologicEntityIdentifier().clear(); subject.getEntity().getBiologicEntityIdentifier().add(createSecondaryBioEntityOrgId(false)); try { service.createSubject(request); fail(); } catch (InvalidSubjectDataExceptionFaultMessage e) { logger.info("missing primary identifier passed."); } // duplicate secondary identifier subject = createSubject(false, true); subject.getEntity().getBiologicEntityIdentifier().get(1).getIdentifier() .setExtension(RandomStringUtils.randomAlphanumeric(16)); request.setSubject(subject); createdSubject = service.createSubject(request).getSubject(); assertNotNull(createdSubject); // If the default c3pr generated system identifier is sent in the request, there is no need to strip it from the created subject //system identifiers in response, otherwise we need to remove the default system identifier from response before doing deep compare. if (!ifC3PRDefaultSystemIdentifierSent(subject)) { stripC3PRDefaultSystemIdentifier(createdSubject); } assertTrue(BeanUtils.deepCompare(subject, createdSubject)); // bad subject data subject.getEntity().getBirthDate().setValue(BAD_ISO_DATE); try { service.createSubject(request); fail(); } catch (InvalidSubjectDataExceptionFaultMessage e) { logger.info("Bad subject data test passed."); } // missing identifiers subject = createSubject(false, true); request.setSubject(subject); subject.getEntity().getBiologicEntityIdentifier().clear(); try { service.createSubject(request); fail(); } catch (InvalidSubjectDataExceptionFaultMessage e) { logger.info("Missing test identifiers passed."); } // Bad subject data, XSD validation. subject.getEntity().setAdministrativeGenderCode(null); try { service.createSubject(request); fail(); } catch (SOAPFaultException e) { logger.info("Bad test subject data, XSD validation passed."); } }