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.evolveum.midpoint.model.common.stringpolicy.ValuePolicyProcessor.java
private String generateAttempt(ValuePolicyType policy, int defaultLength, boolean generateMinimalSize, Context ctx, OperationResult result) { StringPolicyType stringPolicy = policy.getStringPolicy(); // if (policy.getLimitations() != null && // policy.getLimitations().getMinLength() != null){ // generateMinimalSize = true; // }//from ww w . j a va 2 s.c o m // setup default values where missing // PasswordPolicyUtils.normalize(pp); // Optimize usage of limits ass hashmap of limitas and key is set of // valid chars for each limitation Map<StringLimitType, List<String>> lims = new HashMap<>(); int minLen = defaultLength; int maxLen = defaultLength; int unique = defaultLength / 2; if (stringPolicy != null) { for (StringLimitType l : stringPolicy.getLimitations().getLimit()) { if (null != l.getCharacterClass().getValue()) { lims.put(l, StringPolicyUtils.stringTokenizer(l.getCharacterClass().getValue())); } else { lims.put(l, StringPolicyUtils.stringTokenizer(StringPolicyUtils.collectCharacterClass( stringPolicy.getCharacterClass(), l.getCharacterClass().getRef()))); } } // Get global limitations minLen = defaultIfNull(stringPolicy.getLimitations().getMinLength(), 0); if (minLen != 0 && minLen > defaultLength) { defaultLength = minLen; } maxLen = defaultIfNull(stringPolicy.getLimitations().getMaxLength(), 0); unique = defaultIfNull(stringPolicy.getLimitations().getMinUniqueChars(), minLen); } // test correctness of definition if (unique > minLen) { minLen = unique; OperationResult reportBug = new OperationResult("Global limitation check"); reportBug.recordWarning( "There is more required unique characters then defined minimum. Raise minimum to number of required unique chars."); } if (minLen == 0 && maxLen == 0) { minLen = defaultLength; maxLen = defaultLength; generateMinimalSize = true; } if (maxLen == 0) { if (minLen > defaultLength) { maxLen = minLen; } else { maxLen = defaultLength; } } // Initialize generator StringBuilder password = new StringBuilder(); /* * ********************************** Try to find best characters to be * first in password */ Map<StringLimitType, List<String>> mustBeFirst = new HashMap<>(); for (Map.Entry<StringLimitType, List<String>> entry : lims.entrySet()) { final StringLimitType key = entry.getKey(); if (key.isMustBeFirst() != null && key.isMustBeFirst()) { mustBeFirst.put(key, entry.getValue()); } } // If any limitation was found to be first if (!mustBeFirst.isEmpty()) { Map<Integer, List<String>> posibleFirstChars = cardinalityCounter(mustBeFirst, null, false, false, result); int intersectionCardinality = mustBeFirst.keySet().size(); List<String> intersectionCharacters = posibleFirstChars.get(intersectionCardinality); // If no intersection was found then raise error if (null == intersectionCharacters || intersectionCharacters.size() == 0) { result.recordFatalError("No intersection for required first character sets in value policy:" + stringPolicy.getDescription()); // Log error if (LOGGER.isErrorEnabled()) { LOGGER.error("Unable to generate value for " + ctx.path + ": No intersection for required first character sets in value policy: [" + stringPolicy.getDescription() + "] following character limitation and sets are used:"); for (StringLimitType l : mustBeFirst.keySet()) { StrBuilder tmp = new StrBuilder(); tmp.appendSeparator(", "); tmp.appendAll(mustBeFirst.get(l)); LOGGER.error("L:" + l.getDescription() + " -> [" + tmp + "]"); } } // No more processing unrecoverable conflict return null; // EXIT } else { if (LOGGER.isDebugEnabled()) { StrBuilder tmp = new StrBuilder(); tmp.appendSeparator(", "); tmp.appendAll(intersectionCharacters); LOGGER.trace( "Generate first character intersection items [" + tmp + "] into " + ctx.path + "."); } // Generate random char into password from intersection password.append(intersectionCharacters.get(RAND.nextInt(intersectionCharacters.size()))); } } /* * ************************************** Generate rest to fulfill * minimal criteria */ boolean uniquenessReached = false; // Count cardinality of elements Map<Integer, List<String>> chars; for (int i = 0; i < minLen; i++) { // Check if still unique chars are needed if (password.length() >= unique) { uniquenessReached = true; } // Find all usable characters chars = cardinalityCounter(lims, StringPolicyUtils.stringTokenizer(password.toString()), false, uniquenessReached, result); // If something goes badly then go out if (null == chars) { return null; } if (chars.isEmpty()) { LOGGER.trace("Minimal criterias was met. No more characters"); break; } // Find lowest possible cardinality and then generate char for (int card = 1; card < lims.keySet().size(); card++) { if (chars.containsKey(card)) { List<String> validChars = chars.get(card); password.append(validChars.get(RAND.nextInt(validChars.size()))); break; } } } // test if maximum is not exceeded if (password.length() > maxLen) { result.recordFatalError( "Unable to meet minimal criteria and not exceed maximal size of " + ctx.path + "."); return null; } /* * *************************************** Generate chars to not exceed * maximal */ for (int i = 0; i < minLen; i++) { // test if max is reached if (password.length() == maxLen) { // no more characters maximal size is reached break; } if (password.length() >= minLen && generateMinimalSize) { // no more characters are needed break; } // Check if still unique chars are needed if (password.length() >= unique) { uniquenessReached = true; } // find all usable characters chars = cardinalityCounter(lims, StringPolicyUtils.stringTokenizer(password.toString()), true, uniquenessReached, result); // If something goes badly then go out if (null == chars) { // we hope this never happend. result.recordFatalError("No valid characters to generate, but no all limitation are reached"); return null; } // if selection is empty then no more characters and we can close // our work if (chars.isEmpty()) { if (i == 0) { password.append(RandomStringUtils.randomAlphanumeric(minLen)); } break; // if (!StringUtils.isBlank(password.toString()) && // password.length() >= minLen) { // break; // } // check uf this is a firs cycle and if we need to user some // default (alphanum) character class. } // Find lowest possible cardinality and then generate char for (int card = 1; card <= lims.keySet().size(); card++) { if (chars.containsKey(card)) { List<String> validChars = chars.get(card); password.append(validChars.get(RAND.nextInt(validChars.size()))); break; } } } if (password.length() < minLen) { result.recordFatalError("Unable to generate value for " + ctx.path + " and meet minimal size of " + ctx.path + ". Actual length: " + password.length() + ", required: " + minLen); LOGGER.trace("Unable to generate value for " + ctx.path + " and meet minimal size of " + ctx.path + ". Actual length: {}, required: {}", password.length(), minLen); return null; } result.recordSuccess(); // Shuffle output to solve pattern like output StrBuilder sb = new StrBuilder(password.substring(0, 1)); List<String> shuffleBuffer = StringPolicyUtils.stringTokenizer(password.substring(1)); Collections.shuffle(shuffleBuffer); sb.appendAll(shuffleBuffer); return sb.toString(); }
From source file:com.cws.esolutions.core.processors.impl.ServerManagementProcessorImplTest.java
@Test public void addNewServerAsDevMqServer() { String name = RandomStringUtils.randomAlphanumeric(8).toLowerCase(); Service service = new Service(); service.setGuid("1fe90f9d-0ead-4caf-92f6-a64be1dcc6aa"); for (int x = 0; x < 2; x++) { 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.MQSERVER); server.setServerComments("app server"); server.setAssignedEngineer(userAccount); server.setCpuType("AMD 1.0 GHz"); server.setCpuCount(1);//from w w w . j a v a2s . c o m 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.cws.esolutions.security.processors.impl.AccountControlProcessorImpl.java
/** * @see com.cws.esolutions.security.processors.interfaces.IAccountControlProcessor#modifyUserPassword(com.cws.esolutions.security.processors.dto.AccountControlRequest) *//*from ww w . j av a 2 s.c om*/ public AccountControlResponse modifyUserPassword(final AccountControlRequest request) throws AccountControlException { final String methodName = IAccountControlProcessor.CNAME + "#modifyUserPassword(final AccountControlRequest request) throws AccountControlException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("AccountControlRequest: {}", request); } AccountControlResponse response = new AccountControlResponse(); final Calendar calendar = Calendar.getInstance(); final RequestHostInfo reqInfo = request.getHostInfo(); final UserAccount reqAccount = request.getRequestor(); final UserAccount userAccount = request.getUserAccount(); calendar.add(Calendar.DATE, secConfig.getPasswordExpiration()); if (DEBUG) { DEBUGGER.debug("Calendar: {}", calendar); DEBUGGER.debug("RequestHostInfo: {}", reqInfo); DEBUGGER.debug("UserAccount: {}", reqAccount); DEBUGGER.debug("UserAccount: {}", userAccount); } try { // this will require admin and service authorization AccessControlServiceRequest accessRequest = new AccessControlServiceRequest(); accessRequest.setUserAccount(userAccount); accessRequest.setServiceGuid(request.getServiceId()); if (DEBUG) { DEBUGGER.debug("AccessControlServiceRequest: {}", accessRequest); } AccessControlServiceResponse accessResponse = accessControl.isUserAuthorized(accessRequest); if (DEBUG) { DEBUGGER.debug("AccessControlServiceResponse accessResponse: {}", accessResponse); } if (!(accessResponse.getIsUserAuthorized())) { // unauthorized response.setRequestStatus(SecurityRequestStatus.UNAUTHORIZED); // audit try { AuditEntry auditEntry = new AuditEntry(); auditEntry.setHostInfo(reqInfo); auditEntry.setAuditType(AuditType.CHANGEPASS); auditEntry.setUserAccount(userAccount); auditEntry.setAuthorized(Boolean.FALSE); auditEntry.setApplicationId(request.getApplicationId()); auditEntry.setApplicationName(request.getApplicationName()); if (DEBUG) { DEBUGGER.debug("AuditEntry: {}", auditEntry); } AuditRequest auditRequest = new AuditRequest(); auditRequest.setAuditEntry(auditEntry); if (DEBUG) { DEBUGGER.debug("AuditRequest: {}", auditRequest); } auditor.auditRequest(auditRequest); } catch (AuditServiceException asx) { ERROR_RECORDER.error(asx.getMessage(), asx); } return response; } // this is a reset request, so we need to do a few things // 1, we need to generate a unique id that we can email off // to the user, that we can then look up to confirm // then once we have that we can actually do the reset // first, change the existing password // 128 character values - its possible that the reset is // coming as a result of a possible compromise String tmpPassword = PasswordUtils.encryptText( RandomStringUtils.randomAlphanumeric(secConfig.getPasswordMaxLength()), RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength()), secConfig.getAuthAlgorithm(), secConfig.getIterations(), secBean.getConfigData().getSystemConfig().getEncoding()); String tmpSalt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength()); if ((StringUtils.isNotEmpty(tmpPassword)) && (StringUtils.isNotEmpty(tmpSalt))) { // update the authentication datastore with the new password // we never show the user the password, we're only doing this // to prevent unauthorized access (or further unauthorized access) // we get a return code back but we aren't going to use it really boolean isComplete = userManager.modifyUserPassword(userAccount.getGuid(), tmpPassword); if (DEBUG) { DEBUGGER.debug("isComplete: {}", isComplete); } // now generate a temporary id to stuff into the database // this will effectively replace the current salt value String resetId = RandomStringUtils.randomAlphanumeric(secConfig.getResetIdLength()); String resetSms = RandomStringUtils.randomAlphanumeric(secConfig.getSmsCodeLength()); if ((StringUtils.isNotEmpty(resetId)) && (StringUtils.isNotEmpty(resetSms))) { isComplete = userSec.insertResetData(userAccount.getGuid(), resetId, ((secConfig.getSmsResetEnabled()) ? resetSms : null)); if (DEBUG) { DEBUGGER.debug("isComplete: {}", isComplete); } if (isComplete) { response.setResetId(resetId); response.setRequestStatus(SecurityRequestStatus.SUCCESS); } else { ERROR_RECORDER .error("Unable to insert password identifier into database. Cannot continue."); response.setRequestStatus(SecurityRequestStatus.SUCCESS); } } else { ERROR_RECORDER.error("Unable to generate a unique identifier. Cannot continue."); response.setRequestStatus(SecurityRequestStatus.SUCCESS); } } else { ERROR_RECORDER.error("Failed to generate a temporary password. Cannot continue."); response.setRequestStatus(SecurityRequestStatus.SUCCESS); } } catch (SQLException sqx) { ERROR_RECORDER.error(sqx.getMessage(), sqx); throw new AccountControlException(sqx.getMessage(), sqx); } catch (AccessControlServiceException acsx) { ERROR_RECORDER.error(acsx.getMessage(), acsx); throw new AccountControlException(acsx.getMessage(), acsx); } catch (UserManagementException umx) { ERROR_RECORDER.error(umx.getMessage(), umx); throw new AccountControlException(umx.getMessage(), umx); } catch (SecurityException sx) { ERROR_RECORDER.error(sx.getMessage(), sx); throw new AccountControlException(sx.getMessage(), sx); } finally { // audit try { AuditEntry auditEntry = new AuditEntry(); auditEntry.setHostInfo(reqInfo); auditEntry.setAuditType(AuditType.RESETPASS); auditEntry.setUserAccount(reqAccount); auditEntry.setAuthorized(Boolean.TRUE); auditEntry.setApplicationId(request.getApplicationId()); auditEntry.setApplicationName(request.getApplicationName()); if (DEBUG) { DEBUGGER.debug("AuditEntry: {}", auditEntry); } AuditRequest auditRequest = new AuditRequest(); auditRequest.setAuditEntry(auditEntry); if (DEBUG) { DEBUGGER.debug("AuditRequest: {}", auditRequest); } auditor.auditRequest(auditRequest); } catch (AuditServiceException asx) { ERROR_RECORDER.error(asx.getMessage(), asx); } } return response; }
From source file:com.cws.esolutions.core.processors.impl.ServerManagementProcessorImplTest.java
@Test public void addNewServerAsQaMqServer() { String name = RandomStringUtils.randomAlphanumeric(8).toLowerCase(); Service service = new Service(); service.setGuid("1fe90f9d-0ead-4caf-92f6-a64be1dcc6aa"); for (int x = 0; x < 2; x++) { 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.QA); server.setServerStatus(ServerStatus.ONLINE); server.setServerType(ServerType.MQSERVER); server.setServerComments("app server"); server.setAssignedEngineer(userAccount); server.setCpuType("AMD 1.0 GHz"); server.setCpuCount(1);//from w w w . jav a2s.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.kixeye.chassis.transport.WebSocketTransportTest.java
@Test public void testWebSocketServiceWithYaml() throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("websocket.enabled", "true"); properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("websocket.hostname", "localhost"); properties.put("http.enabled", "false"); properties.put("http.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("http.hostname", "localhost"); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); context.register(TestWebSocketService.class); WebSocketClient wsClient = new WebSocketClient(); try {/*from ww w. java 2 s .c om*/ context.refresh(); final MessageSerDe serDe = context.getBean(YamlJacksonMessageSerDe.class); final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class); messageRegistry.registerType("stuff", TestObject.class); wsClient.start(); QueuingWebSocketListener webSocket = new QueuingWebSocketListener(serDe, messageRegistry, null); Session session = wsClient.connect(webSocket, new URI( "ws://localhost:" + properties.get("websocket.port") + "/" + serDe.getMessageFormatName())) .get(5000, TimeUnit.MILLISECONDS); Envelope envelope = new Envelope("getStuff", null, null, Lists.newArrayList(new Header("testheadername", Lists.newArrayList("testheaderval"))), null); session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope))); TestObject response = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); byte[] rawStuff = serDe.serialize(new TestObject("more stuff")); envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff)); session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope))); response = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); envelope = new Envelope("getStuff", null, null, null); session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope))); response = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); rawStuff = serDe.serialize(new TestObject(RandomStringUtils.randomAlphanumeric(100))); envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff)); session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope))); ServiceError error = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(error); Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.code); envelope = new Envelope("expectedError", null, null, null); session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope))); error = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(error); Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.code, error.code); Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.description, error.description); envelope = new Envelope("unexpectedError", null, null, null); session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope))); error = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(error); Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.code); } finally { try { wsClient.stop(); } finally { context.close(); while (context.isActive()) { Thread.sleep(100); } } } }
From source file:com.cws.esolutions.core.processors.impl.ServerManagementProcessorImplTest.java
@Test public void addNewServerAsPrdMqServer() { String name = RandomStringUtils.randomAlphanumeric(8).toLowerCase(); Service service = new Service(); service.setGuid("1fe90f9d-0ead-4caf-92f6-a64be1dcc6aa"); for (int x = 0; x < 2; x++) { 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.PRD); server.setServerStatus(ServerStatus.ONLINE); server.setServerType(ServerType.MQSERVER); server.setServerComments("app server"); server.setAssignedEngineer(userAccount); server.setCpuType("AMD 1.0 GHz"); server.setCpuCount(1);//from ww w . j a va 2 s . c o m 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.cws.esolutions.security.processors.impl.AccountChangeProcessorImpl.java
/** * @see com.cws.esolutions.security.processors.interfaces.IAccountChangeProcessor#enableOtpAuth(com.cws.esolutions.security.processors.dto.AccountChangeRequest) *//*from ww w . j a v a 2 s. c om*/ public AccountChangeResponse enableOtpAuth(final AccountChangeRequest request) throws AccountChangeException { final String methodName = IAccountChangeProcessor.CNAME + "#enableOtpAuth(final AccountChangeRequest request) throws AccountChangeException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("AccountChangeRequest: {}", request); } AccountChangeResponse response = new AccountChangeResponse(); final UserAccount requestor = request.getRequestor(); final RequestHostInfo reqInfo = request.getHostInfo(); final UserAccount userAccount = request.getUserAccount(); final AuthenticationData reqSecurity = request.getUserSecurity(); if (DEBUG) { DEBUGGER.debug("UserAccount: {}", userAccount); DEBUGGER.debug("RequestHostInfo: {}", reqInfo); DEBUGGER.debug("UserAccount: {}", userAccount); } if (!(StringUtils.equals(userAccount.getGuid(), requestor.getGuid()))) { // requesting user is not the same as the user being reset. authorize response.setRequestStatus(SecurityRequestStatus.UNAUTHORIZED); return response; } try { String userSalt = userSec.getUserSalt(userAccount.getGuid(), SaltType.LOGON.name()); if (StringUtils.isNotEmpty(userSalt)) { // we aren't getting the data back here because we don't need it. if the request // fails we'll get an exception and not process further. this might not be the // best flow control, but it does exactly what we need where we need it. authenticator.performLogon(userAccount.getUsername(), PasswordUtils.encryptText(reqSecurity.getPassword(), userSalt, secBean.getConfigData().getSecurityConfig().getAuthAlgorithm(), secBean.getConfigData().getSecurityConfig().getIterations(), secBean.getConfigData().getSystemConfig().getEncoding())); String secret = new String( new Base32().encode(RandomStringUtils.randomAlphanumeric(10).getBytes())); if (DEBUG) { DEBUGGER.debug("String: {}", secret); } String otpSalt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength()); if (StringUtils.isNotEmpty(otpSalt)) { boolean isSaltInserted = userSec.addOrUpdateSalt(userAccount.getGuid(), otpSalt, SaltType.OTP.name()); if (DEBUG) { DEBUGGER.debug("isSaltInserted: {}", isSaltInserted); } if ((!isSaltInserted)) { response.setRequestStatus(SecurityRequestStatus.FAILURE); return response; } boolean isComplete = userManager.modifyOtpSecret(userAccount.getUsername(), true, PasswordUtils.encryptText(secret, otpSalt, secBean.getConfigData().getSecurityConfig().getSecretAlgorithm(), secBean.getConfigData().getSecurityConfig().getIterations(), secBean.getConfigData().getSecurityConfig().getKeyBits(), secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(), secBean.getConfigData().getSecurityConfig().getEncryptionInstance(), secBean.getConfigData().getSystemConfig().getEncoding())); if (DEBUG) { DEBUGGER.debug("isComplete: {}", isComplete); } if (!(isComplete)) { response.setRequestStatus(SecurityRequestStatus.FAILURE); return response; } String qrCodeData = String.format(IAccountChangeProcessor.KEY_URI_FORMAT, userAccount.getUsername(), secret, request.getApplicationName(), secConfig.getOtpAlgorithm()); if (DEBUG) { DEBUGGER.debug("qrCodeData: {}", qrCodeData); } ByteArrayOutputStream qrCode = QRCode.from(qrCodeData.trim()).to(ImageType.PNG).stream(); if (DEBUG) { DEBUGGER.debug("ByteArrayOutputStream: {}", qrCode); } response.setSecret(secret); response.setQrCode(qrCode); response.setRequestStatus(SecurityRequestStatus.SUCCESS); } else { response.setRequestStatus(SecurityRequestStatus.FAILURE); } } else { ERROR_RECORDER.error("Unable to obtain configured user salt. Cannot continue"); response.setRequestStatus(SecurityRequestStatus.FAILURE); } } catch (SQLException sqx) { ERROR_RECORDER.error(sqx.getMessage(), sqx); throw new AccountChangeException(sqx.getMessage(), sqx); } catch (AuthenticatorException ax) { ERROR_RECORDER.error(ax.getMessage(), ax); throw new AccountChangeException(ax.getMessage(), ax); } catch (SecurityException sx) { ERROR_RECORDER.error(sx.getMessage(), sx); throw new SecurityException(sx.getMessage(), sx); } catch (UserManagementException umx) { ERROR_RECORDER.error(umx.getMessage(), umx); throw new SecurityException(umx.getMessage(), umx); } finally { // audit try { AuditEntry auditEntry = new AuditEntry(); auditEntry.setHostInfo(reqInfo); auditEntry.setAuditType(AuditType.CHANGEKEYS); auditEntry.setUserAccount(userAccount); auditEntry.setAuthorized(Boolean.TRUE); auditEntry.setApplicationId(request.getApplicationId()); auditEntry.setApplicationName(request.getApplicationName()); if (DEBUG) { DEBUGGER.debug("AuditEntry: {}", auditEntry); } AuditRequest auditRequest = new AuditRequest(); auditRequest.setAuditEntry(auditEntry); if (DEBUG) { DEBUGGER.debug("AuditRequest: {}", auditRequest); } auditor.auditRequest(auditRequest); } catch (AuditServiceException asx) { ERROR_RECORDER.error(asx.getMessage(), asx); } } return response; }
From source file:com.cws.esolutions.core.processors.impl.ServerManagementProcessorImplTest.java
@Test public void addNewServerAsDevVmgr() { String hostname = 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.250"); server.setOperHostName(hostname);//from www . j a v a2s . c om server.setMgmtIpAddress("192.168.11.250"); server.setMgmtHostName(hostname + "-mgt"); server.setBkIpAddress("172.16.10.55"); server.setBkHostName(hostname + "bak"); server.setNasIpAddress("172.15.10.55"); server.setNasHostName(hostname + "- nas"); server.setServerRegion(ServiceRegion.DEV); server.setServerStatus(ServerStatus.ONLINE); server.setServerType(ServerType.VIRTUALHOST); server.setServerComments("app server"); server.setAssignedEngineer(userAccount); server.setCpuType("AMD 1.0 GHz"); server.setCpuCount(1); server.setServerModel("Virtual Server"); server.setSerialNumber("1YU391"); server.setMgrUrl("https://192.168.10.250:10981/index.html"); 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:edu.duke.cabig.c3pr.webservice.integration.SubjectManagementWebServiceTest.java
/** * @return/*from w w w . ja v a2s .c om*/ */ protected BiologicEntityIdentifier createTertiaryBioEntityOrgId(boolean isPrimary) { OrganizationIdentifier orgId = new OrganizationIdentifier(); orgId.setIdentifier(II(TEST_ORG_ID)); orgId.setPrimaryIndicator(BL(true)); orgId.setTypeCode(CD(ORG_ID_TYPE_CTEP)); Organization org = new Organization(); org.getOrganizationIdentifier().add(orgId); BiologicEntityIdentifier bioId = new BiologicEntityIdentifier(); bioId.setAssigningOrganization(org); bioId.setIdentifier(II(RandomStringUtils.randomAlphanumeric(16))); bioId.setTypeCode(CD(ORG_ID_TYPE_COOP)); bioId.setEffectiveDateRange(IVLTSDateTime(NullFlavor.NI)); bioId.setPrimaryIndicator(isPrimary ? BL(true) : BL(false)); return bioId; }
From source file:com.cws.esolutions.core.processors.impl.ServerManagementProcessorImplTest.java
@Test public void addNewServerAsQaVmgr() { String hostname = 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.250"); server.setOperHostName(hostname);//from w ww. j a va 2s . c om server.setMgmtIpAddress("192.168.11.250"); server.setMgmtHostName(hostname + "-mgt"); server.setBkIpAddress("172.16.10.55"); server.setBkHostName(hostname + "bak"); server.setNasIpAddress("172.15.10.55"); server.setNasHostName(hostname + "- nas"); server.setServerRegion(ServiceRegion.QA); server.setServerStatus(ServerStatus.ONLINE); server.setServerType(ServerType.VIRTUALHOST); server.setServerComments("app server"); server.setAssignedEngineer(userAccount); server.setCpuType("AMD 1.0 GHz"); server.setCpuCount(1); server.setServerModel("Virtual Server"); server.setSerialNumber("1YU391"); server.setMgrUrl("https://192.168.10.250:10981/index.html"); 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()); } }