summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorChristian Klinger2016-08-08 12:43:23 +0200
committerChristian Klinger2016-08-08 12:43:23 +0200
commit97331661c3e0f3371056dcb592f072a8591b0230 (patch)
treeb588be057e3ce4e8e41f607ca71a42514c8f95a1
parent[server] Supply netrules and runscript via webrpc (diff)
parentchanges. (diff)
downloadtutor-module-97331661c3e0f3371056dcb592f072a8591b0230.tar.gz
tutor-module-97331661c3e0f3371056dcb592f072a8591b0230.tar.xz
tutor-module-97331661c3e0f3371056dcb592f072a8591b0230.zip
Merge branch 'feature/mail-templates' into v1.1
Conflicts: dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/database/mappers/DbConfiguration.java
-rw-r--r--dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/database/mappers/DbConfiguration.java83
-rw-r--r--dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/mail/MailGenerator.java132
-rw-r--r--dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/mail/MailTemplate.java74
-rw-r--r--dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/mail/MailTemplateConfiguration.java171
-rw-r--r--dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/mail/MailTemplatePlain.java37
-rw-r--r--dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/web/WebRpc.java31
-rw-r--r--dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/web/WebServer.java1
-rw-r--r--dozentenmodulserver/src/test/java/bwlehrpool/MailTemplateTest.java36
8 files changed, 502 insertions, 63 deletions
diff --git a/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/database/mappers/DbConfiguration.java b/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/database/mappers/DbConfiguration.java
index 553034ee..53e5acc7 100644
--- a/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/database/mappers/DbConfiguration.java
+++ b/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/database/mappers/DbConfiguration.java
@@ -14,12 +14,16 @@ import java.security.cert.CertificateException;
import java.sql.ResultSet;
import java.sql.SQLException;
+import javax.swing.DebugGraphics;
+
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.openslx.bwlp.sat.database.Database;
import org.openslx.bwlp.sat.database.MysqlConnection;
import org.openslx.bwlp.sat.database.MysqlStatement;
import org.openslx.bwlp.sat.mail.MailQueue.MailConfig;
+import org.openslx.bwlp.sat.mail.MailTemplate;
+import org.openslx.bwlp.sat.mail.MailTemplateConfiguration;
import org.openslx.bwlp.thrift.iface.SatelliteConfig;
import org.openslx.util.Json;
@@ -31,14 +35,16 @@ public class DbConfiguration {
private static final String KEY_MAILCONFIG = "mailconfig";
+ private static final String KEY_TEMPLATES = "templates";
+
private static final String KEY_LIMITS = "runtimelimits";
static {
Json.registerThriftClass(SatelliteConfig.class);
}
- public static KeyStore loadKeyStore(String password) throws KeyStoreException, SQLException,
- NoSuchAlgorithmException, CertificateException, IOException {
+ public static KeyStore loadKeyStore(String password)
+ throws KeyStoreException, SQLException, NoSuchAlgorithmException, CertificateException, IOException {
KeyStore keystore = KeyStore.getInstance("JKS");
InputStream stream = retrieveStream(KEY_CERTIFICATE);
if (stream == null)
@@ -57,9 +63,9 @@ public class DbConfiguration {
private static void store(String configKey, byte[] value) throws SQLException {
try (MysqlConnection connection = Database.getConnection()) {
- MysqlStatement stmt = connection.prepareStatement("INSERT INTO configuration"
- + " (parameter, value) VALUES (:parameter, :value)"
- + " ON DUPLICATE KEY UPDATE value = VALUES(value)");
+ MysqlStatement stmt = connection
+ .prepareStatement("INSERT INTO configuration" + " (parameter, value) VALUES (:parameter, :value)"
+ + " ON DUPLICATE KEY UPDATE value = VALUES(value)");
stmt.setString("parameter", configKey);
stmt.setBinary("value", value);
stmt.executeUpdate();
@@ -79,8 +85,8 @@ public class DbConfiguration {
private static byte[] retrieve(String configKey) throws SQLException {
try (MysqlConnection connection = Database.getConnection()) {
- MysqlStatement stmt = connection.prepareStatement("SELECT value FROM configuration"
- + " WHERE parameter = :parameter LIMIT 1");
+ MysqlStatement stmt = connection
+ .prepareStatement("SELECT value FROM configuration" + " WHERE parameter = :parameter LIMIT 1");
stmt.setString("parameter", configKey);
ResultSet rs = stmt.executeQuery();
if (!rs.next())
@@ -118,4 +124,67 @@ public class DbConfiguration {
return Json.deserializeThrift(new String(conf, StandardCharsets.UTF_8), SatelliteConfig.class);
}
+ /*
+ * access the database to read the mail templates. If the template is not
+ * found a hard-coded configuration is used and is merged with the database.
+ *
+ * @param name name of the desired mail template
+ *
+ * @return the mail template with the given name or NULL if no such template
+ * could be found.
+ */
+ public static MailTemplate getMailTemplate(String name) {
+
+ /* Try to get config from DB */
+ MailTemplateConfiguration templateConf = null;
+ try {
+ byte[] raw = retrieve(KEY_TEMPLATES);
+ if (raw != null) {
+ String json = new String(raw, StandardCharsets.UTF_8);
+ templateConf = Json.deserialize(json, MailTemplateConfiguration.class);
+ }
+ } catch (SQLException e) {
+ LOGGER.debug("sql exception while reading mail config");
+ }
+
+ /* Case 1: Nothing in DB */
+ if (templateConf == null) {
+ /* save default to db */
+ LOGGER.debug("No template config in DB -> save the default config to DB");
+ templateConf = MailTemplateConfiguration.defaultTemplateConfiguration;
+ try {
+ store(KEY_TEMPLATES, Json.serialize(templateConf).getBytes());
+ } catch (SQLException e) {
+ LOGGER.debug("erroring while storing");
+ e.printStackTrace();
+ }
+ return templateConf.getByName(name);
+
+ }
+
+ /* Case 2: DB has config but not the template */
+ if (templateConf != null && templateConf.getByName(name) == null) {
+ /* merge default config with templateConf */
+ LOGGER.debug("DB template config does not contain a template for " + name);
+ MailTemplateConfiguration newConf = templateConf
+ .merge(MailTemplateConfiguration.defaultTemplateConfiguration);
+ try {
+ store(KEY_TEMPLATES, Json.serialize(newConf).getBytes());
+ templateConf = newConf;
+ } catch (SQLException e) {
+ LOGGER.debug("sql exception while storing merged config");
+ e.printStackTrace();
+ }
+ return newConf.getByName(name);
+ }
+ /* Case 3: DB has config and has the template */
+ if (templateConf != null && templateConf.getByName(name) != null) {
+ LOGGER.debug("DB template found in DB");
+ return templateConf.getByName(name);
+ }
+ /* CASE 4: No DB and template not in default */
+ LOGGER.debug("Template with name \"" + name + "\" could not be found");
+ return null;
+
+ }
}
diff --git a/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/mail/MailGenerator.java b/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/mail/MailGenerator.java
index aae515b4..0c32339e 100644
--- a/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/mail/MailGenerator.java
+++ b/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/mail/MailGenerator.java
@@ -10,6 +10,7 @@ import java.util.Map;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
+import org.omg.CosNaming.NamingContextPackage.NotFound;
import org.openslx.bwlp.sat.database.mappers.DbConfiguration;
import org.openslx.bwlp.sat.database.mappers.DbImage;
import org.openslx.bwlp.sat.database.mappers.DbImagePermissions;
@@ -31,29 +32,36 @@ import org.openslx.bwlp.thrift.iface.UserInfo;
public class MailGenerator {
- // TODO Hard-Coded template mess. Strings and messages changed a lot while testing :(
- // This is best we could do for Sept. release
-
private static final Logger LOGGER = Logger.getLogger(MailGenerator.class);
/**
* Called when an image has been updated, and linked lectures will be moved
* to the new image version.
*
- * @param lectures List of affected lectures
- * @param newVersion version id of new image
+ * @param lectures
+ * List of affected lectures
+ * @param newVersion
+ * version id of new image
+ * @throws SQLException
*/
- public static void lectureAutoUpdate(List<LectureSummary> lectures, LocalImageVersion newVersion) {
+ public static void lectureAutoUpdate(List<LectureSummary> lectures, LocalImageVersion newVersion)
+ throws SQLException {
if (!hasMailConfig())
return;
for (LectureSummary lecture : lectures) {
List<UserInfo> relevantUsers = getUserToMail(lecture);
- String message = "Zur Veranstaltung '" + lecture.lectureName
- + "' gehörige VM wurde aktualisiert.";
+
+ MailTemplate template = DbConfiguration.getMailTemplate("updatedLecture");
+ Map<String, String> templateArgs = new HashMap<>();
+ templateArgs.put("lecture", lecture.lectureName);
+
+ String msg = template.format(templateArgs);
+
for (UserInfo user : relevantUsers) {
- if (newVersion.uploaderId.equals(user.userId)) // Don't notice about changes by user
+ /* Don't notice about changes by user */
+ if (newVersion.uploaderId.equals(user.userId))
continue;
- MailQueue.queue(new Mail(user, wordWrap(message)));
+ MailQueue.queue(new Mail(user, wordWrap(msg)));
}
}
}
@@ -62,21 +70,29 @@ public class MailGenerator {
* Called when a lecture is downgraded, or a lecture is updated and it
* doesn't have auto-updates enabled.
*
- * @param lectures list of affected lectures
- * @param newVersion the new version being switched to
+ * @param lectures
+ * list of affected lectures
+ * @param newVersion
+ * the new version being switched to
+ * @throws SQLException
*/
- public static void lectureForcedUpdate(List<LectureSummary> lectures, LocalImageVersion newVersion) {
+ public static void lectureForcedUpdate(List<LectureSummary> lectures, LocalImageVersion newVersion)
+ throws SQLException {
if (!hasMailConfig())
return;
for (LectureSummary lecture : lectures) {
List<UserInfo> relevantUsers = getUserToMail(lecture);
- String message = "Die verlinkte VM zur Veranstaltung '" + lecture.lectureName
- + "' wurde gelöscht oder ist beschädigt,"
- + " daher verweist sie jetzt auf die VM-Version vom "
- + Formatter.date(newVersion.createTime) + "."
- + " Bitte überprüfen Sie ggf., ob diese VM-Version für Ihren Kurs geeignet ist.";
+
+ MailTemplate template = DbConfiguration.getMailTemplate("lectureForcedUpdate");
+ Map<String, String> templateArgs = new HashMap<>();
+ templateArgs.put("lecture", lecture.lectureName);
+ templateArgs.put("date", Formatter.date(newVersion.createTime));
+
+ String msg = template.format(templateArgs);
+
+
for (UserInfo user : relevantUsers) {
- MailQueue.queue(new Mail(user, wordWrap(message)));
+ MailQueue.queue(new Mail(user, wordWrap(msg)));
}
}
}
@@ -86,18 +102,20 @@ public class MailGenerator {
return;
for (LectureSummary lecture : lectures) {
List<UserInfo> relevantUsers = getUserToMail(lecture);
- String message = "Die Veranstaltung '" + lecture.lectureName + "' musste deaktiviert werden,"
- + " da die verknüpfte VM gelöscht oder beschädigt wurde. Bitte überprüfen"
- + " Sie die Veranstaltung und ändern Sie ggf. die Verlinkung,"
- + " damit die Veranstaltung wieder verwendbar ist.";
+
+ MailTemplate template = new MailTemplate("lectureDeactivated");
+ Map<String, String> templateArgs = new HashMap<>();
+ templateArgs.put("lecture", lecture.lectureName);
+
+ String msg = template.format(templateArgs);
+
for (UserInfo user : relevantUsers) {
- MailQueue.queue(new Mail(user, wordWrap(message)));
+ MailQueue.queue(new Mail(user, wordWrap(msg)));
}
}
}
- public static void versionDeleted(String imageBaseId, LocalImageVersion oldLocal,
- LocalImageVersion newLocal) {
+ public static void versionDeleted(String imageBaseId, LocalImageVersion oldLocal, LocalImageVersion newLocal) {
if (!hasMailConfig())
return;
ImageDetailsRead image;
@@ -117,12 +135,18 @@ public class MailGenerator {
newVersion = version;
}
}
- if (oldVersion == newVersion)
+
+ MailTemplate template;
+ Map<String, String> templateArgs = new HashMap<>();
+
+ if (oldVersion == newVersion) {
return;
- String message = "Virtuelle Maschine '" + image.imageName + "':";
+ }
+
if (newVersion == null) {
- message += " Die letzte verbliebene Version der VM wurde gelöscht; VM zur Löschung vorgemerkt.";
+ template = DbConfiguration.getMailTemplate("deleteOnlyVersion");
} else {
+ template = DbConfiguration.getMailTemplate("deleteVersion");
String uploaderName;
try {
User uploader = DbUser.getCached(newVersion.uploaderId);
@@ -130,15 +154,17 @@ public class MailGenerator {
} catch (TNotFoundException | SQLException e) {
uploaderName = "(unbekannt)";
}
+ templateArgs.put("uploader", uploaderName);
+ templateArgs.put("new.created", Formatter.date(newVersion.createTime));
+
if (oldVersion != null) {
- message += "\n Alte Version vom " + Formatter.date(oldVersion.createTime) + " gelöscht";
+ templateArgs.put("old.created", Formatter.date(oldVersion.createTime));
}
- message += "\n Neueste Version ist jetzt vom " + Formatter.date(newVersion.createTime)
- + " (erstellt von " + uploaderName + ")";
- }
+ }
+
List<UserInfo> relevantUsers = getUserToMail(image);
for (UserInfo user : relevantUsers) {
- MailQueue.queue(new Mail(user, wordWrap(message)));
+ MailQueue.queue(new Mail(user, wordWrap(template.format(templateArgs))));
}
}
@@ -154,26 +180,29 @@ public class MailGenerator {
}
boolean isCurrentlyLatest = image.latestVersionId == null
|| image.latestVersionId.equals(version.imageVersionId);
- String message;
+
+ MailTemplate template;
+ Map<String, String> templateArgs = new HashMap<>();
+ templateArgs.put("image", image.imageName);
+ templateArgs.put("remaining_days", String.valueOf(days));
+ templateArgs.put("created", Formatter.date(version.createTime));
+
if (isCurrentlyLatest) {
- message = "Die aktuellste Version der VM '" + image.imageName + "' läuft in " + days
- + " Tag(en) ab. Bitte aktualisieren Sie die VM, da verknüpfte"
- + " Veranstaltungen sonst deaktiviert werden.";
+ template = DbConfiguration.getMailTemplate("deletionReminderOfCurrentlyLatest");
} else if (mailForced) {
- message = "Eine alte Version der VM '" + image.imageName + "' läuft in " + days
- + " Tag(en) ab (Version vom " + Formatter.date(version.createTime) + ")."
- + " Eine aktuellere Version ist vorhanden, diese Nachricht dient nur der Information.";
+ template = DbConfiguration.getMailTemplate("deletionRminderOfOldVersion");
} else {
return;
}
List<UserInfo> relevantUsers;
// Mail users responsible for this image
- message = wordWrap(message);
+ String message = wordWrap(template.format(templateArgs));
relevantUsers = getUserToMail(image);
for (UserInfo user : relevantUsers) {
MailQueue.queue(new Mail(user, message));
}
- // Mail users using this image for a lecture, but only if the image expires before the lecture ends
+ // Mail users using this image for a lecture, but only if the image
+ // expires before the lecture ends
// And the image to delete is currently the newest image
if (!isCurrentlyLatest)
return;
@@ -184,12 +213,11 @@ public class MailGenerator {
lectures = new ArrayList<>(0);
}
for (LectureSummary lecture : lectures) {
- if (lecture.endTime < version.expireTime)
+ if (lecture.endTime < version.expireTime) {
continue;
- message = "Hinweis zur Veranstaltung '" + lecture.lectureName + "': Die verwendete VM '"
- + image.imageName + "' läuft in " + days + " Tag(en) ab. Bitte aktualisieren"
- + " oder wechseln Sie die VM.";
- message = wordWrap(message);
+ }
+ template = DbConfiguration.getMailTemplate("deletionReminderUsers");
+ message = wordWrap(template.format(templateArgs));
relevantUsers = getUserToMail(lecture);
for (UserInfo user : relevantUsers) {
MailQueue.queue(new Mail(user, message));
@@ -201,7 +229,13 @@ public class MailGenerator {
if (!hasMailConfig())
return;
List<UserInfo> relevantUsers = getUserToMail(lecture);
- String message = "Die Veranstaltung '" + lecture.lectureName + "' läuft in " + days + " Tag(en) ab.";
+ MailTemplate template = DbConfiguration.getMailTemplate("endDateRemainder");
+ Map<String, String> templateArgs = new HashMap<>();
+ templateArgs.put("lecture", lecture.lectureName);
+ templateArgs.put("remaining_days", String.valueOf(days));
+
+ String message = template.format(templateArgs);
+
for (UserInfo user : relevantUsers) {
MailQueue.queue(new Mail(user, wordWrap(message)));
}
diff --git a/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/mail/MailTemplate.java b/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/mail/MailTemplate.java
new file mode 100644
index 00000000..24133781
--- /dev/null
+++ b/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/mail/MailTemplate.java
@@ -0,0 +1,74 @@
+package org.openslx.bwlp.sat.mail;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.Map;
+
+/**
+ * stores a mail template and offers methods to place variables
+ **/
+public class MailTemplate {
+
+ private ArrayList<String> snippets = new ArrayList<>();
+ private ArrayList<String> identifiers = new ArrayList<>();
+ private String raw;
+
+ public MailTemplate(String raw_template) {
+ this.raw = raw_template;
+ this.parseTemplate(raw_template);
+ }
+
+ public String format(Map<String, String> vars) {
+ Iterator<String> it_snippets = snippets.iterator();
+ Iterator<String> it_identifiers = identifiers.iterator();
+
+ StringBuilder sb = new StringBuilder();
+
+ boolean progress;
+ do {
+ progress = false;
+ if (it_snippets.hasNext()) {
+ sb.append(it_snippets.next());
+ progress = true;
+ }
+ if (it_identifiers.hasNext()) {
+ sb.append(vars.get(it_identifiers.next()));
+ progress = true;
+ }
+ } while (progress);
+
+ return sb.toString();
+ }
+
+ /*
+ * read the raw string from % to % and the fragments either into snippets or
+ * variables
+ */
+ private void parseTemplate(String raw) {
+ int i = 0;
+ while (true) {
+ int begin = raw.indexOf("%", i);
+ int end = raw.indexOf("%", begin + 1);
+
+ if (begin == -1) {
+ /* no variable anymore, so just add a snippet until the end */
+ String snippet = raw.substring(i);
+ this.snippets.add(snippet);
+ break;
+ }
+ String snippet = raw.substring(i, begin);
+ String identifier = raw.substring(begin + 1, end);
+
+ this.snippets.add(snippet);
+ this.identifiers.add(identifier);
+
+ i = end + 1;
+
+ }
+ }
+
+ public String getRaw() {
+ return this.raw;
+ }
+
+}
diff --git a/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/mail/MailTemplateConfiguration.java b/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/mail/MailTemplateConfiguration.java
new file mode 100644
index 00000000..4836ea39
--- /dev/null
+++ b/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/mail/MailTemplateConfiguration.java
@@ -0,0 +1,171 @@
+package org.openslx.bwlp.sat.mail;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+
+/**
+ * used for serialization to the database
+ *
+ * @author klingerc
+ *
+ */
+public class MailTemplateConfiguration {
+
+
+ private static final MailTemplatePlain[] defaultTemplates = {
+ new MailTemplatePlain(
+ "updatedLecture",
+ "Wird nach der Aktualisierung einer VM versendet.",
+ "Zur Veranstaltung %lecture% gehörige VM wurde aktualisiert.",
+ new String[]{},
+ new String[]{"lecture"}),
+
+ new MailTemplatePlain(
+ "lectureDeactivated",
+ "Wird versendet wenn eine Veranstaltung deaktiviert werden musste",
+ "Die Veranstaltung '%lecture%' musste deaktiviert werden,"
+ + " da die verknüpfte VM gelöscht oder beschädigt wurde. Bitte überprüfen"
+ + " Sie die Veranstaltung und ändern Sie ggf. die Verlinkung,"
+ + " damit die Veranstaltung wieder verwendbar ist.",
+ new String[] {},
+ new String[] {"lecture"}
+ ),
+
+ new MailTemplatePlain(
+ "deletionReminderOfCurrentlyLatest",
+ "Die Update-Erinnerung",
+ "Die aktuellste Version der VM '%image%' läuft in %remaining_days% Tag(en) ab."
+ + " Bitte aktualisieren Sie die VM, da verknüpfte Veranstaltungen sonst deaktiviert werden.",
+ new String[]{"remaining_days"},
+ new String[]{"image"}
+ ),
+
+ new MailTemplatePlain(
+ "deletionReminderOfOldVersion",
+ "Benachrichtigung dass eine alte Version einer VM abläuft.",
+ "Eine alte Version der VM '%image%' läuft in %remaining_days% Tag(en) ab (Version vom %created%)."
+ + " Eine aktuellere Version ist vorhanden, diese Nachricht dient nur der Information.",
+ new String[]{"remaining_days", "created"},
+ new String[]{"image"}
+ ),
+
+ new MailTemplatePlain(
+ "deletionReminderUsers",
+ "Die Update-Erinnerung",
+ "Hinweis zur Veranstaltung '%lecture%': Die verwendete VM '%image'"
+ + " läuft in %remaining_days% Tag(en) ab. Bitte aktualisieren oder wechseln Sie die VM.",
+ new String[]{"remaining_days"},
+ new String[]{"lecture"}
+ ),
+
+
+ new MailTemplatePlain(
+ "endDateRemainder",
+ "Erinnerung daran, dass das Enddatum einer Veranstaltung bald erreicht ist",
+ "Die Veranstaltung '%lecture%' läuft in %remaining_days% Tag(en) ab.",
+ new String[]{"remaining_days"},
+ new String[]{"lecture"}
+
+ ),
+
+ new MailTemplatePlain(
+ "deleteOnlyVersion",
+ "Bestätigung dass VM gelöscht wird",
+ "Die letzte verbliebene Version der VM '%image%' wurde gelöscht; VM zur Löschung vorgemerkt.",
+ new String[]{},
+ new String[]{"image"}
+ ),
+
+ new MailTemplatePlain(
+ "deleteVersion",
+ "Bestätigung dass eine alte Version der VM gelöscht wurde",
+ "Eine alte Version der VM '%image%' vom %old.created% wurde gelöscht\n"
+ + "Die neueste Version ist jetzt vom %new.created% (erstellt von %uploader%)",
+ new String[]{"old.created", "new.created"},
+ new String[]{"image"}
+ ),
+ new MailTemplatePlain(
+ "lectureForcedUpdate",
+ "Benachrichtigung nach erzwungenem Update",
+ "Die verlinkte VM zur Veranstaltung '%lecture%' wurde gelöscht oder ist beschädigt,"
+ + "daher verweist sie jetzt auf die VM-Version vom %date%. "
+ + "Bitte überprüfen Sie ggf., ob diese VM-Version für Ihren Kurs geeignet ist.",
+ new String[]{"date"},
+ new String[]{"lecture"}
+ ),
+ new MailTemplatePlain(
+ "testMail",
+ "Die Test-Email, die bei der Dozmod-Konfiguration verschickt wird",
+ "Test der Mailkonfiguration.\n\n%host%:%port% \nSSL: %ssl%"
+ + "\nLogin: %username%",
+ new String[]{"host", "port", "ssl", "username"},
+ new String[]{}
+ )
+ };
+
+
+ public static final MailTemplateConfiguration defaultTemplateConfiguration = new MailTemplateConfiguration(defaultTemplates);
+
+
+
+ private MailTemplatePlain[] templates;
+
+ /**
+ *
+ * @param name the name of the desired mail template
+ * @return the mail template or NULL if no such template exists
+ */
+ public MailTemplate getByName(String name) {
+ for(int i = 0; i < templates.length; i++) {
+ if (templates[i].getName().equals(name)) {
+ return templates[i].toMailTemplate();
+ }
+ }
+ return null;
+ }
+
+ public MailTemplateConfiguration(MailTemplatePlain[] templates) {
+ this.templates = templates;
+ }
+
+ /**
+ *
+ * @param conf the configuration that will be merged
+ * @return a new configuration containing templates from "this" and conf.
+ * If a template with the same name exists in both then "this" has priority
+ */
+ public MailTemplateConfiguration merge(MailTemplateConfiguration conf) {
+ HashMap<String, MailTemplatePlain> templates = new HashMap<>();
+ /* add all templates from conf */
+ for (MailTemplatePlain t : conf.templates) {
+ templates.put(t.getName(), t);
+ }
+
+ /* add all templates from here */
+ for (MailTemplatePlain t : this.templates) {
+ templates.put(t.getName(), t);
+ }
+
+ /* convert to array */
+ MailTemplatePlain[] templatesArray = new MailTemplatePlain[templates.size()];
+ templates.values().toArray(templatesArray);
+
+ return new MailTemplateConfiguration(templatesArray);
+ }
+
+ public int size() {
+ return this.templates.length;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("[");
+ for (MailTemplatePlain p : this.templates) {
+ sb.append(p.getName());
+ sb.append(" ");
+ }
+ sb.append("]");
+ return sb.toString();
+ }
+}
diff --git a/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/mail/MailTemplatePlain.java b/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/mail/MailTemplatePlain.java
new file mode 100644
index 00000000..470bd36d
--- /dev/null
+++ b/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/mail/MailTemplatePlain.java
@@ -0,0 +1,37 @@
+package org.openslx.bwlp.sat.mail;
+
+import com.google.gson.annotations.SerializedName;
+
+public class MailTemplatePlain {
+
+ private String name;
+ private String description;
+ private String template;
+
+ @SerializedName("optional_variables")
+ private String[] optionalVariables;
+
+
+ @SerializedName("mandatory_variables")
+ private String[] mandatoryVariables;
+
+
+
+
+ public MailTemplatePlain(String name, String description, String template, String[] optionalVariables,
+ String[] mandatoryVariables) {
+ this.name = name;
+ this.description = description;
+ this.template = template;
+ this.optionalVariables = optionalVariables;
+ this.mandatoryVariables = mandatoryVariables;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+ public MailTemplate toMailTemplate() {
+ return new MailTemplate(template);
+ }
+
+}
diff --git a/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/web/WebRpc.java b/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/web/WebRpc.java
index 19cb787c..ef21919e 100644
--- a/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/web/WebRpc.java
+++ b/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/web/WebRpc.java
@@ -8,17 +8,24 @@ import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
+import java.sql.SQLException;
+import java.util.HashMap;
import java.util.Map;
import javax.security.auth.login.LoginException;
import org.apache.commons.io.output.ByteArrayOutputStream;
+import org.omg.CosNaming.NamingContextPackage.NotFound;
+import org.openslx.bwlp.sat.database.mappers.DbConfiguration;
+import org.openslx.bwlp.sat.mail.MailTemplate;
import org.openslx.bwlp.sat.mail.SmtpMailer;
import org.openslx.bwlp.sat.mail.SmtpMailer.EncryptionMode;
import org.openslx.bwlp.sat.maintenance.DeleteOldImages;
import org.openslx.bwlp.sat.maintenance.ImageValidCheck;
import org.openslx.util.Util;
+import com.btr.proxy.util.Logger;
+
import fi.iki.elonen.NanoHTTPD;
import fi.iki.elonen.NanoHTTPD.Response;
@@ -53,8 +60,7 @@ public class WebRpc {
StringBuilder res = DeleteOldImages.hardDeleteImages();
if (res == null)
return WebServer.internalServerError();
- return new NanoHTTPD.Response(NanoHTTPD.Response.Status.OK, "text/plain; charset=utf-8",
- res.toString());
+ return new NanoHTTPD.Response(NanoHTTPD.Response.Status.OK, "text/plain; charset=utf-8", res.toString());
}
/**
@@ -98,14 +104,25 @@ public class WebRpc {
}
smtpc = null;
}
+
+
boolean ret = false;
- if (smtpc != null) {
- ret = smtpc.send(recipient, "bwLehrpool Mail Test", "Test der Mailkonfiguration.\n\nHost: "
- + host + ":" + port + "\nSSL: " + ssl.toString() + "\nLogin: " + username);
+ if (smtpc != null) {
+
+ MailTemplate template = DbConfiguration.getMailTemplate("testMail");
+ Map<String, String> templateArgs = new HashMap<>();
+ templateArgs.put("host", host);
+ templateArgs.put("port", String.valueOf(port));
+ templateArgs.put("ssl", ssl.toString());
+ templateArgs.put("username", username);
+
+ String msg = template.format(templateArgs);
+
+ ret = smtpc.send(recipient, "bwLehrpool Mail Test", msg);
}
try {
- baos.write(("\n\n-----------------------------------------\nTestergebnis: "
- + (ret ? "" : "nicht ") + "erfolgreich").getBytes(StandardCharsets.UTF_8));
+ baos.write(("\n\n-----------------------------------------\nTestergebnis: " + (ret ? "" : "nicht ")
+ + "erfolgreich").getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
}
return new NanoHTTPD.Response(NanoHTTPD.Response.Status.OK, "text/plain; charset=utf-8",
diff --git a/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/web/WebServer.java b/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/web/WebServer.java
index c0edc706..e369f162 100644
--- a/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/web/WebServer.java
+++ b/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/web/WebServer.java
@@ -69,6 +69,7 @@ public class WebServer extends NanoHTTPD {
try {
return handle(session, uri);
} catch (Throwable t) {
+ LOGGER.debug("Could not handle request", t);
return internalServerError();
}
}
diff --git a/dozentenmodulserver/src/test/java/bwlehrpool/MailTemplateTest.java b/dozentenmodulserver/src/test/java/bwlehrpool/MailTemplateTest.java
new file mode 100644
index 00000000..7171d3c2
--- /dev/null
+++ b/dozentenmodulserver/src/test/java/bwlehrpool/MailTemplateTest.java
@@ -0,0 +1,36 @@
+package bwlehrpool;
+
+import java.util.HashMap;
+
+import org.openslx.bwlp.sat.mail.MailTemplate;
+
+import junit.framework.TestCase;
+
+public class MailTemplateTest extends TestCase {
+
+ public void testMailTemplate() {
+ String test = "Hallo Eins %zwei% drei";
+ MailTemplate template = new MailTemplate(test);
+
+ /* variables */
+ HashMap<String, String> map = new HashMap<>();
+ map.put("eins", "1");
+ map.put("zwei", "2");
+ map.put("drei", "3");
+
+ assertEquals("Hallo Eins 2 drei", template.format(map));
+ assertEquals("1", new MailTemplate("%eins%").format(map));
+ assertEquals("x1", new MailTemplate("x%eins%").format(map));
+ assertEquals("1x", new MailTemplate("%eins%x").format(map));
+ assertEquals("123", new MailTemplate("%eins%%zwei%%drei%").format(map));
+ }
+
+ public void testMailTemplateWrongPlaceholder() {
+ MailTemplate template = new MailTemplate("hallo %zwei%");
+ HashMap<String, String> map = new HashMap<>();
+ map.put("eins", "eense");
+ assertEquals("hallo null", template.format(map));
+
+ }
+
+}