Example usage for com.liferay.portal.kernel.servlet SessionMessages add

List of usage examples for com.liferay.portal.kernel.servlet SessionMessages add

Introduction

In this page you can find the example usage for com.liferay.portal.kernel.servlet SessionMessages add.

Prototype

public static void add(PortletRequest portletRequest, String key) 

Source Link

Usage

From source file:com.commsen.liferay.portlet.tailgate.TailgatePortlet.java

License:Open Source License

@ProcessAction(name = "saveConfig")
public void saveConfig(final ActionRequest request, final ActionResponse response)
        throws SystemException, PortletException, IOException {

    final String filename = ParamUtil.getString(request, FILE_NAME, null);
    final int lines = ParamUtil.getInteger(request, LINES, 100);
    final String height = ParamUtil.getString(request, WINDOW_HEIGHT, "300px");

    final PortletPreferences prefs = request.getPreferences();
    prefs.setValue(FILE_NAME, filename);
    prefs.setValue(LINES, Integer.toString(lines));
    prefs.setValue(WINDOW_HEIGHT, height);
    prefs.store();/*  w w w  .ja va  2s  . c o m*/

    SessionMessages.add(request, "tailgate-message:config-saved");

    initFileBuffer(request);
}

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  w  w w.  j  a v a  2  s.com
            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.gleo.plugins.hexiagon.portlet.countries.action.ActivateCountryMVCActionCommand.java

License:Open Source License

@Override
protected void doProcessAction(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {
    long countryId = ParamUtil.getLong(actionRequest, "countryId");
    boolean isActive = ParamUtil.getBoolean(actionRequest, "isActive");

    try {//from www. j av a  2 s  .co m
        Country country = ExtCountryServiceUtil.setActive(countryId, !isActive);
        SessionMessages.add(actionRequest, "country-updated-active");
        LOGGER.debug(country);
    } catch (Exception e) {
        LOGGER.error(e);
        SessionErrors.add(actionRequest, "country-error");
    }
}

From source file:com.inkwell.internet.productregistration.registration.portlet.ProductAdminPortlet.java

License:Open Source License

/**
 * This Action adds a product to the database.
 *
 * @param request/*from www . j a  va 2  s.co m*/
 * @param response
 * @throws java.lang.Exception
 */

public void addProduct(ActionRequest request, ActionResponse response) throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
    PRProduct product = ActionUtil.productFromRequest(request);
    ArrayList<String> errors = new ArrayList<String>();

    if (ProdRegValidator.validateProduct(product, errors)) {
        PRProductLocalServiceUtil.addProduct(product, themeDisplay.getUserId());
        SessionMessages.add(request, "product-saved-successfully");
    } else {
        SessionErrors.add(request, "fields-required");
    }
}

From source file:com.inkwell.internet.productregistration.registration.portlet.ProductAdminPortlet.java

License:Open Source License

/**
 * This Action updates an existing product with values that were entered
 * into the edit_product.jsp.//ww  w.j  a  v  a2s.c  o m
 *
 * @param request
 * @param response
 * @throws java.lang.Exception
 */

public void updateProduct(ActionRequest request, ActionResponse response) throws Exception {

    long productKey = ParamUtil.getLong(request, "resourcePrimKey");
    ArrayList<String> errors = new ArrayList();
    if (Validator.isNotNull(productKey)) {
        PRProduct product = PRProductLocalServiceUtil.getPRProduct(productKey);
        PRProduct requestProduct = ActionUtil.productFromRequest(request);

        if (ProdRegValidator.validateProduct(requestProduct, errors)) {
            product.setProductName(requestProduct.getProductName());
            product.setSerialNumber(requestProduct.getSerialNumber());
            PRProductLocalServiceUtil.updatePRProduct(product);
            SessionMessages.add(request, "productUpdated");

        } else {
            for (String error : errors) {
                SessionErrors.add(request, error);

            }

        }

    } else {
        SessionErrors.add(request, "error-updating");
    }

}

From source file:com.inkwell.internet.productregistration.registration.portlet.ProductAdminPortlet.java

License:Open Source License

/**
 * This Action deletes a product from the database.
 *
 * @param request/*  w  ww  .j a  va 2  s.co  m*/
 * @param response
 * @throws java.lang.Exception
 */
public void deleteProduct(ActionRequest request, ActionResponse response) throws Exception {

    long productKey = ParamUtil.getLong(request, "resourcePrimKey");

    if (Validator.isNotNull(productKey)) {
        PRProductLocalServiceUtil.deleteProduct(productKey);
        SessionMessages.add(request, "productDeleted");
    } else {
        SessionErrors.add(request, "error-deleting");
    }
}

From source file:com.inkwell.internet.productregistration.registration.portlet.ProductRegistrationPortlet.java

License:Open Source License

/**
 * Takes a submitted registration and adds it to the database if it passes
 * validation.//from  ww  w . j a v a  2 s.c om
 *
 * @param request
 * @param response
 */
public void registerProduct(ActionRequest request, ActionResponse response) throws Exception {

    PRUser regUser = ActionUtil.prUserFromRequest(request);
    PRRegistration registration = ActionUtil.prRegistrationFromRequest(request);
    ArrayList<String> errors = new ArrayList<String>();
    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
    long userId = themeDisplay.getUserId();

    User liferayUser = UserLocalServiceUtil.getUser(userId);

    boolean userValid = ProdRegValidator.validateUser(regUser, errors);
    boolean regValid = ProdRegValidator.validateRegistration(registration, errors);

    if (userValid && regValid) {
        // TODO: Logic needs to change here for multiple registrations and
        // to check for logged-in users
        PRUser user = null;

        // check to see if user is a guest
        if (liferayUser.isDefaultUser()) {
            userId = 0;
            user = PRUserLocalServiceUtil.addPRUser(regUser, userId);
        } else {
            // Check to see if we have a PR User from the Liferay user ID
            user = PRUserLocalServiceUtil.getPRUser(themeDisplay.getScopeGroupId(), userId);

            if (user == null) {
                // Create a new mapping
                regUser.setUserId(userId);
                user = PRUserLocalServiceUtil.addPRUser(regUser, userId);
            }
        }

        registration.setPrUserId(user.getPrUserId());
        PRRegistrationLocalServiceUtil.addRegistration(registration);
        SessionMessages.add(request, "registration-saved-successfully");
        response.setRenderParameter("jspPage", viewThankYouJSP);
    } else {
        for (String error : errors) {
            SessionErrors.add(request, error);
        }
        SessionErrors.add(request, "error-saving-registration");
        response.setRenderParameter("jspPage", viewAddRegistrationJSP);
        request.setAttribute("regUser", regUser);
        request.setAttribute("registration", registration);
    }
}

From source file:com.inkwell.internet.slogan.actions.DeleteSloganActionCommand.java

License:Open Source License

public boolean processCommand(PortletRequest request, PortletResponse response) throws PortletException {

    long sloganKey = ParamUtil.getLong(request, "resourcePrimKey");

    if (Validator.isNotNull(sloganKey)) {
        try {//w  w w. j a v  a 2s .co  m
            SloganLocalServiceUtil.deleteSlogan(sloganKey);
        } catch (PortalException e) {
            SessionErrors.add(request, "error-deleting");
            return false;
        } catch (SystemException e) {
            SessionErrors.add(request, "error-deleting");
            return false;
        }
        SessionMessages.add(request, "slogan-deleted");
        return true;
    } else {
        SessionErrors.add(request, "error-deleting");
        return false;
    }
}

From source file:com.inkwell.internet.slogan.portlet.SloganContest.java

License:Open Source License

/**
 * Called when a user is either adding or updating a statement. If the
 * primary key is greater than 0, an update is performed, because there's an
 * existing key. Otherwise, an add is performed.
 *
 * @param request//ww w.  jav a 2  s  .  c o  m
 * @param response
 * @throws SystemException
 * @throws PortalException
 */
public void updateSlogan(ActionRequest request, ActionResponse response)
        throws PortalException, SystemException {

    Slogan slogan = ActionUtil.sloganFromRequest(request);

    ArrayList<String> errors = new ArrayList<String>();
    ServiceContext serviceContext = ServiceContextFactory.getInstance(Slogan.class.getName(), request);

    if (SloganValidator.validateSlogan(slogan, errors)) {
        if (slogan.getSloganId() > 0) {
            // Updating

            try {
                Slogan fromDB = SloganLocalServiceUtil.getSlogan(slogan.getSloganId());

                if (fromDB != null && (slogan.getSloganId() == fromDB.getSloganId())) {

                    fromDB = SloganLocalServiceUtil.updateSlogan(slogan, false);

                    SessionMessages.add(request, "slogan-added");
                }
            } catch (PortalException e) {
                errors.add("failed-to-update");
            } catch (SystemException e) {
                errors.add("failed-to-update");
            }
        } else {
            // Adding

            try {
                SloganLocalServiceUtil.addSlogan(slogan, slogan.getUserId(), serviceContext);

            } catch (SystemException e) {
                errors.add("failed-to-add");
            } catch (PortalException e) {
                errors.add("failed-to-add");
            }
        }

        // response.setRenderParameter("jspPage", "/html/view.jsp");
    } else {
        for (String error : errors) {
            SessionErrors.add(request, error);
        }

        request.setAttribute(WebKeys.SLOGAN_ENTRY, slogan);
        response.setRenderParameter("jspPage", "/html/edit_slogan.jsp");
    }
}

From source file:com.inkwell.internet.slogan.portlet.SloganContest.java

License:Open Source License

/**
 * Deletes the slogan from the database.
 *
 * @param request/*  ww w.  j  a v a  2s  .c  om*/
 * @param response
 */
public void deleteSlogan(ActionRequest request, ActionResponse response) throws Exception {

    long sloganKey = ParamUtil.getLong(request, "resourcePrimKey");

    if (Validator.isNotNull(sloganKey)) {
        SloganLocalServiceUtil.deleteSlogan(sloganKey);
        SessionMessages.add(request, "slogan-deleted");
    } else {
        SessionErrors.add(request, "error-deleting");

    }
}