use of cz.metacentrum.perun.registrar.model.ApplicationMail in project perun by CESNET.
the class MailManagerImpl method sendInvitation.
@Override
public void sendInvitation(PerunSession sess, Vo vo, Group group, User user) throws PerunException {
if (group == null) {
if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, vo)) {
throw new PrivilegeException(sess, "sendInvitation");
}
} else {
if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, group) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, group)) {
throw new PrivilegeException(sess, "sendInvitation");
}
}
if (user == null)
throw new RegistrarException("Missing user to send notification to.");
try {
Member m = membersManager.getMemberByUser(registrarSession, vo, user);
// is member, is invite to group ?
if (group != null) {
List<Group> g = groupsManager.getMemberGroups(registrarSession, m);
if (g.contains(group)) {
// user is member of group - can't invite him
throw new RegistrarException("User to invite is already member of your group: " + group.getShortName());
}
} else {
throw new RegistrarException("User to invite is already member of your VO:" + vo.getShortName());
}
} catch (Exception ex) {
log.error("[MAIL MANAGER] Exception {} when getting member by {} from " + vo.toString(), ex, user);
}
// get form
ApplicationForm form;
if (group != null) {
form = registrarManager.getFormForGroup(group);
} else {
form = registrarManager.getFormForVo(vo);
}
// get mail definition
ApplicationMail mail = getMailByParams(form.getId(), AppType.INITIAL, MailType.USER_INVITE);
if (mail == null) {
throw new RegistrarException("You don't have invitation e-mail template defined.");
} else if (mail.getSend() == false) {
throw new RegistrarException("Sending of invitations is disabled.");
}
String language = "en";
try {
Attribute a = attrManager.getAttribute(registrarSession, user, URN_USER_PREFERRED_LANGUAGE);
if (a != null && a.getValue() != null) {
language = BeansUtils.attributeValueToString(a);
}
} catch (Exception ex) {
log.error("[MAIL MANAGER] Exception thrown when getting preferred language for USER={}: {}", user, ex);
}
if (group == null) {
try {
Attribute a = attrManager.getAttribute(registrarSession, vo, URN_VO_LANGUAGE_EMAIL);
if (a != null && a.getValue() != null) {
language = BeansUtils.attributeValueToString(a);
}
} catch (Exception ex) {
log.error("[MAIL MANAGER] Exception thrown when getting preferred language of notification for VO={}: {}", vo, ex);
}
} else {
try {
Attribute a = attrManager.getAttribute(registrarSession, group, URN_GROUP_LANGUAGE_EMAIL);
if (a != null && a.getValue() != null) {
language = BeansUtils.attributeValueToString(a);
}
} catch (Exception ex) {
log.error("[MAIL MANAGER] Exception thrown when getting preferred language of notification for Group={}: {}", group, ex);
}
}
// get language
Locale lang = new Locale(language);
// get localized subject and text
MailText mt = mail.getMessage(lang);
String mailText = "";
String mailSubject = "";
if (mt.getText() != null && !mt.getText().isEmpty()) {
mailText = mt.getText();
}
if (mt.getSubject() != null && !mt.getSubject().isEmpty()) {
mailSubject = mt.getSubject();
}
SimpleMailMessage message = new SimpleMailMessage();
// fake app to get "from" address
Application app = new Application();
app.setVo(vo);
app.setGroup(group);
// get from
setFromMailAddress(message, app);
String email = "";
try {
Attribute a = attrManager.getAttribute(registrarSession, user, URN_USER_PREFERRED_MAIL);
if (a != null && a.getValue() != null) {
email = BeansUtils.attributeValueToString(a);
}
} catch (Exception ex) {
log.error("[MAIL MANAGER] Exception thrown when getting preferred language of notification for Group={}: {}", group, ex);
}
message.setTo(email);
mailText = substituteCommonStringsForInvite(vo, group, user, null, mailText);
mailSubject = substituteCommonStringsForInvite(vo, group, user, null, mailSubject);
message.setSubject(mailSubject);
message.setText(mailText);
try {
mailSender.send(message);
log.info("[MAIL MANAGER] Sending mail: USER_INVITE to: {} / " + app.getVo() + " / " + app.getGroup(), message.getTo());
} catch (MailException ex) {
log.error("[MAIL MANAGER] Sending mail: USER_INVITE failed because of exception: {}", ex);
throw new RegistrarException("Unable to send e-mail.", ex);
}
}
use of cz.metacentrum.perun.registrar.model.ApplicationMail in project perun by CESNET.
the class MailManagerImpl method sendMessage.
@Override
public void sendMessage(Application app, MailType mailType, String reason, List<Exception> exceptions) {
try {
// get form
ApplicationForm form;
if (app.getGroup() != null) {
form = registrarManager.getFormForGroup(app.getGroup());
} else {
form = registrarManager.getFormForVo(app.getVo());
}
// get mail definition
ApplicationMail mail = getMailByParams(form.getId(), app.getType(), mailType);
if (mail == null) {
log.error("[MAIL MANAGER] Mail not sent. Definition (or mail text) for: {} do not exists for VO: " + app.getVo() + " and Group: " + app.getGroup(), mailType.toString());
// mail not found
return;
} else if (mail.getSend() == false) {
log.info("[MAIL MANAGER] Mail not sent. Disabled by VO admin for: " + mail.getMailType() + " / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup());
// sending this mail is disabled by VO admin
return;
}
// get app data
List<ApplicationFormItemData> data = registrarManager.getApplicationDataById(registrarSession, app.getId());
// get language
Locale lang = new Locale(getLanguageFromAppData(app, data));
// get localized subject and text
MailText mt = mail.getMessage(lang);
String mailText = "";
String mailSubject = "";
if (mt.getText() != null && !mt.getText().isEmpty()) {
mailText = mt.getText();
}
if (mt.getSubject() != null && !mt.getSubject().isEmpty()) {
mailSubject = mt.getSubject();
}
// different behavior based on mail type
MailType type = mail.getMailType();
if (MailType.APP_CREATED_USER.equals(type)) {
SimpleMailMessage message = new SimpleMailMessage();
// set FROM
setFromMailAddress(message, app);
// set TO
setUsersMailAsTo(message, app, data);
// substitute common strings
mailText = substituteCommonStrings(app, data, mailText, reason, exceptions);
mailSubject = substituteCommonStrings(app, data, mailSubject, reason, exceptions);
// set subject and text
message.setSubject(mailSubject);
message.setText(mailText);
try {
// send mail
mailSender.send(message);
log.info("[MAIL MANAGER] Sending mail: APP_CREATED_USER to: {} / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup(), message.getTo());
} catch (MailException ex) {
log.error("[MAIL MANAGER] Sending mail: APP_CREATED_USER failed because of exception: {}", ex);
}
} else if (MailType.APP_CREATED_VO_ADMIN.equals(type)) {
SimpleMailMessage message = new SimpleMailMessage();
// set FROM
setFromMailAddress(message, app);
// set language independent on user's preferred language.
lang = new Locale("en");
try {
if (app.getGroup() == null) {
// VO
Attribute a = attrManager.getAttribute(registrarSession, app.getVo(), URN_VO_LANGUAGE_EMAIL);
if (a != null && a.getValue() != null) {
lang = new Locale(BeansUtils.attributeValueToString(a));
}
} else {
Attribute a = attrManager.getAttribute(registrarSession, app.getGroup(), URN_GROUP_LANGUAGE_EMAIL);
if (a != null && a.getValue() != null) {
lang = new Locale(BeansUtils.attributeValueToString(a));
}
}
} catch (Exception ex) {
log.error("Error when resolving notification default language: {}", ex);
}
MailText mt2 = mail.getMessage(lang);
String mailText2 = "";
String mailSubject2 = "";
if (mt2.getText() != null && !mt2.getText().isEmpty()) {
mailText2 = mt2.getText();
}
if (mt2.getSubject() != null && !mt2.getSubject().isEmpty()) {
mailSubject2 = mt2.getSubject();
}
// substitute common strings
mailText2 = substituteCommonStrings(app, data, mailText2, reason, exceptions);
mailSubject2 = substituteCommonStrings(app, data, mailSubject2, reason, exceptions);
// set subject and text
message.setSubject(mailSubject2);
message.setText(mailText2);
// send message to all VO or Group admins
List<String> toEmail = getToMailAddresses(app);
for (String email : toEmail) {
message.setTo(email);
try {
mailSender.send(message);
log.info("[MAIL MANAGER] Sending mail: APP_CREATED_VO_ADMIN to: {} / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup(), message.getTo());
} catch (MailException ex) {
log.error("[MAIL MANAGER] Sending mail: APP_CREATED_VO_ADMIN failed because of exception: {}", ex);
}
}
} else if (MailType.MAIL_VALIDATION.equals(type)) {
SimpleMailMessage message = new SimpleMailMessage();
// set FROM
setFromMailAddress(message, app);
// set TO
// empty = not sent
message.setTo("");
// substitute common strings
mailText = substituteCommonStrings(app, data, mailText, reason, exceptions);
mailSubject = substituteCommonStrings(app, data, mailSubject, reason, exceptions);
// set subject and text
message.setSubject(mailSubject);
// send to all emails, which needs to be validated
for (ApplicationFormItemData d : data) {
ApplicationFormItem item = d.getFormItem();
String value = d.getValue();
// if mail field and not validated
if (ApplicationFormItem.Type.VALIDATED_EMAIL.equals(item.getType()) && !"1".equals(d.getAssuranceLevel())) {
if (value != null && !value.isEmpty()) {
// set TO
message.setTo(value);
// get validation link params
String i = Integer.toString(d.getId(), Character.MAX_RADIX);
String m = getMessageAuthenticationCode(i);
// replace new validation link
if (mailText.contains("{validationLink-")) {
Pattern pattern = Pattern.compile("\\{validationLink-[^\\}]+\\}");
Matcher matcher = pattern.matcher(mailText);
while (matcher.find()) {
// whole "{validationLink-something}"
String toSubstitute = matcher.group(0);
// new login value to replace in text
String newValue = "";
Pattern namespacePattern = Pattern.compile("\\-(.*?)\\}");
Matcher m2 = namespacePattern.matcher(toSubstitute);
while (m2.find()) {
// only namespace "fed", "cert",...
String namespace = m2.group(1);
newValue = getPerunUrl(app.getVo(), app.getGroup());
if (newValue != null && !newValue.isEmpty()) {
if (!newValue.endsWith("/"))
newValue += "/";
newValue += namespace + "/registrar/";
newValue += "?vo=" + getEncodedString(app.getVo().getShortName());
newValue += ((app.getGroup() != null) ? "&group=" + getEncodedString(app.getGroup().getName()) : "");
try {
newValue += "&i=" + URLEncoder.encode(i, "UTF-8") + "&m=" + URLEncoder.encode(m, "UTF-8");
} catch (UnsupportedEncodingException ex) {
newValue += "&i=" + i + "&m=" + m;
}
}
}
// substitute {validationLink-authz} with actual value or empty string
mailText = mailText.replace(toSubstitute, newValue);
}
}
if (mailText.contains("{validationLink}")) {
// new backup if validation URL is missing
String url = getPerunUrl(app.getVo(), app.getGroup());
if (url != null && !url.isEmpty()) {
if (!url.endsWith("/"))
url += "/";
url += "registrar/";
}
if (url != null && !url.isEmpty())
url = url + "?vo=" + getEncodedString(app.getVo().getShortName());
if (app.getGroup() != null) {
// append group name for
if (url != null && !url.isEmpty())
url += "&group=" + getEncodedString(app.getGroup().getName());
}
// construct whole url
StringBuilder url2 = new StringBuilder(url);
if (url.contains("?")) {
if (!url.endsWith("?")) {
url2.append("&");
}
} else {
if (!url2.toString().isEmpty())
url2.append("?");
}
try {
if (!url2.toString().isEmpty())
url2.append("i=").append(URLEncoder.encode(i, "UTF-8")).append("&m=").append(URLEncoder.encode(m, "UTF-8"));
} catch (UnsupportedEncodingException ex) {
if (!url2.toString().isEmpty())
url2.append("i=").append(i).append("&m=").append(m);
}
// replace validation link
mailText = mailText.replace("{validationLink}", url2.toString());
}
// set replaced text
message.setText(mailText);
try {
mailSender.send(message);
log.info("[MAIL MANAGER] Sending mail: MAIL_VALIDATION to: {} / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup(), message.getTo());
} catch (MailException ex) {
log.error("[MAIL MANAGER] Sending mail: MAIL_VALIDATION failed because of exception: {}", ex);
}
} else {
log.error("[MAIL MANAGER] Sending mail: MAIL_VALIDATION failed. Not valid value of VALIDATED_MAIL field: {}", value);
}
}
}
} else if (type.equals(MailType.APP_APPROVED_USER)) {
SimpleMailMessage message = new SimpleMailMessage();
// set FROM
setFromMailAddress(message, app);
// set TO
setUsersMailAsTo(message, app, data);
// substitute common strings
mailText = substituteCommonStrings(app, data, mailText, reason, exceptions);
mailSubject = substituteCommonStrings(app, data, mailSubject, reason, exceptions);
// set subject and text
message.setSubject(mailSubject);
message.setText(mailText);
try {
// send mail
mailSender.send(message);
log.info("[MAIL MANAGER] Sending mail: APP_APPROVED_USER to: {} / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup(), message.getTo());
} catch (MailException ex) {
log.error("[MAIL MANAGER] Sending mail: APP_APPROVED_USER failed because of exception: {}", ex);
}
} else if (type.equals(MailType.APP_REJECTED_USER)) {
SimpleMailMessage message = new SimpleMailMessage();
// set FROM
setFromMailAddress(message, app);
// set TO
setUsersMailAsTo(message, app, data);
// substitute common strings
mailText = substituteCommonStrings(app, data, mailText, reason, exceptions);
mailSubject = substituteCommonStrings(app, data, mailSubject, reason, exceptions);
// set subject and text
message.setSubject(mailSubject);
message.setText(mailText);
try {
// send mail
mailSender.send(message);
log.info("[MAIL MANAGER] Sending mail: APP_REJECTED_USER to: {} / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup(), message.getTo());
} catch (MailException ex) {
log.error("[MAIL MANAGER] Sending mail: APP_REJECTED_USER failed because of exception: {}", ex);
}
} else if (MailType.APP_ERROR_VO_ADMIN.equals(type)) {
SimpleMailMessage message = new SimpleMailMessage();
// set FROM
setFromMailAddress(message, app);
// set language independent on user's preferred language.
lang = new Locale("en");
try {
if (app.getGroup() == null) {
// VO
Attribute a = attrManager.getAttribute(registrarSession, app.getVo(), URN_VO_LANGUAGE_EMAIL);
if (a != null && a.getValue() != null) {
lang = new Locale(BeansUtils.attributeValueToString(a));
}
} else {
Attribute a = attrManager.getAttribute(registrarSession, app.getGroup(), URN_GROUP_LANGUAGE_EMAIL);
if (a != null && a.getValue() != null) {
lang = new Locale(BeansUtils.attributeValueToString(a));
}
}
} catch (Exception ex) {
log.error("Error when resolving notification default language: {}", ex);
}
MailText mt2 = mail.getMessage(lang);
String mailText2 = "";
String mailSubject2 = "";
if (mt2.getText() != null && !mt2.getText().isEmpty()) {
mailText2 = mt2.getText();
}
if (mt2.getSubject() != null && !mt2.getSubject().isEmpty()) {
mailSubject2 = mt2.getSubject();
}
// substitute common strings
mailText2 = substituteCommonStrings(app, data, mailText2, reason, exceptions);
mailSubject2 = substituteCommonStrings(app, data, mailSubject2, reason, exceptions);
// set subject and text
message.setSubject(mailSubject2);
message.setText(mailText2);
// send message to all VO or Group admins
List<String> toEmail = getToMailAddresses(app);
for (String email : toEmail) {
message.setTo(email);
try {
mailSender.send(message);
log.info("[MAIL MANAGER] Sending mail: APP_ERROR_VO_ADMIN to: {} / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup(), message.getTo());
} catch (MailException ex) {
log.error("[MAIL MANAGER] Sending mail: APP_ERROR_VO_ADMIN failed because of exception: {}", ex);
}
}
} else {
log.error("[MAIL MANAGER] Sending mail type: {} is not supported.", type);
}
} catch (Exception ex) {
// all exceptions are catched and logged to: perun-registrar.log
log.error("[MAIL MANAGER] Exception thrown when sending email: {}", ex);
}
}
use of cz.metacentrum.perun.registrar.model.ApplicationMail in project perun by CESNET.
the class RegistrarBaseIntegrationTest method createAppMail.
/*
@Test
public void stringTest() {
String text = "anytext{login-egi-ui}anytext{neco}and{login-neco}";
Pattern MY_PATTERN = Pattern.compile("\\-(.*?)\\}");
Matcher m = MY_PATTERN.matcher(text);
while (m.find()) {
System.out.println(m.group(0));
}
Pattern MY_PATTERN2 = Pattern.compile("\\{login-[^\\}]+\\}");
Matcher m2 = MY_PATTERN2.matcher(text);
while (m2.find()) {
System.out.println(m2.group(0));
}
}
@Test
public void getAppsTest() throws Exception {
List<String> apps = new ArrayList<String>();
apps.add("NEW");
apps.add("VERIFIED");
// get compass
Vo vo = perun.getVosManager().getVoById(session, 321);
System.out.println(vo);
List<Application> result = registrarManager.getApplicationsForVo(session, vo, apps);
System.out.println("APPS ["+result.size()+"]:" + result);
}
@Test
@Transactional
public void testModule() throws PerunException {
registrarManager.approveApplication(session, 1543);
}
*/
@Test
@Transactional
public void createAppMail() throws PerunException {
System.out.println("createAppMail()");
// get form for VO (if not exists, it's created)
//Vo vo = perun.getVosManager().getVoByShortName(session, "meta");
ApplicationForm form = registrarManager.getFormForVo(vo);
ApplicationMail mail = new ApplicationMail(0, AppType.INITIAL, form.getId(), MailType.APP_CREATED_USER, true);
MailText t = mail.getMessage(new Locale("cs"));
t.setText("Český text mailu.");
t.setSubject("Český předmět mailu");
MailText t2 = mail.getMessage(new Locale("en"));
t2.setSubject("Anglický předmět mailu");
t2.setText("Anglický text mailu.");
int id = mailManager.addMail(session, form, mail);
mail = mailManager.getMailById(session, id);
List<ApplicationMail> mails = mailManager.getApplicationMails(session, form);
assertTrue("Mails are empty", (mails != null && !mails.isEmpty()));
assertTrue("Our mail was not returned", mails.contains(mail));
//System.out.println(mails);
}
use of cz.metacentrum.perun.registrar.model.ApplicationMail in project perun by CESNET.
the class MailManagerImpl method getMailByParams.
/**
* Retrieve mail definition from db by params.
* Mail contains all texts.
* If mail not exists, or no texts exists null is returned.
*
* @param formId relation to VO form
* @param appType application type
* @param mailType mail type
* @return mail if definition exists or null
*/
private ApplicationMail getMailByParams(Integer formId, AppType appType, MailType mailType) {
ApplicationMail mail = null;
// get mail def
try {
List<ApplicationMail> mails = jdbc.query(MAILS_SELECT_BY_PARAMS, new RowMapper<ApplicationMail>() {
@Override
public ApplicationMail mapRow(ResultSet rs, int arg1) throws SQLException {
return new ApplicationMail(rs.getInt("id"), AppType.valueOf(rs.getString("app_type")), rs.getInt("form_id"), MailType.valueOf(rs.getString("mail_type")), rs.getBoolean("send"));
}
}, formId, appType.toString(), mailType.toString());
// set
if (mails.size() != 1) {
log.error("[MAIL MANAGER] Wrong number of mail definitions returned by unique params, expected 1 but was: " + mails.size());
return mail;
}
mail = mails.get(0);
} catch (EmptyResultDataAccessException ex) {
return mail;
}
List<MailText> texts = new ArrayList<MailText>();
try {
texts = jdbc.query(MAIL_TEXTS_SELECT_BY_MAIL_ID, new RowMapper<MailText>() {
@Override
public MailText mapRow(ResultSet rs, int arg1) throws SQLException {
return new MailText(new Locale(rs.getString("locale")), rs.getString("subject"), rs.getString("text"));
}
}, mail.getId());
} catch (EmptyResultDataAccessException ex) {
// if no texts it's error
log.error("[MAIL MANAGER] Mail do not contains any text message: {}", ex);
return null;
}
for (MailText text : texts) {
// fill localized messages
mail.getMessage().put(text.getLocale(), text);
}
return mail;
}
use of cz.metacentrum.perun.registrar.model.ApplicationMail in project perun by CESNET.
the class MailManagerImpl method copyMailsFromVoToVo.
@Override
public void copyMailsFromVoToVo(PerunSession sess, Vo fromVo, Vo toVo) throws PerunException {
if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, fromVo) || !AuthzResolver.isAuthorized(sess, Role.VOADMIN, toVo)) {
throw new PrivilegeException(sess, "copyMailsFromVoToVo");
}
ApplicationForm formFrom = registrarManager.getFormForVo(fromVo);
ApplicationForm formTo = registrarManager.getFormForVo(toVo);
List<ApplicationMail> mails = getApplicationMails(sess, formFrom);
for (ApplicationMail mail : mails) {
// to start transaction
try {
registrarManager.getMailManager().addMail(sess, formTo, mail);
} catch (DuplicateKeyException ex) {
log.info("[MAIL MANAGER] Mail notification of type {} skipped while copying (was already present).", mail.getMailType() + "/" + mail.getAppType());
}
}
}
Aggregations