Example usage for com.liferay.portal.kernel.util StringUtil randomString

List of usage examples for com.liferay.portal.kernel.util StringUtil randomString

Introduction

In this page you can find the example usage for com.liferay.portal.kernel.util StringUtil randomString.

Prototype

public static String randomString() 

Source Link

Document

Returns a randomized string of eight characters consisting of lower case letters, upper case letters, and single-digit whole numbers.

Usage

From source file:com.fmdp.webform.action.ConfigurationActionImpl.java

License:Open Source License

protected void validateFields(ActionRequest actionRequest) throws Exception {

    //      Locale defaultLocale = LocaleUtil.getDefault();
    //      String defaultLanguageId = LocaleUtil.toLanguageId(defaultLocale);

    boolean sendAsEmail = GetterUtil.getBoolean(getParameter(actionRequest, "sendAsEmail"));
    String subject = getParameter(actionRequest, "subject");

    boolean sendThanksEmail = GetterUtil.getBoolean(getParameter(actionRequest, "sendThanksEmail"));
    String thanksSubject = getParameter(actionRequest, "thanks-subject");

    boolean saveToDatabase = GetterUtil.getBoolean(getParameter(actionRequest, "saveToDatabase"));

    boolean showPreviousPosts = GetterUtil.getBoolean(getParameter(actionRequest, "showPreviousPosts"));

    boolean saveToFile = GetterUtil.getBoolean(getParameter(actionRequest, "saveToFile"));

    if (!sendAsEmail && !saveToDatabase && !saveToFile) {
        SessionErrors.add(actionRequest, "handlingRequired");
    }/*from ww w.j  a  v  a 2 s .  c o m*/

    if (sendAsEmail) {
        if (Validator.isNull(subject)) {
            SessionErrors.add(actionRequest, "subjectRequired");
        }

        String[] emailAdresses = WebFormUtil.split(getParameter(actionRequest, "emailAddress"));

        if (emailAdresses.length == 0) {
            SessionErrors.add(actionRequest, "emailAddressRequired");
        }

        for (String emailAdress : emailAdresses) {
            emailAdress = emailAdress.trim();

            if (!Validator.isEmailAddress(emailAdress)) {
                SessionErrors.add(actionRequest, "emailAddressInvalid");
            }
        }
        if (sendThanksEmail) {
            if (Validator.isNull(thanksSubject)) {
                SessionErrors.add(actionRequest, "thanksSubjectRequired");
            }
        }

    }

    boolean uploadToDisk = GetterUtil.getBoolean(getParameter(actionRequest, "uploadToDisk"));

    if (uploadToDisk) {
        String uploadDiskDir = getParameter(actionRequest, "uploadDiskDir");
        boolean pathIsValid = true;
        try {
            File checkFolder = null;
            checkFolder = new File(uploadDiskDir);
            if (!checkFolder.isDirectory()) {
                pathIsValid = false;
                SessionErrors.add(actionRequest, "pathNameInvalid");
            }
        } catch (SecurityException se) {
            pathIsValid = false;
            SessionErrors.add(actionRequest, "pathNameInvalid");
        } catch (NullPointerException ne) {
            pathIsValid = false;
            SessionErrors.add(actionRequest, "pathNameInvalid");
        }
        if (pathIsValid) {
            StringBundler tmpFile = new StringBundler(3);

            tmpFile.append(StringUtil.randomString());
            tmpFile.append(StringPool.PERIOD);
            tmpFile.append("tmp");

            String tmpFileName = uploadDiskDir + File.separator + tmpFile.toString();
            // Check if server can create a file as specified

            try {
                FileOutputStream fileOutputStream = new FileOutputStream(tmpFileName, true);

                fileOutputStream.close();
            } catch (SecurityException se) {
                SessionErrors.add(actionRequest, "pathNameInvalid");
            } catch (FileNotFoundException fnfe) {
                SessionErrors.add(actionRequest, "pathNameInvalid");
            }
        }
    }

    if (saveToFile) {
        String fileName = getParameter(actionRequest, "fileName");

        // Check if server can create a file as specified

        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileName, true);

            fileOutputStream.close();
        } catch (SecurityException se) {
            SessionErrors.add(actionRequest, "fileNameInvalid");
        } catch (FileNotFoundException fnfe) {
            SessionErrors.add(actionRequest, "fileNameInvalid");
        }
    }

    if (saveToDatabase) {
        int i = 1;

        String languageId = LocaleUtil.toLanguageId(actionRequest.getLocale());

        String fieldLabel = ParamUtil.getString(actionRequest, "fieldLabel" + i + "_" + languageId);

        while ((i == 1) || Validator.isNotNull(fieldLabel)) {
            if (fieldLabel.length() > 75) {
                SessionErrors.add(actionRequest, "fieldSizeInvalid" + i);
            }

            i++;

            fieldLabel = ParamUtil.getString(actionRequest, "fieldLabel" + i + "_" + languageId);
        }
    }

    if (!saveToDatabase && showPreviousPosts) {
        SessionErrors.add(actionRequest, "noPreviousPosts");
    }
    if (!validateUniqueFieldNames(actionRequest)) {
        SessionErrors.add(actionRequest, DuplicateColumnNameException.class.getName());
    }
}

From source file:com.fmdp.webform.portlet.WebFormPortlet.java

License:Open Source License

public void saveData(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
    ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest);

    String portletId = PortalUtil.getPortletId(actionRequest);

    PortletPreferences preferences = PortletPreferencesFactoryUtil.getPortletSetup(actionRequest, portletId);

    boolean requireCaptcha = GetterUtil.getBoolean(preferences.getValue("requireCaptcha", StringPool.BLANK));
    String successURL = GetterUtil.getString(preferences.getValue("successURL", StringPool.BLANK));
    boolean sendAsEmail = GetterUtil.getBoolean(preferences.getValue("sendAsEmail", StringPool.BLANK));
    boolean sendThanksEmail = GetterUtil.getBoolean(preferences.getValue("sendThanksEmail", StringPool.BLANK));
    boolean saveToDatabase = GetterUtil.getBoolean(preferences.getValue("saveToDatabase", StringPool.BLANK));
    String databaseTableName = GetterUtil
            .getString(preferences.getValue("databaseTableName", StringPool.BLANK));
    boolean saveToFile = GetterUtil.getBoolean(preferences.getValue("saveToFile", StringPool.BLANK));
    boolean uploadToDisk = GetterUtil.getBoolean(preferences.getValue("uploadToDisk", StringPool.BLANK));
    boolean uploadToDM = GetterUtil.getBoolean(preferences.getValue("uploadToDM", StringPool.BLANK));
    long newFolderId = GetterUtil.getLong(preferences.getValue("newFolderId", StringPool.BLANK));
    String fileName = GetterUtil.getString(preferences.getValue("fileName", StringPool.BLANK));
    String uploadDiskDir = GetterUtil.getString(preferences.getValue("uploadDiskDir", StringPool.BLANK));

    if (requireCaptcha) {
        try {/*from ww w  .j a v a  2 s .c  om*/
            CaptchaUtil.check(actionRequest);
        } catch (CaptchaTextException cte) {
            SessionErrors.add(actionRequest, CaptchaTextException.class.getName());

            return;
        }
    }

    UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);

    Map<String, String> fieldsMap = new LinkedHashMap<String, String>();

    String fileAttachment = "";

    for (int i = 1; true; i++) {
        String fieldLabel = preferences.getValue("fieldLabel" + i, StringPool.BLANK);

        String fieldType = preferences.getValue("fieldType" + i, StringPool.BLANK);

        if (Validator.isNull(fieldLabel)) {
            break;
        }

        if (StringUtil.equalsIgnoreCase(fieldType, "paragraph")) {
            continue;
        }
        if (StringUtil.equalsIgnoreCase(fieldType, "file")) {
            if (_log.isDebugEnabled()) {
                _log.debug("Field name for file: " + fieldLabel);
            }

            File file = uploadRequest.getFile("field" + i);

            String sourceFileName = uploadRequest.getFileName("field" + i);
            if (_log.isDebugEnabled()) {
                _log.debug("File attachment: " + sourceFileName);
            }
            JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

            if (Validator.isNotNull(sourceFileName) && !"".equals(sourceFileName)) {

                if (uploadRequest.getSize("field" + i) == 0) {
                    SessionErrors.add(actionRequest, "uploadToDiskError", "Uploaded file size is 0");
                    if (_log.isDebugEnabled()) {
                        _log.debug("Uploaded file size is 0");
                    }
                    return;
                }
                //               List<String> uploadResults = new ArrayList<String>();
                String uploadResult = "";
                if (uploadToDisk) {
                    uploadResult = uploadFile(file, sourceFileName, uploadDiskDir);
                    if (uploadResult.equalsIgnoreCase("File Upload Error")) {
                        SessionErrors.add(actionRequest, "uploadToDiskError", uploadResult);
                        return;
                    }
                    fileAttachment = uploadDiskDir + File.separator + uploadResult;
                    //uploadResults.add(uploadResult);
                    jsonObject.put("fsOriginalName", sourceFileName);
                    jsonObject.put("fsName", uploadResult);
                }
                if (uploadToDM) {
                    uploadResult = "";
                    String contentType = MimeTypesUtil.getContentType(file);
                    Folder folderName = DLAppLocalServiceUtil.getFolder(newFolderId);
                    if (_log.isDebugEnabled()) {
                        _log.debug("DM Folder: " + folderName.getName());
                    }
                    InputStream inputStream = new FileInputStream(file);
                    long repositoryId = folderName.getRepositoryId();
                    try {
                        String selectedFileName = sourceFileName;
                        while (true) {
                            try {
                                DLAppLocalServiceUtil.getFileEntry(themeDisplay.getScopeGroupId(), newFolderId,
                                        selectedFileName);

                                StringBundler sb = new StringBundler(5);

                                sb.append(FileUtil.stripExtension(selectedFileName));
                                sb.append(StringPool.DASH);
                                sb.append(StringUtil.randomString());
                                sb.append(StringPool.PERIOD);
                                sb.append(FileUtil.getExtension(selectedFileName));

                                selectedFileName = sb.toString();
                            } catch (Exception e) {
                                break;
                            }
                        }

                        FileEntry fileEntry = DLAppLocalServiceUtil.addFileEntry(themeDisplay.getUserId(),
                                repositoryId, newFolderId, selectedFileName, //file.getName(), 
                                contentType, selectedFileName, "", "", inputStream, file.length(),
                                serviceContext);
                        if (_log.isDebugEnabled()) {
                            _log.debug("DM file uploade: " + fileEntry.getTitle());
                        }
                        //Map<String, Serializable> workflowContext = new HashMap<String, Serializable>();
                        //workflowContext.put("event",DLSyncConstants.EVENT_UPDATE);
                        //DLFileEntryLocalServiceUtil.updateStatus(themeDisplay.getUserId(), fileEntry.getFileVersion().getFileVersionId(), WorkflowConstants.STATUS_APPROVED, workflowContext, serviceContext);
                        uploadResult = String.valueOf(fileEntry.getFileEntryId());
                        //uploadResults.add(uploadResult);
                        String docUrl = themeDisplay.getPortalURL() + "/c/document_library/get_file?uuid="
                                + fileEntry.getUuid() + "&groupId=" + themeDisplay.getScopeGroupId();
                        jsonObject.put("fe", uploadResult);
                        jsonObject.put("feOriginalName", sourceFileName);
                        jsonObject.put("feName", fileEntry.getTitle());
                        jsonObject.put("feUrl", docUrl);
                    } catch (PortalException pe) {
                        SessionErrors.add(actionRequest, "uploadToDmError");
                        _log.error("The upload to DM failed", pe);
                        return;
                    } catch (Exception e) {
                        _log.error("The upload to DM failed", e);
                        return;
                    }
                }
                jsonObject.put("Status", "With Attachment");
            } else {
                jsonObject.put("Status", "No Attachment");
            }
            fieldsMap.put(fieldLabel, jsonObject.toString());
        } else {
            fieldsMap.put(fieldLabel, uploadRequest.getParameter("field" + i));
        }
    }

    Set<String> validationErrors = null;

    try {
        validationErrors = validate(fieldsMap, preferences);
    } catch (Exception e) {
        SessionErrors.add(actionRequest, "validationScriptError", e.getMessage().trim());

        return;
    }

    User currentUser = PortalUtil.getUser(actionRequest);
    String userEmail = "";
    if (!Validator.isNull(currentUser)) {
        userEmail = currentUser.getEmailAddress();
        if (_log.isDebugEnabled()) {
            _log.debug("User email for the form author: " + userEmail);
        }

        fieldsMap.put("email-from", userEmail);
    } else {
        fieldsMap.put("email-from", "guest");
    }

    DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    df.setTimeZone(TimeZone.getTimeZone(themeDisplay.getTimeZone().getID()));
    Date dateobj = new Date();
    fieldsMap.put("email-sent-on", df.format(dateobj));

    if (validationErrors.isEmpty()) {
        boolean emailSuccess = true;
        boolean databaseSuccess = true;
        boolean fileSuccess = true;
        boolean emailThanksSuccess = true;

        if (sendAsEmail) {
            emailSuccess = WebFormUtil.sendEmail(themeDisplay.getCompanyId(), fieldsMap, preferences,
                    fileAttachment);
        }

        if (sendThanksEmail && !Validator.isNull(currentUser)) {
            emailThanksSuccess = WebFormUtil.sendThanksEmail(themeDisplay.getCompanyId(), fieldsMap,
                    preferences, userEmail);
        }

        if (saveToDatabase) {
            if (Validator.isNull(databaseTableName)) {
                databaseTableName = WebFormUtil.getNewDatabaseTableName(portletId);

                preferences.setValue("databaseTableName", databaseTableName);

                preferences.store();
            }

            databaseSuccess = saveDatabase(themeDisplay.getCompanyId(), fieldsMap, preferences,
                    databaseTableName);
        }

        if (saveToFile) {
            fileSuccess = saveFile(fieldsMap, fileName);
        }

        if (emailSuccess && emailThanksSuccess && databaseSuccess && fileSuccess) {
            if (Validator.isNull(successURL)) {
                SessionMessages.add(actionRequest, "success");
            } else {
                SessionMessages.add(actionRequest,
                        portletId + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_SUCCESS_MESSAGE);
            }
        } else {
            SessionErrors.add(actionRequest, "error");
        }
    } else {
        for (String badField : validationErrors) {
            SessionErrors.add(actionRequest, "error" + badField);
        }
    }

    if (SessionErrors.isEmpty(actionRequest) && Validator.isNotNull(successURL)) {

        actionResponse.sendRedirect(successURL);
    }
}

From source file:com.liferay.adaptive.media.AdaptiveMediaAttributeTest.java

License:Open Source License

@Test
public void testConfigurationUuidRecognizesAnyString() {
    AdaptiveMediaAttribute<?, String> configurationUuid = AdaptiveMediaAttribute.configurationUuid();

    String value = StringUtil.randomString();

    Assert.assertEquals(value, configurationUuid.convert(value));
}

From source file:com.liferay.adaptive.media.AdaptiveMediaAttributeTest.java

License:Open Source License

@Test(expected = AdaptiveMediaRuntimeException.AdaptiveMediaAttributeFormatException.class)
public void testContentLengthFailsForNonIntegers() {
    AdaptiveMediaAttribute<?, Integer> contentLength = AdaptiveMediaAttribute.contentLength();

    contentLength.convert(StringUtil.randomString());
}

From source file:com.liferay.adaptive.media.AdaptiveMediaAttributeTest.java

License:Open Source License

@Test
public void testContentTypeRecognizesAnyString() {
    AdaptiveMediaAttribute<?, String> contentType = AdaptiveMediaAttribute.contentType();

    String value = StringUtil.randomString();

    Assert.assertEquals(value, contentType.convert(value));
}

From source file:com.liferay.adaptive.media.AdaptiveMediaAttributeTest.java

License:Open Source License

@Test
public void testFileNameRecognizesAnyString() {
    AdaptiveMediaAttribute<?, String> fileName = AdaptiveMediaAttribute.fileName();

    String value = StringUtil.randomString();

    Assert.assertEquals(value, fileName.convert(value));
}

From source file:com.liferay.adaptive.media.blogs.internal.exportimport.content.processor.AdaptiveMediaBlogsEntryExportImportContentProcessorTest.java

License:Open Source License

@Test
public void testExportContentWithDynamicReference() throws Exception {
    String prefix = StringUtil.randomString();
    String suffix = StringUtil.randomString();

    String content = prefix + "<img data-fileentryid=\"1\" src=\"url\" />" + suffix;

    _makeOverridenProcessorReturn(content);

    _defineFileEntryToExport(1, _fileEntry1);

    String replacedContent = _blogsExportImportContentProcessor
            .replaceExportContentReferences(_portletDataContext, _blogsEntry, content, false, false);

    Assert.assertEquals(prefix + "PLACEHOLDER_1" + suffix, replacedContent);
}

From source file:com.liferay.adaptive.media.blogs.internal.exportimport.content.processor.AdaptiveMediaBlogsEntryExportImportContentProcessorTest.java

License:Open Source License

@Test
public void testExportContentWithDynamicReferenceContainingMoreAttributes() throws Exception {

    String prefix = StringUtil.randomString();
    String suffix = StringUtil.randomString();

    String content = prefix + "<img attr1=\"1\" data-fileentryid=\"1\" attr2=\"2\" "
            + "src=\"url\" attr3=\"3\"/>" + suffix;

    _makeOverridenProcessorReturn(content);

    _defineFileEntryToExport(1, _fileEntry1);

    String replacedContent = _blogsExportImportContentProcessor
            .replaceExportContentReferences(_portletDataContext, _blogsEntry, content, false, false);

    Assert.assertEquals(prefix + "PLACEHOLDER_1" + suffix, replacedContent);
}

From source file:com.liferay.adaptive.media.blogs.internal.exportimport.content.processor.AdaptiveMediaBlogsEntryExportImportContentProcessorTest.java

License:Open Source License

@Test
public void testExportContentWithMultipleDynamicReferences() throws Exception {

    String prefix = StringUtil.randomString();
    String infix = StringUtil.randomString();
    String suffix = StringUtil.randomString();

    String content = prefix + "<img data-fileentryid=\"1\" src=\"url1\" />" + infix
            + "<img data-fileentryid=\"2\" src=\"url2\" />" + suffix;

    _makeOverridenProcessorReturn(content);

    _defineFileEntryToExport(1, _fileEntry1);
    _defineFileEntryToExport(2, _fileEntry2);

    String replacedContent = _blogsExportImportContentProcessor
            .replaceExportContentReferences(_portletDataContext, _blogsEntry, content, false, false);

    StringBundler sb = new StringBundler();

    sb.append(prefix);/*from  w ww .  j  a v a 2s  . c o  m*/
    sb.append("PLACEHOLDER_1");
    sb.append(infix);
    sb.append("PLACEHOLDER_2");
    sb.append(suffix);

    Assert.assertEquals(sb.toString(), replacedContent);
}

From source file:com.liferay.adaptive.media.blogs.internal.exportimport.content.processor.AdaptiveMediaBlogsEntryExportImportContentProcessorTest.java

License:Open Source License

@Test
public void testExportContentWithMultipleStaticReferences() throws Exception {

    String prefix = StringUtil.randomString();
    String infix = StringUtil.randomString();
    String suffix = StringUtil.randomString();

    String content = prefix + "<picture data-fileentryid=\"1\"></picture>" + infix
            + "<picture data-fileentryid=\"2\"></picture>" + suffix;

    _makeOverridenProcessorReturn(content);

    _defineFileEntryToExport(1, _fileEntry1);
    _defineFileEntryToExport(2, _fileEntry2);

    String replacedContent = _blogsExportImportContentProcessor
            .replaceExportContentReferences(_portletDataContext, _blogsEntry, content, false, false);

    StringBundler sb = new StringBundler();

    sb.append(prefix);// w  w w.  j a  va  2s  .co m
    sb.append("PLACEHOLDER_1");
    sb.append(infix);
    sb.append("PLACEHOLDER_2");
    sb.append(suffix);

    Assert.assertEquals(sb.toString(), replacedContent);
}