refactoring logging, config, error handling

This commit is contained in:
Peter Hormanns 2023-08-15 20:09:02 +02:00
parent 87efe77c78
commit 6e39b2e883
6 changed files with 81 additions and 44 deletions

View File

@ -1,5 +1,7 @@
package de.hsadmin.core.model; package de.hsadmin.core.model;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -13,6 +15,8 @@ public class PersistenceManager {
private Map<String, EntityManagerFactory> persistenceUnits; private Map<String, EntityManagerFactory> persistenceUnits;
private Logger logger;
public static EntityManager getEntityManager(String persistUnitName) { public static EntityManager getEntityManager(String persistUnitName) {
EntityManagerFactory emf = PersistenceManager.getInstance().getEMF(persistUnitName); EntityManagerFactory emf = PersistenceManager.getInstance().getEMF(persistUnitName);
return emf.createEntityManager(); return emf.createEntityManager();
@ -31,6 +35,7 @@ public class PersistenceManager {
if (emf == null) { if (emf == null) {
emf = Persistence.createEntityManagerFactory(persistUnitName); emf = Persistence.createEntityManagerFactory(persistUnitName);
persistenceUnits.put(persistUnitName, emf); persistenceUnits.put(persistUnitName, emf);
logger.log(Level.INFO, "Create Persistence Unit: " + persistUnitName);
} }
return emf; return emf;
} }
@ -43,11 +48,11 @@ public class PersistenceManager {
} }
private void closeFactories() { private void closeFactories() {
for (String puName : persistenceUnits.keySet()) { for (String persistUnitName : persistenceUnits.keySet()) {
System.out.println("Persistence Unit: " + puName); logger.log(Level.INFO, "Close Persistence Unit: " + persistUnitName);
EntityManagerFactory emf = persistenceUnits.get(puName); EntityManagerFactory emf = persistenceUnits.get(persistUnitName);
emf.close(); emf.close();
persistenceUnits.remove(puName); persistenceUnits.remove(persistUnitName);
} }
} }
} }

View File

@ -89,7 +89,7 @@ public class Transaction {
private void sendAll() { private void sendAll() {
for (String hive : taskStores.keySet()) { for (String hive : taskStores.keySet()) {
QueueTaskStore store = taskStores.get(hive); QueueTaskStore store = taskStores.get(hive);
String queueName = "hsadminSystem-" + hive; String queueName = "queue.hsadminSystem-" + hive;
Queue jmsSystemQueue = lookupJMSQueue(queueName); Queue jmsSystemQueue = lookupJMSQueue(queueName);
QueueClient qClient = null; QueueClient qClient = null;
try { try {
@ -179,10 +179,10 @@ public class Transaction {
public UnixUser getLoginUser() { public UnixUser getLoginUser() {
String loginName = getLoginName(); String loginName = getLoginName();
if (loginName != null && loginName.length() == 2) { if (loginName != null && loginName.length() == 2) {
loginName = Config.getInstance().getProperty("accountprefix.hostmaster", "hsh01") + "-" + loginName; loginName = config.getProperty("accountprefix.hostmaster", "hsh01") + "-" + loginName;
} }
if (loginName != null && loginName.length() == 3) { if (loginName != null && loginName.length() == 3) {
loginName = Config.getInstance().getProperty("accountprefix.customer", "hsh00") + "-" + loginName; loginName = config.getProperty("accountprefix.customer", "hsh00") + "-" + loginName;
} }
Query userQuery = getEntityManager().createQuery("SELECT u FROM UnixUsers u WHERE u.name = :username"); Query userQuery = getEntityManager().createQuery("SELECT u FROM UnixUsers u WHERE u.name = :username");
userQuery.setParameter("username", loginName); userQuery.setParameter("username", loginName);
@ -198,7 +198,7 @@ public class Transaction {
if (ticketUser != null && ticketUser.length() == 2) { if (ticketUser != null && ticketUser.length() == 2) {
return true; // 2-letter hostmaster return true; // 2-letter hostmaster
} }
String hostmasterAccountPrefix = Config.getInstance().getProperty("accountprefix.hostmaster", "hsh01") + "-"; String hostmasterAccountPrefix = config.getProperty("accountprefix.hostmaster", "hsh01") + "-";
if (ticketUser != null && ticketUser.startsWith(hostmasterAccountPrefix) && ticketUser.length() == 8) { if (ticketUser != null && ticketUser.startsWith(hostmasterAccountPrefix) && ticketUser.length() == 8) {
return true; // hsh01 hostmaster return true; // hsh01 hostmaster
} }
@ -209,7 +209,7 @@ public class Transaction {
String pacName = unixUser.getPac().getName(); String pacName = unixUser.getPac().getName();
return ticketUser.equals(pacName); // pac-admin return ticketUser.equals(pacName); // pac-admin
} }
String memberAccountPrefix = Config.getInstance().getProperty("accountprefix.customer", "hsh00") + "-"; String memberAccountPrefix = config.getProperty("accountprefix.customer", "hsh00") + "-";
if (ticketUser != null && (ticketUser.length() == 3 || (ticketUser.length() >= 9 && ticketUser.startsWith(memberAccountPrefix)))) { if (ticketUser != null && (ticketUser.length() == 3 || (ticketUser.length() >= 9 && ticketUser.startsWith(memberAccountPrefix)))) {
Query memberQuery = getEntityManager().createQuery("SELECT c FROM Customers c WHERE c.name = :membername"); Query memberQuery = getEntityManager().createQuery("SELECT c FROM Customers c WHERE c.name = :membername");
memberQuery.setParameter("membername", ticketUser.length() == 3 ? (memberAccountPrefix + ticketUser) : ticketUser); memberQuery.setParameter("membername", ticketUser.length() == 3 ? (memberAccountPrefix + ticketUser) : ticketUser);

View File

@ -57,7 +57,7 @@ public class JDBCProcessor extends AbstractProcessor {
throw new ProcessorException("cannot connect to '" + url + "'"); throw new ProcessorException("cannot connect to '" + url + "'");
Statement s = c.createStatement(); Statement s = c.createStatement();
for (String sqlStatement : sql) { for (String sqlStatement : sql) {
System.out.println("SQL: " + sqlStatement); LOG.fine("SQL: " + sqlStatement);
s.execute(sqlStatement); s.execute(sqlStatement);
} }
return 0; return 0;
@ -67,7 +67,7 @@ public class JDBCProcessor extends AbstractProcessor {
exc = aSqlExc; exc = aSqlExc;
} }
errorMsg = exc.getMessage(); errorMsg = exc.getMessage();
System.out.println("ERR: " + errorMsg); LOG.severe("ERR: " + errorMsg);
throw new ProcessorException(aSqlExc.getMessage() + ", reason: " + errorMsg); throw new ProcessorException(aSqlExc.getMessage() + ", reason: " + errorMsg);
} catch (Exception aExc) { } catch (Exception aExc) {
throw new ProcessorException(aExc.getMessage()); throw new ProcessorException(aExc.getMessage());

View File

@ -33,6 +33,8 @@ public class QueueServer implements MessageListener, ExceptionListener {
private String fromEMail; private String fromEMail;
private QueueConnection queueConnection; private QueueConnection queueConnection;
private boolean isConnected;
/** /**
* Runs the QueueServer, using the arguments as ConnectionFactory * Runs the QueueServer, using the arguments as ConnectionFactory
@ -60,11 +62,11 @@ public class QueueServer implements MessageListener, ExceptionListener {
qServ.close(); qServ.close();
} }
}); });
while (!qServ.connect()) {
Thread.sleep(30000);
}
while (true) { while (true) {
Thread.sleep(10000); if (!qServ.isConnected()) {
qServ.connect();
}
Thread.sleep(30000);
} }
} }
@ -80,6 +82,12 @@ public class QueueServer implements MessageListener, ExceptionListener {
public QueueServer() { public QueueServer() {
logger = Logger.getLogger("de.hsadmin.core.qserv"); logger = Logger.getLogger("de.hsadmin.core.qserv");
queueConnection = null;
isConnected = false;
}
private boolean isConnected() {
return isConnected;
} }
private void setServiceEMail(String emailAddress) { private void setServiceEMail(String emailAddress) {
@ -97,26 +105,27 @@ public class QueueServer implements MessageListener, ExceptionListener {
fromEMail = emailAddress; fromEMail = emailAddress;
} }
} }
private boolean connect() { private void connect() {
try { try {
final ActiveMQConnectionFactory mqConnectionFactory = new ActiveMQConnectionFactory(jmsUrl); final ActiveMQConnectionFactory mqConnectionFactory = new ActiveMQConnectionFactory(jmsUrl);
mqConnectionFactory.setTrustAllPackages(true); mqConnectionFactory.setTrustAllPackages(true);
queueConnection = mqConnectionFactory.createQueueConnection(jmsUsername, jmsPassword); queueConnection = mqConnectionFactory.createQueueConnection(jmsUsername, jmsPassword);
queueConnection.setExceptionListener(this); queueConnection.setExceptionListener(this);
final QueueSession session = queueConnection.createQueueSession(false, QueueSession.CLIENT_ACKNOWLEDGE); final QueueSession session = queueConnection.createQueueSession(false, QueueSession.CLIENT_ACKNOWLEDGE);
Queue queue = session.createQueue(jmsSystemQueue); Queue queue = session.createQueue(jmsSystemQueue);
queueConnection.start(); queueConnection.start();
final QueueReceiver receiver = session.createReceiver(queue); final QueueReceiver receiver = session.createReceiver(queue);
receiver.setMessageListener(this); receiver.setMessageListener(this);
return true; isConnected = true;
} catch (Exception e) { } catch (Exception e) {
logger.log(Level.WARNING, e.getMessage(), e); logger.log(Level.WARNING, e.getMessage(), e);
return false; isConnected = false;
} }
} }
public synchronized void onMessage(Message jmsMessage) { public synchronized void onMessage(final Message jmsMessage) {
assert jmsMessage != null;
logger.log(Level.INFO, jmsMessage.toString()); logger.log(Level.INFO, jmsMessage.toString());
TaskTransfer task = null; TaskTransfer task = null;
try { try {
@ -138,6 +147,7 @@ public class QueueServer implements MessageListener, ExceptionListener {
logException(throwable); logException(throwable);
task.setException(throwable.getMessage()); task.setException(throwable.getMessage());
} finally { } finally {
try { jmsMessage.acknowledge(); } catch (JMSException e) { }
sendStatus(task); sendStatus(task);
notifyAll(); notifyAll();
} }
@ -154,11 +164,8 @@ public class QueueServer implements MessageListener, ExceptionListener {
@Override @Override
public void onException(JMSException e) { public void onException(JMSException e) {
logger.log(Level.WARNING, e.getMessage(), e); logger.log(Level.WARNING, e.getMessage(), e);
while (!connect()) { close();
try { isConnected = false;
Thread.sleep(10000);
} catch (InterruptedException e1) { }
}
} }
protected void sendStatus(TaskTransfer queueMessage) { protected void sendStatus(TaskTransfer queueMessage) {
@ -170,7 +177,7 @@ public class QueueServer implements MessageListener, ExceptionListener {
try { try {
queueConnection = mqConnectionFactory.createQueueConnection(jmsUsername, jmsPassword); queueConnection = mqConnectionFactory.createQueueConnection(jmsUsername, jmsPassword);
queueConnection.setExceptionListener(this); queueConnection.setExceptionListener(this);
session = queueConnection.createQueueSession(false, QueueSession.CLIENT_ACKNOWLEDGE); session = queueConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
final Queue queue = session.createQueue(jmsStatusQueue); final Queue queue = session.createQueue(jmsStatusQueue);
queueConnection.start(); queueConnection.start();
producer = session.createProducer(queue); producer = session.createProducer(queue);
@ -182,7 +189,7 @@ public class QueueServer implements MessageListener, ExceptionListener {
} finally { } finally {
if (producer != null) try { producer.close(); } catch (Exception e) { } if (producer != null) try { producer.close(); } catch (Exception e) { }
if (session != null) try { session.close(); } catch (Exception e) { } if (session != null) try { session.close(); } catch (Exception e) { }
if (queueConnection != null) try { queueConnection.close(); } catch (Exception e) { } // if (queueConnection != null) try { queueConnection.close(); } catch (Exception e) { }
} }
} }

View File

@ -6,6 +6,7 @@ import java.io.Writer;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.SocketException; import java.net.SocketException;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.logging.Logger;
import org.apache.commons.net.smtp.SMTPClient; import org.apache.commons.net.smtp.SMTPClient;
import org.apache.commons.net.smtp.SMTPReply; import org.apache.commons.net.smtp.SMTPReply;
@ -16,6 +17,8 @@ import de.hsadmin.core.util.HSAdminException;
public class SmtpHelper { public class SmtpHelper {
private static final Logger LOG = Logger.getLogger(SmtpHelper.class.getName());
public static void send(String fromAddress, String toAddress, String subject, String text) public static void send(String fromAddress, String toAddress, String subject, String text)
throws HSAdminException { throws HSAdminException {
send(fromAddress, toAddress, null, subject, text); send(fromAddress, toAddress, null, subject, text);
@ -24,9 +27,10 @@ public class SmtpHelper {
public static void send(String fromAddress, String toAddress, String ccAddress, String subject, String text) public static void send(String fromAddress, String toAddress, String ccAddress, String subject, String text)
throws HSAdminException { throws HSAdminException {
try { try {
SMTPClient client = new SMTPClient(); final SMTPClient client = new SMTPClient();
String canonicalHostName = InetAddress.getLocalHost().getCanonicalHostName(); String canonicalHostName = InetAddress.getLocalHost().getCanonicalHostName();
String smtpHost = Config.getInstance().getProperty("smtp.host"); final Config config = Config.getInstance();
String smtpHost = config.getProperty("smtp.host");
if (smtpHost == null || smtpHost.trim().isEmpty()) { if (smtpHost == null || smtpHost.trim().isEmpty()) {
smtpHost = "localhost"; smtpHost = "localhost";
} }
@ -34,11 +38,10 @@ public class SmtpHelper {
if (subject.toLowerCase().contains("error")) { if (subject.toLowerCase().contains("error")) {
throw new HSAdminException("Konnte Mail nicht senden"); throw new HSAdminException("Konnte Mail nicht senden");
} }
System.out.println("------------------------"); LOG.finer("From: " + fromAddress);
System.out.println("From: " + fromAddress); LOG.finer("To: " + toAddress);
System.out.println("To: " + toAddress); LOG.finer("Subject: " + subject);
System.out.println("Subject: " + subject); LOG.finer(text);
System.out.println("\n" + text);
return; return;
} }
client.connect(smtpHost, 25); client.connect(smtpHost, 25);

View File

@ -11,31 +11,46 @@ public class Config {
private static Logger LOG = Logger.getLogger(Config.class.getName()); private static Logger LOG = Logger.getLogger(Config.class.getName());
private Properties props; private static final String userDir = System.getProperty("user.dir");
private static final String userHome = System.getProperty("user.home");
private final Properties props;
private Config() { private Config() {
props = new Properties(); props = new Properties();
File file = new File(System.getProperty("user.dir") + "/hsadmin.properties"); final String baseName = "hsadmin";
initPropertiesFromFile(baseName);
}
private Config(String baseName) {
props = new Properties();
initPropertiesFromFile(baseName);
}
private void initPropertiesFromFile(final String baseName) {
File file = new File(userDir + "/" + baseName + ".properties");
if (!file.canRead()) { if (!file.canRead()) {
file = new File(System.getProperty("user.dir") + "/conf/hsadmin.properties"); file = new File(userDir + "/conf/" + baseName + ".properties");
} }
if (!file.canRead()) { if (!file.canRead()) {
file = new File(System.getProperty("user.home") + "/.hsadmin.properties"); file = new File(userHome + "/." + baseName + ".properties");
} }
if (!file.canRead()) { if (!file.canRead()) {
file = new File("/etc/hsadmin/hsadmin.properties"); file = new File("/etc/hsadmin/" + baseName + ".properties");
} }
if (!file.canRead()) { if (!file.canRead()) {
file = new File("/etc/hsadmin.properties"); file = new File("/etc/" + baseName + ".properties");
} }
if (file.canRead()) { if (file.canRead()) {
try { try {
LOG.info("Constructor - Properties-File: " + file.getAbsolutePath()); LOG.info("Constructor - Properties-File: " + file.getAbsolutePath());
props.load(new FileReader(file)); props.load(new FileReader(file));
} catch (Exception e) { } catch (Exception e) {
// should not happen LOG.severe("reading properties failed: " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} }
} else {
LOG.severe("reading properties failed: No properties file found");
} }
} }
@ -46,6 +61,13 @@ public class Config {
return instance; return instance;
} }
public static Config getInstance(String baseName) {
if (instance == null) {
instance = new Config(baseName);
}
return instance;
}
public String getProperty(String propertyName) { public String getProperty(String propertyName) {
String property = props.getProperty(propertyName); String property = props.getProperty(propertyName);
return property; return property;