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

View File

@ -89,7 +89,7 @@ public class Transaction {
private void sendAll() {
for (String hive : taskStores.keySet()) {
QueueTaskStore store = taskStores.get(hive);
String queueName = "hsadminSystem-" + hive;
String queueName = "queue.hsadminSystem-" + hive;
Queue jmsSystemQueue = lookupJMSQueue(queueName);
QueueClient qClient = null;
try {
@ -179,10 +179,10 @@ public class Transaction {
public UnixUser getLoginUser() {
String loginName = getLoginName();
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) {
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");
userQuery.setParameter("username", loginName);
@ -198,7 +198,7 @@ public class Transaction {
if (ticketUser != null && ticketUser.length() == 2) {
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) {
return true; // hsh01 hostmaster
}
@ -209,7 +209,7 @@ public class Transaction {
String pacName = unixUser.getPac().getName();
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)))) {
Query memberQuery = getEntityManager().createQuery("SELECT c FROM Customers c WHERE c.name = :membername");
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 + "'");
Statement s = c.createStatement();
for (String sqlStatement : sql) {
System.out.println("SQL: " + sqlStatement);
LOG.fine("SQL: " + sqlStatement);
s.execute(sqlStatement);
}
return 0;
@ -67,7 +67,7 @@ public class JDBCProcessor extends AbstractProcessor {
exc = aSqlExc;
}
errorMsg = exc.getMessage();
System.out.println("ERR: " + errorMsg);
LOG.severe("ERR: " + errorMsg);
throw new ProcessorException(aSqlExc.getMessage() + ", reason: " + errorMsg);
} catch (Exception aExc) {
throw new ProcessorException(aExc.getMessage());

View File

@ -33,6 +33,8 @@ public class QueueServer implements MessageListener, ExceptionListener {
private String fromEMail;
private QueueConnection queueConnection;
private boolean isConnected;
/**
* Runs the QueueServer, using the arguments as ConnectionFactory
@ -60,11 +62,11 @@ public class QueueServer implements MessageListener, ExceptionListener {
qServ.close();
}
});
while (!qServ.connect()) {
Thread.sleep(30000);
}
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() {
logger = Logger.getLogger("de.hsadmin.core.qserv");
queueConnection = null;
isConnected = false;
}
private boolean isConnected() {
return isConnected;
}
private void setServiceEMail(String emailAddress) {
@ -98,7 +106,7 @@ public class QueueServer implements MessageListener, ExceptionListener {
}
}
private boolean connect() {
private void connect() {
try {
final ActiveMQConnectionFactory mqConnectionFactory = new ActiveMQConnectionFactory(jmsUrl);
mqConnectionFactory.setTrustAllPackages(true);
@ -109,14 +117,15 @@ public class QueueServer implements MessageListener, ExceptionListener {
queueConnection.start();
final QueueReceiver receiver = session.createReceiver(queue);
receiver.setMessageListener(this);
return true;
isConnected = true;
} catch (Exception 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());
TaskTransfer task = null;
try {
@ -138,6 +147,7 @@ public class QueueServer implements MessageListener, ExceptionListener {
logException(throwable);
task.setException(throwable.getMessage());
} finally {
try { jmsMessage.acknowledge(); } catch (JMSException e) { }
sendStatus(task);
notifyAll();
}
@ -154,11 +164,8 @@ public class QueueServer implements MessageListener, ExceptionListener {
@Override
public void onException(JMSException e) {
logger.log(Level.WARNING, e.getMessage(), e);
while (!connect()) {
try {
Thread.sleep(10000);
} catch (InterruptedException e1) { }
}
close();
isConnected = false;
}
protected void sendStatus(TaskTransfer queueMessage) {
@ -170,7 +177,7 @@ public class QueueServer implements MessageListener, ExceptionListener {
try {
queueConnection = mqConnectionFactory.createQueueConnection(jmsUsername, jmsPassword);
queueConnection.setExceptionListener(this);
session = queueConnection.createQueueSession(false, QueueSession.CLIENT_ACKNOWLEDGE);
session = queueConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
final Queue queue = session.createQueue(jmsStatusQueue);
queueConnection.start();
producer = session.createProducer(queue);
@ -182,7 +189,7 @@ public class QueueServer implements MessageListener, ExceptionListener {
} finally {
if (producer != null) try { producer.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.SocketException;
import java.net.UnknownHostException;
import java.util.logging.Logger;
import org.apache.commons.net.smtp.SMTPClient;
import org.apache.commons.net.smtp.SMTPReply;
@ -16,6 +17,8 @@ import de.hsadmin.core.util.HSAdminException;
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)
throws HSAdminException {
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)
throws HSAdminException {
try {
SMTPClient client = new SMTPClient();
final SMTPClient client = new SMTPClient();
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()) {
smtpHost = "localhost";
}
@ -34,11 +38,10 @@ public class SmtpHelper {
if (subject.toLowerCase().contains("error")) {
throw new HSAdminException("Konnte Mail nicht senden");
}
System.out.println("------------------------");
System.out.println("From: " + fromAddress);
System.out.println("To: " + toAddress);
System.out.println("Subject: " + subject);
System.out.println("\n" + text);
LOG.finer("From: " + fromAddress);
LOG.finer("To: " + toAddress);
LOG.finer("Subject: " + subject);
LOG.finer(text);
return;
}
client.connect(smtpHost, 25);

View File

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