Skip to content

Commit

Permalink
Mailing improvements.
Browse files Browse the repository at this point in the history
  • Loading branch information
autumoswitzerland committed Nov 7, 2024
1 parent 5b22c56 commit 67603ad
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 60 deletions.
Binary file not shown.
56 changes: 23 additions & 33 deletions src/main/java/ch/autumo/beetroot/BeetRootConfigurationManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,10 @@ public class BeetRootConfigurationManager {
private ServletContext servletContext = null;
protected boolean isWithinDesktop = false;

/** Full path of configuration file without configuration file name. */
private String fullConfigBasePath = null;
/** Configuration file name. */
private String cfgFileName = null;

private Properties generalProps = null;
private Properties htmlInputMap = null;
Expand All @@ -85,7 +88,6 @@ public class BeetRootConfigurationManager {
rootPath = "." + Helper.FILE_SEPARATOR;
if (!rootPath.endsWith(Helper.FILE_SEPARATOR))
rootPath += Helper.FILE_SEPARATOR;

// App-Version
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try {
Expand Down Expand Up @@ -227,34 +229,27 @@ public void initializeWithFullPath(String absolutePath, ServletContext servletCo
* @throws Exception exception
*/
public synchronized void initializeWithFullPath(String configFilePath) throws Exception {

if (isInitialized) {
LOG.warn("WARNING: Initialisation of configuration manager is called more than once!");
return;
}

if (servletContext == null) {

if (rootPath == null || rootPath.length() == 0) {
LogBuffer.log(LogLevel.ERROR, "Specified '-DROOTPATH' is non-existant! Check starting script of java process.");
throw new Exception("Specified '-DROOTPATH' is non-existant! Check starting script of java process.");
}

// check root path
if (!rootPath.endsWith(Helper.FILE_SEPARATOR))
rootPath += Helper.FILE_SEPARATOR;

final File dir = new File(rootPath);
if (!dir.exists() || !dir.isDirectory()) {
LogBuffer.log(LogLevel.ERROR, "Specified '-DROOTPATH' is invalid! Check starting script of java process.");
throw new Exception("Specified '-DROOTPATH' is non-existant! Check starting script of java process.");
}
}

generalProps = new Properties();
String file = configFilePath;
File f = new File(file);

if (f.exists()) {
// Get path only
fullConfigBasePath = f.getParent();
Expand All @@ -275,27 +270,23 @@ public synchronized void initializeWithFullPath(String configFilePath) throws Ex
generalProps.load(fis);
else
generalProps.load(BeetRootConfigurationManager.class.getResourceAsStream(file));

} catch (IOException e) {
LogBuffer.log(LogLevel.ERROR, "Couldn't read general server configuration '{}' !", file, e);
throw new Exception("Couldn't read general server configuration '" + file + "' !");
} finally {
if (fis != null)
fis.close();
}


// set file name
cfgFileName = new File(file).getName();
// load some main props separately
this.csrf = getYesOrNo(Constants.KEY_WS_USE_CSRF_TOKENS, Constants.YES);
if (this.csrf)
LogBuffer.log(LogLevel.INFO, "CSRF activated.");

this.extendedRoles = getYesOrNo(Constants.KEY_WS_USE_EXT_ROLES, Constants.YES);
this.translateTemplates = getYesOrNo(Constants.KEY_WEB_TRANSLATIONS, Constants.NO);
if (this.translateTemplates)
LogBuffer.log(LogLevel.INFO, "Web templates are translated.");


// HTML Input map
fis = null;
final String htmlMap = getString(Constants.KEY_WEB_INPUT_MAP);
Expand All @@ -321,8 +312,6 @@ public synchronized void initializeWithFullPath(String configFilePath) throws Ex
fis.close();
}
}


// Languages
InputStreamReader isr = null;
file = fullConfigBasePath + "languages.cfg";
Expand All @@ -346,8 +335,6 @@ public synchronized void initializeWithFullPath(String configFilePath) throws Ex
if (isr != null)
isr.close();
}


isInitialized = true;
}

Expand All @@ -360,37 +347,37 @@ public synchronized void initializeWithFullPath(String configFilePath) throws Ex
* @throws Exception exception
*/
public synchronized void initializeDesktop(String desktopCfgFile, String appName) throws Exception {

if (isInitialized) {
LOG.warn("WARNING: Initialisation of configuration manager is called more than once!");
return;
}

this.isWithinDesktop = true;

final String path = Helper.getDesktopPropertiesPath(appName);
final String filePath = path + desktopCfgFile;
final File f = new File(filePath);
Properties p = null;
if (f.exists()) {
p = new Properties();
FileInputStream fis = null;
try {
final FileInputStream fis = new FileInputStream(f);
fis = new FileInputStream(f);
p.load(fis);
fis.close();
} catch (IOException ex) {
LOG.error("Couldn't read general desktop configuration '{}' !", path, ex);
throw new Exception("Couldn't read general desktop configuration '" + path + "' !");
}
} finally {
if (fis != null)
fis.close();
}
this.generalProps = p;
} else {
LOG.error("Couldn't read general desktop configuration '{}', file doesn't exist !", path);
throw new Exception("Couldn't read general desktop configuration '" + path + "', file doesn't exist !");
}

// set full path
fullConfigBasePath = path;

fullConfigBasePath = f.getParent();
// set file name
cfgFileName = f.getName();
// At last
isInitialized = true;
}
Expand Down Expand Up @@ -453,6 +440,15 @@ public String getHtmlInputMapPattern(String columnName) {
public String getFullConfigBasePath() {
return fullConfigBasePath;
}

/**
* Returns the file name of the base configuration.
*
* @return file name
*/
public String getConfigFileNme() {
return cfgFileName;
}

/**
* Translated templates?
Expand Down Expand Up @@ -556,7 +552,6 @@ public String[] getKeys(String keyPrefix) {
* @return collected values
*/
public String[] getValues(String keyPrefix) {

final List<String> collectedVals = new ArrayList<>();
final Set<Object> keys = generalProps.keySet();
for (Iterator<Object> iterator = keys.iterator(); iterator.hasNext();) {
Expand Down Expand Up @@ -814,20 +809,15 @@ public static Document getXMLModuleConfigWithFullPath(String xmlConfigFilePath,
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
// parse XML file
final DocumentBuilder db = dbf.newDocumentBuilder();

final File cfg = new File(xmlConfigFilePath);
if (cfg.exists())
doc = db.parse(new File(xmlConfigFilePath));
else
doc = db.parse(BeetRootConfigurationManager.class.getResourceAsStream(xmlConfigFilePath));

doc.getDocumentElement().normalize();

final String module = doc.getDocumentElement().getNodeName();

if (!module.equalsIgnoreCase(moduleName))
throw new IllegalAccessException("Module '"+moduleName+"' is not a valid module name; here '"+module+"' would be right!");

} catch (Exception e) {
LOG.error("Couldn't load module XML configuration from '"+xmlConfigFilePath+"'!", e);
}
Expand Down
17 changes: 4 additions & 13 deletions src/main/java/ch/autumo/beetroot/BeetRootDatabaseManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -228,38 +228,31 @@ public void initialize() throws Exception {
}

private void initializePool() throws Exception {

// hikari data-source
// Hikari data-source
dataSource = new HikariDataSource();

// hikari proerties if any
// Hikari properties if any
final Properties dsProps = new Properties();

// read additional configuration parameters
final BeetRootConfigurationManager cm = BeetRootConfigurationManager.getInstance();


// 1. external JNDI and data-source?
dsExternalJndi = cm.getStringNoWarn(CFG_KEY_DS_EXT_JNDI);
if (dsExternalJndi != null && dsExternalJndi.length() > 0) {
LOG.info("External JNDI data-source '"+dsExternalJndi+"' has been configured");
// check if we still have a JDBC-URL prefix for determining the db type for beetRoot
LOG.info("External JNDI data-source '{}' has been configured.", dsExternalJndi);
// check if we still have a JDBC-URL prefix for determining the DB type for beetRoot
if (url == null || url.length() == 0)
throw new Exception("External JNDI data-source '"+dsExternalJndi+"' has been configured, but no JDBC-URL-prefix within 'db_url' "
+ "configuration parameterhas been defined! "
+ OS.LINE_SEPARATOR +
"It is used at least for determining what database is used; scheme 'jdbc:<database-id>'.");

dataSource.setDataSourceJNDI(dsExternalJndi);
// This means jdbcUrl, driverClassName, dataSourceProperties, user-name, password have been set externally
// --> All done!
return;
}


// 2. set pool name for internal data-source
dataSource.setPoolName(cm.getString(Constants.KEY_SERVER_NAME) + POOL_NAME_POSTFIX);


// 3 optional settings?
final String poolConfigKeys[] = cm.getKeys("db_pool_");
Expand All @@ -271,7 +264,6 @@ private void initializePool() throws Exception {
}
if (dsProps.size() > 0)
dataSource.setDataSourceProperties(dsProps);


// 4. own defined data-source?
final String dscn = cm.getStringNoWarn(CFG_KEY_DS_INT_DSCN);
Expand All @@ -289,7 +281,6 @@ private void initializePool() throws Exception {
return;
}


// 5. Default initialization with JDBC URL and driver class
dataSource.setJdbcUrl(url);
dataSource.setUsername(user);
Expand Down
55 changes: 41 additions & 14 deletions src/main/java/ch/autumo/beetroot/mailing/JavaxMailer.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import java.util.Map;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
Expand All @@ -48,29 +49,55 @@ public class JavaxMailer extends AbstractMailer {

private static final Logger LOG = LoggerFactory.getLogger(JavaxMailer.class.getName());

@SuppressWarnings("static-access")
@Override
public void mail(String[] to, String subject, Map<String, String> variables, String templateName, BeetRootHTTPSession session) throws Exception {
final Properties props = super.getProperties();
props.put("mail.from", from);

Session mailSession = null;
String msname = BeetRootDatabaseManager.getInstance().getProperty("mail.session.name");
if (msname == null || msname.length() == 0) {
msname = BeetRootConfigurationManager.getInstance().getString("mail_session_name");
if (msname == null || msname.length() == 0)
msname = "beetRootMailSession";
}
final InitialContext ic = new InitialContext();
final Session initSession = (Session) ic.lookup(msname);
@SuppressWarnings("static-access")
final Session mailSession = initSession.getInstance(props);
if (auth) {
mailSession.setPasswordAuthentication(
new URLName("smtp", host, -1, null, user, null),
new PasswordAuthentication(user, password)
);
if (msname == null || msname.length() == 0) {
// no external mail session
if (auth) {
final Authenticator auth = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
};
mailSession = Session.getInstance(props, auth);
}
else {
mailSession = Session.getDefaultInstance(props);
}
} else {
final InitialContext ic = new InitialContext();
final Session initSession = (Session) ic.lookup(msname);
mailSession = initSession.getInstance(props);
if (auth) {
mailSession.setPasswordAuthentication(
new URLName("smtp", host, -1, null, user, null),
new PasswordAuthentication(user, password)
);
}
LOG.info("External Mail-session '{}' (from {}) has been configured.", msname, BeetRootConfigurationManager.getInstance().getConfigFileNme());
}
} else {
final InitialContext ic = new InitialContext();
final Session initSession = (Session) ic.lookup(msname);
mailSession = initSession.getInstance(props);
if (auth) {
mailSession.setPasswordAuthentication(
new URLName("smtp", host, -1, null, user, null),
new PasswordAuthentication(user, password)
);
}
LOG.info("External Mail-session '{}' (from database) has been configured.", msname);
}

final MimeMessage message = new MimeMessage(mailSession);
String from = BeetRootDatabaseManager.getInstance().getProperty("mail.mailer");
from = from == null ? BeetRootConfigurationManager.getInstance().getString("mail_from") : from;
message.setFrom(new InternetAddress(from));
// process receivers
for (int i = 0; i < to.length; i++) {
Expand Down

0 comments on commit 67603ad

Please sign in to comment.