Example usage for org.apache.commons.lang RandomStringUtils randomAlphanumeric

List of usage examples for org.apache.commons.lang RandomStringUtils randomAlphanumeric

Introduction

In this page you can find the example usage for org.apache.commons.lang RandomStringUtils randomAlphanumeric.

Prototype

public static String randomAlphanumeric(int count) 

Source Link

Document

Creates a random string whose length is the number of characters specified.

Characters will be chosen from the set of alpha-numeric characters.

Usage

From source file:com.highcharts.export.controller.ExportController.java

public String createRandomFileName(String extension) {
    Path path = Paths.get(TempDir.outputDir.toString(),
            RandomStringUtils.randomAlphanumeric(8) + "." + extension);
    return path.toString();
}

From source file:com.cws.esolutions.core.processors.impl.ServerManagementProcessorImplTest.java

@Test
public void addServerAsQaWebServer() {
    for (int x = 0; x < 4; x++) {
        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.QA);
        server.setServerStatus(ServerStatus.ONLINE);
        server.setServerType(ServerType.WEBSERVER);
        server.setServerComments("app server");
        server.setAssignedEngineer(userAccount);
        server.setCpuType("AMD 1.0 GHz");
        server.setCpuCount(1);//from  w w  w .j  av a2s .  co  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.aurel.track.admin.user.person.PersonBL.java

/**
 * Creates a new user//from w w w. j a v a2 s .  c  o m
 * @param username
 * @param firstName
 * @param lastName
 * @param email
 * @return
 */
public static TPersonBean createMsProjectImportNewUser(String username, String firstName, String lastName,
        String email) {
    TPersonBean personBean = new TPersonBean();
    personBean.setLoginName(username);
    personBean.setFirstName(firstName);
    personBean.setLastName(lastName);
    personBean.setEmail(email);
    String pass = RandomStringUtils.randomAlphanumeric(8);
    personBean.setPasswd(pass);
    personBean.setPrefEmailType("HTML");
    personBean.setPrefLocale("");
    personBean.setEnableQueryLayout(true);
    personBean.setUserLevel(TPersonBean.USERLEVEL.FULL);
    personBean.setDepartmentID(DepartmentBL.getDefaultDepartment());
    return personBean;
}

From source file:com.cws.esolutions.security.processors.impl.AccountResetProcessorImpl.java

/**
 * @see com.cws.esolutions.security.processors.interfaces.IAccountResetProcessor#resetUserPassword(com.cws.esolutions.security.processors.dto.AccountResetRequest)
 *//*from   www  . j  a v a 2  s  . c  om*/
public AccountResetResponse resetUserPassword(final AccountResetRequest request) throws AccountResetException {
    final String methodName = IAccountResetProcessor.CNAME
            + "#resetUserPassword(final AccountResetRequest request) throws AccountResetException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("AccountResetRequest: {}", request);
    }

    AccountResetResponse response = new AccountResetResponse();

    final Calendar calendar = Calendar.getInstance();
    final RequestHostInfo reqInfo = request.getHostInfo();
    final UserAccount userAccount = request.getUserAccount();

    calendar.add(Calendar.DATE, secConfig.getPasswordExpiration());

    if (DEBUG) {
        DEBUGGER.debug("Calendar: {}", calendar);
        DEBUGGER.debug("RequestHostInfo: {}", reqInfo);
        DEBUGGER.debug("UserAccount: {}", userAccount);
    }

    try {
        String resetId = RandomStringUtils.randomAlphanumeric(secConfig.getResetIdLength());
        String smsReset = RandomStringUtils.randomAlphanumeric(secConfig.getSmsCodeLength());

        if (StringUtils.isNotEmpty(resetId)) {
            boolean isComplete = userSec.insertResetData(userAccount.getGuid(), resetId,
                    ((secConfig.getSmsResetEnabled()) ? smsReset : null));

            if (DEBUG) {
                DEBUGGER.debug("isComplete: {}", isComplete);
            }

            if (isComplete) {
                // load the user account for the email response
                List<Object> userData = userManager.loadUserAccount(userAccount.getGuid());

                if (DEBUG) {
                    DEBUGGER.debug("UserData: {}", userData);
                }

                if ((userData != null) && (!(userData.isEmpty()))) {
                    UserAccount responseAccount = new UserAccount();
                    responseAccount.setGuid((String) userData.get(0));
                    responseAccount.setUsername((String) userData.get(1));
                    responseAccount.setGivenName((String) userData.get(6));
                    responseAccount.setSurname((String) userData.get(7));
                    responseAccount.setDisplayName((String) userData.get(8));
                    responseAccount.setEmailAddr((String) userData.get(9));
                    responseAccount.setPagerNumber((String) userData.get(10));
                    responseAccount.setTelephoneNumber((String) userData.get(11));

                    if (DEBUG) {
                        DEBUGGER.debug("UserAccount: {}", responseAccount);
                    }

                    response.setResetId(resetId);
                    response.setSmsCode(((secConfig.getSmsResetEnabled()) ? smsReset : null));
                    response.setUserAccount(responseAccount);
                    response.setRequestStatus(SecurityRequestStatus.SUCCESS);
                } else {
                    ERROR_RECORDER.error(
                            "Failed to locate user account in authentication repository. Cannot continue.");

                    response.setRequestStatus(SecurityRequestStatus.FAILURE);
                }
            } else {
                ERROR_RECORDER.error("Unable to insert password identifier into database. Cannot continue.");

                response.setRequestStatus(SecurityRequestStatus.FAILURE);
            }
        } else {
            ERROR_RECORDER.error("Unable to generate a unique identifier. Cannot continue.");

            response.setRequestStatus(SecurityRequestStatus.FAILURE);
        }
    } catch (SQLException sqx) {
        ERROR_RECORDER.error(sqx.getMessage(), sqx);

        throw new AccountResetException(sqx.getMessage(), sqx);
    } catch (UserManagementException umx) {
        ERROR_RECORDER.error(umx.getMessage(), umx);

        throw new AccountResetException(umx.getMessage(), umx);
    } finally {
        // audit
        try {
            AuditEntry auditEntry = new AuditEntry();
            auditEntry.setHostInfo(reqInfo);
            auditEntry.setAuditType(AuditType.RESETPASS);
            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.google.cloud.bigtable.hbase.TestPut.java

@Test
@Category(KnownGap.class)
public void testMultiplePutsOneBadSameRow() throws Exception {
    final int numberOfGoodPuts = 100;
    byte[] rowKey = Bytes.toBytes("testrow-" + RandomStringUtils.randomAlphanumeric(8));
    byte[][] goodkeys = new byte[numberOfGoodPuts][];
    for (int i = 0; i < numberOfGoodPuts; ++i) {
        goodkeys[i] = rowKey;/*from  w  w w .  j a v a  2s  .  c o  m*/
    }
    multiplePutsOneBad(numberOfGoodPuts, goodkeys, rowKey);
    Get get = new Get(rowKey);
    Table table = getConnection().getTable(TABLE_NAME);
    Result whatsLeft = table.get(get);
    Assert.assertEquals("Same row, all other puts accepted", numberOfGoodPuts, whatsLeft.size());
    table.close();
}

From source file:com.exalttech.trex.util.Util.java

/**
 * Generate and return random value/*from  ww w.  j av a  2  s .  c o  m*/
 *
 * @param length
 * @return
 */
public static String getRandomID(int length) {
    return RandomStringUtils.randomAlphanumeric(length).toUpperCase();
}

From source file:com.redhat.rhn.testing.TestUtils.java

/**
 * Return a random 13 letter string.  Useful for creating unique
 * string labels/names in your tests.// w  w  w  .jav  a  2s  . co m
 * @return String that is 13 chars long and alphanumeric
 */
public static String randomString() {
    return RandomStringUtils.randomAlphanumeric(13);
}

From source file:com.google.cloud.bigtable.hbase.TestPut.java

@Test
@Category(KnownGap.class)
public void testMultiplePutsOneBadDiffRows() throws Exception {
    final int numberOfGoodPuts = 100;
    byte[] badkey = Bytes.toBytes("testrow-" + RandomStringUtils.randomAlphanumeric(8));
    byte[][] goodkeys = new byte[numberOfGoodPuts][];
    for (int i = 0; i < numberOfGoodPuts; ++i) {
        goodkeys[i] = Bytes.toBytes("testrow-" + RandomStringUtils.randomAlphanumeric(8));
        assert !Arrays.equals(badkey, goodkeys[i]);
    }//w  ww  .jav a 2s .c  o m
    multiplePutsOneBad(numberOfGoodPuts, goodkeys, badkey);

    List<Get> gets = new ArrayList<Get>();
    for (int i = 0; i < numberOfGoodPuts; ++i) {
        Get get = new Get(goodkeys[i]);
        gets.add(get);
    }
    Table table = getConnection().getTable(TABLE_NAME);
    Result[] whatsLeft = table.get(gets);
    int cellCount = 0;
    for (Result result : whatsLeft) {
        cellCount += result.size();
    }
    Assert.assertEquals("Different row, all other puts accepted", numberOfGoodPuts, cellCount);
    table.close();
}

From source file:com.cws.esolutions.security.processors.impl.AccountChangeProcessorImpl.java

/**
 * @see com.cws.esolutions.security.processors.interfaces.IAccountChangeProcessor#changeUserPassword(com.cws.esolutions.security.processors.dto.AccountChangeRequest)
 *///from  w  ww.j a  v  a 2 s. c o m
public AccountChangeResponse changeUserPassword(final AccountChangeRequest request)
        throws AccountChangeException {
    final String methodName = IAccountChangeProcessor.CNAME
            + "#changeUserPassword(final AccountChangeRequest request) throws AccountChangeException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("AccountChangeRequest: {}", request);
    }

    // List<String> authList = null;
    String currentPassword = null;
    AccountChangeResponse response = new AccountChangeResponse();

    final Calendar calendar = Calendar.getInstance();
    final RequestHostInfo reqInfo = request.getHostInfo();
    final UserAccount requestor = request.getRequestor();
    final UserAccount userAccount = request.getUserAccount();
    final AuthenticationData reqSecurity = request.getUserSecurity();
    final String newUserSalt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength());

    calendar.add(Calendar.DATE, secConfig.getPasswordExpiration());

    if (DEBUG) {
        DEBUGGER.debug("Calendar: {}", calendar);
        DEBUGGER.debug("RequestHostInfo: {}", reqInfo);
        DEBUGGER.debug("UserAccount: {}", requestor);
        DEBUGGER.debug("UserAccount: {}", userAccount);
    }

    // ok, first things first. if this is an administrative reset, make sure the requesting user
    // is authorized to perform the action.
    if (!(StringUtils.equals(userAccount.getGuid(), requestor.getGuid()))) {
        // requesting user is not the same as the user being reset. no authorization here,
        // no one is allowed to change user security but the owning user
        response.setRequestStatus(SecurityRequestStatus.UNAUTHORIZED);

        return response;
    }

    try {
        // otherwise, keep going
        // make sure the new password isnt the same as the existing
        if (StringUtils.equals(reqSecurity.getNewPassword(), reqSecurity.getPassword())) {
            throw new AccountChangeException("The new password MUST differ from the existing password.");
        } else if ((reqSecurity.getNewPassword().length() < secConfig.getPasswordMinLength()) // less than minimum
                || (reqSecurity.getNewPassword().length() > secConfig.getPasswordMaxLength())) // greater than maximum
        {
            // password doesnt meet requirements, is either too short or too long
            throw new AccountChangeException(
                    "The chosen password does not meet the configured length requirements.");
        } else {
            if (!(request.isReset())) {
                // ok, authenticate first
                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()));
                }
            }

            if (StringUtils.isNotEmpty(newUserSalt)) {
                // get rollback information in case something breaks...
                // we already have the existing expiry and password, all we really need to get here is the salt.
                String existingSalt = userSec.getUserSalt(userAccount.getGuid(), SaltType.LOGON.name());

                if (StringUtils.isNotEmpty(existingSalt)) {
                    // good, move forward
                    // put the new salt in the database
                    boolean isComplete = userSec.addOrUpdateSalt(userAccount.getGuid(), newUserSalt,
                            SaltType.LOGON.name());

                    if (DEBUG) {
                        DEBUGGER.debug("isComplete: {}", isComplete);
                    }

                    if (isComplete) {
                        // make the modification in the user repository
                        userManager.modifyUserPassword(userAccount.getGuid(),
                                PasswordUtils.encryptText(reqSecurity.getNewPassword(), newUserSalt,
                                        secConfig.getAuthAlgorithm(), secConfig.getIterations(),
                                        secBean.getConfigData().getSystemConfig().getEncoding()));

                        if (DEBUG) {
                            DEBUGGER.debug("isComplete: {}", isComplete);
                        }

                        if (isComplete) {
                            if ((userAccount.getStatus() == LoginStatus.EXPIRED)
                                    || (userAccount.getStatus() == LoginStatus.RESET)) {
                                // update the account
                                userAccount.setStatus(LoginStatus.SUCCESS);
                            }

                            response.setUserAccount(userAccount);
                            response.setRequestStatus(SecurityRequestStatus.SUCCESS);
                        } else {
                            if (!(request.isReset())) {
                                // something failed. we're going to undo what we did in the user
                                // repository, because we couldnt update the salt value. if we don't
                                // undo it then the user will never be able to login without admin
                                // intervention
                                boolean isBackedOut = userManager.modifyUserPassword(userAccount.getUsername(),
                                        currentPassword);

                                if (!(isBackedOut)) {
                                    throw new AccountChangeException(
                                            "Failed to modify the user account and unable to revert to existing state.");
                                }
                            }

                            response.setRequestStatus(SecurityRequestStatus.FAILURE);
                        }
                    } else {
                        response.setRequestStatus(SecurityRequestStatus.FAILURE);
                    }
                } else {
                    throw new AccountChangeException(
                            "Unable to obtain existing salt value from datastore. Cannot continue.");
                }
            } else {
                throw new AccountChangeException("Unable to generate new salt for provided user account.");
            }
        }
    } catch (SQLException sqx) {
        ERROR_RECORDER.error(sqx.getMessage(), sqx);

        throw new AccountChangeException(sqx.getMessage(), sqx);
    } catch (UserManagementException umx) {
        ERROR_RECORDER.error(umx.getMessage(), umx);

        throw new AccountChangeException(umx.getMessage(), umx);
    } 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 AccountChangeException(sx.getMessage(), sx);
    } finally {
        // audit
        try {
            AuditEntry auditEntry = new AuditEntry();
            auditEntry.setHostInfo(reqInfo);
            auditEntry.setAuditType(AuditType.CHANGEPASS);
            auditEntry.setUserAccount(requestor);
            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:de.thm.arsnova.services.UserService.java

@Override
public void initiatePasswordReset(String username) {
    DbUser dbUser = databaseDao.getUser(username);
    if (null == dbUser) {
        throw new NotFoundException();
    }//from w w w  .  ja v a  2 s  .co m
    if (System.currentTimeMillis() < dbUser.getPasswordResetTime() + REPEATED_PASSWORD_RESET_DELAY_MS) {
        throw new BadRequestException();
    }

    dbUser.setPasswordResetKey(RandomStringUtils.randomAlphanumeric(32));
    dbUser.setPasswordResetTime(System.currentTimeMillis());
    databaseDao.createOrUpdateUser(dbUser);

    String resetPasswordUrl;
    try {
        resetPasswordUrl = MessageFormat.format("{0}{1}/{2}?action=resetpassword&username={3}&key={4}", rootUrl,
                customizationPath, resetPasswordPath, UriUtils.encodeQueryParam(dbUser.getUsername(), "UTF-8"),
                dbUser.getPasswordResetKey());
    } catch (UnsupportedEncodingException e1) {
        LOGGER.error(e1.getMessage());

        return;
    }

    sendEmail(dbUser, resetPasswordMailSubject, MessageFormat.format(resetPasswordMailBody, resetPasswordUrl));
}