Java tutorial
package com.stoxx.portlet.accountdetails.controller; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.mail.MessagingException; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortletException; import javax.portlet.PortletRequest; import javax.portlet.PortletSession; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import javax.portlet.ResourceRequest; import javax.portlet.ResourceResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.portlet.bind.annotation.ActionMapping; import org.springframework.web.portlet.bind.annotation.RenderMapping; import org.springframework.web.portlet.bind.annotation.ResourceMapping; import com.liferay.portal.NoSuchUserException; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.language.LanguageUtil; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.util.ListUtil; import com.liferay.portal.kernel.util.PrefsPropsUtil; import com.liferay.portal.kernel.util.PropsUtil; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.kernel.util.StringUtil; import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.kernel.util.WebKeys; import com.liferay.portal.model.User; import com.liferay.portal.security.auth.AuthTokenUtil; import com.liferay.portal.service.UserLocalServiceUtil; import com.liferay.portal.theme.ThemeDisplay; import com.liferay.portal.util.PortalUtil; import com.liferay.portlet.journal.model.JournalArticle; import com.liferay.portlet.journal.service.JournalArticleLocalServiceUtil; import com.liferay.portlet.journalcontent.util.JournalContentUtil; import com.stoxx.portlet.accountdetails.delegate.AccountDetailsDelegate; import com.stoxx.portlet.accountdetails.model.AccessDetails; import com.stoxx.portlet.accountdetails.model.AccountDetails; import com.stoxx.portlet.accountdetails.model.PackageModel; import com.stoxx.portlet.accountdetails.utils.AccountDetailsUtil; import com.stoxx.service.business.packagedetails.PackageDetailsService; import com.stoxx.service.domain.userprofile.UserProfileDetails; import com.stoxx.service.exception.STOXXException; import com.stoxx.service.util.STOXXEncrypter; import com.stoxx.service.util.STOXXMailUtil; @Controller @RequestMapping("view") public class AccountDetailsController implements Serializable { private static final String MESSAGE_SECTION = "messageSection"; private static final String PORTAL_URL = "portalURL"; private static final String FROM_ADDRESS = "fromAddress"; private static final String FROM_NAME = "fromName"; private static final String TO_NAME = "toName"; private static final String ADDUSERMSG = "addusermsg"; private static final String STOXX_MAIL_FROM_ADDRESS = "stoxx-mail-from-address"; private static final String SITE_STOXXNET_GROUPID = "site.stoxxnet.groupid"; private static final long serialVersionUID = 385033983407798887L; private static final String SHOWHOMEPAGE = "/accountDetails"; private PortletSession session; private String companyName = StringPool.BLANK; private static final String ENCRYPTION_KEY = "URL-4A144BEBF7EVE7B7DCF26491AE"; private int unUsedUsers = 0; private AccountDetails accountDetails; private static final String AUTH_TOKEN = "p_auth"; @ModelAttribute("accountDetails") public AccountDetails getAccountDetails() { return accountDetails; } public void setAccountDetails(AccountDetails accountDetails) { this.accountDetails = accountDetails; } private List<AccessDetails> accessDetails; @ModelAttribute("accessDetails") public List<AccessDetails> getAccessDetails() { return accessDetails; } private STOXXMailUtil stoxxMailUtil; public void setStoxxMailUtil(STOXXMailUtil stoxxMailUtil) { this.stoxxMailUtil = stoxxMailUtil; } public STOXXMailUtil getStoxxMailUtil() { return stoxxMailUtil; } private PackageDetailsService packageDetailsService; public void setPackageDetailsService(PackageDetailsService packageDetailsService) { this.packageDetailsService = packageDetailsService; } public PackageDetailsService getPackageDetailsService() { return packageDetailsService; } private AccountDetailsDelegate accountDetailsDelegate; public void setAccountDetailsDelegate(AccountDetailsDelegate accountDetailsDelegate) { this.accountDetailsDelegate = accountDetailsDelegate; } public AccountDetailsDelegate getAccountDetailsDelegate() { return accountDetailsDelegate; } public PortletSession getSession() { return session; } public void setSession(PortletSession session) { this.session = session; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public int getUnUsedUsers() { return unUsedUsers; } public void setUnUsedUsers(int unUsedUsers) { this.unUsedUsers = unUsedUsers; } public void setAccessDetails(List<AccessDetails> accessDetails) { this.accessDetails = accessDetails; } @RenderMapping public String showHomePage(final RenderRequest request, final RenderResponse response, final Model model) { try { ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); User user = themeDisplay.getUser(); long stoxxnetGroupId = Long.parseLong(PropsUtil.get("site.stoxxnet.groupid")); log.info("themeDisplay.getUser()>>>>>>>>>>>>>" + themeDisplay.getUser()); accountDetails = accountDetailsDelegate.getSalesForceDetails(user.getEmailAddress()); if (null != accountDetails) { accountDetails.setKeyAccHolderName(user.getFullName()); accountDetails.setContactEmail(user.getEmailAddress()); companyName = accountDetails.getCompanyName(); if (StringUtils.isNotBlank(accountDetails.getPackageName())) { List<PackageModel> packageModels = new ArrayList<PackageModel>(); for (String pkgname : accountDetails.getPackageName().split(StringPool.COMMA)) { PackageModel packageModel = new PackageModel(); String articleId = StringPool.BLANK; JournalArticle journalArticle; log.info("pkgname>>>>>>>>>>>>>" + pkgname); log.info( "accountDetails.getSalesEntryId()>>>>>>>>>>>>>" + accountDetails.getSalesEntryId()); try { journalArticle = JournalArticleLocalServiceUtil.getArticleByUrlTitle( Long.valueOf(PropsUtil.get(SITE_STOXXNET_GROUPID)).longValue(), AccountDetailsUtil.getUrlTitle(pkgname)); String articleText = JournalContentUtil.getContent( Long.valueOf(PropsUtil.get("site.stoxxnet.groupid")), journalArticle.getArticleId(), "VIEW", journalArticle.getUrlTitle(), themeDisplay); articleId = journalArticle.getArticleId(); packageModel.setArticleId(articleId); packageModel.setPackageText(articleText); log.info("articleId>>>>>>>>>>>>>" + articleId); } catch (Exception e) { log.error("Exception is >>>>>>>>>>>>>" + e.getMessage()); } packageModel.setDescription(pkgname); packageModel.setArticleId(articleId); packageModel.setIsBluePackage( packageDetailsService.getPackageCategoryByPackageName(pkgname.trim())); packageModel.setStoxxnetGroupId(stoxxnetGroupId); packageModels.add(packageModel); } accountDetails.setPackageList(packageModels); } } if (Validator.isNotNull(accountDetails)) { accessDetails = accountDetailsDelegate.getLicensedUsers(accountDetails.getSalesEntryId(), user.getEmailAddress()); } if (null != accessDetails && null != accountDetails && accessDetails.size() > 0) { log.info("accountDetails.getSalesEntryId() in side setting accesdetails >>>>>>>>>>>>>" + accountDetails.getSalesEntryId()); if (StringUtils.isNotBlank(accountDetails.getTotalUsers())) { int totalUsers = Integer.valueOf(accountDetails.getTotalUsers()).intValue(); log.info("totalUsers" + totalUsers); int usedUsers = accessDetails.size(); log.info("usedUsers>>>>>>>>>>>>>" + usedUsers); if (usedUsers == totalUsers) { unUsedUsers = 0; log.info("unUsedUsers>>>>>>>>>>>>>" + unUsedUsers); accountDetails.setUnUsedUsers(unUsedUsers + StringPool.BLANK); } else { unUsedUsers = totalUsers - usedUsers; accountDetails.setUnUsedUsers(unUsedUsers + StringPool.BLANK); } } } if (null != accessDetails && null != accountDetails && accessDetails.size() > 0) { model.addAttribute("accountDetails", accountDetails); model.addAttribute("accessDetails", accessDetails); } } catch (STOXXException e) { log.error("STOXXException in AccountDetailsController" + e); } catch (SystemException e) { log.error(e.getMessage() + e); } catch (NumberFormatException e) { log.error(e.getMessage() + e); } return SHOWHOMEPAGE; } @ActionMapping(params = "action=deleteUser") public void deleteUser(final ActionRequest request, final ActionResponse response, @ModelAttribute("accountDetails") AccountDetails accountDetails, final Model model) { Map<String, Object> emailBodyMap = new HashMap<String, Object>(); try { ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); String emailTemplateFolder = "templates"; String emailVelocityTemplate = StringPool.BLANK; emailVelocityTemplate = emailTemplateFolder + "/" + "keyAccHolderDeactivationMail.vm"; String deleteEmail = request.getParameter("deleteEmail"); log.info("accountDetails.getKeyAccHolderName()>>>>> " + accountDetails.getKeyAccHolderName()); log.info("deleteEmail>>>>> " + deleteEmail); if (StringUtils.isNotBlank(accountDetails.getKeyAccHolderName()) && StringUtils.isNotBlank(deleteEmail)) { emailBodyMap.put(TO_NAME, deleteEmail); emailBodyMap.put(FROM_NAME, PrefsPropsUtil.getString("stoxx-mail-from-name")); emailBodyMap.put(FROM_ADDRESS, PropsUtil.get(STOXX_MAIL_FROM_ADDRESS)); emailBodyMap.put(PORTAL_URL, PrefsPropsUtil.getString("stoxx-mail-from-url")); emailBodyMap.put(MESSAGE_SECTION, LanguageUtil.get(themeDisplay.getLocale(), "stoxx-accountDetails-delete-licenced-user") + StringPool.SPACE + accountDetails.getKeyAccHolderName()); log.info(emailBodyMap.get(TO_NAME) + " " + emailBodyMap.get(FROM_NAME) + " " + emailBodyMap.get(FROM_ADDRESS) + " " + emailBodyMap.get(PORTAL_URL) + " " + emailBodyMap.get(MESSAGE_SECTION)); accountDetailsDelegate.deleteUserByEmail(themeDisplay.getCompanyId(), deleteEmail, themeDisplay.getUser()); stoxxMailUtil.sendEmailNotification( deleteEmail, PropsUtil.get(STOXX_MAIL_FROM_ADDRESS), emailVelocityTemplate, LanguageUtil .get(themeDisplay.getLocale(), "stoxx-accountDetails-delete-licenced-user-subject"), emailBodyMap); } request.setAttribute("deleteusermsg", "SUCCESS"); } catch (SystemException e) { log.error(e.getMessage() + e); } catch (MessagingException e) { log.error(e.getMessage() + e); } } @ActionMapping(params = "action=addUser") public void saveCustomerAsStoxxUsersByEmail(ActionRequest request, ActionResponse response) { log.info("inside saveCustomerAsStoxxUsers--"); ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); String emailTemplateFolder = "templates"; String emailVelocityTemplate = emailTemplateFolder + "/" + "subUsersActivationEmail.vm"; String userEmail = request.getParameter("memberData"); userEmail = StringUtil.toLowerCase(userEmail); String accountType = request.getParameter("typeData"); log.info("userEmail>>>>> " + userEmail); log.info("accountType>>>>> " + accountType); try { log.info("unUsedUsers in adduser >>>>>>>>>>>>>>>>>>>>" + unUsedUsers); if (0 != unUsedUsers) { if (StringUtils.isNotBlank(userEmail) && StringUtils.isNotBlank(accountType)) { if (Validator .isNotNull(StringUtil.trim(ListUtil.toString(accountDetails.getDomains(), "", "")))) { boolean isValidDomain = false; for (String domain : accountDetails.getDomains()) { domain = StringUtil.toLowerCase(domain); if (userEmail.endsWith(domain)) { isValidDomain = true; break; } } if (!isValidDomain) { request.setAttribute(ADDUSERMSG, "INVALID_DOMAIN"); return; } } if (checkCaptcha(request)) { log.info("Answer was entered correctly!"); Map<String, Object> emailBodyMap = new HashMap<String, Object>(); emailBodyMap.put(FROM_NAME, PrefsPropsUtil.getString("stoxx-mail-from-name")); emailBodyMap.put(FROM_ADDRESS, PropsUtil.get(STOXX_MAIL_FROM_ADDRESS)); emailBodyMap.put(PORTAL_URL, PrefsPropsUtil.getString("stoxx-mail-from-url")); log.info("Email addresses>>>>> "); log.info("Email addresses>>>>> " + userEmail); String encryptedEmailId = STOXXEncrypter.encrypt(userEmail, ENCRYPTION_KEY); String activationLink = themeDisplay.getPortalURL() + PrefsPropsUtil.getString("stoxx-pre-reg-admin-acount-registration") + encryptedEmailId; log.info("ADD USER activationlink >>>>>>>>>>>>>>>>>>>>>>>>>>" + activationLink); if (StringUtils.isNotBlank(companyName)) { User userlocal = null; UserProfileDetails profileDetailsLocal = accountDetailsDelegate .getUserProfile(userEmail); boolean isDeletedUser = (profileDetailsLocal != null && Validator.equals(profileDetailsLocal.getStatus(), Integer.valueOf(4))); try { userlocal = UserLocalServiceUtil.getUserByEmailAddress(themeDisplay.getCompanyId(), userEmail); } catch (NoSuchUserException e) { log.error(e.getMessage(), e); } catch (PortalException e) { log.error(e.getMessage(), e); } if (null == userlocal && !(StringUtils.isNotBlank(profileDetailsLocal.getEmailAddress()))) { accountDetailsDelegate.saveStoxxUser( themeDisplay.getUser().getEmailAddress().toLowerCase(), userEmail, activationLink, companyName, accountType); emailBodyMap.put(TO_NAME, userEmail); emailBodyMap.put("userActivationLink", activationLink); stoxxMailUtil.sendEmailNotification(userEmail, PropsUtil.get(STOXX_MAIL_FROM_ADDRESS), emailVelocityTemplate, LanguageUtil.get(themeDisplay.getLocale(), "stoxx-prereg-email-subject"), emailBodyMap); request.setAttribute(ADDUSERMSG, "SUCCESS"); } else { if (isDeletedUser) { accountDetailsDelegate.updateStoxxUser( themeDisplay.getUser().getEmailAddress().toLowerCase(), activationLink, accountType, companyName, profileDetailsLocal); emailBodyMap.put(TO_NAME, userEmail); emailBodyMap.put("userActivationLink", activationLink); stoxxMailUtil.sendEmailNotification(userEmail, PropsUtil.get(STOXX_MAIL_FROM_ADDRESS), emailVelocityTemplate, LanguageUtil.get(themeDisplay.getLocale(), "stoxx-prereg-email-subject"), emailBodyMap); request.setAttribute(ADDUSERMSG, "SUCCESS"); } else if (null != userlocal && (StringUtils.isNotBlank(profileDetailsLocal.getEmailAddress())) && !isDeletedUser) { if (null != profileDetailsLocal.getSalesEntryId()) { request.setAttribute(ADDUSERMSG, "ADDREGISTER"); } else { request.setAttribute(ADDUSERMSG, "ADDREGISTEROTHER"); } } else if (null != userlocal && !(StringUtils.isNotBlank(profileDetailsLocal.getEmailAddress()))) { request.setAttribute(ADDUSERMSG, "EXISTS"); } else if (null == userlocal && (StringUtils.isNotBlank(profileDetailsLocal.getEmailAddress()))) { if (null != profileDetailsLocal.getSalesEntryId()) { request.setAttribute(ADDUSERMSG, "ADD"); } else { request.setAttribute(ADDUSERMSG, "ADDOTHER"); } } } } } else { request.setAttribute(ADDUSERMSG, "WRONGCAPTCHA"); } } } else { request.setAttribute(ADDUSERMSG, "FAILURE"); } } catch (STOXXException e) { log.error("STOXXException in AccountDetailsController", e); } catch (SystemException e) { log.error(e.getMessage(), e); } catch (MessagingException e) { log.error(e.getMessage(), e); } catch (PortletException e) { log.error(e.getMessage(), e); } } public String getCaptchaValueFromSession() { Enumeration<String> atNames = session.getAttributeNames(); while (atNames.hasMoreElements()) { String name = atNames.nextElement(); if (name.contains("CAPTCHA_TEXT")) { return (String) session.getAttribute(name); } } return ""; } private boolean checkCaptcha(PortletRequest request) throws PortletException { String enteredCaptchaText = StringPool.COMMA; if (StringUtils.isNotBlank(request.getParameter("captchaEntered"))) { enteredCaptchaText = request.getParameter("captchaEntered"); } if (StringUtils.isNotBlank(request.getParameter("captchaEntered2"))) { enteredCaptchaText = request.getParameter("captchaEntered2"); } boolean isValid = true; PortletSession sessionCaptcha = request.getPortletSession(); String captchaText = getCaptchaValueFromSession(sessionCaptcha); if (Validator.isNull(captchaText)) { log.info("Internal Error! Captcha text not found in session"); isValid = false; } if (!captchaText.equals(enteredCaptchaText)) { log.info("Invalid captcha text. Please reenter."); isValid = false; } return isValid; } private String getCaptchaValueFromSession(PortletSession session) { Enumeration<String> atNames = session.getAttributeNames(); while (atNames.hasMoreElements()) { String name = atNames.nextElement(); if (name.contains("CAPTCHA_TEXT")) { return (String) session.getAttribute(name); } } return null; } @ResourceMapping public void handleResource(ResourceRequest request, ResourceResponse response) { try { HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper( PortalUtil.getHttpServletRequest(request)) { @Override public String getParameter(String name) { log.info("The name is " + name); if (name.equals(AUTH_TOKEN)) { log.info("The name matches"); return PortalUtil.getOriginalServletRequest((HttpServletRequest) super.getRequest()) .getParameter(name); } return super.getParameter(name); } }; AuthTokenUtil.checkCSRFToken(wrapper, this.getClass().getName()); } catch (Exception e) { log.error("INVALID CSRF TOKEN", e); return; } try { com.liferay.portal.kernel.captcha.CaptchaUtil.serveImage(request, response); } catch (IOException e) { log.error("IOException", e); } } private static Log log = LogFactoryUtil.getLog(AccountDetailsController.class); }