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:apim.restful.importexport.APIService.java

/**
 * This service exports an API from API Manager for a given API ID
 * Meta information, API icon, documentation, WSDL and sequences are exported
 * This service generates a zipped archive which contains all the above mentioned resources
 * for a given API//from  w ww  .j  av  a 2  s  .  c o m
 *
 * @param name         Name of the API that needs to be exported
 * @param version      Version of the API that needs to be exported
 * @param providerName Provider name of the API that needs to be exported
 * @return Zipped API as the response to the service call
 */
@GET
@Path("/export-api")
@Produces("application/zip")
public Response exportAPI(@QueryParam("name") String name, @QueryParam("version") String version,
        @QueryParam("provider") String providerName, @Context HttpHeaders httpHeaders) {

    String userName;
    if (name == null || version == null || providerName == null) {
        log.error("Invalid API Information ");

        return Response.status(Response.Status.BAD_REQUEST).entity("Invalid API Information")
                .type(MediaType.APPLICATION_JSON).build();
    }
    log.info("Retrieving API for API-Id : " + name + "-" + version + "-" + providerName);
    APIIdentifier apiIdentifier;
    try {

        Response authorizationResponse = AuthenticatorUtil.authorizeUser(httpHeaders);
        if (!(Response.Status.OK.getStatusCode() == authorizationResponse.getStatus())) {
            return authorizationResponse;
        }

        userName = AuthenticatorUtil.getAuthenticatedUserName();
        //provider names with @ signs are only accepted
        String apiDomain = MultitenantUtils.getTenantDomain(providerName);
        String apiRequesterDomain = MultitenantUtils.getTenantDomain(userName);
        //Allows to export APIs created only in current tenant domain
        if (!apiDomain.equals(apiRequesterDomain)) {
            //not authorized to export requested API
            log.error("Not authorized to " + "export API :" + name + "-" + version + "-" + providerName);
            return Response.status(Response.Status.FORBIDDEN)
                    .entity("Not authorized to export API :" + name + "-" + version + "-" + providerName)
                    .type(MediaType.APPLICATION_JSON).build();
        }

        apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(providerName), name, version);

        //create temp location for storing API data to generate archive
        String currentDirectory = System.getProperty(APIImportExportConstants.TEMP_DIR);
        String createdFolders = File.separator
                + RandomStringUtils.randomAlphanumeric(APIImportExportConstants.TEMP_FILENAME_LENGTH)
                + File.separator;
        File exportFolder = new File(currentDirectory + createdFolders);
        APIExportUtil.createDirectory(exportFolder.getPath());
        String archiveBasePath = exportFolder.toString();

        APIExportUtil.setArchiveBasePath(archiveBasePath);

        Response apiResourceRetrievalResponse = APIExportUtil.retrieveApiToExport(apiIdentifier, userName);

        //Retrieve resources : thumbnail, meta information, wsdl, sequences and documents
        // available for the exporting API
        if (!(Response.Status.OK.getStatusCode() == apiResourceRetrievalResponse.getStatus())) {
            return apiResourceRetrievalResponse;
        }

        ArchiveGeneratorUtil.archiveDirectory(archiveBasePath);

        log.info("API" + name + "-" + version + " exported successfully");

        File file = new File(archiveBasePath + ".zip");
        Response.ResponseBuilder response = Response.ok(file);
        response.header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
        return response.build();

    } catch (APIExportException e) {
        log.error("APIExportException occurred while exporting ", e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Internal Server Error")
                .type(MediaType.APPLICATION_JSON).build();
    }

}

From source file:net.nelz.simplesm.test.dao.TestDAOImpl.java

@ReadThroughMultiCache(namespace = "Delta", expiration = 1000)
public List<String> getRandomStrings(@ParameterValueKeyProvider final List<Long> keys) {
    try {//from   w  w  w  .  ja  v a2s  .  co  m
        Thread.sleep(500);
    } catch (InterruptedException ex) {
    }
    final String series = RandomStringUtils.randomAlphabetic(6);
    final List<String> results = new ArrayList<String>(keys.size());
    for (final Long key : keys) {
        results.add(series + "-" + key.toString() + "-"
                + RandomStringUtils.randomAlphanumeric(25 + RandomUtils.nextInt(30)));
    }
    return results;
}

From source file:com.spotify.docker.client.messages.AuthConfigTest.java

@Test
public void testFromDockerConfig_MissingConfigFile() throws Exception {
    final Path randomPath = Paths.get(RandomStringUtils.randomAlphanumeric(16) + ".json");
    expectedException.expect(FileNotFoundException.class);
    AuthConfig.fromDockerConfig(randomPath).build();
}

From source file:com.redhat.rhn.frontend.xmlrpc.configchannel.test.ConfigChannelHandlerTest.java

public void testUpdate() {
    ConfigChannel cc = handler.create(admin, LABEL, NAME, DESCRIPTION);
    String newName = NAME + TestUtils.randomString();
    String desc = DESCRIPTION + TestUtils.randomString();
    try {//from  w w w .  j  a va 2 s  . c o  m
        handler.update(regular, LABEL, newName, desc);
        String msg = "Needs to be a config admin/have access.. " + "perm error not detected.";
        fail(msg);
    } catch (Exception e) {
        //Cool perm error!
    }
    cc = handler.update(admin, LABEL, newName, desc);
    assertEquals(LABEL, cc.getLabel());
    assertEquals(newName, cc.getName());
    assertEquals(desc, cc.getDescription());
    assertEquals(admin.getOrg(), cc.getOrg());
    try {
        String name = RandomStringUtils.randomAlphanumeric(ConfigChannelCreationHelper.MAX_NAME_LENGTH + 1);
        cc = handler.update(admin, LABEL, name, DESCRIPTION);
        String msg = "Max length reached for name- not detected :(";
        fail(msg);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        //Cool invalid check works!..
    }
}

From source file:com.duroty.application.admin.manager.AdminManager.java

/**
 * DOCUMENT ME!//from w  w w  .j av a 2  s.  c o m
 *
 * @param hsession DOCUMENT ME!
 * @param userObj DOCUMENT ME!
 *
 * @throws AdminException DOCUMENT ME!
 */
public void addUser(Session hsession, UserObj userObj) throws AdminException {
    try {
        Users users = new Users();
        users.setUseActive(userObj.isActive());
        users.setUseEmail(userObj.getEmail());
        users.setUseLanguage(userObj.getLanguage());
        users.setUseName(userObj.getName());
        users.setUsePassword(userObj.getPassword());
        users.setUseRegisterDate(userObj.getRegisterDate());
        users.setUseUsername(userObj.getUsername());

        if ((userObj.getRoles() != null) && (userObj.getRoles().length > 0)) {
            Criteria crit = hsession.createCriteria(Roles.class);
            crit.add(Restrictions.in("rolIdint", userObj.getRoles()));

            ScrollableResults scroll = crit.scroll();

            while (scroll.next()) {
                UserRole userRole = new UserRole(new UserRoleId(users, (Roles) scroll.get(0)));
                users.addUserRole(userRole);
            }
        }

        hsession.save(users);
        hsession.flush();

        MailPreferences mailPreferences = new MailPreferences();
        mailPreferences.setUsers(users);
        mailPreferences.setMaprHtmlMessage(userObj.isHtmlMessages());
        mailPreferences.setMaprMessagesByPage(userObj.getMessagesByPage());
        mailPreferences.setMaprQuotaSize(userObj.getQuotaSize());

        if (userObj.getSignature() != null) {
            mailPreferences.setMaprSignature("\n" + userObj.getSignature().replaceAll("'", "\\\\'"));
        }

        if (userObj.isSpamTolerance()) {
            mailPreferences.setMaprSpamTolerance(100);
        } else {
            mailPreferences.setMaprSpamTolerance(-1);
        }

        mailPreferences.setMaprVacationActive(userObj.isVactionActive());
        mailPreferences.setMaprVacationBody(userObj.getVacationBody());
        mailPreferences.setMaprVacationSubject(userObj.getVacationSubject());

        hsession.save(mailPreferences);
        hsession.flush();

        Identity identity = new Identity();
        identity.setIdeActive(true);
        identity.setIdeCode(RandomStringUtils.randomAlphanumeric(25));
        identity.setIdeDefault(true);
        identity.setIdeEmail(userObj.getEmailIdentity());
        identity.setIdeName(userObj.getName());
        identity.setIdeReplyTo(userObj.getEmailIdentity());
        identity.setUsers(users);

        hsession.save(identity);
        hsession.flush();
    } catch (Exception ex) {
        throw new AdminException(ex);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.flexive.tests.embedded.persistence.ContentSecurityTest.java

@BeforeClass
public void setup() throws FxApplicationException, FxLoginFailedException, FxAccountInUseException {
    user = TestUsers.createUser("SecurityTestUser", Role.BackendAccess);
    final UserGroupEngine ug = EJBLookup.getUserGroupEngine();
    final ACLEngine ae = getAclEngine();
    long mandator = TestUsers.getTestMandator();
    FxContext.get().runAsSystem();/*w w  w . ja  va  2  s. c o m*/
    try {
        user.createUser(TestUsers.getTestMandator(), TestUsers.getEnglishLanguageId());
        login(user);
        groups = new UserGroup[26];
        for (int i = 0; i < 26; i++)
            groups[i] = ug.load(ug.create("UG" + (i + 1), "#FFFFFF", mandator));
        typeACL = ae.load(ae.create("TYPE_" + RandomStringUtils.randomAlphanumeric(5), new FxString("Type ACL"),
                mandator, "#FFFFFF", "Type ACL", ACLCategory.STRUCTURE));
        instanceACL = ae.load(ae.create("INSTANCE_" + RandomStringUtils.randomAlphanumeric(5),
                new FxString("Instance ACL"), mandator, "#FFFFFF", "Instance ACL", ACLCategory.INSTANCE));
        property1ACL = ae.load(ae.create("PROPERTY1_" + RandomStringUtils.randomAlphanumeric(5),
                new FxString("Property1 ACL"), mandator, "#FFFFFF", "Property1 ACL", ACLCategory.STRUCTURE));
        property2ACL = ae.load(ae.create("PROPERTY2_" + RandomStringUtils.randomAlphanumeric(5),
                new FxString("Property2 ACL"), mandator, "#FFFFFF", "Property2 ACL", ACLCategory.STRUCTURE));
        editACL = ae.load(ae.create("EDIT_" + RandomStringUtils.randomAlphanumeric(5), new FxString("Edit ACL"),
                mandator, "#FFFFFF", "Edit ACL", ACLCategory.WORKFLOW));
        liveACL = ae.load(ae.create("LIVE_" + RandomStringUtils.randomAlphanumeric(5), new FxString("Live ACL"),
                mandator, "#FFFFFF", "Live ACL", ACLCategory.WORKFLOW));

        WorkflowEdit wfEdit = WorkflowEdit
                .createNew("Security_Workflow_" + RandomStringUtils.randomAlphanumeric(5));
        wfEdit.getSteps().add(StepEdit.createNew(StepDefinition.EDIT_STEP_ID));
        wfEdit.getSteps().add(StepEdit.createNew(StepDefinition.LIVE_STEP_ID));
        long wf = EJBLookup.getWorkflowEngine().create(wfEdit);
        workflow = CacheAdmin.getEnvironment().getWorkflow(wf);
        Step edit, live;
        assertEquals(workflow.getSteps().size(), 2);
        if (workflow.getSteps().get(0).isLiveStep()) {
            live = workflow.getSteps().get(0);
            edit = workflow.getSteps().get(1);
        } else {
            live = workflow.getSteps().get(1);
            edit = workflow.getSteps().get(0);
        }
        EJBLookup.getWorkflowStepEngine().updateStep(edit.getId(), editACL.getId(), 1);
        EJBLookup.getWorkflowStepEngine().updateStep(live.getId(), liveACL.getId(), 1);
        workflow = CacheAdmin.getEnvironment().getWorkflow(wf);
        //create routes for the route test
        wfEdit = workflow.asEditable();
        wfEdit.getRoutes().add(RouteEdit.createNew(getGroup(25), edit.getId(), live.getId()));
        wfEdit.getRoutes().add(RouteEdit.createNew(getGroup(26), live.getId(), edit.getId()));
        EJBLookup.getWorkflowEngine().update(wfEdit);
        workflow = CacheAdmin.getEnvironment().getWorkflow(wf);
        FxTypeEdit te = FxTypeEdit.createNew("SecurityTest");
        te.setWorkflow(workflow);
        te.setACL(typeACL);
        long typeId = EJBLookup.getTypeEngine().save(te);
        EJBLookup.getAssignmentEngine().createProperty(typeId,
                FxPropertyEdit
                        .createNew("P1", new FxString("Property 1"), new FxString("Hint"),
                                FxMultiplicity.MULT_1_1, property1ACL, FxDataType.String1024)
                        .setMultiLang(false),
                "/");
        EJBLookup.getAssignmentEngine().createProperty(typeId,
                FxPropertyEdit
                        .createNew("P2", new FxString("Property 2"), new FxString("Hint"),
                                FxMultiplicity.MULT_0_1, property2ACL, FxDataType.String1024)
                        .setMultiLang(false),
                "/");
        type = CacheAdmin.getEnvironment().getType(typeId);
    } finally {
        FxContext.get().stopRunAsSystem();
    }
}

From source file:com.its.web.services.LicensesService.java

public String generatePassword() {

    StringBuffer password = new StringBuffer(20);
    int next = RandomUtils.nextInt(13) + 8;
    password.append(RandomStringUtils.randomAlphanumeric(next));
    return password.toString();
}

From source file:com.xwiki.authentication.saml.XWikiSAMLAuthenticator.java

public void showLogin(XWikiContext context) throws XWikiException {
    XWikiRequest request = context.getRequest();
    XWikiResponse response = context.getResponse();

    try {//from w  w  w  .  j a  v  a2s  . c o  m
        DefaultBootstrap.bootstrap();
    } catch (ConfigurationException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Failed to bootstrap saml module");
        }
        throw new XWikiException(XWikiException.MODULE_XWIKI_USER, XWikiException.ERROR_XWIKI_USER_INIT,
                "Failed to bootstrap saml module");
    }
    XMLObjectBuilderFactory builderFactory = org.opensaml.Configuration.getBuilderFactory();

    // Generate ID
    String randId = RandomStringUtils.randomAlphanumeric(42);
    if (LOG.isDebugEnabled())
        LOG.debug("Random ID: " + randId);

    String sourceurl = request.getParameter("xredirect");
    if (sourceurl == null) {
        if (context.getAction().startsWith("login"))
            sourceurl = context.getWiki().getURL("Main.WebHome", "view", context);
        else {
            context.getWiki();
            sourceurl = XWiki.getRequestURL(request).toString();
        }
    }

    request.getSession().setAttribute("saml_url", sourceurl);
    request.getSession().setAttribute("saml_id", randId);

    //Create an issuer Object
    IssuerBuilder issuerBuilder = new IssuerBuilder();
    Issuer issuer = issuerBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:assertion", "Issuer", "samlp");
    issuer.setValue(getSAMLIssuer(context));

    //Create NameIDPolicy
    NameIDPolicyBuilder nameIdPolicyBuilder = new NameIDPolicyBuilder();
    NameIDPolicy nameIdPolicy = nameIdPolicyBuilder.buildObject();
    nameIdPolicy.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent");
    nameIdPolicy.setSPNameQualifier(getSAMLNameQualifier(context));
    nameIdPolicy.setAllowCreate(true);

    //Create AuthnContextClassRef
    AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
    AuthnContextClassRef authnContextClassRef = authnContextClassRefBuilder
            .buildObject("urn:oasis:names:tc:SAML:2.0:assertion", "AuthnContextClassRef", "saml");
    authnContextClassRef
            .setAuthnContextClassRef("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");

    //Create RequestedAuthnContext
    RequestedAuthnContextBuilder requestedAuthnContextBuilder = new RequestedAuthnContextBuilder();
    RequestedAuthnContext requestedAuthnContext = requestedAuthnContextBuilder.buildObject();
    requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
    requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);

    DateTime issueInstant = new DateTime();
    AuthnRequestBuilder authRequestBuilder = new AuthnRequestBuilder();
    AuthnRequest authRequest = authRequestBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:protocol",
            "AuthnRequest", "samlp");
    authRequest.setForceAuthn(false);
    authRequest.setIsPassive(false);
    authRequest.setIssueInstant(issueInstant);
    authRequest.setProtocolBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
    authRequest.setAssertionConsumerServiceURL(getSAMLAuthenticatorURL(context));
    authRequest.setIssuer(issuer);
    authRequest.setNameIDPolicy(nameIdPolicy);
    authRequest.setRequestedAuthnContext(requestedAuthnContext);
    authRequest.setID(randId);
    authRequest.setVersion(SAMLVersion.VERSION_20);
    String stringRep = authRequest.toString();

    if (LOG.isDebugEnabled()) {
        LOG.debug("New AuthnRequestImpl: " + stringRep);
        LOG.debug("Assertion Consumer Service URL: " + authRequest.getAssertionConsumerServiceURL());
    }

    // Now we must build our representation to put into the html form to be submitted to the idp
    MarshallerFactory mfact = org.opensaml.Configuration.getMarshallerFactory();
    Marshaller marshaller = (Marshaller) mfact.getMarshaller(authRequest);
    if (marshaller == null) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Failed to get marshaller for " + authRequest);
        }
        throw new XWikiException(XWikiException.MODULE_XWIKI_USER, XWikiException.ERROR_XWIKI_USER_INIT,
                "Failed to get marshaller for " + authRequest);
    } else {
        Element authDOM;
        String samlRequest = "";
        try {
            authDOM = marshaller.marshall(authRequest);
            StringWriter rspWrt = new StringWriter();
            XMLHelper.writeNode(authDOM, rspWrt);
            String messageXML = rspWrt.toString();
            Deflater deflater = new Deflater(Deflater.DEFLATED, true);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream,
                    deflater);
            deflaterOutputStream.write(messageXML.getBytes());
            deflaterOutputStream.close();
            samlRequest = Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES);
            String outputString = new String(byteArrayOutputStream.toByteArray());
            samlRequest = URLEncoder.encode(samlRequest);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Converted AuthRequest: " + messageXML);
                // LOG.debug("samlRequest: " + samlRequest);
            }
        } catch (Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Failed to marshaller request for " + authRequest);
            }
            throw new XWikiException(XWikiException.MODULE_XWIKI_USER, XWikiException.ERROR_XWIKI_USER_INIT,
                    "Failed to marshaller request for " + authRequest);
        }

        String actionURL = getSAMLAuthenticatorURL(context);
        String url = actionURL + "?SAMLRequest=" + samlRequest;
        if (LOG.isInfoEnabled()) {
            LOG.info("Saml request sent to " + url);
        }
        try {
            response.sendRedirect(url);
            context.setFinished(true);
        } catch (IOException e) {
        }
    }
}

From source file:com.google.code.ssm.test.dao.TestDAOImpl.java

@Override
@ReadThroughSingleCache(namespace = "Charlie", expiration = 1000)
public String getRandomString(@ParameterValueKeyProvider final Long key) {
    try {// w w w .jav a2 s  . c o m
        Thread.sleep(500);
    } catch (InterruptedException ex) {
    }
    return RandomStringUtils.randomAlphanumeric(25 + RandomUtils.nextInt(30));
}

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

/**
 * @see com.cws.esolutions.security.processors.interfaces.IAccountControlProcessor#createNewUser(com.cws.esolutions.security.processors.dto.AccountControlRequest)
 *///from   w  w  w  .  j a  v a 2s .co m
public AccountControlResponse createNewUser(final AccountControlRequest request)
        throws AccountControlException {
    final String methodName = IAccountControlProcessor.CNAME
            + "#createNewUser(final CreateUserRequest createReq) throws AccountControlException";

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

    AccountControlResponse response = new AccountControlResponse();

    final RequestHostInfo reqInfo = request.getHostInfo();
    final UserAccount reqAccount = request.getRequestor();
    final UserAccount userAccount = request.getUserAccount();
    final AuthenticationData userSecurity = request.getUserSecurity();
    final String newUserSalt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength());

    if (DEBUG) {
        DEBUGGER.debug("Requestor: {}", reqAccount);
        DEBUGGER.debug("RequestHostInfo: {}", reqInfo);
        DEBUGGER.debug("UserAccount: {}", userAccount);
        DEBUGGER.debug("AuthenticationData: {}", userSecurity);
    }

    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.CREATEUSER);
                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;
        }

        String userGuid = UUID.randomUUID().toString();

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

        int x = 0;

        while (true) {
            if (x == 10) {
                throw new AccountControlException("Failed to generate a unique user GUID");
            }

            try {
                userManager.validateUserAccount(userAccount.getUsername(), userGuid);

                break;
            } catch (UserManagementException umx) {
                ERROR_RECORDER.error(umx.getMessage(), umx);

                if (!(StringUtils.contains(umx.getMessage(), "UUID"))) {
                    response.setRequestStatus(SecurityRequestStatus.FAILURE);

                    return response;
                }

                userGuid = UUID.randomUUID().toString();

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

                x++;

                continue;
            }
        }

        // insert the user salt
        boolean isSaltInserted = userSec.addOrUpdateSalt(userGuid, newUserSalt, SaltType.LOGON.name());

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

        if (isSaltInserted) {
            String newPassword = PasswordUtils.encryptText(
                    RandomStringUtils.randomAlphanumeric(secConfig.getPasswordMaxLength()), newUserSalt,
                    secConfig.getAuthAlgorithm(), secConfig.getIterations(),
                    secBean.getConfigData().getSystemConfig().getEncoding());

            List<String> accountData = new ArrayList<String>(Arrays.asList(userGuid, userAccount.getUsername(),
                    newPassword, String.valueOf(userAccount.isSuspended()), userAccount.getSurname(),
                    userAccount.getGivenName(), userAccount.getGivenName() + " " + userAccount.getSurname(),
                    userAccount.getEmailAddr()));

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

            boolean isUserCreated = userManager.addUserAccount(accountData,
                    new ArrayList<String>(Arrays.asList(Arrays.toString(userAccount.getGroups()))));

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

            if (isUserCreated) {
                response.setRequestStatus(SecurityRequestStatus.SUCCESS);
            } else {
                // failed to add the user to the repository
                ERROR_RECORDER.error("Failed to add user to the userAccount repository");

                response.setRequestStatus(SecurityRequestStatus.FAILURE);
            }
        } else {
            // failed to insert salt
            ERROR_RECORDER.error("Failed to provision new user: failed to insert the generated salt value");

            response.setRequestStatus(SecurityRequestStatus.FAILURE);
        }
    } catch (AccountControlException acx) {
        ERROR_RECORDER.error(acx.getMessage(), acx);

        throw new AccountControlException(acx.getMessage(), acx);
    } catch (AccessControlServiceException acx) {
        ERROR_RECORDER.error(acx.getMessage(), acx);

        throw new AccountControlException(acx.getMessage(), acx);
    } catch (UserManagementException umx) {
        ERROR_RECORDER.error(umx.getMessage(), umx);

        throw new AccountControlException(umx.getMessage(), umx);
    } catch (SQLException sqx) {
        ERROR_RECORDER.error(sqx.getMessage(), sqx);

        throw new AccountControlException(sqx.getMessage(), sqx);
    } 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.CREATEUSER);
            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;
}