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.cws.esolutions.core.processors.impl.ServerManagementProcessorImplTest.java

@Test
public void addNewServerAsPrdVmgr() {
    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 ww  w.  j  a v  a 2  s .  co m*/
    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.PRD);
    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:com.duroty.application.mail.manager.PreferencesManager.java

/**
 * DOCUMENT ME!/*from   w  w w . ja  va  2  s.co m*/
 *
 * @param hsession DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param identityObj DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public String createIdentity(Session hsession, String repositoryName, IdentityObj identityObj)
        throws MailException {
    String randomString = null;

    try {
        Users user = getUser(hsession, repositoryName);

        randomString = RandomStringUtils.randomAlphanumeric(25);

        Identity identity = new Identity();
        identity.setIdeActive(false);
        identity.setIdeCode(randomString);
        identity.setIdeDefault(identityObj.isImportant());
        identity.setIdeEmail(identityObj.getEmail());
        identity.setIdeName(identityObj.getName());

        if (!StringUtils.isBlank(identityObj.getReplyTo())) {
            identity.setIdeReplyTo(identityObj.getReplyTo());
        } else {
            identity.setIdeReplyTo(identityObj.getName());
        }

        identity.setUsers(user);

        hsession.save(identity);

        hsession.flush();

        return randomString;
    } catch (Exception e) {
        throw new MailException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.flexive.tests.embedded.FxTreeTest.java

@Test(groups = { "ejb", "tree" })
public void testLongPaths() throws FxApplicationException {
    if ("Oracle".equals(FxContext.get().getDivisionData().getDbVendor()))
        return; //skip this test with oracle as the stored procedures currently can not pass parameters longer than 4k characters ...
    // push FQN path limits
    long firstFolderId = -1;
    long folderId = FxTreeNode.ROOT_NODE;
    try {//from   ww w  .  ja  va 2 s  . c o  m
        final List<String> paths = Lists.newArrayList();
        final List<String> captions = Lists.newArrayList();

        for (int i = 0; i < 10; i++) {
            final String path = RandomStringUtils.randomAlphanumeric(1024);
            final String caption = RandomStringUtils.randomAlphanumeric(1024);
            folderId = getTreeEngine().save(FxTreeNodeEdit.createNew(path).setLabel(new FxString(true, caption))
                    .setParentNodeId(folderId));
            if (firstFolderId == -1) {
                firstFolderId = folderId;
            }
            paths.add(path);
            captions.add(caption);
        }

        for (int i = 1; i < 10; i++) {
            getTreeEngine().getIdByPath(FxTreeMode.Edit, "/" + StringUtils.join(paths.subList(0, i), '/'));
            getTreeEngine().getIdByLabelPath(FxTreeMode.Edit, FxTreeNode.ROOT_NODE,
                    "/" + StringUtils.join(captions.subList(0, i), '/'));
        }
    } finally {
        getTreeEngine().remove(FxTreeMode.Edit, firstFolderId, FxTreeRemoveOp.Remove, true);
    }
}

From source file:edu.harvard.iq.dvn.core.web.subsetting.AnalysisPage.java

public void moveRecodeVariable(ActionEvent acev) {

    dbgLog.fine("***** moveRecodeVariable(): begins here *****");
    resetMsgMoveRecodeVarBttn();//w w w.  j a v  a 2 s. c o m
    if (listboxRecode.getValue() != null) {
        dbgLog.fine("listboxRecode.getValue=" + listboxRecode.getValue());
    } else {
        dbgLog.fine("listboxRecode.getValue is null");
    }
    if (selectedRecodeVariable != null) {
        dbgLog.fine("selectedRecodeVariable=" + selectedRecodeVariable);
    } else {
        dbgLog.fine("selectedRecodeVariable is null");
    }

    String varId = null;// getSelectedRecodeVariable();
    if (selectedRecodeVariable == null) {
        dbgLog.fine("recode varId selected from the binding=" + listboxRecode.getValue());
        varId = (String) listboxRecode.getValue();
    } else {
        dbgLog.fine("recode varId selected from the value=" + selectedRecodeVariable);
        varId = selectedRecodeVariable;
    }

    if (varId != null) {
        dbgLog.fine("Is this a recoded var?[" + isRecodedVar(varId) + "]");
    } else {
        dbgLog.fine("recode-variable id is still null");

        msgMoveRecodeVarBttn.setRendered(true);
        msgMoveRecodeVarBttn.setValue("Select one variable as a source variable;<br />"
                + "and click the start button to set up the recode table");
        return;
    }
    if (!groupPanelRecodeTableArea.isRendered()) {
        groupPanelRecodeTableArea.setRendered(true);
        groupPanelRecodeInstruction2.setRendered(true);
        groupPanelRecodeInstruction1.setRendered(false);
    }
    resetMsgSaveRecodeBttn();
    if (isRecodedVar(varId)) {
        // newly recoded var case
        dbgLog.fine("This a recoded var[" + varId + "]");

        List<Object> rvs = getRecodedVarSetRow(varId);
        if (rvs != null) {

            dbgLog.fine("requested newly recoded var was found");
            dbgLog.fine("new varName=" + rvs.get(0));
            dbgLog.fine("new varLabel=" + rvs.get(1));

            recallRecodedVariable(varId);

        } else {
            dbgLog.fine("requested newly recoded var was not found=" + varId);

        }

    } else {
        if (varId != null) {
            // set the name
            String varName = getVariableNamefromId(varId);
            dbgLog.fine("recode variable Name=" + varName);
            // setRecodeVariableName(varName);

            currentRecodeVariableName = varName;
            currentRecodeVariableId = varId;
            dbgLog.fine("currentRecodeVariableName=" + currentRecodeVariableName);
            dbgLog.fine("currentRecodeVariableId=" + currentRecodeVariableId);

            dbgLog.fine("recodeTargetVarName(b)=" + recodeTargetVarName.getValue());
            // set the label
            // setRecodeVariableLabel(getVariableLabelfromId(varId));
            String newNamePrefix = "new_" + RandomStringUtils.randomAlphanumeric(2) + "_";
            recodeTargetVarName.setValue(newNamePrefix + varName);
            recodeTargetVarLabel.setValue(newNamePrefix + getVariableLabelfromId(varId));
            dbgLog.fine("recodeTargetVarName(a)=" + recodeTargetVarName.getValue());
            // get value/label data and set them to the table
            DataVariable dv = getVariableById(varId);

            Collection<VariableCategory> catStat = dv.getCategories();
            recodeDataList.clear();
            recodeValueBox.setSubmittedValue(null);
            recodeTable.setRendered(false);
            dbgLog.fine("catStat.size=" + catStat.size());
            if (catStat.size() > 0) {
                // catStat exists
                dbgLog.fine("catStat exists");

                for (Iterator elc = catStat.iterator(); elc.hasNext();) {
                    VariableCategory dvcat = (VariableCategory) elc.next();
                    if ((dvcat.getValue().equals(".")) && (dvcat.getFrequency() == 0)) {
                        continue;
                    }
                    List<Object> rw = new ArrayList<Object>();

                    // 0th: Drop
                    rw.add(new Boolean(false));
                    // 1st: New value
                    rw.add(dvcat.getValue());
                    // 2nd: New value label
                    rw.add(dvcat.getLabel());
                    // conditions
                    rw.add(dvcat.getValue());
                    //
                    recodeDataList.add(rw);
                }

            } else {
                // no catStat, either sumStat or too-many-categories
                dbgLog.fine("catStat does not exists");
                dbgLog.fine("create a default two-row table");
                for (int i = 0; i < 2; i++) {
                    List<Object> rw = new ArrayList<Object>();
                    // 0th: Drop
                    rw.add(new Boolean(false));
                    // 1st: New value
                    rw.add("enter value here");
                    // 2nd: New value label
                    rw.add("enter label here");
                    // conditions
                    rw.add("enter a condition here");
                    //
                    recodeDataList.add(rw);
                }

            }
            dbgLog.fine("recodeDataList=" + recodeDataList);
            //recodeTable.setValue(recodeDataList);
            dbgLog.fine("recodeTable: value=" + recodeTable.getValue());
            // show the recodeTable
            dbgLog.fine("Number of rows in this Recode Table=" + recodeDataList.size());
            groupPanelRecodeTableHelp.setRendered(true);
            recodeValueBox.setRendered(true);
            //                recodeTable.setValue(recodeDataList);
            //                recodeTable.setRendered(true);

            addValueRangeBttn.setRendered(true);
            // keep this variable's Id
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
                    .put("currentRecodeVariableId", currentRecodeVariableId);
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
                    .put("currentRecodeVariableName", currentRecodeVariableName);
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("recodeDataList",
                    recodeDataList);
            //FacesContext.getCurrentInstance().renderResponse();
            recodeTable.setRendered(true);
            recodeTable.setValue(recodeDataList);
            recodeValueBox.setRendered(true);
        } else {
            dbgLog.fine("Variable to be recoded is null");
        }
    }
    dbgLog.fine("***** moveRecodeVariable(): ends here *****");

}

From source file:com.tasktop.c2c.server.tasks.tests.service.TaskServiceTest.java

License:asdf

private com.tasktop.c2c.server.tasks.domain.Component getMockComponent() throws ValidationException {
    com.tasktop.c2c.server.tasks.domain.Component testComponent = new com.tasktop.c2c.server.tasks.domain.Component();
    testComponent.setName(RandomStringUtils.randomAlphanumeric(24));
    testComponent.setDescription(RandomStringUtils.randomAlphanumeric(1024));
    testComponent.setInitialOwner(getCreatedMockTaskUserProfile());
    testComponent.setProduct(getCreatedMockDomainProduct());

    com.tasktop.c2c.server.tasks.domain.Component createdComponent = taskService.createComponent(testComponent);
    return createdComponent;
}

From source file:com.flexive.ejb.beans.AccountEngineBean.java

/**
 * {@inheritDoc}//from   w  ww .  ja v  a  2 s  .  co m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public String generateRestToken() throws FxApplicationException {
    final UserTicket ticket = FxContext.getUserTicket();

    if (ticket.isGuest()) {
        throw new FxUpdateException("ex.account.rest.generate.guest");
    }

    if (!ticket.isInRole(Role.RestApiAccess)) {
        throw new FxNoAccessException("ex.account.rest.generate.role", ticket.getLoginName(),
                Role.RestApiAccess.getName());
    }

    Connection con = null;
    PreparedStatement stmt = null;
    final DBStorage storage = StorageManager.getStorageImpl();
    try {
        con = Database.getDbConnection();
        stmt = con.prepareStatement(
                "UPDATE " + DatabaseConst.TBL_ACCOUNTS + " SET REST_TOKEN=?, REST_EXPIRES=? WHERE ID=?");

        final String token = RandomStringUtils.randomAlphanumeric(REST_TOKEN_LENGTH);
        stmt.setString(1, token);
        stmt.setLong(2, System.currentTimeMillis() + REST_TOKEN_EXPIRY);
        stmt.setLong(3, ticket.getUserId());

        stmt.executeUpdate();

        return token;
    } catch (SQLException e) {
        if (storage.isUniqueConstraintViolation(e)) {
            // try again
            Database.closeObjects(AccountEngineBean.class, con, stmt);
            generateRestToken();
        }
        throw new FxDbException(e);
    } finally {
        Database.closeObjects(AccountEngineBean.class, con, stmt);
    }
}

From source file:jp.co.ntts.vhut.logic.PrivateCloudLogic.java

/**
 * ID??//from  w  w w  . j  a va2  s.  c  o m
 * @see jp.co.ntts.vhut.logic.ICloudServiceLogic#changeUsersPassword(List<String>)
 */
@Override
public String changeUsersPassword(List<String> accountList) {

    ICommand icmd = this.commandFactory.newCommand(CommandOperation.CHANGE_USERS_PASSWORD, this.getCloudId());

    //? #7??
    String password = RandomStringUtils.randomAlphanumeric(7);
    //?
    this.issueCommand(CommandOperation.CHANGE_USERS_PASSWORD, (Serializable) accountList,
            (Serializable) password);

    return password;
}

From source file:com.tasktop.c2c.server.tasks.tests.service.TaskServiceTest.java

License:asdf

@Test
public void testUpdateRetrieveProductComponentAsigneeAndDelta() throws Exception {
    RepositoryConfiguration repo = taskService.getRepositoryContext();
    com.tasktop.c2c.server.tasks.domain.Task toCreate = getMockTask();
    toCreate.setProduct(repo.getProducts().get(0));
    toCreate.setComponent(repo.getComponents()
            .get(repo.getComponents().indexOf(toCreate.getProduct().getDefaultComponent())));
    com.tasktop.c2c.server.tasks.domain.Task created = taskService.createTask(toCreate);
    assertEquals(repo.getProducts().get(0), created.getProduct());
    assertEquals(repo.getProducts().get(0).getDefaultComponent(), created.getComponent());

    Date createdDiff = created.getModificationDate();
    com.tasktop.c2c.server.tasks.domain.Component testComponent = new com.tasktop.c2c.server.tasks.domain.Component();
    testComponent.setName(RandomStringUtils.randomAlphanumeric(24));
    testComponent.setDescription(RandomStringUtils.randomAlphanumeric(1024));
    testComponent.setProduct(getCreatedMockDomainProduct());

    com.tasktop.c2c.server.tasks.domain.Component createComponent = taskService.createComponent(testComponent);
    created.setProduct(testComponent.getProduct());
    created.setComponent(createComponent);
    created.setAssignee(repo.getUsers().get(0));
    Assert.assertNotSame(toCreate.getAssignee(), created.getAssignee());
    Thread.sleep(1000);// To get a later delta

    com.tasktop.c2c.server.tasks.domain.Task updated = taskService.updateTask(created);
    assertEquals(createComponent.getProduct(), updated.getProduct());
    assertEquals(createComponent, updated.getComponent());
    assertEquals(repo.getUsers().get(0), updated.getAssignee());
    assertTrue(createdDiff.before(updated.getModificationDate()));
}

From source file:edu.harvard.iq.dvn.core.study.StudyServiceBean.java

private void generateHandle(Metadata metadata, String protocol, String authority, boolean generateRandom) {
    String studyId = null;/*  w  ww  .ja  va 2s. c  om*/

    if (generateRandom) {
        do {
            studyId = RandomStringUtils.randomAlphanumeric(5);
        } while (!isUniqueStudyId(studyId, protocol, authority));

    } else {
        if (metadata.getStudyOtherIds().size() > 0) {
            studyId = metadata.getStudyOtherIds().get(0).getOtherId();
            if (!isValidStudyIdString(studyId)) {
                throw new EJBException("The Other ID (from DDI) was invalid.");
            }
        } else {
            throw new EJBException("No Other ID (from DDI) was available for generating a handle.");
        }
    }

    Study study = metadata.getStudyVersion().getStudy();
    study.setProtocol(protocol);
    study.setAuthority(authority);
    study.setStudyId(studyId);

}

From source file:it.fub.jardin.server.DbUtils.java

public void sendRegistrationMail(MailUtility mailUtility, RegistrationInfo regInfo, Integer output)
        throws HiddenException {

    String mitt = mailUtility.getMailSmtpSender();
    String oggetto = "Jardin Manager - conferma registrazione";
    String password = RandomStringUtils.randomAlphanumeric(RandomUtils.nextInt(13) + 8);
    String testo = "Jardin Manager\n\n Conferma della registrazione al portale per l'utente "
            + regInfo.getNome() + " " + regInfo.getCognome() + "\n\n" + "Credenziali primo accesso:\n\n"
            + "Username: " + regInfo.getUsername() + "\n";

    if (output == 2) {
        testo = testo + "Password: " + password;
        updateUserCreds(regInfo, password);

        // invio email al sysadmin
        String sysadminMailText1 = "Jardin Manager\n\n Effettuata nuova registrazione per l'utente "
                + regInfo.getNome() + " " + regInfo.getCognome() + "\n\n" + "Credenziali primo accesso:\n\n"
                + "Username: " + regInfo.getUsername() + "\n" + "Password: inviata tramite mail all'utente";

        try {/*ww w.j  a v a  2 s.  c  om*/

            mailUtility.sendMail(mailUtility.getMailSmtpSysadmin(), mitt,
                    "JardinManager - effettuata nuova registrazione con sola email", sysadminMailText1);
        } catch (MessagingException e) {
            e.printStackTrace();
            JardinLogger.error(regInfo.getUsername(),
                    "Invio email per nuova registrazione a sysadmin non riuscito!");
            JardinLogger.error(regInfo.getUsername(), "MessagingException: " + e.toString());
            // Log.info(e.toString());
        }
    } else if (output == 3) {
        testo = testo + "Prima parte della password: " + password;
        // la seconda parte della password  inviata tramite sms o telefonata
        String password2 = RandomStringUtils.randomAlphanumeric(RandomUtils.nextInt(13) + 8);

        JardinLogger.info(regInfo.getUsername(),
                "REGISTRAZIONE: all'utente " + regInfo.getUsername()
                        + " deve essere fornita la seconda parte della password: " + password2
                        + " (la prima parte  " + password + ")");

        updateUserCreds(regInfo, password + password2);

        testo = testo
                + "\n\n La seconda parte della password verr fornita tramite il numero di telefono indicato";

        // invio email al sysadmin
        String sysadminMailText2 = "Jardin Manager\n\n Effettuata nuova registrazione per l'utente"
                + regInfo.getNome() + " " + regInfo.getCognome() + "\n\n" + "Credenziali primo accesso:\n\n"
                + "Username: " + regInfo.getUsername() + "\n" + "Seconda parte della password: " + password2
                + "\n" + "(La prima parte della password  stata inviata tramite mail all'utente)\n\n"
                + "FORNIRE ALL'UTENTE LA SECONDA PARTE DELLA PASSWORD USANDO IL NUMERO DI TELEFONO "
                + regInfo.getTelefono() + "\n";

        try {

            mailUtility.sendMail(mailUtility.getMailSmtpSysadmin(), mitt,
                    "JardinManager - effettuata nuova registrazione con email e telefono", sysadminMailText2);
        } catch (MessagingException e) {
            e.printStackTrace();
            JardinLogger.error(regInfo.getUsername(),
                    "Invio email per nuova registrazione a sysadmin non riuscito!");
            JardinLogger.error(regInfo.getUsername(), "MessagingException: " + e.toString());
            // Log.info(e.toString());
        }
    }

    try {
        // invio mail all'utente
        mailUtility.sendMail(regInfo.getEmail(), mitt, oggetto, testo);

    } catch (MessagingException e) {
        e.printStackTrace();
        JardinLogger.error(regInfo.getUsername(), "Invio non riuscito!");
        JardinLogger.error(regInfo.getUsername(), "MessagingException: " + e.toString());
        // Log.info(e.toString());
    }

}