Java tutorial
/* * EYWA.COM (Eywa Commerce) * This program is an integrated platform with E-Commerce and Configurator system. * Support: Please, contact the Author on http://www.smartfeeling.org. * Copyright (C) 2014 Gian Angelo Geminiani * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.eywa.impl.app.controllers.central; import com.eywa.AppEywa; import com.eywa.impl.app.IAppConstants; import com.eywa.impl.app.controllers.scheduled.reports.JobReport; import com.eywa.impl.app.mongo.entities.*; import com.eywa.impl.app.mongo.entities.Process; import com.eywa.impl.app.mongo.entities.items.ItemOptions; import com.eywa.impl.app.mongo.entities.items.jobs.ItemJobMessage; import com.eywa.impl.app.mongo.services.*; import com.eywa.impl.app.resources.templates.BaseTemplateManager; import com.eywa.impl.app.resources.templates.emails.account.activation.MailAccountActivation; import com.eywa.impl.app.resources.templates.emails.account.resetpassword.MailUserPassword; import com.eywa.impl.app.resources.templates.emails.comment.MailNewComment; import com.eywa.impl.app.resources.templates.emails.comment.registered.MailNewCommentRegistered; import com.eywa.impl.app.resources.templates.emails.comment.registered.commenter.MailNewCommentCommenter; import com.eywa.impl.app.resources.templates.emails.comment.registered.hubowner.MailNewCommentHubOwner; import com.eywa.impl.app.resources.templates.emails.comment.registered.postowner.MailNewCommentPostOwner; import com.eywa.impl.app.resources.templates.emails.comment.unregistered.MailNewCommentUnregistered; import com.eywa.impl.app.resources.templates.emails.filedownload.MailFileDownload; import com.eywa.impl.app.resources.templates.emails.fileupdate.MailFileUpdate; import com.eywa.impl.app.resources.templates.emails.fileupdate.registered.MailFileUpdateRegistered; import com.eywa.impl.app.resources.templates.emails.fileupdate.unregistered.MailFileUpdateUnregistered; import com.eywa.impl.app.resources.templates.emails.stuff.MailNewPost; import com.eywa.impl.app.resources.templates.emails.stuff.invitation.MailNewPostInvitation; import com.eywa.impl.app.resources.templates.emails.stuff.registered.restricted.MailNewPostRegisteredRestricted; import com.eywa.impl.app.resources.templates.emails.stuff.registered.unrestricted.MailNewPostRegistered; import com.eywa.impl.app.resources.templates.emails.stuff.unregistered.restricted.MailNewPostUnregisteredRestricted; import com.eywa.impl.app.resources.templates.emails.stuff.unregistered.unrestricted.MailNewPostUnregistered; import com.eywa.impl.app.resources.templates.emails.system.error.MailSystemError; import com.eywa.impl.app.resources.templates.emails.system.scheduledjobs.MailScheduledJob; import com.eywa.impl.app.resources.templates.emails.system.scheduledjobs.error.MailScheduledJobError; import com.eywa.impl.app.resources.templates.emails.system.scheduledjobs.report.MailScheduledJobReport; import com.eywa.impl.app.resources.templates.mailadminnewuser.MailAdminNewUser; import com.eywa.impl.app.resources.templates.mailadminremoveduser.MailAdminRemovedUser; import com.eywa.impl.app.resources.templates.mailcontact.MailContact; import com.eywa.impl.app.resources.templates.mailcontactsent.MailContactSent; import com.mongodb.DBObject; import org.ly.Smartly; import org.ly.commons.Delegates; import org.ly.commons.async.Async; import org.ly.commons.logging.Level; import org.ly.commons.logging.Logger; import org.ly.commons.logging.util.LoggingUtils; import org.ly.commons.network.shorturl.ShortURL; import org.ly.commons.util.*; import org.ly.packages.mail.impl.MailUtils; import org.ly.packages.mongo.impl.util.MongoUtils; import org.ly.packages.velocity.impl.templates.VLCTemplateManager; import org.ly.packages.velocity.impl.vtools.ConvertTool; import java.text.DateFormat; import java.util.*; /** * Manage all emails */ public class Mail { public static final String MAIL_TEMPLATE_ACTIVATION_LINK = "activation_link"; //-- fields --// private static final boolean _autoenable_users = AppEywa.getAutoenableUser(); private static final String _admin_email = AppEywa.getAdminEmail(); private static final String _lang = Smartly.getLang(); private static final String[] _send_email_on_new_user = AppEywa.getSendEmailOnNewUser(); //-- paths --// private static final String URL_APP = PathUtils.concat(AppEywa.getWebServerUrl(), "/"); private static final String URL_LOGIN = IAppConstants.URL_LOGIN; private static final String URL_ACTIVATE_ACCOUNT = IAppConstants.URL_ACTIVATE_ACCOUNT; private static final String URL_DOWNLOADS = PathUtils.concat(URL_APP, "stuffdownload"); private static final String URL_POST = PathUtils.concat(URL_APP, "stuff"); private static final String URL_SINGLE_POST = URL_APP.concat("file_app/index.html?page=page_post&post={0}"); // ------------------------------------------------------------------------ // p u b l i c // ------------------------------------------------------------------------ public void notifyError(final String message, final Throwable t) { //-- start async call --// Async.Action(new Delegates.Action() { @Override public void handle(Object... args) { try { notifyErrorSync(message, t); } catch (Throwable t) { getLogger().log(Level.SEVERE, null, t); } } }); } public void notifyProcessTerminated(final String processId) { //-- start async call --// Async.Action(new Delegates.Action() { @Override public void handle(Object... args) { try { final DBObject item = ProcessService.get(processId); notifyProcessTerminatedSync(item); } catch (Throwable t) { getLogger().log(Level.SEVERE, null, t); } } }); } public void notifyProcessTerminated(final DBObject process) { try { notifyProcessTerminatedSync(process); } catch (Throwable t) { getLogger().log(Level.SEVERE, null, t); } } public void notifyScheduledJobError(final DBObject job, final Throwable exception) { Async.Action(new Delegates.Action() { @Override public void handle(Object... args) { notifyScheduledJob(job, null, exception); } }); } public void notifyScheduledJobFinish(final DBObject job, final JobReport report) { Async.Action(new Delegates.Action() { @Override public void handle(Object... args) { notifyScheduledJob(job, report, null); } }); } public void sendEmailUserRemoved(final DBObject user) { try { final String adminemail = _admin_email; final String lang = _lang; if (StringUtils.hasText(adminemail)) { final MailAdminRemovedUser msg = new MailAdminRemovedUser(); msg.addUser(user); final String[] emails = StringUtils.split(adminemail, ","); this.sendEmail(lang, emails, msg); } } catch (Throwable ignored) { } } public void sendEmailUserRegistered(final String langCode, final DBObject user) { try { if (null != user) { // send activation email if needed sendEmailActivateAccount(langCode, user); // email to administrator if (_send_email_on_new_user.length > 0) { final String lang = _lang; final MailAdminNewUser message = new MailAdminNewUser(); message.addUser(user); this.sendEmail(lang, _send_email_on_new_user, message); } } } catch (Throwable t) { getLogger().log(Level.SEVERE, null, t); } } public void sendEmailActivateAccount(final String langCode, final DBObject user) { try { if (null != user) { // email to user final boolean autoenable = _autoenable_users; // send activation email if needed if (!autoenable) { final String email = User.getEmail(user); final String http_root = AppEywa.getWebServerUrl(); final String link = PathUtils.concat(http_root, URL_ACTIVATE_ACCOUNT) + "?id=" + User.getId(user) + "&lang=" + langCode; final MailAccountActivation message = new MailAccountActivation(); message.addHref(link); message.addUser(user); this.sendEmail(langCode, new String[] { email }, message); } } } catch (Throwable t) { getLogger().log(Level.SEVERE, null, t); } } public void sendEmailNewPassword(final DBObject user, final String new_password) { try { if (null != user) { // email to user final String email = User.getEmail(user); final String langCode = User.getLang(user); User.setPassword(user, new_password); final MailUserPassword message = new MailUserPassword(); message.addUser(user); this.sendEmail(langCode, new String[] { email }, message); } } catch (Throwable t) { getLogger().log(Level.SEVERE, null, t); } } /** * Utility to send email * * @param lang Language * @param addresses Addresses * @param message Message */ public void sendEmail(final String lang, final String[] addresses, final VLCTemplateManager message) { final Locale locale = LocaleUtils.getLocaleFromString(lang); final String title = message.getTitle(locale); sendEmail(null, locale, addresses, title, message); } public boolean sendEmail(final JsonWrapper data) { try { final ConvertTool convert = new ConvertTool(); convert.decodeAll(data); final MailContact template = new MailContact(); template.addData(data.toMap()); this.sendEmail(AppEywa.getLang(), AppEywa.getContactEmail(), template); //-- send email to sender --// final String user_email = data.getString(IAppConstants.EMAIL); final String user_lang = data.getString(IAppConstants.LANG); final MailContactSent user_template = new MailContactSent(); user_template.addData(data.toMap()); this.sendEmail(user_lang, new String[] { user_email }, user_template); return true; } catch (Throwable t) { return false; } } // ------------------------------------------------------------------------ // p r i v a t e // ------------------------------------------------------------------------ private static Logger getLogger() { return LoggingUtils.getLogger(Mail.class); } private static void sendEmail(final String from, final String lang, final String[] addresses, final String title, final VLCTemplateManager message) { final Locale locale = LocaleUtils.getLocaleFromString(lang); sendEmail(from, locale, addresses, title, message); } private static void sendEmail(final String from, final Locale locale, final String[] addresses, final String title, final VLCTemplateManager message) { try { //final Locale locale = LocaleUtils.getLocaleFromString(lang); final String body = StringUtils.trim(message.getContent(locale)); final String subject = "[".concat(AppEywa.getAppTitle()).concat("] ") .concat(StringUtils.leftStr(RegExUtils.preserve(RegExUtils.ALPHANUMERIC_EXT, title), 50, true)); if (StringUtils.hasText(from) && RegExUtils.isValidEmail(from)) { MailUtils.sendMailHTMLTo(from, addresses, subject, body); } else { MailUtils.sendMailHTMLTo(addresses, subject, body); } } catch (Exception e) { getLogger().log(Level.SEVERE, null, e); } } private static void notifyScheduledJob(final DBObject job, final JobReport report, final Throwable exception) { if (null != job) { // creates template final MailScheduledJob template; if (null == report) { // exception template = new MailScheduledJobError(); } else { // report template = new MailScheduledJobReport(); } // send default email to main user, if any notifyScheduledJob(ScheduledJob.getUserId(job), job, report, exception, template); // send emails to other recipients final DBObject recipients = ScheduledJob.getNotifyRecipients(job); if (null != recipients) { final DBObject recipients_templates = ItemJobMessage.getRecipientsWithTemplates(recipients); final Set<String> userIds = recipients_templates.keySet(); for (final String userId : userIds) { final DBObject templateItem = MongoUtils.getDBObject(recipients_templates, userId); if (null != templateItem) { final String title = MongoUtils.getString(templateItem, ItemJobMessage.TITLE); final String content = MongoUtils.getString(templateItem, ItemJobMessage.CONTENT); if (StringUtils.hasText(content)) { final DBObject user = UserService.get(userId); final String recipient_email = User.getEmail(user); final String recipient_realname = User.getRealname(user); final Locale locale = LocaleUtils.getLocaleByLang(User.getLang(user)); // override template data template.setTitle(locale, title); template.setContent(locale, content); notifyScheduledJob(locale, recipient_email, recipient_realname, job, report, exception, template); } } } } } } private static void notifyScheduledJob(final String userId, final DBObject job, final JobReport report, final Throwable exception, final MailScheduledJob template) { final DBObject user = UserService.get(userId); notifyScheduledJob(user, job, report, exception, template); } private static void notifyScheduledJob(final DBObject user, final DBObject job, final JobReport report, final Throwable exception, final MailScheduledJob template) { if (null != user && null != job) { final String lang = User.getLang(user); final Locale locale = LocaleUtils.getLocaleByLang(lang); final String recipient_email = User.getEmail(user); final String recipient_realname = User.getRealname(user); notifyScheduledJob(locale, recipient_email, recipient_realname, job, report, exception, template); } } private static void notifyScheduledJob(final Locale locale, final String recipient_email, final String recipient_realname, final DBObject job, final JobReport report, final Throwable exception, final MailScheduledJob template) { if (null != job) { final long execution_date = ScheduledJob.getRunLastDate(job); final boolean is_one_shot = ScheduledJob.isOneShot(job); final String job_type = ScheduledJob.getType(job); final StringBuilder subject = new StringBuilder(); subject.append(template.getTitle(locale)); // get a description for job type final String type_desc = template.getPropertyValue(locale, job_type); final Map<String, Object> args = new HashMap<String, Object>(); args.put(MailScheduledJob.RECIPIENT_REALNAME, recipient_realname); args.put(MailScheduledJob.SUBJECT, subject.toString()); args.put(MailScheduledJob.ERROR_MESSAGE, null != exception ? ExceptionUtils.getMessage(exception) : ""); args.put(MailScheduledJob.RUN_DATE, is_one_shot); args.put(MailScheduledJob.IS_ONE_SHOT, execution_date); args.put(MailScheduledJob.JOB_TYPE, StringUtils.hasText(type_desc) ? type_desc : job_type); if (null != report) { // report data args.put(MailScheduledJob.ELAPSED_TIME, FormatUtils.formatDate(report.getElapsedTime(), FormatUtils.DEFAULT_TIMEFORMAT)); } template.addData(args); //-- send email --// sendEmail("", locale, new String[] { recipient_email }, subject.toString(), template); } } private static void notifyProcessTerminatedSync(final DBObject process) { if (null != process && Process.getNotifyWenTerminated(process)) { final String userId = Process.getUserId(process); final DBObject user = UserService.getEnabled(userId); if (null != user) { // ready to notify process terminated by email to user // TODO: crate template and send email } } } private void notifyErrorSync(final String message, final Throwable t) { final String[] recipients = StringUtils.splitUnique(_admin_email, new String[] { " ", ",", ";" }); final String langCode = AppEywa.getLang(); final Locale locale = LocaleUtils.getLocaleByLang(langCode); final BaseTemplateManager template = new MailSystemError(); final String subject = template.getTitle(locale); final String error_message = null != t ? FormatUtils.format("{0}: {1}", message, t) : message; final Map<String, Object> args = new HashMap<String, Object>(); args.put(MailSystemError.ERROR_MESSAGE, error_message); //-- merge template with data and send email --// template.addData(args); sendEmail(null, langCode, recipients, subject, template); } }